@devries-cameron20 / composio Mirror · read-only / commits / 93a5224c1
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 09:45 UTC

fix(cli): remove `experimental_subAgent` and its ACP transport (#4732)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/4725 - removes `experimental_subAgent()` (alias `invokeAgent`) from `composio run`: its ACP transport answered every permission request from the spawned agent with `allow_always`. Both transports, the output MCP server, and the read-roots handling are deleted; calling the helper now rejects with a removal message. - removes `--acp-only`, `COMPOSIO_RUN_ACP_ONLY`, the redundant `--logs-off` flag, and the `experimental_subagent` config field. A stored key is ignored and preserved; an invalid target used to reset the whole config to defaults. - keeps ten legacy archive paths (four root `run-subagent-*.mjs`, six `acp-adapters/*`) as zero-byte placeholders. Stable CLIs from 0.2.12 to 0.4.2 verify a downloaded upgrade archive by path existence with their own path list, so `composio upgrade` keeps working. The archive gate now checks that the placeholders are empty and the live `services/` bundles are not. - rebuilds ZIPs and their staging directories from scratch so repeat packaging cannot retain removed bundles. - flattens release artifacts to a list of names, removes unused platform/architecture metadata, and drops archive assertions already covered by exact entry-list checks. Legacy-client compatibility checks remain. - drops the adapter build scripts, `_tarball-integrity`, five dependencies (`@agentclientprotocol/sdk`, `@modelcontextprotocol/sdk`, `@composio/json-schema-to-zod`, `@zed-industries/claude-code-acp`, `@zed-industries/codex-acp`), and the `minimatch` override that existed for the adapter. About 4.7k lines removed. - rejects an unknown flag, including names with underscores, before inline `run` code by name (`Unrecognized flag: --x in command composio run`) instead of executing it as source. Inline source that is exactly one flag-shaped token needs an explicit `--`; file mode still forwards unknown flags to the script. - updates `run --help`, the CLI docs page, the bundled skill, the README, and the CLI changelog. The uninstall lists in `INSTALL.md`, `cli.mdx`, and the install health check are unchanged because the placeholder files still ship. - breaking: - a script that calls `experimental_subAgent()` fails at that call; tool calls it made earlier have already run - `--acp-only` and `--logs-off` are no longer recognized flags; helper logs are saved to disk, and `--debug` also prints them to stderr ## Context This is finding 5 of the CLI audit from 2026-09-24. The helper was experimental, its originating PRs (#3011, #3046–#3053) state no motivation, and no analytics event records its use. The audit proposed keeping it on the older `claude -p` / `codex exec` transport; this PR removes it instead. ## How Has This Been Tested? Latest validation after the additional cleanup (`3e3583bc5`): - CLI suite: **1,396 passed, 1 skipped** across 129 test files; CLI skill and lint-boundary validators passed. - `pnpm typecheck`: all 14 workspace tasks passed. CLI build, compiled native binary build, release-workflow tests, and agent-skill/routing validators passed. Lint on the cleanup files passed with no warnings or errors. The broader CLI lint previously passed with warnings and no errors. - Earlier validation (`44a8d0d`), focused Docker upgrade E2E: **2 passed**, 34 assertions, fresh Linux image. Both installed and copied binaries execute a script using injected `z` after upgrading. - Ran the actual packager twice with stale ZIP and staging entries seeded beforehand. Removed bundles and dependencies disappear, the binary updates, obsolete release metadata disappears, and all ten legacy placeholders stay empty. The original packager fails this fixture. - Earlier validation (`44a8d0d`), built a real macOS ZIP, passed the archive companion gate, extracted it, and ran a script using injected `z`. The extracted binary rejects `--foo_bar` before executing source and reports the removed helper with its reason and suggested alternative. - Downloaded and checksum-verified the released macOS 0.2.14, 0.3.3, and 0.4.2 binaries, then upgraded each through local release metadata and a checksum-verified archive built from the updated PR. All three reported the new version and ran a script with injected `z`. Version 0.2.14 repairs missing run and generation companions on first `run`; 0.3.3 repairs the generation companion; 0.4.2 needs no repair. The first two therefore need network access to the matching release on first use. - The rebuilt compiled CLI omits `--logs-off` from help and rejects `--logs-off`, `--logs-off=false`, and `--no-logs-off` before running inline source. - Not run: the full Docker CLI E2E suite or released clients upgrading to a **published** beta containing this change. Before stable promotion, install 0.4.2, 0.3.3, and 0.2.14, upgrade each to the first beta carrying this change (0.2.14 needs `GITHUB_TAG='@composio/cli@<beta>' composio upgrade`), confirm the version, and run `composio run 'console.log(1)'`. ## Follow-ups - The archive gate checks bundle size, not that the bundle loads. A smoke run of the packaged binary in the release workflow would close that. - `docs/kb/semantic-index.json` is stale until the existing rebuild workflow runs. ## Type of change - [x] Bug fix - [x] Refactor/Chore - [x] Documentation - [x] Breaking change ## Checklist - [x] Ran relevant local tests and validators; limitations are documented above - [x] Updated documentation and added regressions for changed public behavior - [x] Updated the CLI changelog; no Changeset because the CLI is excluded from Changesets - [ ] Author has reviewed the full diff

Alberto Schiabel committed Oct 8, 2026 at 21:46 UTC 93a5224c129628878a9aa51ad3e77be9fbc6162e
51 files changed +690 -4793
.github/scripts/cli-release/verify-archive-companions.sh
+61 -38
@@ -1,63 +1,86 @@
1 #!/usr/bin/env bash
2 #
3 -# Loud failure gate: assert one release archive carries the codex-acp layout the CLI
4 -# actually ships — every platform's path present, but real bytes only for the platform
5 -# this archive runs on.
3 +# Loud failure gate: assert one release archive carries the companion layout the CLI
4 +# actually ships — the legacy paths present but empty, the live bundles present with
5 +# real bytes.
6 #
7 -# Both halves matter, and each guards a shipped regression:
7 +# Each check guards a different failure:
8 #
9 -# - A missing path breaks `composio upgrade` for every CLI released before 2026-08-18.
10 -# Those clients verify a downloaded package against all four codex-acp paths and
11 -# refuse one that lacks any of them.
12 -# - A populated foreign binary is ~200MB nobody unpacking this archive can execute,
13 -# which is what made the upgrade download several minutes of mostly dead weight.
9 +# - A missing legacy path breaks `composio upgrade` for every stable CLI from 0.2.12
10 +# to 0.4.2. Those clients verify a downloaded package against their own path list,
11 +# by existence only, and refuse one that lacks any of them.
12 +# - A legacy path with content means sub-agent or adapter code is shipping again. The
13 +# helper it served was removed; the path is only a placeholder.
14 +# - An empty live bundle passes every existence check and still breaks `composio run`
15 +# and `composio generate`. The root files of the same name are one-line re-export
16 +# wrappers, so the bundles under services/ are what carries the code.
17 #
18 # The unit tests cover the packaging rules on synthetic inputs; only this gate looks at a
16 -# real archive, so a change to the packaging pipeline cannot quietly reintroduce either
17 -# state.
19 +# real archive, so a change to the packaging pipeline cannot quietly reintroduce any of
20 +# these states.
21 #
19 -# Inputs (env): ARCHIVE (path to the .zip), ARTIFACT (its top-level directory),
20 -# HOST_CODEX_TARGET (the one target that must carry real bytes)
22 +# Inputs (env): ARCHIVE (path to the .zip), ARTIFACT (its top-level directory)
23 set -euo pipefail
24
25 : "${ARCHIVE:?ARCHIVE is required}"
26 : "${ARTIFACT:?ARTIFACT is required}"
25 -: "${HOST_CODEX_TARGET:?HOST_CODEX_TARGET is required}"
27
27 -# Keep in lock-step with RUN_CODEX_ACP_BINARY_TARGETS in
28 -# ts/packages/cli/src/services/run-companion-modules.ts. Adding a codex target there must
29 -# extend this list, or the gate stops covering it.
30 -codex_targets=(darwin-arm64 darwin-x64 linux-arm64 linux-x64)
28 +# Keep in lock-step with RUN_COMPANION_LEGACY_PLACEHOLDER_RELATIVE_PATHS in
29 +# ts/packages/cli/src/services/run-companion-modules.ts. The list is frozen: it is what
30 +# already-released clients ask for.
31 +legacy_placeholders=(
32 + run-subagent-shared.mjs
33 + run-subagent-acp.mjs
34 + run-subagent-legacy.mjs
35 + run-subagent-output-mcp.mjs
36 + acp-adapters/claude-code-acp.mjs
37 + acp-adapters/cli.js
38 + acp-adapters/codex/darwin-arm64/codex-acp
39 + acp-adapters/codex/darwin-x64/codex-acp
40 + acp-adapters/codex/linux-arm64/codex-acp
41 + acp-adapters/codex/linux-x64/codex-acp
42 +)
43 +
44 +live_bundles=(
45 + services/run-helpers-runtime.mjs
46 + services/generation-runtime.mjs
47 +)
48
49 fail() {
50 echo "::error::$1"
51 exit 1
52 }
53
37 -printf '%s\n' "${codex_targets[@]}" | grep -Fxq "$HOST_CODEX_TARGET" ||
38 - fail "HOST_CODEX_TARGET '$HOST_CODEX_TARGET' is not a known codex target (${codex_targets[*]})"
39 -
54 test -f "$ARCHIVE" || fail "archive not found: $ARCHIVE"
55 entries="$(unzip -Z1 "$ARCHIVE")"
56
43 -for target in "${codex_targets[@]}"; do
44 - entry="${ARTIFACT}/acp-adapters/codex/${target}/codex-acp"
57 +# Byte count of an entry as stored, read without extracting to disk.
58 +entry_size() {
59 + unzip -p "$ARCHIVE" "$1" | wc -c | tr -d '[:space:]'
60 +}
61 +
62 +for relative_path in "${legacy_placeholders[@]}"; do
63 + entry="${ARTIFACT}/${relative_path}"
64 +
65 + grep -Fxq "$entry" <<<"$entries" ||
66 + fail "missing legacy entry '$entry'; CLIs from 0.2.12 to 0.4.2 refuse an archive without it"
67 +
68 + size="$(entry_size "$entry")"
69 + [ "$size" -eq 0 ] ||
70 + fail "'$entry' is a legacy placeholder but carries $size bytes; it must be empty"
71 + echo "ok: $relative_path is an empty placeholder"
72 +done
73 +
74 +for relative_path in "${live_bundles[@]}"; do
75 + entry="${ARTIFACT}/${relative_path}"
76
77 grep -Fxq "$entry" <<<"$entries" ||
47 - fail "missing codex-acp entry '$entry'; pre-2026-08-18 clients refuse an archive without it"
48 -
49 - # Byte count of the entry as stored, read without extracting to disk.
50 - size="$(unzip -p "$ARCHIVE" "$entry" | wc -c | tr -d '[:space:]')"
51 -
52 - if [ "$target" = "$HOST_CODEX_TARGET" ]; then
53 - [ "$size" -gt 0 ] ||
54 - fail "'$entry' is this archive's own platform but is empty; the CLI cannot run an ACP sub-agent"
55 - echo "ok: $target carries $size bytes (this archive's platform)"
56 - else
57 - [ "$size" -eq 0 ] ||
58 - fail "'$entry' is a foreign platform but carries $size bytes; it can never execute here"
59 - echo "ok: $target is an empty placeholder"
60 - fi
78 + fail "missing companion bundle '$entry'; the CLI cannot run without it"
79 +
80 + size="$(entry_size "$entry")"
81 + [ "$size" -gt 0 ] ||
82 + fail "'$entry' is empty; the CLI cannot run without it"
83 + echo "ok: $relative_path carries $size bytes"
84 done
85
63 -echo "Archive companion layout verified for $ARTIFACT (host target: $HOST_CODEX_TARGET)."
86 +echo "Archive companion layout verified for $ARTIFACT."
.github/workflows/build-cli-binaries.yml
+1 -6
@@ -98,19 +98,15 @@ jobs:
98 - target: bun-linux-x64
99 artifact: composio-linux-x64
100 runner: ubuntu-latest
101 - codex_target: linux-x64
101 - target: bun-linux-arm64
102 artifact: composio-linux-aarch64
103 runner: ubuntu-latest
105 - codex_target: linux-arm64
104 - target: bun-darwin-x64
105 artifact: composio-darwin-x64
106 runner: macos-15-intel
109 - codex_target: darwin-x64
107 - target: bun-darwin-arm64
108 artifact: composio-darwin-aarch64
109 runner: macos-15
113 - codex_target: darwin-arm64
110
111 steps:
112 - name: Checkout
@@ -166,12 +162,11 @@ jobs:
162 working-directory: ts/packages/cli
163 run: unzip -p dist/binaries/${{ matrix.artifact }}.zip ${{ matrix.artifact }}/release-tag.txt | grep -Fx '${{ needs.prepare.outputs.release_tag }}'
164
169 - - name: Verify companion adapters in archive
165 + - name: Verify companion layout in archive
166 working-directory: ts/packages/cli
167 env:
168 ARCHIVE: dist/binaries/${{ matrix.artifact }}.zip
169 ARTIFACT: ${{ matrix.artifact }}
174 - HOST_CODEX_TARGET: ${{ matrix.codex_target }}
170 run: bash "${{ github.workspace }}/.github/scripts/cli-release/verify-archive-companions.sh"
171
172 - name: Upload artifact
.oxlintrc.json
-1
@@ -23,7 +23,6 @@
23 "ts/packages/core/pack/generated/**",
24 "ts/packages/slim/generated/**",
25 "ts/packages/**/.generated/**",
26 - "ts/packages/**/acp-adapters/**",
26 "node_modules/**",
27 "ts/examples/**/dist-worker/**",
28 "ts/examples/cloudflare-wrangler/worker-configuration.d.ts",
docs/content/docs/cli.mdx
+5 -26
@@ -243,6 +243,9 @@ composio execute GMAIL_FETCH_EMAILS \
243 Use `composio execute <slug> --get-schema` to print the tool's input schema as JSON.
244 `composio execute <slug> --help` now shows command options and examples.
245
246 +Use `composio execute <slug> --get-schema` to print the tool's input schema as JSON.
247 +`composio execute <slug> --help` now shows command options and examples.
248 +
249 The commands you'll reach for most:
250
251 | Command | Use it for |
@@ -258,9 +261,9 @@ Use `composio proxy` when the agent already knows the provider's API endpoint an
261 composio proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail
262 ```
263
261 -### Run scripts and sub-agents
264 +### Run scripts
265
263 -Reach for `composio run` when the agent needs a multi-step workflow: loops, parallel fan-out, data transformation, or LLM-assisted summarization. It runs inline TS/JS or a file, with `execute()`, `search()`, `proxy()`, `experimental_subAgent()`, `result.prompt()`, and `z` injected.
266 +Reach for `composio run` when the agent needs a multi-step workflow: loops, parallel fan-out, or data transformation. It runs inline TS/JS or a file, with `execute()`, `search()`, `proxy()`, `result.prompt()`, and `z` injected.
267
268 Run a single scripted workflow:
269
@@ -287,30 +290,6 @@ console.log({ emails: emails.data, issues: issues.data, events: events.data });
290 '
291 ```
292
290 -Ask a sub-agent to summarize tool output and return structured data:
291 -
292 -```bash
293 -composio run --logs-off '
294 -const [emails, issues] = await Promise.all([
295 - execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),
296 - execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),
297 -]);
298 -
299 -const brief = await experimental_subAgent(
300 - `Create a morning brief from these emails and issues.\n\n${emails.prompt()}\n\n${issues.prompt()}`,
301 - {
302 - schema: z.object({
303 - brief: z.string(),
304 - urgentEmails: z.array(z.string()),
305 - urgentIssues: z.array(z.string()),
306 - }),
307 - }
308 -);
309 -
310 -console.log(brief.structuredOutput);
311 -'
312 -```
313 -
293 Run a checked-in script:
294
295 ```bash
pnpm-lock.yaml
+1 -309
@@ -109,7 +109,6 @@ overrides:
109 '@mastra/mcp@>=1.17.3 <2': 1.17.2
110 qs@<6.16.0: '>=6.16.0 <7'
111 protobufjs: 7.6.5
112 - minimatch@>=10.0.0 <10.2.3: '>=10.2.3 <11'
112 js-yaml@>=4.0.0 <4.3.2: '>=4.3.2 <5'
113 undici@>=5.0.0 <6.28.1: '>=6.28.1 <7'
114 js-yaml@>=3.0.0 <3.15.2: '>=3.15.2 <4'
@@ -1218,9 +1217,6 @@ importers:
1217
1218 ts/packages/cli:
1219 dependencies:
1221 - '@agentclientprotocol/sdk':
1222 - specifier: ^1.5.0
1223 - version: 1.5.0(zod@4.5.4)
1220 '@clack/core':
1221 specifier: 'catalog:'
1222 version: 1.5.1
@@ -1239,24 +1235,12 @@ importers:
1235 '@composio/json-schema-to-effect-schema':
1236 specifier: workspace:*
1237 version: link:../json-schema-to-effect-schema
1242 - '@composio/json-schema-to-zod':
1243 - specifier: workspace:*
1244 - version: link:../json-schema-to-zod
1238 '@composio/ts-builders':
1239 specifier: workspace:*
1240 version: link:../ts-builders
1241 '@effect/platform-bun':
1242 specifier: 'catalog:'
1243 version: 4.0.0-rc.117(effect@4.0.0-rc.117)
1251 - '@modelcontextprotocol/sdk':
1252 - specifier: 'catalog:'
1253 - version: 1.32.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
1254 - '@zed-industries/claude-code-acp':
1255 - specifier: ^0.16.2
1256 - version: 0.16.2(@cfworker/json-schema@4.1.1)(zod@4.5.4)
1257 - '@zed-industries/codex-acp':
1258 - specifier: ^0.16.0
1259 - version: 0.16.0
1244 effect:
1245 specifier: 'catalog:'
1246 version: 4.0.0-rc.117
@@ -1827,16 +1811,6 @@ packages:
1811 express:
1812 optional: true
1813
1830 - '@agentclientprotocol/sdk@0.14.1':
1831 - resolution: {integrity: sha512-b6r3PS3Nly+Wyw9U+0nOr47bV8tfS476EgyEMhoKvJCZLbgqoDFN7DJwkxL88RR0aiOqOYV1ZnESHqb+RmdH8w==}
1832 - peerDependencies:
1833 - zod: ^3.25.0 || ^4.0.0
1834 -
1835 - '@agentclientprotocol/sdk@1.5.0':
1836 - resolution: {integrity: sha512-524jwbB2iYWA+kWWyv9fhKbhU89dH/lu9u5EXwVNmfYzopV8BujCDxByBDZhxRUkB7RWIJzISCnwivdDk+bdVg==}
1837 - peerDependencies:
1838 - zod: ^3.25.0 || ^4.0.0
1839 -
1814 '@ai-sdk/gateway@3.0.201':
1815 resolution: {integrity: sha512-kbnt9E213FCVXJVyjRZDxxbTwANYIzKZ16eIGTGjsDeC4FlBDpiYx7miZFQ6Yym6DFekAXfZHshthYXjFf44HA==}
1816 engines: {node: '>=18'}
@@ -1980,12 +1954,6 @@ packages:
1954 cpu: [x64]
1955 os: [win32]
1956
1983 - '@anthropic-ai/claude-agent-sdk@0.2.44':
1984 - resolution: {integrity: sha512-bryUo6qq5dalO4MmhYLTPonTOAmdSVpMaVLJl8Y0qm6M7G+NZ3WS4cTMGrTbz97Uz5nah+FIOMA4hh8sKLm3YQ==}
1985 - engines: {node: '>=18.0.0'}
1986 - peerDependencies:
1987 - zod: ^4.0.0
1988 -
1957 '@anthropic-ai/claude-agent-sdk@0.3.282':
1958 resolution: {integrity: sha512-6UAerS1udzndLEx+0XW3gQWiICgfu/a+2fx/aLY3gUy+1JUQESbwYkhR40+D6d+yjueCslkLmvkPlZQFZDph6A==}
1959 engines: {node: '>=18.0.0'}
@@ -2755,24 +2723,12 @@ packages:
2723 resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}
2724 engines: {node: '>=18'}
2725
2758 - '@img/sharp-darwin-arm64@0.33.5':
2759 - resolution: {integrity: sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==}
2760 - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
2761 - cpu: [arm64]
2762 - os: [darwin]
2763 -
2726 '@img/sharp-darwin-arm64@0.35.4':
2727 resolution: {integrity: sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==}
2728 engines: {node: '>=20.9.0'}
2729 cpu: [arm64]
2730 os: [darwin]
2731
2770 - '@img/sharp-darwin-x64@0.33.5':
2771 - resolution: {integrity: sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==}
2772 - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
2773 - cpu: [x64]
2774 - os: [darwin]
2775 -
2732 '@img/sharp-darwin-x64@0.35.4':
2733 resolution: {integrity: sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==}
2734 engines: {node: '>=20.9.0'}
@@ -2784,44 +2740,22 @@ packages:
2740 engines: {node: '>=20.9.0'}
2741 os: [freebsd]
2742
2787 - '@img/sharp-libvips-darwin-arm64@1.0.4':
2788 - resolution: {integrity: sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==}
2789 - cpu: [arm64]
2790 - os: [darwin]
2791 -
2743 '@img/sharp-libvips-darwin-arm64@1.3.3':
2744 resolution: {integrity: sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==}
2745 cpu: [arm64]
2746 os: [darwin]
2747
2797 - '@img/sharp-libvips-darwin-x64@1.0.4':
2798 - resolution: {integrity: sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==}
2799 - cpu: [x64]
2800 - os: [darwin]
2801 -
2748 '@img/sharp-libvips-darwin-x64@1.3.3':
2749 resolution: {integrity: sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==}
2750 cpu: [x64]
2751 os: [darwin]
2752
2807 - '@img/sharp-libvips-linux-arm64@1.0.4':
2808 - resolution: {integrity: sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==}
2809 - cpu: [arm64]
2810 - os: [linux]
2811 - libc: [glibc]
2812 -
2753 '@img/sharp-libvips-linux-arm64@1.3.3':
2754 resolution: {integrity: sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==}
2755 cpu: [arm64]
2756 os: [linux]
2757 libc: [glibc]
2758
2819 - '@img/sharp-libvips-linux-arm@1.0.5':
2820 - resolution: {integrity: sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==}
2821 - cpu: [arm]
2822 - os: [linux]
2823 - libc: [glibc]
2824 -
2759 '@img/sharp-libvips-linux-arm@1.3.3':
2760 resolution: {integrity: sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==}
2761 cpu: [arm]
@@ -2846,49 +2780,24 @@ packages:
2780 os: [linux]
2781 libc: [glibc]
2782
2849 - '@img/sharp-libvips-linux-x64@1.0.4':
2850 - resolution: {integrity: sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==}
2851 - cpu: [x64]
2852 - os: [linux]
2853 - libc: [glibc]
2854 -
2783 '@img/sharp-libvips-linux-x64@1.3.3':
2784 resolution: {integrity: sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==}
2785 cpu: [x64]
2786 os: [linux]
2787 libc: [glibc]
2788
2861 - '@img/sharp-libvips-linuxmusl-arm64@1.0.4':
2862 - resolution: {integrity: sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==}
2863 - cpu: [arm64]
2864 - os: [linux]
2865 - libc: [musl]
2866 -
2789 '@img/sharp-libvips-linuxmusl-arm64@1.3.3':
2790 resolution: {integrity: sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==}
2791 cpu: [arm64]
2792 os: [linux]
2793 libc: [musl]
2794
2873 - '@img/sharp-libvips-linuxmusl-x64@1.0.4':
2874 - resolution: {integrity: sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==}
2875 - cpu: [x64]
2876 - os: [linux]
2877 - libc: [musl]
2878 -
2795 '@img/sharp-libvips-linuxmusl-x64@1.3.3':
2796 resolution: {integrity: sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==}
2797 cpu: [x64]
2798 os: [linux]
2799 libc: [musl]
2800
2885 - '@img/sharp-linux-arm64@0.33.5':
2886 - resolution: {integrity: sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==}
2887 - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
2888 - cpu: [arm64]
2889 - os: [linux]
2890 - libc: [glibc]
2891 -
2801 '@img/sharp-linux-arm64@0.35.4':
2802 resolution: {integrity: sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==}
2803 engines: {node: '>=20.9.0'}
@@ -2896,13 +2805,6 @@ packages:
2805 os: [linux]
2806 libc: [glibc]
2807
2899 - '@img/sharp-linux-arm@0.33.5':
2900 - resolution: {integrity: sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==}
2901 - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
2902 - cpu: [arm]
2903 - os: [linux]
2904 - libc: [glibc]
2905 -
2808 '@img/sharp-linux-arm@0.35.4':
2809 resolution: {integrity: sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==}
2810 engines: {node: '>=20.9.0'}
@@ -2931,13 +2833,6 @@ packages:
2833 os: [linux]
2834 libc: [glibc]
2835
2934 - '@img/sharp-linux-x64@0.33.5':
2935 - resolution: {integrity: sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==}
2936 - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
2937 - cpu: [x64]
2938 - os: [linux]
2939 - libc: [glibc]
2940 -
2836 '@img/sharp-linux-x64@0.35.4':
2837 resolution: {integrity: sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==}
2838 engines: {node: '>=20.9.0'}
@@ -2945,13 +2840,6 @@ packages:
2840 os: [linux]
2841 libc: [glibc]
2842
2948 - '@img/sharp-linuxmusl-arm64@0.33.5':
2949 - resolution: {integrity: sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==}
2950 - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
2951 - cpu: [arm64]
2952 - os: [linux]
2953 - libc: [musl]
2954 -
2843 '@img/sharp-linuxmusl-arm64@0.35.4':
2844 resolution: {integrity: sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==}
2845 engines: {node: '>=20.9.0'}
@@ -2959,13 +2847,6 @@ packages:
2847 os: [linux]
2848 libc: [musl]
2849
2962 - '@img/sharp-linuxmusl-x64@0.33.5':
2963 - resolution: {integrity: sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==}
2964 - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
2965 - cpu: [x64]
2966 - os: [linux]
2967 - libc: [musl]
2968 -
2850 '@img/sharp-linuxmusl-x64@0.35.4':
2851 resolution: {integrity: sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==}
2852 engines: {node: '>=20.9.0'}
@@ -2994,12 +2875,6 @@ packages:
2875 cpu: [ia32]
2876 os: [win32]
2877
2997 - '@img/sharp-win32-x64@0.33.5':
2998 - resolution: {integrity: sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==}
2999 - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
3000 - cpu: [x64]
3001 - os: [win32]
3002 -
2878 '@img/sharp-win32-x64@0.35.4':
2879 resolution: {integrity: sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==}
2880 engines: {node: '>=20.9.0'}
@@ -4371,58 +4246,6 @@ packages:
4246 '@yuku-toolchain/types@0.9.3':
4247 resolution: {integrity: sha512-rFE+5P4g2wxko5C85MugJOlVjBHEQq87dIkhLkniLXLp63PEtgaFjD954i5HXlfnyzLxPcZHsSOVDVgmo1HToA==}
4248
4374 - '@zed-industries/claude-code-acp@0.16.2':
4375 - resolution: {integrity: sha512-D8BJe6CCD49RtNFbZYPsfZOpQI8Z/EzhyYC9zAGMwN/HVunEtVY2sXqYl1iDSkkayzhqABfaDkDZfeqDM1T/aA==}
4376 - deprecated: This package has been renamed to @agentclientprotocol/claude-agent-acp. Please migrate to continue receiving updates.
4377 - hasBin: true
4378 -
4379 - '@zed-industries/codex-acp-darwin-arm64@0.16.0':
4380 - resolution: {integrity: sha512-2AmbWsc/+Mpn6U8UOIlPLvgwGsGOr/LFpgcvrnjcCT9V1yY92MLrqzjMX82+VjTrRLRuXvc25SB5Z1++4Pw29g==}
4381 - cpu: [arm64]
4382 - os: [darwin]
4383 - deprecated: This package has been replaced by @agentclientprotocol/codex-acp. Please migrate to continue receiving updates.
4384 - hasBin: true
4385 -
4386 - '@zed-industries/codex-acp-darwin-x64@0.16.0':
4387 - resolution: {integrity: sha512-QCWggk0s4GTPLCR7eznyx29Dls4gzUKvp4MjZ4nzPX5gDL/02PGY+oCV1WsQOsnzWRK0RxM+GlK19rG1qzqplw==}
4388 - cpu: [x64]
4389 - os: [darwin]
4390 - deprecated: This package has been replaced by @agentclientprotocol/codex-acp. Please migrate to continue receiving updates.
4391 - hasBin: true
4392 -
4393 - '@zed-industries/codex-acp-linux-arm64@0.16.0':
4394 - resolution: {integrity: sha512-8HaZGWVPVs1N6yqImLCKlnlcYTYc9BMCEhaVJk0ON9lyofhK9mOBBAHQndKC4Scqq5JLUHQIOyb8+jwHUe3hSQ==}
4395 - cpu: [arm64]
4396 - os: [linux]
4397 - deprecated: This package has been replaced by @agentclientprotocol/codex-acp. Please migrate to continue receiving updates.
4398 - hasBin: true
4399 -
4400 - '@zed-industries/codex-acp-linux-x64@0.16.0':
4401 - resolution: {integrity: sha512-xs5zZBLpJuciEbZNx6ZSNL0qCa9h3i/zWpj40sp6QtF+L4Ow/7qzHdBzboGhHdcz1jrLedfZeRFDA2Elj8TLMA==}
4402 - cpu: [x64]
4403 - os: [linux]
4404 - deprecated: This package has been replaced by @agentclientprotocol/codex-acp. Please migrate to continue receiving updates.
4405 - hasBin: true
4406 -
4407 - '@zed-industries/codex-acp-win32-arm64@0.16.0':
4408 - resolution: {integrity: sha512-4V3pDJvEyNkgVqWqlm0bLYEZ8liGXXp8InuHzCy5cgr+SFur6BuasA29tisN8NUrLus/ZvMhXCrOsNKurYAWQw==}
4409 - cpu: [arm64]
4410 - os: [win32]
4411 - deprecated: This package has been replaced by @agentclientprotocol/codex-acp. Please migrate to continue receiving updates.
4412 - hasBin: true
4413 -
4414 - '@zed-industries/codex-acp-win32-x64@0.16.0':
4415 - resolution: {integrity: sha512-ZriI/ay5E3DCg8s22LZykIRI2XzQL6sZg/t81K+6qc86ldscaSWQSOT6KSnRcv31QJCMfBlFxMj22pZiGSVjQA==}
4416 - cpu: [x64]
4417 - os: [win32]
4418 - deprecated: This package has been replaced by @agentclientprotocol/codex-acp. Please migrate to continue receiving updates.
4419 - hasBin: true
4420 -
4421 - '@zed-industries/codex-acp@0.16.0':
4422 - resolution: {integrity: sha512-XKzqztT5R8Wg1BVFnk6/U4JVx5GNUaZgxpf9gP2Cw6BsknvJWh3aefcAGZQljgdMivRqczjNKYL4F6H65dc5vA==}
4423 - deprecated: This package has been replaced by @agentclientprotocol/codex-acp. Please migrate to continue receiving updates.
4424 - hasBin: true
4425 -
4249 accepts@2.0.0:
4250 resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==}
4251 engines: {node: '>= 0.6'}
@@ -4740,10 +4563,6 @@ packages:
4563 devlop@1.1.0:
4564 resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}
4565
4743 - diff@8.0.3:
4744 - resolution: {integrity: sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ==}
4745 - engines: {node: '>=0.3.1'}
4746 -
4566 diff@8.0.4:
4567 resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==}
4568 engines: {node: '>=0.3.1'}
@@ -6131,10 +5950,6 @@ packages:
5950 resolution: {integrity: sha512-kUMbT1oBJCpgrnKoSr0o6wPtvRWT9W9UKvGLwfJYO2WuahZRHOpEyL1ckyMGgMWh0UdpmaoFqKKD29WTomNEGA==}
5951 engines: {node: '>=8'}
5952
6134 - source-map-js@1.2.1:
6135 - resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
6136 - engines: {node: '>=0.10.0'}
6137 -
5953 source-map-js@1.2.2:
5954 resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
5955 engines: {node: '>=0.10.0'}
@@ -6751,14 +6566,6 @@ snapshots:
6566 optionalDependencies:
6567 express: 5.2.1
6568
6754 - '@agentclientprotocol/sdk@0.14.1(zod@4.5.4)':
6755 - dependencies:
6756 - zod: 4.5.4
6757 -
6758 - '@agentclientprotocol/sdk@1.5.0(zod@4.5.4)':
6759 - dependencies:
6760 - zod: 4.5.4
6761 -
6569 '@ai-sdk/gateway@3.0.201(zod@3.25.76)':
6570 dependencies:
6571 '@ai-sdk/provider': 3.0.17
@@ -6962,19 +6769,6 @@ snapshots:
6769 '@anthropic-ai/claude-agent-sdk-win32-x64@0.3.282':
6770 optional: true
6771
6965 - '@anthropic-ai/claude-agent-sdk@0.2.44(zod@4.5.4)':
6966 - dependencies:
6967 - zod: 4.5.4
6968 - optionalDependencies:
6969 - '@img/sharp-darwin-arm64': 0.33.5
6970 - '@img/sharp-darwin-x64': 0.33.5
6971 - '@img/sharp-linux-arm': 0.33.5
6972 - '@img/sharp-linux-arm64': 0.33.5
6973 - '@img/sharp-linux-x64': 0.33.5
6974 - '@img/sharp-linuxmusl-arm64': 0.33.5
6975 - '@img/sharp-linuxmusl-x64': 0.33.5
6976 - '@img/sharp-win32-x64': 0.33.5
6977 -
6772 '@anthropic-ai/claude-agent-sdk@0.3.282(@anthropic-ai/sdk@0.127.0(zod@4.5.4))(@modelcontextprotocol/sdk@1.32.0(@cfworker/json-schema@4.1.1)(zod@4.5.4))(zod@4.5.4)':
6773 dependencies:
6774 '@anthropic-ai/sdk': 0.127.0(zod@4.5.4)
@@ -7813,21 +7607,11 @@ snapshots:
7607
7608 '@img/colour@1.1.0': {}
7609
7816 - '@img/sharp-darwin-arm64@0.33.5':
7817 - optionalDependencies:
7818 - '@img/sharp-libvips-darwin-arm64': 1.0.4
7819 - optional: true
7820 -
7610 '@img/sharp-darwin-arm64@0.35.4':
7611 optionalDependencies:
7612 '@img/sharp-libvips-darwin-arm64': 1.3.3
7613 optional: true
7614
7826 - '@img/sharp-darwin-x64@0.33.5':
7827 - optionalDependencies:
7828 - '@img/sharp-libvips-darwin-x64': 1.0.4
7829 - optional: true
7830 -
7615 '@img/sharp-darwin-x64@0.35.4':
7616 optionalDependencies:
7617 '@img/sharp-libvips-darwin-x64': 1.3.3
@@ -7838,27 +7622,15 @@ snapshots:
7622 '@img/sharp-wasm32': 0.35.4
7623 optional: true
7624
7841 - '@img/sharp-libvips-darwin-arm64@1.0.4':
7842 - optional: true
7843 -
7625 '@img/sharp-libvips-darwin-arm64@1.3.3':
7626 optional: true
7627
7847 - '@img/sharp-libvips-darwin-x64@1.0.4':
7848 - optional: true
7849 -
7628 '@img/sharp-libvips-darwin-x64@1.3.3':
7629 optional: true
7630
7853 - '@img/sharp-libvips-linux-arm64@1.0.4':
7854 - optional: true
7855 -
7631 '@img/sharp-libvips-linux-arm64@1.3.3':
7632 optional: true
7633
7859 - '@img/sharp-libvips-linux-arm@1.0.5':
7860 - optional: true
7861 -
7634 '@img/sharp-libvips-linux-arm@1.3.3':
7635 optional: true
7636
@@ -7871,39 +7643,20 @@ snapshots:
7643 '@img/sharp-libvips-linux-s390x@1.3.3':
7644 optional: true
7645
7874 - '@img/sharp-libvips-linux-x64@1.0.4':
7875 - optional: true
7876 -
7646 '@img/sharp-libvips-linux-x64@1.3.3':
7647 optional: true
7648
7880 - '@img/sharp-libvips-linuxmusl-arm64@1.0.4':
7881 - optional: true
7882 -
7649 '@img/sharp-libvips-linuxmusl-arm64@1.3.3':
7650 optional: true
7651
7886 - '@img/sharp-libvips-linuxmusl-x64@1.0.4':
7887 - optional: true
7888 -
7652 '@img/sharp-libvips-linuxmusl-x64@1.3.3':
7653 optional: true
7654
7892 - '@img/sharp-linux-arm64@0.33.5':
7893 - optionalDependencies:
7894 - '@img/sharp-libvips-linux-arm64': 1.0.4
7895 - optional: true
7896 -
7655 '@img/sharp-linux-arm64@0.35.4':
7656 optionalDependencies:
7657 '@img/sharp-libvips-linux-arm64': 1.3.3
7658 optional: true
7659
7902 - '@img/sharp-linux-arm@0.33.5':
7903 - optionalDependencies:
7904 - '@img/sharp-libvips-linux-arm': 1.0.5
7905 - optional: true
7906 -
7660 '@img/sharp-linux-arm@0.35.4':
7661 optionalDependencies:
7662 '@img/sharp-libvips-linux-arm': 1.3.3
@@ -7924,31 +7677,16 @@ snapshots:
7677 '@img/sharp-libvips-linux-s390x': 1.3.3
7678 optional: true
7679
7927 - '@img/sharp-linux-x64@0.33.5':
7928 - optionalDependencies:
7929 - '@img/sharp-libvips-linux-x64': 1.0.4
7930 - optional: true
7931 -
7680 '@img/sharp-linux-x64@0.35.4':
7681 optionalDependencies:
7682 '@img/sharp-libvips-linux-x64': 1.3.3
7683 optional: true
7684
7937 - '@img/sharp-linuxmusl-arm64@0.33.5':
7938 - optionalDependencies:
7939 - '@img/sharp-libvips-linuxmusl-arm64': 1.0.4
7940 - optional: true
7941 -
7685 '@img/sharp-linuxmusl-arm64@0.35.4':
7686 optionalDependencies:
7687 '@img/sharp-libvips-linuxmusl-arm64': 1.3.3
7688 optional: true
7689
7947 - '@img/sharp-linuxmusl-x64@0.33.5':
7948 - optionalDependencies:
7949 - '@img/sharp-libvips-linuxmusl-x64': 1.0.4
7950 - optional: true
7951 -
7690 '@img/sharp-linuxmusl-x64@0.35.4':
7691 optionalDependencies:
7692 '@img/sharp-libvips-linuxmusl-x64': 1.3.3
@@ -7970,9 +7708,6 @@ snapshots:
7708 '@img/sharp-win32-ia32@0.35.4':
7709 optional: true
7710
7973 - '@img/sharp-win32-x64@0.33.5':
7974 - optional: true
7975 -
7711 '@img/sharp-win32-x64@0.35.4':
7712 optional: true
7713
@@ -9271,45 +9006,6 @@ snapshots:
9006
9007 '@yuku-toolchain/types@0.9.3': {}
9008
9274 - '@zed-industries/claude-code-acp@0.16.2(@cfworker/json-schema@4.1.1)(zod@4.5.4)':
9275 - dependencies:
9276 - '@agentclientprotocol/sdk': 0.14.1(zod@4.5.4)
9277 - '@anthropic-ai/claude-agent-sdk': 0.2.44(zod@4.5.4)
9278 - '@modelcontextprotocol/sdk': 1.32.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
9279 - diff: 8.0.3
9280 - minimatch: 10.2.5
9281 - transitivePeerDependencies:
9282 - - '@cfworker/json-schema'
9283 - - supports-color
9284 - - zod
9285 -
9286 - '@zed-industries/codex-acp-darwin-arm64@0.16.0':
9287 - optional: true
9288 -
9289 - '@zed-industries/codex-acp-darwin-x64@0.16.0':
9290 - optional: true
9291 -
9292 - '@zed-industries/codex-acp-linux-arm64@0.16.0':
9293 - optional: true
9294 -
9295 - '@zed-industries/codex-acp-linux-x64@0.16.0':
9296 - optional: true
9297 -
9298 - '@zed-industries/codex-acp-win32-arm64@0.16.0':
9299 - optional: true
9300 -
9301 - '@zed-industries/codex-acp-win32-x64@0.16.0':
9302 - optional: true
9303 -
9304 - '@zed-industries/codex-acp@0.16.0':
9305 - optionalDependencies:
9306 - '@zed-industries/codex-acp-darwin-arm64': 0.16.0
9307 - '@zed-industries/codex-acp-darwin-x64': 0.16.0
9308 - '@zed-industries/codex-acp-linux-arm64': 0.16.0
9309 - '@zed-industries/codex-acp-linux-x64': 0.16.0
9310 - '@zed-industries/codex-acp-win32-arm64': 0.16.0
9311 - '@zed-industries/codex-acp-win32-x64': 0.16.0
9312 -
9009 accepts@2.0.0:
9010 dependencies:
9011 mime-types: 3.0.2
@@ -9601,8 +9297,6 @@ snapshots:
9297 dependencies:
9298 dequal: 2.0.3
9299
9604 - diff@8.0.3: {}
9605 -
9300 diff@8.0.4: {}
9301
9302 dom-serializer@2.0.0:
@@ -10905,7 +10599,7 @@ snapshots:
10599 dependencies:
10600 nanoid: 3.3.18
10601 picocolors: 1.1.1
10908 - source-map-js: 1.2.1
10602 + source-map-js: 1.2.2
10603
10604 posthog-node@5.46.1:
10605 dependencies:
@@ -11286,8 +10980,6 @@ snapshots:
10980 dependencies:
10981 unicode-emoji-modifier-base: 1.0.0
10982
11289 - source-map-js@1.2.1: {}
11290 -
10983 source-map-js@1.2.2: {}
10984
10985 sprintf-js@1.0.3: {}
pnpm-workspace.yaml
-2
@@ -111,8 +111,6 @@ overrides:
111 # Drop when its lockfile resolution is >=6.16.0 without an override.
112 'qs@<6.16.0': '>=6.16.0 <7'
113 protobufjs: 7.6.5
114 - # temporary: @zed-industries/claude-code-acp@0.16.2 (latest) exact-pins vulnerable 10.2.1; drop when it ships >=10.2.3
115 - 'minimatch@>=10.0.0 <10.2.3': '>=10.2.3 <11'
114 # temporary: @redocly/openapi-core@1.34.x (via openapi-typescript) exact-pins
115 # vulnerable 4.2.0; GHSA-2883-xcg3-v3hh raised the patched floor to 4.3.2.
116 # Drop when it ships >=4.3.2.
ts/e2e-tests/_utils/Dockerfile.cli
+4 -12
@@ -59,18 +59,10 @@ RUN bun build ./src/bin.ts \
59 --outfile /out/composio
60
61 # Build the `composio run` companion modules next to the binary. Without the
62 -# run-*.mjs wrappers every `composio run` treats the install as broken and
63 -# enters the GitHub self-repair path. `--host-only` restricts the bundled
64 -# codex-acp binary to this image's own platform; shipping all four costs ~870MB
65 -# and ~2min of build time for binaries this image can never execute.
66 -#
67 -# The acp-adapters are dropped afterwards: they are only needed when a script
68 -# invokes an ACP sub-agent, which is checked lazily at the invocation site, and
69 -# no CLI e2e test does. Keeping them would add ~224MB to the image. The build
70 -# script still produces them (it asserts on its own output), so the removal
71 -# happens in the same layer to keep it out of the image entirely.
72 -RUN bun scripts/build-companion-modules.ts /out --host-only && \
73 - rm -rf /out/acp-adapters
62 +# run-helpers-runtime.mjs and generation-runtime.mjs wrappers every
63 +# `composio run` treats the install as broken and enters the GitHub self-repair
64 +# path.
65 +RUN bun scripts/build-companion-modules.ts /out
66
67 # Copy CLI e2e tests last (changes frequently)
68 WORKDIR /app
ts/e2e-tests/cli/upgrade/e2e.test.ts
+27 -11
@@ -8,15 +8,20 @@ import { e2e, type E2ETestResult } from '@e2e-tests/utils';
8 import { TIMEOUTS } from '@e2e-tests/utils/const';
9 import { beforeAll, describe, expect, it } from 'bun:test';
10
11 -const companionRelativePaths = [
12 - // RUN_COMPANION_MODULE_FILENAMES
13 - 'run-helpers-runtime.mjs',
11 +// The "downloaded" bundle is laid out like a release archive: the live companions
12 +// with their real contents, plus the legacy paths as empty placeholders.
13 +
14 +// RUN_COMPANION_MODULE_FILENAMES
15 +const liveCompanionFileNames = ['run-helpers-runtime.mjs', 'generation-runtime.mjs'] as const;
16 +
17 +const runOutputMarker = 'composio-upgrade-run-companions-loaded';
18 +
19 +// RUN_COMPANION_LEGACY_PLACEHOLDER_RELATIVE_PATHS
20 +const legacyPlaceholderRelativePaths = [
21 'run-subagent-shared.mjs',
22 'run-subagent-acp.mjs',
23 'run-subagent-legacy.mjs',
24 'run-subagent-output-mcp.mjs',
18 - 'generation-runtime.mjs',
19 - // RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS
25 'acp-adapters/claude-code-acp.mjs',
26 'acp-adapters/cli.js',
27 'acp-adapters/codex/darwin-arm64/codex-acp',
@@ -25,12 +30,17 @@ const companionRelativePaths = [
30 'acp-adapters/codex/linux-x64/codex-acp',
31 ] as const;
32
28 -const sourceBundleSetup = companionRelativePaths
29 - .map(
33 +const sourceBundleSetup = [
34 + 'mkdir -p "$source_dir/services"',
35 + ...liveCompanionFileNames.flatMap(fileName => [
36 + `cp "/usr/local/bin/${fileName}" "$source_dir/${fileName}"`,
37 + `cp "/usr/local/bin/services/${fileName}" "$source_dir/services/${fileName}"`,
38 + ]),
39 + ...legacyPlaceholderRelativePaths.map(
40 relativePath =>
41 `mkdir -p "$(dirname "$source_dir/${relativePath}")"\n: > "$source_dir/${relativePath}"`
32 - )
33 - .join('\n');
42 + ),
43 +].join('\n');
44
45 const upgradeCommand = ({
46 executablePath,
@@ -60,12 +70,16 @@ fi
70
71 version_output=$("$executable_path" version)
72 version_status=$?
63 -printf 'before_inode=%s\nafter_inode=%s\nupgrade_status=%s\nexecutable_status=%s\nversion_status=%s\nversion=%s\n' \
64 - "$before_inode" "$after_inode" "$upgrade_status" "$executable_status" "$version_status" "$version_output"
73 +run_output=$("$executable_path" run 'console.log(z.string().parse("${runOutputMarker}"))')
74 +run_status=$?
75 +printf 'before_inode=%s\nafter_inode=%s\nupgrade_status=%s\nexecutable_status=%s\nversion_status=%s\nversion=%s\nrun_status=%s\nrun_output=%s\n' \
76 + "$before_inode" "$after_inode" "$upgrade_status" "$executable_status" "$version_status" "$version_output" "$run_status" "$run_output"
77
78 if [ "$upgrade_status" -eq 0 ] &&
79 [ "$executable_status" -eq 0 ] &&
80 [ "$version_status" -eq 0 ] &&
81 + [ "$run_status" -eq 0 ] &&
82 + [ "$run_output" = "${runOutputMarker}" ] &&
83 [ -n "$before_inode" ] &&
84 [ -n "$after_inode" ] &&
85 [ "$before_inode" != "$after_inode" ]; then
@@ -87,6 +101,8 @@ const expectAtomicUpgrade = (result: E2ETestResult) => {
101 expect(outputField(result, 'executable_status')).toBe('0');
102 expect(outputField(result, 'version_status')).toBe('0');
103 expect(outputField(result, 'version')).toMatch(/\d+\.\d+\.\d+/);
104 + expect(outputField(result, 'run_status')).toBe('0');
105 + expect(outputField(result, 'run_output')).toBe(runOutputMarker);
106 expect(outputField(result, 'after_inode')).not.toBe(outputField(result, 'before_inode'));
107 };
108
ts/packages/cli-keyring/README.md
+1 -1
@@ -190,7 +190,7 @@ logout:
190
191 ### The `dangerouslySaveApiKeyInUserConfig` escape hatch
192
193 -Lives in `CliUserConfig` (`~/.composio/config.json`), alongside existing `experimentalFeatures` / `artifactDirectory` / `experimentalSubagent`. **Opt-in, not a CLI flag, not advertised in `--help`** — users who need it edit `config.json` themselves.
193 +Lives in `CliUserConfig` (`~/.composio/config.json`), alongside existing `experimentalFeatures` / `artifactDirectory`. **Opt-in, not a CLI flag, not advertised in `--help`** — users who need it edit `config.json` themselves.
194
195 ```json
196 {
ts/packages/cli/AGENTS.md
+1 -1
@@ -195,7 +195,7 @@ Conversion patterns, in order of preference:
195 3. Pass the resolved service instance (e.g. `Path.Path`, `FileSystem.FileSystem`) as a plain parameter into sync callbacks or promise pipelines that cannot become Effects (see `tool-permissions.ts`, `generation/typescript/virtual-compiler-host.ts`).
196 4. Modules that self-provide layers add `BunPath.layer` / `BunFileSystem.layer` / `NodeOs.Default` to their stack instead of reaching for Node builtins.
197
198 -The only code allowed to bypass services sits at declared runtime boundaries: the `bin.ts` bootstrap, the child-process companion runtime (`run-helpers-runtime.ts`, `run-subagent-*` — bundled into `.mjs` files that run in the user's spawned process), import-time UI setup (`ui/colors.ts`, `ui/redact.ts`), environment **writes** and whole-environment enumeration (which `effect/Config` cannot express), and spawn-time env handshakes between parent and child `composio run` processes. Every such boundary is an inline `// eslint-disable-next-line <rule> -- <reason>` comment registered in `lint-boundaries.json`. (oxlint honors both the `eslint-disable` and `oxlint-disable` spellings; only `eslint-disable-next-line` is sanctioned here, and the boundary validator rejects `oxlint-disable` comments in `src/`. The restricted-syntax rule ships from a JS plugin, so its disables name it `eslint-js/no-restricted-syntax`.)
198 +The only code allowed to bypass services sits at declared runtime boundaries: the `bin.ts` bootstrap, the child-process companion runtime (`run-helpers-runtime.ts` — bundled into a `.mjs` file that runs in the user's spawned process), import-time UI setup (`ui/colors.ts`, `ui/redact.ts`), environment **writes** and whole-environment enumeration (which `effect/Config` cannot express), and spawn-time env handshakes between parent and child `composio run` processes. Every such boundary is an inline `// eslint-disable-next-line <rule> -- <reason>` comment registered in `lint-boundaries.json`. (oxlint honors both the `eslint-disable` and `oxlint-disable` spellings; only `eslint-disable-next-line` is sanctioned here, and the boundary validator rejects `oxlint-disable` comments in `src/`. The restricted-syntax rule ships from a JS plugin, so its disables name it `eslint-js/no-restricted-syntax`.)
199
200 **Enforcement**: `pnpm run validate:boundaries` (part of `pnpm test`, CI-blocking) fails when any eslint-disable in `src/` is missing from the manifest, lacks a `-- reason`, or uses a file-wide form. Do not add new disables — thread the service instead. If code genuinely cannot run inside the Effect runtime, that is a new boundary: regenerate the manifest with `pnpm run validate:boundaries -- --update` and justify the boundary in the PR.
201
ts/packages/cli/CHANGELOG.md
+22
@@ -48,6 +48,28 @@
48 Swift. Permission prompts always use the browser approval page. A
49 stored `local_tools` setting is now listed as an unknown feature and has no
50 effect.
51 +- Remove `experimental_subAgent()` (alias `invokeAgent`) from `composio run`.
52 + Its ACP transport approved every tool call the spawned agent requested, so
53 + both transports (ACP and the older `claude -p` / `codex exec` one), the output
54 + MCP server, and the bundled ACP adapters are gone. `execute`, `search`,
55 + `proxy`, `result.prompt()`, and the `z` / `zod` globals are unchanged. A
56 + script that still calls the helper fails at that call with a message naming
57 + the removal; tool calls it made earlier have already taken effect. To keep
58 + the helper, install an older CLI with the installer:
59 + `curl -fsSL https://composio.dev/install | COMPOSIO_INSTALL_VERSION=<version> sh`.
60 + `composio upgrade <older version>` from this CLI is not a way back. A stored
61 + `experimental_subagent` config key is now ignored and preserved; an invalid
62 + target used to reset the whole config to defaults. `COMPOSIO_RUN_ACP_ONLY` is
63 + no longer read and the hidden `--acp-only` flag is gone. Remove `--logs-off`,
64 + which only canceled `--debug` after sub-agent streaming was removed. Helper
65 + logs are written to disk; use `--debug` to also print them to stderr. An
66 + unknown flag placed before inline `run` code is now rejected by name
67 + (`Unrecognized flag: --x in command composio run`) instead of being executed
68 + as source; inline source that is exactly one flag-shaped token needs an
69 + explicit `--`. Release archives keep ten legacy paths (the four root
70 + `run-subagent-*.mjs` files and six `acp-adapters/*` paths) as intentionally
71 + empty placeholders so that a CLI installed before this change still passes
72 + its upgrade verification. No adapter binaries are downloaded or shipped.
73 - Every Composio API call now goes through the `@composio/client` 2.0 runtime,
74 the same client `@composio/core` uses. Org, project, session-info, and
75 consumer lookups gain the client's retries and redirect handling, and API
ts/packages/cli/README.md
-1
@@ -84,7 +84,6 @@ The CLI and its installer use these variables to coordinate nested commands. The
84 | ------------------------------ | -------------------------------------------------------------------------- | ------- |
85 | COMPOSIO_CLI_INVOCATION_ORIGIN | Identifies whether another CLI surface, such as `composio run`, invoked it | cli |
86 | COMPOSIO_CLI_PARENT_RUN_ID | Reuses the parent run ID for nested command telemetry | None |
87 -| COMPOSIO_RUN_ACP_ONLY | Set to `1` to disable the legacy sub-agent fallback | 0 |
87 | COMPOSIO_RUN_OUTPUT_DIR | Shares one artifact directory across nested `composio run` commands | None |
88
89 Additionally, `composio upgrade` supports the following environment variables:
ts/packages/cli/lint-boundaries.json
+1 -1
@@ -16,7 +16,7 @@
16 "src/services/run-helpers-runtime.ts": [
17 {
18 "rule": "no-restricted-imports",
19 - "reason": "sync fs for run-log appends, run-file writes, and CLI config reads in the child process, outside the Effect runtime",
19 + "reason": "sync fs for run-log appends and run-file writes in the child process, outside the Effect runtime",
20 "target": "import * as fs from 'node:fs';"
21 }
22 ],
ts/packages/cli/package.json
-5
@@ -63,19 +63,14 @@
63 "vitest": "catalog:"
64 },
65 "dependencies": {
66 - "@agentclientprotocol/sdk": "^1.5.0",
66 "@clack/core": "catalog:",
67 "@clack/prompts": "catalog:",
68 "@composio/cli-keyring": "workspace:*",
69 "@composio/client": "catalog:",
70 "@composio/core": "workspace:*",
71 "@composio/json-schema-to-effect-schema": "workspace:*",
73 - "@composio/json-schema-to-zod": "workspace:*",
72 "@composio/ts-builders": "workspace:*",
73 "@effect/platform-bun": "catalog:",
76 - "@modelcontextprotocol/sdk": "catalog:",
77 - "@zed-industries/claude-code-acp": "^0.16.2",
78 - "@zed-industries/codex-acp": "^0.16.0",
74 "effect": "catalog:",
75 "extract-zip": "^2.0.1",
76 "fast-string-width": "^3.0.2",
ts/packages/cli/scripts/_acp-adapters.ts deleted
-366
@@ -1,366 +0,0 @@
1 -import { chmod, copyFile, mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises';
2 -import { createRequire } from 'node:module';
3 -import * as path from 'node:path';
4 -import { fileURLToPath } from 'node:url';
5 -import {
6 - RUN_CODEX_ACP_BINARY_TARGETS,
7 - type RunCodexAcpBinaryTarget,
8 -} from '../src/services/run-companion-modules';
9 -import {
10 - assertBytesMatchIntegrity,
11 - expectedIntegrityFor,
12 - loadLockfileIntegrity,
13 -} from './_tarball-integrity';
14 -
15 -const GENERATED_ROOT_DIR = path.resolve('./.generated');
16 -const ACP_ADAPTERS_CACHE_DIR = path.join(GENERATED_ROOT_DIR, 'acp-adapters');
17 -const ACP_ADAPTERS_MANIFEST_PATH = path.join(GENERATED_ROOT_DIR, 'acp-adapters.manifest.json');
18 -const REGISTRY_BASE_URL = 'https://registry.npmjs.org';
19 -const USER_AGENT = 'composio-cli-acp-vendor/1';
20 -const ACP_ADAPTERS_PREFIX = 'acp-adapters/';
21 -const ACP_ADAPTERS_CACHE_FORMAT_VERSION = 2;
22 -
23 -type PackageJson = {
24 - readonly bin?: Readonly<Record<string, string>>;
25 - readonly optionalDependencies?: Readonly<Record<string, string>>;
26 - readonly version?: string;
27 -};
28 -
29 -type RegistryVersionManifest = {
30 - readonly dist?: {
31 - readonly tarball?: string;
32 - };
33 -};
34 -
35 -type AcpAdaptersManifest = {
36 - readonly cacheFormatVersion: number;
37 - readonly claude: {
38 - readonly packageName: '@zed-industries/claude-code-acp';
39 - readonly version: string;
40 - readonly agentSdkVersion: string;
41 - };
42 - readonly codex: ReadonlyArray<{
43 - readonly packageName: string;
44 - readonly relativePath: string;
45 - readonly version: string;
46 - }>;
47 -};
48 -
49 -const require = createRequire(import.meta.url);
50 -
51 -const fileExists = async (filePath: string): Promise<boolean> => Bun.file(filePath).exists();
52 -
53 -const readJsonFile = async <T>(filePath: string): Promise<T> =>
54 - JSON.parse(await readFile(filePath, 'utf8')) as T;
55 -
56 -const resolvePackageJsonPath = (specifier: string): string =>
57 - require.resolve(`${specifier}/package.json`);
58 -
59 -const stripAcpAdaptersPrefix = (relativePath: string): string =>
60 - relativePath.startsWith(ACP_ADAPTERS_PREFIX)
61 - ? relativePath.slice(ACP_ADAPTERS_PREFIX.length)
62 - : relativePath;
63 -
64 -const readInstalledPackageJson = async (specifier: string): Promise<PackageJson> =>
65 - readJsonFile<PackageJson>(resolvePackageJsonPath(specifier));
66 -
67 -const resolveClaudeAdapterEntryPath = async (): Promise<string> => {
68 - const manifest = await readInstalledPackageJson('@zed-industries/claude-code-acp');
69 - const entryPath = manifest.bin?.['claude-code-acp'];
70 - if (!entryPath) {
71 - throw new Error('Missing claude-code-acp bin entry in installed package metadata.');
72 - }
73 -
74 - return path.join(
75 - path.dirname(resolvePackageJsonPath('@zed-industries/claude-code-acp')),
76 - entryPath
77 - );
78 -};
79 -
80 -const resolveClaudeAgentSdkCliPath = (): string => {
81 - const claudeCodeAcpPkg = require.resolve('@zed-industries/claude-code-acp/package.json');
82 - const nestedRequire = createRequire(claudeCodeAcpPkg);
83 - const agentSdkPkg = nestedRequire.resolve('@anthropic-ai/claude-agent-sdk/package.json');
84 - return path.join(path.dirname(agentSdkPkg), 'cli.js');
85 -};
86 -
87 -const resolveClaudeAgentSdkPackageJsonPath = (): string => {
88 - const claudeCodeAcpPkg = require.resolve('@zed-industries/claude-code-acp/package.json');
89 - const nestedRequire = createRequire(claudeCodeAcpPkg);
90 - return nestedRequire.resolve('@anthropic-ai/claude-agent-sdk/package.json');
91 -};
92 -
93 -const buildCacheManifest = async (
94 - codexBinaryTargets: ReadonlyArray<RunCodexAcpBinaryTarget>
95 -): Promise<AcpAdaptersManifest> => {
96 - const claudePackage = await readInstalledPackageJson('@zed-industries/claude-code-acp');
97 - const agentSdkPackage = await readJsonFile<PackageJson>(resolveClaudeAgentSdkPackageJsonPath());
98 - const codexLauncherPackage = await readInstalledPackageJson('@zed-industries/codex-acp');
99 -
100 - const codexTargets = codexBinaryTargets.map(target => {
101 - const version = codexLauncherPackage.optionalDependencies?.[target.packageName];
102 - if (!version) {
103 - throw new Error(
104 - `Missing pinned optional dependency version for ${target.packageName} in @zed-industries/codex-acp.`
105 - );
106 - }
107 -
108 - return {
109 - packageName: target.packageName,
110 - relativePath: target.relativePath,
111 - version,
112 - };
113 - });
114 -
115 - if (!claudePackage.version || !agentSdkPackage.version) {
116 - throw new Error('Missing installed claude ACP package versions.');
117 - }
118 -
119 - return {
120 - cacheFormatVersion: ACP_ADAPTERS_CACHE_FORMAT_VERSION,
121 - claude: {
122 - packageName: '@zed-industries/claude-code-acp',
123 - version: claudePackage.version,
124 - agentSdkVersion: agentSdkPackage.version,
125 - },
126 - codex: codexTargets,
127 - };
128 -};
129 -
130 -const readExistingManifest = async (): Promise<AcpAdaptersManifest | null> => {
131 - if (!(await fileExists(ACP_ADAPTERS_MANIFEST_PATH))) {
132 - return null;
133 - }
134 -
135 - return readJsonFile<AcpAdaptersManifest>(ACP_ADAPTERS_MANIFEST_PATH).catch(() => null);
136 -};
137 -
138 -const manifestPathsExist = async (manifest: AcpAdaptersManifest): Promise<boolean> => {
139 - const requiredPaths = [
140 - path.join(ACP_ADAPTERS_CACHE_DIR, 'claude-code-acp.mjs'),
141 - path.join(ACP_ADAPTERS_CACHE_DIR, 'cli.js'),
142 - ...manifest.codex.map(target =>
143 - path.join(ACP_ADAPTERS_CACHE_DIR, stripAcpAdaptersPrefix(target.relativePath))
144 - ),
145 - ];
146 -
147 - for (const requiredPath of requiredPaths) {
148 - if (!(await fileExists(requiredPath))) {
149 - return false;
150 - }
151 - }
152 -
153 - return true;
154 -};
155 -
156 -const fetchRegistryJson = async (
157 - packageName: string,
158 - version: string
159 -): Promise<RegistryVersionManifest> => {
160 - const url = `${REGISTRY_BASE_URL}/${encodeURIComponent(packageName)}/${version}`;
161 - const response = await fetch(url, {
162 - headers: {
163 - accept: 'application/json',
164 - 'user-agent': USER_AGENT,
165 - },
166 - });
167 -
168 - if (!response.ok) {
169 - throw new Error(
170 - `Failed to fetch registry metadata for ${packageName}@${version}: ${response.status}`
171 - );
172 - }
173 -
174 - return (await response.json()) as RegistryVersionManifest;
175 -};
176 -
177 -const downloadTarball = async (url: string, targetPath: string): Promise<void> => {
178 - const response = await fetch(url, {
179 - headers: {
180 - 'user-agent': USER_AGENT,
181 - },
182 - });
183 -
184 - if (!response.ok) {
185 - throw new Error(`Failed to download ${url}: ${response.status}`);
186 - }
187 -
188 - await writeFile(targetPath, new Uint8Array(await response.arrayBuffer()));
189 -};
190 -
191 -const bundleBunRuntimeFile = async ({
192 - entryPath,
193 - outputPath,
194 -}: {
195 - readonly entryPath: string;
196 - readonly outputPath: string;
197 -}): Promise<void> => {
198 - const result = await Bun.build({
199 - entrypoints: [entryPath],
200 - outdir: path.dirname(outputPath),
201 - naming: path.basename(outputPath),
202 - target: 'bun',
203 - format: 'esm',
204 - packages: 'bundle',
205 - sourcemap: 'none',
206 - });
207 -
208 - if (!result.success) {
209 - const details = result.logs
210 - .map(log => log.message)
211 - .filter(message => message.length > 0)
212 - .join('\n');
213 - throw new Error(
214 - details.length > 0
215 - ? `Failed to bundle ${path.basename(outputPath)}:\n${details}`
216 - : `Failed to bundle ${path.basename(outputPath)}.`
217 - );
218 - }
219 -
220 - await chmod(outputPath, 0o755);
221 -};
222 -
223 -const buildClaudeAdapterBundle = async (cacheDir: string): Promise<void> => {
224 - const outputPath = path.join(cacheDir, 'claude-code-acp.mjs');
225 - const entryPath = await resolveClaudeAdapterEntryPath();
226 - await bundleBunRuntimeFile({
227 - entryPath,
228 - outputPath,
229 - });
230 -
231 - const cliOutputPath = path.join(cacheDir, 'cli.js');
232 - await bundleBunRuntimeFile({
233 - entryPath: resolveClaudeAgentSdkCliPath(),
234 - outputPath: cliOutputPath,
235 - });
236 -};
237 -
238 -const extractCodexBinaryFromTarball = async ({
239 - binaryFileName,
240 - integrityByPackage,
241 - packageName,
242 - relativePath,
243 - stageCacheDir,
244 - stageRootDir,
245 - version,
246 -}: {
247 - readonly binaryFileName: string;
248 - readonly integrityByPackage: ReadonlyMap<string, string>;
249 - readonly packageName: string;
250 - readonly relativePath: string;
251 - readonly stageCacheDir: string;
252 - readonly stageRootDir: string;
253 - readonly version: string;
254 -}): Promise<void> => {
255 - // Read before the download so a missing pin fails before any bytes are fetched.
256 - const expectedIntegrity = expectedIntegrityFor(integrityByPackage, packageName, version);
257 -
258 - const metadata = await fetchRegistryJson(packageName, version);
259 - const tarballUrl = metadata.dist?.tarball;
260 - if (!tarballUrl) {
261 - throw new Error(
262 - `Registry metadata for ${packageName}@${version} did not include a tarball URL.`
263 - );
264 - }
265 -
266 - const tempArchivePath = path.join(
267 - stageRootDir,
268 - `${packageName.split('/')[1]?.replaceAll('/', '-') ?? 'package'}-${version}.tgz`
269 - );
270 - const tempExtractDir = path.join(
271 - stageRootDir,
272 - `${path.basename(tempArchivePath, '.tgz')}-extract`
273 - );
274 -
275 - await downloadTarball(tarballUrl, tempArchivePath);
276 -
277 - // Checked against the lockfile rather than the registry's own `dist.integrity`:
278 - // whoever can serve the tarball can serve the metadata that vouches for it.
279 - const archiveBytes = await Bun.file(tempArchivePath).bytes();
280 - await assertBytesMatchIntegrity(archiveBytes, expectedIntegrity, `${packageName}@${version}`);
281 -
282 - await mkdir(tempExtractDir, { recursive: true });
283 - const archive = new Bun.Archive(archiveBytes);
284 - await archive.extract(tempExtractDir);
285 -
286 - const extractedBinaryPath = path.join(tempExtractDir, 'package', 'bin', binaryFileName);
287 - if (!(await fileExists(extractedBinaryPath))) {
288 - throw new Error(
289 - `Codex ACP tarball for ${packageName}@${version} did not contain ${binaryFileName}.`
290 - );
291 - }
292 -
293 - const outputPath = path.join(stageCacheDir, stripAcpAdaptersPrefix(relativePath));
294 - await mkdir(path.dirname(outputPath), { recursive: true });
295 - await copyFile(extractedBinaryPath, outputPath);
296 - await chmod(outputPath, 0o755);
297 -};
298 -
299 -const materializeCodexAdapters = async (
300 - manifest: AcpAdaptersManifest,
301 - stageRootDir: string,
302 - stageCacheDir: string
303 -): Promise<void> => {
304 - const integrityByPackage = await loadLockfileIntegrity(
305 - path.dirname(fileURLToPath(import.meta.url))
306 - );
307 -
308 - await Promise.all(
309 - manifest.codex.map(target =>
310 - extractCodexBinaryFromTarball({
311 - binaryFileName:
312 - RUN_CODEX_ACP_BINARY_TARGETS.find(
313 - candidate => candidate.packageName === target.packageName
314 - )?.binaryFileName ?? 'codex-acp',
315 - integrityByPackage,
316 - packageName: target.packageName,
317 - relativePath: target.relativePath,
318 - stageCacheDir,
319 - stageRootDir,
320 - version: target.version,
321 - })
322 - )
323 - );
324 -};
325 -
326 -/**
327 - * Materializes the ACP adapter cache.
328 - *
329 - * `codexBinaryTargets` narrows which codex-acp binaries are downloaded; release
330 - * builds keep the default (every supported platform), while a build that only
331 - * has to run on the building machine — e.g. the CLI e2e image — passes just its
332 - * own target to avoid downloading ~200MB per foreign platform.
333 - */
334 -export const materializeAcpAdaptersCache = async (
335 - codexBinaryTargets: ReadonlyArray<RunCodexAcpBinaryTarget> = RUN_CODEX_ACP_BINARY_TARGETS
336 -): Promise<string> => {
337 - const manifest = await buildCacheManifest(codexBinaryTargets);
338 - const existingManifest = await readExistingManifest();
339 -
340 - if (
341 - existingManifest &&
342 - JSON.stringify(existingManifest) === JSON.stringify(manifest) &&
343 - (await manifestPathsExist(manifest))
344 - ) {
345 - return ACP_ADAPTERS_CACHE_DIR;
346 - }
347 -
348 - await mkdir(GENERATED_ROOT_DIR, { recursive: true });
349 -
350 - const stageRootDir = await mkdtemp(path.join(GENERATED_ROOT_DIR, '.acp-adapters-'));
351 - const stageCacheDir = path.join(stageRootDir, 'acp-adapters');
352 -
353 - try {
354 - await mkdir(stageCacheDir, { recursive: true });
355 - await buildClaudeAdapterBundle(stageCacheDir);
356 - await materializeCodexAdapters(manifest, stageRootDir, stageCacheDir);
357 -
358 - await rm(ACP_ADAPTERS_CACHE_DIR, { force: true, recursive: true });
359 - await rename(stageCacheDir, ACP_ADAPTERS_CACHE_DIR);
360 - await writeFile(ACP_ADAPTERS_MANIFEST_PATH, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
361 - } finally {
362 - await rm(stageRootDir, { force: true, recursive: true });
363 - }
364 -
365 - return ACP_ADAPTERS_CACHE_DIR;
366 -};
ts/packages/cli/scripts/_release-artifacts.ts
+23 -82
@@ -1,66 +1,21 @@
1 /**
2 - * Release artifact identity: which platform/arch each published archive targets,
3 - * and which companion assets belong inside it.
2 + * Published artifact names and the companion paths included in every archive.
3 *
4 * Deliberately free of Bun-only imports so the packaging rules stay unit-testable
5 * under Node.
6 */
7
9 -import { Data, Option, Result } from 'effect';
10 -import {
11 - RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,
12 - runCompanionStaticAssetRelativePathsFor,
13 -} from '../src/services/run-companion-modules';
14 -
15 -export type ReleaseArtifactTarget = {
16 - readonly artifactName: string;
17 - readonly platform: NodeJS.Platform;
18 - readonly arch: string;
19 -};
20 -
21 -/**
22 - * Every published binary artifact, mapped to the Node `platform`/`arch` pair its
23 - * archive runs on. Artifact names use the `aarch64` spelling; Node calls the same
24 - * architecture `arm64`.
25 - */
26 -export const RELEASE_ARTIFACT_TARGETS: ReadonlyArray<ReleaseArtifactTarget> = [
27 - { artifactName: 'composio-darwin-aarch64', platform: 'darwin', arch: 'arm64' },
28 - { artifactName: 'composio-darwin-x64', platform: 'darwin', arch: 'x64' },
29 - { artifactName: 'composio-linux-x64', platform: 'linux', arch: 'x64' },
30 - { artifactName: 'composio-linux-aarch64', platform: 'linux', arch: 'arm64' },
31 -];
8 +import { RUN_COMPANION_LEGACY_PLACEHOLDER_RELATIVE_PATHS } from '../src/services/run-companion-modules';
9
10 /**
11 * Known binary artifact names (without extension).
12 */
36 -export const ARTIFACT_NAMES: ReadonlyArray<string> = RELEASE_ARTIFACT_TARGETS.map(
37 - target => target.artifactName
38 -);
39 -
40 -export class UnknownReleaseArtifactError extends Data.TaggedError(
41 - 'scripts/UnknownReleaseArtifactError'
42 -)<{
43 - readonly artifactName: string;
44 -}> {
45 - get message(): string {
46 - return `Unknown release artifact ${this.artifactName}. Expected one of: ${ARTIFACT_NAMES.join(', ')}.`;
47 - }
48 -}
49 -
50 -/**
51 - * Resolve an artifact name to its platform/arch. The mapping is total over
52 - * {@link RELEASE_ARTIFACT_TARGETS}; anything else fails instead of silently
53 - * producing an archive with no platform-specific assets.
54 - */
55 -export const releaseArtifactTargetFor = (
56 - artifactName: string
57 -): Result.Result<ReleaseArtifactTarget, UnknownReleaseArtifactError> =>
58 - Result.fromOption(
59 - Option.fromUndefinedOr(
60 - RELEASE_ARTIFACT_TARGETS.find(target => target.artifactName === artifactName)
61 - ),
62 - () => new UnknownReleaseArtifactError({ artifactName })
63 - );
13 +export const ARTIFACT_NAMES: ReadonlyArray<string> = [
14 + 'composio-darwin-aarch64',
15 + 'composio-darwin-x64',
16 + 'composio-linux-x64',
17 + 'composio-linux-aarch64',
18 +];
19
20 export type ArchiveCompanionEntryKind = 'copy' | 'placeholder';
21
@@ -70,39 +25,25 @@ export type ArchiveCompanionEntry = {
25 };
26
27 /**
73 - * Decide how each companion asset enters one archive.
74 - *
75 - * An archive already carries a platform-specific `composio` binary, so only one
76 - * of the four codex-acp binaries inside it can ever execute. The other three are
77 - * ~651 MB that every machine unpacking this archive downloads, stores, and can
78 - * never run.
28 + * Decide how each companion path enters an archive.
29 *
80 - * They cannot simply be dropped. A CLI released before 2026-08-18 verifies a
81 - * downloaded upgrade package against all four codex-acp paths and refuses to
30 + * The live companions are copied. The legacy paths are written as empty files:
31 + * the sub-agent helper they served is gone, but every stable CLI from 0.2.12 to
32 + * 0.4.2 verifies a downloaded upgrade package against those paths and refuses to
33 * install one that is missing any of them, so omitting them breaks
83 - * `composio upgrade` for every client already in the field. An empty placeholder
84 - * satisfies that existence check at zero bytes, and no host ever executes a
85 - * foreign codex-acp binary, so the placeholder is never read.
34 + * `composio upgrade` for every client already in the field. That check looks at
35 + * existence only, and an empty wrapper imports nothing, so a placeholder
36 + * satisfies it at zero bytes and is never read.
37 *
38 * Once no supported client performs that check, placeholders can become plain
39 * omissions.
40 */
90 -export const archiveCompanionEntries = ({
91 - allRelativePaths,
92 - target,
93 -}: {
94 - readonly allRelativePaths: ReadonlyArray<string>;
95 - readonly target: ReleaseArtifactTarget;
96 -}): ReadonlyArray<ArchiveCompanionEntry> => {
97 - const executableHere = new Set(runCompanionStaticAssetRelativePathsFor(target));
98 - const foreignCodexPaths = new Set(
99 - RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS.filter(
100 - relativePath => !executableHere.has(relativePath)
101 - )
102 - );
103 -
104 - return allRelativePaths.map(relativePath => ({
41 +export const archiveCompanionEntries = (
42 + liveRelativePaths: ReadonlyArray<string>
43 +): ReadonlyArray<ArchiveCompanionEntry> => [
44 + ...liveRelativePaths.map(relativePath => ({ relativePath, kind: 'copy' as const })),
45 + ...RUN_COMPANION_LEGACY_PLACEHOLDER_RELATIVE_PATHS.map(relativePath => ({
46 relativePath,
106 - kind: foreignCodexPaths.has(relativePath) ? ('placeholder' as const) : ('copy' as const),
107 - }));
108 -};
47 + kind: 'placeholder' as const,
48 + })),
49 +];
ts/packages/cli/scripts/_shared.ts
+9 -65
@@ -1,16 +1,10 @@
1 import { builtinModules } from 'node:module';
2 -import { chmod, copyFile, mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises';
2 +import { mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises';
3 import * as path from 'node:path';
4 import process from 'node:process';
5 import { Effect } from 'effect';
6 -import {
7 - codexAcpBinaryTargetFor,
8 - RUN_CODEX_ACP_BINARY_TARGETS,
9 - RUN_COMPANION_MODULE_BASENAMES,
10 - type RunCodexAcpBinaryTarget,
11 -} from '../src/services/run-companion-modules';
6 +import { RUN_COMPANION_MODULE_BASENAMES } from '../src/services/run-companion-modules';
7 import { buildCliReleaseVersionDefineArgs } from '../src/utils/cli-release-version';
13 -import { materializeAcpAdaptersCache } from './_acp-adapters';
8
9 export { teardown } from './_teardown';
10
@@ -31,44 +25,6 @@ const exportStatementPattern =
25 /(?:^|[;\n])\s*export\s+(?:\*\s+from\s+|\{[^}\n]+\}\s+from\s+)["']([^"']+)["']/gm;
26 const runtimeImportCallPattern = /(?:^|[^\w$.])(?:__require|require|import)\(\s*["']([^"']+)["']/g;
27
34 -const copyDirectoryRecursive = async (sourceDir: string, targetDir: string): Promise<void> => {
35 - await mkdir(targetDir, { recursive: true });
36 -
37 - for (const entry of await readdir(sourceDir, { withFileTypes: true })) {
38 - const sourcePath = path.join(sourceDir, entry.name);
39 - const targetPath = path.join(targetDir, entry.name);
40 -
41 - if (entry.isDirectory()) {
42 - await copyDirectoryRecursive(sourcePath, targetPath);
43 - continue;
44 - }
45 -
46 - await copyFile(sourcePath, targetPath);
47 - const mode = (await stat(sourcePath)).mode & 0o777;
48 - await chmod(targetPath, mode || 0o755);
49 - }
50 -};
51 -
52 -const copyBundledAcpAdapters = async (
53 - outputDir: string,
54 - codexBinaryTargets: ReadonlyArray<RunCodexAcpBinaryTarget>
55 -): Promise<void> => {
56 - const acpAdaptersCacheDir = await materializeAcpAdaptersCache(codexBinaryTargets);
57 - const acpOutputDir = path.join(outputDir, 'acp-adapters');
58 - await rm(acpOutputDir, { force: true, recursive: true });
59 - await copyDirectoryRecursive(acpAdaptersCacheDir, acpOutputDir);
60 -};
61 -
62 -// The codex-acp binary the building machine can actually execute. Unsupported
63 -// hosts get an empty list, matching the host requirement set the CLI checks.
64 -export const hostCodexAcpBinaryTargets = (): ReadonlyArray<RunCodexAcpBinaryTarget> => {
65 - const hostTarget = codexAcpBinaryTargetFor({
66 - platform: process.platform,
67 - arch: process.arch,
68 - });
69 - return hostTarget ? [hostTarget] : [];
70 -};
71 -
28 // Kept out of --env: Bun honors only the last --env, which would clobber DEBUG_OVERRIDE_*.
29 export const posthogBakeArgs = (): ReadonlyArray<string> => {
30 const key = process.env.COMPOSIO_POSTHOG_PROJECT_API_KEY?.trim();
@@ -219,16 +175,12 @@ const collectRuntimeFiles = async (rootDir: string): Promise<ReadonlyArray<strin
175 }
176 }
177
222 - for (const relativeDir of ['services', 'acp-adapters']) {
223 - const absoluteDir = path.join(rootDir, relativeDir);
224 - const exists = await stat(absoluteDir)
225 - .then(stats => stats.isDirectory())
226 - .catch(() => false);
227 - if (!exists) {
228 - continue;
229 - }
230 -
231 - for (const filePath of await collectJavaScriptFiles(absoluteDir)) {
178 + const servicesDir = path.join(rootDir, 'services');
179 + const exists = await stat(servicesDir)
180 + .then(stats => stats.isDirectory())
181 + .catch(() => false);
182 + if (exists) {
183 + for (const filePath of await collectJavaScriptFiles(servicesDir)) {
184 collected.add(filePath);
185 }
186 }
@@ -388,12 +340,7 @@ const assertExecutableExcludesCompanionModules = async (): Promise<void> => {
340 }
341 };
342
391 -export const buildCompanionModules = (
392 - outputDir: string,
393 - options: {
394 - readonly codexBinaryTargets?: ReadonlyArray<RunCodexAcpBinaryTarget>;
395 - } = {}
396 -) =>
343 +export const buildCompanionModules = (outputDir: string) =>
344 Effect.gen(function* () {
345 yield* Effect.tryPromise(() => mkdir(outputDir, { recursive: true }));
346
@@ -405,9 +352,6 @@ export const buildCompanionModules = (
352 yield* Effect.tryPromise(() => writeFile(wrapperPath, wrapperSource, 'utf8'));
353 }
354
408 - yield* Effect.tryPromise(() =>
409 - copyBundledAcpAdapters(outputDir, options.codexBinaryTargets ?? RUN_CODEX_ACP_BINARY_TARGETS)
410 - );
355 yield* Effect.tryPromise(() => assertBundledRuntimeFiles(outputDir));
356 yield* Effect.tryPromise(() => assertExecutableExcludesCompanionModules());
357 });
ts/packages/cli/scripts/_tarball-integrity.ts deleted
-173
@@ -1,173 +0,0 @@
1 -import { readFile, stat } from 'node:fs/promises';
2 -import * as path from 'node:path';
3 -
4 -/**
5 - * Integrity verification for tarballs this repo downloads outside of pnpm.
6 - *
7 - * `pnpm install --frozen-lockfile` verifies every dependency it installs
8 - * against the `integrity` recorded in `pnpm-lock.yaml`. A tarball fetched by a
9 - * build script gets none of that: the script asks the registry where the bytes
10 - * live and writes whatever comes back. The codex-acp binaries are fetched that
11 - * way — they must be present for all four platforms on a single-platform runner,
12 - * which pnpm will not install — and they are then packaged, executable, inside
13 - * the published CLI release archive.
14 - *
15 - * The lockfile already carries the expected hash for exactly those packages, so
16 - * the fix is to use it. Verification is fail-closed: a package with no lockfile
17 - * entry, or a lockfile that cannot be found, aborts the build rather than
18 - * shipping unverified bytes.
19 - */
20 -
21 -const LOCKFILE_NAME = 'pnpm-lock.yaml';
22 -
23 -/** ` '@scope/name@1.2.3':` or ` name@1.2.3:` at the top level of `packages:`. */
24 -const PACKAGE_KEY_PATTERN = /^ {2}(?:'(.+)'|([^\s'][^\s]*?)):$/;
25 -
26 -/** `integrity: sha512-…` inside a `resolution: { … }` mapping. */
27 -const INTEGRITY_PATTERN = /^\s+resolution:\s*\{[^}]*\bintegrity:\s*(sha\d{3}-[A-Za-z0-9+/=]+)/;
28 -
29 -export class TarballIntegrityError extends Error {
30 - constructor(message: string) {
31 - super(message);
32 - this.name = 'TarballIntegrityError';
33 - }
34 -}
35 -
36 -/**
37 - * Maps every `name@version` in a pnpm lockfile to its recorded integrity hash.
38 - *
39 - * Deliberately line-based rather than a YAML parse: the lockfile is large, the
40 - * shape being read is two adjacent lines, and this keeps the build script free
41 - * of a YAML dependency. Entries whose `resolution` carries no `integrity` — git
42 - * and direct-tarball resolutions — are skipped, so asking for one fails closed
43 - * in `expectedIntegrityFor` instead of silently passing.
44 - */
45 -export const parseLockfileIntegrity = (lockfileText: string): ReadonlyMap<string, string> => {
46 - const integrityByPackage = new Map<string, string>();
47 - const lines = lockfileText.split('\n');
48 -
49 - for (let index = 0; index < lines.length - 1; index += 1) {
50 - const keyMatch = PACKAGE_KEY_PATTERN.exec(lines[index] ?? '');
51 - if (!keyMatch) {
52 - continue;
53 - }
54 -
55 - const integrityMatch = INTEGRITY_PATTERN.exec(lines[index + 1] ?? '');
56 - if (!integrityMatch) {
57 - continue;
58 - }
59 -
60 - const packageKey = keyMatch[1] ?? keyMatch[2];
61 - const integrity = integrityMatch[1];
62 - if (packageKey && integrity && !integrityByPackage.has(packageKey)) {
63 - integrityByPackage.set(packageKey, integrity);
64 - }
65 - }
66 -
67 - return integrityByPackage;
68 -};
69 -
70 -/**
71 - * The integrity hash the lockfile pins for `packageName@version`.
72 - *
73 - * Throws when the package is absent: a build script that downloads something
74 - * the lockfile never resolved has no pinned bytes to check against, which is
75 - * the situation this module exists to refuse.
76 - */
77 -export const expectedIntegrityFor = (
78 - integrityByPackage: ReadonlyMap<string, string>,
79 - packageName: string,
80 - version: string
81 -): string => {
82 - const packageKey = `${packageName}@${version}`;
83 - const integrity = integrityByPackage.get(packageKey);
84 -
85 - if (!integrity) {
86 - throw new TarballIntegrityError(
87 - `${packageKey} has no integrity hash in ${LOCKFILE_NAME}; refusing to package unverified bytes.`
88 - );
89 - }
90 -
91 - return integrity;
92 -};
93 -
94 -/** Lockfile hash prefix to the Web Crypto algorithm name that computes it. */
95 -const SUBTLE_ALGORITHM_BY_PREFIX: Readonly<Record<string, string>> = {
96 - sha1: 'SHA-1',
97 - sha256: 'SHA-256',
98 - sha384: 'SHA-384',
99 - sha512: 'SHA-512',
100 -};
101 -
102 -/** Subresource-integrity string for `bytes` under the given lockfile prefix. */
103 -const computeIntegrity = async (bytes: Uint8Array, prefix: string): Promise<string> => {
104 - const digest = await crypto.subtle.digest(
105 - SUBTLE_ALGORITHM_BY_PREFIX[prefix] as string,
106 - bytes as BufferSource
107 - );
108 - const base64 = btoa(String.fromCharCode(...new Uint8Array(digest)));
109 - return `${prefix}-${base64}`;
110 -};
111 -
112 -/**
113 - * Throws unless `bytes` hashes to `expectedIntegrity`.
114 - *
115 - * The algorithm is read from the expected value so a lockfile that moves off
116 - * sha512 keeps working, and an unrecognised one fails loudly here rather than
117 - * comparing two strings that could never match.
118 - */
119 -export const assertBytesMatchIntegrity = async (
120 - bytes: Uint8Array,
121 - expectedIntegrity: string,
122 - label: string
123 -): Promise<void> => {
124 - const prefix = expectedIntegrity.split('-')[0] ?? '';
125 - if (!(prefix in SUBTLE_ALGORITHM_BY_PREFIX)) {
126 - throw new TarballIntegrityError(
127 - `Unsupported integrity algorithm for ${label}: "${expectedIntegrity}".`
128 - );
129 - }
130 -
131 - const actualIntegrity = await computeIntegrity(bytes, prefix);
132 -
133 - if (actualIntegrity !== expectedIntegrity) {
134 - throw new TarballIntegrityError(
135 - `Integrity mismatch for ${label}.\n Expected: ${expectedIntegrity}\n Actual: ${actualIntegrity}`
136 - );
137 - }
138 -};
139 -
140 -/**
141 - * Nearest `pnpm-lock.yaml` at or above `startDir`.
142 - *
143 - * Walks up rather than resolving a fixed `../../..` so the script keeps working
144 - * from whichever directory a build or test invokes it in.
145 - */
146 -export const findLockfilePath = async (startDir: string): Promise<string> => {
147 - let directory = path.resolve(startDir);
148 -
149 - for (;;) {
150 - const candidate = path.join(directory, LOCKFILE_NAME);
151 - const found = await stat(candidate)
152 - .then(stats => stats.isFile())
153 - .catch(() => false);
154 -
155 - if (found) {
156 - return candidate;
157 - }
158 -
159 - const parent = path.dirname(directory);
160 - if (parent === directory) {
161 - throw new TarballIntegrityError(
162 - `Could not find ${LOCKFILE_NAME} at or above ${startDir}; cannot verify downloaded tarballs.`
163 - );
164 - }
165 - directory = parent;
166 - }
167 -};
168 -
169 -/** Lockfile integrity map for the workspace containing `startDir`. */
170 -export const loadLockfileIntegrity = async (
171 - startDir: string
172 -): Promise<ReadonlyMap<string, string>> =>
173 - parseLockfileIntegrity(await readFile(await findLockfilePath(startDir), 'utf8'));
ts/packages/cli/scripts/build-companion-modules.ts
+8 -20
@@ -3,26 +3,23 @@
3 /**
4 * Build the `composio run` companion modules next to an already-compiled binary.
5 *
6 - * `scripts/build-binary.ts` does this as part of a full release build, shipping
7 - * every platform's codex-acp binary. This entry point exists for builds whose
8 - * output only ever runs on the building machine — the CLI e2e image — where
9 - * downloading three foreign codex-acp binaries costs ~600MB and minutes of build
10 - * time for files that machine can never execute.
6 + * `scripts/build-binary.ts` does this as part of a full release build. This
7 + * entry point exists for builds that compile the binary themselves, such as the
8 + * CLI e2e image.
9 *
12 - * Usage: `bun scripts/build-companion-modules.ts <OUTPUT_DIR> [--host-only]`
10 + * Usage: `bun scripts/build-companion-modules.ts <OUTPUT_DIR>`
11 */
12
13 import process from 'node:process';
14 import { Config, ConfigProvider, Console, Effect, Logger, Layer, References } from 'effect';
15 import * as BunServices from '@effect/platform-bun/BunServices';
16 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
19 -import { buildCompanionModules, hostCodexAcpBinaryTargets, teardown } from './_shared';
17 +import { buildCompanionModules, teardown } from './_shared';
18 import { BinaryBuildError } from './build-error';
19
20 export function buildCompanionModulesCommand() {
21 return Effect.gen(function* () {
24 - const args = process.argv.slice(2);
25 - const outputDir = args.find(arg => !arg.startsWith('--'));
22 + const outputDir = process.argv[2];
23
24 if (!outputDir) {
25 return yield* new BinaryBuildError({
@@ -31,18 +28,9 @@ export function buildCompanionModulesCommand() {
28 });
29 }
30
34 - const hostOnly = args.includes('--host-only');
35 - const codexBinaryTargets = hostOnly ? hostCodexAcpBinaryTargets() : undefined;
31 + yield* buildCompanionModules(outputDir);
32
37 - yield* buildCompanionModules(outputDir, { codexBinaryTargets });
38 -
39 - yield* Console.log(
40 - `Companion modules built in ${outputDir}${
41 - hostOnly
42 - ? ` (codex-acp: ${codexBinaryTargets?.map(target => target.relativePath).join(', ') || 'none for this host'})`
43 - : ''
44 - }`
45 - );
33 + yield* Console.log(`Companion modules built in ${outputDir}`);
34 });
35 }
36
ts/packages/cli/scripts/package-binaries.ts
+12 -25
@@ -22,15 +22,8 @@ import { teardown } from './_shared';
22 import { $ } from 'bun';
23 import { readdir, stat, writeFile } from 'node:fs/promises';
24 import path from 'node:path';
25 -import {
26 - collectExpectedRunCompanionAssetRelativePaths,
27 - RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,
28 -} from '../src/services/run-companion-modules';
29 -import {
30 - archiveCompanionEntries,
31 - ARTIFACT_NAMES,
32 - releaseArtifactTargetFor,
33 -} from './_release-artifacts';
25 +import { collectExpectedRunCompanionAssetRelativePaths } from '../src/services/run-companion-modules';
26 +import { archiveCompanionEntries, ARTIFACT_NAMES } from './_release-artifacts';
27
28 const BINARIES_DIR = './dist/binaries';
29 const COMPANIONS_DIR = path.join(BINARIES_DIR, 'companions');
@@ -48,13 +41,11 @@ export function packageBinaries() {
41 return;
42 }
43
51 - // One packaging host produces all four archives, so `COMPANIONS_DIR` must hold
52 - // every platform's codex-acp binary before packaging starts.
53 - const allCompanionRelativePaths = yield* collectExpectedRunCompanionAssetRelativePaths(
54 - COMPANIONS_DIR,
55 - { staticAssetRelativePaths: RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS }
56 - );
57 - for (const relativePath of allCompanionRelativePaths) {
44 + // Only the live companions come from `COMPANIONS_DIR`. The legacy placeholders
45 + // are written straight into each archive and exist nowhere else.
46 + const liveCompanionRelativePaths =
47 + yield* collectExpectedRunCompanionAssetRelativePaths(COMPANIONS_DIR);
48 + for (const relativePath of liveCompanionRelativePaths) {
49 const companionPath = path.join(COMPANIONS_DIR, relativePath);
50 const exists = yield* Effect.tryPromise(() => Bun.file(companionPath).exists());
51 if (!exists) {
@@ -68,16 +59,10 @@ export function packageBinaries() {
59
60 yield* Console.log(`Packaging ${binaries.length} binaries...`);
61
71 - for (const binary of binaries) {
72 - // Every archive names all four codex-acp paths, but carries real bytes
73 - // only for the one its own `composio` binary can execute. See
74 - // `archiveCompanionEntries` for why the other three are present but empty.
75 - const target = yield* Effect.fromResult(releaseArtifactTargetFor(binary));
76 - const companionEntries = archiveCompanionEntries({
77 - allRelativePaths: allCompanionRelativePaths,
78 - target,
79 - });
62 + // See `archiveCompanionEntries` for why the legacy paths are present but empty.
63 + const companionEntries = archiveCompanionEntries(liveCompanionRelativePaths);
64
65 + for (const binary of binaries) {
66 const binaryPath = path.join(BINARIES_DIR, binary);
67 const zipPath = path.join(BINARIES_DIR, `${binary}.zip`);
68 const absoluteZipPath = path.resolve(zipPath);
@@ -87,6 +72,8 @@ export function packageBinaries() {
72 const nestedDir = path.join(tempDir, binary);
73
74 yield* Effect.tryPromise(async () => {
75 + await $`rm -f ${zipPath}`.quiet();
76 + await $`rm -rf ${tempDir}`.quiet();
77 await $`mkdir -p ${nestedDir}`.quiet();
78 await $`cp ${binaryPath} ${nestedDir}/composio`.quiet();
79 for (const { relativePath, kind } of companionEntries) {
ts/packages/cli/skills-src/composio-cli/index.ts
+2 -6
@@ -196,11 +196,11 @@ const commands: SkillCommand[] = [
196 },
197 {
198 id: 'run',
199 - title: '`run` - Scripting, LLMs, and Programmatic Workflows',
199 + title: '`run` - Scripting and Programmatic Workflows',
200 summary:
201 'For programmatic calls, loops, output plumbing, or anything beyond a single tool call, prefer `composio run`.',
202 intro: [
203 - '`composio run` executes an inline ESM JavaScript/TypeScript snippet with authenticated `execute()`, `search()`, `proxy()`, and the experimental `experimental_subAgent()` helper pre-injected. No SDK setup required.',
203 + '`composio run` executes an inline ESM JavaScript/TypeScript snippet with authenticated `execute()`, `search()`, and `proxy()` pre-injected. No SDK setup required.',
204 ],
205 examples: [
206 {
@@ -211,10 +211,6 @@ const commands: SkillCommand[] = [
211 description: 'Fan out with Promise.all',
212 code: 'composio run \'\n const [me, emails] = await Promise.all([\n execute("GITHUB_GET_THE_AUTHENTICATED_USER"),\n execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),\n ]);\n console.log({ login: me.data.login, emailCount: emails.data.messages?.length });\n\'',
213 },
214 - {
215 - description: 'Feed tool output into an LLM and get structured JSON back',
216 - code: 'composio run --logs-off \'\n const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 5 });\n const brief = await experimental_subAgent(\n `Summarize these emails and count them.\\n\\n${emails.prompt()}`,\n { schema: z.object({ summary: z.string(), count: z.number() }) }\n );\n console.log(brief.structuredOutput);\n\'',
217 - },
214 ],
215 notes: [
216 'Use top-level `execute --parallel` instead when the user only needs a few independent tool calls and does not need script logic.',
ts/packages/cli/skills-src/composio-cli/references/power-user-examples.ts
+1 -28
@@ -4,7 +4,7 @@ export const powerUserExamplesReference: ReferenceDocument = {
4 slug: 'power-user-examples',
5 title: 'Power-User Examples',
6 intro: [
7 - 'Load this file when the user needs more than one top-level command, wants to script workflows, or wants to use `experimental_subAgent()` inside `composio run`.',
7 + 'Load this file when the user needs more than one top-level command or wants to script workflows with `composio run`.',
8 ],
9 sections: [
10 {
@@ -80,32 +80,6 @@ export const powerUserExamplesReference: ReferenceDocument = {
80 },
81 ],
82 },
83 - {
84 - title: 'Use `experimental_subAgent()` With `z` And `result.prompt()`',
85 - body: [
86 - 'Turn a tool result into structured output:',
87 - 'Use `result.prompt()` when the helper result is too noisy for a raw object dump but you still want to feed it into `experimental_subAgent()`.',
88 - ],
89 - commands: [
90 - {
91 - code: `composio run --logs-off '
92 - const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 2 });
93 -
94 - const brief = await experimental_subAgent(
95 - \`Return only valid JSON matching the schema. Summarize these emails in one sentence and report how many items were returned.\\n\\n\${emails.prompt()}\`,
96 - {
97 - schema: z.object({
98 - summary: z.string(),
99 - count: z.number(),
100 - }),
101 - }
102 - );
103 -
104 - console.log(brief.structuredOutput);
105 -'`,
106 - },
107 - ],
108 - },
83 {
84 title: 'Use `proxy()` For Raw API Access',
85 body: [
@@ -147,7 +121,6 @@ export const powerUserExamplesReference: ReferenceDocument = {
121 body: [
122 '- Use `--dry-run` to preview every `execute()` call in the script.',
123 '- Use `--debug` to see helper steps while the script runs.',
150 - '- Use `--logs-off` when `experimental_subAgent()` streaming logs are too noisy for the task.',
124 'Example:',
125 ],
126 commands: [
ts/packages/cli/skills-src/composio-cli/references/troubleshooting.ts
+1 -1
@@ -88,7 +88,7 @@ cat payload.json | composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-che
88 '- the user wants to run multiple unrelated tools in one step',
89 '- the user is about to write a script only to execute a few independent calls',
90 'Fix:',
91 - 'Escalate to `composio run` only when the user needs control flow, loops, `Promise.all`, `search()` inside a script, `proxy()`, or `experimental_subAgent()`.',
91 + 'Escalate to `composio run` only when the user needs control flow, loops, `Promise.all`, `search()` inside a script, or `proxy()`.',
92 ],
93 commands: [
94 {
ts/packages/cli/src/commands/argv-compat.ts
+11 -1
@@ -1,5 +1,5 @@
1 import { Array as Arr } from 'effect';
2 -import { RUN_KNOWN_BOOLEAN_FLAGS, RUN_KNOWN_VALUE_FLAGS } from './run.cmd';
2 +import { RUN_FILE_FLAGS, RUN_KNOWN_BOOLEAN_FLAGS, RUN_KNOWN_VALUE_FLAGS } from './run.cmd';
3 import { rootCommandIndex } from 'src/utils/cli-args';
4
5 export const normalizeListenStreamFlag = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
@@ -22,18 +22,27 @@ export const normalizeListenStreamFlag = (argv: ReadonlyArray<string>): Readonly
22 );
23 };
24
25 +// A token shaped like a lone option (`--name`, `--name=value`, `-n`), as opposed to source code.
26 +const FLAG_SHAPED_TOKEN = /^--?[A-Za-z][A-Za-z0-9_-]*(=|$)/;
27 +
28 // Preserve the legacy undelimited script syntax by inserting Effect's native `--`
29 // before the script tail. The framework then parses every operand itself.
30 +//
31 +// Without `--file` the first operand is inline source. An unknown option in that position is
32 +// left ahead of the boundary so the framework rejects it by name instead of running it as code.
33 +// Source that really starts that way needs an explicit `--`.
34 export const normalizeRunScriptArgs = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
35 const commandIndex = 2 + rootCommandIndex(argv.slice(2));
36 if (argv[commandIndex] !== 'run') return argv;
37
38 let index = commandIndex + 1;
39 + let hasFile = false;
40 while (index < argv.length) {
41 const token = argv[index];
42 const equalsIndex = token.indexOf('=');
43 const flagName = equalsIndex === -1 ? token : token.slice(0, equalsIndex);
44 if (RUN_KNOWN_VALUE_FLAGS.has(flagName)) {
45 + hasFile ||= RUN_FILE_FLAGS.has(flagName);
46 index += equalsIndex === -1 ? 2 : 1;
47 } else if (RUN_KNOWN_BOOLEAN_FLAGS.has(flagName)) {
48 index += 1;
@@ -42,6 +51,7 @@ export const normalizeRunScriptArgs = (argv: ReadonlyArray<string>): ReadonlyArr
51 }
52 }
53 if (index >= argv.length) return argv;
54 + if (!hasFile && FLAG_SHAPED_TOKEN.test(argv[index])) return argv;
55
56 const tail = argv.slice(index);
57 // The first user delimiter marks the script boundary; subsequent delimiters
ts/packages/cli/src/commands/run.cmd.ts
+6 -80
@@ -6,7 +6,6 @@ import { ChildProcess, ChildProcessSpawner } from 'effect/unstable/process';
6 import { Data, Deferred, Duration, Effect, MutableRef, Option, Result } from 'effect';
7 import { APP_VERSION } from 'src/constants';
8 import { loadGenerationRuntime } from 'src/effects/generation-runtime';
9 -import { APP_CONFIG, UNPREFIXED_CONFIG } from 'src/effects/app-config';
9 import { resolveCommandProject } from 'src/services/command-project';
10 import { type RunHelperContext } from 'src/services/run-helpers-runtime';
11 import { warmToolInputDefinitions } from 'src/services/tool-input-validation';
@@ -14,12 +13,10 @@ import { ComposioUserContext } from 'src/services/user-context';
13 import {
14 CLI_DEBUG_FLAG_NAMES,
15 debugFlagsToChildEnv,
17 - isAcpOnlyEnabled,
16 isPerfDebugEnabled,
17 isTelemetryDebugEnabled,
18 isToolDebugEnabled,
19 } from 'src/services/runtime-flags';
22 -import { detectMasterFromHost } from 'src/services/master-detector';
20 import { cliInvocationContext, CliRunId } from 'src/services/runtime-cli-context';
21 import {
22 repairMissingInstalledRunCompanionModules,
@@ -29,17 +26,13 @@ import {
26 appendCliSessionHistory,
27 resolveCliSessionArtifacts,
28 } from 'src/services/cli-session-artifacts';
32 -import { USER_COMPOSIO_DIR } from 'src/constants';
29 import { TerminalUI } from 'src/services/terminal-ui';
34 -import { loadHostConfig } from 'src/services/config';
35 -import { resolveCliConfigPath } from 'src/services/cli-user-config';
30 import { NodeOs } from 'src/services/node-os';
31
32 const RUN_FLAG_NAMES = {
33 file: 'file',
34 dryRun: 'dry-run',
35 debug: 'debug',
42 - logsOff: 'logs-off',
36 skipConnectionCheck: 'skip-connection-check',
37 skipToolParamsCheck: 'skip-tool-params-check',
38 skipChecks: 'skip-checks',
@@ -59,10 +52,6 @@ const debug = Flag.Boolean(RUN_FLAG_NAMES.debug).pipe(
52 Flag.withDescription('Log helper steps while the script runs'),
53 Flag.withDefault(false)
54 );
62 -const logsOff = Flag.Boolean(RUN_FLAG_NAMES.logsOff).pipe(
63 - Flag.withDescription('Hide helper streaming logs; keep them only in the run log file.'),
64 - Flag.withDefault(false)
65 -);
55 const skipConnectionCheck = Flag.Boolean(RUN_FLAG_NAMES.skipConnectionCheck).pipe(
56 Flag.withDescription('Skip the connected-account check'),
57 Flag.withDefault(false)
@@ -80,14 +69,14 @@ const runFlags = {
69 file,
70 dryRun,
71 debug,
83 - logsOff,
72 skipConnectionCheck,
73 skipToolParamsCheck,
74 skipChecks,
75 };
76
77 /** Share names with the passthrough adapter; the framework owns parsing the flag values. */
90 -export const RUN_KNOWN_VALUE_FLAGS = new Set([`--${RUN_FLAG_NAMES.file}`, '-f', '--log-level']);
78 +export const RUN_FILE_FLAGS = new Set([`--${RUN_FLAG_NAMES.file}`, '-f']);
79 +export const RUN_KNOWN_VALUE_FLAGS = new Set([...RUN_FILE_FLAGS, '--log-level']);
80 export const RUN_KNOWN_BOOLEAN_FLAGS = new Set([
81 ...Object.values(RUN_FLAG_NAMES)
82 .filter(name => name !== RUN_FLAG_NAMES.file)
@@ -192,28 +181,11 @@ const createRunHelpersPreloadFile = (
181 ? context.runOutputDir
182 : yield* fs.makeTempDirectory({ directory: os.tmpdir, prefix: 'composio-run-artifacts-' });
183 const runLogFilePath = path.join(runOutputDir, 'run.log');
195 - const readAccessRoots = [
196 - ...new Set(
197 - [
198 - ...(Array.isArray(context.readAccessRoots) ? context.readAccessRoots : []),
199 - runOutputDir,
200 - ].map(value => path.resolve(value))
201 - ),
202 - ];
184 yield* fs.makeDirectory(runOutputDir, { recursive: true });
185 yield* fs.writeFileString(runLogFilePath, '');
186 yield* fs.writeFileString(
187 preloadPath,
207 - buildRunHelpersSource(
208 - cliPrefix,
209 - {
210 - ...context,
211 - runOutputDir,
212 - runLogFilePath,
213 - readAccessRoots,
214 - },
215 - moduleUrls
216 - )
188 + buildRunHelpersSource(cliPrefix, { ...context, runOutputDir, runLogFilePath }, moduleUrls)
189 );
190 return { directory, preloadPath, runOutputDir, runLogFilePath };
191 });
@@ -293,29 +265,14 @@ export const buildRunCommand = ({
265
266 const resolveRunHelperContext = () =>
267 Effect.gen(function* () {
296 - const path = yield* Path.Path;
297 - const os = yield* NodeOs;
268 const userContext = yield* ComposioUserContext;
269 const apiKey = Option.getOrUndefined(userContext.data.apiKey);
270 const orgId = Option.getOrUndefined(userContext.data.orgId);
301 - const defaultComposioDir = path.join(os.homedir, USER_COMPOSIO_DIR);
302 - // Honors the same COMPOSIO_CACHE_DIR-then-CACHE_DIR precedence the spawned
303 - // run-helpers child applies when locating its cache, so the sandbox read
304 - // roots below always include the directory the child actually uses.
305 - const composioCacheDir = yield* APP_CONFIG.CACHE_DIR;
306 - const hostCacheDir = yield* loadHostConfig(UNPREFIXED_CONFIG.CACHE_DIR);
307 - const configuredCacheDir = composioCacheDir || hostCacheDir || defaultComposioDir;
308 - const baseReadAccessRoots = [
309 - ...new Set([defaultComposioDir, configuredCacheDir].map(value => path.resolve(value))),
310 - ];
311 -
271 const baseContext = {
272 apiKey,
273 baseURL: userContext.data.baseURL,
274 webURL: userContext.data.webURL,
275 orgId,
317 - cliConfigPath: yield* resolveCliConfigPath,
318 - readAccessRoots: baseReadAccessRoots,
276 } satisfies RunHelperContext;
277
278 if (!apiKey || !orgId) {
@@ -340,13 +297,6 @@ const resolveRunHelperContext = () =>
297 consumerProjectId: consumerProject.value.projectId,
298 consumerProjectName: consumerProject.value.projectName,
299 runOutputDir: sessionArtifactsDir,
343 - readAccessRoots: [
344 - ...new Set(
345 - [...baseReadAccessRoots, sessionArtifactsDir]
346 - .filter((value): value is string => typeof value === 'string' && value.length > 0)
347 - .map(value => path.resolve(value))
348 - ),
349 - ],
300 } satisfies RunHelperContext;
301 });
302
@@ -454,7 +404,7 @@ export const runCmd = Command.make('run', {
404 args,
405 }).pipe(
406 Command.withDescription(
457 - 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.\n\nInjected helpers (behave like their CLI counterparts):\n execute(slug, data?) Same as `composio execute` — returns parsed JSON\n search(query, options?) Same as `composio search` — returns matching tools\n experimental_subAgent(prompt, options?) Experimental helper to spawn a powerful sub-agent from the same agent family as your current main agent\n (Codex -> Codex, Claude -> Claude) with optional Zod structured output\n result.prompt() Prompt-safe serialization of a helper result, ideal for experimental_subAgent(...)\n const f = await proxy(toolkit) Same as `composio proxy` — returns a fetch function\n Example: const f = await proxy("gmail")\n const me = await f("https://gmail.googleapis.com/gmail/v1/users/me/profile")\n z Injected global from `zod` for structured output schemas\n\nAll helpers reuse your CLI auth state and connected accounts.\n\nUse composio search "<query>" to discover tools and composio execute <slug> --get-schema to inspect inputs.'
407 + 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.\n\nInjected helpers (behave like their CLI counterparts):\n execute(slug, data?) Same as `composio execute` — returns parsed JSON\n search(query, options?) Same as `composio search` — returns matching tools\n result.prompt() Prompt-safe serialization of a helper result\n const f = await proxy(toolkit) Same as `composio proxy` — returns a fetch function\n Example: const f = await proxy("gmail")\n const me = await f("https://gmail.googleapis.com/gmail/v1/users/me/profile")\n z Injected global from `zod` for defining and validating schemas\n\nAll helpers reuse your CLI auth state and connected accounts.\n\nUse composio search "<query>" to discover tools and composio execute <slug> --get-schema to inspect inputs.'
408 ),
409 Command.withShortDescription(
410 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.'
@@ -488,33 +438,13 @@ export const runCmd = Command.make('run', {
438 'composio run \'\n const f = await proxy("gmail");\n console.log(await f("https://gmail.googleapis.com/gmail/v1/users/me/profile"));\n\'',
439 description: 'proxy(toolkit) — returns a fetch() bound to your connected account',
440 },
491 - {
492 - command:
493 - 'composio run \'\n const [emails, issues] = await Promise.all([\n execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),\n execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),\n ]);\n // result.prompt() serializes helper output for LLM consumption\n // z is a global from zod for defining structured output schemas\n const brief = await experimental_subAgent(\n `Summarize these emails and issues.\\n\\n${emails.prompt()}\\n\\n${issues.prompt()}`,\n { schema: z.object({ summary: z.string(), urgent: z.array(z.string()) }) }\n );\n console.log(brief.structuredOutput);\n\'',
494 - description:
495 - 'experimental_subAgent + z + result.prompt() — structured output from a sub-agent',
496 - },
441 {
442 command: 'composio run --file ./workflow.ts -- --repo acme/app',
443 description: 'Run from a file',
444 },
501 - {
502 - command:
503 - 'composio run \'\n const [emails, issues] = await Promise.all([\n execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),\n execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),\n ]);\n const brief = await experimental_subAgent(\n `Create a morning brief from these emails and issues.\\n\\n${emails.prompt()}\\n\\n${issues.prompt()}`,\n {\n schema: z.object({\n brief: z.string(),\n urgentEmails: z.array(z.string()),\n urgentIssues: z.array(z.string()),\n }),\n }\n );\n brief.structuredOutput;\n\'',
504 - description: 'Create a structured brief with an injected sub-agent.',
505 - },
445 ]),
446 Command.withHandler(
508 - ({
509 - file,
510 - dryRun,
511 - debug,
512 - logsOff,
513 - skipConnectionCheck,
514 - skipToolParamsCheck,
515 - skipChecks,
516 - args,
517 - }) =>
447 + ({ file, dryRun, debug, skipConnectionCheck, skipToolParamsCheck, skipChecks, args }) =>
448 Effect.gen(function* () {
449 // Checked before any setup work so a bare `composio run` neither creates a run-artifacts
450 // directory nor advertises a log file for a script that will never start.
@@ -533,7 +463,6 @@ export const runCmd = Command.make('run', {
463 );
464 const perfDebug = yield* isPerfDebugEnabled;
465 const toolDebug = yield* isToolDebugEnabled;
536 - const acpOnly = yield* isAcpOnlyEnabled;
466 const telemetryDebug = yield* isTelemetryDebugEnabled;
467 if (Option.isNone(file)) {
468 const [inlineCode] = args;
@@ -550,13 +479,10 @@ export const runCmd = Command.make('run', {
479 const helperContext: RunHelperContext = {
480 ...(yield* resolveRunHelperContext()),
481 runId,
553 - master: yield* detectMasterFromHost,
482 perfDebug,
483 toolDebug,
484 telemetryDebug,
485 debug,
558 - logsOff,
559 - acpOnly,
486 dryRun,
487 skipConnectionCheck,
488 skipToolParamsCheck,
@@ -605,7 +531,7 @@ export const runCmd = Command.make('run', {
531 env: {
532 BUN_BE_BUN: '1',
533 COMPOSIO_CLI_PARENT_RUN_ID: runId,
608 - ...debugFlagsToChildEnv({ perfDebug, toolDebug, acpOnly, telemetryDebug }),
534 + ...debugFlagsToChildEnv({ perfDebug, toolDebug, telemetryDebug }),
535 },
536 extendEnv: true,
537 stdin: 'inherit',
ts/packages/cli/src/effects/app-config.ts
+1 -7
@@ -1,4 +1,4 @@
1 -import { Config, Effect, LogLevel, Option, Schema } from 'effect';
1 +import { Config, LogLevel, Option, Schema } from 'effect';
2 import * as constants from 'src/constants';
3
4 type APP_CONFIG = Config.Wrap<{
@@ -16,7 +16,6 @@ type APP_CONFIG = Config.Wrap<{
16 WEBHOOK_SECRET: string | undefined;
17 CLI_INVOCATION_ORIGIN: string | undefined;
18 CLI_PARENT_RUN_ID: string | undefined;
19 - RUN_ACP_ONLY: boolean;
19 RUN_OUTPUT_DIR: string | undefined;
20 PERF_DEBUG: boolean;
21 TOOL_DEBUG: boolean;
@@ -24,7 +23,6 @@ type APP_CONFIG = Config.Wrap<{
23 }>;
24
25 type UNPREFIXED_CONFIG = Config.Wrap<{
27 - CACHE_DIR: string | undefined;
26 NPM_CONFIG_USER_AGENT: string | undefined;
27 CI_REDACTION_ENABLED: boolean;
28 INTERACTIVE_PERMISSION_UI_DISABLED: boolean;
@@ -173,7 +171,6 @@ export const APP_CONFIG = {
171 // Internal context propagated between CLI processes
172 CLI_INVOCATION_ORIGIN: optionalTrimmedString('CLI_INVOCATION_ORIGIN'),
173 CLI_PARENT_RUN_ID: optionalTrimmedString('CLI_PARENT_RUN_ID'),
176 - RUN_ACP_ONLY: booleanFlag('RUN_ACP_ONLY'),
174 RUN_OUTPUT_DIR: optionalTrimmedString('RUN_OUTPUT_DIR'),
175
176 // Runtime debug flags
@@ -194,9 +191,6 @@ export const APP_CONFIG = {
191 * inspect raw environment strings.
192 */
193 export const UNPREFIXED_CONFIG = {
197 - // The cache directory of the host tool driving the CLI (not `COMPOSIO_CACHE_DIR`)
198 - CACHE_DIR: optionalTrimmedString('CACHE_DIR'),
199 -
194 // The package manager that invoked the CLI, as reported by npm-compatible clients
195 NPM_CONFIG_USER_AGENT: optionalString('npm_config_user_agent'),
196
ts/packages/cli/src/models/cli-user-config.ts
+2 -28
@@ -2,9 +2,6 @@ import { Effect, Schema, SchemaGetter } from 'effect';
2 import { OptionFromOptionalNullOr } from 'effect/Schema';
3 import { JSONTransformSchema } from './utils/json-transform-schema';
4
5 -export const ExperimentalSubagentTarget = Schema.Literals(['auto', 'claude', 'codex']);
6 -export type ExperimentalSubagentTarget = Schema.Schema.Type<typeof ExperimentalSubagentTarget>;
7 -
5 /**
6 * Where the CLI stores the Composio API key.
7 *
@@ -55,12 +52,6 @@ const CliUserConfigStruct = Schema.Struct({
52 Schema.withDecodingDefaultType(Effect.succeed({}))
53 ),
54 artifactDirectory: OptionFromOptionalNullOr(Schema.String, { onNoneEncoding: null }),
58 - experimentalSubagent: OptionFromOptionalNullOr(
59 - Schema.Struct({
60 - target: ExperimentalSubagentTarget,
61 - }),
62 - { onNoneEncoding: null }
63 - ),
55 /**
56 * Where the CLI stores the Composio API key. See the
57 * `SecurityBackend` type above for semantics. Default: `"auto"`
@@ -76,7 +67,6 @@ const CliUserConfigWithEncodedKeys = CliUserConfigStruct.pipe(
67 Schema.encodeKeys({
68 experimentalFeatures: 'experimental_features',
69 artifactDirectory: 'artifact_directory',
79 - experimentalSubagent: 'experimental_subagent',
70 })
71 );
72
@@ -90,36 +80,20 @@ export const CliUserConfig = Schema.StructWithRest(
80 Schema.StructWithRest(CliUserConfigWithEncodedKeys.to, unknownCliUserConfigFields),
81 {
82 decode: SchemaGetter.transform(
93 - ({
94 - developer,
95 - experimental_features,
96 - artifact_directory,
97 - experimental_subagent,
98 - security,
99 - ...rest
100 - }) => ({
83 + ({ developer, experimental_features, artifact_directory, security, ...rest }) => ({
84 ...rest,
85 developer,
86 experimentalFeatures: experimental_features,
87 artifactDirectory: artifact_directory,
105 - experimentalSubagent: experimental_subagent,
88 security,
89 })
90 ),
91 encode: SchemaGetter.transform(
110 - ({
111 - developer,
112 - experimentalFeatures,
113 - artifactDirectory,
114 - experimentalSubagent,
115 - security,
116 - ...rest
117 - }) => ({
92 + ({ developer, experimentalFeatures, artifactDirectory, security, ...rest }) => ({
93 ...rest,
94 developer,
95 experimental_features: experimentalFeatures,
96 artifact_directory: artifactDirectory,
122 - experimental_subagent: experimentalSubagent,
97 security,
98 })
99 ),
ts/packages/cli/src/services/cli-user-config.ts
-6
@@ -20,7 +20,6 @@ export type CliUserConfigResolved = {
20 readonly developerDangerousCommandsEnabled: boolean;
21 readonly experimentalFeatures: Readonly<Record<string, boolean>>;
22 readonly artifactDirectory: string | undefined;
23 - readonly experimentalSubagentTarget: 'auto' | 'claude' | 'codex';
23 /**
24 * Where the CLI stores the Composio API key. See the
25 * `SecurityBackend` type in `src/models/cli-user-config.ts`.
@@ -40,7 +39,6 @@ const DEFAULT_CLI_USER_CONFIG = CliUserConfig.make({
39 },
40 experimentalFeatures: {},
41 artifactDirectory: Option.none(),
43 - experimentalSubagent: Option.none(),
42 security: 'auto',
43 });
44
@@ -73,10 +71,6 @@ const resolveConfig = (raw: CliUserConfig, channel: CliReleaseChannel): CliUserC
71 developerDangerousCommandsEnabled: raw.developer.destructiveActions,
72 experimentalFeatures: raw.experimentalFeatures,
73 artifactDirectory: Option.getOrUndefined(raw.artifactDirectory),
76 - experimentalSubagentTarget: Option.match(raw.experimentalSubagent, {
77 - onNone: () => 'auto',
78 - onSome: value => value.target,
79 - }),
74 security: raw.security,
75 });
76
ts/packages/cli/src/services/run-companion-modules.ts
+33 -241
@@ -9,13 +9,12 @@ import { extractZipSafely } from 'src/utils/extract-zip-safely';
9 import { APP_VERSION, IS_RELEASE_BUILD } from 'src/constants';
10 import { GitHubRelease } from 'src/effects/resolve-cli-release';
11 import { getBaseConfigProvider, extendConfigProvider } from 'src/services/config';
12 -import { NodeOs } from 'src/services/node-os';
12 import { atomicReplaceFile } from 'src/utils/atomic-replace';
13 import { parseChecksumsText, sha256Hex } from 'src/utils/checksums';
14 import { CLI_RELEASE_TAG_PREFIX } from 'src/utils/cli-release-version';
15
16 // Modules the binary build bundles separately (`dist/<name>.mjs` next to the
18 -// executable) instead of into the executable itself. The first five are what
17 +// executable) instead of into the executable itself. The first one is what
18 // `composio run` preloads into the script it spawns. The last one is loaded into
19 // the CLI's own process, on demand, through `loadInstalledCompanionModule`: it
20 // carries the TypeScript compiler, which was 44% of the executable's JavaScript
@@ -23,10 +22,6 @@ import { CLI_RELEASE_TAG_PREFIX } from 'src/utils/cli-release-version';
22 // reach it.
23 export const RUN_COMPANION_MODULE_BASENAMES: ReadonlyArray<string> = [
24 'run-helpers-runtime',
26 - 'run-subagent-shared',
27 - 'run-subagent-acp',
28 - 'run-subagent-legacy',
29 - 'run-subagent-output-mcp',
25 'generation-runtime',
26 ];
27
@@ -35,100 +30,30 @@ export const RUN_COMPANION_MODULE_FILENAMES = RUN_COMPANION_MODULE_BASENAMES.map
30 );
31
32 export const RUN_COMPANION_RELEASE_TAG_FILENAME = 'release-tag.txt';
38 -export type RunCodexAcpBinaryTarget = {
39 - readonly platform: NodeJS.Platform;
40 - readonly arch: string;
41 - readonly packageName: string;
42 - readonly binaryFileName: string;
43 - readonly relativePath: string;
44 -};
33
46 -export const RUN_CODEX_ACP_BINARY_TARGETS: ReadonlyArray<RunCodexAcpBinaryTarget> = [
47 - {
48 - platform: 'darwin',
49 - arch: 'arm64',
50 - packageName: '@zed-industries/codex-acp-darwin-arm64',
51 - binaryFileName: 'codex-acp',
52 - relativePath: 'acp-adapters/codex/darwin-arm64/codex-acp',
53 - },
54 - {
55 - platform: 'darwin',
56 - arch: 'x64',
57 - packageName: '@zed-industries/codex-acp-darwin-x64',
58 - binaryFileName: 'codex-acp',
59 - relativePath: 'acp-adapters/codex/darwin-x64/codex-acp',
60 - },
61 - {
62 - platform: 'linux',
63 - arch: 'arm64',
64 - packageName: '@zed-industries/codex-acp-linux-arm64',
65 - binaryFileName: 'codex-acp',
66 - relativePath: 'acp-adapters/codex/linux-arm64/codex-acp',
67 - },
68 - {
69 - platform: 'linux',
70 - arch: 'x64',
71 - packageName: '@zed-industries/codex-acp-linux-x64',
72 - binaryFileName: 'codex-acp',
73 - relativePath: 'acp-adapters/codex/linux-x64/codex-acp',
74 - },
75 -];
76 -export const codexAcpBinaryTargetFor = ({
77 - platform,
78 - arch,
79 -}: {
80 - readonly platform: string;
81 - readonly arch: string;
82 -}): RunCodexAcpBinaryTarget | undefined =>
83 - RUN_CODEX_ACP_BINARY_TARGETS.find(target => target.platform === platform && target.arch === arch);
84 -
85 -// Portable ACP assets: any install that invokes an ACP sub-agent needs these
86 -// regardless of platform/arch. They belong to the lazy tier — see
87 -// `listMissingInstalledRunCompanionModules` for the two-tier split.
88 -export const RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS: ReadonlyArray<string> = [
34 +// Paths the removed `experimental_subAgent` helper used to ship. Release archives
35 +// keep them as zero-byte files because every stable CLI from 0.2.12 to 0.4.2
36 +// verifies a downloaded upgrade package against its own copy of this list, by
37 +// existence only, and refuses a package that lacks any of them.
38 +//
39 +// Frozen: nothing derives it from live code, so it must not change while those
40 +// clients can still upgrade. It stays out of `RUN_COMPANION_MODULE_BASENAMES`,
41 +// which drives the bundler; packaging is the only writer, so installs and source
42 +// checkouts never require these files.
43 +// `.github/scripts/cli-release/verify-archive-companions.sh` carries the same list.
44 +export const RUN_COMPANION_LEGACY_PLACEHOLDER_RELATIVE_PATHS: ReadonlyArray<string> = [
45 + 'run-subagent-shared.mjs',
46 + 'run-subagent-acp.mjs',
47 + 'run-subagent-legacy.mjs',
48 + 'run-subagent-output-mcp.mjs',
49 'acp-adapters/claude-code-acp.mjs',
90 - // cli.js from @anthropic-ai/claude-agent-sdk must live next to claude-code-acp.mjs.
91 - // The bundled adapter uses import.meta.url to locate it at runtime.
50 'acp-adapters/cli.js',
51 + 'acp-adapters/codex/darwin-arm64/codex-acp',
52 + 'acp-adapters/codex/darwin-x64/codex-acp',
53 + 'acp-adapters/codex/linux-arm64/codex-acp',
54 + 'acp-adapters/codex/linux-x64/codex-acp',
55 ];
56
95 -// Every asset a release archive ships, across all supported platforms. Only the
96 -// packaging step cares about this: a single machine can execute exactly one of
97 -// the codex-acp binaries.
98 -export const RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS: ReadonlyArray<string> = [
99 - ...RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
100 - ...RUN_CODEX_ACP_BINARY_TARGETS.map(target => target.relativePath),
101 -];
102 -
103 -/**
104 - * ACP assets an install must contain to be complete on the given platform/arch:
105 - * the portable ones plus at most the single codex-acp binary this host can run.
106 - * Unsupported platform/arch pairs simply have no codex-acp requirement.
107 - *
108 - * These are the *lazy* tier: `composio run` only needs them when the script it
109 - * runs actually invokes an ACP sub-agent, so startup never demands them.
110 - */
111 -export const runCompanionStaticAssetRelativePathsFor = ({
112 - platform,
113 - arch,
114 -}: {
115 - readonly platform: string;
116 - readonly arch: string;
117 -}): ReadonlyArray<string> => {
118 - const hostTarget = codexAcpBinaryTargetFor({ platform, arch });
119 -
120 - return hostTarget
121 - ? [...RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS, hostTarget.relativePath]
122 - : RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS;
123 -};
124 -
125 -// NodeOs is the sanctioned platform/arch boundary; self-provided so callers keep
126 -// their existing FileSystem/Path-only requirements.
127 -export const hostRunCompanionStaticAssetRelativePaths: Effect.Effect<ReadonlyArray<string>> =
128 - Effect.map(NodeOs, os =>
129 - runCompanionStaticAssetRelativePathsFor({ platform: os.platform, arch: os.arch })
130 - ).pipe(Effect.provide(NodeOs.Default));
131 -
57 export class RunCompanionRepairError extends Data.TaggedError('services/RunCompanionRepairError')<{
58 readonly message: string;
59 readonly cause?: unknown;
@@ -206,108 +131,17 @@ const collectRelativeImportPaths = ({
131 }
132 });
133
209 -export const collectRunCompanionAssetRelativePaths = (
210 - rootDir: string
211 -): Effect.Effect<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> =>
212 - Effect.gen(function* () {
213 - const fs = yield* FileSystem.FileSystem;
214 - const path = yield* Path.Path;
215 - const collected = new Set<string>();
216 -
217 - for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
218 - yield* collectRelativeImportPaths({
219 - fs,
220 - path,
221 - rootDir,
222 - relativePath: fileName,
223 - collected,
224 - });
225 - }
226 -
227 - if (collected.size === 0) {
228 - for (const baseName of RUN_COMPANION_MODULE_BASENAMES) {
229 - yield* collectRelativeImportPaths({
230 - fs,
231 - path,
232 - rootDir,
233 - relativePath: `services/${baseName}.mjs`,
234 - collected,
235 - });
236 - }
237 - }
238 -
239 - for (const relativePath of yield* hostRunCompanionStaticAssetRelativePaths) {
240 - yield* collectRelativeImportPaths({
241 - fs,
242 - path,
243 - rootDir,
244 - relativePath,
245 - collected,
246 - });
247 - }
248 -
249 - return [...collected].sort();
250 - });
251 -
252 -/**
253 - * A release archive names every codex-acp path but fills only the one its own
254 - * platform can execute; the rest are empty placeholders that keep older clients'
255 - * upgrade verification passing. `requireNonEmpty` makes a placeholder resolve as
256 - * absent so the caller falls through to its next adapter source.
257 - */
258 -const fileHasContent = (fs: FileSystem.FileSystem, filePath: string) =>
259 - fs.stat(filePath).pipe(
260 - Effect.map(info => Number(info.size) > 0),
261 - Effect.orElseSucceed(() => false)
262 - );
263 -
264 -export const resolveRunCompanionAssetPath = ({
265 - callerImportMetaUrl,
266 - execPath,
267 - relativePathFromRoot,
268 - requireNonEmpty = false,
269 -}: {
270 - callerImportMetaUrl: string;
271 - execPath: string;
272 - relativePathFromRoot: string;
273 - requireNonEmpty?: boolean;
274 -}): Effect.Effect<string | null, never, FileSystem.FileSystem | Path.Path> =>
275 - Effect.gen(function* () {
276 - const fs = yield* FileSystem.FileSystem;
277 - const path = yield* Path.Path;
278 - const currentFilePath = yield* filePathFromUrl(path, callerImportMetaUrl);
279 - const currentDirectory = path.dirname(currentFilePath);
280 - const executableDirectory = path.dirname(execPath);
281 -
282 - const candidates = [
283 - path.resolve(currentDirectory, relativePathFromRoot),
284 - path.resolve(currentDirectory, '..', relativePathFromRoot),
285 - path.resolve(executableDirectory, relativePathFromRoot),
286 - ];
287 -
288 - const isUsable = requireNonEmpty ? fileHasContent : fileExists;
289 - const found = yield* Effect.findFirst(candidates, candidate => isUsable(fs, candidate));
290 - return Option.getOrNull(found);
291 - });
292 -
134 /**
294 - * Relative paths an install rooted at `rootDir` is expected to contain.
295 - *
296 - * `staticAssetRelativePaths` defaults to the host's requirement set, so a
297 - * missing codex-acp binary for a foreign platform never counts as a broken
298 - * install. Release packaging passes `RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS`
299 - * because one packaging host builds archives for every platform.
135 + * Relative paths an install rooted at `rootDir` is expected to contain: the
136 + * companion wrappers and every relative import reachable from them.
137 */
138 export const collectExpectedRunCompanionAssetRelativePaths = (
302 - rootDir: string,
303 - options: { readonly staticAssetRelativePaths?: ReadonlyArray<string> } = {}
139 + rootDir: string
140 ): Effect.Effect<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> =>
141 Effect.gen(function* () {
142 const fs = yield* FileSystem.FileSystem;
143 const path = yield* Path.Path;
144 const collected = new Set<string>();
309 - const staticAssetRelativePaths =
310 - options.staticAssetRelativePaths ?? (yield* hostRunCompanionStaticAssetRelativePaths);
145
146 for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
147 yield* collectRelativeImportPaths({
@@ -320,17 +154,6 @@ export const collectExpectedRunCompanionAssetRelativePaths = (
154 });
155 }
156
323 - for (const relativePath of staticAssetRelativePaths) {
324 - yield* collectRelativeImportPaths({
325 - fs,
326 - path,
327 - rootDir,
328 - relativePath,
329 - collected,
330 - recordMissingPaths: true,
331 - });
332 - }
333 -
157 return [...collected].sort();
158 });
159
@@ -447,15 +270,11 @@ export const writeInstalledReleaseTag = (
270 });
271
272 /**
450 - * Startup tier: the companion wrappers and their import graph.
273 + * The companion wrappers and their import graph, listed when missing.
274 *
452 - * Every `composio run` preloads the `run-*` modules into the spawned child, and
453 - * the CLI loads the in-process ones on demand, so a missing one really is a
454 - * broken install and justifies the self-repair download. The ACP
455 - * adapter assets are deliberately excluded — a script like
456 - * `composio run 'console.log(1)'` never invokes a sub-agent, and requiring
457 - * ~224MB of adapters for it turned a working install into a hard failure.
458 - * `run-subagent-acp` checks the ACP tier lazily at the invocation site instead.
275 + * `composio run` preloads `run-helpers-runtime` into the spawned child, and the
276 + * CLI loads the in-process ones on demand, so a missing one really is a broken
277 + * install and justifies the self-repair download.
278 */
279 export const listMissingInstalledRunCompanionModules = (
280 execPath: string
@@ -464,10 +283,8 @@ export const listMissingInstalledRunCompanionModules = (
283 const fs = yield* FileSystem.FileSystem;
284 const path = yield* Path.Path;
285 const installDirectory = path.dirname(execPath);
467 - const expectedRelativePaths = yield* collectExpectedRunCompanionAssetRelativePaths(
468 - installDirectory,
469 - { staticAssetRelativePaths: [] }
470 - );
286 + const expectedRelativePaths =
287 + yield* collectExpectedRunCompanionAssetRelativePaths(installDirectory);
288 return yield* Effect.filter(expectedRelativePaths, relativePath =>
289 Effect.map(fileExists(fs, path.join(installDirectory, relativePath)), exists => !exists)
290 );
@@ -499,28 +316,6 @@ const listMissingInstalledCompanionModuleFiles = (
316 );
317 });
318
502 -/**
503 - * Whether the companion wrappers sit next to the executable, which is how
504 - * packaged installs ship them.
505 - *
506 - * This distinguishes an install whose shipped assets went missing (report the
507 - * fix: reinstall / `composio upgrade`) from a source checkout that never had
508 - * them, where the CLI runs through `bun` and the npx/PATH adapter fallbacks are
509 - * the intended route.
510 - */
511 -export const hasInstalledRunCompanionModules = (
512 - execPath: string
513 -): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>
514 - Effect.gen(function* () {
515 - const fs = yield* FileSystem.FileSystem;
516 - const path = yield* Path.Path;
517 - const installDirectory = path.dirname(execPath);
518 - const missing = yield* Effect.findFirst(RUN_COMPANION_MODULE_FILENAMES, fileName =>
519 - Effect.map(fileExists(fs, path.join(installDirectory, fileName)), exists => !exists)
520 - );
521 - return Option.isNone(missing);
522 - });
523 -
319 const fetchGitHubJson = async <A, I>(
320 schema: Schema.Codec<A, I>,
321 {
@@ -659,12 +454,9 @@ const githubRepairConfig = Effect.orDie(
454 );
455
456 /**
662 - * Restores a packaged install whose companion wrappers went missing.
663 - *
664 - * Triggered by the startup tier only (`listMissingInstalledRunCompanionModules`),
665 - * so a plain `composio run` never downloads a release just because the ACP
666 - * adapters are absent. Once it does run it restores the host's full asset set,
667 - * ACP adapters included, so a repaired install is a complete one.
457 + * Restores a packaged install whose companion wrappers went missing, from the
458 + * release archive of the running version. The archive's legacy placeholders are
459 + * not companions and are left behind.
460 */
461 export const repairMissingInstalledRunCompanionModules = ({
462 callerImportMetaUrl,
@@ -677,7 +469,7 @@ export const repairMissingInstalledRunCompanionModules = ({
469 appVersion: string;
470 /**
471 * Repair only when this companion's own files are missing, rather than when
680 - * any startup-tier file is. The repair still restores the full set.
472 + * any companion file is. The repair still restores the full set.
473 */
474 companionBaseName?: string;
475 }): Effect.Effect<
ts/packages/cli/src/services/run-helpers-runtime.ts
+28 -286
@@ -1,7 +1,7 @@
1 import { cliRequestHeaders } from './client-provenance';
2 // This module is preloaded into the user's spawned child process, where no Effect
3 // runtime or @effect/platform layers are provided, so it uses sync Node builtins.
4 -// eslint-disable-next-line no-restricted-imports -- sync fs for run-log appends, run-file writes, and CLI config reads in the child process, outside the Effect runtime
4 +// eslint-disable-next-line no-restricted-imports -- sync fs for run-log appends and run-file writes in the child process, outside the Effect runtime
5 import * as fs from 'node:fs';
6 import { ssrfSafeFetch } from '@composio/core/utils/ssrf-guard';
7 import { ChildProcess as Command } from 'effect/unstable/process';
@@ -9,16 +9,6 @@ import * as Path from 'effect/Path';
9 import * as BunServices from '@effect/platform-bun/BunServices';
10 import { Effect, Result, ManagedRuntime, Predicate, Schema } from 'effect';
11 import { z } from 'zod';
12 -import { JsonRecordSchema } from 'src/effects/json';
13 -import type { MasterKind } from 'src/services/master-detector';
14 -import {
15 - isAcpInvokeError,
16 - parseJson,
17 - type HelperDebugLog,
18 - type InvokeAgentNormalizedOptions,
19 -} from 'src/services/run-subagent-shared';
20 -import { invokeAcpSubAgent } from 'src/services/run-subagent-acp';
21 -import { invokeLegacySubAgent } from 'src/services/run-subagent-legacy';
12 import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';
13 import { NodeOs } from 'src/services/node-os';
14 import { collectText } from 'src/services/command-runner';
@@ -46,14 +36,9 @@ export type RunHelperContext = {
36 readonly skipConnectionCheck?: boolean;
37 readonly skipToolParamsCheck?: boolean;
38 readonly skipChecks?: boolean;
49 - readonly master?: MasterKind;
39 readonly debug?: boolean;
51 - readonly acpOnly?: boolean;
52 - readonly logsOff?: boolean;
40 readonly runOutputDir?: string;
41 readonly runLogFilePath?: string;
55 - readonly readAccessRoots?: ReadonlyArray<string>;
56 - readonly cliConfigPath?: string;
42 };
43
44 type RunHelpersInstallParams = {
@@ -63,15 +48,8 @@ type RunHelpersInstallParams = {
48
49 type RunCliResult = unknown;
50
66 -const JsonObject = JsonRecordSchema;
67 -const ExperimentalSubagentConfig = Schema.Struct({
68 - experimental_subagent: Schema.optional(
69 - Schema.Struct({ target: Schema.optional(Schema.Unknown) })
70 - ),
71 -});
72 -const decodeExperimentalSubagentConfig = Schema.decodeUnknownSync(
73 - Schema.fromJsonString(ExperimentalSubagentConfig)
74 -);
51 +type HelperDebugLog = (step: string, details?: Record<string, unknown>) => void;
52 +
53 const ProxySessionResponse = Schema.Struct({ session_id: Schema.NonEmptyString });
54 const ProxyExecuteCompletedResponse = Schema.Struct({
55 // Absent when an older server answers; any other value fails the decode
@@ -102,48 +80,6 @@ const ProxyExecuteResponse = Schema.Union([
80 ]);
81 const isProxyInputRequired = Schema.is(ProxyExecuteInputRequiredResponse);
82
105 -const experimentalSubAgentSchema = {
106 - type: 'function',
107 - description:
108 - 'Experimental helper: prompt a sub-agent from the same agent family as the current main agent (Codex -> Codex, Claude -> Claude) and return its final response.',
109 - parameters: {
110 - type: 'object',
111 - additionalProperties: false,
112 - required: ['prompt'],
113 - properties: {
114 - prompt: { type: 'string', description: 'The prompt to send to the agent CLI.' },
115 - target: {
116 - type: 'string',
117 - enum: ['claude', 'codex', 'user'],
118 - description: 'Optional master override. Defaults to the detected current master.',
119 - },
120 - model: {
121 - type: 'string',
122 - description: 'Optional model override passed through to the agent CLI.',
123 - },
124 - schema: {
125 - description:
126 - 'Optional structured-output schema. Accepts a Zod schema or raw JSON Schema object.',
127 - },
128 - jsonSchema: {
129 - description: 'Optional JSON Schema requesting structured output from the agent.',
130 - },
131 - },
132 - },
133 - returns: {
134 - type: 'object',
135 - additionalProperties: false,
136 - required: ['master', 'target', 'result'],
137 - properties: {
138 - master: { type: 'string', enum: ['claude', 'codex', 'user'] },
139 - target: { type: 'string', enum: ['claude', 'codex'] },
140 - result: { description: 'Final plain-text result when available.' },
141 - structuredOutput: { description: 'Structured output when jsonSchema was requested.' },
142 - logFilePath: { description: 'Path to the local run log file for helper execution details.' },
143 - },
144 - },
145 -};
146 -
83 const proxySchema = {
84 type: 'function',
85 description:
@@ -174,6 +110,16 @@ const proxySchema = {
110 },
111 };
112
113 +const REMOVED_SUB_AGENT_MESSAGE =
114 + 'experimental_subAgent() was removed from composio run because its agent transport automatically approved permission requests. Print the tool results and let the calling agent summarize them instead.';
115 +
116 +// Rejects instead of throwing synchronously: the removed helper always returned a
117 +// promise, so scripts that handle its failure with `.catch` or `Promise.allSettled`
118 +// keep doing so.
119 +const removedSubAgent = async (): Promise<never> => {
120 + throw new Error(REMOVED_SUB_AGENT_MESSAGE);
121 +};
122 +
123 const encodeBase64 = (bytes: Uint8Array): string => {
124 let binary = '';
125 for (const byte of bytes) {
@@ -186,6 +132,18 @@ const encodeBase64 = (bytes: Uint8Array): string => {
132 // Pure helpers — no run-context captures, hoisted to module scope
133 // ---------------------------------------------------------------------------
134
135 +export const parseJson = (text: string): unknown => {
136 + const value = text.trim();
137 + if (!value) {
138 + return undefined;
139 + }
140 + // Non-JSON output is returned verbatim by design.
141 + return Result.getOrElse(
142 + Result.try((): unknown => JSON.parse(value)),
143 + () => value
144 + );
145 +};
146 +
147 const executeId = () => crypto.randomUUID().slice(0, 8);
148
149 const truncateDebugText = (value: unknown, max = 240) => {
@@ -213,58 +171,6 @@ const previewDebugValue = (value: unknown): string => {
171
172 const formatHelperDebugEvent = (step: string, details: Record<string, unknown> = {}) => {
173 switch (step) {
216 - case 'subAgent.target':
217 - return `[experimental_subAgent] triggered with ${details.resolvedTarget}`;
218 - case 'subAgent.acp.resolve':
219 - return `[experimental_subAgent] ACP via ${details.source} (${details.target})`;
220 - case 'subAgent.acp.initialized':
221 - return `[experimental_subAgent] ACP initialized (${details.target})`;
222 - case 'subAgent.acp.session':
223 - return `[experimental_subAgent] session ready (${details.target})`;
224 - case 'subAgent.acp.model':
225 - return details.applied === true
226 - ? `[experimental_subAgent] model=${details.model}`
227 - : `[experimental_subAgent] model unchanged (${details.model})`;
228 - case 'subAgent.acp.message': {
229 - const text = previewDebugValue(details.text);
230 - return text ? `[experimental_subAgent] ${text}` : null;
231 - }
232 - case 'subAgent.acp.thought': {
233 - const text = previewDebugValue(details.text);
234 - return text ? `[experimental_subAgent:thinking] ${text}` : null;
235 - }
236 - case 'subAgent.acp.tool_call': {
237 - const locations = Array.isArray(details.locations) ? details.locations : [];
238 - const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';
239 - return `[experimental_subAgent:tool] ${details.status || 'pending'} ${
240 - details.title || details.kind || 'tool'
241 - }${where}`;
242 - }
243 - case 'subAgent.acp.tool_call_update': {
244 - const locations = Array.isArray(details.locations) ? details.locations : [];
245 - const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';
246 - const preview = previewDebugValue(details.rawOutput);
247 - return `[experimental_subAgent:tool] ${details.status || 'update'} ${
248 - details.title || details.toolCallId || details.kind || 'tool'
249 - }${where}${preview ? ` -> ${preview}` : ''}`;
250 - }
251 - case 'subAgent.acp.plan': {
252 - const entries = Array.isArray(details.entries)
253 - ? details.entries.filter(Predicate.isObject)
254 - : [];
255 - if (entries.length === 0) return '[experimental_subAgent:plan] updated';
256 - const summary = entries
257 - .slice(0, 3)
258 - .map(entry => {
259 - const status = typeof entry.status === 'string' ? entry.status : 'pending';
260 - const content = typeof entry.content === 'string' ? entry.content : '';
261 - return `${status}:${truncateDebugText(content, 48)}`;
262 - })
263 - .join(' | ');
264 - return `[experimental_subAgent:plan] ${summary}`;
265 - }
266 - case 'subAgent.acp.fallback':
267 - return `[experimental_subAgent] ACP fallback (${details.code})`;
174 case 'execute.prepare':
175 return `[execute] ${details.slug}`;
176 case 'search.prepare':
@@ -348,73 +254,6 @@ const summarizeCliResultPreview = (result: RunCliResult): unknown => {
254 return result;
255 };
256
351 -const readConfiguredExperimentalSubagentTarget = (
352 - cliConfigPath: string | undefined
353 -): 'auto' | 'claude' | 'codex' => {
354 - if (!cliConfigPath) return 'auto';
355 -
356 - return Result.getOrElse(
357 - Result.try(() => {
358 - const raw = fs.readFileSync(cliConfigPath, 'utf8');
359 - const parsed = decodeExperimentalSubagentConfig(raw);
360 - const target = parsed.experimental_subagent?.target;
361 - return target === 'claude' || target === 'codex' || target === 'auto' ? target : 'auto';
362 - }),
363 - () => 'auto' as const
364 - );
365 -};
366 -
367 -const normalizeInvokeAgentOptions = (
368 - options: Record<string, unknown> = {}
369 -): InvokeAgentNormalizedOptions => {
370 - if (options == null || typeof options !== 'object' || Array.isArray(options)) {
371 - throw new Error('experimental_subAgent() options must be an object when provided.');
372 - }
373 - if (options.schema !== undefined && options.jsonSchema !== undefined) {
374 - throw new Error(
375 - 'experimental_subAgent() accepts either options.schema or options.jsonSchema, not both.'
376 - );
377 - }
378 - const requestedTarget = options.target;
379 - if (
380 - requestedTarget !== undefined &&
381 - requestedTarget !== 'claude' &&
382 - requestedTarget !== 'codex' &&
383 - requestedTarget !== 'user'
384 - ) {
385 - throw new Error(
386 - 'experimental_subAgent() target must be "claude", "codex", or "user" when provided.'
387 - );
388 - }
389 - const inputSchema = options.schema ?? options.jsonSchema;
390 - let structuredSchema: Record<string, unknown> | undefined;
391 - let zodSchema: z.ZodType | undefined;
392 - if (inputSchema !== undefined) {
393 - if (inputSchema instanceof z.ZodType) {
394 - if (typeof z.toJSONSchema !== 'function') {
395 - throw new Error(
396 - 'experimental_subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.'
397 - );
398 - }
399 - zodSchema = inputSchema;
400 - const generatedSchema = z.toJSONSchema(inputSchema);
401 - structuredSchema = Schema.decodeUnknownSync(JsonObject)(generatedSchema);
402 - } else if (Predicate.isObject(inputSchema)) {
403 - structuredSchema = inputSchema;
404 - } else {
405 - throw new Error('experimental_subAgent() schema must be a Zod schema or JSON Schema object.');
406 - }
407 - }
408 - return {
409 - ...(requestedTarget === undefined ? {} : { target: requestedTarget }),
410 - ...(typeof options.model === 'string' ? { model: options.model } : {}),
411 - ...(options.schema === undefined ? {} : { schema: options.schema }),
412 - ...(options.jsonSchema === undefined ? {} : { jsonSchema: options.jsonSchema }),
413 - ...(structuredSchema === undefined ? {} : { structuredSchema }),
414 - ...(zodSchema === undefined ? {} : { zodSchema }),
415 - };
416 -};
417 -
257 const normalizeProxyToolkit = (toolkit: string) => {
258 if (typeof toolkit !== 'string' || toolkit.trim().length === 0) {
259 throw new Error('proxy() requires a non-empty toolkit string.');
@@ -525,18 +364,12 @@ const createRunHelperLoggers = (params: {
364 writeError(`[perf] ${JSON.stringify(payload)}`);
365 };
366
528 - const shouldStreamHelperLog = (step: string, formattedLine: string | null): boolean => {
529 - if (helperContext.logsOff === true) return false;
530 - if (helperContext.debug === true) return true;
531 - return formattedLine !== null && (step.startsWith('subAgent.') || step.startsWith('agent.'));
532 - };
533 -
367 const helperDebugLog: HelperDebugLog = (step, details = {}) => {
368 const formattedLine = formatHelperDebugEvent(step, details);
369 const elapsedMs = Date.now() - perfDebugStart;
370 const line = formattedLine ?? `[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`;
371 appendRunLogLine(line);
539 - if (shouldStreamHelperLog(step, formattedLine)) {
372 + if (helperContext.debug === true) {
373 writeError(line);
374 }
375 };
@@ -669,7 +502,6 @@ const createCliRunner = (params: {
502 ...debugFlagsToChildEnv({
503 perfDebug: perfDebugEnabled,
504 toolDebug: toolDebugEnabled,
672 - acpOnly: helperContext.acpOnly === true,
505 telemetryDebug: helperContext.telemetryDebug === true,
506 }),
507 };
@@ -824,95 +656,6 @@ const createSearchAndExecuteHelpers = (params: {
656 return { search, execute };
657 };
658
827 -const createExperimentalSubAgent = (params: {
828 - readonly helperContext: RunHelperContext;
829 - readonly helperDebugLog: HelperDebugLog;
830 -}) => {
831 - const { helperContext, helperDebugLog } = params;
832 -
833 - // The parent CLI resolves the master via `detectMasterFromHost` and serializes
834 - // it into `helperContext` (see run.cmd.ts), so a missing or unrecognized value
835 - // deliberately falls back to 'user' instead of re-detecting from this child
836 - // process's environment.
837 - const detectInvokeAgentMaster = (): MasterKind | 'user' => {
838 - if (
839 - helperContext.master === 'claude' ||
840 - helperContext.master === 'codex' ||
841 - helperContext.master === 'user'
842 - ) {
843 - return helperContext.master;
844 - }
845 - return 'user';
846 - };
847 -
848 - const resolveInvokeAgentTarget = (requestedTarget?: string): 'claude' | 'codex' => {
849 - if (requestedTarget === 'claude' || requestedTarget === 'codex') return requestedTarget;
850 - const configuredTarget = readConfiguredExperimentalSubagentTarget(helperContext.cliConfigPath);
851 - if (configuredTarget === 'claude' || configuredTarget === 'codex') return configuredTarget;
852 - const detected = requestedTarget === 'user' ? 'user' : detectInvokeAgentMaster();
853 - if (detected === 'codex' || detected === 'claude') return detected;
854 - if (typeof Bun.which === 'function' && Bun.which('codex')) return 'codex';
855 - if (typeof Bun.which === 'function' && Bun.which('claude')) return 'claude';
856 - throw new Error(
857 - 'experimental_subAgent() could not determine an agent CLI. Current master is user; install codex or claude, or pass { target: "codex" | "claude" }.'
858 - );
859 - };
860 -
861 - const experimentalSubAgentImpl = async (
862 - prompt: string,
863 - options: Record<string, unknown> = {}
864 - ) => {
865 - if (typeof prompt !== 'string' || prompt.trim().length === 0) {
866 - throw new Error('experimental_subAgent() requires a non-empty prompt string.');
867 - }
868 - const logFilePath =
869 - typeof helperContext.runLogFilePath === 'string' && helperContext.runLogFilePath.length > 0
870 - ? helperContext.runLogFilePath
871 - : undefined;
872 - const normalizedOptions = normalizeInvokeAgentOptions(options);
873 - const target = resolveInvokeAgentTarget(normalizedOptions.target);
874 - const master = detectInvokeAgentMaster();
875 - helperDebugLog('subAgent.target', {
876 - requestedTarget: normalizedOptions.target ?? null,
877 - resolvedTarget: target,
878 - master,
879 - });
880 - const response = await invokeAcpSubAgent({
881 - prompt: prompt.trim(),
882 - options: normalizedOptions,
883 - master,
884 - target,
885 - allowedReadRoots: Array.isArray(helperContext.readAccessRoots)
886 - ? helperContext.readAccessRoots
887 - : [],
888 - helperDebugLog,
889 - }).catch(error => {
890 - // Only ACP protocol failures fall back to the legacy sub-agent. A damaged
891 - // install (MissingAcpAdapterAssetsError) is not one of them: its message
892 - // names the repair, and swapping in a different sub-agent implementation
893 - // would hide the fact that the install needs fixing.
894 - if (!isAcpInvokeError(error)) throw error;
895 - if (helperContext.acpOnly === true) throw error;
896 - helperDebugLog('subAgent.acp.fallback', {
897 - target,
898 - code: error.code,
899 - message: error.message,
900 - });
901 - return invokeLegacySubAgent({
902 - prompt: prompt.trim(),
903 - options: normalizedOptions,
904 - master,
905 - target,
906 - helperDebugLog,
907 - });
908 - });
909 - return logFilePath ? { ...response, logFilePath } : response;
910 - };
911 -
912 - Object.defineProperty(experimentalSubAgentImpl, 'schema', { value: experimentalSubAgentSchema });
913 - return experimentalSubAgentImpl;
914 -};
915 -
659 const createProxyHelper = (params: {
660 readonly helperContext: RunHelperContext;
661 readonly composioBaseURL: string;
@@ -1100,9 +843,8 @@ export const installRunHelpers = async ({
843 helperDebugLog,
844 });
845
1103 - const experimentalSubAgentImpl = createExperimentalSubAgent({ helperContext, helperDebugLog });
1104 - Reflect.set(globalThis, 'experimental_subAgent', experimentalSubAgentImpl);
1105 - Reflect.set(globalThis, 'invokeAgent', experimentalSubAgentImpl);
846 + Reflect.set(globalThis, 'experimental_subAgent', removedSubAgent);
847 + Reflect.set(globalThis, 'invokeAgent', removedSubAgent);
848
849 const proxy = createProxyHelper({ helperContext, composioBaseURL, helperDebugLog });
850
ts/packages/cli/src/services/run-subagent-acp.ts deleted
-1008
@@ -1,1008 +0,0 @@
1 -import { createRequire } from 'node:module';
2 -import * as acp from '@agentclientprotocol/sdk';
3 -import * as BunServices from '@effect/platform-bun/BunServices';
4 -import {
5 - Cause,
6 - Config,
7 - Data,
8 - Effect,
9 - Exit,
10 - FileSystem,
11 - Layer,
12 - Option,
13 - Path,
14 - Predicate,
15 - Queue,
16 - Stream,
17 -} from 'effect';
18 -import { ChildProcess as Command } from 'effect/unstable/process';
19 -import type { MasterKind } from 'src/services/master-detector';
20 -import { NodeOs } from 'src/services/node-os';
21 -import {
22 - codexAcpBinaryTargetFor,
23 - hasInstalledRunCompanionModules,
24 - resolveRunCompanionAssetPath,
25 - resolveRunCompanionModulePath,
26 - RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
27 -} from 'src/services/run-companion-modules';
28 -import {
29 - ACP_STRUCTURED_OUTPUT_TOOL_NAME,
30 - AcpInvokeError,
31 - buildStructuredRepairPrompt,
32 - buildStructuredPrompt,
33 - buildStructuredToolPrompt,
34 - finalizeInvokeAgentText,
35 - toInvokeAgentResponse,
36 - unwrapStructuredOutputToolPayload,
37 - validateStructuredOutput,
38 - type HelperDebugLog,
39 - type InvokeAgentNormalizedOptions,
40 - type InvokeAgentResponse,
41 - type InvokeAgentTarget,
42 -} from 'src/services/run-subagent-shared';
43 -
44 -type LegacySetSessionModelConnection = {
45 - readonly unstable_setSessionModel?: (params: {
46 - readonly sessionId: string;
47 - readonly modelId: string;
48 - }) => Promise<unknown>;
49 -};
50 -
51 -type AcpAdapterCommand = {
52 - readonly cmd: readonly [string, ...ReadonlyArray<string>];
53 - readonly env?: Readonly<Record<string, string>>;
54 - readonly source: 'shipped' | 'bundled' | 'which' | 'npx';
55 -};
56 -
57 -// This module is bundled as a standalone `composio run` companion module, so it
58 -// provides its own platform layers instead of assuming the CLI runtime.
59 -const RunSubAgentAcpLive = Layer.mergeAll(BunServices.layer, NodeOs.Default);
60 -
61 -const getLegacySetSessionModel = (
62 - connection: unknown
63 -): LegacySetSessionModelConnection['unstable_setSessionModel'] => {
64 - if (!Predicate.hasProperty(connection, 'unstable_setSessionModel')) {
65 - return undefined;
66 - }
67 - const method = connection.unstable_setSessionModel;
68 - return Predicate.isFunction(method) ? async params => method.call(connection, params) : undefined;
69 -};
70 -
71 -// Bridges the ACP connection's outgoing ndjson writes into an Effect Queue that
72 -// a forked fiber drains into the child's stdin Sink. A bounded queue keeps the
73 -// child's stdin backpressure visible to the ACP writer, and shutting the queue
74 -// down on close/abort ends the stdin stream (EOF) for the child.
75 -const writableStreamFromQueue = (queue: Queue.Queue<Uint8Array>): WritableStream<Uint8Array> =>
76 - new WritableStream<Uint8Array>({
77 - write: chunk => Effect.runPromise(Effect.asVoid(Queue.offer(queue, chunk))),
78 - close: () => Effect.runPromise(Effect.asVoid(Queue.shutdown(queue))),
79 - abort: () => Effect.runPromise(Effect.asVoid(Queue.shutdown(queue))),
80 - });
81 -
82 -/**
83 - * The ACP adapter assets are the lazy tier of the companion install: `composio
84 - * run` no longer requires them at startup, so this is the first place that can
85 - * observe them missing. When a packaged install has lost them, say so with the
86 - * fix instead of silently falling through to an npx download or a 404 from the
87 - * startup repair path.
88 - */
89 -export class MissingAcpAdapterAssetsError extends Data.TaggedError(
90 - 'services/MissingAcpAdapterAssetsError'
91 -)<{
92 - readonly message: string;
93 - readonly target: InvokeAgentTarget;
94 - readonly missingRelativePaths: ReadonlyArray<string>;
95 - readonly installDirectory: string;
96 -}> {
97 - // The error crosses into the user's script as a rejection, so it reports its
98 - // own name rather than the internal `services/`-prefixed tag.
99 - override readonly name = 'MissingAcpAdapterAssetsError';
100 -}
101 -
102 -type ShippedAdapterAsset = {
103 - /** Absolute path to the adapter shipped with this install, when present. */
104 - readonly resolvedPath: string | null;
105 - /**
106 - * Asset paths a complete install ships for this target on this host, relative
107 - * to the install root. Empty when this platform has no shipped adapter at all
108 - * (no codex-acp binary is built for it), which is not a broken install.
109 - */
110 - readonly expectedRelativePaths: ReadonlyArray<string>;
111 -};
112 -
113 -const resolveShippedAdapterAsset = ({
114 - target,
115 - execPath,
116 -}: {
117 - target: InvokeAgentTarget;
118 - execPath: string;
119 -}): Effect.Effect<ShippedAdapterAsset, never, FileSystem.FileSystem | Path.Path> =>
120 - Effect.gen(function* () {
121 - if (target === 'claude') {
122 - return {
123 - resolvedPath: yield* resolveRunCompanionAssetPath({
124 - callerImportMetaUrl: import.meta.url,
125 - execPath,
126 - relativePathFromRoot: 'acp-adapters/claude-code-acp.mjs',
127 - }),
128 - // cli.js has no separate resolution step: the bundled adapter finds it
129 - // through import.meta.url, so name it as part of the requirement.
130 - expectedRelativePaths: RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
131 - };
132 - }
133 -
134 - const binaryTarget = codexAcpBinaryTargetFor({
135 - platform: process.platform,
136 - arch: process.arch,
137 - });
138 - if (!binaryTarget) {
139 - return { resolvedPath: null, expectedRelativePaths: [] };
140 - }
141 -
142 - return {
143 - // Reject a zero-byte placeholder: a foreign-platform slot in the archive
144 - // can never execute, so treat it as absent and fall through.
145 - resolvedPath: yield* resolveRunCompanionAssetPath({
146 - callerImportMetaUrl: import.meta.url,
147 - execPath,
148 - relativePathFromRoot: binaryTarget.relativePath,
149 - requireNonEmpty: true,
150 - }),
151 - expectedRelativePaths: [binaryTarget.relativePath],
152 - };
153 - });
154 -
155 -const missingAcpAdapterAssetsError = ({
156 - target,
157 - installDirectory,
158 - missingRelativePaths,
159 -}: {
160 - target: InvokeAgentTarget;
161 - installDirectory: string;
162 - missingRelativePaths: ReadonlyArray<string>;
163 -}) =>
164 - new MissingAcpAdapterAssetsError({
165 - target,
166 - installDirectory,
167 - missingRelativePaths,
168 - message: [
169 - `This Composio install cannot run a ${target} sub-agent: the ACP adapter files are missing from ${installDirectory}.`,
170 - ...missingRelativePaths.map(relativePath => ` - ${relativePath}`),
171 - `Run 'composio upgrade' to restore them, or reinstall the CLI.`,
172 - ].join('\n'),
173 - });
174 -
175 -const resolveInstalledAdapter = (target: InvokeAgentTarget): string | null => {
176 - const specifier =
177 - target === 'claude'
178 - ? '@zed-industries/claude-code-acp/dist/index.js'
179 - : '@zed-industries/codex-acp/bin/codex-acp.js';
180 - const require = createRequire(import.meta.url);
181 - return Option.getOrNull(Option.liftThrowable(() => require.resolve(specifier))());
182 -};
183 -
184 -export const resolveAcpAdapterCommand = (
185 - target: InvokeAgentTarget,
186 - { execPath = process.execPath }: { readonly execPath?: string } = {}
187 -): Effect.Effect<
188 - AcpAdapterCommand,
189 - MissingAcpAdapterAssetsError,
190 - FileSystem.FileSystem | Path.Path
191 -> =>
192 - Effect.gen(function* () {
193 - const path = yield* Path.Path;
194 - const binary = target === 'claude' ? 'claude-code-acp' : 'codex-acp';
195 - const packageName =
196 - target === 'claude' ? '@zed-industries/claude-code-acp' : '@zed-industries/codex-acp';
197 -
198 - // 1. Prefer shipped companion assets next to the CLI binary / dist bundle.
199 - const shipped = yield* resolveShippedAdapterAsset({ target, execPath });
200 - if (shipped.resolvedPath) {
201 - if (target === 'codex') {
202 - return {
203 - cmd: [shipped.resolvedPath],
204 - source: 'shipped',
205 - } satisfies AcpAdapterCommand;
206 - }
207 -
208 - return {
209 - cmd: [execPath, shipped.resolvedPath],
210 - env: {
211 - BUN_BE_BUN: '1',
212 - },
213 - source: 'shipped',
214 - } satisfies AcpAdapterCommand;
215 - }
216 -
217 - // A packaged install ships both the companion wrappers and the adapters. If
218 - // the wrappers are there and the adapters are not, the install is damaged —
219 - // report the repair instead of quietly downloading an adapter through npx.
220 - // A source checkout has no wrappers next to `bun`, so it keeps falling back.
221 - if (
222 - shipped.expectedRelativePaths.length > 0 &&
223 - (yield* hasInstalledRunCompanionModules(execPath))
224 - ) {
225 - return yield* missingAcpAdapterAssetsError({
226 - target,
227 - installDirectory: path.dirname(execPath),
228 - missingRelativePaths: shipped.expectedRelativePaths,
229 - });
230 - }
231 -
232 - // 2. Try the installed dependency bundle next (no npx overhead).
233 - const bundled = resolveInstalledAdapter(target);
234 - if (bundled) {
235 - return {
236 - cmd: [execPath, bundled],
237 - env: {
238 - BUN_BE_BUN: '1',
239 - },
240 - source: 'bundled',
241 - } satisfies AcpAdapterCommand;
242 - }
243 -
244 - // 3. Check if the binary is on PATH.
245 - if (typeof Bun !== 'undefined' && typeof Bun.which === 'function') {
246 - const resolved = Bun.which(binary);
247 - if (resolved) {
248 - return {
249 - cmd: [resolved],
250 - source: 'which',
251 - } satisfies AcpAdapterCommand;
252 - }
253 - }
254 -
255 - // 4. Fall back to npx.
256 - return {
257 - cmd: [process.platform === 'win32' ? 'npx.cmd' : 'npx', '-y', packageName],
258 - source: 'npx',
259 - } satisfies AcpAdapterCommand;
260 - });
261 -
262 -const chunkFlushPattern = /[\s,.;:!?)\]}"]$/;
263 -const resolveStructuredOutputMcpModulePath = resolveRunCompanionModulePath({
264 - callerImportMetaUrl: import.meta.url,
265 - execPath: process.execPath,
266 - relativeNoExtensionFromCaller: './run-subagent-output-mcp',
267 -});
268 -
269 -const collectToolCallPaths = (
270 - value: unknown,
271 - results: Set<string>,
272 - pathApi: Path.Path,
273 - homedir: string,
274 - parentKey?: string
275 -): void => {
276 - if (typeof value === 'string') {
277 - const key = parentKey?.toLowerCase() ?? '';
278 - if (
279 - key === 'path' ||
280 - key === 'file_path' ||
281 - key === 'directory' ||
282 - key.endsWith('_path') ||
283 - key.endsWith('_directory')
284 - ) {
285 - results.add(value);
286 - } else if (key === 'command' || key === 'cmd') {
287 - for (const candidatePath of extractPathsFromCommandText(value, pathApi, homedir)) {
288 - results.add(candidatePath);
289 - }
290 - }
291 - return;
292 - }
293 -
294 - if (Array.isArray(value)) {
295 - const key = parentKey?.toLowerCase() ?? '';
296 - if (
297 - key === 'paths' ||
298 - key === 'directories' ||
299 - key.endsWith('_paths') ||
300 - key.endsWith('_directories')
301 - ) {
302 - for (const entry of value) {
303 - if (typeof entry === 'string') {
304 - results.add(entry);
305 - }
306 - }
307 - return;
308 - }
309 -
310 - for (const entry of value) {
311 - collectToolCallPaths(entry, results, pathApi, homedir);
312 - }
313 - return;
314 - }
315 -
316 - if (!value || typeof value !== 'object') {
317 - return;
318 - }
319 -
320 - for (const [key, nestedValue] of Object.entries(value)) {
321 - collectToolCallPaths(nestedValue, results, pathApi, homedir, key);
322 - }
323 -};
324 -
325 -const extractPathsFromCommandText = (
326 - command: string,
327 - pathApi: Path.Path,
328 - homedir: string
329 -): ReadonlyArray<string> => {
330 - const results = new Set<string>();
331 - const matches = command.matchAll(/(^|[\s"'`])((?:~\/|\/)[^\s"'`|&;<>]+)/g);
332 - for (const match of matches) {
333 - const rawPath = match[2]?.trim();
334 - if (!rawPath) {
335 - continue;
336 - }
337 -
338 - results.add(rawPath.startsWith('~/') ? pathApi.join(homedir, rawPath.slice(2)) : rawPath);
339 - }
340 -
341 - return [...results];
342 -};
343 -
344 -const extractToolCallPaths = (
345 - toolCall: Pick<acp.RequestPermissionRequest, 'toolCall'>['toolCall'],
346 - pathApi: Path.Path,
347 - homedir: string
348 -): ReadonlyArray<string> => {
349 - const paths = new Set<string>();
350 - for (const location of toolCall.locations ?? []) {
351 - if (typeof location.path === 'string' && location.path.length > 0) {
352 - paths.add(location.path);
353 - }
354 - }
355 -
356 - collectToolCallPaths(toolCall.rawInput, paths, pathApi, homedir);
357 - if (typeof toolCall.title === 'string') {
358 - for (const candidatePath of extractPathsFromCommandText(toolCall.title, pathApi, homedir)) {
359 - paths.add(candidatePath);
360 - }
361 - }
362 - return [...paths];
363 -};
364 -
365 -export const selectPermissionOutcome = (
366 - params: Pick<acp.RequestPermissionRequest, 'options' | 'toolCall'>,
367 - _allowedReadRoots: ReadonlyArray<string> = []
368 -): acp.RequestPermissionResponse => {
369 - const allowOnce =
370 - params.options.find(option => option.kind === 'allow_always') ??
371 - params.options.find(option => option.kind === 'allow_once');
372 - const rejectOption =
373 - params.options.find(option => option.kind === 'reject_once') ??
374 - params.options.find(option => option.kind === 'reject_always');
375 -
376 - // Intentionally permissive for `composio run` experimental_subAgent sessions. The user is
377 - // explicitly opting into local tool access, so prefer broad ACP approval over
378 - // heuristic rejections that strand the agent mid-task.
379 - if (allowOnce) {
380 - return {
381 - outcome: {
382 - outcome: 'selected',
383 - optionId: allowOnce.optionId,
384 - },
385 - };
386 - }
387 -
388 - if (rejectOption) {
389 - return {
390 - outcome: {
391 - outcome: 'selected',
392 - optionId: rejectOption.optionId,
393 - },
394 - };
395 - }
396 -
397 - return {
398 - outcome: {
399 - outcome: 'cancelled',
400 - },
401 - };
402 -};
403 -
404 -export class BufferedChunkLogger {
405 - private buffer = '';
406 -
407 - constructor(
408 - private readonly step: 'subAgent.acp.message' | 'subAgent.acp.thought',
409 - private readonly helperDebugLog: HelperDebugLog
410 - ) {}
411 -
412 - push(text: string): void {
413 - this.buffer += text;
414 - this.flushCompletedLines();
415 - this.flushWhenReadable();
416 - }
417 -
418 - flush(): void {
419 - this.emit(this.buffer);
420 - this.buffer = '';
421 - }
422 -
423 - private flushCompletedLines(): void {
424 - let newlineIndex = this.buffer.indexOf('\n');
425 - while (newlineIndex !== -1) {
426 - const line = this.buffer.slice(0, newlineIndex);
427 - this.emit(line);
428 - this.buffer = this.buffer.slice(newlineIndex + 1);
429 - newlineIndex = this.buffer.indexOf('\n');
430 - }
431 - }
432 -
433 - private flushWhenReadable(): void {
434 - if (this.buffer.length < 48) {
435 - return;
436 - }
437 -
438 - if (!chunkFlushPattern.test(this.buffer)) {
439 - return;
440 - }
441 -
442 - this.emit(this.buffer);
443 - this.buffer = '';
444 - }
445 -
446 - private emit(text: string): void {
447 - const normalized = text.replace(/\s+/g, ' ').trim();
448 - if (!normalized) {
449 - return;
450 - }
451 -
452 - this.helperDebugLog(this.step, {
453 - text: normalized,
454 - });
455 - }
456 -}
457 -
458 -class RunSubAgentClient {
459 - private readonly textChunks: string[] = [];
460 - private readonly messageLogger: BufferedChunkLogger;
461 - private readonly thoughtLogger: BufferedChunkLogger;
462 -
463 - constructor(
464 - private readonly helperDebugLog: HelperDebugLog,
465 - private readonly allowedReadRoots: ReadonlyArray<string>,
466 - private readonly pathApi: Path.Path,
467 - private readonly homedir: string
468 - ) {
469 - this.messageLogger = new BufferedChunkLogger('subAgent.acp.message', helperDebugLog);
470 - this.thoughtLogger = new BufferedChunkLogger('subAgent.acp.thought', helperDebugLog);
471 - }
472 -
473 - async requestPermission(
474 - params: acp.RequestPermissionRequest
475 - ): Promise<acp.RequestPermissionResponse> {
476 - const requestedPaths = extractToolCallPaths(params.toolCall, this.pathApi, this.homedir);
477 - const decision = selectPermissionOutcome(params, this.allowedReadRoots);
478 - this.helperDebugLog('subAgent.acp.permission', {
479 - toolCallId: params.toolCall.toolCallId,
480 - title: params.toolCall.title ?? null,
481 - kind: params.toolCall.kind ?? null,
482 - locations: params.toolCall.locations?.map(location => location.path) ?? [],
483 - requestedPaths,
484 - allowedReadRoots: this.allowedReadRoots,
485 - selectedOptionId: decision.outcome.outcome === 'selected' ? decision.outcome.optionId : null,
486 - options: params.options.map(option => option.kind),
487 - });
488 -
489 - return decision;
490 - }
491 -
492 - async sessionUpdate(params: acp.SessionNotification): Promise<void> {
493 - const update = params.update;
494 - if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') {
495 - this.textChunks.push(update.content.text);
496 - this.messageLogger.push(update.content.text);
497 - return;
498 - }
499 -
500 - if (update.sessionUpdate === 'agent_thought_chunk' && update.content.type === 'text') {
501 - this.thoughtLogger.push(update.content.text);
502 - return;
503 - }
504 -
505 - if (update.sessionUpdate === 'tool_call') {
506 - this.helperDebugLog('subAgent.acp.tool_call', {
507 - title: update.title,
508 - kind: update.kind ?? null,
509 - status: update.status ?? null,
510 - locations: update.locations?.map(location => location.path) ?? [],
511 - });
512 - return;
513 - }
514 -
515 - if (update.sessionUpdate === 'tool_call_update') {
516 - this.helperDebugLog('subAgent.acp.tool_call_update', {
517 - toolCallId: update.toolCallId,
518 - title: update.title ?? null,
519 - kind: update.kind ?? null,
520 - status: update.status ?? null,
521 - locations: update.locations?.map(location => location.path) ?? [],
522 - rawOutput: update.rawOutput ?? null,
523 - });
524 - return;
525 - }
526 -
527 - if (update.sessionUpdate === 'plan') {
528 - this.helperDebugLog('subAgent.acp.plan', {
529 - entries: update.entries.map(entry => ({
530 - status: entry.status,
531 - priority: entry.priority ?? null,
532 - content: entry.content,
533 - })),
534 - });
535 - return;
536 - }
537 -
538 - this.helperDebugLog('subAgent.acp.update', {
539 - type: update.sessionUpdate,
540 - });
541 - }
542 -
543 - getText(): string {
544 - this.messageLogger.flush();
545 - this.thoughtLogger.flush();
546 - return this.textChunks.join('');
547 - }
548 -}
549 -
550 -const createFallbackError = (
551 - code: ConstructorParameters<typeof AcpInvokeError>[0],
552 - message: string,
553 - cause?: unknown
554 -): AcpInvokeError => new AcpInvokeError(code, message, cause === undefined ? undefined : { cause });
555 -
556 -type StructuredOutputMcpContext = {
557 - readonly mcpServer: acp.McpServerStdio;
558 - readonly resultFilePath: string;
559 - readonly cleanup: Effect.Effect<void>;
560 -};
561 -
562 -export const createStructuredOutputMcpContext = ({
563 - options,
564 - helperDebugLog,
565 -}: {
566 - options: InvokeAgentNormalizedOptions;
567 - helperDebugLog: HelperDebugLog;
568 -}): Effect.Effect<StructuredOutputMcpContext | null, never, FileSystem.FileSystem | Path.Path> =>
569 - Effect.gen(function* () {
570 - const structuredSchema = options.structuredSchema;
571 - if (!structuredSchema) {
572 - return null;
573 - }
574 -
575 - const fs = yield* FileSystem.FileSystem;
576 - const pathApi = yield* Path.Path;
577 - const structuredOutputMcpModulePath = yield* resolveStructuredOutputMcpModulePath;
578 -
579 - const build = Effect.gen(function* () {
580 - // Keep this on an OS temp dir for now. Repointing MCP schema/result files into
581 - // session artifacts needs a broader bundling + run-companion test pass so we
582 - // don't break structured sub-agent output in packaged CLI builds.
583 - const tempDirectory = yield* fs.makeTempDirectory({
584 - prefix: 'composio-subagent-output-mcp-',
585 - });
586 - const removeTempDirectory = Effect.ignore(
587 - fs.remove(tempDirectory, { recursive: true, force: true })
588 - );
589 - const schemaFilePath = pathApi.join(tempDirectory, 'schema.json');
590 - const resultFilePath = pathApi.join(tempDirectory, 'result.json');
591 - yield* Effect.try({
592 - try: () => JSON.stringify(structuredSchema),
593 - catch: error => error,
594 - }).pipe(
595 - Effect.flatMap(schemaJson => fs.writeFileString(schemaFilePath, schemaJson)),
596 - Effect.tapError(() => removeTempDirectory)
597 - );
598 -
599 - helperDebugLog('subAgent.acp.structured_output_tool', {
600 - modulePath: structuredOutputMcpModulePath,
601 - schemaFilePath,
602 - resultFilePath,
603 - });
604 -
605 - const context: StructuredOutputMcpContext = {
606 - mcpServer: {
607 - name: 'composio-structured-output',
608 - command: process.execPath,
609 - args: [
610 - structuredOutputMcpModulePath,
611 - '--schema-file',
612 - schemaFilePath,
613 - '--result-file',
614 - resultFilePath,
615 - ],
616 - env: [
617 - {
618 - name: 'BUN_BE_BUN',
619 - value: '1',
620 - },
621 - ],
622 - },
623 - resultFilePath,
624 - cleanup: removeTempDirectory,
625 - };
626 - return context;
627 - });
628 -
629 - return yield* build.pipe(
630 - Effect.catch(error =>
631 - Effect.sync(() => {
632 - helperDebugLog('subAgent.acp.structured_output_tool_failed', {
633 - error: error instanceof Error ? error.message : String(error),
634 - modulePath: structuredOutputMcpModulePath,
635 - });
636 - return null;
637 - })
638 - )
639 - );
640 - });
641 -
642 -const maybeReadStructuredOutputFromTool = ({
643 - context,
644 - options,
645 - helperDebugLog,
646 -}: {
647 - context: StructuredOutputMcpContext | null;
648 - options: InvokeAgentNormalizedOptions;
649 - helperDebugLog: HelperDebugLog;
650 -}): Effect.Effect<unknown, never, FileSystem.FileSystem> =>
651 - Effect.gen(function* () {
652 - const structuredSchema = options.structuredSchema;
653 - if (!context || !structuredSchema) {
654 - return undefined;
655 - }
656 -
657 - const fs = yield* FileSystem.FileSystem;
658 - const resultFileExists = yield* fs
659 - .exists(context.resultFilePath)
660 - .pipe(Effect.orElseSucceed(() => false));
661 - if (!resultFileExists) {
662 - return undefined;
663 - }
664 -
665 - const read = fs.readFileString(context.resultFilePath).pipe(
666 - Effect.flatMap(rawText =>
667 - Effect.try({
668 - try: () => {
669 - const rawPayload: unknown = JSON.parse(rawText);
670 - const parsed = unwrapStructuredOutputToolPayload(rawPayload, structuredSchema);
671 - helperDebugLog('subAgent.acp.structured_output_tool_result', {
672 - resultFilePath: context.resultFilePath,
673 - });
674 - return validateStructuredOutput(parsed, options);
675 - },
676 - catch: error => error,
677 - })
678 - )
679 - );
680 -
681 - return yield* read.pipe(
682 - Effect.catch(error =>
683 - Effect.sync<unknown>(() => {
684 - helperDebugLog('subAgent.acp.structured_output_tool_result_failed', {
685 - resultFilePath: context.resultFilePath,
686 - error: error instanceof Error ? error.message : String(error),
687 - });
688 - return undefined;
689 - })
690 - )
691 - );
692 - });
693 -
694 -type InvokeAcpSubAgentParams = {
695 - prompt: string;
696 - options: InvokeAgentNormalizedOptions;
697 - master: MasterKind;
698 - target: InvokeAgentTarget;
699 - allowedReadRoots: ReadonlyArray<string>;
700 - helperDebugLog: HelperDebugLog;
701 -};
702 -
703 -// Turns the accumulated agent text into the final response, retrying once with
704 -// a structured-repair prompt when a structured schema was requested and the
705 -// first finalize attempt failed. Non-structured failures propagate unchanged.
706 -const finalizeWithStructuredRepair = ({
707 - client,
708 - options,
709 - master,
710 - target,
711 - structuredOutputMcp,
712 - helperDebugLog,
713 - runPrompt,
714 - stderrSuffix,
715 -}: {
716 - client: RunSubAgentClient;
717 - options: InvokeAgentNormalizedOptions;
718 - master: MasterKind;
719 - target: InvokeAgentTarget;
720 - structuredOutputMcp: StructuredOutputMcpContext | null;
721 - helperDebugLog: HelperDebugLog;
722 - runPrompt: (text: string) => Effect.Effect<acp.PromptResponse, AcpInvokeError>;
723 - stderrSuffix: () => string;
724 -}): Effect.Effect<InvokeAgentResponse, unknown, FileSystem.FileSystem> => {
725 - const finalizeText = Effect.try({
726 - try: () => finalizeInvokeAgentText(client.getText(), options),
727 - catch: error => error,
728 - });
729 -
730 - return finalizeText.pipe(
731 - Effect.map(payload => toInvokeAgentResponse(master, target, payload)),
732 - Effect.catch(error => {
733 - const structuredSchema = options.structuredSchema;
734 - if (!structuredSchema) {
735 - return Effect.fail(error);
736 - }
737 -
738 - return Effect.gen(function* () {
739 - helperDebugLog('subAgent.acp.structured_repair', {
740 - target,
741 - reason: error instanceof Error ? error.message : String(error),
742 - });
743 -
744 - const repairResponse = yield* runPrompt(
745 - buildStructuredRepairPrompt(
746 - structuredSchema,
747 - structuredOutputMcp ? ACP_STRUCTURED_OUTPUT_TOOL_NAME : undefined
748 - )
749 - );
750 -
751 - if (repairResponse.stopReason === 'cancelled') {
752 - return yield* Effect.fail(
753 - createFallbackError(
754 - 'prompt_failed',
755 - `${target} ACP repair prompt was cancelled${stderrSuffix()}`
756 - )
757 - );
758 - }
759 -
760 - const repairedStructuredOutput = yield* maybeReadStructuredOutputFromTool({
761 - context: structuredOutputMcp,
762 - options,
763 - helperDebugLog,
764 - });
765 - if (repairedStructuredOutput !== undefined) {
766 - return toInvokeAgentResponse(master, target, {
767 - result: null,
768 - structuredOutput: repairedStructuredOutput,
769 - });
770 - }
771 -
772 - const payload = yield* finalizeText;
773 - return toInvokeAgentResponse(master, target, payload);
774 - });
775 - })
776 - );
777 -};
778 -
779 -const invokeAcpSubAgentEffect = ({
780 - prompt,
781 - options,
782 - master,
783 - target,
784 - allowedReadRoots,
785 - helperDebugLog,
786 -}: InvokeAcpSubAgentParams) =>
787 - Effect.gen(function* () {
788 - const pathApi = yield* Path.Path;
789 - const nodeOs = yield* NodeOs;
790 -
791 - const structuredOutputMcp = yield* createStructuredOutputMcpContext({
792 - options,
793 - helperDebugLog,
794 - });
795 - yield* Effect.addFinalizer(() =>
796 - structuredOutputMcp ? structuredOutputMcp.cleanup : Effect.void
797 - );
798 -
799 - const resolved = yield* resolveAcpAdapterCommand(target);
800 - helperDebugLog('subAgent.acp.resolve', {
801 - target,
802 - source: resolved.source,
803 - command: resolved.cmd[0],
804 - args: resolved.cmd.slice(1),
805 - });
806 -
807 - // The Claude Code CLI refuses to start when it inherits CLAUDECODE=1. The
808 - // platform Command executor inherits the parent environment, so the
809 - // variable cannot be dropped; mask it with an empty string instead —
810 - // falsy and distinct from the guarded "1" — only when the parent has it set.
811 - const claudeCode = yield* Config.option(Config.String('CLAUDECODE'));
812 - const childEnv: Record<string, string> = {
813 - ...(Option.isSome(claudeCode) ? { CLAUDECODE: '' } : {}),
814 - ...(resolved.env ?? {}),
815 - };
816 -
817 - const stdinQueue = yield* Queue.bounded<Uint8Array>(16);
818 - const [executable, ...commandArgs] = resolved.cmd;
819 - // extendEnv keeps the inherited environment (PATH included) underneath the
820 - // per-child overrides, matching the previous spawn semantics.
821 - const command = Command.make(executable, commandArgs, { env: childEnv, extendEnv: true });
822 -
823 - const child = yield* command.pipe(
824 - Effect.mapError(error =>
825 - createFallbackError('spawn_failed', `Failed to spawn ${target} ACP adapter.`, error)
826 - )
827 - );
828 -
829 - // Teardown parity with the previous finally block: SIGTERM the child, wait
830 - // for it to exit for at most 200ms, then SIGKILL it if it is still alive.
831 - // Registered after the spawn so it runs before the spawner's own
832 - // scope finalizer (which would otherwise await a stubborn child forever).
833 - yield* Effect.addFinalizer(() =>
834 - Effect.gen(function* () {
835 - yield* Effect.interruptible(child.kill({ killSignal: 'SIGTERM' })).pipe(
836 - Effect.timeout('200 millis'),
837 - Effect.ignore
838 - );
839 - const stillRunning = yield* child.isRunning.pipe(Effect.orElseSucceed(() => false));
840 - if (stillRunning) {
841 - yield* Effect.ignore(child.kill({ killSignal: 'SIGKILL' }));
842 - }
843 - })
844 - );
845 -
846 - let stderrText = '';
847 - yield* Stream.runForEach(Stream.decodeText(child.stderr), text =>
848 - Effect.sync(() => {
849 - stderrText += text;
850 - })
851 - ).pipe(Effect.ignore, Effect.forkScoped);
852 - const stderrSuffix = () => (stderrText.trim() ? `: ${stderrText.trim()}` : '');
853 -
854 - yield* Stream.run(Stream.fromQueue(stdinQueue), child.stdin).pipe(
855 - Effect.ignore,
856 - Effect.forkScoped
857 - );
858 -
859 - const client = new RunSubAgentClient(
860 - helperDebugLog,
861 - [...new Set(allowedReadRoots.map(root => pathApi.resolve(root)))],
862 - pathApi,
863 - nodeOs.homedir
864 - );
865 - const stream = acp.ndJsonStream(
866 - writableStreamFromQueue(stdinQueue),
867 - Stream.toReadableStream(child.stdout)
868 - );
869 - const connection = new acp.ClientSideConnection(() => client, stream);
870 -
871 - const initialized = yield* Effect.tryPromise({
872 - try: () =>
873 - connection.initialize({
874 - protocolVersion: acp.PROTOCOL_VERSION,
875 - clientCapabilities: {},
876 - }),
877 - catch: error =>
878 - createFallbackError(
879 - 'initialize_failed',
880 - `${target} ACP initialize failed${stderrSuffix()}`,
881 - error
882 - ),
883 - });
884 -
885 - helperDebugLog('subAgent.acp.initialized', {
886 - target,
887 - protocolVersion: initialized.protocolVersion,
888 - });
889 -
890 - const session = yield* Effect.tryPromise({
891 - try: () =>
892 - connection.newSession({
893 - cwd: process.cwd(),
894 - mcpServers: structuredOutputMcp ? [structuredOutputMcp.mcpServer] : [],
895 - }),
896 - catch: error =>
897 - createFallbackError(
898 - 'session_failed',
899 - `${target} ACP session creation failed${stderrSuffix()}`,
900 - error
901 - ),
902 - });
903 -
904 - helperDebugLog('subAgent.acp.session', {
905 - target,
906 - sessionId: session.sessionId,
907 - });
908 -
909 - if (typeof options.model === 'string' && options.model.trim().length > 0) {
910 - const model = options.model.trim();
911 - const setSessionModel = getLegacySetSessionModel(connection);
912 - const modelFailure =
913 - setSessionModel === undefined
914 - ? 'ACP session model selection is not supported by this connection'
915 - : yield* Effect.tryPromise({
916 - try: () => setSessionModel({ sessionId: session.sessionId, modelId: model }),
917 - catch: error => (error instanceof Error ? error.message : String(error)),
918 - }).pipe(
919 - Effect.match({
920 - onSuccess: (): string | undefined => undefined,
921 - onFailure: message => message,
922 - })
923 - );
924 -
925 - helperDebugLog('subAgent.acp.model', {
926 - target,
927 - model,
928 - ...(modelFailure === undefined
929 - ? { applied: true }
930 - : { applied: false, error: modelFailure }),
931 - });
932 - }
933 -
934 - const promptText =
935 - options.structuredSchema && structuredOutputMcp
936 - ? buildStructuredToolPrompt(
937 - prompt,
938 - options.structuredSchema,
939 - ACP_STRUCTURED_OUTPUT_TOOL_NAME
940 - )
941 - : buildStructuredPrompt(prompt, options.structuredSchema);
942 - const runPrompt = (text: string) =>
943 - Effect.tryPromise({
944 - try: () =>
945 - connection.prompt({
946 - sessionId: session.sessionId,
947 - prompt: [{ type: 'text', text }],
948 - }),
949 - catch: error =>
950 - connection.signal.aborted
951 - ? createFallbackError(
952 - 'connection_closed',
953 - `${target} ACP connection closed before prompt completion${stderrSuffix()}`,
954 - error
955 - )
956 - : createFallbackError(
957 - 'prompt_failed',
958 - `${target} ACP prompt failed${stderrSuffix()}`,
959 - error
960 - ),
961 - });
962 -
963 - const response = yield* runPrompt(promptText);
964 -
965 - if (response.stopReason === 'cancelled') {
966 - return yield* Effect.fail(
967 - createFallbackError('prompt_failed', `${target} ACP prompt was cancelled${stderrSuffix()}`)
968 - );
969 - }
970 -
971 - const structuredOutput = yield* maybeReadStructuredOutputFromTool({
972 - context: structuredOutputMcp,
973 - options,
974 - helperDebugLog,
975 - });
976 - if (structuredOutput !== undefined) {
977 - return toInvokeAgentResponse(master, target, {
978 - result: null,
979 - structuredOutput,
980 - });
981 - }
982 -
983 - return yield* finalizeWithStructuredRepair({
984 - client,
985 - options,
986 - master,
987 - target,
988 - structuredOutputMcp,
989 - helperDebugLog,
990 - runPrompt,
991 - stderrSuffix,
992 - });
993 - });
994 -
995 -export const invokeAcpSubAgent = async (
996 - params: InvokeAcpSubAgentParams
997 -): Promise<InvokeAgentResponse> => {
998 - const exit = await Effect.runPromiseExit(
999 - invokeAcpSubAgentEffect(params).pipe(Effect.scoped, Effect.provide(RunSubAgentAcpLive))
1000 - );
1001 - if (Exit.isSuccess(exit)) {
1002 - return exit.value;
1003 - }
1004 -
1005 - // Surface the original error instance (callers branch on AcpInvokeError and
1006 - // its code), not a FiberFailure wrapper.
1007 - throw Cause.squash(exit.cause);
1008 -};
ts/packages/cli/src/services/run-subagent-legacy.ts deleted
-198
@@ -1,198 +0,0 @@
1 -import * as BunServices from '@effect/platform-bun/BunServices';
2 -import { Cause, Data, Effect, Exit, FileSystem, Path, Predicate, Stream } from 'effect';
3 -import { ChildProcess as Command } from 'effect/unstable/process';
4 -import type { MasterKind } from 'src/services/master-detector';
5 -import {
6 - parseJson,
7 - toInvokeAgentResponse,
8 - type HelperDebugLog,
9 - type InvokeAgentNormalizedOptions,
10 - type InvokeAgentResponse,
11 - type InvokeAgentTarget,
12 -} from 'src/services/run-subagent-shared';
13 -
14 -class SubAgentCommandFailedError extends Data.TaggedError('SubAgentCommandFailedError')<{
15 - readonly command: string;
16 - readonly exitCode: number;
17 - readonly details: string;
18 -}> {
19 - override get message(): string {
20 - const suffix = this.details ? `: ${this.details}` : '';
21 - return `${this.command} failed with exit code ${this.exitCode}${suffix}`;
22 - }
23 -}
24 -
25 -class SubAgentNonJsonOutputError extends Data.TaggedError('SubAgentNonJsonOutputError')<{
26 - readonly target: InvokeAgentTarget;
27 -}> {
28 - override get message(): string {
29 - return `${this.target} returned non-JSON output in experimental_subAgent().`;
30 - }
31 -}
32 -
33 -const collectUtf8Text = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
34 - Stream.mkString(Stream.decodeText(stream));
35 -
36 -const runExternalCommandText = (
37 - cmd: readonly [string, ...Array<string>],
38 - helperDebugLog: HelperDebugLog
39 -) =>
40 - Effect.gen(function* () {
41 - const [executable, ...commandArgs] = cmd;
42 - helperDebugLog('agent.spawn', { command: cmd[0], args: cmd.slice(1) });
43 -
44 - // The child never reads interactive input: hand it an immediately-closed
45 - // stdin pipe (EOF), matching the previous `stdio: ['ignore', ...]` spawn.
46 - const command = Command.make(executable, commandArgs, { stdin: Stream.empty });
47 -
48 - const [exitCode, stdout, stderr] = yield* Effect.scoped(
49 - Effect.flatMap(command, child =>
50 - Effect.all([child.exitCode, collectUtf8Text(child.stdout), collectUtf8Text(child.stderr)], {
51 - concurrency: 3,
52 - })
53 - )
54 - );
55 -
56 - if (exitCode !== 0) {
57 - const details = stderr.trim() || stdout.trim();
58 - helperDebugLog('agent.error', {
59 - command: cmd[0],
60 - exitCode,
61 - stderr: stderr.trim() || undefined,
62 - });
63 - return yield* new SubAgentCommandFailedError({ command: executable, exitCode, details });
64 - }
65 -
66 - helperDebugLog('agent.done', {
67 - command: cmd[0],
68 - exitCode,
69 - stdoutBytes: stdout.length,
70 - stderrBytes: stderr.length,
71 - });
72 - return { stdout, stderr, exitCode };
73 - });
74 -
75 -const invokeClaudeLegacy = (
76 - prompt: string,
77 - options: InvokeAgentNormalizedOptions,
78 - master: MasterKind,
79 - helperDebugLog: HelperDebugLog
80 -) =>
81 - Effect.gen(function* () {
82 - helperDebugLog('subAgent.prepare', {
83 - target: 'claude',
84 - transport: 'legacy',
85 - hasSchema: options.structuredSchema !== undefined,
86 - });
87 -
88 - const args: [string, ...Array<string>] = ['claude', '--bare', '-p', '--output-format', 'json'];
89 - if (typeof options.model === 'string' && options.model.trim().length > 0) {
90 - args.push('--model', options.model.trim());
91 - }
92 - if (options.structuredSchema !== undefined) {
93 - args.push('--json-schema', JSON.stringify(options.structuredSchema));
94 - }
95 - args.push(prompt);
96 -
97 - const result = yield* runExternalCommandText(args, helperDebugLog);
98 - const parsed = parseJson(result.stdout.trim());
99 - if (!Predicate.isObject(parsed)) {
100 - return yield* new SubAgentNonJsonOutputError({ target: 'claude' });
101 - }
102 -
103 - const payload =
104 - options.structuredSchema !== undefined
105 - ? {
106 - result: null,
107 - structuredOutput: parsed.structured_output ?? null,
108 - }
109 - : {
110 - result: typeof parsed.result === 'string' ? parsed.result : null,
111 - structuredOutput: null,
112 - };
113 -
114 - return toInvokeAgentResponse(master, 'claude', payload);
115 - });
116 -
117 -const invokeCodexLegacy = (
118 - prompt: string,
119 - options: InvokeAgentNormalizedOptions,
120 - master: MasterKind,
121 - helperDebugLog: HelperDebugLog
122 -) =>
123 - Effect.gen(function* () {
124 - const fs = yield* FileSystem.FileSystem;
125 - const path = yield* Path.Path;
126 -
127 - const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: 'composio-invoke-agent-' });
128 - const outputPath = path.join(tempDir, 'last-message.txt');
129 - const args: [string, ...Array<string>] = [
130 - 'codex',
131 - 'exec',
132 - '--skip-git-repo-check',
133 - '--sandbox',
134 - 'read-only',
135 - '-o',
136 - outputPath,
137 - ];
138 -
139 - helperDebugLog('subAgent.prepare', {
140 - target: 'codex',
141 - transport: 'legacy',
142 - hasSchema: options.structuredSchema !== undefined,
143 - });
144 -
145 - if (typeof options.model === 'string' && options.model.trim().length > 0) {
146 - args.push('--model', options.model.trim());
147 - }
148 -
149 - if (options.structuredSchema !== undefined) {
150 - const schemaPath = path.join(tempDir, 'schema.json');
151 - yield* fs.writeFileString(schemaPath, JSON.stringify(options.structuredSchema));
152 - args.push('--output-schema', schemaPath);
153 - }
154 -
155 - args.push(prompt);
156 - yield* runExternalCommandText(args, helperDebugLog);
157 -
158 - const text = (yield* fs.readFileString(outputPath)).trim();
159 - if (options.structuredSchema !== undefined) {
160 - return toInvokeAgentResponse(master, 'codex', {
161 - result: null,
162 - structuredOutput: parseJson(text) ?? null,
163 - });
164 - }
165 -
166 - return toInvokeAgentResponse(master, 'codex', {
167 - result: text,
168 - structuredOutput: null,
169 - });
170 - }).pipe(Effect.scoped);
171 -
172 -export const invokeLegacySubAgent = async ({
173 - prompt,
174 - options,
175 - master,
176 - target,
177 - helperDebugLog,
178 -}: {
179 - prompt: string;
180 - options: InvokeAgentNormalizedOptions;
181 - master: MasterKind;
182 - target: InvokeAgentTarget;
183 - helperDebugLog: HelperDebugLog;
184 -}): Promise<InvokeAgentResponse> => {
185 - const program =
186 - target === 'claude'
187 - ? invokeClaudeLegacy(prompt, options, master, helperDebugLog)
188 - : invokeCodexLegacy(prompt, options, master, helperDebugLog);
189 -
190 - const exit = await Effect.runPromiseExit(Effect.provide(program, BunServices.layer));
191 - if (Exit.isSuccess(exit)) {
192 - return exit.value;
193 - }
194 -
195 - // Surface the original error instance (same message callers matched on
196 - // before), not a FiberFailure wrapper.
197 - throw Cause.squash(exit.cause);
198 -};
ts/packages/cli/src/services/run-subagent-output-mcp.ts deleted
-69
@@ -1,69 +0,0 @@
1 -import process from 'node:process';
2 -import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
3 -import * as FileSystem from 'effect/FileSystem';
4 -import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
5 -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
6 -import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7 -import { Effect } from 'effect';
8 -import {
9 - ACP_STRUCTURED_OUTPUT_TOOL_NAME,
10 - buildStructuredOutputToolSchema,
11 - decodeStructuredSchemaJson,
12 -} from 'src/services/run-subagent-shared';
13 -import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';
14 -
15 -const readFlag = (name: string): string => {
16 - const index = process.argv.indexOf(name);
17 - const value = index >= 0 ? process.argv[index + 1] : undefined;
18 - if (!value) {
19 - throw new Error(`Missing required flag: ${name}`);
20 - }
21 - return value;
22 -};
23 -
24 -const main = async (): Promise<void> => {
25 - const fs = Effect.runSync(FileSystem.FileSystem.pipe(Effect.provide(BunFileSystem.layer)));
26 - const schemaFilePath = readFlag('--schema-file');
27 - const resultFilePath = readFlag('--result-file');
28 - const schemaText = await Effect.runPromise(fs.readFileString(schemaFilePath));
29 - const structuredSchema = decodeStructuredSchemaJson(schemaText);
30 - const toolInputSchema = jsonSchemaToZod(buildStructuredOutputToolSchema(structuredSchema));
31 -
32 - const server = new McpServer({
33 - name: 'composio-subagent-output',
34 - version: '1.0.0',
35 - });
36 -
37 - server.registerTool(
38 - ACP_STRUCTURED_OUTPUT_TOOL_NAME,
39 - {
40 - title: 'Submit structured output',
41 - description:
42 - 'Submit the final structured experimental_subAgent output. Call this exactly once when the task is complete.',
43 - inputSchema: toolInputSchema,
44 - },
45 - async (payload: unknown) => {
46 - await Effect.runPromise(fs.writeFileString(resultFilePath, JSON.stringify(payload)));
47 - return {
48 - content: [
49 - {
50 - type: 'text',
51 - text: 'Structured output captured.',
52 - },
53 - ],
54 - };
55 - }
56 - );
57 -
58 - const transport = new StdioServerTransport();
59 - await server.connect(transport);
60 -};
61 -
62 -void main().catch(error => {
63 - const message = error instanceof Error ? (error.stack ?? error.message) : String(error);
64 - Effect.gen(function* () {
65 - const ui = yield* TerminalUI;
66 - yield* ui.error(message);
67 - }).pipe(Effect.provide(TerminalUILive), Effect.runSync);
68 - process.exit(1);
69 -});
ts/packages/cli/src/services/run-subagent-shared.ts deleted
-401
@@ -1,401 +0,0 @@
1 -import { Option, Predicate, Schema } from 'effect';
2 -import { JsonRecordSchema } from 'src/effects/json';
3 -import type { MasterKind } from 'src/services/master-detector';
4 -
5 -export type InvokeAgentTarget = 'claude' | 'codex';
6 -
7 -export type InvokeAgentNormalizedOptions = {
8 - readonly target?: InvokeAgentTarget | 'user';
9 - readonly model?: string;
10 - readonly schema?: unknown;
11 - readonly jsonSchema?: unknown;
12 - readonly structuredSchema?: Record<string, unknown>;
13 - readonly zodSchema?: {
14 - safeParse: (
15 - value: unknown
16 - ) => { success: true; data: unknown } | { success: false; error: unknown };
17 - };
18 -};
19 -
20 -export type InvokeAgentResponse = {
21 - readonly master: MasterKind;
22 - readonly target: InvokeAgentTarget;
23 - readonly result: string | null;
24 - readonly structuredOutput?: unknown;
25 - readonly logFilePath?: string;
26 -};
27 -
28 -export const ACP_STRUCTURED_OUTPUT_TOOL_NAME = 'submit_structured_output';
29 -export const ACP_STRUCTURED_OUTPUT_WRAPPER_KEY = 'value';
30 -
31 -export type HelperDebugLog = (step: string, details?: Record<string, unknown>) => void;
32 -
33 -export type AcpInvokeFailure =
34 - | 'adapter_not_found'
35 - | 'spawn_failed'
36 - | 'initialize_failed'
37 - | 'session_failed'
38 - | 'prompt_failed'
39 - | 'connection_closed';
40 -
41 -export class AcpInvokeError extends Error {
42 - readonly code: AcpInvokeFailure;
43 -
44 - constructor(code: AcpInvokeFailure, message: string, options?: { cause?: unknown }) {
45 - super(message, options);
46 - this.name = 'AcpInvokeError';
47 - this.code = code;
48 - }
49 -}
50 -
51 -const isAcpInvokeFailure = (value: unknown): value is AcpInvokeFailure =>
52 - value === 'adapter_not_found' ||
53 - value === 'spawn_failed' ||
54 - value === 'initialize_failed' ||
55 - value === 'session_failed' ||
56 - value === 'prompt_failed' ||
57 - value === 'connection_closed';
58 -
59 -export const isAcpInvokeError = (value: unknown): value is AcpInvokeError =>
60 - Predicate.isObject(value) &&
61 - value.name === 'AcpInvokeError' &&
62 - typeof value.message === 'string' &&
63 - isAcpInvokeFailure(value.code);
64 -
65 -export const toInvokeAgentResponse = (
66 - master: MasterKind,
67 - target: InvokeAgentTarget,
68 - payload: Partial<Pick<InvokeAgentResponse, 'result' | 'structuredOutput' | 'logFilePath'>> = {}
69 -): InvokeAgentResponse => ({
70 - master,
71 - target,
72 - result: payload.result ?? null,
73 - ...(payload.structuredOutput === undefined || payload.structuredOutput === null
74 - ? {}
75 - : { structuredOutput: payload.structuredOutput }),
76 - ...(typeof payload.logFilePath === 'string' && payload.logFilePath.length > 0
77 - ? { logFilePath: payload.logFilePath }
78 - : {}),
79 -});
80 -
81 -/**
82 - * Sync JSON probe shared with the non-Effect child-process runtime; `Option`
83 - * is pure data from the already-bundled `effect` package, so it is safe there.
84 - */
85 -const parseJsonOption = (text: string): Option.Option<unknown> =>
86 - Option.liftThrowable((s: string): unknown => JSON.parse(s))(text);
87 -
88 -export const parseJson = (text: string): unknown => {
89 - const value = text.trim();
90 - if (!value) {
91 - return undefined;
92 - }
93 - // Non-JSON sub-agent stdout is returned verbatim by design.
94 - return Option.getOrElse(parseJsonOption(value), (): unknown => value);
95 -};
96 -
97 -const decodeStructuredSchema = Schema.decodeUnknownSync(Schema.fromJsonString(JsonRecordSchema));
98 -
99 -export const decodeStructuredSchemaJson = (text: string): Record<string, unknown> =>
100 - decodeStructuredSchema(text);
101 -
102 -const summarizeValidationError = (error: unknown): string => {
103 - const issues = Predicate.isObject(error) && Array.isArray(error.issues) ? error.issues : [];
104 -
105 - if (issues.length === 0) {
106 - return 'Invalid structured output.';
107 - }
108 -
109 - return issues
110 - .slice(0, 5)
111 - .map(issue => {
112 - if (!Predicate.isObject(issue)) {
113 - return '<root>: Invalid value';
114 - }
115 - const path =
116 - Array.isArray(issue.path) && issue.path.length > 0 ? issue.path.join('.') : '<root>';
117 - const message = typeof issue.message === 'string' ? issue.message : 'Invalid value';
118 - return `${path}: ${message}`;
119 - })
120 - .join('; ');
121 -};
122 -
123 -export const buildStructuredPrompt = (
124 - prompt: string,
125 - structuredSchema?: Record<string, unknown>
126 -): string => {
127 - if (!structuredSchema) {
128 - return prompt;
129 - }
130 -
131 - return [
132 - prompt,
133 - '',
134 - 'Return only a valid JSON value that matches this schema.',
135 - 'Do not include Markdown fences, commentary, or any extra text before or after the JSON.',
136 - JSON.stringify(structuredSchema, null, 2),
137 - ].join('\n');
138 -};
139 -
140 -const isStructuredObjectSchema = (structuredSchema?: Record<string, unknown>): boolean => {
141 - if (!structuredSchema || Array.isArray(structuredSchema)) {
142 - return false;
143 - }
144 -
145 - const schemaType = structuredSchema.type;
146 - if (schemaType === 'object') {
147 - return true;
148 - }
149 -
150 - if (Array.isArray(schemaType) && schemaType.includes('object')) {
151 - return true;
152 - }
153 -
154 - return (
155 - 'properties' in structuredSchema ||
156 - 'required' in structuredSchema ||
157 - 'additionalProperties' in structuredSchema
158 - );
159 -};
160 -
161 -export const buildStructuredOutputToolSchema = (
162 - structuredSchema: Record<string, unknown>
163 -): Record<string, unknown> =>
164 - isStructuredObjectSchema(structuredSchema)
165 - ? structuredSchema
166 - : {
167 - type: 'object',
168 - additionalProperties: false,
169 - required: [ACP_STRUCTURED_OUTPUT_WRAPPER_KEY],
170 - properties: {
171 - [ACP_STRUCTURED_OUTPUT_WRAPPER_KEY]: structuredSchema,
172 - },
173 - };
174 -
175 -export const unwrapStructuredOutputToolPayload = (
176 - payload: unknown,
177 - structuredSchema: Record<string, unknown>
178 -): unknown => {
179 - if (isStructuredObjectSchema(structuredSchema)) {
180 - return payload;
181 - }
182 -
183 - if (Predicate.isObject(payload) && ACP_STRUCTURED_OUTPUT_WRAPPER_KEY in payload) {
184 - return payload[ACP_STRUCTURED_OUTPUT_WRAPPER_KEY];
185 - }
186 -
187 - return payload;
188 -};
189 -
190 -export const buildStructuredToolPrompt = (
191 - prompt: string,
192 - structuredSchema: Record<string, unknown>,
193 - toolName: string
194 -): string => {
195 - const usesWrapper = !isStructuredObjectSchema(structuredSchema);
196 - const toolShapeInstruction = usesWrapper
197 - ? `Call \`${toolName}\` with a single argument named \`${ACP_STRUCTURED_OUTPUT_WRAPPER_KEY}\` containing the final value.`
198 - : `Call \`${toolName}\` with the final structured object as the tool arguments.`;
199 -
200 - return [
201 - prompt,
202 - '',
203 - 'You may inspect files, search, and use tools as needed before producing the final answer.',
204 - `When you are ready to deliver the final structured response, call the MCP tool \`${toolName}\` exactly once.`,
205 - toolShapeInstruction,
206 - `If the MCP tool \`${toolName}\` is unavailable or you cannot call it, reply with only raw JSON matching the schema.`,
207 - 'Do not include prose, markdown fences, or any text before or after the final structured payload.',
208 - 'The final structured value must match this schema:',
209 - JSON.stringify(structuredSchema, null, 2),
210 - ].join('\n');
211 -};
212 -
213 -export const buildStructuredRepairPrompt = (
214 - structuredSchema: Record<string, unknown>,
215 - toolName?: string
216 -): string =>
217 - [
218 - 'Your previous response was not valid structured output.',
219 - 'Do not read files. Do not run terminal commands. Do not inspect the workspace again.',
220 - 'Reuse the analysis you already completed.',
221 - toolName
222 - ? `If the MCP tool \`${toolName}\` is available, call it exactly once with the final structured result. Otherwise reply with only raw JSON matching the schema.`
223 - : 'Reply with only raw JSON matching the schema.',
224 - 'Do not include prose, markdown fences, or any extra text.',
225 - JSON.stringify(structuredSchema, null, 2),
226 - ].join('\n');
227 -
228 -export const validateStructuredOutput = (
229 - parsed: unknown,
230 - options: InvokeAgentNormalizedOptions
231 -): unknown => {
232 - if (options.zodSchema && typeof options.zodSchema.safeParse === 'function') {
233 - const validation = options.zodSchema.safeParse(parsed);
234 - if (!validation.success) {
235 - throw new Error(
236 - `experimental_subAgent() structured output failed schema validation: ${summarizeValidationError(validation.error)}`
237 - );
238 - }
239 -
240 - return validation.data;
241 - }
242 -
243 - return parsed;
244 -};
245 -
246 -const tryParseStructuredJson = (text: string): unknown | undefined => {
247 - const trimmed = text.trim();
248 - if (!trimmed) {
249 - return undefined;
250 - }
251 -
252 - // A parse failure here is the signal to fall through to more permissive
253 - // extraction for agents that emit a short status line before the final JSON
254 - // payload, not an error to surface.
255 - const direct = parseJsonOption(trimmed);
256 - if (Option.isSome(direct)) {
257 - return direct.value;
258 - }
259 -
260 - const fencedMatches = [...trimmed.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];
261 - for (let index = fencedMatches.length - 1; index >= 0; index -= 1) {
262 - const candidate = fencedMatches[index]?.[1]?.trim();
263 - if (!candidate) {
264 - continue;
265 - }
266 -
267 - // Probes each fenced block for valid JSON; an invalid block just advances
268 - // the scan to the next one.
269 - const fenced = parseJsonOption(candidate);
270 - if (Option.isSome(fenced)) {
271 - return fenced.value;
272 - }
273 - }
274 -
275 - const findBalancedJsonEnd = (value: string, start: number): number | null => {
276 - const opening = value[start];
277 - if (opening !== '{' && opening !== '[') {
278 - return null;
279 - }
280 -
281 - const closingStack = [opening === '{' ? '}' : ']'];
282 - let insideString = false;
283 - let escaped = false;
284 -
285 - for (let cursor = start + 1; cursor < value.length; cursor += 1) {
286 - const char = value[cursor]!;
287 - if (insideString) {
288 - if (escaped) {
289 - escaped = false;
290 - continue;
291 - }
292 - if (char === '\\') {
293 - escaped = true;
294 - continue;
295 - }
296 - if (char === '"') {
297 - insideString = false;
298 - }
299 - continue;
300 - }
301 -
302 - if (char === '"') {
303 - insideString = true;
304 - continue;
305 - }
306 - if (char === '{') {
307 - closingStack.push('}');
308 - continue;
309 - }
310 - if (char === '[') {
311 - closingStack.push(']');
312 - continue;
313 - }
314 -
315 - const expected = closingStack.at(-1);
316 - if ((char === '}' || char === ']') && expected === char) {
317 - closingStack.pop();
318 - if (closingStack.length === 0) {
319 - return cursor;
320 - }
321 - }
322 - }
323 -
324 - return null;
325 - };
326 -
327 - let bestCandidate:
328 - | {
329 - readonly length: number;
330 - readonly start: number;
331 - readonly isObject: boolean;
332 - readonly value: unknown;
333 - }
334 - | undefined;
335 -
336 - for (let start = 0; start < trimmed.length; start += 1) {
337 - const char = trimmed[start];
338 - if (char !== '{' && char !== '[') {
339 - continue;
340 - }
341 -
342 - const end = findBalancedJsonEnd(trimmed, start);
343 - if (end === null) {
344 - continue;
345 - }
346 -
347 - const candidate = trimmed.slice(start, end + 1);
348 - // Probes each balanced {...}/[...] substring for valid JSON inside a
349 - // tight scanning loop; a failure just skips the candidate so the scan can
350 - // keep looking for a larger valid JSON payload.
351 - const parsedCandidate = parseJsonOption(candidate);
352 - if (Option.isNone(parsedCandidate)) {
353 - continue;
354 - }
355 -
356 - const parsed = parsedCandidate.value;
357 - const nextCandidate = {
358 - length: candidate.length,
359 - start,
360 - isObject: !Array.isArray(parsed) && parsed !== null && typeof parsed === 'object',
361 - value: parsed,
362 - };
363 -
364 - if (
365 - !bestCandidate ||
366 - nextCandidate.length > bestCandidate.length ||
367 - (nextCandidate.length === bestCandidate.length &&
368 - nextCandidate.isObject &&
369 - !bestCandidate.isObject) ||
370 - (nextCandidate.length === bestCandidate.length &&
371 - nextCandidate.isObject === bestCandidate.isObject &&
372 - nextCandidate.start < bestCandidate.start)
373 - ) {
374 - bestCandidate = nextCandidate;
375 - }
376 - }
377 -
378 - return bestCandidate?.value;
379 -};
380 -
381 -export const finalizeInvokeAgentText = (
382 - text: string,
383 - options: InvokeAgentNormalizedOptions
384 -): Pick<InvokeAgentResponse, 'result' | 'structuredOutput'> => {
385 - const trimmed = text.trim();
386 - if (!options.structuredSchema) {
387 - return {
388 - result: trimmed,
389 - };
390 - }
391 -
392 - const parsed = tryParseStructuredJson(trimmed);
393 - if (parsed === undefined) {
394 - throw new Error('experimental_subAgent() expected valid JSON output for structured response.');
395 - }
396 -
397 - return {
398 - result: null,
399 - structuredOutput: validateStructuredOutput(parsed, options),
400 - };
401 -};
ts/packages/cli/src/services/runtime-flags.ts
+1 -12
@@ -20,7 +20,7 @@ export const readTelemetryDebugOverride = (argv: ReadonlyArray<string>): boolean
20 };
21
22 /**
23 - * Values parsed from the hidden `--perf-debug` / `--tool-debug` / `--acp-only` flags.
23 + * Values parsed from the hidden `--perf-debug` / `--tool-debug` flags.
24 *
25 * `undefined` means "the flag was absent", which is what lets the corresponding `COMPOSIO_*`
26 * config value through; an explicit `true`/`false` always wins over it.
@@ -28,13 +28,11 @@ export const readTelemetryDebugOverride = (argv: ReadonlyArray<string>): boolean
28 export type CliDebugFlagOverrides = {
29 readonly perfDebug: boolean | undefined;
30 readonly toolDebug: boolean | undefined;
31 - readonly acpOnly: boolean | undefined;
31 };
32
33 export const NO_CLI_DEBUG_FLAG_OVERRIDES: CliDebugFlagOverrides = {
34 perfDebug: undefined,
35 toolDebug: undefined,
37 - acpOnly: undefined,
36 };
37
38 /**
@@ -57,7 +55,6 @@ const debugSetting = <const Name extends string>(name: Name) =>
55 const debugSettings = {
56 'perf-debug': debugSetting('perf-debug'),
57 'tool-debug': debugSetting('tool-debug'),
60 - 'acp-only': debugSetting('acp-only'),
58 'telemetry-debug': debugSetting('telemetry-debug'),
59 };
60 export const CLI_DEBUG_FLAG_NAMES = Object.keys(debugSettings);
@@ -87,12 +84,6 @@ export const isToolDebugEnabled = debugFlagOr(
84 Effect.orDie(APP_CONFIG.TOOL_DEBUG)
85 );
86
90 -export const isAcpOnlyEnabled = debugFlagOr(
91 - debugSettings['acp-only'],
92 - overrides => overrides.acpOnly,
93 - Effect.orDie(APP_CONFIG.RUN_ACP_ONLY)
94 -);
95 -
87 /**
88 * Debug state a parent CLI process resolved for the processes it spawns.
89 *
@@ -104,14 +95,12 @@ export const isAcpOnlyEnabled = debugFlagOr(
95 export type ChildProcessDebugFlags = {
96 readonly perfDebug: boolean;
97 readonly toolDebug: boolean;
107 - readonly acpOnly: boolean;
98 readonly telemetryDebug: boolean;
99 };
100
101 export const debugFlagsToChildEnv = (flags: ChildProcessDebugFlags): Record<string, string> => ({
102 COMPOSIO_PERF_DEBUG: flags.perfDebug ? '1' : '0',
103 COMPOSIO_TOOL_DEBUG: flags.toolDebug ? '1' : '0',
114 - COMPOSIO_RUN_ACP_ONLY: flags.acpOnly ? '1' : '0',
104 COMPOSIO_CLI_TELEMETRY_DEBUG: flags.telemetryDebug ? '1' : '0',
105 });
106
ts/packages/cli/test/__utils__/services/test-layer.ts
-2
@@ -921,7 +921,6 @@ export const TestLayer = (input?: TestLiveInput) =>
921 },
922 experimentalFeatures: input?.cliUserConfig?.experimentalFeatures ?? {},
923 artifactDirectory: Option.none(),
924 - experimentalSubagent: Option.none(),
924 security: 'auto',
925 });
926
@@ -935,7 +934,6 @@ export const TestLayer = (input?: TestLiveInput) =>
934 developerDangerousCommandsEnabled: rawCliUserConfig.developer.destructiveActions,
935 experimentalFeatures: rawCliUserConfig.experimentalFeatures,
936 artifactDirectory: Option.getOrUndefined(rawCliUserConfig.artifactDirectory),
938 - experimentalSubagentTarget: 'auto' as const,
937 security: 'auto' as const,
938 };
939 },
ts/packages/cli/test/src/commands/argv-compat.test.ts new
+31
@@ -0,0 +1,31 @@
1 +import { describe, expect, it } from 'vitest';
2 +import { normalizeRunScriptArgs } from 'src/commands/argv-compat';
3 +
4 +const argv = (...args: ReadonlyArray<string>) => ['bun', 'composio', ...args];
5 +
6 +describe('normalizeRunScriptArgs', () => {
7 + it.each(['--unknown', '--foo_bar', '--foo_bar=value', '-foo_bar'])(
8 + 'leaves %s ahead of inline source for the framework to reject',
9 + flag => {
10 + const input = argv('run', flag, 'console.log(1)');
11 +
12 + expect(normalizeRunScriptArgs(input)).toEqual(input);
13 + }
14 + );
15 +
16 + it('still treats inline source that starts with a dash and a digit as the script', () => {
17 + expect(normalizeRunScriptArgs(argv('run', '-1 + 2'))).toEqual(argv('run', '--', '-1 + 2'));
18 + });
19 +
20 + it('forwards an unknown flag after --file as a script argument', () => {
21 + expect(normalizeRunScriptArgs(argv('run', '--file', 'script.ts', '--repo', 'acme'))).toEqual(
22 + argv('run', '--file', 'script.ts', '--', '--repo', 'acme')
23 + );
24 + });
25 +
26 + it('keeps flag-shaped inline source behind an explicit delimiter', () => {
27 + const input = argv('run', '--', '--unknown');
28 +
29 + expect(normalizeRunScriptArgs(input)).toEqual(input);
30 + });
31 +});
ts/packages/cli/test/src/commands/root-help-consistency.test.ts
+1 -1
@@ -61,7 +61,7 @@ describe('framework command help', () => {
61 expect((yield* capture(['version', '--help'])).stdout).toContain('--check');
62 const run = yield* capture(['run', '--help']);
63 expect(run.stdout).toContain('--skip-checks');
64 - expect(run.stdout).toContain('--logs-off');
64 + expect(run.stdout).not.toContain('--logs-off');
65 expect(run.stdout).not.toContain('--perf-debug');
66 })
67 );
ts/packages/cli/test/src/commands/run.cmd.test.ts
+101 -337
@@ -20,31 +20,17 @@ import {
20 } from 'src/commands/run-source-transforms';
21 import {
22 RUN_COMPANION_MODULE_FILENAMES,
23 - hasInstalledRunCompanionModules,
24 - hostRunCompanionStaticAssetRelativePaths,
23 listMissingInstalledRunCompanionModules,
24 readInstalledReleaseTag,
25 resolveRunCompanionModulePath,
26 writeInstalledReleaseTag,
27 } from 'src/services/run-companion-modules';
30 -import {
31 - ACP_STRUCTURED_OUTPUT_WRAPPER_KEY,
32 - buildStructuredRepairPrompt,
33 - buildStructuredOutputToolSchema,
34 - buildStructuredPrompt,
35 - buildStructuredToolPrompt,
36 - finalizeInvokeAgentText,
37 -} from 'src/services/run-subagent-shared';
28 import { extendConfigProvider } from 'src/services/config';
29 import { telemetryDebugModeLayer } from 'src/services/runtime-flags';
30 import { DEFAULT_CLI_INVOCATION_ORIGIN } from 'src/services/runtime-cli-context';
31 import { cli, MockConsole, TestLive } from 'test/__utils__';
32 import { CommandRunner } from 'src/services/command-runner';
33
44 -const acpOnlyConfigProvider = ConfigProvider.fromEnvRecord({
45 - COMPOSIO_RUN_ACP_ONLY: '1',
46 -}).pipe(extendConfigProvider);
47 -
34 const enabledRuntimeFlagsConfigProvider = ConfigProvider.fromEnvRecord({
35 COMPOSIO_RUN_ACP_ONLY: '1',
36 COMPOSIO_PERF_DEBUG: '1',
@@ -230,39 +216,54 @@ describe('CLI: composio run', () => {
216 );
217 });
218
233 - layer(RunTestLive({ baseConfigProvider: acpOnlyConfigProvider }))(it => {
219 + layer(RunTestLive())(it => {
220 + it.effect('[Given] a run [Then] the preload context carries no sub-agent inputs', () =>
221 + Effect.gen(function* () {
222 + let preloadSource = '';
223 + commandRuns.mockImplementation(command => {
224 + preloadSource = readRunPreloadSource(inspectRunCommand(command).cmd);
225 + return Effect.succeed(ChildProcessSpawner.ExitCode(0));
226 + });
227 +
228 + yield* cli(['run', 'console.log("hi")']);
229 +
230 + expect(preloadSource).toContain('"runLogFilePath":');
231 + expect(preloadSource).not.toContain('"master":');
232 + expect(preloadSource).not.toContain('"readAccessRoots":');
233 + expect(preloadSource).not.toContain('"cliConfigPath":');
234 + })
235 + );
236 + });
237 +
238 + layer(RunTestLive({ baseConfigProvider: enabledRuntimeFlagsConfigProvider }))(it => {
239 it.effect(
235 - '[Given] COMPOSIO_RUN_ACP_ONLY=1 [Then] run enables ACP-only execution without a flag',
240 + '[Given] COMPOSIO_RUN_ACP_ONLY=1 [Then] only the remaining debug flags reach the script',
241 () =>
242 Effect.gen(function* () {
243 + let preloadSource = '';
244 commandRuns.mockImplementation(command => {
239 - expect(readRunPreloadSource(inspectRunCommand(command).cmd)).toContain(
240 - '"acpOnly":true'
241 - );
245 + preloadSource = readRunPreloadSource(inspectRunCommand(command).cmd);
246 return Effect.succeed(ChildProcessSpawner.ExitCode(0));
247 });
248
249 yield* cli(['run', 'console.log("hi")']);
250
247 - expect(commandRuns).toHaveBeenCalledTimes(1);
251 + const command = inspectRunCommand(commandRuns.mock.calls[0]![0]);
252 + expect(command.env).toEqual({
253 + BUN_BE_BUN: '1',
254 + COMPOSIO_CLI_PARENT_RUN_ID: expect.any(String),
255 + COMPOSIO_PERF_DEBUG: '1',
256 + COMPOSIO_TOOL_DEBUG: '1',
257 + COMPOSIO_CLI_TELEMETRY_DEBUG: '0',
258 + });
259 + expect(preloadSource).toContain('"perfDebug":true');
260 + expect(preloadSource).toContain('"toolDebug":true');
261 + expect(preloadSource).toContain('"telemetryDebug":false');
262 + expect(preloadSource).not.toContain('acpOnly');
263 + expect(preloadSource).not.toContain('COMPOSIO_RUN_ACP_ONLY');
264 })
265 );
266
251 - it.effect('[Given] --acp-only=false and configured ACP-only mode [Then] the flag wins', () =>
252 - Effect.gen(function* () {
253 - commandRuns.mockImplementation(command => {
254 - expect(readRunPreloadSource(inspectRunCommand(command).cmd)).toContain('"acpOnly":false');
255 - return Effect.succeed(ChildProcessSpawner.ExitCode(0));
256 - });
257 -
258 - yield* cli(['run', '--acp-only=false', 'console.log("hi")']);
259 -
260 - expect(commandRuns).toHaveBeenCalledTimes(1);
261 - })
262 - );
263 - });
264 -
265 - layer(RunTestLive({ baseConfigProvider: enabledRuntimeFlagsConfigProvider }))(it => {
267 it.effect('[Given] explicit false flags [Then] inherited true values are cleared', () =>
268 Effect.gen(function* () {
269 let preloadSource = '';
@@ -271,22 +272,16 @@ describe('CLI: composio run', () => {
272 return Effect.succeed(ChildProcessSpawner.ExitCode(0));
273 });
274
274 - yield* cli([
275 - 'run',
276 - '--perf-debug=false',
277 - '--tool-debug=false',
278 - '--acp-only=false',
279 - 'console.log("hi")',
280 - ]);
275 + yield* cli(['run', '--perf-debug=false', '--tool-debug=false', 'console.log("hi")']);
276
277 const command = inspectRunCommand(commandRuns.mock.calls[0]![0]);
278 expect(command.env).toMatchObject({
279 COMPOSIO_PERF_DEBUG: '0',
280 COMPOSIO_TOOL_DEBUG: '0',
286 - COMPOSIO_RUN_ACP_ONLY: '0',
281 COMPOSIO_CLI_TELEMETRY_DEBUG: '0',
282 });
289 - expect(preloadSource).toContain('"acpOnly":false');
283 + expect(preloadSource).toContain('"perfDebug":false');
284 + expect(preloadSource).toContain('"toolDebug":false');
285 })
286 );
287 });
@@ -312,25 +307,29 @@ describe('CLI: composio run', () => {
307 });
308
309 layer(RunTestLive())(it => {
315 - it.effect(
316 - '[Given] --acp-only [Then] run accepts the flag and forwards execution normally',
317 - () =>
310 + for (const flag of [
311 + '--acp-only',
312 + '--acp-only=false',
313 + '--no-acp-only',
314 + '--logs-off',
315 + '--logs-off=false',
316 + '--no-logs-off',
317 + '--foo_bar',
318 + '--foo_bar=value',
319 + ]) {
320 + it.effect(`[Given] the unknown ${flag} [Then] run rejects it as an unknown flag`, () =>
321 Effect.gen(function* () {
319 - commandRuns.mockImplementation(command => {
320 - expect(readRunPreloadSource(inspectRunCommand(command).cmd)).toContain(
321 - '"acpOnly":true'
322 - );
323 - return Effect.succeed(ChildProcessSpawner.ExitCode(0));
324 - });
325 -
326 - yield* cli(['run', '--acp-only', 'console.log("hi")']);
322 + const exit = yield* cli(['run', flag, 'console.log(1)']).pipe(Effect.exit);
323
328 - expect(commandRuns).toHaveBeenCalledTimes(1);
329 - const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
330 - expect(spawnConfig.cmd[3]).toBe('--eval');
331 - expect(process.exitCode).toBe(0);
324 + expect(Exit.isFailure(exit)).toBe(true);
325 + expect(commandRuns).not.toHaveBeenCalled();
326 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
327 + expect(output).toContain(
328 + `Unrecognized flag: ${flag.split('=')[0]} in command composio run`
329 + );
330 })
333 - );
331 + );
332 + }
333
334 it.effect('[Given] repeated invocations [Then] hidden flags do not leak', () =>
335 Effect.gen(function* () {
@@ -340,66 +339,46 @@ describe('CLI: composio run', () => {
339 return Effect.succeed(ChildProcessSpawner.ExitCode(0));
340 });
341
343 - yield* cli(['run', '--acp-only', 'console.log("first")']);
342 + yield* cli(['run', '--perf-debug', 'console.log("first")']);
343 yield* cli(['run', 'console.log("second")']);
344
345 expect(preloadSources).toHaveLength(2);
347 - expect(preloadSources[0]).toContain('"acpOnly":true');
348 - expect(preloadSources[1]).toContain('"acpOnly":false');
346 + expect(preloadSources[0]).toContain('"perfDebug":true');
347 + expect(preloadSources[1]).toContain('"perfDebug":false');
348 })
349 );
350 });
351
352 layer(RunTestLive())(it => {
353 it.effect(
355 - '[Given] --logs-off [Then] run accepts the flag and forwards execution normally',
356 - () =>
357 - Effect.gen(function* () {
358 - yield* cli(['run', '--logs-off', 'console.log("hi")']);
359 -
360 - expect(commandRuns).toHaveBeenCalledTimes(1);
361 - const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
362 - expect(spawnConfig.cmd[3]).toBe('--eval');
363 - expect(process.exitCode).toBe(0);
364 - })
365 - );
366 - });
367 -
368 - layer(RunTestLive())(it => {
369 - it.effect(
370 - '[Given] a multiline structured experimental_subAgent script [Then] run preserves the inline TypeScript source',
354 + '[Given] a multiline execute script [Then] run preserves the inline TypeScript source',
355 () =>
356 Effect.gen(function* () {
357 const script = `
374 - const brief = await experimental_subAgent(
375 - [
376 - "Do not read files.",
377 - "Do not run terminal commands.",
378 - "Do not inspect the workspace.",
379 - "Return exactly this structured value:",
380 - "{\\"summary\\":\\"ok\\",\\"urgent\\":[\\"a\\",\\"b\\"]}",
381 - ].join("\\n"),
358 + const issue = await execute(
359 + "GITHUB_CREATE_ISSUE",
360 {
383 - target: "codex",
384 - schema: z.object({ summary: z.string(), urgent: z.array(z.string()) }),
361 + owner: "acme",
362 + title: [
363 + "Deploy v2",
364 + "Do not run terminal commands.",
365 + ].join("\\n"),
366 }
367 );
387 - console.log(JSON.stringify(brief));
388 - console.log(JSON.stringify(brief.structuredOutput));
368 + console.log(JSON.stringify(issue));
369 + console.log(JSON.stringify(issue.data));
370 `;
390 - yield* cli(['run', '--logs-off', script]);
371 + yield* cli(['run', script]);
372
373 expect(commandRuns).toHaveBeenCalledTimes(1);
374 const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
375 expect(spawnConfig.cmd[3]).toBe('--eval');
395 - expect(spawnConfig.cmd[4]).toContain('const brief = await experimental_subAgent(');
376 + expect(spawnConfig.cmd[4]).toContain('const issue = await execute(');
377 expect(spawnConfig.cmd[4]).toContain('"Do not run terminal commands."');
378 expect(spawnConfig.cmd[4]).toContain('].join("\\n"),');
398 - expect(spawnConfig.cmd[4]).toContain('target: "codex"');
399 - expect(spawnConfig.cmd[4]).toContain('console.log(JSON.stringify(brief));');
400 - expect(spawnConfig.cmd[4]).toContain(
401 - 'return (console.log(JSON.stringify(brief.structuredOutput)));'
402 - );
379 + expect(spawnConfig.cmd[4]).toContain('owner: "acme"');
380 + expect(spawnConfig.cmd[4]).toContain('console.log(JSON.stringify(issue));');
381 + expect(spawnConfig.cmd[4]).toContain('return (console.log(JSON.stringify(issue.data)));');
382 expect(spawnConfig.cmd[4]).not.toContain('"Do not run terminal\n');
383 expect(process.exitCode).toBe(0);
384 })
@@ -490,14 +469,7 @@ describe('CLI: composio run', () => {
469 () =>
470 Effect.gen(function* () {
471 const script = 'console.log("hi")';
493 - const tail = [
494 - '--perf-debug',
495 - '--tool-debug',
496 - '--acp-only',
497 - '--telemetry-debug',
498 - '--help',
499 - '--version',
500 - ];
472 + const tail = ['--perf-debug', '--tool-debug', '--telemetry-debug', '--help', '--version'];
473 for (const args of [
474 [script, ...tail],
475 [script, '--', ...tail],
@@ -509,7 +481,6 @@ describe('CLI: composio run', () => {
481 expect(spawned.env).toMatchObject({
482 COMPOSIO_PERF_DEBUG: '0',
483 COMPOSIO_TOOL_DEBUG: '0',
512 - COMPOSIO_RUN_ACP_ONLY: '0',
484 COMPOSIO_CLI_TELEMETRY_DEBUG: '0',
485 });
486 }
@@ -552,7 +523,7 @@ describe('CLI: composio run', () => {
523
524 layer(RunTestLive())(it => {
525 it.effect(
555 - '[Given] run help [Then] it documents injected execute, search, proxy, experimental_subAgent, and z helpers',
526 + '[Given] run help [Then] it documents injected execute, search, proxy, and z helpers without the removed sub-agent',
527 () =>
528 Effect.gen(function* () {
529 yield* cli(['run', '--help']);
@@ -564,10 +535,13 @@ describe('CLI: composio run', () => {
535 expect(output).toContain('--skip-connection-check');
536 expect(output).toContain('--skip-tool-params-check');
537 expect(output).toContain('--skip-checks');
567 - expect(output).toContain('--logs-off');
568 - expect(output).toContain('experimental_subAgent');
569 - expect(output).toContain('schema: z.object');
538 + expect(output).not.toContain('--logs-off');
539 + expect(output).not.toContain('experimental_subAgent');
540 expect(output).toContain('Injected helpers');
541 + expect(output).toContain('execute(slug, data?)');
542 + expect(output).toContain('search(query, options?)');
543 + expect(output).toContain('result.prompt()');
544 + expect(output).toContain('const f = await proxy(toolkit)');
545 expect(output).toContain('Injected global from `zod`');
546 expect(output).toContain('composio search "<query>"');
547 expect(output).toContain('composio execute <slug> --get-schema');
@@ -587,8 +561,6 @@ describe('buildRunHelpersSource', () => {
561 webURL: 'https://app.example.test',
562 orgId: 'org_test',
563 consumerUserId: 'consumer_user_test',
590 - acpOnly: true,
591 - logsOff: true,
564 dryRun: true,
565 runLogFilePath: '/tmp/composio-run/run.log',
566 },
@@ -600,127 +572,12 @@ describe('buildRunHelpersSource', () => {
572 expect(source).toContain('import { installRunHelpers } from "file://');
573 expect(source).toContain('await installRunHelpers(');
574 expect(source).toContain('"cliPrefix":["/tmp/composio"]');
603 - expect(source).toContain('"acpOnly":true');
604 - expect(source).toContain('"logsOff":true');
575 expect(source).toContain('"runLogFilePath":"/tmp/composio-run/run.log"');
576 expect(source).toContain('"consumerUserId":"consumer_user_test"');
577 expect(source).not.toContain('globalThis.execute = async (slug, data = {}) => {');
578 });
579 });
580
611 -describe('run-subagent-shared', () => {
612 - it('[Given] a structured schema [Then] it appends a strict JSON response contract', () => {
613 - expect(buildStructuredPrompt('hello', { type: 'object' })).toContain(
614 - 'Return only a valid JSON value that matches this schema.'
615 - );
616 - });
617 -
618 - it('[Given] a non-object structured schema [Then] the MCP output tool schema wraps it under a value key', () => {
619 - expect(buildStructuredOutputToolSchema({ type: 'array', items: { type: 'string' } })).toEqual({
620 - type: 'object',
621 - additionalProperties: false,
622 - required: [ACP_STRUCTURED_OUTPUT_WRAPPER_KEY],
623 - properties: {
624 - [ACP_STRUCTURED_OUTPUT_WRAPPER_KEY]: { type: 'array', items: { type: 'string' } },
625 - },
626 - });
627 - });
628 -
629 - it('[Given] structured tool mode [Then] the prompt instructs the agent to use the output tool', () => {
630 - expect(
631 - buildStructuredToolPrompt(
632 - 'Summarize it.',
633 - { type: 'array', items: { type: 'string' } },
634 - 'submit_structured_output'
635 - )
636 - ).toContain('call the MCP tool `submit_structured_output` exactly once');
637 - });
638 -
639 - it('[Given] a repair prompt [Then] it requires no more tools and JSON-only fallback', () => {
640 - const prompt = buildStructuredRepairPrompt(
641 - { type: 'object', properties: { summary: { type: 'string' } } },
642 - 'submit_structured_output'
643 - );
644 -
645 - expect(prompt).toContain('Your previous response was not valid structured output.');
646 - expect(prompt).toContain('Do not read files. Do not run terminal commands.');
647 - expect(prompt).toContain('reply with only raw JSON matching the schema');
648 - });
649 -
650 - it('[Given] Zod-like structured output [Then] it validates and returns structured data', () => {
651 - const result = finalizeInvokeAgentText('{"ok":true}', {
652 - structuredSchema: { type: 'object' },
653 - zodSchema: {
654 - safeParse: value => ({ success: true as const, data: value }),
655 - },
656 - });
657 -
658 - expect(result).toEqual({
659 - result: null,
660 - structuredOutput: { ok: true },
661 - });
662 - });
663 -
664 - it('[Given] plain text output [Then] it omits structuredOutput', () => {
665 - const result = finalizeInvokeAgentText('hello', {});
666 -
667 - expect(result).toEqual({
668 - result: 'hello',
669 - });
670 - expect('structuredOutput' in result).toBe(false);
671 - });
672 -
673 - it('[Given] invalid JSON in structured mode [Then] it throws a clear error', () => {
674 - expect(() =>
675 - finalizeInvokeAgentText('not-json', {
676 - structuredSchema: { type: 'object' },
677 - })
678 - ).toThrow('experimental_subAgent() expected valid JSON output for structured response.');
679 - });
680 -
681 - it('[Given] prose followed by JSON in structured mode [Then] it recovers the final JSON payload', () => {
682 - const result = finalizeInvokeAgentText('Reading file now.\n{"ok":true}', {
683 - structuredSchema: { type: 'object' },
684 - zodSchema: {
685 - safeParse: value => ({ success: true as const, data: value }),
686 - },
687 - });
688 -
689 - expect(result).toEqual({
690 - result: null,
691 - structuredOutput: { ok: true },
692 - });
693 - });
694 -
695 - it('[Given] fenced JSON in structured mode [Then] it parses the fenced payload', () => {
696 - const result = finalizeInvokeAgentText('```json\n{"ok":true}\n```', {
697 - structuredSchema: { type: 'object' },
698 - zodSchema: {
699 - safeParse: value => ({ success: true as const, data: value }),
700 - },
701 - });
702 -
703 - expect(result).toEqual({
704 - result: null,
705 - structuredOutput: { ok: true },
706 - });
707 - });
708 -
709 - it('[Given] an object containing arrays [Then] it prefers the full object over an inner array', () => {
710 - const result = finalizeInvokeAgentText('Working...\n{"summary":"done","urgent":["a","b"]}', {
711 - structuredSchema: { type: 'object' },
712 - zodSchema: {
713 - safeParse: value => ({ success: true as const, data: value }),
714 - },
715 - });
716 -
717 - expect(result).toEqual({
718 - result: null,
719 - structuredOutput: { summary: 'done', urgent: ['a', 'b'] },
720 - });
721 - });
722 -});
723 -
581 describe('inferCliInvocationPrefix', () => {
582 layer(BunServices.layer)(it => {
583 it.effect(
@@ -745,7 +602,7 @@ describe('resolveRunCompanionModulePath', () => {
602 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-companion-dist-'));
603 const callerPath = path.join(tempDir, 'commands-abc.mjs');
604 const servicesDir = path.join(tempDir, 'services');
748 - const companionPath = path.join(servicesDir, 'run-subagent-shared.mjs');
605 + const companionPath = path.join(servicesDir, 'run-helpers-runtime.mjs');
606 fs.writeFileSync(callerPath, '', 'utf8');
607 fs.mkdirSync(servicesDir);
608 fs.writeFileSync(companionPath, '', 'utf8');
@@ -754,7 +611,7 @@ describe('resolveRunCompanionModulePath', () => {
611 yield* resolveRunCompanionModulePath({
612 callerImportMetaUrl: pathToFileURL(callerPath).href,
613 execPath: '/tmp/composio',
757 - relativeNoExtensionFromCaller: '../services/run-subagent-shared',
614 + relativeNoExtensionFromCaller: '../services/run-helpers-runtime',
615 })
616 ).toBe(companionPath);
617 })
@@ -766,14 +623,14 @@ describe('resolveRunCompanionModulePath', () => {
623 Effect.gen(function* () {
624 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-companion-bin-'));
625 const execPath = path.join(tempDir, 'composio');
769 - const companionPath = path.join(tempDir, 'run-subagent-shared.mjs');
626 + const companionPath = path.join(tempDir, 'run-helpers-runtime.mjs');
627 fs.writeFileSync(companionPath, '', 'utf8');
628
629 expect(
630 yield* resolveRunCompanionModulePath({
631 callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
632 execPath,
776 - relativeNoExtensionFromCaller: '../services/run-subagent-shared',
633 + relativeNoExtensionFromCaller: '../services/run-helpers-runtime',
634 })
635 ).toBe(companionPath);
636 })
@@ -810,39 +667,6 @@ describe('run companion install metadata', () => {
667 })
668 );
669
813 - it.effect(
814 - '[Given] an install without ACP adapters [Then] the startup tier reports nothing missing',
815 - () =>
816 - Effect.gen(function* () {
817 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-no-acp-'));
818 - const execPath = path.join(tempDir, 'composio');
819 - for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
820 - fs.writeFileSync(path.join(tempDir, fileName), '', 'utf8');
821 - }
822 -
823 - // The ACP adapters are the lazy tier: a plain `composio run` must not
824 - // treat an install without them as broken.
825 - const hostStaticAssets = yield* hostRunCompanionStaticAssetRelativePaths;
826 - expect(hostStaticAssets.length).toBeGreaterThan(0);
827 - for (const relativePath of hostStaticAssets) {
828 - expect(fs.existsSync(path.join(tempDir, relativePath))).toBe(false);
829 - }
830 -
831 - expect(yield* listMissingInstalledRunCompanionModules(execPath)).toEqual([]);
832 - expect(yield* hasInstalledRunCompanionModules(execPath)).toBe(true);
833 - })
834 - );
835 -
836 - it.effect(
837 - '[Given] a source checkout [Then] the executable has no companion modules next to it',
838 - () =>
839 - Effect.gen(function* () {
840 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-no-install-'));
841 -
842 - expect(yield* hasInstalledRunCompanionModules(path.join(tempDir, 'bun'))).toBe(false);
843 - })
844 - );
845 -
670 it.effect(
671 '[Given] a nested companion dependency is missing [Then] it reports the missing helper asset',
672 () =>
@@ -858,23 +682,8 @@ describe('run companion install metadata', () => {
682 'utf8'
683 );
684 fs.writeFileSync(
861 - path.join(tempDir, 'run-subagent-shared.mjs'),
862 - 'export * from "./services/run-subagent-shared.mjs";\n',
863 - 'utf8'
864 - );
865 - fs.writeFileSync(
866 - path.join(tempDir, 'run-subagent-acp.mjs'),
867 - 'export * from "./services/run-subagent-acp.mjs";\n',
868 - 'utf8'
869 - );
870 - fs.writeFileSync(
871 - path.join(tempDir, 'run-subagent-legacy.mjs'),
872 - 'export * from "./services/run-subagent-legacy.mjs";\n',
873 - 'utf8'
874 - );
875 - fs.writeFileSync(
876 - path.join(tempDir, 'run-subagent-output-mcp.mjs'),
877 - 'export * from "./services/run-subagent-output-mcp.mjs";\n',
685 + path.join(tempDir, 'generation-runtime.mjs'),
686 + 'export * from "./services/generation-runtime.mjs";\n',
687 'utf8'
688 );
689
@@ -884,29 +693,14 @@ describe('run companion install metadata', () => {
693 'utf8'
694 );
695 fs.writeFileSync(
887 - path.join(servicesDir, 'run-subagent-shared.mjs'),
888 - 'export const x = 1;\n',
889 - 'utf8'
890 - );
891 - fs.writeFileSync(
892 - path.join(servicesDir, 'run-subagent-acp.mjs'),
696 + path.join(servicesDir, 'generation-runtime.mjs'),
697 'export * from "../run-companion-modules-abc123.mjs";\n',
698 'utf8'
699 );
896 - fs.writeFileSync(
897 - path.join(servicesDir, 'run-subagent-legacy.mjs'),
898 - 'export const y = 1;\n',
899 - 'utf8'
900 - );
901 - fs.writeFileSync(
902 - path.join(servicesDir, 'run-subagent-output-mcp.mjs'),
903 - 'export const z = 1;\n',
904 - 'utf8'
905 - );
700
907 - expect(yield* listMissingInstalledRunCompanionModules(execPath)).toContain(
908 - 'run-companion-modules-abc123.mjs'
909 - );
701 + expect(yield* listMissingInstalledRunCompanionModules(execPath)).toEqual([
702 + 'run-companion-modules-abc123.mjs',
703 + ]);
704 })
705 );
706
@@ -925,23 +719,8 @@ describe('run companion install metadata', () => {
719 'utf8'
720 );
721 fs.writeFileSync(
928 - path.join(tempDir, 'run-subagent-shared.mjs'),
929 - 'export * from "./services/run-subagent-shared.mjs";\n',
930 - 'utf8'
931 - );
932 - fs.writeFileSync(
933 - path.join(tempDir, 'run-subagent-acp.mjs'),
934 - 'export * from "./services/run-subagent-acp.mjs";\n',
935 - 'utf8'
936 - );
937 - fs.writeFileSync(
938 - path.join(tempDir, 'run-subagent-legacy.mjs'),
939 - 'export * from "./services/run-subagent-legacy.mjs";\n',
940 - 'utf8'
941 - );
942 - fs.writeFileSync(
943 - path.join(tempDir, 'run-subagent-output-mcp.mjs'),
944 - 'export * from "./services/run-subagent-output-mcp.mjs";\n',
722 + path.join(tempDir, 'generation-runtime.mjs'),
723 + 'export * from "./services/generation-runtime.mjs";\n',
724 'utf8'
725 );
726
@@ -951,29 +730,14 @@ describe('run companion install metadata', () => {
730 'utf8'
731 );
732 fs.writeFileSync(
954 - path.join(servicesDir, 'run-subagent-shared.mjs'),
955 - 'export const sharedValue = 1;\n',
956 - 'utf8'
957 - );
958 - fs.writeFileSync(
959 - path.join(servicesDir, 'run-subagent-acp.mjs'),
733 + path.join(servicesDir, 'generation-runtime.mjs'),
734 'export { helperValue } from "../run-companion-modules-def456.mjs";\n',
735 'utf8'
736 );
963 - fs.writeFileSync(
964 - path.join(servicesDir, 'run-subagent-legacy.mjs'),
965 - 'export const legacyValue = 1;\n',
966 - 'utf8'
967 - );
968 - fs.writeFileSync(
969 - path.join(servicesDir, 'run-subagent-output-mcp.mjs'),
970 - 'export const outputValue = 1;\n',
971 - 'utf8'
972 - );
737
974 - expect(yield* listMissingInstalledRunCompanionModules(execPath)).toContain(
975 - 'run-companion-modules-def456.mjs'
976 - );
738 + expect(yield* listMissingInstalledRunCompanionModules(execPath)).toEqual([
739 + 'run-companion-modules-def456.mjs',
740 + ]);
741 })
742 );
743 });
ts/packages/cli/test/src/scripts/release-artifacts.test.ts
+88 -143
@@ -1,167 +1,112 @@
1 -import { Option, Result } from 'effect';
1 import { describe, expect, it } from 'vitest';
2
4 -import {
5 - RUN_CODEX_ACP_BINARY_TARGETS,
6 - RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,
7 - RUN_COMPANION_MODULE_FILENAMES,
8 - RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
9 -} from '../../../src/services/run-companion-modules';
10 -import {
11 - archiveCompanionEntries,
12 - ARTIFACT_NAMES,
13 - RELEASE_ARTIFACT_TARGETS,
14 - releaseArtifactTargetFor,
15 - UnknownReleaseArtifactError,
16 -} from '../../../scripts/_release-artifacts';
3 +import { RUN_COMPANION_MODULE_FILENAMES } from '../../../src/services/run-companion-modules';
4 +import { archiveCompanionEntries } from '../../../scripts/_release-artifacts';
5
6 /**
7 * Everything `collectExpectedRunCompanionAssetRelativePaths` yields for a fully
20 - * populated companions directory: the wrappers, their bundled services, and the
21 - * multi-platform static asset set.
8 + * populated companions directory: the wrappers and their bundled services.
9 */
23 -const ALL_COMPANION_RELATIVE_PATHS: ReadonlyArray<string> = [
10 +const LIVE_COMPANION_RELATIVE_PATHS: ReadonlyArray<string> = [
11 ...RUN_COMPANION_MODULE_FILENAMES,
12 ...RUN_COMPANION_MODULE_FILENAMES.map(fileName => `services/${fileName}`),
26 - ...RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,
13 ].sort();
14
29 -const codexAcpRelativePathsIn = (relativePaths: ReadonlyArray<string>): ReadonlyArray<string> =>
30 - relativePaths.filter(relativePath => relativePath.endsWith('/codex-acp'));
31 -
32 -describe('releaseArtifactTargetFor', () => {
33 - it('maps every published artifact name to a Node platform/arch pair', () => {
34 - expect(
35 - RELEASE_ARTIFACT_TARGETS.map(({ artifactName, platform, arch }) => [
36 - artifactName,
37 - `${platform}-${arch}`,
38 - ])
39 - ).toEqual([
40 - ['composio-darwin-aarch64', 'darwin-arm64'],
41 - ['composio-darwin-x64', 'darwin-x64'],
42 - ['composio-linux-x64', 'linux-x64'],
43 - ['composio-linux-aarch64', 'linux-arm64'],
44 - ]);
45 - });
46 -
47 - it.each(ARTIFACT_NAMES)('resolves %s', artifactName => {
48 - const target = releaseArtifactTargetFor(artifactName);
49 -
50 - expect(Result.isSuccess(target)).toBe(true);
51 - });
52 -
53 - it('covers every codex-acp binary target exactly once', () => {
54 - const artifactTargets = RELEASE_ARTIFACT_TARGETS.map(
55 - ({ platform, arch }) => `${platform}-${arch}`
56 - ).sort();
57 - const codexTargets = RUN_CODEX_ACP_BINARY_TARGETS.map(
58 - ({ platform, arch }) => `${platform}-${arch}`
59 - ).sort();
60 -
61 - expect(artifactTargets).toEqual(codexTargets);
62 - });
63 -
64 - it.each(['composio-linux-arm64', 'composio-windows-x64', 'composio', ''])(
65 - 'rejects the unknown artifact name %o',
66 - artifactName => {
67 - const target = releaseArtifactTargetFor(artifactName);
68 -
69 - const error = Option.getOrUndefined(Result.getFailure(target));
70 -
71 - expect(error).toBeInstanceOf(UnknownReleaseArtifactError);
72 - expect(error?.message).toContain('Unknown release artifact');
73 - }
74 - );
75 -});
15 +const LEGACY_WRAPPERS: ReadonlyArray<string> = [
16 + 'run-subagent-shared.mjs',
17 + 'run-subagent-acp.mjs',
18 + 'run-subagent-legacy.mjs',
19 + 'run-subagent-output-mcp.mjs',
20 +];
21
22 describe('archiveCompanionEntries', () => {
78 - const pathsOfKind = (
79 - entries: ReadonlyArray<{ relativePath: string; kind: string }>,
80 - kind: string
81 - ): ReadonlyArray<string> =>
82 - entries.filter(entry => entry.kind === kind).map(entry => entry.relativePath);
23 + // Every archive gets the same entries, whatever platform its binary targets.
24 + const entries = archiveCompanionEntries(LIVE_COMPANION_RELATIVE_PATHS);
25
84 - it.each(RELEASE_ARTIFACT_TARGETS)(
85 - 'names every codex-acp path in $artifactName so older clients still verify',
86 - target => {
87 - const entries = archiveCompanionEntries({
88 - allRelativePaths: ALL_COMPANION_RELATIVE_PATHS,
89 - target,
90 - });
91 -
92 - expect(entries.map(entry => entry.relativePath)).toEqual(ALL_COMPANION_RELATIVE_PATHS);
93 - }
94 - );
95 -
96 - it.each(RELEASE_ARTIFACT_TARGETS)(
97 - 'carries real bytes only for the $platform-$arch codex-acp binary',
98 - target => {
99 - const entries = archiveCompanionEntries({
100 - allRelativePaths: ALL_COMPANION_RELATIVE_PATHS,
101 - target,
102 - });
103 -
104 - expect(codexAcpRelativePathsIn(pathsOfKind(entries, 'copy'))).toEqual([
105 - `acp-adapters/codex/${target.platform}-${target.arch}/codex-acp`,
106 - ]);
107 - }
108 - );
109 -
110 - it.each(RELEASE_ARTIFACT_TARGETS)(
111 - 'placeholders exactly the foreign codex-acp binaries in $artifactName',
112 - target => {
113 - const entries = archiveCompanionEntries({
114 - allRelativePaths: ALL_COMPANION_RELATIVE_PATHS,
115 - target,
116 - });
117 -
118 - expect(pathsOfKind(entries, 'placeholder')).toEqual(
119 - RUN_CODEX_ACP_BINARY_TARGETS.filter(
120 - codexTarget =>
121 - codexTarget.platform !== target.platform || codexTarget.arch !== target.arch
122 - ).map(codexTarget => codexTarget.relativePath)
123 - );
124 - }
125 - );
26 + const pathsOfKind = (kind: string): ReadonlyArray<string> =>
27 + entries.filter(entry => entry.kind === kind).map(entry => entry.relativePath);
28
127 - it.each(RELEASE_ARTIFACT_TARGETS)('copies the portable assets into $artifactName', target => {
128 - const entries = archiveCompanionEntries({
129 - allRelativePaths: ALL_COMPANION_RELATIVE_PATHS,
130 - target,
131 - });
29 + it('writes each of the ten legacy paths as a placeholder', () => {
30 + expect(pathsOfKind('placeholder')).toEqual([
31 + 'run-subagent-shared.mjs',
32 + 'run-subagent-acp.mjs',
33 + 'run-subagent-legacy.mjs',
34 + 'run-subagent-output-mcp.mjs',
35 + 'acp-adapters/claude-code-acp.mjs',
36 + 'acp-adapters/cli.js',
37 + 'acp-adapters/codex/darwin-arm64/codex-acp',
38 + 'acp-adapters/codex/darwin-x64/codex-acp',
39 + 'acp-adapters/codex/linux-arm64/codex-acp',
40 + 'acp-adapters/codex/linux-x64/codex-acp',
41 + ]);
42 + });
43
133 - expect(pathsOfKind(entries, 'copy')).toEqual(
134 - expect.arrayContaining([
135 - ...RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
136 - ...RUN_COMPANION_MODULE_FILENAMES,
137 - ...RUN_COMPANION_MODULE_FILENAMES.map(fileName => `services/${fileName}`),
138 - ])
139 - );
44 + it('copies the live companions and their bundles, and nothing else', () => {
45 + expect(pathsOfKind('copy')).toEqual([
46 + 'generation-runtime.mjs',
47 + 'run-helpers-runtime.mjs',
48 + 'services/generation-runtime.mjs',
49 + 'services/run-helpers-runtime.mjs',
50 + ]);
51 });
52 });
53
54 /**
144 - * Packaging names {@link RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS} in every
145 - * archive, because a CLI released before 2026-08-18 verifies an upgrade package
146 - * against all four codex-acp paths and refuses one that is missing any of them.
55 + * An already-released CLI verifies a downloaded upgrade package with its own
56 + * path list, by existence only. From 0.2.15 it also follows the relative `.mjs`
57 + * imports of each wrapper it requires. The lists below are what each range of
58 + * stable releases asks for, spelled out because those binaries no longer change.
59 */
148 -describe('published archive companion coverage', () => {
149 - it.each(RUN_CODEX_ACP_BINARY_TARGETS)(
150 - 'names the $platform-$arch codex-acp binary in every archive',
151 - codexTarget => {
152 - expect(RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS).toContain(codexTarget.relativePath);
153 - }
60 +describe('upgrade from already-released clients', () => {
61 + const entries = archiveCompanionEntries(LIVE_COMPANION_RELATIVE_PATHS);
62 + const entryPaths = entries.map(entry => entry.relativePath);
63 +
64 + const clientRanges: ReadonlyArray<{
65 + readonly range: string;
66 + readonly requiredFor: (host: string) => ReadonlyArray<string>;
67 + }> = [
68 + {
69 + range: '0.2.12 - 0.2.14',
70 + requiredFor: () => LEGACY_WRAPPERS,
71 + },
72 + {
73 + range: '0.2.15 - 0.3.3',
74 + requiredFor: () => [
75 + 'run-helpers-runtime.mjs',
76 + 'services/run-helpers-runtime.mjs',
77 + ...LEGACY_WRAPPERS,
78 + 'acp-adapters/claude-code-acp.mjs',
79 + 'acp-adapters/cli.js',
80 + 'acp-adapters/codex/darwin-arm64/codex-acp',
81 + 'acp-adapters/codex/darwin-x64/codex-acp',
82 + 'acp-adapters/codex/linux-arm64/codex-acp',
83 + 'acp-adapters/codex/linux-x64/codex-acp',
84 + ],
85 + },
86 + {
87 + range: '0.4.0 - 0.4.2',
88 + requiredFor: host => [
89 + 'run-helpers-runtime.mjs',
90 + 'services/run-helpers-runtime.mjs',
91 + 'generation-runtime.mjs',
92 + 'services/generation-runtime.mjs',
93 + ...LEGACY_WRAPPERS,
94 + 'acp-adapters/claude-code-acp.mjs',
95 + 'acp-adapters/cli.js',
96 + `acp-adapters/codex/${host}/codex-acp`,
97 + ],
98 + },
99 + ];
100 +
101 + const cases = clientRanges.flatMap(({ range, requiredFor }) =>
102 + ['darwin-arm64', 'darwin-x64', 'linux-x64', 'linux-arm64'].map(host => ({
103 + range,
104 + host,
105 + required: requiredFor(host),
106 + }))
107 );
108
156 - it('covers one codex-acp binary per release artifact', () => {
157 - expect(codexAcpRelativePathsIn(RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS)).toHaveLength(
158 - RELEASE_ARTIFACT_TARGETS.length
159 - );
160 - });
161 -
162 - it('keeps the portable assets alongside them', () => {
163 - expect(RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS).toEqual(
164 - expect.arrayContaining([...RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS])
165 - );
109 + it.each(cases)('a $range client finds every path it requires on $host', ({ required }) => {
110 + expect(entryPaths).toEqual(expect.arrayContaining([...required]));
111 });
112 });
ts/packages/cli/test/src/scripts/tarball-integrity.test.ts deleted
-206
@@ -1,206 +0,0 @@
1 -import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
2 -import { tmpdir } from 'node:os';
3 -import * as path from 'node:path';
4 -import { fileURLToPath } from 'node:url';
5 -import { afterAll, describe, expect, it } from 'vitest';
6 -
7 -import {
8 - assertBytesMatchIntegrity,
9 - expectedIntegrityFor,
10 - findLockfilePath,
11 - loadLockfileIntegrity,
12 - parseLockfileIntegrity,
13 - TarballIntegrityError,
14 -} from '../../../scripts/_tarball-integrity';
15 -
16 -/**
17 - * A pnpm v9 lockfile excerpt covering the shapes that matter: a quoted scoped
18 - * key, an unquoted bare key, an entry whose resolution carries no integrity,
19 - * and a `snapshots:` repeat of a key already seen in `packages:`.
20 - */
21 -const LOCKFILE = `lockfileVersion: '9.0'
22 -
23 -packages:
24 -
25 - '@zed-industries/codex-acp-linux-x64@0.16.0':
26 - resolution: {integrity: sha512-xs5zZBLpJuciEbZNx6ZSNL0qCa9h3i/zWpj40sp6QtF+L4Ow/7qzHdBzboGhHdcz1jrLedfZeRFDA2Elj8TLMA==}
27 - cpu: [x64]
28 - os: [linux]
29 - hasBin: true
30 -
31 - extract-zip@2.0.1:
32 - resolution: {integrity: sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==}
33 - engines: {node: '>= 10.17.0'}
34 -
35 - some-git-dep@1.0.0:
36 - resolution: {type: git, repo: git@example.test:owner/repo.git, commit: abc123}
37 -
38 -snapshots:
39 -
40 - extract-zip@2.0.1:
41 - dependencies:
42 - debug: 4.4.3
43 -`;
44 -
45 -const integrityOf = async (bytes: Uint8Array, prefix = 'sha512'): Promise<string> => {
46 - const algorithm = prefix === 'sha512' ? 'SHA-512' : 'SHA-256';
47 - const digest = await crypto.subtle.digest(algorithm, bytes as BufferSource);
48 - return `${prefix}-${btoa(String.fromCharCode(...new Uint8Array(digest)))}`;
49 -};
50 -
51 -const tempDirs: Array<string> = [];
52 -
53 -const makeTempDir = async (): Promise<string> => {
54 - const dir = await mkdtemp(path.join(tmpdir(), 'tarball-integrity-'));
55 - tempDirs.push(dir);
56 - return dir;
57 -};
58 -
59 -afterAll(async () => {
60 - await Promise.all(tempDirs.map(dir => rm(dir, { force: true, recursive: true })));
61 -});
62 -
63 -describe('parseLockfileIntegrity', () => {
64 - it('reads quoted scoped keys and unquoted bare keys', () => {
65 - const parsed = parseLockfileIntegrity(LOCKFILE);
66 -
67 - expect(parsed.get('@zed-industries/codex-acp-linux-x64@0.16.0')).toBe(
68 - 'sha512-xs5zZBLpJuciEbZNx6ZSNL0qCa9h3i/zWpj40sp6QtF+L4Ow/7qzHdBzboGhHdcz1jrLedfZeRFDA2Elj8TLMA=='
69 - );
70 - expect(parsed.get('extract-zip@2.0.1')).toBe(
71 - 'sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=='
72 - );
73 - });
74 -
75 - it('skips resolutions that carry no integrity', () => {
76 - expect(parseLockfileIntegrity(LOCKFILE).has('some-git-dep@1.0.0')).toBe(false);
77 - });
78 -
79 - it('is empty for a lockfile with no packages', () => {
80 - expect(parseLockfileIntegrity("lockfileVersion: '9.0'\n").size).toBe(0);
81 - });
82 -});
83 -
84 -describe('expectedIntegrityFor', () => {
85 - const parsed = parseLockfileIntegrity(LOCKFILE);
86 -
87 - it('returns the pinned hash for a package the lockfile resolved', () => {
88 - expect(expectedIntegrityFor(parsed, 'extract-zip', '2.0.1')).toMatch(/^sha512-/);
89 - });
90 -
91 - it('refuses a package the lockfile never resolved', () => {
92 - expect(() => expectedIntegrityFor(parsed, 'extract-zip', '9.9.9')).toThrow(
93 - TarballIntegrityError
94 - );
95 - });
96 -
97 - it('refuses a version the lockfile pins under a different number', () => {
98 - expect(() =>
99 - expectedIntegrityFor(parsed, '@zed-industries/codex-acp-linux-x64', '0.17.0')
100 - ).toThrow(/no integrity hash/);
101 - });
102 -});
103 -
104 -describe('assertBytesMatchIntegrity', () => {
105 - const bytes = new TextEncoder().encode('codex-acp binary bytes');
106 -
107 - it('accepts bytes that hash to the expected value', async () => {
108 - await expect(
109 - assertBytesMatchIntegrity(bytes, await integrityOf(bytes), 'pkg@1.0.0')
110 - ).resolves.toBeUndefined();
111 - });
112 -
113 - it('rejects bytes swapped after the hash was pinned', async () => {
114 - const tampered = new TextEncoder().encode('codex-acp binary bytes + backdoor');
115 -
116 - await expect(
117 - assertBytesMatchIntegrity(tampered, await integrityOf(bytes), 'pkg@1.0.0')
118 - ).rejects.toThrow(TarballIntegrityError);
119 - });
120 -
121 - it('rejects a single flipped byte', async () => {
122 - const tampered = new Uint8Array(bytes);
123 - tampered[0] ^= 0xff;
124 -
125 - await expect(
126 - assertBytesMatchIntegrity(tampered, await integrityOf(bytes), 'pkg@1.0.0')
127 - ).rejects.toThrow(TarballIntegrityError);
128 - });
129 -
130 - it('names the package and both hashes so a mismatch is diagnosable', async () => {
131 - const tampered = new TextEncoder().encode('other');
132 -
133 - await expect(
134 - assertBytesMatchIntegrity(tampered, await integrityOf(bytes), 'pkg@1.0.0')
135 - ).rejects.toThrow(/pkg@1\.0\.0[\s\S]*Expected:[\s\S]*Actual:/);
136 - });
137 -
138 - it('rejects an integrity string whose algorithm it cannot compute', async () => {
139 - await expect(assertBytesMatchIntegrity(bytes, 'md6-abcdef', 'pkg@1.0.0')).rejects.toThrow(
140 - /Unsupported integrity algorithm/
141 - );
142 - });
143 -
144 - it('verifies under whichever sha algorithm the lockfile used', async () => {
145 - await expect(
146 - assertBytesMatchIntegrity(bytes, await integrityOf(bytes, 'sha256'), 'pkg@1.0.0')
147 - ).resolves.toBeUndefined();
148 - });
149 -});
150 -
151 -describe('findLockfilePath', () => {
152 - it('walks up from a nested directory to the workspace lockfile', async () => {
153 - const root = await makeTempDir();
154 - const nested = path.join(root, 'ts', 'packages', 'cli', 'scripts');
155 - await mkdir(nested, { recursive: true });
156 - await writeFile(path.join(root, 'pnpm-lock.yaml'), LOCKFILE, 'utf8');
157 -
158 - await expect(findLockfilePath(nested)).resolves.toBe(path.join(root, 'pnpm-lock.yaml'));
159 - });
160 -
161 - it('fails closed when no lockfile exists above the start directory', async () => {
162 - const root = await makeTempDir();
163 -
164 - await expect(findLockfilePath(root)).rejects.toThrow(TarballIntegrityError);
165 - });
166 -});
167 -
168 -describe('loadLockfileIntegrity', () => {
169 - it('parses the nearest lockfile found above the start directory', async () => {
170 - const root = await makeTempDir();
171 - const nested = path.join(root, 'scripts');
172 - await mkdir(nested, { recursive: true });
173 - await writeFile(path.join(root, 'pnpm-lock.yaml'), LOCKFILE, 'utf8');
174 -
175 - const parsed = await loadLockfileIntegrity(nested);
176 -
177 - expect(parsed.get('extract-zip@2.0.1')).toMatch(/^sha512-/);
178 - });
179 -});
180 -
181 -/**
182 - * Named literally rather than imported from `RUN_CODEX_ACP_BINARY_TARGETS`, for
183 - * the same reason `verify-archive-companions.sh` spells its list out: importing
184 - * that module pulls in `@composio/core`, and this file otherwise needs nothing
185 - * built. Adding a codex target there must extend this list.
186 - */
187 -const CODEX_ACP_PACKAGES = [
188 - '@zed-industries/codex-acp-darwin-arm64',
189 - '@zed-industries/codex-acp-darwin-x64',
190 - '@zed-industries/codex-acp-linux-arm64',
191 - '@zed-industries/codex-acp-linux-x64',
192 -];
193 -
194 -describe('this repository', () => {
195 - it('pins an integrity hash for every codex-acp binary the release packages', async () => {
196 - const parsed = await loadLockfileIntegrity(path.dirname(fileURLToPath(import.meta.url)));
197 - const keys = [...parsed.keys()];
198 -
199 - for (const packageName of CODEX_ACP_PACKAGES) {
200 - expect(
201 - keys.find(key => key.startsWith(`${packageName}@`)),
202 - `${packageName} has no integrity hash in pnpm-lock.yaml`
203 - ).toBeDefined();
204 - }
205 - });
206 -});
ts/packages/cli/test/src/services/cli-user-config.test.ts
+47 -8
@@ -34,7 +34,6 @@ describe('ComposioCliUserConfig', () => {
34 assertEquals(config.data.developerDangerousCommandsEnabled, false);
35 assertEquals(config.data.experimentalFeatures.listen, undefined);
36 assertEquals(config.isExperimentalFeatureEnabled('listen'), false);
37 - assertEquals(config.data.experimentalSubagentTarget, 'auto');
37 assertEquals(config.data.artifactDirectory, undefined);
38
39 const fs = yield* FileSystem.FileSystem;
@@ -83,7 +82,6 @@ describe('ComposioCliUserConfig', () => {
82 assertEquals(config.data.developerDangerousCommandsEnabled, false);
83 assertEquals(config.data.experimentalFeatures.listen, undefined);
84 assertEquals(config.isExperimentalFeatureEnabled('listen'), true);
86 - assertEquals(config.data.experimentalSubagentTarget, 'auto');
85 }).pipe(Effect.provide(CliUserConfigTest));
86 });
87
@@ -103,9 +101,6 @@ describe('ComposioCliUserConfig', () => {
101 multi_account: false,
102 },
103 artifact_directory: '/tmp/composio-artifacts',
106 - experimental_subagent: {
107 - target: 'claude',
108 - },
104 })
105 );
106
@@ -125,7 +120,6 @@ describe('ComposioCliUserConfig', () => {
120 assertEquals(config.data.experimentalFeatures.multi_account, false);
121 assertEquals(config.isExperimentalFeatureEnabled('multi_account'), false);
122 assertEquals(config.data.artifactDirectory, '/tmp/composio-artifacts');
128 - assertEquals(config.data.experimentalSubagentTarget, 'claude');
123
124 const persisted = yield* fileSystem.readFileString(
125 path.join(cwd, '.composio', 'config.json'),
@@ -138,7 +132,6 @@ describe('ComposioCliUserConfig', () => {
132 };
133 experimental_features: { listen: boolean; multi_account: boolean };
134 artifact_directory: string;
141 - experimental_subagent: { target: string };
135 };
136
137 assertEquals(parsed.developer.enabled, false);
@@ -146,7 +139,6 @@ describe('ComposioCliUserConfig', () => {
139 assertEquals(parsed.experimental_features.listen, false);
140 assertEquals(parsed.experimental_features.multi_account, false);
141 assertEquals(parsed.artifact_directory, '/tmp/composio-artifacts');
149 - assertEquals(parsed.experimental_subagent.target, 'claude');
142 }).pipe(Effect.provide(CliUserConfigTest));
143 });
144
@@ -244,6 +236,53 @@ describe('ComposioCliUserConfig', () => {
236 }).pipe(Effect.provide(CliUserConfigTest));
237 });
238
239 + for (const storedSubagent of [{ target: 'gemini' }, null]) {
240 + it.effect(
241 + `ignores a stored experimental_subagent of ${JSON.stringify(storedSubagent)} and writes it back unchanged`,
242 + () => {
243 + const cwd = tempy.temporaryDirectory();
244 + const map = new Map([['DEBUG_OVERRIDE_VERSION', '1.2.3']]) satisfies Map<string, string>;
245 + fs.mkdirSync(path.join(cwd, '.composio'), { recursive: true });
246 + fs.writeFileSync(
247 + path.join(cwd, '.composio', 'config.json'),
248 + JSON.stringify({
249 + developer: { enabled: false, destructive_actions: true },
250 + experimental_subagent: storedSubagent,
251 + security: 'json',
252 + })
253 + );
254 +
255 + const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
256 + const CliUserConfigTest = Layer.provideMerge(
257 + ComposioCliUserConfigLive,
258 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
259 + );
260 +
261 + return Effect.gen(function* () {
262 + const fileSystem = yield* FileSystem.FileSystem;
263 + const config = yield* ComposioCliUserConfig;
264 + assertEquals(config.data.developerModeEnabled, false);
265 + assertEquals(config.data.developerDangerousCommandsEnabled, true);
266 + assertEquals(config.data.security, 'json');
267 +
268 + yield* config.update({ experimentalFeatures: { listen: true } });
269 +
270 + const persisted = yield* fileSystem.readFileString(
271 + path.join(cwd, '.composio', 'config.json'),
272 + 'utf8'
273 + );
274 + const parsed = JSON.parse(persisted) as Record<string, unknown>;
275 +
276 + assertEquals(parsed.developer, { enabled: false, destructive_actions: true });
277 + assertEquals(parsed.security, 'json');
278 + assertEquals(parsed.experimental_features, { listen: true });
279 + assertEquals('experimental_subagent' in parsed, true);
280 + assertEquals(parsed.experimental_subagent, storedSubagent);
281 + }).pipe(Effect.provide(CliUserConfigTest));
282 + }
283 + );
284 + }
285 +
286 it.effect('replaces malformed persisted config with safe defaults', () => {
287 const cwd = tempy.temporaryDirectory();
288 const map = new Map([['DEBUG_OVERRIDE_VERSION', '1.2.3']]) satisfies Map<string, string>;
ts/packages/cli/test/src/services/config.test.ts
+10 -13
@@ -15,7 +15,6 @@ const NORMALIZED_APP_CONFIG_DEFAULTS = {
15 WEBHOOK_SECRET: undefined,
16 CLI_INVOCATION_ORIGIN: undefined,
17 CLI_PARENT_RUN_ID: undefined,
18 - RUN_ACP_ONLY: false,
18 RUN_OUTPUT_DIR: undefined,
19 PERF_DEBUG: false,
20 TOOL_DEBUG: false,
@@ -112,7 +111,6 @@ describe('Config', () => {
111 WEBHOOK_SECRET: 'secret',
112 CLI_INVOCATION_ORIGIN: 'run',
113 CLI_PARENT_RUN_ID: 'run_parent',
115 - RUN_ACP_ONLY: true,
114 RUN_OUTPUT_DIR: '/tmp/composio-output',
115 PERF_DEBUG: true,
116 TOOL_DEBUG: true,
@@ -155,16 +153,14 @@ describe('Config', () => {
153 // config decoding, which would surface as an unrecoverable defect at the call site.
154 const map = new Map([
155 ['COMPOSIO_PERF_DEBUG', ''],
158 - ['COMPOSIO_TOOL_DEBUG', ' '],
159 - ['COMPOSIO_RUN_ACP_ONLY', 'maybe'],
160 - ['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', ''],
156 + ['COMPOSIO_TOOL_DEBUG', 'maybe'],
157 + ['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', ' '],
158 ]) satisfies Map<string, string>;
159
160 const actual = yield* withMapConfigProvider(map)(
161 Config.all({
162 perfDebug: APP_CONFIG.PERF_DEBUG,
163 toolDebug: APP_CONFIG.TOOL_DEBUG,
167 - acpOnly: APP_CONFIG.RUN_ACP_ONLY,
164 disableConnectedAccountCache: APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE,
165 })
166 );
@@ -172,11 +168,10 @@ describe('Config', () => {
168 deepStrictEqual(actual, {
169 // Blank falls back to the flag's own default, ...
170 perfDebug: false,
175 - toolDebug: false,
171 // ... which must hold for a default-true flag too, ...
172 disableConnectedAccountCache: true,
173 // ... while any other non-falsy value counts as set.
179 - acpOnly: true,
174 + toolDebug: true,
175 });
176 })
177 );
@@ -186,18 +181,22 @@ describe('Config', () => {
181 const map = new Map([
182 ['COMPOSIO_PERF_DEBUG', '0'],
183 ['COMPOSIO_TOOL_DEBUG', 'false'],
189 - ['COMPOSIO_RUN_ACP_ONLY', 'OFF'],
184 + ['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'OFF'],
185 ]) satisfies Map<string, string>;
186
187 const actual = yield* withMapConfigProvider(map)(
188 Config.all({
189 perfDebug: APP_CONFIG.PERF_DEBUG,
190 toolDebug: APP_CONFIG.TOOL_DEBUG,
196 - acpOnly: APP_CONFIG.RUN_ACP_ONLY,
191 + disableConnectedAccountCache: APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE,
192 })
193 );
194
200 - deepStrictEqual(actual, { perfDebug: false, toolDebug: false, acpOnly: false });
195 + deepStrictEqual(actual, {
196 + perfDebug: false,
197 + toolDebug: false,
198 + disableConnectedAccountCache: false,
199 + });
200 })
201 );
202
@@ -406,7 +405,6 @@ describe('Config', () => {
405 Effect.gen(function* () {
406 const provider = ConfigProvider.fromEnvRecord(
407 Object.fromEntries([
409 - ['CACHE_DIR', ' /host/cache '],
408 ['npm_config_user_agent', 'pnpm/9.0.0 npm/? node/v22.0.0 darwin arm64'],
409 ['CI', ' TRUE '],
410 ['NO_COLOR', '1'],
@@ -421,7 +419,6 @@ describe('Config', () => {
419 const actual = yield* Config.all(UNPREFIXED_CONFIG).parse(provider);
420
421 expect(actual).toEqual({
424 - CACHE_DIR: '/host/cache',
422 NPM_CONFIG_USER_AGENT: 'pnpm/9.0.0 npm/? node/v22.0.0 darwin arm64',
423 CI_REDACTION_ENABLED: true,
424 INTERACTIVE_PERMISSION_UI_DISABLED: true,
ts/packages/cli/test/src/services/run-companion-modules.test.ts
+80 -130
@@ -6,18 +6,13 @@ import { afterEach, describe, expect, it, layer } from '@effect/vitest';
6 import { ConfigProvider, Effect } from 'effect';
7 import { vi } from 'vitest';
8 import {
9 - hostRunCompanionStaticAssetRelativePaths,
9 listMissingInstalledRunCompanionModules,
10 loadInstalledCompanionModule,
11 repairMissingInstalledRunCompanionModules,
13 - resolveRunCompanionAssetPath,
14 - RUN_CODEX_ACP_BINARY_TARGETS,
15 - RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,
12 + RUN_COMPANION_LEGACY_PLACEHOLDER_RELATIVE_PATHS,
13 RUN_COMPANION_MODULE_BASENAMES,
14 RUN_COMPANION_MODULE_FILENAMES,
15 RUN_COMPANION_RELEASE_TAG_FILENAME,
19 - RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
20 - runCompanionStaticAssetRelativePathsFor,
16 } from 'src/services/run-companion-modules';
17 import { getBaseConfigProvider, extendConfigProvider } from 'src/services/config';
18
@@ -31,11 +26,23 @@ const TEST_BINARY_ASSET_NAMES = [
26 'composio-linux-aarch64.zip',
27 'composio-linux-x64.zip',
28 ];
34 -// A release archive ships every platform's codex-acp binary.
35 -const TEST_COMPANION_RELATIVE_PATHS = [
29 +// A release archive ships the live companions plus the legacy placeholders.
30 +const TEST_ARCHIVE_RELATIVE_PATHS = [
31 ...RUN_COMPANION_MODULE_FILENAMES,
37 - ...RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,
38 -].sort();
32 + ...RUN_COMPANION_LEGACY_PLACEHOLDER_RELATIVE_PATHS,
33 +];
34 +
35 +// What a complete install holds next to the executable.
36 +const writeLiveCompanions = (installDirectory: string) => {
37 + fs.mkdirSync(path.join(installDirectory, 'services'));
38 + for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
39 + fs.writeFileSync(
40 + path.join(installDirectory, fileName),
41 + `export * from "./services/${fileName}";\n`
42 + );
43 + fs.writeFileSync(path.join(installDirectory, 'services', fileName), 'export {};\n');
44 + }
45 +};
46
47 const stubRepairFetch = () => {
48 const fetchMock = vi.fn((url: string) =>
@@ -63,11 +70,16 @@ const mockArchiveContents = (missingRelativePath?: string) => {
70 extractZipMock.mockImplementation(
71 async (archivePath: string, options: { readonly dir: string }) => {
72 const packageDirectory = path.join(options.dir, path.parse(archivePath).name);
66 - for (const relativePath of TEST_COMPANION_RELATIVE_PATHS) {
73 + for (const relativePath of TEST_ARCHIVE_RELATIVE_PATHS) {
74 if (relativePath === missingRelativePath) continue;
75 const filePath = path.join(packageDirectory, relativePath);
76 fs.mkdirSync(path.dirname(filePath), { recursive: true });
70 - fs.writeFileSync(filePath, `new:${relativePath}`);
77 + fs.writeFileSync(
78 + filePath,
79 + RUN_COMPANION_LEGACY_PLACEHOLDER_RELATIVE_PATHS.includes(relativePath)
80 + ? ''
81 + : `new:${relativePath}`
82 + );
83 }
84 }
85 );
@@ -80,46 +92,37 @@ describe('run-companion-modules', () => {
92 vi.unstubAllEnvs();
93 });
94
83 - describe('runCompanionStaticAssetRelativePathsFor', () => {
84 - it('[Given] a supported host [Then] it requires only that host codex-acp binary', () => {
85 - for (const target of RUN_CODEX_ACP_BINARY_TARGETS) {
86 - expect(
87 - runCompanionStaticAssetRelativePathsFor({
88 - platform: target.platform,
89 - arch: target.arch,
90 - })
91 - ).toEqual([...RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS, target.relativePath]);
92 - }
93 - });
95 + it('pins the legacy placeholder list to the ten paths released clients require', () => {
96 + expect(RUN_COMPANION_LEGACY_PLACEHOLDER_RELATIVE_PATHS).toEqual([
97 + 'run-subagent-shared.mjs',
98 + 'run-subagent-acp.mjs',
99 + 'run-subagent-legacy.mjs',
100 + 'run-subagent-output-mcp.mjs',
101 + 'acp-adapters/claude-code-acp.mjs',
102 + 'acp-adapters/cli.js',
103 + 'acp-adapters/codex/darwin-arm64/codex-acp',
104 + 'acp-adapters/codex/darwin-x64/codex-acp',
105 + 'acp-adapters/codex/linux-arm64/codex-acp',
106 + 'acp-adapters/codex/linux-x64/codex-acp',
107 + ]);
108 + });
109
95 - it('[Given] an unsupported host [Then] it requires only the portable assets', () => {
96 - expect(runCompanionStaticAssetRelativePathsFor({ platform: 'win32', arch: 'x64' })).toEqual(
97 - RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS
98 - );
99 - });
110 + it('keeps the legacy placeholders out of the live companion list', () => {
111 + expect(
112 + RUN_COMPANION_MODULE_FILENAMES.filter(fileName =>
113 + RUN_COMPANION_LEGACY_PLACEHOLDER_RELATIVE_PATHS.includes(fileName)
114 + )
115 + ).toEqual([]);
116 });
117
118 layer(BunServices.layer)(it => {
119 it.effect(
104 - "[Given] an install lacking another platform's codex-acp binary [Then] nothing needs repair",
120 + '[Given] an install with only the live companions and their bundles [Then] nothing needs repair',
121 () =>
122 Effect.gen(function* () {
107 - const hostStaticAssets = yield* hostRunCompanionStaticAssetRelativePaths;
108 - const foreignRelativePaths = RUN_CODEX_ACP_BINARY_TARGETS.map(
109 - target => target.relativePath
110 - ).filter(relativePath => !hostStaticAssets.includes(relativePath));
111 -
112 - expect(foreignRelativePaths.length).toBe(RUN_CODEX_ACP_BINARY_TARGETS.length - 1);
113 -
114 - const installDirectory = fs.mkdtempSync(
115 - path.join(os.tmpdir(), 'composio-run-host-scope-')
116 - );
123 + const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-live-'));
124 const execPath = path.join(installDirectory, 'composio');
118 - for (const relativePath of [...RUN_COMPANION_MODULE_FILENAMES, ...hostStaticAssets]) {
119 - const filePath = path.join(installDirectory, relativePath);
120 - fs.mkdirSync(path.dirname(filePath), { recursive: true });
121 - fs.writeFileSync(filePath, `installed:${relativePath}`);
122 - }
125 + writeLiveCompanions(installDirectory);
126 const fetchMock = stubRepairFetch();
127
128 return yield* Effect.gen(function* () {
@@ -141,13 +144,16 @@ describe('run-companion-modules', () => {
144 );
145
146 it.effect(
144 - '[Given] an install without ACP adapters [Then] a plain run neither reports nor repairs anything',
147 + '[Given] an install holding empty legacy placeholders [Then] it is not damaged and nothing is repaired',
148 () =>
149 Effect.gen(function* () {
147 - const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-no-acp-'));
150 + const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-legacy-'));
151 const execPath = path.join(installDirectory, 'composio');
149 - for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
150 - fs.writeFileSync(path.join(installDirectory, fileName), '', 'utf8');
152 + writeLiveCompanions(installDirectory);
153 + for (const relativePath of RUN_COMPANION_LEGACY_PLACEHOLDER_RELATIVE_PATHS) {
154 + const filePath = path.join(installDirectory, relativePath);
155 + fs.mkdirSync(path.dirname(filePath), { recursive: true });
156 + fs.writeFileSync(filePath, '');
157 }
158 const fetchMock = stubRepairFetch();
159
@@ -160,8 +166,6 @@ describe('run-companion-modules', () => {
166 appVersion: '0.0.0-test',
167 })
168 ).toEqual({ repaired: false });
163 - // The self-repair download is what 404s on a dev build; the ACP tier
164 - // must never reach it.
169 expect(fetchMock).not.toHaveBeenCalled();
170 }).pipe(
171 Effect.ensuring(
@@ -171,11 +175,30 @@ describe('run-companion-modules', () => {
175 })
176 );
177
178 + it.effect('[Given] a missing run-helpers-runtime.mjs [Then] it is reported as missing', () =>
179 + Effect.gen(function* () {
180 + const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-'));
181 + const execPath = path.join(installDirectory, 'composio');
182 + writeLiveCompanions(installDirectory);
183 + fs.rmSync(path.join(installDirectory, 'run-helpers-runtime.mjs'));
184 +
185 + return yield* Effect.gen(function* () {
186 + expect(yield* listMissingInstalledRunCompanionModules(execPath)).toEqual([
187 + 'run-helpers-runtime.mjs',
188 + ]);
189 + }).pipe(
190 + Effect.ensuring(
191 + Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
192 + )
193 + );
194 + })
195 + );
196 +
197 it.effect(
175 - '[Given] a missing companion wrapper [Then] repair still restores the ACP tier too',
198 + '[Given] a missing companion wrapper [Then] repair restores the companions and leaves the archive placeholders behind',
199 () => {
200 const installDirectory = fs.mkdtempSync(
178 - path.join(os.tmpdir(), 'composio-run-tier-repair-')
201 + path.join(os.tmpdir(), 'composio-run-repair-scope-')
202 );
203 const execPath = path.join(installDirectory, 'composio');
204 stubRepairFetch();
@@ -189,9 +212,9 @@ describe('run-companion-modules', () => {
212 });
213
214 expect(result).toEqual({ repaired: true, releaseTag: TEST_RELEASE_TAG });
192 - for (const relativePath of yield* hostRunCompanionStaticAssetRelativePaths) {
193 - expect(fs.existsSync(path.join(installDirectory, relativePath))).toBe(true);
194 - }
215 + expect(fs.readdirSync(installDirectory).sort()).toEqual(
216 + [...RUN_COMPANION_MODULE_FILENAMES, RUN_COMPANION_RELEASE_TAG_FILENAME].sort()
217 + );
218 }).pipe(
219 Effect.ensuring(
220 Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
@@ -269,7 +292,7 @@ describe('run-companion-modules', () => {
292 it.effect('[Given] a complete archive [Then] repair atomically replaces companions', () => {
293 const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-repair-test-'));
294 const execPath = path.join(installDirectory, 'composio');
272 - const companionRelativePath = TEST_COMPANION_RELATIVE_PATHS[0]!;
295 + const companionRelativePath = RUN_COMPANION_MODULE_FILENAMES[0]!;
296 const companionPath = path.join(installDirectory, companionRelativePath);
297 const releaseTagPath = path.join(installDirectory, RUN_COMPANION_RELEASE_TAG_FILENAME);
298 fs.mkdirSync(path.dirname(companionPath), { recursive: true });
@@ -305,7 +328,7 @@ describe('run-companion-modules', () => {
328 const execPath = path.join(installDirectory, 'composio');
329 const releaseTagPath = path.join(installDirectory, RUN_COMPANION_RELEASE_TAG_FILENAME);
330 const previousReleaseTag = '@composio/cli@0.2.31\n';
308 - const missingRelativePath = TEST_COMPANION_RELATIVE_PATHS.at(-1)!;
331 + const missingRelativePath = RUN_COMPANION_MODULE_FILENAMES.at(-1)!;
332 fs.writeFileSync(releaseTagPath, previousReleaseTag);
333 stubRepairFetch();
334 mockArchiveContents(missingRelativePath);
@@ -449,79 +472,6 @@ describe('run-companion-modules', () => {
472 });
473 });
474
452 -/**
453 - * Release archives fill only the codex-acp binary their own platform can execute
454 - * and leave the other three as empty placeholders, so that a CLI installed
455 - * before 2026-08-18 still passes its upgrade verification. A placeholder must
456 - * never be handed back as a runnable adapter.
457 - */
458 -describe('resolveRunCompanionAssetPath', () => {
459 - layer(BunServices.layer)(it => {
460 - const withInstallDirectory = <A, E, R>(
461 - contents: number,
462 - use: (execPath: string) => Effect.Effect<A, E, R>
463 - ) =>
464 - Effect.gen(function* () {
465 - const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'companion-asset-'));
466 - const execPath = path.join(installDirectory, 'composio');
467 - const assetPath = path.join(installDirectory, 'acp-adapters', 'codex', 'darwin-arm64');
468 - fs.mkdirSync(assetPath, { recursive: true });
469 - fs.writeFileSync(path.join(assetPath, 'codex-acp'), Buffer.alloc(contents));
470 - return yield* use(execPath).pipe(
471 - Effect.ensuring(
472 - Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
473 - )
474 - );
475 - });
476 -
477 - const relativePathFromRoot = 'acp-adapters/codex/darwin-arm64/codex-acp';
478 -
479 - it.effect('resolves a populated binary', () =>
480 - withInstallDirectory(64, execPath =>
481 - Effect.gen(function* () {
482 - const resolved = yield* resolveRunCompanionAssetPath({
483 - callerImportMetaUrl: import.meta.url,
484 - execPath,
485 - relativePathFromRoot,
486 - requireNonEmpty: true,
487 - });
488 -
489 - expect(resolved).toBe(path.join(path.dirname(execPath), relativePathFromRoot));
490 - })
491 - )
492 - );
493 -
494 - it.effect('reports an empty placeholder as absent under requireNonEmpty', () =>
495 - withInstallDirectory(0, execPath =>
496 - Effect.gen(function* () {
497 - const resolved = yield* resolveRunCompanionAssetPath({
498 - callerImportMetaUrl: import.meta.url,
499 - execPath,
500 - relativePathFromRoot,
501 - requireNonEmpty: true,
502 - });
503 -
504 - expect(resolved).toBeNull();
505 - })
506 - )
507 - );
508 -
509 - it.effect('still resolves an empty file when only existence is required', () =>
510 - withInstallDirectory(0, execPath =>
511 - Effect.gen(function* () {
512 - const resolved = yield* resolveRunCompanionAssetPath({
513 - callerImportMetaUrl: import.meta.url,
514 - execPath,
515 - relativePathFromRoot,
516 - });
517 -
518 - expect(resolved).toBe(path.join(path.dirname(execPath), relativePathFromRoot));
519 - })
520 - )
521 - );
522 - });
523 -});
524 -
475 describe('loadInstalledCompanionModule', () => {
476 layer(BunServices.layer)(it => {
477 it('registers the in-process companion alongside the run preload set', () => {
ts/packages/cli/test/src/services/run-helpers-runtime.test.ts
+67 -5
@@ -1,7 +1,7 @@
1 import { inspect } from 'node:util';
2 import { Predicate } from 'effect';
3 import { afterEach, assert, describe, expect, it, vi } from 'vitest';
4 -import { installRunHelpers } from 'src/services/run-helpers-runtime';
4 +import { installRunHelpers, parseJson } from 'src/services/run-helpers-runtime';
5 import { ToolInputRequiredError } from 'src/utils/tool-input-required';
6
7 const installedGlobalNames = [
@@ -19,6 +19,30 @@ const originalGlobalDescriptors = new Map(
19 installedGlobalNames.map(name => [name, Object.getOwnPropertyDescriptor(globalThis, name)])
20 );
21
22 +const readInstalledFunction = (name: string): ((...args: ReadonlyArray<unknown>) => unknown) => {
23 + const value: unknown = Reflect.get(globalThis, name);
24 + if (typeof value !== 'function') {
25 + throw new Error(`installRunHelpers() did not install ${name}().`);
26 + }
27 + return (...args) => Reflect.apply(value, undefined, [...args]);
28 +};
29 +
30 +describe('parseJson', () => {
31 + it('[Given] blank text [Then] returns undefined', () => {
32 + expect(parseJson(' ')).toBeUndefined();
33 + });
34 +
35 + it('[Given] valid JSON [Then] returns the parsed value', () => {
36 + expect(parseJson(' {"a": 1} ')).toEqual({ a: 1 });
37 + expect(parseJson('[1, 2, 3]')).toEqual([1, 2, 3]);
38 + expect(parseJson('null')).toBeNull();
39 + });
40 +
41 + it('[Given] non-JSON text [Then] returns the trimmed text verbatim', () => {
42 + expect(parseJson(' not json at all ')).toBe('not json at all');
43 + });
44 +});
45 +
46 describe('run-helpers-runtime', () => {
47 afterEach(() => {
48 vi.unstubAllGlobals();
@@ -32,6 +56,47 @@ describe('run-helpers-runtime', () => {
56 }
57 });
58
59 + it('[Given] installed helpers [Then] every documented global is defined', async () => {
60 + await installRunHelpers({ cliPrefix: ['composio'] });
61 +
62 + for (const name of ['execute', 'search', 'proxy', 'experimental_subAgent', 'invokeAgent']) {
63 + expect(typeof Reflect.get(globalThis, name)).toBe('function');
64 + }
65 + expect(Reflect.get(globalThis, 'z')).toBeDefined();
66 + expect(Reflect.get(globalThis, 'zod')).toBe(Reflect.get(globalThis, 'z'));
67 + });
68 +
69 + it('[Given] experimental_subAgent or invokeAgent [Then] both reject with the same removal message and alternative', async () => {
70 + await installRunHelpers({ cliPrefix: ['composio'] });
71 +
72 + const outcomes = await Promise.allSettled([
73 + readInstalledFunction('experimental_subAgent')('p'),
74 + readInstalledFunction('invokeAgent')('p'),
75 + ]);
76 +
77 + const messages = outcomes.map(outcome =>
78 + outcome.status === 'rejected' && outcome.reason instanceof Error
79 + ? outcome.reason.message
80 + : undefined
81 + );
82 + expect(outcomes.map(outcome => outcome.status)).toEqual(['rejected', 'rejected']);
83 + expect(messages[0]).toContain('removed');
84 + expect(messages[0]).toContain('automatically approved permission requests');
85 + expect(messages[0]).toContain('let the calling agent summarize');
86 + expect(messages[1]).toBe(messages[0]);
87 + });
88 +
89 + it('[Given] any arguments, including none [Then] experimental_subAgent rejects instead of throwing', async () => {
90 + await installRunHelpers({ cliPrefix: ['composio'] });
91 + const subAgent = readInstalledFunction('experimental_subAgent');
92 +
93 + for (const args of [[], ['p', { target: 'codex' }], [42, null, 'extra']]) {
94 + const returned = subAgent(...args);
95 + expect(returned).toBeInstanceOf(Promise);
96 + await expect(returned).rejects.toThrow(/removed/);
97 + }
98 + });
99 +
100 it('[Given] a malformed proxy session response [Then] it rejects the HTTP boundary payload', async () => {
101 const fetchMock = vi.fn().mockResolvedValue(
102 new Response(JSON.stringify({ session_id: 42 }), {
@@ -288,7 +353,6 @@ describe('run-helpers-runtime', () => {
353 vi.stubEnv('COMPOSIO_RUN_ENV_SENTINEL', 'forwarded');
354 vi.stubEnv('COMPOSIO_PERF_DEBUG', '1');
355 vi.stubEnv('COMPOSIO_TOOL_DEBUG', '1');
291 - vi.stubEnv('COMPOSIO_RUN_ACP_ONLY', '1');
356 vi.stubEnv('BUN_BE_BUN', '1');
357
358 const childScript = [
@@ -298,7 +362,6 @@ describe('run-helpers-runtime', () => {
362 ' sentinel: process.env.COMPOSIO_RUN_ENV_SENTINEL,',
363 ' perfDebug: process.env.COMPOSIO_PERF_DEBUG,',
364 ' toolDebug: process.env.COMPOSIO_TOOL_DEBUG,',
301 - ' acpOnly: process.env.COMPOSIO_RUN_ACP_ONLY,',
365 ' bunBeBun: process.env.BUN_BE_BUN,',
366 ' },',
367 '}));',
@@ -306,7 +369,7 @@ describe('run-helpers-runtime', () => {
369
370 await installRunHelpers({
371 cliPrefix: [process.execPath, '-e', childScript],
309 - helperContext: { perfDebug: false, toolDebug: false, acpOnly: false },
372 + helperContext: { perfDebug: false, toolDebug: false },
373 });
374
375 const installedGlobals: unknown = globalThis;
@@ -324,7 +387,6 @@ describe('run-helpers-runtime', () => {
387 sentinel: 'forwarded',
388 perfDebug: '0',
389 toolDebug: '0',
327 - acpOnly: '0',
390 bunBeBun: '',
391 },
392 });
ts/packages/cli/test/src/services/run-subagent-acp.test.ts deleted
-327
@@ -1,327 +0,0 @@
1 -import * as fs from 'node:fs';
2 -import * as os from 'node:os';
3 -import * as path from 'node:path';
4 -import * as BunServices from '@effect/platform-bun/BunServices';
5 -import { Effect } from 'effect';
6 -import { afterEach, describe, expect, it, vi } from '@effect/vitest';
7 -import {
8 - BufferedChunkLogger,
9 - createStructuredOutputMcpContext,
10 - MissingAcpAdapterAssetsError,
11 - resolveAcpAdapterCommand,
12 - selectPermissionOutcome,
13 -} from 'src/services/run-subagent-acp';
14 -import { RUN_COMPANION_MODULE_FILENAMES } from 'src/services/run-companion-modules';
15 -import { AcpInvokeError, isAcpInvokeError } from 'src/services/run-subagent-shared';
16 -
17 -describe('run-subagent-acp', () => {
18 - afterEach(() => {
19 - vi.unstubAllGlobals();
20 - });
21 -
22 - it.effect(
23 - '[Given] bundled adapter packages [Then] it resolves to the bundled path without npx',
24 - () =>
25 - Effect.gen(function* () {
26 - const result = yield* resolveAcpAdapterCommand('claude');
27 - expect(result.source).toBe('bundled');
28 - expect(result.cmd[0]).toBe(process.execPath);
29 - expect(result.cmd[1]).toMatch(/claude-code-acp/);
30 - }).pipe(Effect.provide(BunServices.layer))
31 - );
32 -
33 - it.effect('[Given] bundled codex adapter [Then] it resolves to the bundled path', () =>
34 - Effect.gen(function* () {
35 - const result = yield* resolveAcpAdapterCommand('codex');
36 - expect(result.source).toBe('bundled');
37 - expect(result.cmd[0]).toBe(process.execPath);
38 - expect(result.cmd[1]).toMatch(/codex-acp/);
39 - }).pipe(Effect.provide(BunServices.layer))
40 - );
41 -
42 - it.effect(
43 - '[Given] a packaged install shipping the adapter [Then] it runs the shipped asset',
44 - () =>
45 - Effect.gen(function* () {
46 - const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-acp-shipped-'));
47 - const execPath = path.join(installDirectory, 'composio');
48 - for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
49 - fs.writeFileSync(path.join(installDirectory, fileName), '', 'utf8');
50 - }
51 - const adapterPath = path.join(installDirectory, 'acp-adapters', 'claude-code-acp.mjs');
52 - fs.mkdirSync(path.dirname(adapterPath), { recursive: true });
53 - fs.writeFileSync(adapterPath, '', 'utf8');
54 -
55 - return yield* Effect.gen(function* () {
56 - const result = yield* resolveAcpAdapterCommand('claude', { execPath });
57 - expect(result.source).toBe('shipped');
58 - expect(result.cmd).toEqual([execPath, adapterPath]);
59 - }).pipe(
60 - Effect.ensuring(
61 - Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
62 - )
63 - );
64 - }).pipe(Effect.provide(BunServices.layer))
65 - );
66 -
67 - it.effect(
68 - '[Given] a packaged install missing the ACP adapters [Then] it names the repair instead of falling back',
69 - () =>
70 - Effect.gen(function* () {
71 - const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-acp-missing-'));
72 - const execPath = path.join(installDirectory, 'composio');
73 - for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
74 - fs.writeFileSync(path.join(installDirectory, fileName), '', 'utf8');
75 - }
76 -
77 - return yield* Effect.gen(function* () {
78 - const error = yield* Effect.flip(resolveAcpAdapterCommand('claude', { execPath }));
79 -
80 - expect(error).toBeInstanceOf(MissingAcpAdapterAssetsError);
81 - expect(error.missingRelativePaths).toContain('acp-adapters/claude-code-acp.mjs');
82 - expect(error.message).toContain(
83 - `This Composio install cannot run a claude sub-agent: the ACP adapter files are missing from ${installDirectory}.`
84 - );
85 - expect(error.message).toContain("Run 'composio upgrade' to restore them");
86 - // Not an AcpInvokeError, so the helper runtime surfaces it to the user
87 - // instead of silently retrying through the legacy sub-agent.
88 - expect(isAcpInvokeError(error)).toBe(false);
89 - }).pipe(
90 - Effect.ensuring(
91 - Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
92 - )
93 - );
94 - }).pipe(Effect.provide(BunServices.layer))
95 - );
96 -
97 - it('[Given] an ACP invoke error [Then] it is classified for fallback', () => {
98 - const error = new AcpInvokeError('initialize_failed', 'boom');
99 - expect(isAcpInvokeError(error)).toBe(true);
100 - expect(error.code).toBe('initialize_failed');
101 - });
102 -
103 - it('[Given] an ACP-like error from another bundle [Then] it is still classified for fallback', () => {
104 - const error = {
105 - name: 'AcpInvokeError',
106 - code: 'prompt_failed',
107 - message: 'boom',
108 - };
109 -
110 - expect(isAcpInvokeError(error)).toBe(true);
111 - });
112 -
113 - it('[Given] an unknown ACP error code [Then] it is not admitted into the fallback union', () => {
114 - const error = {
115 - name: 'AcpInvokeError',
116 - code: 'unexpected_failure',
117 - message: 'boom',
118 - };
119 -
120 - expect(isAcpInvokeError(error)).toBe(false);
121 - });
122 -
123 - it('[Given] a cancelled ACP prompt [Then] it remains fallback-eligible', () => {
124 - const error = new AcpInvokeError('prompt_failed', 'claude ACP prompt was cancelled.');
125 -
126 - expect(isAcpInvokeError(error)).toBe(true);
127 - expect(error.code).toBe('prompt_failed');
128 - });
129 -
130 - it('[Given] tokenized message chunks [Then] it emits buffered readable text', () => {
131 - const helperDebugLog = vi.fn();
132 - const logger = new BufferedChunkLogger('subAgent.acp.message', helperDebugLog);
133 -
134 - logger.push('Pick');
135 - logger.push(' one');
136 - logger.push(' fruit');
137 - logger.push(' from');
138 - logger.push(' the');
139 - logger.push(' mixed');
140 - logger.push(' box.');
141 - logger.flush();
142 -
143 - expect(helperDebugLog).toHaveBeenCalledWith('subAgent.acp.message', {
144 - text: 'Pick one fruit from the mixed box.',
145 - });
146 - });
147 -
148 - it('[Given] a read permission request [Then] it allows the read once', () => {
149 - const result = selectPermissionOutcome(
150 - {
151 - options: [
152 - { optionId: 'allow', kind: 'allow_once', name: 'Allow once' },
153 - { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },
154 - ],
155 - toolCall: {
156 - toolCallId: 'tool-1',
157 - kind: 'read',
158 - title: 'Read File',
159 - rawInput: {
160 - file_path: '/tmp/composio/session/artifacts/emails.json',
161 - },
162 - },
163 - } as never,
164 - ['/tmp/composio/session', '/Users/test/.composio']
165 - );
166 -
167 - expect(result).toEqual({
168 - outcome: {
169 - outcome: 'selected',
170 - optionId: 'allow',
171 - },
172 - });
173 - });
174 -
175 - it('[Given] a non-read permission request [Then] it allows the request in permissive mode', () => {
176 - const result = selectPermissionOutcome(
177 - {
178 - options: [
179 - { optionId: 'allow-always', kind: 'allow_always', name: 'Allow always' },
180 - { optionId: 'allow-once', kind: 'allow_once', name: 'Allow once' },
181 - { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },
182 - ],
183 - toolCall: {
184 - toolCallId: 'tool-2',
185 - kind: 'edit',
186 - title: 'Edit File',
187 - rawInput: {
188 - file_path: '/tmp/composio/session/artifacts/emails.json',
189 - },
190 - },
191 - } as never,
192 - ['/tmp/composio/session', '/Users/test/.composio']
193 - );
194 -
195 - expect(result).toEqual({
196 - outcome: {
197 - outcome: 'selected',
198 - optionId: 'allow-always',
199 - },
200 - });
201 - });
202 -
203 - it('[Given] a title-only read permission request [Then] it still allows the read once', () => {
204 - const result = selectPermissionOutcome(
205 - {
206 - options: [
207 - { optionId: 'allow', kind: 'allow_once', name: 'Allow once' },
208 - { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },
209 - ],
210 - toolCall: {
211 - toolCallId: 'tool-3',
212 - kind: null,
213 - title: 'Read File',
214 - rawInput: {
215 - file_path: '/Users/test/.composio/tool_definitions/GMAIL_FETCH_EMAILS.json',
216 - },
217 - },
218 - } as never,
219 - ['/tmp/composio/session', '/Users/test/.composio']
220 - );
221 -
222 - expect(result).toEqual({
223 - outcome: {
224 - outcome: 'selected',
225 - optionId: 'allow',
226 - },
227 - });
228 - });
229 -
230 - it('[Given] an out-of-scope read request [Then] it still allows the read in permissive mode', () => {
231 - const result = selectPermissionOutcome(
232 - {
233 - options: [
234 - { optionId: 'allow-always', kind: 'allow_always', name: 'Allow always' },
235 - { optionId: 'allow', kind: 'allow_once', name: 'Allow once' },
236 - { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },
237 - ],
238 - toolCall: {
239 - toolCallId: 'tool-4',
240 - kind: 'read',
241 - title: 'Read File',
242 - rawInput: {
243 - file_path: '/etc/passwd',
244 - },
245 - },
246 - } as never,
247 - ['/tmp/composio/session', '/Users/test/.composio']
248 - );
249 -
250 - expect(result).toEqual({
251 - outcome: {
252 - outcome: 'selected',
253 - optionId: 'allow-always',
254 - },
255 - });
256 - });
257 -
258 - it('[Given] a read-only terminal command over an allowed artifact path [Then] it allows the command once', () => {
259 - const result = selectPermissionOutcome(
260 - {
261 - options: [
262 - { optionId: 'allow', kind: 'allow_once', name: 'Allow once' },
263 - { optionId: 'reject', kind: 'reject_once', name: 'Reject once' },
264 - ],
265 - toolCall: {
266 - toolCallId: 'tool-5',
267 - kind: null,
268 - title:
269 - "`head -n 100 /tmp/composio/session/artifacts/emails.json | jq '.data' 2>/dev/null || head -n 100 /tmp/composio/session/artifacts/emails.json`",
270 - rawInput: {},
271 - },
272 - } as never,
273 - ['/tmp/composio/session', '/Users/test/.composio']
274 - );
275 -
276 - expect(result).toEqual({
277 - outcome: {
278 - outcome: 'selected',
279 - optionId: 'allow',
280 - },
281 - });
282 - });
283 -
284 - it.effect(
285 - '[Given] a structured schema [Then] it creates a stdio MCP server context for output capture',
286 - () =>
287 - Effect.gen(function* () {
288 - const helperDebugLog = vi.fn();
289 - const context = yield* createStructuredOutputMcpContext({
290 - options: {
291 - structuredSchema: {
292 - type: 'object',
293 - properties: {
294 - summary: { type: 'string' },
295 - },
296 - required: ['summary'],
297 - },
298 - },
299 - helperDebugLog,
300 - });
301 -
302 - expect(context).not.toBeNull();
303 - expect(context?.mcpServer.command).toBe(process.execPath);
304 - expect(context?.mcpServer.args).toEqual(
305 - expect.arrayContaining([
306 - expect.stringContaining('run-subagent-output-mcp'),
307 - '--schema-file',
308 - expect.stringContaining('schema.json'),
309 - '--result-file',
310 - expect.stringContaining('result.json'),
311 - ])
312 - );
313 - expect(context?.mcpServer.env).toEqual(
314 - expect.arrayContaining([{ name: 'BUN_BE_BUN', value: '1' }])
315 - );
316 - expect(context?.resultFilePath).toContain('result.json');
317 - expect(helperDebugLog).toHaveBeenCalledWith(
318 - 'subAgent.acp.structured_output_tool',
319 - expect.objectContaining({
320 - modulePath: expect.stringContaining('run-subagent-output-mcp'),
321 - })
322 - );
323 -
324 - yield* context!.cleanup;
325 - }).pipe(Effect.provide(BunServices.layer))
326 - );
327 -});
ts/packages/cli/test/src/services/run-subagent-output-mcp.test.ts deleted
-24
@@ -1,24 +0,0 @@
1 -import * as fs from 'node:fs';
2 -import { fileURLToPath } from 'node:url';
3 -import { describe, expect, it } from 'vitest';
4 -import { decodeStructuredSchemaJson } from 'src/services/run-subagent-shared';
5 -
6 -describe('run-subagent-output-mcp source', () => {
7 - it('[Given] a non-object schema file [Then] it rejects the malformed boundary payload', () => {
8 - expect(() => decodeStructuredSchemaJson('[]')).toThrow();
9 - });
10 -
11 - it('[Given] the structured output helper source [Then] it statically imports the MCP SDK', () => {
12 - const sourcePath = fileURLToPath(
13 - new URL('../../../src/services/run-subagent-output-mcp.ts', import.meta.url)
14 - );
15 - const source = fs.readFileSync(sourcePath, 'utf8');
16 -
17 - expect(source).toContain("from '@modelcontextprotocol/sdk/server/mcp.js'");
18 - expect(source).toContain("from '@modelcontextprotocol/sdk/server/stdio.js'");
19 - expect(source).toContain("from '@composio/json-schema-to-zod'");
20 - expect(source).not.toContain("from '@composio/core'");
21 - expect(source).not.toContain('@modelcontextprotocol/sdk/package.json');
22 - expect(source).not.toContain('createRequire(import.meta.url)');
23 - });
24 -});
ts/packages/cli/test/src/services/run-subagent-shared.test.ts deleted
-57
@@ -1,57 +0,0 @@
1 -import { describe, expect, it } from 'vitest';
2 -import { finalizeInvokeAgentText, parseJson } from 'src/services/run-subagent-shared';
3 -
4 -describe('run-subagent-shared JSON probes', () => {
5 - describe('parseJson', () => {
6 - it('[Given] blank text [Then] returns undefined', () => {
7 - expect(parseJson(' ')).toBeUndefined();
8 - });
9 -
10 - it('[Given] valid JSON [Then] returns the parsed value', () => {
11 - expect(parseJson(' {"a": 1} ')).toEqual({ a: 1 });
12 - expect(parseJson('[1, 2, 3]')).toEqual([1, 2, 3]);
13 - expect(parseJson('null')).toBeNull();
14 - });
15 -
16 - it('[Given] non-JSON text [Then] returns the trimmed text verbatim', () => {
17 - expect(parseJson(' not json at all ')).toBe('not json at all');
18 - });
19 - });
20 -
21 - describe('finalizeInvokeAgentText structured extraction', () => {
22 - const options = { structuredSchema: { type: 'object' } as Record<string, unknown> };
23 -
24 - it('[Given] direct JSON output [Then] parses it as the structured output', () => {
25 - expect(finalizeInvokeAgentText('{"a": 1}', options)).toEqual({
26 - result: null,
27 - structuredOutput: { a: 1 },
28 - });
29 - });
30 -
31 - it('[Given] a status line before a fenced JSON block [Then] extracts the fenced payload', () => {
32 - const text = 'Analysis complete.\n```json\n{"b": 2}\n```';
33 - expect(finalizeInvokeAgentText(text, options)).toEqual({
34 - result: null,
35 - structuredOutput: { b: 2 },
36 - });
37 - });
38 -
39 - it('[Given] JSON embedded in prose [Then] extracts the balanced payload', () => {
40 - const text = 'The final answer is {"c": {"nested": true}} as requested.';
41 - expect(finalizeInvokeAgentText(text, options)).toEqual({
42 - result: null,
43 - structuredOutput: { c: { nested: true } },
44 - });
45 - });
46 -
47 - it('[Given] output without any JSON [Then] throws the structured output error', () => {
48 - expect(() => finalizeInvokeAgentText('no structured payload here', options)).toThrow(
49 - 'experimental_subAgent() expected valid JSON output for structured response.'
50 - );
51 - });
52 -
53 - it('[Given] no structured schema [Then] returns the trimmed text as the result', () => {
54 - expect(finalizeInvokeAgentText(' plain answer ', {})).toEqual({ result: 'plain answer' });
55 - });
56 - });
57 -});
ts/packages/cli/test/src/services/runtime-flags.test.ts
+1 -7
@@ -4,7 +4,6 @@ import { ConfigProvider, Effect } from 'effect';
4 import {
5 cliDebugFlagsLayer,
6 debugFlagsToChildEnv,
7 - isAcpOnlyEnabled,
7 isPerfDebugEnabled,
8 isTelemetryDebugEnabled,
9 isToolDebugEnabled,
@@ -22,13 +21,11 @@ describe('debugFlagsToChildEnv', () => {
21 debugFlagsToChildEnv({
22 perfDebug: true,
23 toolDebug: false,
25 - acpOnly: true,
24 telemetryDebug: false,
25 })
26 ).toEqual({
27 COMPOSIO_PERF_DEBUG: '1',
28 COMPOSIO_TOOL_DEBUG: '0',
31 - COMPOSIO_RUN_ACP_ONLY: '1',
29 COMPOSIO_CLI_TELEMETRY_DEBUG: '0',
30 });
31 });
@@ -64,7 +61,6 @@ const enabledDebugConfig = ConfigProvider.fromEnvRecord({
61 const readAllDebugFlags = Effect.all({
62 perfDebug: isPerfDebugEnabled,
63 toolDebug: isToolDebugEnabled,
67 - acpOnly: isAcpOnlyEnabled,
64 });
65
66 describe('debug flag precedence', () => {
@@ -74,7 +70,6 @@ describe('debug flag precedence', () => {
70 expect(yield* readAllDebugFlags).toEqual({
71 perfDebug: true,
72 toolDebug: true,
77 - acpOnly: true,
73 });
74 }).pipe(
75 Effect.provide(cliDebugFlagsLayer(NO_CLI_DEBUG_FLAG_OVERRIDES)),
@@ -87,10 +82,9 @@ describe('debug flag precedence', () => {
82 expect(yield* readAllDebugFlags).toEqual({
83 perfDebug: false,
84 toolDebug: false,
90 - acpOnly: false,
85 });
86 }).pipe(
93 - Effect.provide(cliDebugFlagsLayer({ perfDebug: false, toolDebug: false, acpOnly: false })),
87 + Effect.provide(cliDebugFlagsLayer({ perfDebug: false, toolDebug: false })),
88 Effect.provideService(ConfigProvider.ConfigProvider, enabledDebugConfig)
89 )
90 );
ts/packages/cli/test/src/services/user-context.test.ts
-2
@@ -52,14 +52,12 @@ const MockCliUserConfigLayer = Layer.succeed(
52 developerDangerousCommandsEnabled: false,
53 experimentalFeatures: {},
54 artifactDirectory: undefined,
55 - experimentalSubagentTarget: 'auto',
55 security: 'auto',
56 },
57 raw: CliUserConfig.make({
58 developer: { enabled: true, destructiveActions: false },
59 experimentalFeatures: {},
60 artifactDirectory: Option.none(),
62 - experimentalSubagent: Option.none(),
61 security: 'auto',
62 }),
63 channel: 'beta',
ts/packages/cli/tsdown.config.ts
+2 -14
@@ -3,26 +3,14 @@ import { baseConfig } from '../../../tsdown.config.base.ts';
3
4 export default defineConfig({
5 ...baseConfig,
6 - entry: [
7 - 'src/bin.ts',
8 - 'src/services/run-subagent-shared.ts',
9 - 'src/services/run-subagent-acp.ts',
10 - 'src/services/run-subagent-legacy.ts',
11 - 'src/services/run-subagent-output-mcp.ts',
12 - 'src/services/generation-runtime.ts',
13 - ],
6 + entry: ['src/bin.ts', 'src/services/generation-runtime.ts'],
7 format: ['esm'],
8 shims: true,
9 tsconfig: './tsconfig.src.json',
10 deps: {
11 ...baseConfig.deps,
12 neverBundle: [/^bun:/, /^node:/],
20 - alwaysBundle: [
21 - '@composio/core',
22 - /^zod(?:\/.*)?$/,
23 - /^@agentclientprotocol\/sdk(?:\/.*)?$/,
24 - /^@modelcontextprotocol\/sdk(?:\/.*)?$/,
25 - ],
13 + alwaysBundle: ['@composio/core', /^zod(?:\/.*)?$/],
14 },
15 publint: undefined,
16 attw: undefined,