@devries-cameron20 / composio Mirror · read-only / commits / c7e7da1e0
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, 11:00 UTC

refactor(cli): remove experimental local-tools stack (#4682)

This PR: - deletes `@composio/cli-local-tools` (TypeScript + Swift sources, the `peekaboo` and `platform-imessage` submodules) and its workspace, changeset, oxlint and `.gitattributes` entries - removes the `local-tools` command group, `dev native-ui`, the `local_tools` experimental flag, and every `LOCAL_*` branch in `execute`, `search`, `ToolsExecutor`, input validation and Tool Router session creation - drops the Swift 6.2 setup and sidecar build/verify steps from `build-cli-binaries.yml`; archives and `composio upgrade` no longer carry `local-tools-binaries/` - makes the browser page the only permission prompt; the CI kill switch and caller-agent detection it still needs move to `src/services/permission-ui.ts` - removes `atomicReplaceDirectory`, whose only caller was the local-tools upgrade step - drops `local-tools-binaries` from the uninstall lists in `INSTALL.md`, `docs/content/docs/cli.mdx` and `cli.install-health-check.yml`; `install.sh` and `composio upgrade` now delete a leftover `local-tools-binaries/` from older installs ## Context The local-tools stack was on for beta and off for stable, and the docs didn't cover it, yet every release still installed Swift and built three macOS sidecars. Behavior on stable is unchanged. Enhanced controls stay disabled on Intel Macs (#3421). A stored `local_tools` setting is now listed as an unknown feature and has no effect. ## Testing - `pnpm typecheck` and `pnpm test` in `ts/packages/cli`: 1,450 tests pass - `oxlint`, `pnpm test:install-sh`, `pnpm test:release-workflow`, `test/install-sh-uninstall-snippet.test.sh`, `pnpm validate:agent-skills`, `pnpm validate:skill-routing`, `pnpm validate:changesets` - local `build-binary.ts`: `composio local-tools` is now an unknown subcommand and `dist/` has no `local-tools-binaries/` The `cli.mdx` edit needs a docs KB semantic artifact rebuild before merge.

Alberto Schiabel committed Sep 29, 2026 at 04:57 UTC c7e7da1e0542a1fbe82629bcf96c9da1d3f9da25
115 files changed +269 -9516
.agents/skills/cli-release/SKILL.md
+1 -1
@@ -11,7 +11,7 @@ Read `references/release-workflow.md` before selecting a candidate or dispatchin
11
12 ## Release Contract
13
14 -- Never add a Changeset for `@composio/cli` or `@composio/cli-local-tools`; both packages are ignored by Changesets and such files wedge `ts.release.yml`.
14 +- Never add a Changeset for `@composio/cli`; the package is ignored by Changesets and such files wedge `ts.release.yml`.
15 - Treat a merge to `next` that touches CLI paths as a beta build. Promote a tested beta with the `promote-stable` workflow action for the normal stable-release path.
16 - Never bump the private CLI `package.json` to select a binary version. For an
17 intentional minor or major, build an explicitly versioned beta and promote
.agents/skills/cli-release/references/release-workflow.md
+2 -2
@@ -17,7 +17,7 @@
17 - `.github/scripts/cli-release/resolve-release-target.sh` decides the tag and source commit.
18 - `.github/scripts/cli-release/verify-assets.sh` defines the required asset set.
19 - `.github/workflows/cli.test-installation.yml` validates installers after publication.
20 -- `.changeset/config.json` ignores `@composio/cli` and `@composio/cli-local-tools`.
20 +- `.changeset/config.json` ignores `@composio/cli`.
21
22 `ts.release.yml` is the TypeScript SDK/npm release train. It is not the normal CLI binary release path.
23
@@ -36,7 +36,7 @@ dispatch an explicitly versioned beta, verify it, and promote that exact beta.
36
37 ## Changeset Rule
38
39 -Never create a `.changeset/*.md` entry for `@composio/cli` or `@composio/cli-local-tools` while those packages remain in `.changeset/config.json#ignore`.
39 +Never create a `.changeset/*.md` entry for `@composio/cli` while it remains in `.changeset/config.json#ignore`.
40
41 An ignored-package changeset makes `changesets/action` enter version-PR mode, while `changeset version` emits no commit. The action then fails with `No commits between next and changeset-release/next` and blocks unrelated SDK publishing.
42
.agents/skills/repo-guidance/references/repository-workflow.md
+1 -1
@@ -48,7 +48,7 @@ make build
48 ## Changesets
49
50 - Add a changeset for changes to published TypeScript packages.
51 -- `@composio/cli` and `@composio/cli-local-tools` are ignored by Changesets. Never target them in a changeset while they remain ignored; use the `cli-release` skill for beta builds and stable promotion.
51 +- `@composio/cli` is ignored by Changesets. Never target it in a changeset while it remains ignored; use the `cli-release` skill for beta builds and stable promotion.
52 - Do not add a changeset for repo guidance, docs-only, tests-only, or validation-only changes unless release metadata changes.
53
54 ## Generated And Vendor Files
.changeset/config.json
+1 -1
@@ -14,5 +14,5 @@
14 "___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH": {
15 "onlyUpdatePeerDependentsWhenOutOfRange": true
16 },
17 - "ignore": ["@composio/cli", "@composio/cli-local-tools"]
17 + "ignore": ["@composio/cli"]
18 }
.gitattributes
-1
@@ -4,7 +4,6 @@
4
5 # Vendored, read-only reference snapshots (git submodules)
6 ts/vendor/** linguist-vendored=true
7 -ts/packages/cli-local-tools/vendor/** linguist-vendored=true
7
8 # Generated SDK surfaces (produced by `composio generate` / the build pipeline)
9 ts/packages/core/generated/** linguist-generated=true
.github/workflows/build-cli-binaries.yml
-34
@@ -5,7 +5,6 @@ on:
5 branches: [next]
6 paths:
7 - 'ts/packages/cli/**'
8 - - 'ts/packages/cli-local-tools/**'
8 - '.github/actions/setup-node-pnpm-bun/action.yml'
9 - '.github/scripts/cli-release/**'
10 - '.github/workflows/build-cli-binaries.yml'
@@ -99,22 +98,18 @@ jobs:
98 - target: bun-linux-x64
99 artifact: composio-linux-x64
100 runner: ubuntu-latest
102 - local_tools_target: ''
101 codex_target: linux-x64
102 - target: bun-linux-arm64
103 artifact: composio-linux-aarch64
104 runner: ubuntu-latest
107 - local_tools_target: ''
105 codex_target: linux-arm64
106 - target: bun-darwin-x64
107 artifact: composio-darwin-x64
108 runner: macos-15-intel
112 - local_tools_target: ''
109 codex_target: darwin-x64
110 - target: bun-darwin-arm64
111 artifact: composio-darwin-aarch64
112 runner: macos-15
117 - local_tools_target: darwin-arm64
113 codex_target: darwin-arm64
114
115 steps:
@@ -129,30 +124,9 @@ jobs:
124 - name: Install dependencies
125 run: pnpm install --frozen-lockfile
126
132 - - name: Setup Swift 6.2 for local-tool sidecars
133 - if: matrix.local_tools_target != ''
134 - uses: swift-actions/setup-swift@364295d9c23900ce04d4e5cc708387921b4e50f9 # v3
135 - with:
136 - swift-version: '6.2'
137 -
138 - - name: Verify Swift toolchain
139 - if: matrix.local_tools_target != ''
140 - run: swift --version
141 -
127 - name: Build packages
128 run: pnpm build:packages
129
145 - - name: Build local-tool sidecar binaries
146 - if: matrix.local_tools_target != ''
147 - run: pnpm --filter @composio/cli-local-tools build:local-tool-binaries -- --target ${{ matrix.local_tools_target }}
148 -
149 - - name: Verify local-tool sidecars
150 - if: matrix.local_tools_target != ''
151 - run: |
152 - test -x ts/packages/cli-local-tools/local-tools-binaries/beeper-imessage/${{ matrix.local_tools_target }}/imessage-cli
153 - test -x ts/packages/cli-local-tools/local-tools-binaries/peekaboo/${{ matrix.local_tools_target }}/peekaboo
154 - test -x ts/packages/cli-local-tools/local-tools-binaries/composio-native-ui/${{ matrix.local_tools_target }}/composio-native-ui
155 -
130 - name: Cross-compile CLI binary
131 working-directory: ts/packages/cli
132 env:
@@ -200,14 +174,6 @@ jobs:
174 HOST_CODEX_TARGET: ${{ matrix.codex_target }}
175 run: bash "${{ github.workspace }}/.github/scripts/cli-release/verify-archive-companions.sh"
176
203 - - name: Verify local-tool sidecars in archive
204 - if: matrix.local_tools_target != ''
205 - working-directory: ts/packages/cli
206 - run: |
207 - unzip -Z1 dist/binaries/${{ matrix.artifact }}.zip | grep -F "local-tools-binaries/beeper-imessage/${{ matrix.local_tools_target }}/imessage-cli"
208 - unzip -Z1 dist/binaries/${{ matrix.artifact }}.zip | grep -F "local-tools-binaries/peekaboo/${{ matrix.local_tools_target }}/peekaboo"
209 - unzip -Z1 dist/binaries/${{ matrix.artifact }}.zip | grep -F "local-tools-binaries/composio-native-ui/${{ matrix.local_tools_target }}/composio-native-ui"
210 -
177 - name: Upload artifact
178 uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
179 with:
.github/workflows/cli.install-e2e.yml
-1
@@ -10,7 +10,6 @@ on:
10 - 'install/**'
11 - 'test/install-sh-release-resolution.test.sh'
12 - 'ts/packages/cli/**'
13 - - 'ts/packages/cli-local-tools/**'
13 - 'ts/e2e-tests/cli/install/**'
14 - 'ts/e2e-tests/_utils/**'
15 - '.github/actions/setup-node-pnpm-bun/action.yml'
.gitmodules
-7
@@ -5,10 +5,3 @@
5 [submodule "ts/vendor/clack"]
6 path = ts/vendor/clack
7 url = https://github.com/bombshell-dev/clack.git
8 -[submodule "ts/packages/cli-local-tools/vendor/platform-imessage"]
9 - path = ts/packages/cli-local-tools/vendor/platform-imessage
10 - url = https://github.com/ComposioHQ/platform-imessage
11 - branch = main
12 -[submodule "ts/packages/cli-local-tools/vendor/peekaboo"]
13 - path = ts/packages/cli-local-tools/vendor/peekaboo
14 - url = https://github.com/steipete/Peekaboo
.oxlintrc.json
-1
@@ -19,7 +19,6 @@
19 // The docs site has its own Bun dependency tree and nested oxlint config.
20 "docs/**",
21 "ts/vendor/**",
22 - "ts/packages/cli-local-tools/vendor/**",
22 "ts/packages/core/generated/**",
23 "ts/packages/core/pack/generated/**",
24 "ts/packages/slim/generated/**",
AGENTS.md
+1 -2
@@ -61,7 +61,6 @@ docs/decisions/ Neutral docs decisions and ADR-style records
61 Do not hand-edit these. They are regenerated or vendored, and edits will be overwritten. They are also marked `linguist-generated`/`linguist-vendored` in `.gitattributes`.
62
63 - `ts/vendor/**` — vendored read-only snapshots of Effect and Clack (git submodules); reference only.
64 -- `ts/packages/cli-local-tools/vendor/**` — vendored local-tool sources (git submodules).
64 - `ts/packages/core/generated/**`, `ts/packages/core/pack/generated/**` — generated SDK surfaces produced by `composio generate` / the build pipeline.
65 - `pnpm-lock.yaml`, `uv.lock`, `**/bun.lock` — package-manager lockfiles; change them by running the package manager, never by hand.
66
@@ -100,7 +99,7 @@ make build
99 ## Release And Package Notes
100
101 - TypeScript package releases use Changesets. Add a changeset only when published TypeScript packages change.
103 -- `@composio/cli` and `@composio/cli-local-tools` are excluded from Changesets; use `cli-release` for CLI binaries and never target those packages in a changeset while they remain ignored.
102 +- `@composio/cli` is excluded from Changesets; use `cli-release` for CLI binaries and never target that package in a changeset while it remains ignored.
103 - Documentation-only and agent-guidance-only changes do not need a changeset.
104 - Python release metadata lives in `python/pyproject.toml`, `python/setup.py`, and `uv.lock`.
105 - Bumping generated clients is manual. Verify the package version is published before changing pins.
CONTRIBUTING.md
-1
@@ -107,7 +107,6 @@ composio/
107 │ │ ├── core/ # Core SDK package (@composio/core)
108 │ │ ├── cli/ # CLI binary and command implementations
109 │ │ ├── cli-keyring/ # Keyring helper for the CLI
110 -│ │ ├── cli-local-tools/ # Local tools support for the CLI
110 │ │ ├── providers/ # AI framework provider adapters
111 │ │ ├── json-schema-to-zod/ # Schema conversion utility
112 │ │ └── ts-builders/ # TypeScript build helpers
install.sh
+6
@@ -318,6 +318,12 @@ install_bundle() {
318 publish_staged_entry "$stage/composio"
319 rmdir "$stage" || warn "Published CLI; retained recovery staging directory at $stage"
320 stage=
321 +
322 + # Remove legacy sidecars only when the selected release omits them.
323 + if [ ! -d "$install_bundle_dir/local-tools-binaries" ]; then
324 + rm -rf "$resolved_install_dir/local-tools-binaries" ||
325 + warn "Could not remove obsolete $resolved_install_dir/local-tools-binaries"
326 + fi
327 }
328
329 install_entry_point() {
package.json
-2
@@ -13,7 +13,6 @@
13 "ts/packages/json-schema-to-zod",
14 "ts/packages/cli",
15 "ts/packages/cli-keyring",
16 - "ts/packages/cli-local-tools",
16 "ts/packages/ts-builders",
17 "ts/packages/providers/*"
18 ],
@@ -77,7 +76,6 @@
76 "@changesets/cli": "^3.0.3",
77 "@changesets/read": "^1.0.1",
78 "@composio/anthropic": "workspace:*",
80 - "@composio/cli-local-tools": "workspace:*",
79 "@composio/core": "workspace:*",
80 "@composio/openai": "workspace:*",
81 "@types/bun": "catalog:",
pnpm-lock.yaml
-52
@@ -140,9 +140,6 @@ importers:
140 '@composio/anthropic':
141 specifier: workspace:*
142 version: link:ts/packages/providers/anthropic
143 - '@composio/cli-local-tools':
144 - specifier: workspace:*
145 - version: link:ts/packages/cli-local-tools
143 '@composio/core':
144 specifier: workspace:*
145 version: link:ts/packages/core
@@ -1227,9 +1224,6 @@ importers:
1224 '@composio/cli-keyring':
1225 specifier: workspace:*
1226 version: link:../cli-keyring
1230 - '@composio/cli-local-tools':
1231 - specifier: workspace:*
1232 - version: link:../cli-local-tools
1227 '@composio/client':
1228 specifier: 'catalog:'
1229 version: 2.0.0-rc.8
@@ -1346,37 +1340,6 @@ importers:
1340 specifier: 'catalog:'
1341 version: 5.0.1(@opentelemetry/api@1.9.1)(@types/node@26.6.2)(@vitest/ui@5.0.1)(vite@7.3.5(@types/node@26.6.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.0))
1342
1349 - ts/packages/cli-local-tools:
1350 - dependencies:
1351 - '@composio/core':
1352 - specifier: workspace:*
1353 - version: link:../core
1354 - '@modelcontextprotocol/sdk':
1355 - specifier: 'catalog:'
1356 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)
1357 - extract-zip:
1358 - specifier: ^2.0.1
1359 - version: 2.0.1(supports-color@10.2.2)
1360 - zod:
1361 - specifier: 'catalog:'
1362 - version: 4.5.4
1363 - devDependencies:
1364 - '@types/node':
1365 - specifier: ^26.6.2
1366 - version: 26.6.2
1367 - chrome-devtools-mcp:
1368 - specifier: 1.9.0
1369 - version: 1.9.0
1370 - tsdown:
1371 - specifier: 'catalog:'
1372 - version: 0.23.0(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.15)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3))
1373 - typescript:
1374 - specifier: 'catalog:'
1375 - version: 7.0.2
1376 - vitest:
1377 - specifier: 'catalog:'
1378 - version: 5.0.1(@opentelemetry/api@1.9.1)(@types/node@26.6.2)(@vitest/ui@5.0.1)(vite@7.3.5(@types/node@26.6.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.0))
1379 -
1343 ts/packages/core:
1344 dependencies:
1345 '@composio/client':
@@ -4619,19 +4582,6 @@ packages:
4582 zod:
4583 optional: true
4584
4622 - chrome-devtools-mcp@1.9.0:
4623 - resolution: {integrity: sha512-RnzXoJiUQ44hpOihWk90uOhLD/CnwDkDy0ldHMZONJ2nYQ+dWN1fq1luHHqyd+7FuYnyIlCY6uTThbN5ut9kSQ==}
4624 - engines: {node: ^20.19.0 || ^22.12.0 || >=23}
4625 - hasBin: true
4626 - peerDependencies:
4627 - '@blackwell-systems/gcf': ^2.2.2
4628 - '@toon-format/toon': ^4.1.0
4629 - peerDependenciesMeta:
4630 - '@blackwell-systems/gcf':
4631 - optional: true
4632 - '@toon-format/toon':
4633 - optional: true
4634 -
4585 cjs-module-lexer@1.2.3:
4586 resolution: {integrity: sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ==}
4587
@@ -9550,8 +9500,6 @@ snapshots:
9500 transitivePeerDependencies:
9501 - supports-color
9502
9553 - chrome-devtools-mcp@1.9.0: {}
9554 -
9503 cjs-module-lexer@1.2.3: {}
9504
9505 cjs-module-lexer@1.4.3: {}
pnpm-workspace.yaml
+3 -4
@@ -8,7 +8,6 @@ packages:
8 - ts/examples/*
9 - ts/packages/cli
10 - ts/packages/cli-keyring
11 - - ts/packages/cli-local-tools
11 - ts/packages/core
12 - ts/packages/experimental
13 - ts/packages/json-schema-to-effect-schema
@@ -165,10 +164,10 @@ auditConfig:
164 ignoreGhsas:
165 # extract-zip symlink path traversal. GitHub records no fixed version --
166 # 2.0.1 is the newest release and the repository has been dormant since
168 - # 2021 -- so there is nothing to upgrade to. Both consumers extract through
167 + # 2021 -- so there is nothing to upgrade to. The CLI extracts through
168 # `extractZipSafely`, which rejects symlink entries before they are written
170 - # (ts/packages/cli/src/utils/extract-zip-safely.ts and the cli-local-tools
171 - # copy, both covered by tests). Drop once a patched release exists.
169 + # (ts/packages/cli/src/utils/extract-zip-safely.ts, covered by tests). Drop
170 + # once a patched release exists.
171 # GHSA-7pqw-9j4j-h8q3 is GitHub's second write-up of the same symlink
172 # extraction bug (arbitrary file write through a symlink entry), with the
173 # same empty patched range.
test/install-sh-atomic-replace.test.sh
+31 -9
@@ -97,10 +97,15 @@ while (($# > 0)); do
97 done
98
99 bundle="$dest/composio-$TEST_TARGET"
100 -mkdir -p "$bundle/services" "$bundle/local-tools-binaries"
100 +mkdir -p "$bundle/services" "$bundle/acp-adapters"
101 printf '%s\n' 'new-support' >"$bundle/run-bun.mjs"
102 printf '%s\n' 'new-service' >"$bundle/services/example.txt"
103 -printf '%s\n' 'new-local-tool' >"$bundle/local-tools-binaries/current.txt"
103 +printf '%s\n' 'new-adapter' >"$bundle/acp-adapters/current.txt"
104 +
105 +if [[ ${TEST_ARCHIVE_MODE:-complete} == with-sidecars ]]; then
106 + mkdir -p "$bundle/local-tools-binaries/peekaboo"
107 + printf '%s\n' bundled-sidecar >"$bundle/local-tools-binaries/peekaboo/peekaboo"
108 +fi
109
110 if [[ ${TEST_ARCHIVE_MODE:-complete} == missing-binary ]]; then
111 exit 0
@@ -125,7 +130,7 @@ set -euo pipefail
130 if [[ ${TEST_FAIL_ASIDE_CLEANUP:-} == 1 ]]; then
131 for arg in "$@"; do
132 case $arg in
128 - */.composio-aside.local-tools-binaries) exit 23 ;;
133 + */.composio-aside.acp-adapters) exit 23 ;;
134 esac
135 done
136 fi
@@ -171,12 +176,25 @@ for interpreter in "${interpreters[@]}"; do
176 [[ -x "$install_dir/composio" ]] || fail "$interpreter_name empty install executable"
177 [[ -f "$install_dir/run-bun.mjs" ]] || fail "$interpreter_name empty install support file"
178 [[ -f "$install_dir/services/example.txt" ]] || fail "$interpreter_name empty install service"
174 - [[ -f "$install_dir/local-tools-binaries/current.txt" ]] ||
175 - fail "$interpreter_name empty install local tool"
179 + [[ -f "$install_dir/acp-adapters/current.txt" ]] ||
180 + fail "$interpreter_name empty install adapter"
181 [[ $(<"$install_dir/release-tag.txt") == "$version" ]] ||
182 fail "$interpreter_name empty install metadata"
183 assert_no_residue "$install_dir"
184
185 + run_installer with-sidecars >/dev/null 2>&1
186 + sidecar="$install_dir/local-tools-binaries/peekaboo/peekaboo"
187 + [[ -f "$sidecar" ]] || fail "$interpreter_name install removed bundled sidecar"
188 + [[ $(<"$sidecar") == bundled-sidecar ]] || fail "$interpreter_name installed sidecar contents"
189 + printf '%s\n' outdated >"$sidecar"
190 + printf '%s\n' stale >"$install_dir/local-tools-binaries/stale.txt"
191 + run_installer with-sidecars >/dev/null 2>&1
192 + [[ -f "$sidecar" ]] || fail "$interpreter_name reinstall removed bundled sidecar"
193 + [[ $(<"$sidecar") == bundled-sidecar ]] || fail "$interpreter_name reinstall sidecar contents"
194 + [[ ! -e "$install_dir/local-tools-binaries/stale.txt" ]] ||
195 + fail "$interpreter_name reinstall retained stale sidecar contents"
196 + assert_no_residue "$install_dir"
197 +
198 marker="$case_root/old-process"
199 cat >"$install_dir/composio" <<'EOF'
200 #!/bin/sh
@@ -188,7 +206,9 @@ done
206 printf '%s\n' old-process >"$marker.result"
207 EOF
208 chmod +x "$install_dir/composio"
191 - printf '%s\n' stale >"$install_dir/local-tools-binaries/stale.txt"
209 + printf '%s\n' stale >"$install_dir/acp-adapters/stale.txt"
210 + mkdir -p "$install_dir/local-tools-binaries/peekaboo"
211 + printf '%s\n' legacy >"$install_dir/local-tools-binaries/peekaboo/peekaboo"
212 old_inode=$(stat_inode "$install_dir/composio")
213 "$install_dir/composio" "$marker" &
214 survivor_pid=$!
@@ -203,8 +223,10 @@ EOF
223 [[ $new_inode != "$old_inode" ]] || fail "$interpreter_name reinstall kept the binary inode"
224 grep -Fq 'new-binary-marker' "$install_dir/composio" ||
225 fail "$interpreter_name reinstall binary contents"
206 - [[ ! -e "$install_dir/local-tools-binaries/stale.txt" ]] ||
226 + [[ ! -e "$install_dir/acp-adapters/stale.txt" ]] ||
227 fail "$interpreter_name reinstall retained stale directory contents"
228 + [[ ! -e "$install_dir/local-tools-binaries" ]] ||
229 + fail "$interpreter_name reinstall retained obsolete local-tools-binaries"
230 : >"$marker.release"
231 wait "$survivor_pid"
232 survivor_pid=
@@ -227,7 +249,7 @@ EOF
249 fail "$interpreter_name missing binary changed metadata"
250 assert_no_residue "$install_dir"
251
230 - printf '%s\n' old-aside >"$install_dir/local-tools-binaries/recoverable.txt"
252 + printf '%s\n' old-aside >"$install_dir/acp-adapters/recoverable.txt"
253 if ! aside_cleanup_output=$(run_installer complete 1 2>&1); then
254 fail "$interpreter_name aside cleanup failure aborted published install"
255 fi
@@ -239,7 +261,7 @@ EOF
261 fail "$interpreter_name aside cleanup did not publish executable"
262 retained_stage=$(find "$install_dir" -maxdepth 1 -type d -name '.composio-install.*' -print -quit)
263 [[ -n $retained_stage ]] || fail "$interpreter_name missing retained recovery staging directory"
242 - [[ $(<"$retained_stage/.composio-aside.local-tools-binaries/recoverable.txt") == old-aside ]] ||
264 + [[ $(<"$retained_stage/.composio-aside.acp-adapters/recoverable.txt") == old-aside ]] ||
265 fail "$interpreter_name retained aside is not recoverable"
266
267 printf 'install.sh atomic replacement passed under %s\n' "$interpreter_name"
test/install-sh-release-resolution.test.sh
+1 -1
@@ -360,7 +360,7 @@ while (($# > 0)); do
360 done
361 [[ -n $dest ]] || exit 95
362 bundle="$dest/composio-$TEST_TARGET"
363 -mkdir -p "$bundle/services" "$bundle/local-tools-binaries"
363 +mkdir -p "$bundle/services" "$bundle/acp-adapters"
364 cat >"$bundle/composio" <<'BIN'
365 #!/bin/sh
366 printf '%s|%s|%s|%s\n' "${COMPOSIO_INSTALL_HELP:-}" "${COMPOSIO_CLI_INVOCATION_ORIGIN:-}" "${COMPOSIO_BIN_DIR:-}" "$*" >>"$TEST_COMPOSIO_LOG"
test/install-sh-uninstall-snippet.test.sh
+3
@@ -115,6 +115,8 @@ for interpreter in "${interpreters[@]}"; do
115 mkdir -p "$home_main/.config/fish" "$home_main/.composio/services" "$home_main/.local/bin"
116 printf 'binary\n' >"$home_main/.composio/composio"
117 printf 'service\n' >"$home_main/.composio/services/example.txt"
118 + mkdir -p "$home_main/.composio/local-tools-binaries/peekaboo"
119 + printf 'sidecar\n' >"$home_main/.composio/local-tools-binaries/peekaboo/peekaboo"
120 printf 'keep me\n' >"$home_main/.composio/user-data.json"
121 ln -s "$home_main/.composio/composio" "$home_main/.local/bin/composio"
122 cat >"$home_main/.zshrc" <<'EOF'
@@ -165,6 +167,7 @@ EOF
167 [[ ! -e "$home_main/.local/bin/composio" ]] || fail "$interpreter_name kept the bin entry point"
168 [[ ! -e "$home_main/.composio/composio" ]] || fail "$interpreter_name kept the installed binary"
169 [[ ! -e "$home_main/.composio/services" ]] || fail "$interpreter_name kept the services directory"
170 + [[ ! -e "$home_main/.composio/local-tools-binaries" ]] || fail "$interpreter_name kept legacy sidecars"
171 [[ -f "$home_main/.composio/user-data.json" ]] || fail "$interpreter_name deleted user state"
172 assert_no_predictable_tmp "$home_main" "$interpreter_name main case"
173
ts/AGENTS.md
+1 -1
@@ -34,6 +34,6 @@ pnpm test:e2e:cli
34 - Do not edit `ts/vendor/`; those submodules are read-only references.
35 - Keep generated outputs owned by their generator.
36 - Add changesets only for changes to published TypeScript packages.
37 -- Never add changesets for `@composio/cli` or `@composio/cli-local-tools` while `.changeset/config.json` ignores them; record CLI notes in `ts/packages/cli/CHANGELOG.md` instead.
37 +- Never add changesets for `@composio/cli` while `.changeset/config.json` ignores it; record CLI notes in `ts/packages/cli/CHANGELOG.md` instead.
38 - Prefer focused package tests before broad workspace tests.
39 - Parse untyped or external data (API payloads, JSON, `unknown`) at the boundary with schemas and let inferred types flow downstream: zod in SDK packages (`@composio/core`, providers, shared packages), `effect/Schema` in `ts/packages/cli/`. Never hand-roll structural guards (`'x' in obj` / `typeof` chains) or cast parsed JSON with `as`.
ts/README.md
+1 -1
@@ -32,7 +32,7 @@ Published packages:
32 | [`@composio/experimental`](packages/experimental) | Experimental integrations, currently the Pi provider. |
33 | [`@composio/json-schema-to-zod`](packages/json-schema-to-zod) | JSON Schema to Zod conversion. |
34
35 -Internal (unpublished) packages: `cli-keyring` and `cli-local-tools` support the CLI; `ts-builders` generates TypeScript source.
35 +Internal (unpublished) packages: `cli-keyring` supports the CLI; `ts-builders` generates TypeScript source.
36
37 ## Layout
38
ts/e2e-tests/cli/install/e2e.test.ts
-1
@@ -235,7 +235,6 @@ test -L "$HOME/.local/bin/composio"
235 test "$(readlink -f "$HOME/.local/bin/composio")" = "$HOME/.composio/composio"
236 test "$(cat "$HOME/.composio/release-tag.txt")" = "$E2E_RELEASE_TAG"
237 test -f "$HOME/.composio/run-helpers-runtime.mjs"
238 -test -d "$HOME/.composio/local-tools-binaries"
238 test "$(grep -Fc '# Composio CLI' "$HOME/.zshrc")" = 1
239 test "$(zsh -ilc 'command -v composio')" = "$HOME/.local/bin/composio"
240 test "$(zsh -ilc 'composio --version')" = 98.0.0
ts/packages/cli-local-tools/CHANGELOG.md deleted
-67
@@ -1,67 +0,0 @@
1 -# @composio/cli-local-tools
2 -
3 -## 0.1.0
4 -
5 -### Minor Changes
6 -
7 -- 025a657: Drop CommonJS entrypoints and publish the TypeScript SDK packages as ESM-only packages. This is a breaking change within the existing 0.x release line: consumers must use Node.js 22.22.3 or newer. CommonJS callers can only rely on Node's native `require(esm)` interop, and the SDK no longer ships custom CommonJS compatibility machinery or `.cjs` artifacts.
8 -
9 -### Patch Changes
10 -
11 -- Updated dependencies [552859a]
12 -- Updated dependencies [a0bef5d]
13 -- Updated dependencies [23f9053]
14 -- Updated dependencies [dfd7a08]
15 -- Updated dependencies [507318d]
16 -- Updated dependencies [025a657]
17 -- Updated dependencies [6a4cb54]
18 -- Updated dependencies [4b76dbf]
19 -- Updated dependencies [cbbad15]
20 - - @composio/core@0.12.0
21 -
22 -## 0.0.5
23 -
24 -### Patch Changes
25 -
26 -- Updated dependencies [22a9171]
27 -- Updated dependencies [93b67e8]
28 -- Updated dependencies [b69cef1]
29 -- Updated dependencies [1ba66ca]
30 -- Updated dependencies [a94715f]
31 -- Updated dependencies [ce4b213]
32 -- Updated dependencies [44e5458]
33 - - @composio/core@0.11.0
34 -
35 -## 0.0.4
36 -
37 -### Patch Changes
38 -
39 -- Updated dependencies [42ebff3]
40 - - @composio/core@0.10.0
41 -
42 -## 0.0.3
43 -
44 -### Patch Changes
45 -
46 -- Updated dependencies [84a3a07]
47 -- Updated dependencies [c358ffa]
48 - - @composio/core@0.9.1
49 -
50 -## 0.0.2
51 -
52 -### Patch Changes
53 -
54 -- 79ac220: Add the Beeper iMessage local toolkit, rebuildable sidecar binaries from the ComposioHQ platform-imessage submodule, and higher-level wrappers for compact thread discovery, contact-aware thread search, send verification, and primary-instance reaction preparation.
55 -- 79ac220: Add first-class Chrome DevTools local tools backed by the official `chrome-devtools-mcp` package and its stateful `chrome-devtools` CLI daemon.
56 -- 79ac220: Scaffold the CLI local-tools foundation package, wire it into Tool Router search/execute sessions, and expose `composio local-tools list|doctor|configure|meta` for discovery, readiness checks, setup hints, and local metadata state. Concrete app integrations are added in follow-up stack PRs.
57 -- 79ac220: Add first-class Peekaboo macOS local tools backed by a bundled darwin-arm64 Peekaboo CLI binary.
58 -- Updated dependencies [c9b6525]
59 -- Updated dependencies [cc673b6]
60 -- Updated dependencies [9f14971]
61 -- Updated dependencies [81f8027]
62 -- Updated dependencies [711a703]
63 -- Updated dependencies [bccd32b]
64 -- Updated dependencies [bccd32b]
65 -- Updated dependencies [07c9bab]
66 -- Updated dependencies [3ece424]
67 - - @composio/core@0.9.0
ts/packages/cli-local-tools/local-tools-binaries/.gitignore deleted
-5
@@ -1,5 +0,0 @@
1 -# Local tool binaries are generated during CLI binary builds/release jobs.
2 -# Keep notices/licenses in git, but never commit generated executables.
3 -/beeper-imessage/darwin-*/imessage-cli
4 -/peekaboo/darwin-*/peekaboo
5 -/composio-native-ui/darwin-*/composio-native-ui
ts/packages/cli-local-tools/local-tools-binaries/README.md deleted
-20
@@ -1,20 +0,0 @@
1 -# Local tool binary assets
2 -
3 -Platform-specific executable and dynamic-library assets for first-party local tool integrations and CLI native sidecars are generated into this directory during local-tool binary builds.
4 -
5 -Do not commit generated executables. Keep notices/licenses in git, pin source with git submodules under `ts/packages/cli-local-tools/vendor/`, and regenerate binaries in CLI release jobs before packaging artifacts.
6 -
7 -Current native binary sources:
8 -
9 -- Beeper iMessage: `vendor/platform-imessage` (`https://github.com/ComposioHQ/platform-imessage`)
10 -- Peekaboo: `vendor/peekaboo` (`https://github.com/steipete/Peekaboo`)
11 -- Composio native UI sidecar: `native/composio-native-ui` (in-repository Swift package)
12 -
13 -Build macOS sidecars for the current host/target with:
14 -
15 -```bash
16 -pnpm --filter @composio/cli-local-tools build:local-tool-binaries -- --target darwin-arm64
17 -pnpm --filter @composio/cli-local-tools build:local-tool-binaries -- --target darwin-x64
18 -```
19 -
20 -Linux CLI artifacts skip these native sidecars. Chrome DevTools is an npm/npx-based integration and does not use this directory.
ts/packages/cli-local-tools/local-tools-binaries/beeper-imessage/LICENSE.txt deleted
-22
@@ -1,22 +0,0 @@
1 -MIT License
2 -
3 -Copyright (c) 2020-2023 Texts.com, 2023- Automattic Inc
4 -
5 -Permission is hereby granted, free of charge, to any person obtaining a copy
6 -of this software and associated documentation files (the "Software"), to deal
7 -in the Software without restriction, including without limitation the rights
8 -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 -copies of the Software, and to permit persons to whom the Software is
10 -furnished to do so, subject to the following conditions:
11 -
12 -The above copyright notice and this permission notice shall be included in all
13 -copies or substantial portions of the Software.
14 -
15 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 -SOFTWARE.
22 -
ts/packages/cli-local-tools/local-tools-binaries/beeper-imessage/NOTICE.md deleted
-14
@@ -1,14 +0,0 @@
1 -# Beeper platform-imessage CLI binary
2 -
3 -These `imessage-cli` binaries are built from the Composio fork of Beeper platform-imessage.
4 -
5 -- Upstream fork: `https://github.com/ComposioHQ/platform-imessage`
6 -- Upstream version: `0.21.0`
7 -- Upstream submodule commit: `364445a1b3089ad9fe293d5951efe160c5677c42`
8 -- License: MIT (`license.txt` in the upstream repository)
9 -- Build command: `pnpm --filter @composio/cli-local-tools build:beeper-imessage -- --target <darwin-arm64|darwin-x64>`
10 -- Underlying Swift build commands:
11 - - `swift build -c release --product imessage-cli --arch arm64`
12 - - `swift build -c release --product imessage-cli --arch x86_64`
13 -
14 -The binaries are stripped release builds for macOS arm64 and x64. They require local macOS Messages data and may prompt for Messages Data, Accessibility, Contacts, and Automation permissions depending on the command.
ts/packages/cli-local-tools/local-tools-binaries/composio-native-ui/NOTICE.md deleted
-11
@@ -1,11 +0,0 @@
1 -# Composio native UI sidecar
2 -
3 -The `composio-native-ui` binaries are built from the in-repository Swift package at `ts/packages/cli-local-tools/native/composio-native-ui`.
4 -
5 -- Purpose: native macOS UI surface that the Bun-compiled Composio CLI can spawn for auth flows, tool pickers, and other desktop affordances.
6 -- Build command: `pnpm --filter @composio/cli-local-tools build:composio-native-ui -- --target <darwin-arm64|darwin-x64>`
7 -- Underlying Swift build commands:
8 - - `swift build -c release --product composio-native-ui --arch arm64`
9 - - `swift build -c release --product composio-native-ui --arch x86_64`
10 -
11 -The scaffold currently opens a small AppKit panel near the bottom-right corner of the active screen. Generated executables are intentionally not committed; release jobs rebuild them before packaging CLI artifacts.
ts/packages/cli-local-tools/local-tools-binaries/peekaboo/LICENSE.txt deleted
-21
@@ -1,21 +0,0 @@
1 -MIT License
2 -
3 -Copyright (c) 2025 Peter Steinberger
4 -
5 -Permission is hereby granted, free of charge, to any person obtaining a copy
6 -of this software and associated documentation files (the "Software"), to deal
7 -in the Software without restriction, including without limitation the rights
8 -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 -copies of the Software, and to permit persons to whom the Software is
10 -furnished to do so, subject to the following conditions:
11 -
12 -The above copyright notice and this permission notice shall be included in all
13 -copies or substantial portions of the Software.
14 -
15 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 -SOFTWARE.
ts/packages/cli-local-tools/local-tools-binaries/peekaboo/NOTICE.md deleted
-12
@@ -1,12 +0,0 @@
1 -# Peekaboo CLI binary
2 -
3 -These `peekaboo` binaries are built from the upstream Peekaboo repository.
4 -
5 -- Upstream repository: `https://github.com/steipete/Peekaboo`
6 -- Upstream version: `3.0.0-beta4`
7 -- Upstream submodule commit: `31e66e8d02656141d18f60bf3b46b24c2b9bc785`
8 -- License: MIT (`LICENSE` in the upstream repository)
9 -- Build command: `pnpm --filter @composio/cli-local-tools build:peekaboo -- --target <darwin-arm64|darwin-x64>`
10 -- Underlying Swift build command: `swift build --arch <arm64|x86_64> -c release -Xswiftc -Osize -Xswiftc -wmo -Xlinker -dead_strip` from `Apps/CLI`
11 -
12 -The binaries are release builds for macOS. Peekaboo requires macOS 15+, Screen Recording permission for capture/read tools, and Accessibility/Automation permissions for GUI control tools.
ts/packages/cli-local-tools/native/composio-native-ui/.gitignore deleted
-2
@@ -1,2 +0,0 @@
1 -.build/
2 -.swiftpm/
ts/packages/cli-local-tools/native/composio-native-ui/Package.swift deleted
-18
@@ -1,18 +0,0 @@
1 -// swift-tools-version: 6.0
2 -import PackageDescription
3 -
4 -let package = Package(
5 - name: "ComposioNativeUI",
6 - platforms: [
7 - .macOS(.v13)
8 - ],
9 - products: [
10 - .executable(name: "composio-native-ui", targets: ["ComposioNativeUI"])
11 - ],
12 - targets: [
13 - .executableTarget(
14 - name: "ComposioNativeUI",
15 - path: "Sources/ComposioNativeUI"
16 - )
17 - ]
18 -)
ts/packages/cli-local-tools/native/composio-native-ui/Sources/ComposioNativeUI/main.swift deleted
-829
@@ -1,829 +0,0 @@
1 -import AppKit
2 -import MetalKit
3 -import QuartzCore
4 -
5 -struct Configuration {
6 - // Content (programmatic):
7 - var tool: String = "GMAIL_GET_PROFILE"
8 - var account: String = "gmail_pall-seba"
9 - var callerAgent: String? = nil // claude | codex | openclaw | composio (omit → CLI mode)
10 - var callerName: String? = nil // overrides agent.displayName
11 - var title: String? = nil // overrides the auto-built title
12 - var subtitle: String? = nil // overrides the auto-built subtitle
13 - var denyLabel: String = "Deny"
14 - var allowSessionLabel: String = "Allow for 1 hr"
15 - var allowOnceLabel: String = "Allow once"
16 -
17 - // Window:
18 - var width: CGFloat = 460
19 - var height: CGFloat = 200
20 - var margin: CGFloat = 24
21 - var timeoutSeconds: TimeInterval?
22 -
23 - // Result channel: if set, the decision JSON is written to this file path.
24 - // Otherwise it is written to stdout. Either way the process exits 0 for a
25 - // button press, 1 for dismissed / timeout / window-close.
26 - var callbackFile: String?
27 -
28 - var resolvedAgent: Agent? { callerAgent.map(Agents.resolve) }
29 - var resolvedCallerName: String { callerName ?? resolvedAgent?.displayName ?? "The composio cli" }
30 -
31 - // Sentinel used when no custom --title is supplied; makeContentView
32 - // builds an attributed string with an inline agent logo at this point.
33 - var resolvedTitle: String {
34 - title ?? ""
35 - }
36 -
37 - var resolvedSubtitle: String {
38 - if let subtitle, !subtitle.isEmpty { return subtitle }
39 - return "Approve once, for 1 hour, or deny."
40 - }
41 -
42 - init(arguments: [String]) {
43 - var index = 0
44 - while index < arguments.count {
45 - let argument = arguments[index]
46 - let value = index + 1 < arguments.count ? arguments[index + 1] : nil
47 -
48 - switch argument {
49 - case "--tool":
50 - if let value { tool = value; index += 1 }
51 - case "--account":
52 - if let value { account = value; index += 1 }
53 - case "--caller-agent", "--agent":
54 - if let value { callerAgent = value; index += 1 }
55 - case "--caller-name":
56 - if let value { callerName = value; index += 1 }
57 - case "--title", "--message":
58 - if let value { title = value; index += 1 }
59 - case "--subtitle", "--detail":
60 - if let value { subtitle = value; index += 1 }
61 - case "--deny-label":
62 - if let value { denyLabel = value; index += 1 }
63 - case "--allow-session-label":
64 - if let value { allowSessionLabel = value; index += 1 }
65 - case "--allow-once-label":
66 - if let value { allowOnceLabel = value; index += 1 }
67 - case "--callback-file":
68 - if let value { callbackFile = value; index += 1 }
69 - case "--width":
70 - if let value, let parsed = Double(value) { width = CGFloat(parsed); index += 1 }
71 - case "--height":
72 - if let value, let parsed = Double(value) { height = CGFloat(parsed); index += 1 }
73 - case "--margin":
74 - if let value, let parsed = Double(value) { margin = CGFloat(parsed); index += 1 }
75 - case "--timeout":
76 - if let value, let parsed = Double(value), parsed > 0 {
77 - timeoutSeconds = parsed
78 - index += 1
79 - }
80 - case "--help", "-h":
81 - print("""
82 - Usage: composio-native-ui [options]
83 -
84 - Content:
85 - --tool <slug> Tool slug shown in the title. Default: GMAIL_GET_PROFILE
86 - --account <name> Account identifier. Default: gmail_pall-seba
87 - --caller-agent <id> Agent calling the tool. claude | codex | openclaw | composio (default).
88 - --caller-name <text> Override the agent display name shown in the title.
89 - --title <text> Override the auto-built title entirely.
90 - --message <text> Alias for --title, used by CLI dev previews.
91 - --subtitle <text> Subtitle / description line.
92 - --deny-label <text> Override the "Deny" button label.
93 - --allow-session-label <text>
94 - --allow-once-label <text> Override the action button labels.
95 -
96 - Window:
97 - --width <points> Window width. Default: 460
98 - --height <points> Window height. Default: 200
99 - --margin <points> Margin from visible screen edges. Default: 24
100 - --timeout <secs> Auto-close after the given number of seconds.
101 -
102 - Result:
103 - --callback-file <path> Write the decision JSON to this file. If omitted, JSON is printed to stdout.
104 -
105 - Emits a single JSON line:
106 - {"decision":"allow_once|allow_session|deny|dismissed","tool":"...","account":"..."}
107 -
108 - Exit code: 0 on button press, 1 on dismissed/timeout/window-close.
109 - """)
110 - Foundation.exit(0)
111 - default:
112 - break
113 - }
114 -
115 - index += 1
116 - }
117 - }
118 -}
119 -
120 -// MARK: - Shader
121 -
122 -final class ShaderRenderer: NSObject, MTKViewDelegate {
123 - private let commandQueue: MTLCommandQueue
124 - private let pipelineState: MTLRenderPipelineState
125 - private let startTime = CACurrentMediaTime()
126 -
127 - init?(device: MTLDevice, pixelFormat: MTLPixelFormat) {
128 - guard let commandQueue = device.makeCommandQueue() else { return nil }
129 - self.commandQueue = commandQueue
130 -
131 - let source = """
132 - #include <metal_stdlib>
133 - using namespace metal;
134 -
135 - struct VertexOut {
136 - float4 position [[position]];
137 - float2 uv;
138 - };
139 -
140 - vertex VertexOut vertex_main(uint vertexID [[vertex_id]]) {
141 - float2 positions[3] = {
142 - float2(-1.0, -1.0),
143 - float2( 3.0, -1.0),
144 - float2(-1.0, 3.0)
145 - };
146 - VertexOut out;
147 - out.position = float4(positions[vertexID], 0.0, 1.0);
148 - out.uv = positions[vertexID] * 0.5 + 0.5;
149 - return out;
150 - }
151 -
152 - // Ordered 8x8 Bayer matrix, normalised to [0,1).
153 - float bayer8(int2 p) {
154 - const int M[64] = {
155 - 0, 32, 8, 40, 2, 34, 10, 42,
156 - 48, 16, 56, 24, 50, 18, 58, 26,
157 - 12, 44, 4, 36, 14, 46, 6, 38,
158 - 60, 28, 52, 20, 62, 30, 54, 22,
159 - 3, 35, 11, 43, 1, 33, 9, 41,
160 - 51, 19, 59, 27, 49, 17, 57, 25,
161 - 15, 47, 7, 39, 13, 45, 5, 37,
162 - 63, 31, 55, 23, 61, 29, 53, 21
163 - };
164 - int x = ((p.x % 8) + 8) % 8;
165 - int y = ((p.y % 8) + 8) % 8;
166 - return float(M[y * 8 + x]) / 64.0;
167 - }
168 -
169 - // Matches the dashboard's <Dither + SineWave> composition:
170 - // colorB="#c2c2c2" pattern="bayer8" pixelSize=2
171 - // spread=0.8 threshold=0.59
172 - // SineWave amplitude=0.1 angle=162 frequency=0.5 softness=1 speed=-0.4
173 - fragment float4 fragment_main(VertexOut in [[stage_in]], constant float &time [[buffer(0)]]) {
174 - const float PI = 3.14159265;
175 - float2 uv = in.uv;
176 -
177 - // SineWave field across the canvas. Angle 162° from horizontal.
178 - float ang = 162.0 * PI / 180.0;
179 - float2 dir = float2(cos(ang), sin(ang));
180 - float frequency = 0.5;
181 - float amplitude = 0.10;
182 - float softness = 1.0;
183 - float speed = -0.4;
184 -
185 - float coord = dot(uv - 0.5, dir) * frequency * 6.28318 + time * speed * 3.0;
186 - float wave = 0.5 + 0.5 * sin(coord); // 0..1
187 - // softness=1 → broad, gentle band; softness<1 would sharpen.
188 - wave = pow(wave, 1.0 / max(softness, 0.001));
189 - // amplitude=0.1 modulates a small swing around 0.5.
190 - float sineValue = 0.5 + (wave - 0.5) * (amplitude * 4.0);
191 -
192 - // Bayer-ordered dither at pixelSize=2.
193 - int2 pix = int2(floor(in.position.xy * 0.5));
194 - float b = bayer8(pix);
195 - float spread = 0.80;
196 - float threshold = 0.59;
197 -
198 - // Standard ordered-dither comparison.
199 - float mask = step(threshold, sineValue + (b - 0.5) * spread);
200 -
201 - float3 white = float3(1.0, 1.0, 1.0);
202 - float3 grey = float3(0.7607, 0.7607, 0.7607); // #c2c2c2
203 -
204 - float3 color = mix(grey, white, mask);
205 - return float4(color, 1.0);
206 - }
207 - """
208 -
209 - do {
210 - let library = try device.makeLibrary(source: source, options: nil)
211 - let descriptor = MTLRenderPipelineDescriptor()
212 - descriptor.vertexFunction = library.makeFunction(name: "vertex_main")
213 - descriptor.fragmentFunction = library.makeFunction(name: "fragment_main")
214 - descriptor.colorAttachments[0].pixelFormat = pixelFormat
215 - descriptor.colorAttachments[0].isBlendingEnabled = false
216 - self.pipelineState = try device.makeRenderPipelineState(descriptor: descriptor)
217 - } catch {
218 - fputs("Failed to compile Metal shader: \(error)\n", stderr)
219 - return nil
220 - }
221 -
222 - super.init()
223 - }
224 -
225 - func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {}
226 -
227 - func draw(in view: MTKView) {
228 - guard
229 - let descriptor = view.currentRenderPassDescriptor,
230 - let drawable = view.currentDrawable,
231 - let commandBuffer = commandQueue.makeCommandBuffer(),
232 - let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: descriptor)
233 - else { return }
234 -
235 - var elapsed = Float(CACurrentMediaTime() - startTime)
236 - encoder.setRenderPipelineState(pipelineState)
237 - encoder.setFragmentBytes(&elapsed, length: MemoryLayout<Float>.stride, index: 0)
238 - encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)
239 - encoder.endEncoding()
240 - commandBuffer.present(drawable)
241 - commandBuffer.commit()
242 - }
243 -}
244 -
245 -@MainActor
246 -final class MetalBackgroundView: MTKView {
247 - private var shaderRenderer: ShaderRenderer?
248 -
249 - init(frame: CGRect) {
250 - let device = MTLCreateSystemDefaultDevice()
251 - super.init(frame: frame, device: device)
252 -
253 - wantsLayer = true
254 - layer?.isOpaque = true
255 - colorPixelFormat = .bgra8Unorm
256 - framebufferOnly = true
257 - isPaused = false
258 - enableSetNeedsDisplay = false
259 - preferredFramesPerSecond = 60
260 - clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
261 -
262 - if let device, let renderer = ShaderRenderer(device: device, pixelFormat: colorPixelFormat) {
263 - shaderRenderer = renderer
264 - delegate = renderer
265 - }
266 - }
267 -
268 - required init(coder: NSCoder) {
269 - fatalError("init(coder:) has not been implemented")
270 - }
271 -}
272 -
273 -// MARK: - Tokens
274 -
275 -// SVG logos for each caller agent — embedded so the sidecar remains a
276 -// single binary with no asset bundle. macOS NSImage decodes SVG directly.
277 -
278 -struct Agent {
279 - let id: String
280 - let displayName: String
281 - let svg: String
282 -
283 - func makeImage() -> NSImage? {
284 - if svg.hasPrefix("data:image/png;base64,") {
285 - let encoded = String(svg.dropFirst("data:image/png;base64,".count))
286 - guard let data = Data(base64Encoded: encoded),
287 - let image = NSImage(data: data) else { return nil }
288 - return image
289 - }
290 -
291 - guard let data = svg.data(using: .utf8),
292 - let image = NSImage(data: data) else { return nil }
293 - return image
294 - }
295 -}
296 -
297 -enum Agents {
298 - static let composioSVG = #"""
299 - <svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
300 - <g clip-path="url(#clip0_2367_5)">
301 - <path d="M91.7032 28.1801L35.3611 16.6572C31.6669 15.8988 28.1929 18.7367 28.1929 22.5043V49.1954V50.6144V77.3052C28.1929 81.0729 31.6669 83.9112 35.3611 83.1526L91.7032 71.6296" stroke="black" stroke-width="2.8556" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
302 - <path d="M48.1992 7.38531C48.1993 2.09223 53.6097 -1.44765 58.4546 0.57874L58.6851 0.679333L58.6902 0.68227L88.8308 14.6023C91.4759 15.7947 93.1338 18.4366 93.1346 21.3053V33.0975C93.1346 37.3994 89.4707 40.797 85.1902 40.4658L51.0547 37.918V61.8914L85.185 59.3435L85.585 59.323C89.6842 59.2231 93.1331 62.5334 93.109 66.6876V78.4797C93.109 81.3707 91.4075 83.9737 88.8105 85.1812L88.806 85.1827L58.691 99.0774L58.6917 99.0782C53.7808 101.351 48.1992 97.7714 48.1992 92.3759V81.1383C47.9779 81.2256 47.741 81.2834 47.4921 81.3015L30.8347 82.5007C29.4429 82.6007 28.2584 81.4977 28.2582 80.1023V67.7354C28.2583 67.256 28.4014 66.8063 28.6474 66.4277L14.9439 67.4513H14.9388C10.6701 67.7539 7.00001 64.3671 7 60.0823V39.7271C7.00031 35.4239 10.6671 32.0248 14.9491 32.3589H14.9483L28.3486 33.3589C28.2905 33.152 28.2583 32.9345 28.2582 32.7099V19.6826C28.2582 17.7807 29.9597 16.3299 31.8377 16.6304L47.6992 19.168C47.8735 19.1959 48.0404 19.2435 48.1992 19.3059V7.38531ZM85.4075 62.191H85.4023L51.0547 64.755V79.6601L90.2541 71.4669V66.6774L90.2496 66.435C90.1323 63.9438 87.9489 61.9928 85.4075 62.191ZM27.7075 36.1748C27.9471 36.5495 28.0863 36.9936 28.0864 37.4678V62.7813C28.0864 63.0748 28.0314 63.3559 27.9344 63.6169L48.1992 62.1044V37.7043L27.7075 36.1748ZM51.0547 35.0544L85.4023 37.6183L85.4075 37.6191L85.6511 37.6316C88.1632 37.6928 90.279 35.6595 90.279 33.0975V28.1405L51.0547 19.9411V35.0544Z" fill="black"/>
303 - </g>
304 - <defs>
305 - <clipPath id="clip0_2367_5">
306 - <rect width="86.4662" height="100" fill="white" transform="translate(7)"/>
307 - </clipPath>
308 - </defs>
309 - </svg>
310 - """#
311 -
312 - static let claudeSVG = #"""
313 - <svg preserveAspectRatio="xMidYMid" viewBox="0 0 256 257" xmlns="http://www.w3.org/2000/svg"><path fill="#D97757" d="m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0 82.05 1.426l4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999-.064.065Z"/></svg>
314 - """#
315 -
316 - // Codex icon from the dashboard asset, with the white app-tile background removed
317 - // so it renders cleanly on the native permission card.
318 - static let codexSVG = #"""
319 - <svg height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M9.064 3.344a4.578 4.578 0 012.285-.312c1 .115 1.891.54 2.673 1.275.01.01.024.017.037.021a.09.09 0 00.043 0 4.55 4.55 0 013.046.275l.047.022.116.057a4.581 4.581 0 012.188 2.399c.209.51.313 1.041.315 1.595a4.24 4.24 0 01-.134 1.223.123.123 0 00.03.115c.594.607.988 1.33 1.183 2.17.289 1.425-.007 2.71-.887 3.854l-.136.166a4.548 4.548 0 01-2.201 1.388.123.123 0 00-.081.076c-.191.551-.383 1.023-.74 1.494-.9 1.187-2.222 1.846-3.711 1.838-1.187-.006-2.239-.44-3.157-1.302a.107.107 0 00-.105-.024c-.388.125-.78.143-1.204.138a4.441 4.441 0 01-1.945-.466 4.544 4.544 0 01-1.61-1.335c-.152-.202-.303-.392-.414-.617a5.81 5.81 0 01-.37-.961 4.582 4.582 0 01-.014-2.298.124.124 0 00.006-.056.085.085 0 00-.027-.048 4.467 4.467 0 01-1.034-1.651 3.896 3.896 0 01-.251-1.192 5.189 5.189 0 01.141-1.6c.337-1.112.982-1.985 1.933-2.618.212-.141.413-.251.601-.33.215-.089.43-.164.646-.227a.098.098 0 00.065-.066 4.51 4.51 0 01.829-1.615 4.535 4.535 0 011.837-1.388zm3.482 10.565a.637.637 0 000 1.272h3.636a.637.637 0 100-1.272h-3.636zM8.462 9.23a.637.637 0 00-1.106.631l1.272 2.224-1.266 2.136a.636.636 0 101.095.649l1.454-2.455a.636.636 0 00.005-.64L8.462 9.23z" fill="url(#lobe-icons-codex-_R_0_)"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-codex-_R_0_" x1="12" x2="12" y1="3" y2="21"><stop stop-color="#B1A7FF"></stop><stop offset=".5" stop-color="#7A9DFF"></stop><stop offset="1" stop-color="#3941FF"></stop></linearGradient></defs></svg>
320 - """#
321 -
322 - static let openclawSVG = #"""
323 - <svg viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="openclaw__lobster-gradient" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="#ff4d4d"/><stop offset="100%" stop-color="#991b1b"/></linearGradient></defs><path d="M60 10 C30 10 15 35 15 55 C15 75 30 95 45 100 L45 110 L55 110 L55 100 C55 100 60 102 65 100 L65 110 L75 110 L75 100 C90 95 105 75 105 55 C105 35 90 10 60 10Z" fill="url(#openclaw__lobster-gradient)"/><path d="M20 45 C5 40 0 50 5 60 C10 70 20 65 25 55 C28 48 25 45 20 45Z" fill="url(#openclaw__lobster-gradient)"/><path d="M100 45 C115 40 120 50 115 60 C110 70 100 65 95 55 C92 48 95 45 100 45Z" fill="url(#openclaw__lobster-gradient)"/><path d="M45 15 Q35 5 30 8" stroke="#ff4d4d" stroke-width="3" stroke-linecap="round"/><path d="M75 15 Q85 5 90 8" stroke="#ff4d4d" stroke-width="3" stroke-linecap="round"/><circle cx="45" cy="35" r="6" fill="#050810"/><circle cx="75" cy="35" r="6" fill="#050810"/><circle cx="46" cy="34" r="2.5" fill="#00e5cc"/><circle cx="76" cy="34" r="2.5" fill="#00e5cc"/></svg>
324 - """#
325 -
326 - static let composio = Agent(id: "composio", displayName: "Composio", svg: composioSVG)
327 - static let claude = Agent(id: "claude", displayName: "Claude", svg: claudeSVG)
328 - static let codex = Agent(id: "codex", displayName: "Codex", svg: codexSVG)
329 - static let openclaw = Agent(id: "openclaw", displayName: "OpenClaw", svg: openclawSVG)
330 -
331 - static func resolve(_ id: String) -> Agent {
332 - switch id.lowercased() {
333 - case "claude", "claude-code", "claudecode": return claude
334 - case "codex": return codex
335 - case "openclaw", "open-claw": return openclaw
336 - case "composio", "": return composio
337 - default: return composio
338 - }
339 - }
340 -}
341 -
342 -// Matches the dashboard's light theme (oklch tokens flattened to sRGB).
343 -enum Palette {
344 - static let cardBg = NSColor.white.withAlphaComponent(0.86) // bg-card/80
345 - static let border = NSColor(white: 0.0, alpha: 0.10) // border-border
346 - static let divider = NSColor(white: 0.0, alpha: 0.08)
347 - static let textPrimary = NSColor(white: 0.07, alpha: 1.0) // near-black
348 - static let textSecondary = NSColor(white: 0.40, alpha: 1.0) // text-muted-foreground
349 - static let textMuted = NSColor(white: 0.55, alpha: 1.0)
350 - static let primary = NSColor(white: 0.09, alpha: 1.0) // primary button
351 - static let primaryHover = NSColor(white: 0.18, alpha: 1.0)
352 - static let onPrimary = NSColor.white
353 -}
354 -
355 -// MARK: - Card chrome
356 -
357 -// Light-theme card: rounded-2xl + border + subtle inner stroke, like
358 -// `border-border bg-card/80 rounded-2xl shadow-* backdrop-blur-md`.
359 -@MainActor
360 -final class CardView: NSView {
361 - private let innerStroke = CAShapeLayer()
362 -
363 - override init(frame frameRect: NSRect) {
364 - super.init(frame: frameRect)
365 - wantsLayer = true
366 - layer?.cornerRadius = 16
367 - layer?.cornerCurve = .continuous
368 - layer?.masksToBounds = true
369 -
370 - innerStroke.fillColor = NSColor.clear.cgColor
371 - innerStroke.strokeColor = Palette.border.cgColor
372 - innerStroke.lineWidth = 1
373 - layer?.addSublayer(innerStroke)
374 - }
375 -
376 - required init?(coder: NSCoder) { fatalError() }
377 -
378 - override func layout() {
379 - super.layout()
380 - innerStroke.frame = bounds
381 - innerStroke.path = CGPath(
382 - roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5),
383 - cornerWidth: 15.5, cornerHeight: 15.5, transform: nil
384 - )
385 - }
386 -}
387 -
388 -enum AccentStyle {
389 - case primary // dark filled, white text
390 - case secondary // transparent w/ border, dark text
391 -}
392 -
393 -@MainActor
394 -final class AccentButton: NSButton {
395 - private let action_: () -> Void
396 - private let style: AccentStyle
397 - private let fill = CALayer()
398 - private let stroke = CAShapeLayer()
399 - private let glow = CALayer()
400 - private var isHovering = false
401 - private var isPressed = false
402 -
403 - init(title: String, style: AccentStyle = .primary, action: @escaping () -> Void) {
404 - self.action_ = action
405 - self.style = style
406 - super.init(frame: .zero)
407 - self.title = ""
408 - isBordered = false
409 - wantsLayer = true
410 - layer?.masksToBounds = false
411 - focusRingType = .none
412 -
413 - glow.backgroundColor = NSColor.clear.cgColor
414 - glow.shadowColor = NSColor.black.cgColor
415 - glow.shadowOpacity = 0.0
416 - glow.shadowRadius = 12
417 - glow.shadowOffset = CGSize(width: 0, height: 2)
418 - layer?.addSublayer(glow)
419 -
420 - fill.cornerRadius = 8
421 - fill.cornerCurve = .continuous
422 - layer?.addSublayer(fill)
423 -
424 - stroke.fillColor = NSColor.clear.cgColor
425 - stroke.lineWidth = 1
426 - layer?.addSublayer(stroke)
427 -
428 - let textColor: NSColor
429 - switch style {
430 - case .primary:
431 - fill.backgroundColor = Palette.primary.cgColor
432 - stroke.strokeColor = NSColor.clear.cgColor
433 - textColor = Palette.onPrimary
434 - case .secondary:
435 - fill.backgroundColor = NSColor.white.withAlphaComponent(0.55).cgColor
436 - stroke.strokeColor = Palette.border.cgColor
437 - textColor = Palette.textPrimary
438 - }
439 -
440 - let attr = NSMutableAttributedString(string: title, attributes: [
441 - .font: NSFont.systemFont(ofSize: 12.5, weight: .medium),
442 - .foregroundColor: textColor,
443 - .kern: 0.1,
444 - ])
445 - attributedTitle = attr
446 -
447 - target = self
448 - self.action = #selector(invoke)
449 -
450 - let tracking = NSTrackingArea(rect: .zero,
451 - options: [.mouseEnteredAndExited, .inVisibleRect, .activeInActiveApp],
452 - owner: self, userInfo: nil)
453 - addTrackingArea(tracking)
454 - }
455 -
456 - required init?(coder: NSCoder) { fatalError() }
457 -
458 - override var intrinsicContentSize: NSSize {
459 - let base = super.intrinsicContentSize
460 - return NSSize(width: base.width + 22, height: 30)
461 - }
462 -
463 - override func layout() {
464 - super.layout()
465 - fill.frame = bounds
466 - glow.frame = bounds
467 - glow.shadowPath = CGPath(roundedRect: bounds, cornerWidth: 8, cornerHeight: 8, transform: nil)
468 - stroke.frame = bounds
469 - stroke.path = CGPath(
470 - roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5),
471 - cornerWidth: 7.5, cornerHeight: 7.5, transform: nil
472 - )
473 - }
474 -
475 - override func resetCursorRects() {
476 - addCursorRect(bounds, cursor: .pointingHand)
477 - }
478 -
479 - override func mouseEntered(with event: NSEvent) {
480 - isHovering = true
481 - setState(hover: true, pressed: isPressed)
482 - }
483 -
484 - override func mouseExited(with event: NSEvent) {
485 - isHovering = false
486 - setState(hover: false, pressed: false)
487 - }
488 -
489 - override func mouseDown(with event: NSEvent) {
490 - isPressed = true
491 - setState(hover: isHovering, pressed: true)
492 - super.mouseDown(with: event)
493 - isPressed = false
494 - setState(hover: isHovering, pressed: false)
495 - }
496 -
497 - private func setState(hover: Bool, pressed: Bool) {
498 - CATransaction.begin()
499 - CATransaction.setAnimationDuration(0.14)
500 - let scale: CGFloat = pressed ? 0.97 : 1.0
501 - layer?.transform = CATransform3DMakeScale(scale, scale, 1)
502 - switch style {
503 - case .primary:
504 - glow.shadowOpacity = hover ? 0.18 : 0.0
505 - fill.backgroundColor = (hover ? Palette.primaryHover : Palette.primary).cgColor
506 - case .secondary:
507 - glow.shadowOpacity = 0.0
508 - fill.backgroundColor = (hover
509 - ? NSColor.white.withAlphaComponent(0.85)
510 - : NSColor.white.withAlphaComponent(0.55)).cgColor
511 - }
512 - CATransaction.commit()
513 - }
514 -
515 - @objc private func invoke() { action_() }
516 -}
517 -
518 -// MARK: - Decision callback
519 -
520 -enum Decision: String {
521 - case deny = "deny"
522 - case allowOnce = "allow_once"
523 - case allowSession = "allow_session"
524 - case dismissed = "dismissed"
525 -}
526 -
527 -@MainActor
528 -final class DecisionSink {
529 - static let shared = DecisionSink()
530 - private var hasEmitted = false
531 - private var configuration: Configuration?
532 -
533 - func configure(_ config: Configuration) {
534 - self.configuration = config
535 - }
536 -
537 - func emitAndExit(_ decision: Decision) {
538 - guard !hasEmitted, let config = configuration else {
539 - Foundation.exit(decision == .dismissed ? 1 : 0)
540 - }
541 - hasEmitted = true
542 -
543 - let payload: [String: Any] = [
544 - "decision": decision.rawValue,
545 - "tool": config.tool,
546 - "account": config.account,
547 - ]
548 - let line: String
549 - if let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]),
550 - let json = String(data: data, encoding: .utf8) {
551 - line = json + "\n"
552 - } else {
553 - line = "{\"decision\":\"\(decision.rawValue)\"}\n"
554 - }
555 -
556 - if let path = config.callbackFile {
557 - try? line.write(toFile: path, atomically: true, encoding: .utf8)
558 - } else {
559 - FileHandle.standardOutput.write(Data(line.utf8))
560 - }
561 -
562 - Foundation.exit(decision == .dismissed ? 1 : 0)
563 - }
564 -}
565 -
566 -// MARK: - App
567 -
568 -@MainActor
569 -final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
570 - private let configuration: Configuration
571 - private var window: NSWindow?
572 -
573 - init(configuration: Configuration) {
574 - self.configuration = configuration
575 - super.init()
576 - }
577 -
578 - func applicationDidFinishLaunching(_ notification: Notification) {
579 - NSApp.setActivationPolicy(.accessory)
580 - DecisionSink.shared.configure(configuration)
581 - createWindow()
582 -
583 - if let timeoutSeconds = configuration.timeoutSeconds {
584 - Timer.scheduledTimer(withTimeInterval: timeoutSeconds, repeats: false) { _ in
585 - Task { @MainActor in
586 - DecisionSink.shared.emitAndExit(.dismissed)
587 - }
588 - }
589 - }
590 - }
591 -
592 - func windowWillClose(_ notification: Notification) {
593 - DecisionSink.shared.emitAndExit(.dismissed)
594 - }
595 -
596 - private func createWindow() {
597 - let frame = bottomRightFrame()
598 -
599 - let panel = NSPanel(
600 - contentRect: frame,
601 - styleMask: [.borderless, .nonactivatingPanel],
602 - backing: .buffered,
603 - defer: false
604 - )
605 - panel.isOpaque = false
606 - panel.backgroundColor = .clear
607 - panel.hasShadow = false
608 - panel.ignoresMouseEvents = false
609 - panel.isMovableByWindowBackground = true
610 - panel.isFloatingPanel = true
611 - panel.animationBehavior = .none
612 - panel.level = .floating
613 - panel.collectionBehavior = [.moveToActiveSpace, .fullScreenAuxiliary]
614 - panel.delegate = self
615 - panel.contentView = makeContentView()
616 - panel.setFrame(frame, display: true, animate: false)
617 - panel.orderFrontRegardless()
618 -
619 - DispatchQueue.main.async { [weak panel] in
620 - panel?.setFrame(self.bottomRightFrame(), display: true, animate: false)
621 - }
622 -
623 - window = panel
624 - }
625 -
626 - private func bottomRightFrame() -> NSRect {
627 - let screen = screenForPlacement()
628 - let visibleFrame = screen.visibleFrame
629 - let size = NSSize(width: configuration.width, height: configuration.height)
630 - let origin = NSPoint(
631 - x: visibleFrame.maxX - size.width - configuration.margin,
632 - y: visibleFrame.minY + configuration.margin
633 - )
634 - return NSRect(origin: origin, size: size)
635 - }
636 -
637 - private func screenForPlacement() -> NSScreen {
638 - let mouseLocation = NSEvent.mouseLocation
639 - if let containingMouse = NSScreen.screens.first(where: { NSMouseInRect(mouseLocation, $0.frame, false) }) {
640 - return containingMouse
641 - }
642 - return NSScreen.main ?? NSScreen.screens.first ?? NSScreen()
643 - }
644 -
645 - private func makeContentView() -> NSView {
646 - let root = NSView(frame: NSRect(x: 0, y: 0, width: configuration.width, height: configuration.height))
647 - root.wantsLayer = true
648 - root.layer?.backgroundColor = NSColor.clear.cgColor
649 - root.layer?.masksToBounds = false
650 -
651 - // Soft drop shadow behind the card.
652 - let shadowHost = NSView()
653 - shadowHost.wantsLayer = true
654 - shadowHost.translatesAutoresizingMaskIntoConstraints = false
655 - if let l = shadowHost.layer {
656 - l.shadowColor = NSColor.black.cgColor
657 - l.shadowOpacity = 0.18
658 - l.shadowRadius = 30
659 - l.shadowOffset = CGSize(width: 0, height: -12)
660 - l.masksToBounds = false
661 - }
662 - root.addSubview(shadowHost)
663 -
664 - let card = CardView()
665 - card.translatesAutoresizingMaskIntoConstraints = false
666 - shadowHost.addSubview(card)
667 -
668 - // Dithered sine-wave shader — fills the card.
669 - let background = MetalBackgroundView(frame: .zero)
670 - background.translatesAutoresizingMaskIntoConstraints = false
671 - card.addSubview(background)
672 -
673 - // Translucent white wash so the dither reads more softly under text.
674 - let wash = NSView()
675 - wash.wantsLayer = true
676 - wash.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.55).cgColor
677 - wash.translatesAutoresizingMaskIntoConstraints = false
678 - card.addSubview(wash)
679 -
680 - // --- Bottom-left brand mark is always Composio.
681 - let logoView = NSImageView()
682 - logoView.image = Agents.composio.makeImage()
683 - logoView.imageScaling = .scaleProportionallyUpOrDown
684 - logoView.imageAlignment = .alignCenter
685 - logoView.translatesAutoresizingMaskIntoConstraints = false
686 - card.addSubview(logoView)
687 -
688 - // --- Title: "[agent-icon] wants to use TOOL with ACCOUNT".
689 - // Agent logo is inlined into the attributed string via NSTextAttachment,
690 - // so it sits on the same baseline as the rest of the title.
691 - let toolSlug = configuration.tool
692 - let account = configuration.account
693 - let titleFont = NSFont.systemFont(ofSize: 15, weight: .semibold)
694 - let monoFont = NSFont.monospacedSystemFont(ofSize: 13, weight: .semibold)
695 - let textAttrs: [NSAttributedString.Key: Any] = [
696 - .font: titleFont,
697 - .foregroundColor: Palette.textPrimary,
698 - .kern: -0.2,
699 - ]
700 - let monoAttrs: [NSAttributedString.Key: Any] = [
701 - .font: monoFont,
702 - .foregroundColor: Palette.textPrimary,
703 - ]
704 -
705 - let titleAttr = NSMutableAttributedString()
706 - if let customTitle = configuration.title, !customTitle.isEmpty {
707 - // Caller supplied a verbatim title — render as-is, still
708 - // monospacing the tool/account if they appear.
709 - titleAttr.append(NSAttributedString(string: customTitle, attributes: textAttrs))
710 - if let r = customTitle.range(of: toolSlug) {
711 - titleAttr.addAttribute(.font, value: monoFont,
712 - range: NSRange(r, in: customTitle))
713 - }
714 - if let r = customTitle.range(of: account) {
715 - titleAttr.addAttribute(.font, value: monoFont,
716 - range: NSRange(r, in: customTitle))
717 - }
718 - } else if let agent = configuration.resolvedAgent {
719 - // Inline agent logo as the subject of the sentence.
720 - if let agentImage = agent.makeImage() {
721 - let attachment = NSTextAttachment()
722 - attachment.image = agentImage
723 - attachment.bounds = CGRect(x: 0, y: -7, width: 28, height: 28)
724 - titleAttr.append(NSAttributedString(attachment: attachment))
725 - titleAttr.append(NSAttributedString(string: " ", attributes: textAttrs))
726 - }
727 - titleAttr.append(NSAttributedString(string: "wants to use ", attributes: textAttrs))
728 - titleAttr.append(NSAttributedString(string: toolSlug, attributes: monoAttrs))
729 - } else {
730 - // No caller agent — plain CLI-mode sentence, no inline logo.
731 - titleAttr.append(NSAttributedString(string: "The composio cli wants to execute ", attributes: textAttrs))
732 - titleAttr.append(NSAttributedString(string: toolSlug, attributes: monoAttrs))
733 - }
734 -
735 - let title = NSTextField(labelWithAttributedString: titleAttr)
736 - title.lineBreakMode = .byTruncatingTail
737 - title.maximumNumberOfLines = 2
738 - title.translatesAutoresizingMaskIntoConstraints = false
739 - card.addSubview(title)
740 -
741 - // --- Account line: "Account: <account>"
742 - let accountAttr = NSMutableAttributedString()
743 - accountAttr.append(NSAttributedString(string: "Account: ", attributes: [
744 - .font: NSFont.systemFont(ofSize: 12, weight: .regular),
745 - .foregroundColor: Palette.textSecondary,
746 - ]))
747 - accountAttr.append(NSAttributedString(string: account, attributes: [
748 - .font: NSFont.monospacedSystemFont(ofSize: 12, weight: .semibold),
749 - .foregroundColor: Palette.textPrimary,
750 - ]))
751 - let accountField = NSTextField(labelWithAttributedString: accountAttr)
752 - accountField.lineBreakMode = .byTruncatingTail
753 - accountField.maximumNumberOfLines = 1
754 - accountField.translatesAutoresizingMaskIntoConstraints = false
755 - card.addSubview(accountField)
756 -
757 - // --- Three actions matching the elicitation oneOf decisions.
758 - let denyButton = AccentButton(title: configuration.denyLabel, style: .secondary) {
759 - DecisionSink.shared.emitAndExit(.deny)
760 - }
761 - let allowSessionButton = AccentButton(title: configuration.allowSessionLabel, style: .secondary) {
762 - DecisionSink.shared.emitAndExit(.allowSession)
763 - }
764 - let allowOnceButton = AccentButton(title: configuration.allowOnceLabel, style: .primary) {
765 - DecisionSink.shared.emitAndExit(.allowOnce)
766 - }
767 - // Enter triggers the default action.
768 - allowOnceButton.keyEquivalent = "\r"
769 -
770 - let buttonRow = NSStackView(views: [denyButton, allowSessionButton, allowOnceButton])
771 - buttonRow.orientation = .horizontal
772 - buttonRow.alignment = .centerY
773 - buttonRow.spacing = 8
774 - buttonRow.translatesAutoresizingMaskIntoConstraints = false
775 - card.addSubview(buttonRow)
776 -
777 - let hPad: CGFloat = 22
778 - let headerTop: CGFloat = 20
779 - let bodyBottom: CGFloat = 18
780 - let logoSize: CGFloat = 32
781 -
782 - NSLayoutConstraint.activate([
783 - shadowHost.leadingAnchor.constraint(equalTo: root.leadingAnchor),
784 - shadowHost.trailingAnchor.constraint(equalTo: root.trailingAnchor),
785 - shadowHost.topAnchor.constraint(equalTo: root.topAnchor),
786 - shadowHost.bottomAnchor.constraint(equalTo: root.bottomAnchor),
787 -
788 - card.leadingAnchor.constraint(equalTo: shadowHost.leadingAnchor),
789 - card.trailingAnchor.constraint(equalTo: shadowHost.trailingAnchor),
790 - card.topAnchor.constraint(equalTo: shadowHost.topAnchor),
791 - card.bottomAnchor.constraint(equalTo: shadowHost.bottomAnchor),
792 -
793 - background.leadingAnchor.constraint(equalTo: card.leadingAnchor),
794 - background.trailingAnchor.constraint(equalTo: card.trailingAnchor),
795 - background.topAnchor.constraint(equalTo: card.topAnchor),
796 - background.bottomAnchor.constraint(equalTo: card.bottomAnchor),
797 -
798 - wash.leadingAnchor.constraint(equalTo: card.leadingAnchor),
799 - wash.trailingAnchor.constraint(equalTo: card.trailingAnchor),
800 - wash.topAnchor.constraint(equalTo: card.topAnchor),
801 - wash.bottomAnchor.constraint(equalTo: card.bottomAnchor),
802 -
803 - // Logo anchored to the bottom-left, aligned with button row baseline.
804 - logoView.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: hPad),
805 - logoView.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -bodyBottom - 4),
806 - logoView.widthAnchor.constraint(equalToConstant: logoSize),
807 - logoView.heightAnchor.constraint(equalToConstant: logoSize),
808 -
809 - title.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: hPad),
810 - title.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -hPad),
811 - title.topAnchor.constraint(equalTo: card.topAnchor, constant: headerTop),
812 -
813 - accountField.leadingAnchor.constraint(equalTo: title.leadingAnchor),
814 - accountField.trailingAnchor.constraint(lessThanOrEqualTo: card.trailingAnchor, constant: -hPad),
815 - accountField.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 6),
816 -
817 - buttonRow.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -hPad),
818 - buttonRow.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -bodyBottom),
819 - ])
820 -
821 - return root
822 - }
823 -}
824 -
825 -let configuration = Configuration(arguments: Array(CommandLine.arguments.dropFirst()))
826 -let application = NSApplication.shared
827 -let delegate = AppDelegate(configuration: configuration)
828 -application.delegate = delegate
829 -application.run()
ts/packages/cli-local-tools/package.json deleted
-50
@@ -1,50 +0,0 @@
1 -{
2 - "name": "@composio/cli-local-tools",
3 - "version": "0.1.0",
4 - "private": true,
5 - "description": "Local tool and toolkit declarations for the Composio CLI.",
6 - "type": "module",
7 - "main": "dist/index.mjs",
8 - "module": "dist/index.mjs",
9 - "types": "dist/index.d.mts",
10 - "exports": {
11 - ".": {
12 - "types": "./dist/index.d.mts",
13 - "default": "./dist/index.mjs"
14 - }
15 - },
16 - "repository": {
17 - "type": "git",
18 - "url": "https://github.com/ComposioHQ/composio.git",
19 - "directory": "ts/packages/cli-local-tools"
20 - },
21 - "license": "ISC",
22 - "files": [
23 - "dist",
24 - "local-tools-binaries"
25 - ],
26 - "sideEffects": false,
27 - "scripts": {
28 - "clean": "git clean -xdf node_modules",
29 - "build": "tsdown",
30 - "build:beeper-imessage": "bun run ./scripts/build-beeper-imessage-binaries.ts",
31 - "build:peekaboo": "bun run ./scripts/build-peekaboo-binaries.ts",
32 - "build:composio-native-ui": "bun run ./scripts/build-composio-native-ui-binaries.ts",
33 - "build:local-tool-binaries": "bun run ./scripts/build-local-tool-binaries.ts",
34 - "test": "vitest run",
35 - "typecheck": "tsc --noEmit -p ./tsconfig.src.json"
36 - },
37 - "dependencies": {
38 - "@composio/core": "workspace:*",
39 - "@modelcontextprotocol/sdk": "catalog:",
40 - "extract-zip": "^2.0.1",
41 - "zod": "catalog:"
42 - },
43 - "devDependencies": {
44 - "@types/node": "^26.6.2",
45 - "chrome-devtools-mcp": "1.9.0",
46 - "tsdown": "catalog:",
47 - "typescript": "catalog:",
48 - "vitest": "catalog:"
49 - }
50 -}
ts/packages/cli-local-tools/scripts/build-beeper-imessage-binaries.ts deleted
-230
@@ -1,230 +0,0 @@
1 -#!/usr/bin/env bun
2 -
3 -import { $ } from 'bun';
4 -import fs from 'node:fs/promises';
5 -import path from 'node:path';
6 -import { fileURLToPath } from 'node:url';
7 -
8 -const scriptDir = path.dirname(fileURLToPath(import.meta.url));
9 -const packageRoot = path.resolve(scriptDir, '..');
10 -const repoRoot = path.resolve(packageRoot, '../../..');
11 -const submodulePath = path.join(packageRoot, 'vendor/platform-imessage');
12 -const submoduleRelativePath = path.relative(repoRoot, submodulePath);
13 -const outputRoot = path.join(packageRoot, 'local-tools-binaries/beeper-imessage');
14 -
15 -const upstreamRepository = 'https://github.com/ComposioHQ/platform-imessage';
16 -
17 -const targets = [
18 - {
19 - platform: 'darwin-arm64',
20 - swiftArch: 'arm64',
21 - buildPath: '.build/arm64-apple-macosx/release/imessage-cli',
22 - },
23 -] as const;
24 -
25 -type Target = (typeof targets)[number];
26 -
27 -const exists = async (filePath: string): Promise<boolean> =>
28 - fs
29 - .access(filePath)
30 - .then(() => true)
31 - .catch(() => false);
32 -
33 -const readJson = async <T>(filePath: string): Promise<T> =>
34 - JSON.parse(await fs.readFile(filePath, 'utf8')) as T;
35 -
36 -// BetterSwiftAX 0.1.0 references Accessibility constants that are not
37 -// consistently exported by the macOS SDK on GitHub runners. Swift exposes AX
38 -// constants as Strings whose values are the constant name without the `k` prefix
39 -// and category suffix, so patch the resolved package checkout to literals before
40 -// compiling sidecar binaries.
41 -const betterSwiftAxFallbackFiles = [
42 - 'Accessibility+Action.swift',
43 - 'Accessibility+AttributeKey.swift',
44 - 'Accessibility+Notification.swift',
45 - 'Accessibility+ParameterizedAttributeKey.swift',
46 - 'Accessibility+Role.swift',
47 - 'Accessibility+Subrole.swift',
48 - 'Accessibility+Value.swift',
49 -] as const;
50 -
51 -const betterSwiftAxConstantReferencePattern =
52 - /\bkAX[A-Za-z0-9]+(?:Action|ParameterizedAttribute|Attribute|Notification|Subrole|Role|Value)\b/g;
53 -const betterSwiftAxConstantPattern =
54 - /^kAX(.+?)(Action|ParameterizedAttribute|Attribute|Notification|Subrole|Role|Value)$/;
55 -
56 -const betterSwiftAxConstantLiteral = (constantName: string): string => {
57 - const match = betterSwiftAxConstantPattern.exec(constantName);
58 - if (!match) {
59 - throw new Error(`Unsupported BetterSwiftAX constant fallback: ${constantName}`);
60 - }
61 - return `"AX${match[1]}"`;
62 -};
63 -
64 -const ensurePlatform = () => {
65 - if (process.platform !== 'darwin') {
66 - throw new Error(
67 - 'Building Beeper iMessage local-tool binaries requires macOS and the Swift toolchain.'
68 - );
69 - }
70 -};
71 -
72 -const ensureSubmodule = async () => {
73 - if (await exists(path.join(submodulePath, 'Package.swift'))) return;
74 -
75 - console.log(`Initializing ${submoduleRelativePath} submodule...`);
76 - await $`git submodule update --init --recursive -- ${submoduleRelativePath}`.cwd(repoRoot);
77 -
78 - if (!(await exists(path.join(submodulePath, 'Package.swift')))) {
79 - throw new Error(
80 - `Missing platform-imessage submodule at ${submoduleRelativePath}. Run: git submodule update --init --recursive -- ${submoduleRelativePath}`
81 - );
82 - }
83 -};
84 -
85 -const getSubmoduleCommit = async (): Promise<string> =>
86 - (await $`git rev-parse HEAD`.cwd(submodulePath).text()).trim();
87 -
88 -const getSubmoduleVersion = async (): Promise<string> => {
89 - const packageJson = await readJson<{ version?: string }>(
90 - path.join(submodulePath, 'package.json')
91 - );
92 - return packageJson.version ?? 'unknown';
93 -};
94 -
95 -const copyLicense = async () => {
96 - const licenseCandidates = ['license.txt', 'LICENSE.txt', 'LICENSE', 'LICENSE.md'];
97 - for (const candidate of licenseCandidates) {
98 - const sourcePath = path.join(submodulePath, candidate);
99 - if (await exists(sourcePath)) {
100 - await fs.copyFile(sourcePath, path.join(outputRoot, 'LICENSE.txt'));
101 - return;
102 - }
103 - }
104 - throw new Error('No upstream license file found in platform-imessage submodule.');
105 -};
106 -
107 -const patchBetterSwiftAxForCurrentSdk = async () => {
108 - await $`swift package resolve`.cwd(submodulePath);
109 -
110 - const checkoutRoot = path.join(
111 - submodulePath,
112 - '.build/checkouts/BetterSwiftAX/Sources/AccessibilityControl'
113 - );
114 - if (!(await exists(checkoutRoot))) {
115 - throw new Error(
116 - 'Swift package resolution completed but the BetterSwiftAX AccessibilityControl checkout was not found.'
117 - );
118 - }
119 -
120 - let replacementCount = 0;
121 - for (const fileName of betterSwiftAxFallbackFiles) {
122 - const sourcePath = path.join(checkoutRoot, fileName);
123 - if (!(await exists(sourcePath))) {
124 - throw new Error(
125 - `Swift package resolution completed but BetterSwiftAX ${fileName} was not found.`
126 - );
127 - }
128 -
129 - const source = await fs.readFile(sourcePath, 'utf8');
130 - let fileReplacementCount = 0;
131 - const patched = source.replace(betterSwiftAxConstantReferencePattern, constantName => {
132 - fileReplacementCount += 1;
133 - return betterSwiftAxConstantLiteral(constantName);
134 - });
135 -
136 - if (patched !== source) {
137 - await fs.chmod(sourcePath, 0o644).catch(() => undefined);
138 - await fs.writeFile(sourcePath, patched, 'utf8');
139 - replacementCount += fileReplacementCount;
140 - }
141 - }
142 -
143 - if (replacementCount > 0) {
144 - console.log(
145 - `Patched ${replacementCount} BetterSwiftAX Accessibility constants for the current macOS SDK.`
146 - );
147 - }
148 -};
149 -
150 -const buildTarget = async (target: Target) => {
151 - console.log(`Building imessage-cli for ${target.platform} (${target.swiftArch})...`);
152 - await patchBetterSwiftAxForCurrentSdk();
153 - await $`swift build -c release --product imessage-cli --arch ${target.swiftArch}`.cwd(
154 - submodulePath
155 - );
156 -
157 - const builtBinary = path.join(submodulePath, target.buildPath);
158 - if (!(await exists(builtBinary))) {
159 - throw new Error(`Swift build completed but ${target.buildPath} was not produced.`);
160 - }
161 -
162 - const targetDir = path.join(outputRoot, target.platform);
163 - const outputBinary = path.join(targetDir, 'imessage-cli');
164 - await fs.mkdir(targetDir, { recursive: true });
165 - await fs.copyFile(builtBinary, outputBinary);
166 - await fs.chmod(outputBinary, 0o755);
167 - console.log(`Wrote ${path.relative(repoRoot, outputBinary)}`);
168 -};
169 -
170 -const writeNotice = async (params: { version: string; commit: string }) => {
171 - const notice = `# Beeper platform-imessage CLI binary
172 -
173 -These \`imessage-cli\` binaries are built from the Composio fork of Beeper platform-imessage.
174 -
175 -- Upstream fork: \`${upstreamRepository}\`
176 -- Upstream version: \`${params.version}\`
177 -- Upstream submodule commit: \`${params.commit}\`
178 -- License: MIT (\`license.txt\` in the upstream repository)
179 -- Build command: \`pnpm --filter @composio/cli-local-tools build:beeper-imessage -- --target <darwin-arm64>\`
180 -- Underlying Swift build commands:
181 - - \`swift build -c release --product imessage-cli --arch arm64\`
182 -
183 -The binaries are stripped release builds for macOS arm64. They require local macOS Messages data and may prompt for Messages Data, Accessibility, Contacts, and Automation permissions depending on the command.
184 -`;
185 - await fs.writeFile(path.join(outputRoot, 'NOTICE.md'), notice, 'utf8');
186 -};
187 -
188 -const parseTargets = (): ReadonlyArray<Target> => {
189 - const rawArgs = process.argv.slice(2).filter(arg => arg !== '--');
190 - const targetIndex = rawArgs.indexOf('--target');
191 - const args =
192 - targetIndex >= 0 && rawArgs[targetIndex + 1]
193 - ? [rawArgs[targetIndex + 1]!]
194 - : rawArgs.filter(arg => !arg.startsWith('--'));
195 -
196 - if (args.length === 0 || args.includes('all')) return targets;
197 -
198 - const selected = targets.filter(target => args.includes(target.platform));
199 - const unknown = args.filter(arg => !targets.some(target => target.platform === arg));
200 - if (unknown.length > 0) {
201 - throw new Error(
202 - `Unknown target(s): ${unknown.join(', ')}. Expected one of: all, ${targets
203 - .map(target => target.platform)
204 - .join(', ')}`
205 - );
206 - }
207 - return selected;
208 -};
209 -
210 -const main = async () => {
211 - ensurePlatform();
212 - await ensureSubmodule();
213 -
214 - await fs.mkdir(outputRoot, { recursive: true });
215 - const selectedTargets = parseTargets();
216 - for (const target of selectedTargets) {
217 - await buildTarget(target);
218 - }
219 -
220 - await copyLicense();
221 - await writeNotice({
222 - version: await getSubmoduleVersion(),
223 - commit: await getSubmoduleCommit(),
224 - });
225 -};
226 -
227 -main().catch(error => {
228 - console.error(error instanceof Error ? error.message : error);
229 - process.exit(1);
230 -});
ts/packages/cli-local-tools/scripts/build-composio-native-ui-binaries.ts deleted
-107
@@ -1,107 +0,0 @@
1 -#!/usr/bin/env bun
2 -
3 -import { $ } from 'bun';
4 -import fs from 'node:fs/promises';
5 -import path from 'node:path';
6 -import { fileURLToPath } from 'node:url';
7 -
8 -const scriptDir = path.dirname(fileURLToPath(import.meta.url));
9 -const packageRoot = path.resolve(scriptDir, '..');
10 -const repoRoot = path.resolve(packageRoot, '../../..');
11 -const swiftPackagePath = path.join(packageRoot, 'native/composio-native-ui');
12 -const outputRoot = path.join(packageRoot, 'local-tools-binaries/composio-native-ui');
13 -
14 -const targets = [
15 - {
16 - platform: 'darwin-arm64',
17 - swiftArch: 'arm64',
18 - buildPath: '.build/arm64-apple-macosx/release/composio-native-ui',
19 - },
20 -] as const;
21 -
22 -type Target = (typeof targets)[number];
23 -
24 -const exists = async (filePath: string): Promise<boolean> =>
25 - fs
26 - .access(filePath)
27 - .then(() => true)
28 - .catch(() => false);
29 -
30 -const ensurePlatform = () => {
31 - if (process.platform !== 'darwin') {
32 - throw new Error(
33 - 'Building the Composio native UI sidecar requires macOS and the Swift toolchain.'
34 - );
35 - }
36 -};
37 -
38 -const buildTarget = async (target: Target) => {
39 - console.log(`Building composio-native-ui for ${target.platform} (${target.swiftArch})...`);
40 - await $`swift build -c release --product composio-native-ui --arch ${target.swiftArch}`.cwd(
41 - swiftPackagePath
42 - );
43 -
44 - const builtBinary = path.join(swiftPackagePath, target.buildPath);
45 - if (!(await exists(builtBinary))) {
46 - throw new Error(`Swift build completed but ${target.buildPath} was not produced.`);
47 - }
48 -
49 - const targetDir = path.join(outputRoot, target.platform);
50 - const outputBinary = path.join(targetDir, 'composio-native-ui');
51 - await fs.mkdir(targetDir, { recursive: true });
52 - await fs.copyFile(builtBinary, outputBinary);
53 - await fs.chmod(outputBinary, 0o755);
54 - console.log(`Wrote ${path.relative(repoRoot, outputBinary)}`);
55 -};
56 -
57 -const writeNotice = async () => {
58 - const notice = `# Composio native UI sidecar
59 -
60 -The \`composio-native-ui\` binaries are built from the in-repository Swift package at \`ts/packages/cli-local-tools/native/composio-native-ui\`.
61 -
62 -- Purpose: native macOS UI surface that the Bun-compiled Composio CLI can spawn for auth flows, tool pickers, and other desktop affordances.
63 -- Build command: \`pnpm --filter @composio/cli-local-tools build:composio-native-ui -- --target <darwin-arm64>\`
64 -- Underlying Swift build commands:
65 - - \`swift build -c release --product composio-native-ui --arch arm64\`
66 -
67 -The scaffold currently opens a small AppKit panel near the bottom-right corner of the active screen. Generated executables are intentionally not committed; release jobs rebuild them before packaging CLI artifacts.
68 -`;
69 - await fs.writeFile(path.join(outputRoot, 'NOTICE.md'), notice, 'utf8');
70 -};
71 -
72 -const parseTargets = (): ReadonlyArray<Target> => {
73 - const rawArgs = process.argv.slice(2).filter(arg => arg !== '--');
74 - const targetIndex = rawArgs.indexOf('--target');
75 - const args =
76 - targetIndex >= 0 && rawArgs[targetIndex + 1]
77 - ? [rawArgs[targetIndex + 1]!]
78 - : rawArgs.filter(arg => !arg.startsWith('--'));
79 -
80 - if (args.length === 0 || args.includes('all')) return targets;
81 -
82 - const selected = targets.filter(target => args.includes(target.platform));
83 - const unknown = args.filter(arg => !targets.some(target => target.platform === arg));
84 - if (unknown.length > 0) {
85 - throw new Error(
86 - `Unknown target(s): ${unknown.join(', ')}. Expected one of: all, ${targets
87 - .map(target => target.platform)
88 - .join(', ')}`
89 - );
90 - }
91 - return selected;
92 -};
93 -
94 -const main = async () => {
95 - ensurePlatform();
96 - await fs.mkdir(outputRoot, { recursive: true });
97 - const selectedTargets = parseTargets();
98 - for (const target of selectedTargets) {
99 - await buildTarget(target);
100 - }
101 - await writeNotice();
102 -};
103 -
104 -main().catch(error => {
105 - console.error(error instanceof Error ? error.message : error);
106 - process.exit(1);
107 -});
ts/packages/cli-local-tools/scripts/build-local-tool-binaries.ts deleted
-83
@@ -1,83 +0,0 @@
1 -#!/usr/bin/env bun
2 -
3 -import { $ } from 'bun';
4 -import path from 'node:path';
5 -import { fileURLToPath } from 'node:url';
6 -
7 -const scriptDir = path.dirname(fileURLToPath(import.meta.url));
8 -const packageRoot = path.resolve(scriptDir, '..');
9 -
10 -const targetAliases = new Map<string, string>([
11 - ['bun-darwin-arm64', 'darwin-arm64'],
12 - ['bun-darwin-aarch64', 'darwin-arm64'],
13 - ['composio-darwin-aarch64', 'darwin-arm64'],
14 - ['darwin-aarch64', 'darwin-arm64'],
15 - ['darwin-arm64', 'darwin-arm64'],
16 - ['bun-darwin-x64', 'darwin-x64'],
17 - ['composio-darwin-x64', 'darwin-x64'],
18 - ['darwin-x64', 'darwin-x64'],
19 - ['bun-linux-x64', 'linux-x64'],
20 - ['composio-linux-x64', 'linux-x64'],
21 - ['linux-x64', 'linux-x64'],
22 - ['bun-linux-arm64', 'linux-arm64'],
23 - ['bun-linux-aarch64', 'linux-arm64'],
24 - ['composio-linux-aarch64', 'linux-arm64'],
25 - ['linux-aarch64', 'linux-arm64'],
26 - ['linux-arm64', 'linux-arm64'],
27 -]);
28 -
29 -const parseTargetArg = (): string | undefined => {
30 - const args = process.argv.slice(2).filter(arg => arg !== '--');
31 - const targetIndex = args.indexOf('--target');
32 - if (targetIndex >= 0) return args[targetIndex + 1];
33 - return args.find(arg => !arg.startsWith('--'));
34 -};
35 -
36 -const detectHostTarget = (): string => {
37 - if (process.platform === 'darwin') {
38 - return process.arch === 'x64' ? 'darwin-x64' : 'darwin-arm64';
39 - }
40 - if (process.platform === 'linux') {
41 - return process.arch === 'arm64' ? 'linux-arm64' : 'linux-x64';
42 - }
43 - return `${process.platform}-${process.arch}`;
44 -};
45 -
46 -const normalizeTarget = (target?: string): string => {
47 - const value = target ?? detectHostTarget();
48 - return targetAliases.get(value) ?? value;
49 -};
50 -
51 -const runScript = async (scriptName: string, target: string) => {
52 - await $`bun run ${path.join('scripts', scriptName)} --target ${target}`.cwd(packageRoot);
53 -};
54 -
55 -const main = async () => {
56 - const target = normalizeTarget(parseTargetArg());
57 -
58 - if (!target.startsWith('darwin-')) {
59 - console.log(`Skipping native local-tool binary build for non-macOS target: ${target}`);
60 - return;
61 - }
62 -
63 - if (target === 'darwin-x64') {
64 - console.log('Skipping native local-tool binary build for darwin-x64 (unsupported target).');
65 - return;
66 - }
67 -
68 - if (process.platform !== 'darwin') {
69 - throw new Error(
70 - `Building native local-tool binaries for ${target} requires a macOS runner with the Swift toolchain.`
71 - );
72 - }
73 -
74 - console.log(`Building native local-tool binaries for ${target}...`);
75 - await runScript('build-beeper-imessage-binaries.ts', target);
76 - await runScript('build-peekaboo-binaries.ts', target);
77 - await runScript('build-composio-native-ui-binaries.ts', target);
78 -};
79 -
80 -main().catch(error => {
81 - console.error(error instanceof Error ? error.message : error);
82 - process.exit(1);
83 -});
ts/packages/cli-local-tools/scripts/build-peekaboo-binaries.ts deleted
-272
@@ -1,272 +0,0 @@
1 -#!/usr/bin/env bun
2 -
3 -import { $ } from 'bun';
4 -import fs from 'node:fs/promises';
5 -import path from 'node:path';
6 -import { fileURLToPath } from 'node:url';
7 -import { patchSwiftSystemAtResolveBeneathGuard } from './swift-system-patches';
8 -
9 -const scriptDir = path.dirname(fileURLToPath(import.meta.url));
10 -const packageRoot = path.resolve(scriptDir, '..');
11 -const repoRoot = path.resolve(packageRoot, '../../..');
12 -const submodulePath = path.join(packageRoot, 'vendor/peekaboo');
13 -const submoduleRelativePath = path.relative(repoRoot, submodulePath);
14 -const cliPackagePath = path.join(submodulePath, 'Apps/CLI');
15 -const outputRoot = path.join(packageRoot, 'local-tools-binaries/peekaboo');
16 -
17 -const upstreamRepository = 'https://github.com/steipete/Peekaboo';
18 -
19 -const targets = [
20 - {
21 - platform: 'darwin-arm64',
22 - swiftArch: 'arm64',
23 - buildPath: 'Apps/CLI/.build/arm64-apple-macosx/release/peekaboo',
24 - },
25 -] as const;
26 -
27 -type Target = (typeof targets)[number];
28 -
29 -const exists = async (filePath: string): Promise<boolean> =>
30 - fs
31 - .access(filePath)
32 - .then(() => true)
33 - .catch(() => false);
34 -
35 -const readJson = async <T>(filePath: string): Promise<T> =>
36 - JSON.parse(await fs.readFile(filePath, 'utf8')) as T;
37 -
38 -const swiftConfigurationPatchReplacements = [
39 - {
40 - filePath: 'Sources/Configuration/Providers/Files/FileProvider.swift',
41 - oldText: `self._snapshot = try snapshotType.init(
42 - data: fileContents!.bytes,
43 - providerName: providerName,
44 - parsingOptions: parsingOptions
45 - )`,
46 - newText: `self._snapshot = try fileContents!.withUnsafeBytes { bytes in
47 - try snapshotType.init(
48 - data: RawSpan(_unsafeBytes: bytes),
49 - providerName: providerName,
50 - parsingOptions: parsingOptions
51 - )
52 - }`,
53 - },
54 - {
55 - filePath: 'Sources/Configuration/Providers/Files/ReloadingFileProvider.swift',
56 - oldText: `initialSnapshot = try snapshotType.init(
57 - data: data.bytes,
58 - providerName: providerName,
59 - parsingOptions: parsingOptions
60 - )`,
61 - newText: `initialSnapshot = try data.withUnsafeBytes { bytes in
62 - try snapshotType.init(
63 - data: RawSpan(_unsafeBytes: bytes),
64 - providerName: providerName,
65 - parsingOptions: parsingOptions
66 - )
67 - }`,
68 - },
69 - {
70 - filePath: 'Sources/Configuration/Providers/Files/ReloadingFileProvider.swift',
71 - oldText: `newSnapshot = try Snapshot.init(
72 - data: data.bytes,
73 - providerName: providerName,
74 - parsingOptions: parsingOptions
75 - )`,
76 - newText: `newSnapshot = try data.withUnsafeBytes { bytes in
77 - try Snapshot.init(
78 - data: RawSpan(_unsafeBytes: bytes),
79 - providerName: providerName,
80 - parsingOptions: parsingOptions
81 - )
82 - }`,
83 - },
84 -] as const;
85 -
86 -const ensurePlatform = () => {
87 - if (process.platform !== 'darwin') {
88 - throw new Error(
89 - 'Building Peekaboo local-tool binaries requires macOS and the Swift toolchain.'
90 - );
91 - }
92 -};
93 -
94 -const ensureSubmodule = async () => {
95 - if (!(await exists(path.join(submodulePath, 'Apps/CLI/Package.swift')))) {
96 - console.log(`Initializing ${submoduleRelativePath} submodule...`);
97 - await $`git submodule update --init --recursive -- ${submoduleRelativePath}`.cwd(repoRoot);
98 - }
99 -
100 - if (!(await exists(path.join(submodulePath, 'Apps/CLI/Package.swift')))) {
101 - throw new Error(
102 - `Missing Peekaboo submodule at ${submoduleRelativePath}. Run: git submodule update --init --recursive -- ${submoduleRelativePath}`
103 - );
104 - }
105 -
106 - if (!(await exists(path.join(submodulePath, 'Commander/Package.swift')))) {
107 - console.log(`Initializing nested Peekaboo submodules...`);
108 - await $`git submodule update --init --recursive`.cwd(submodulePath);
109 - }
110 -
111 - if (!(await exists(path.join(submodulePath, 'Commander/Package.swift')))) {
112 - throw new Error('Missing nested Peekaboo submodules after initialization.');
113 - }
114 -};
115 -
116 -const getSubmoduleCommit = async (): Promise<string> =>
117 - (await $`git rev-parse HEAD`.cwd(submodulePath).text()).trim();
118 -
119 -const getSubmoduleVersion = async (): Promise<string> => {
120 - const versionJson = await readJson<{ version?: string }>(
121 - path.join(submodulePath, 'version.json')
122 - );
123 - return versionJson.version ?? 'unknown';
124 -};
125 -
126 -const copyLicense = async () => {
127 - const licenseCandidates = ['LICENSE', 'LICENSE.txt', 'LICENSE.md'];
128 - for (const candidate of licenseCandidates) {
129 - const sourcePath = path.join(submodulePath, candidate);
130 - if (await exists(sourcePath)) {
131 - await fs.copyFile(sourcePath, path.join(outputRoot, 'LICENSE.txt'));
132 - return;
133 - }
134 - }
135 - throw new Error('No upstream license file found in Peekaboo submodule.');
136 -};
137 -
138 -const patchSwiftConfigurationForCurrentToolchain = async () => {
139 - await $`swift package resolve`.cwd(cliPackagePath);
140 -
141 - const checkoutRoot = path.join(cliPackagePath, '.build/checkouts/swift-configuration');
142 - if (!(await exists(checkoutRoot))) {
143 - throw new Error(
144 - 'Swift package resolution completed but the swift-configuration checkout was not found.'
145 - );
146 - }
147 -
148 - let replacementCount = 0;
149 - for (const replacement of swiftConfigurationPatchReplacements) {
150 - const sourcePath = path.join(checkoutRoot, replacement.filePath);
151 - if (!(await exists(sourcePath))) {
152 - throw new Error(
153 - `Swift package resolution completed but ${replacement.filePath} was not found.`
154 - );
155 - }
156 -
157 - const source = await fs.readFile(sourcePath, 'utf8');
158 - if (!source.includes(replacement.oldText)) {
159 - if (source.includes(replacement.newText)) continue;
160 - throw new Error(`Unable to patch swift-configuration file: ${replacement.filePath}`);
161 - }
162 -
163 - const patched = source.replaceAll(replacement.oldText, replacement.newText);
164 - await fs.chmod(sourcePath, 0o644).catch(() => undefined);
165 - await fs.writeFile(sourcePath, patched, 'utf8');
166 - replacementCount += 1;
167 - }
168 -
169 - if (replacementCount > 0) {
170 - console.log(
171 - `Patched ${replacementCount} swift-configuration Data.bytes usages for the current Swift toolchain.`
172 - );
173 - }
174 -};
175 -
176 -const patchSwiftSystemForCurrentSdk = async () => {
177 - const checkoutRoot = path.join(cliPackagePath, '.build/checkouts/swift-system');
178 - if (!(await exists(checkoutRoot))) {
179 - throw new Error(
180 - 'Swift package resolution completed but the swift-system checkout was not found.'
181 - );
182 - }
183 -
184 - const replacementCount = await patchSwiftSystemAtResolveBeneathGuard(checkoutRoot, exists);
185 - if (replacementCount > 0) {
186 - console.log(
187 - `Patched ${replacementCount} swift-system AT_RESOLVE_BENEATH guards for the current macOS SDK.`
188 - );
189 - }
190 -};
191 -
192 -const buildTarget = async (target: Target) => {
193 - console.log(`Building peekaboo for ${target.platform} (${target.swiftArch})...`);
194 - await patchSwiftConfigurationForCurrentToolchain();
195 - await patchSwiftSystemForCurrentSdk();
196 - await $`swift build --arch ${target.swiftArch} -c release -Xswiftc -Osize -Xswiftc -wmo -Xlinker -dead_strip`.cwd(
197 - cliPackagePath
198 - );
199 -
200 - const builtBinary = path.join(submodulePath, target.buildPath);
201 - if (!(await exists(builtBinary))) {
202 - throw new Error(`Swift build completed but ${target.buildPath} was not produced.`);
203 - }
204 -
205 - const targetDir = path.join(outputRoot, target.platform);
206 - const outputBinary = path.join(targetDir, 'peekaboo');
207 - await fs.mkdir(targetDir, { recursive: true });
208 - await fs.copyFile(builtBinary, outputBinary);
209 - await fs.chmod(outputBinary, 0o755);
210 - console.log(`Wrote ${path.relative(repoRoot, outputBinary)}`);
211 -};
212 -
213 -const writeNotice = async (params: { version: string; commit: string }) => {
214 - const notice = `# Peekaboo CLI binary
215 -
216 -These \`peekaboo\` binaries are built from the upstream Peekaboo repository.
217 -
218 -- Upstream repository: \`${upstreamRepository}\`
219 -- Upstream version: \`${params.version}\`
220 -- Upstream submodule commit: \`${params.commit}\`
221 -- License: MIT (\`LICENSE\` in the upstream repository)
222 -- Build command: \`pnpm --filter @composio/cli-local-tools build:peekaboo -- --target <darwin-arm64>\`
223 -- Underlying Swift build command: \`swift build --arch arm64 -c release -Xswiftc -Osize -Xswiftc -wmo -Xlinker -dead_strip\` from \`Apps/CLI\`
224 -
225 -The binaries are release builds for macOS. Peekaboo requires macOS 15+, Screen Recording permission for capture/read tools, and Accessibility/Automation permissions for GUI control tools.
226 -`;
227 - await fs.writeFile(path.join(outputRoot, 'NOTICE.md'), notice, 'utf8');
228 -};
229 -
230 -const parseTargets = (): ReadonlyArray<Target> => {
231 - const rawArgs = process.argv.slice(2).filter(arg => arg !== '--');
232 - const targetIndex = rawArgs.indexOf('--target');
233 - const args =
234 - targetIndex >= 0 && rawArgs[targetIndex + 1]
235 - ? [rawArgs[targetIndex + 1]!]
236 - : rawArgs.filter(arg => !arg.startsWith('--'));
237 -
238 - if (args.length === 0 || args.includes('all')) return targets;
239 -
240 - const selected = targets.filter(target => args.includes(target.platform));
241 - const unknown = args.filter(arg => !targets.some(target => target.platform === arg));
242 - if (unknown.length > 0) {
243 - throw new Error(
244 - `Unknown target(s): ${unknown.join(', ')}. Expected one of: all, ${targets
245 - .map(target => target.platform)
246 - .join(', ')}`
247 - );
248 - }
249 - return selected;
250 -};
251 -
252 -const main = async () => {
253 - ensurePlatform();
254 - await ensureSubmodule();
255 -
256 - await fs.mkdir(outputRoot, { recursive: true });
257 - const selectedTargets = parseTargets();
258 - for (const target of selectedTargets) {
259 - await buildTarget(target);
260 - }
261 -
262 - await copyLicense();
263 - await writeNotice({
264 - version: await getSubmoduleVersion(),
265 - commit: await getSubmoduleCommit(),
266 - });
267 -};
268 -
269 -main().catch(error => {
270 - console.error(error instanceof Error ? error.message : error);
271 - process.exit(1);
272 -});
ts/packages/cli-local-tools/scripts/swift-system-patches.test.ts deleted
-36
@@ -1,36 +0,0 @@
1 -import { describe, expect, it } from 'vitest';
2 -import { patchSwiftSystemAtResolveBeneathGuardInSource } from './swift-system-patches';
3 -
4 -describe('swift-system build patches', () => {
5 - it('narrows AT_RESOLVE_BENEATH availability to FreeBSD', () => {
6 - const source = `#if canImport(Darwin, _version: 346) || os(FreeBSD)
7 -@_alwaysEmitIntoClient
8 -internal var _AT_RESOLVE_BENEATH: CInt { AT_RESOLVE_BENEATH }
9 -#endif
10 -`;
11 -
12 - const patched = patchSwiftSystemAtResolveBeneathGuardInSource(
13 - source,
14 - 'Sources/System/Internals/Constants.swift'
15 - );
16 -
17 - expect(patched.replacementCount).toBe(1);
18 - expect(patched.source).toContain('#if os(FreeBSD)');
19 - expect(patched.source).not.toContain('canImport(Darwin, _version: 346)');
20 - });
21 -
22 - it('is idempotent for already patched sources', () => {
23 - const source = `#if os(FreeBSD)
24 -@_alwaysEmitIntoClient
25 -internal var _AT_RESOLVE_BENEATH: CInt { AT_RESOLVE_BENEATH }
26 -#endif
27 -`;
28 -
29 - const patched = patchSwiftSystemAtResolveBeneathGuardInSource(
30 - source,
31 - 'Sources/System/Internals/Constants.swift'
32 - );
33 -
34 - expect(patched).toEqual({ source, replacementCount: 0 });
35 - });
36 -});
ts/packages/cli-local-tools/scripts/swift-system-patches.ts deleted
-60
@@ -1,60 +0,0 @@
1 -import fs from 'node:fs/promises';
2 -import path from 'node:path';
3 -
4 -const swiftSystemAtResolveBeneathGuard = '#if canImport(Darwin, _version: 346) || os(FreeBSD)';
5 -const swiftSystemFreeBsdOnlyGuard = '#if os(FreeBSD)';
6 -
7 -// swift-system 1.7.x exposes AT_RESOLVE_BENEATH on Darwin when compiling with
8 -// Swift 6.2, but GitHub's macOS SDK currently omits the C constant.
9 -const swiftSystemAtResolveBeneathFiles = [
10 - 'Sources/System/Internals/Constants.swift',
11 - 'Sources/System/FileSystem/Stat.swift',
12 -] as const;
13 -
14 -const countOccurrences = (source: string, pattern: string): number =>
15 - source.split(pattern).length - 1;
16 -
17 -export const patchSwiftSystemAtResolveBeneathGuardInSource = (
18 - source: string,
19 - filePath: string
20 -): { source: string; replacementCount: number } => {
21 - const replacementCount = countOccurrences(source, swiftSystemAtResolveBeneathGuard);
22 - if (replacementCount > 0) {
23 - return {
24 - source: source.replaceAll(swiftSystemAtResolveBeneathGuard, swiftSystemFreeBsdOnlyGuard),
25 - replacementCount,
26 - };
27 - }
28 -
29 - if (source.includes(swiftSystemFreeBsdOnlyGuard) && source.includes('AT_RESOLVE_BENEATH')) {
30 - return { source, replacementCount: 0 };
31 - }
32 -
33 - throw new Error(`Unable to patch swift-system AT_RESOLVE_BENEATH guard in ${filePath}`);
34 -};
35 -
36 -export const patchSwiftSystemAtResolveBeneathGuard = async (
37 - checkoutRoot: string,
38 - exists: (filePath: string) => Promise<boolean>
39 -): Promise<number> => {
40 - let replacementCount = 0;
41 -
42 - for (const filePath of swiftSystemAtResolveBeneathFiles) {
43 - const sourcePath = path.join(checkoutRoot, filePath);
44 - if (!(await exists(sourcePath))) {
45 - throw new Error(
46 - `Swift package resolution completed but swift-system ${filePath} was not found.`
47 - );
48 - }
49 -
50 - const source = await fs.readFile(sourcePath, 'utf8');
51 - const patched = patchSwiftSystemAtResolveBeneathGuardInSource(source, filePath);
52 - if (patched.replacementCount === 0) continue;
53 -
54 - await fs.chmod(sourcePath, 0o644).catch(() => undefined);
55 - await fs.writeFile(sourcePath, patched.source, 'utf8');
56 - replacementCount += patched.replacementCount;
57 - }
58 -
59 - return replacementCount;
60 -};
ts/packages/cli-local-tools/src/bun-ffi.d.ts deleted
-7
@@ -1,7 +0,0 @@
1 -declare module 'bun:ffi' {
2 - export const FFIType: Record<string, unknown>;
3 - export function dlopen(
4 - path: string,
5 - symbols: Record<string, { args: ReadonlyArray<unknown>; returns: unknown }>
6 - ): { symbols: Record<string, (...args: ReadonlyArray<unknown>) => unknown> };
7 -}
ts/packages/cli-local-tools/src/bundled-binaries.test.ts deleted
-92
@@ -1,92 +0,0 @@
1 -import fs from 'node:fs/promises';
2 -import os from 'node:os';
3 -import path from 'node:path';
4 -import { afterEach, describe, expect, it } from 'vitest';
5 -import { z } from 'zod/v3';
6 -import { detectCliPlatform } from './platform';
7 -import { checkLocalToolkitsReadiness } from './readiness';
8 -import { normalizeLocalToolSlug } from './registry';
9 -import { executeLocalTool } from './runtime';
10 -import type { LocalToolkitDeclaration } from './types';
11 -
12 -const tempDirs: string[] = [];
13 -const originalBinDir = process.env.COMPOSIO_LOCAL_TOOLS_BIN_DIR;
14 -
15 -afterEach(async () => {
16 - if (originalBinDir === undefined) {
17 - delete process.env.COMPOSIO_LOCAL_TOOLS_BIN_DIR;
18 - } else {
19 - process.env.COMPOSIO_LOCAL_TOOLS_BIN_DIR = originalBinDir;
20 - }
21 - await Promise.all(tempDirs.splice(0).map(dir => fs.rm(dir, { force: true, recursive: true })));
22 -});
23 -
24 -const createExecutable = async (relativePath: string, source: string): Promise<string> => {
25 - const root = await fs.mkdtemp(path.join(os.tmpdir(), 'composio-local-tools-bin-'));
26 - tempDirs.push(root);
27 - const absolutePath = path.join(root, relativePath);
28 - await fs.mkdir(path.dirname(absolutePath), { recursive: true });
29 - await fs.writeFile(absolutePath, source, 'utf8');
30 - await fs.chmod(absolutePath, 0o755);
31 - process.env.COMPOSIO_LOCAL_TOOLS_BIN_DIR = root;
32 - return absolutePath;
33 -};
34 -
35 -describe('@composio/cli-local-tools bundled binaries', () => {
36 - it('resolves and executes platform-specific bundled command binaries', async () => {
37 - const platform = detectCliPlatform();
38 - const relativePath = path.join(platform, 'fixture-tool');
39 - const executablePath = await createExecutable(
40 - relativePath,
41 - '#!/usr/bin/env bash\nprintf \'{"ok":true,"value":"%s"}\' "$1"\n'
42 - );
43 -
44 - const toolkit: LocalToolkitDeclaration = {
45 - slug: 'FIXTURE_APP',
46 - name: 'Fixture App',
47 - description: 'Fixture local toolkit for bundled binary tests.',
48 - platforms: [platform],
49 - bundledBinaries: [
50 - {
51 - id: 'fixture-tool',
52 - targets: [{ platforms: [platform], path: relativePath }],
53 - },
54 - ],
55 - tools: [
56 - {
57 - slug: 'RUN_BUNDLED',
58 - name: 'Run bundled command',
59 - description: 'Runs the bundled fixture executable.',
60 - platforms: [platform],
61 - inputParams: z.object({ value: z.string() }),
62 - execution: {
63 - kind: 'command',
64 - command: { bundledBinary: 'fixture-tool' },
65 - args: input => [String(input.value)],
66 - parseJson: true,
67 - },
68 - },
69 - ],
70 - };
71 - const tool = toolkit.tools[0]!;
72 - const finalSlug = normalizeLocalToolSlug(tool.slug, toolkit.slug);
73 -
74 - const readiness = await checkLocalToolkitsReadiness({
75 - currentPlatform: platform,
76 - declarations: [toolkit],
77 - metaOptions: {
78 - path: path.join(os.tmpdir(), `composio-local-tools-test-${Date.now()}.json`),
79 - },
80 - });
81 - expect(readiness.toolkits[0]?.tools[0]?.command?.path).toBe(executablePath);
82 -
83 - const result = await executeLocalTool(
84 - tool.execution,
85 - { value: 'hello' },
86 - { toolkit, tool, finalSlug, platform }
87 - );
88 -
89 - expect(result.command).toBe(executablePath);
90 - expect(result.parsed).toEqual({ ok: true, value: 'hello' });
91 - });
92 -});
ts/packages/cli-local-tools/src/bundled-binaries.ts deleted
-340
@@ -1,340 +0,0 @@
1 -import fsSync from 'node:fs';
2 -import fs from 'node:fs/promises';
3 -import os from 'node:os';
4 -import path from 'node:path';
5 -import { fileURLToPath } from 'node:url';
6 -import { extractZipSafely } from './extract-zip-safely';
7 -import { detectCliPlatform, supportsCliPlatform } from './platform';
8 -import type {
9 - LocalBundledBinaryDeclaration,
10 - LocalBundledBinaryRef,
11 - LocalCliPlatform,
12 - LocalToolkitDeclaration,
13 -} from './types';
14 -
15 -const DEFAULT_BUNDLE_DIR = 'local-tools-binaries';
16 -const RELEASE_TAG_FILENAME = 'release-tag.txt';
17 -
18 -const DEFAULT_GITHUB_CONFIG = {
19 - apiBaseUrl: 'https://api.github.com',
20 - owner: 'ComposioHQ',
21 - repo: 'composio',
22 -} as const;
23 -
24 -type GitHubReleaseAsset = {
25 - readonly name: string;
26 - readonly browser_download_url: string;
27 -};
28 -
29 -type GitHubRelease = {
30 - readonly tag_name: string;
31 - readonly assets: ReadonlyArray<GitHubReleaseAsset>;
32 -};
33 -
34 -let localToolsRepairPromise: Promise<boolean> | null = null;
35 -
36 -export interface LocalBundledBinaryResolution {
37 - readonly id: string;
38 - readonly path: string;
39 - readonly platform: LocalCliPlatform;
40 - readonly exists: boolean;
41 - readonly source: 'bundled' | 'fallback';
42 -}
43 -
44 -export const getLocalToolsBundleRootCandidates = (): ReadonlyArray<string> => {
45 - if (process.env.COMPOSIO_LOCAL_TOOLS_BIN_DIR?.trim()) {
46 - return [process.env.COMPOSIO_LOCAL_TOOLS_BIN_DIR.trim()];
47 - }
48 -
49 - const moduleDir = path.dirname(fileURLToPath(import.meta.url));
50 - const candidates = [
51 - // Bundled CLI JS / unpacked CLI binary sidecar location.
52 - path.join(moduleDir, DEFAULT_BUNDLE_DIR),
53 - // Package-root asset location when @composio/cli-local-tools is consumed as
54 - // a normal dependency and its JS lives under dist/.
55 - path.resolve(moduleDir, '..', DEFAULT_BUNDLE_DIR),
56 - // Standalone Bun executable zip/install layout: assets live next to the
57 - // compiled executable, not inside the virtual module directory.
58 - path.join(path.dirname(process.execPath), DEFAULT_BUNDLE_DIR),
59 - ];
60 -
61 - return [...new Set(candidates)];
62 -};
63 -
64 -export const getLocalToolsBundleRoot = (): string => {
65 - const candidates = getLocalToolsBundleRootCandidates();
66 - return candidates.find(candidate => fsSync.existsSync(candidate)) ?? candidates[0];
67 -};
68 -
69 -const hasPathSeparator = (value: string): boolean => value.includes('/') || value.includes('\\');
70 -
71 -const binaryExists = async (filePath: string): Promise<boolean> => {
72 - try {
73 - await fs.access(filePath);
74 - return true;
75 - } catch {
76 - return false;
77 - }
78 -};
79 -
80 -const readTextFileIfPresent = async (filePath: string): Promise<string | undefined> => {
81 - try {
82 - const value = (await fs.readFile(filePath, 'utf8')).trim();
83 - return value.length > 0 ? value : undefined;
84 - } catch {
85 - return undefined;
86 - }
87 -};
88 -
89 -const resolveBinaryAssetName = (): string | undefined => {
90 - switch (`${process.platform}-${process.arch}`) {
91 - case 'darwin-arm64':
92 - return 'composio-darwin-aarch64.zip';
93 - case 'darwin-x64':
94 - return 'composio-darwin-x64.zip';
95 - case 'linux-x64':
96 - return 'composio-linux-x64.zip';
97 - case 'linux-arm64':
98 - return 'composio-linux-aarch64.zip';
99 - default:
100 - return undefined;
101 - }
102 -};
103 -
104 -const fetchGitHubJson = async <T>({
105 - url,
106 - accessToken,
107 -}: {
108 - readonly url: string;
109 - readonly accessToken?: string;
110 -}): Promise<T> => {
111 - const response = await fetch(url, {
112 - headers: {
113 - Accept: 'application/vnd.github+json',
114 - 'User-Agent': 'composio-cli-local-tools-repair',
115 - ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
116 - },
117 - });
118 - if (!response.ok) {
119 - throw new Error(`GitHub request failed: HTTP ${response.status}`);
120 - }
121 - return (await response.json()) as T;
122 -};
123 -
124 -const downloadAsset = async (
125 - asset: GitHubReleaseAsset,
126 - accessToken?: string
127 -): Promise<Uint8Array> => {
128 - const response = await fetch(asset.browser_download_url, {
129 - headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined,
130 - });
131 - if (!response.ok) {
132 - throw new Error(`Failed to download ${asset.name}: HTTP ${response.status}`);
133 - }
134 - return new Uint8Array(await response.arrayBuffer());
135 -};
136 -
137 -const fetchChecksums = async (
138 - release: GitHubRelease,
139 - accessToken?: string
140 -): Promise<Map<string, string> | undefined> => {
141 - const checksumsAsset = release.assets.find(asset => asset.name === 'checksums.txt');
142 - if (!checksumsAsset) return undefined;
143 -
144 - const response = await fetch(checksumsAsset.browser_download_url, {
145 - headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined,
146 - });
147 - if (!response.ok) return undefined;
148 -
149 - const checksums = new Map<string, string>();
150 - const text = await response.text();
151 - for (const line of text.split('\n')) {
152 - const trimmed = line.trim();
153 - if (!trimmed) continue;
154 - const parts = trimmed.split(/\s+/);
155 - if (parts.length >= 2) {
156 - checksums.set(parts[1]!, parts[0]!);
157 - }
158 - }
159 - return checksums;
160 -};
161 -
162 -const verifyChecksum = async ({
163 - data,
164 - expectedHash,
165 - fileName,
166 -}: {
167 - readonly data: Uint8Array;
168 - readonly expectedHash: string;
169 - readonly fileName: string;
170 -}): Promise<void> => {
171 - const digest = await crypto.subtle.digest('SHA-256', data.slice().buffer);
172 - const actualHash = Array.from(new Uint8Array(digest))
173 - .map(byte => byte.toString(16).padStart(2, '0'))
174 - .join('');
175 - if (actualHash !== expectedHash) {
176 - throw new Error(
177 - `Checksum mismatch while repairing ${fileName}\n Expected: ${expectedHash}\n Actual: ${actualHash}`
178 - );
179 - }
180 -};
181 -
182 -const isStandaloneBunExecutable = (): boolean => {
183 - const currentFilePath = fileURLToPath(import.meta.url);
184 - return currentFilePath.startsWith('/$bunfs/');
185 -};
186 -
187 -const repairInstalledLocalToolsBundle = async (): Promise<boolean> => {
188 - if (process.env.COMPOSIO_LOCAL_TOOLS_BIN_DIR?.trim() || !isStandaloneBunExecutable()) {
189 - return false;
190 - }
191 -
192 - const installDirectory = path.dirname(process.execPath);
193 - const releaseTag =
194 - process.env.GITHUB_TAG?.trim() ||
195 - (await readTextFileIfPresent(path.join(installDirectory, RELEASE_TAG_FILENAME)));
196 - if (!releaseTag) return false;
197 -
198 - const assetName = resolveBinaryAssetName();
199 - if (!assetName) return false;
200 -
201 - const githubConfig = {
202 - apiBaseUrl:
203 - process.env.GITHUB_API_BASE_URL ||
204 - process.env.COMPOSIO_GITHUB_API_BASE_URL ||
205 - DEFAULT_GITHUB_CONFIG.apiBaseUrl,
206 - owner:
207 - process.env.GITHUB_OWNER || process.env.COMPOSIO_GITHUB_OWNER || DEFAULT_GITHUB_CONFIG.owner,
208 - repo: process.env.GITHUB_REPO || process.env.COMPOSIO_GITHUB_REPO || DEFAULT_GITHUB_CONFIG.repo,
209 - accessToken: process.env.GITHUB_ACCESS_TOKEN || process.env.COMPOSIO_GITHUB_ACCESS_TOKEN,
210 - };
211 -
212 - const release = await fetchGitHubJson<GitHubRelease>({
213 - url: `${githubConfig.apiBaseUrl}/repos/${githubConfig.owner}/${githubConfig.repo}/releases/tags/${encodeURIComponent(releaseTag)}`,
214 - accessToken: githubConfig.accessToken,
215 - });
216 - const asset = release.assets.find(candidate => candidate.name === assetName);
217 - if (!asset) return false;
218 -
219 - const archiveData = await downloadAsset(asset, githubConfig.accessToken);
220 - const expectedChecksum = (await fetchChecksums(release, githubConfig.accessToken))?.get(
221 - asset.name
222 - );
223 - if (expectedChecksum) {
224 - await verifyChecksum({
225 - data: archiveData,
226 - expectedHash: expectedChecksum,
227 - fileName: asset.name,
228 - });
229 - }
230 -
231 - const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'composio-local-tools-repair-'));
232 - try {
233 - const zipPath = path.join(tempDir, asset.name);
234 - const extractDir = path.join(tempDir, 'extract');
235 - await fs.writeFile(zipPath, archiveData);
236 - await extractZipSafely(zipPath, extractDir);
237 -
238 - const archiveBundleRoot = path.join(
239 - extractDir,
240 - path.parse(asset.name).name,
241 - DEFAULT_BUNDLE_DIR
242 - );
243 - if (!(await binaryExists(archiveBundleRoot))) return false;
244 -
245 - const installBundleRoot = path.join(installDirectory, DEFAULT_BUNDLE_DIR);
246 - await fs.rm(installBundleRoot, { force: true, recursive: true });
247 - await fs.cp(archiveBundleRoot, installBundleRoot, { recursive: true });
248 - return true;
249 - } finally {
250 - await fs.rm(tempDir, { force: true, recursive: true });
251 - }
252 -};
253 -
254 -const maybeRepairInstalledLocalToolsBundle = async (): Promise<boolean> => {
255 - localToolsRepairPromise ??= repairInstalledLocalToolsBundle().catch(() => false);
256 - return localToolsRepairPromise;
257 -};
258 -
259 -const findDeclaration = (
260 - toolkit: LocalToolkitDeclaration,
261 - id: string
262 -): LocalBundledBinaryDeclaration | undefined =>
263 - toolkit.bundledBinaries?.find(binary => binary.id === id);
264 -
265 -const resolveBundledPaths = (
266 - declaration: LocalBundledBinaryDeclaration,
267 - platform: LocalCliPlatform
268 -): ReadonlyArray<string> => {
269 - const target = declaration.targets.find(candidate =>
270 - supportsCliPlatform(candidate.platforms, platform)
271 - );
272 - if (!target) return [];
273 - return getLocalToolsBundleRootCandidates().map(root => path.resolve(root, target.path));
274 -};
275 -
276 -export const resolveBundledBinary = async (
277 - toolkit: LocalToolkitDeclaration,
278 - ref: LocalBundledBinaryRef,
279 - options: { readonly currentPlatform?: LocalCliPlatform } = {}
280 -): Promise<LocalBundledBinaryResolution | undefined> => {
281 - const currentPlatform = options.currentPlatform ?? detectCliPlatform();
282 - const declaration = findDeclaration(toolkit, ref.bundledBinary);
283 - const bundledPaths = declaration ? resolveBundledPaths(declaration, currentPlatform) : [];
284 - for (const bundledPath of bundledPaths) {
285 - if (await binaryExists(bundledPath)) {
286 - return {
287 - id: ref.bundledBinary,
288 - path: bundledPath,
289 - platform: currentPlatform,
290 - exists: true,
291 - source: 'bundled',
292 - };
293 - }
294 - }
295 -
296 - if (bundledPaths.length > 0 && (await maybeRepairInstalledLocalToolsBundle())) {
297 - for (const bundledPath of bundledPaths) {
298 - if (await binaryExists(bundledPath)) {
299 - return {
300 - id: ref.bundledBinary,
301 - path: bundledPath,
302 - platform: currentPlatform,
303 - exists: true,
304 - source: 'bundled',
305 - };
306 - }
307 - }
308 - }
309 -
310 - if (
311 - ref.fallbackCommand &&
312 - hasPathSeparator(ref.fallbackCommand) &&
313 - (await binaryExists(ref.fallbackCommand))
314 - ) {
315 - return {
316 - id: ref.bundledBinary,
317 - path: ref.fallbackCommand,
318 - platform: currentPlatform,
319 - exists: true,
320 - source: 'fallback',
321 - };
322 - }
323 -
324 - return bundledPaths[0]
325 - ? {
326 - id: ref.bundledBinary,
327 - path: bundledPaths[0],
328 - platform: currentPlatform,
329 - exists: false,
330 - source: 'bundled',
331 - }
332 - : undefined;
333 -};
334 -
335 -export const ensureBundledBinaryExecutable = async (filePath: string): Promise<void> => {
336 - if (process.platform === 'win32') return;
337 - const stat = await fs.stat(filePath);
338 - if ((stat.mode & 0o111) !== 0) return;
339 - await fs.chmod(filePath, stat.mode | 0o755);
340 -};
ts/packages/cli-local-tools/src/extract-zip-safely.test.ts deleted
-54
@@ -1,54 +0,0 @@
1 -import fs from 'node:fs';
2 -import os from 'node:os';
3 -import path from 'node:path';
4 -import { describe, expect, it } from 'vitest';
5 -import { extractZipSafely, isSymlinkZipEntry, UnsafeZipEntryError } from './extract-zip-safely';
6 -
7 -const FIXTURES_DIR = path.join(__dirname, 'zip-fixtures');
8 -
9 -const withTempDir = async (use: (dir: string) => Promise<void>): Promise<void> => {
10 - const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'local-tools-extract-'));
11 - try {
12 - await use(dir);
13 - } finally {
14 - fs.rmSync(dir, { recursive: true, force: true });
15 - }
16 -};
17 -
18 -describe('isSymlinkZipEntry', () => {
19 - it.each([
20 - ['symbolic link', 0o120755, true],
21 - ['regular file', 0o100644, false],
22 - ['directory', 0o40755, false],
23 - ])('classifies a %s', (_label, mode, expected) => {
24 - expect(isSymlinkZipEntry(mode << 16)).toBe(expected);
25 - });
26 -
27 - it('accepts a Windows-authored entry that carries no Unix mode', () => {
28 - expect(isSymlinkZipEntry(0)).toBe(false);
29 - });
30 -});
31 -
32 -describe('extractZipSafely', () => {
33 - it('extracts an archive of regular files and directories', async () => {
34 - await withTempDir(async dir => {
35 - await extractZipSafely(path.join(FIXTURES_DIR, 'benign.zip'), dir);
36 -
37 - expect(fs.readFileSync(path.join(dir, 'a.txt'), 'utf8').trim()).toBe('hello');
38 - expect(fs.readFileSync(path.join(dir, 'sub', 'b.txt'), 'utf8').trim()).toBe('world');
39 - });
40 - });
41 -
42 - it.each(['symlink-absolute.zip', 'symlink-relative.zip'])(
43 - 'refuses %s and plants nothing',
44 - async fixture => {
45 - await withTempDir(async dir => {
46 - await expect(extractZipSafely(path.join(FIXTURES_DIR, fixture), dir)).rejects.toThrow(
47 - UnsafeZipEntryError
48 - );
49 -
50 - expect(fs.readdirSync(dir)).toEqual([]);
51 - });
52 - }
53 - );
54 -});
ts/packages/cli-local-tools/src/extract-zip-safely.ts deleted
-40
@@ -1,40 +0,0 @@
1 -import extractZip from 'extract-zip';
2 -
3 -/**
4 - * Zip extraction that refuses symlink entries.
5 - *
6 - * `extract-zip` writes a symlink entry without validating its target
7 - * (CVE-2026-56876 / GHSA-jmr9-qjv8-65gv), and the advisory has no fixed
8 - * version. Sidecar archives never contain symlinks, so rejecting the entry type
9 - * removes the vector. See the matching helper in `@composio/cli` for why this
10 - * is a local workaround rather than an upstream fix, and when it can go; the
11 - * two are kept separate because this package must not be pulled into the CLI's
12 - * standalone companion bundles.
13 - */
14 -
15 -// Unix mode lives in the high 16 bits of a zip entry's external attributes.
16 -const UNIX_MODE_SHIFT = 16;
17 -const FILE_TYPE_MASK = 0o170000;
18 -const SYMLINK_FILE_TYPE = 0o120000;
19 -
20 -export class UnsafeZipEntryError extends Error {
21 - constructor(readonly entryName: string) {
22 - super(
23 - `Refusing to extract archive: "${entryName}" is a symbolic link, which this CLI never ships.`
24 - );
25 - this.name = 'UnsafeZipEntryError';
26 - }
27 -}
28 -
29 -export const isSymlinkZipEntry = (externalFileAttributes: number): boolean =>
30 - ((externalFileAttributes >>> UNIX_MODE_SHIFT) & FILE_TYPE_MASK) === SYMLINK_FILE_TYPE;
31 -
32 -export const extractZipSafely = (zipPath: string, dir: string): Promise<void> =>
33 - extractZip(zipPath, {
34 - dir,
35 - onEntry: entry => {
36 - if (isSymlinkZipEntry(entry.externalFileAttributes)) {
37 - throw new UnsafeZipEntryError(entry.fileName);
38 - }
39 - },
40 - });
ts/packages/cli-local-tools/src/index.ts deleted
-7
@@ -1,7 +0,0 @@
1 -export * from './types';
2 -export * from './platform';
3 -export * from './meta';
4 -export * from './runtime';
5 -export * from './bundled-binaries';
6 -export * from './readiness';
7 -export * from './registry';
ts/packages/cli-local-tools/src/meta.ts deleted
-158
@@ -1,158 +0,0 @@
1 -import fs from 'node:fs/promises';
2 -import os from 'node:os';
3 -import path from 'node:path';
4 -
5 -export const LOCAL_TOOLS_META_VERSION = 1;
6 -
7 -export interface LocalToolMetaEntry {
8 - readonly authenticated?: boolean;
9 - readonly auth?: {
10 - readonly type?: string;
11 - readonly account?: string;
12 - readonly env?: Record<string, string>;
13 - readonly data?: Record<string, unknown>;
14 - };
15 - readonly installation?: {
16 - /** Override the command/binary used by CLI-backed local tools. */
17 - readonly command?: string;
18 - readonly path?: string;
19 - readonly version?: string;
20 - };
21 - readonly disabled?: boolean;
22 - readonly notes?: string;
23 - readonly updatedAt?: string;
24 - readonly metadata?: Record<string, unknown>;
25 -}
26 -
27 -export type LocalToolkitMetaEntry = LocalToolMetaEntry;
28 -
29 -export interface LocalToolsMetaFile {
30 - readonly version: number;
31 - readonly updatedAt?: string;
32 - readonly tools: Record<string, LocalToolMetaEntry>;
33 - readonly toolkits: Record<string, LocalToolkitMetaEntry>;
34 -}
35 -
36 -export interface LocalToolsMetaOptions {
37 - readonly homeDir?: string;
38 - readonly path?: string;
39 -}
40 -
41 -export const getLocalToolsMetaPath = (options: LocalToolsMetaOptions = {}): string =>
42 - options.path ??
43 - process.env.COMPOSIO_LOCAL_TOOLS_PATH ??
44 - path.join(options.homeDir ?? os.homedir(), 'composio', 'local_tools.json');
45 -
46 -export const createEmptyLocalToolsMeta = (): LocalToolsMetaFile => ({
47 - version: LOCAL_TOOLS_META_VERSION,
48 - tools: {},
49 - toolkits: {},
50 -});
51 -
52 -const isRecord = (value: unknown): value is Record<string, unknown> =>
53 - typeof value === 'object' && value !== null && !Array.isArray(value);
54 -
55 -const parseLocalToolsMeta = (raw: string): LocalToolsMetaFile => {
56 - const parsed = JSON.parse(raw) as unknown;
57 - if (!isRecord(parsed)) {
58 - return createEmptyLocalToolsMeta();
59 - }
60 - return {
61 - version: typeof parsed.version === 'number' ? parsed.version : LOCAL_TOOLS_META_VERSION,
62 - updatedAt: typeof parsed.updatedAt === 'string' ? parsed.updatedAt : undefined,
63 - tools: isRecord(parsed.tools) ? (parsed.tools as Record<string, LocalToolMetaEntry>) : {},
64 - toolkits: isRecord(parsed.toolkits)
65 - ? (parsed.toolkits as Record<string, LocalToolkitMetaEntry>)
66 - : {},
67 - };
68 -};
69 -
70 -export const readLocalToolsMeta = async (
71 - options: LocalToolsMetaOptions = {}
72 -): Promise<LocalToolsMetaFile> => {
73 - const filePath = getLocalToolsMetaPath(options);
74 - try {
75 - return parseLocalToolsMeta(await fs.readFile(filePath, 'utf8'));
76 - } catch (error) {
77 - if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
78 - return createEmptyLocalToolsMeta();
79 - }
80 - throw error;
81 - }
82 -};
83 -
84 -export const writeLocalToolsMeta = async (
85 - meta: LocalToolsMetaFile,
86 - options: LocalToolsMetaOptions = {}
87 -): Promise<void> => {
88 - const filePath = getLocalToolsMetaPath(options);
89 - await fs.mkdir(path.dirname(filePath), { recursive: true });
90 - const next: LocalToolsMetaFile = {
91 - ...meta,
92 - version: LOCAL_TOOLS_META_VERSION,
93 - updatedAt: new Date().toISOString(),
94 - };
95 - await fs.writeFile(filePath, `${JSON.stringify(next, null, 2)}\n`, 'utf8');
96 -};
97 -
98 -export const getLocalToolMeta = async (
99 - finalSlug: string,
100 - options: LocalToolsMetaOptions = {}
101 -): Promise<LocalToolMetaEntry | undefined> => {
102 - const meta = await readLocalToolsMeta(options);
103 - return meta.tools[finalSlug.toUpperCase()] ?? meta.tools[finalSlug];
104 -};
105 -
106 -export const getLocalToolkitMeta = async (
107 - toolkitSlug: string,
108 - options: LocalToolsMetaOptions = {}
109 -): Promise<LocalToolkitMetaEntry | undefined> => {
110 - const meta = await readLocalToolsMeta(options);
111 - return meta.toolkits[toolkitSlug.toLowerCase()] ?? meta.toolkits[toolkitSlug];
112 -};
113 -
114 -export const updateLocalToolMeta = async (
115 - finalSlug: string,
116 - patch: LocalToolMetaEntry,
117 - options: LocalToolsMetaOptions = {}
118 -): Promise<LocalToolsMetaFile> => {
119 - const meta = await readLocalToolsMeta(options);
120 - const key = finalSlug.toUpperCase();
121 - const previous = meta.tools[key] ?? {};
122 - const next: LocalToolsMetaFile = {
123 - ...meta,
124 - tools: {
125 - ...meta.tools,
126 - [key]: {
127 - ...previous,
128 - ...patch,
129 - updatedAt: new Date().toISOString(),
130 - },
131 - },
132 - };
133 - await writeLocalToolsMeta(next, options);
134 - return next;
135 -};
136 -
137 -export const updateLocalToolkitMeta = async (
138 - toolkitSlug: string,
139 - patch: LocalToolkitMetaEntry,
140 - options: LocalToolsMetaOptions = {}
141 -): Promise<LocalToolsMetaFile> => {
142 - const meta = await readLocalToolsMeta(options);
143 - const key = toolkitSlug.toLowerCase();
144 - const previous = meta.toolkits[key] ?? {};
145 - const next: LocalToolsMetaFile = {
146 - ...meta,
147 - toolkits: {
148 - ...meta.toolkits,
149 - [key]: {
150 - ...previous,
151 - ...patch,
152 - updatedAt: new Date().toISOString(),
153 - },
154 - },
155 - };
156 - await writeLocalToolsMeta(next, options);
157 - return next;
158 -};
ts/packages/cli-local-tools/src/platform.ts deleted
-40
@@ -1,40 +0,0 @@
1 -import type { LocalCliPlatform } from './types';
2 -
3 -export interface DetectPlatformInput {
4 - readonly platform?: NodeJS.Platform;
5 - readonly arch?: NodeJS.Architecture | string;
6 -}
7 -
8 -export const detectCliPlatform = (input: DetectPlatformInput = {}): LocalCliPlatform => {
9 - const platform = input.platform ?? process.platform;
10 - const arch = input.arch ?? process.arch;
11 - if (platform === 'darwin') {
12 - return arch === 'x64' ? 'darwin-x64' : 'darwin-arm64';
13 - }
14 - if (platform === 'linux') {
15 - return arch === 'arm64' ? 'linux-arm64' : 'linux-x64';
16 - }
17 - if (platform === 'win32') {
18 - return arch === 'arm64' ? 'win32-arm64' : 'win32-x64';
19 - }
20 - return 'all';
21 -};
22 -
23 -const platformFamily = (platform: LocalCliPlatform): LocalCliPlatform => {
24 - if (platform.startsWith('darwin')) return 'darwin';
25 - if (platform.startsWith('linux')) return 'linux';
26 - if (platform.startsWith('win32')) return 'win32';
27 - return platform;
28 -};
29 -
30 -export const supportsCliPlatform = (
31 - supportedPlatforms: ReadonlyArray<LocalCliPlatform>,
32 - currentPlatform: LocalCliPlatform = detectCliPlatform()
33 -): boolean => {
34 - if (supportedPlatforms.includes('all')) return true;
35 - if (supportedPlatforms.includes(currentPlatform)) return true;
36 - return supportedPlatforms.includes(platformFamily(currentPlatform));
37 -};
38 -
39 -export const formatSupportedPlatforms = (platforms: ReadonlyArray<LocalCliPlatform>): string =>
40 - platforms.includes('all') ? 'all CLI platforms' : platforms.join(', ');
ts/packages/cli-local-tools/src/readiness.ts deleted
-460
@@ -1,460 +0,0 @@
1 -import { constants as fsConstants } from 'node:fs';
2 -import fs from 'node:fs/promises';
3 -import path from 'node:path';
4 -import { resolveBundledBinary } from './bundled-binaries';
5 -import { detectCliPlatform, formatSupportedPlatforms, supportsCliPlatform } from './platform';
6 -import { readLocalToolsMeta, type LocalToolsMetaOptions } from './meta';
7 -import { localToolkitDeclarations, normalizeLocalToolSlug } from './registry';
8 -import type {
9 - LocalBundledBinaryRef,
10 - LocalCliPlatform,
11 - LocalCommandInvocation,
12 - LocalMcpServerSpec,
13 - LocalToolkitDeclaration,
14 - LocalToolDeclaration,
15 - LocalToolExecution,
16 -} from './types';
17 -
18 -export type LocalReadinessStatus =
19 - | 'ready'
20 - | 'unsupported'
21 - | 'disabled'
22 - | 'missing'
23 - | 'not_implemented'
24 - | 'unknown';
25 -
26 -export interface LocalCommandReadiness {
27 - readonly command: string;
28 - readonly args?: ReadonlyArray<string>;
29 - readonly found: boolean;
30 - readonly path?: string;
31 -}
32 -
33 -export interface LocalToolReadiness {
34 - readonly finalSlug: string;
35 - readonly slug: string;
36 - readonly name: string;
37 - readonly toolkitSlug: string;
38 - readonly executionKind: LocalToolExecution['kind'];
39 - readonly platforms: ReadonlyArray<LocalCliPlatform>;
40 - readonly supported: boolean;
41 - readonly status: LocalReadinessStatus;
42 - readonly command?: LocalCommandReadiness;
43 - readonly messages: ReadonlyArray<string>;
44 - readonly hints: ReadonlyArray<string>;
45 -}
46 -
47 -export interface LocalToolkitReadiness {
48 - readonly slug: string;
49 - readonly name: string;
50 - readonly description: string;
51 - readonly platforms: ReadonlyArray<LocalCliPlatform>;
52 - readonly supported: boolean;
53 - readonly status: LocalReadinessStatus;
54 - readonly source?: LocalToolkitDeclaration['source'];
55 - readonly setup?: LocalToolkitDeclaration['setup'];
56 - readonly tools: ReadonlyArray<LocalToolReadiness>;
57 - readonly messages: ReadonlyArray<string>;
58 - readonly hints: ReadonlyArray<string>;
59 -}
60 -
61 -export interface LocalToolsReadinessReport {
62 - readonly currentPlatform: LocalCliPlatform;
63 - readonly toolkits: ReadonlyArray<LocalToolkitReadiness>;
64 -}
65 -
66 -const toolkitMatchesFilter = (
67 - toolkit: LocalToolkitDeclaration,
68 - requestedToolkits?: ReadonlyArray<string>
69 -): boolean => {
70 - if (!requestedToolkits || requestedToolkits.length === 0) return true;
71 - const requested = new Set(requestedToolkits.map(slug => slug.toLowerCase()));
72 - return requested.has(toolkit.slug.toLowerCase());
73 -};
74 -
75 -const statusPriority: Record<LocalReadinessStatus, number> = {
76 - ready: 0,
77 - unknown: 1,
78 - not_implemented: 2,
79 - missing: 3,
80 - disabled: 4,
81 - unsupported: 5,
82 -};
83 -
84 -const aggregateStatus = (statuses: ReadonlyArray<LocalReadinessStatus>): LocalReadinessStatus => {
85 - if (statuses.length === 0) return 'unknown';
86 - return statuses.reduce((current, next) =>
87 - statusPriority[next] > statusPriority[current] ? next : current
88 - );
89 -};
90 -
91 -const resolveValue = <T>(
92 - value: T | ((input: Record<string, unknown>) => T),
93 - input: Record<string, unknown> = {}
94 -): T =>
95 - typeof value === 'function' ? (value as (input: Record<string, unknown>) => T)(input) : value;
96 -
97 -const splitPathEntries = (pathValue: string | undefined): ReadonlyArray<string> =>
98 - (pathValue ?? '')
99 - .split(path.delimiter)
100 - .map(entry => entry.trim())
101 - .filter(Boolean);
102 -
103 -const hasPathSeparator = (command: string): boolean =>
104 - command.includes('/') || command.includes('\\');
105 -
106 -const executableCandidates = (command: string): ReadonlyArray<string> => {
107 - if (process.platform !== 'win32') return [command];
108 - const extensions = (process.env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM')
109 - .split(';')
110 - .map(ext => ext.trim())
111 - .filter(Boolean);
112 - if (extensions.some(ext => command.toUpperCase().endsWith(ext.toUpperCase()))) return [command];
113 - return extensions.map(ext => `${command}${ext}`);
114 -};
115 -
116 -const canExecute = async (filePath: string): Promise<boolean> => {
117 - try {
118 - await fs.access(filePath, fsConstants.X_OK);
119 - return true;
120 - } catch {
121 - return false;
122 - }
123 -};
124 -
125 -export const findExecutableOnPath = async (command: string): Promise<string | undefined> => {
126 - const trimmed = command.trim();
127 - if (!trimmed) return undefined;
128 -
129 - if (path.isAbsolute(trimmed) || hasPathSeparator(trimmed)) {
130 - for (const candidate of executableCandidates(trimmed)) {
131 - if (await canExecute(candidate)) return candidate;
132 - }
133 - return undefined;
134 - }
135 -
136 - for (const pathEntry of splitPathEntries(process.env.PATH)) {
137 - for (const candidate of executableCandidates(path.join(pathEntry, trimmed))) {
138 - if (await canExecute(candidate)) return candidate;
139 - }
140 - }
141 -
142 - return undefined;
143 -};
144 -
145 -const getToolkitMeta = (
146 - meta: Awaited<ReturnType<typeof readLocalToolsMeta>>,
147 - toolkitSlug: string
148 -) => meta.toolkits[toolkitSlug.toLowerCase()] ?? meta.toolkits[toolkitSlug];
149 -
150 -const getToolMeta = (meta: Awaited<ReturnType<typeof readLocalToolsMeta>>, finalSlug: string) =>
151 - meta.tools[finalSlug.toUpperCase()] ?? meta.tools[finalSlug];
152 -
153 -const isBundledBinaryRef = (value: unknown): value is LocalBundledBinaryRef =>
154 - typeof value === 'object' &&
155 - value !== null &&
156 - 'bundledBinary' in value &&
157 - typeof (value as { bundledBinary?: unknown }).bundledBinary === 'string';
158 -
159 -const resolveCommandSpec = async (
160 - execution: Extract<LocalToolExecution, { kind: 'command' }>,
161 - params: {
162 - readonly toolkit: LocalToolkitDeclaration;
163 - readonly currentPlatform: LocalCliPlatform;
164 - readonly commandOverride?: string;
165 - }
166 -): Promise<LocalCommandInvocation> => {
167 - const commandValue = resolveValue(execution.command);
168 - const invocation: LocalCommandInvocation =
169 - typeof commandValue === 'string'
170 - ? { command: commandValue }
171 - : isBundledBinaryRef(commandValue)
172 - ? await (async () => {
173 - const resolved = await resolveBundledBinary(params.toolkit, commandValue, {
174 - currentPlatform: params.currentPlatform,
175 - });
176 - return {
177 - command: resolved?.exists
178 - ? resolved.path
179 - : (commandValue.fallbackCommand ?? resolved?.path ?? commandValue.bundledBinary),
180 - };
181 - })()
182 - : commandValue;
183 - return {
184 - ...invocation,
185 - command: params.commandOverride ?? invocation.command,
186 - args: invocation.args ?? (execution.args ? resolveValue(execution.args) : undefined),
187 - };
188 -};
189 -
190 -const resolveMcpServer = (
191 - execution: Extract<LocalToolExecution, { kind: 'mcp' }>
192 -): LocalMcpServerSpec => resolveValue(execution.server);
193 -
194 -const setupHintsForToolkit = (toolkit: LocalToolkitDeclaration): ReadonlyArray<string> => [
195 - ...(toolkit.setup?.install ? [toolkit.setup.install] : []),
196 - ...(toolkit.setup?.commandOverrides ?? []),
197 - ...(toolkit.setup?.notes ?? []),
198 -];
199 -
200 -const checkCommand = async (
201 - command: string,
202 - args?: ReadonlyArray<string>
203 -): Promise<LocalCommandReadiness> => {
204 - const executablePath = await findExecutableOnPath(command);
205 - return {
206 - command,
207 - ...(args ? { args } : {}),
208 - found: executablePath !== undefined,
209 - ...(executablePath ? { path: executablePath } : {}),
210 - };
211 -};
212 -
213 -const checkToolReadiness = async (params: {
214 - readonly toolkit: LocalToolkitDeclaration;
215 - readonly tool: LocalToolDeclaration;
216 - readonly currentPlatform: LocalCliPlatform;
217 - readonly toolkitDisabled: boolean;
218 - readonly commandOverride?: string;
219 - readonly toolDisabled: boolean;
220 -}): Promise<LocalToolReadiness> => {
221 - const { toolkit, tool, currentPlatform, toolkitDisabled, commandOverride, toolDisabled } = params;
222 - const finalSlug = normalizeLocalToolSlug(tool.slug, toolkit.slug);
223 - const supported =
224 - supportsCliPlatform(toolkit.platforms, currentPlatform) &&
225 - supportsCliPlatform(tool.platforms, currentPlatform);
226 - const base = {
227 - finalSlug,
228 - slug: tool.slug,
229 - name: tool.name,
230 - toolkitSlug: toolkit.slug,
231 - executionKind: tool.execution.kind,
232 - platforms: tool.platforms,
233 - supported,
234 - } as const;
235 -
236 - if (!supported) {
237 - return {
238 - ...base,
239 - status: 'unsupported',
240 - messages: [
241 - `Unsupported on ${currentPlatform}; tool platforms: ${formatSupportedPlatforms(tool.platforms)}.`,
242 - ],
243 - hints: setupHintsForToolkit(toolkit),
244 - };
245 - }
246 -
247 - if (toolkitDisabled || toolDisabled) {
248 - return {
249 - ...base,
250 - status: 'disabled',
251 - messages: ['Disabled by ~/composio/local_tools.json metadata.'],
252 - hints: ['Remove disabled=true from the toolkit/tool metadata entry to re-enable it.'],
253 - };
254 - }
255 -
256 - if (tool.execution.kind === 'command') {
257 - try {
258 - const invocation = await resolveCommandSpec(tool.execution, {
259 - toolkit,
260 - currentPlatform,
261 - commandOverride,
262 - });
263 - const command = await checkCommand(invocation.command, invocation.args);
264 - return {
265 - ...base,
266 - status: command.found ? 'ready' : 'missing',
267 - command,
268 - messages: command.found
269 - ? [`Command found: ${command.path ?? command.command}.`]
270 - : [`Command not found on PATH: ${command.command}.`],
271 - hints: command.found
272 - ? []
273 - : [
274 - ...setupHintsForToolkit(toolkit),
275 - `Set ${finalSlug}.installation.command or ${toolkit.slug.toLowerCase()}.installation.command in ~/composio/local_tools.json to override the binary.`,
276 - ],
277 - };
278 - } catch (error) {
279 - return {
280 - ...base,
281 - status: 'unknown',
282 - messages: [
283 - `Could not resolve command wrapper: ${error instanceof Error ? error.message : String(error)}.`,
284 - ],
285 - hints: setupHintsForToolkit(toolkit),
286 - };
287 - }
288 - }
289 -
290 - if (tool.execution.kind === 'mcp') {
291 - try {
292 - const server = resolveMcpServer(tool.execution);
293 - const command = await checkCommand(server.command, server.args);
294 - return {
295 - ...base,
296 - status: command.found ? 'ready' : 'missing',
297 - command,
298 - messages: command.found
299 - ? [`MCP server launcher found: ${command.path ?? command.command}.`]
300 - : [`MCP server launcher not found on PATH: ${command.command}.`],
301 - hints: command.found ? (toolkit.setup?.notes ?? []) : setupHintsForToolkit(toolkit),
302 - };
303 - } catch (error) {
304 - return {
305 - ...base,
306 - status: 'unknown',
307 - messages: [
308 - `Could not resolve MCP server wrapper: ${error instanceof Error ? error.message : String(error)}.`,
309 - ],
310 - hints: setupHintsForToolkit(toolkit),
311 - };
312 - }
313 - }
314 -
315 - if (tool.execution.kind === 'ffi') {
316 - const library = tool.execution.library;
317 - const libraryPath =
318 - typeof library === 'string'
319 - ? library
320 - : ((await resolveBundledBinary(toolkit, library, { currentPlatform }))?.path ??
321 - library.fallbackCommand);
322 - const found = libraryPath
323 - ? await fs.access(libraryPath).then(
324 - () => true,
325 - () => false
326 - )
327 - : false;
328 - const bunAvailable = typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined';
329 - return {
330 - ...base,
331 - status: found ? (bunAvailable ? 'ready' : 'unknown') : 'missing',
332 - messages: [
333 - found
334 - ? `FFI library found: ${libraryPath}.`
335 - : `FFI library not found${typeof library === 'string' ? `: ${library}` : ` for bundled binary ${library.bundledBinary}`}.`,
336 - bunAvailable
337 - ? 'Bun FFI runtime is available.'
338 - : 'Bun FFI runtime is not available in this process; packaged CLI execution is required.',
339 - ],
340 - hints: found && bunAvailable ? [] : setupHintsForToolkit(toolkit),
341 - };
342 - }
343 -
344 - if (tool.execution.kind === 'native' && tool.execution.readiness) {
345 - const command = await checkCommand(
346 - commandOverride ?? tool.execution.readiness.command,
347 - tool.execution.readiness.args
348 - );
349 - return {
350 - ...base,
351 - status: command.found ? 'ready' : 'missing',
352 - command,
353 - messages: command.found
354 - ? [
355 - `Native wrapper prerequisite found: ${command.path ?? command.command}; app-specific runtime checks still happen at execution time.`,
356 - ]
357 - : [`Native wrapper prerequisite not found on PATH: ${command.command}.`],
358 - hints: command.found ? [] : setupHintsForToolkit(toolkit),
359 - };
360 - }
361 -
362 - if (tool.execution.kind === 'native' && toolkit.bundledBinaries?.length) {
363 - const bundledChecks = await Promise.all(
364 - toolkit.bundledBinaries.map(async binary => ({
365 - binary,
366 - resolved: await resolveBundledBinary(
367 - toolkit,
368 - { bundledBinary: binary.id },
369 - { currentPlatform }
370 - ),
371 - }))
372 - );
373 - const missing = bundledChecks.filter(check => check.resolved?.exists !== true);
374 - return {
375 - ...base,
376 - status: missing.length === 0 ? 'ready' : 'missing',
377 - messages:
378 - missing.length === 0
379 - ? bundledChecks.map(
380 - check => `Bundled local binary found: ${check.resolved?.path ?? check.binary.id}.`
381 - )
382 - : missing.map(check => `Bundled local binary not found: ${check.binary.id}.`),
383 - hints: missing.length === 0 ? [] : setupHintsForToolkit(toolkit),
384 - };
385 - }
386 -
387 - return {
388 - ...base,
389 - status: 'unknown',
390 - messages: ['Native local tool wrapper will self-check at execution time.'],
391 - hints: setupHintsForToolkit(toolkit),
392 - };
393 -};
394 -
395 -export const checkLocalToolkitsReadiness = async (
396 - options: {
397 - readonly currentPlatform?: LocalCliPlatform;
398 - readonly toolkits?: ReadonlyArray<string>;
399 - readonly includeUnsupported?: boolean;
400 - readonly metaOptions?: LocalToolsMetaOptions;
401 - readonly declarations?: ReadonlyArray<LocalToolkitDeclaration>;
402 - } = {}
403 -): Promise<LocalToolsReadinessReport> => {
404 - const currentPlatform = options.currentPlatform ?? detectCliPlatform();
405 - const meta = await readLocalToolsMeta(options.metaOptions);
406 - const toolkits = (options.declarations ?? localToolkitDeclarations).filter(toolkit =>
407 - toolkitMatchesFilter(toolkit, options.toolkits)
408 - );
409 - const visibleToolkits = options.includeUnsupported
410 - ? toolkits
411 - : toolkits.filter(toolkit => supportsCliPlatform(toolkit.platforms, currentPlatform));
412 -
413 - const reports = await Promise.all(
414 - visibleToolkits.map(async toolkit => {
415 - const toolkitMeta = getToolkitMeta(meta, toolkit.slug);
416 - const toolkitSupported = supportsCliPlatform(toolkit.platforms, currentPlatform);
417 - const toolkitDisabled = toolkitMeta?.disabled === true;
418 - const tools = await Promise.all(
419 - toolkit.tools.map(tool => {
420 - const finalSlug = normalizeLocalToolSlug(tool.slug, toolkit.slug);
421 - const toolMeta = getToolMeta(meta, finalSlug);
422 - return checkToolReadiness({
423 - toolkit,
424 - tool,
425 - currentPlatform,
426 - toolkitDisabled,
427 - toolDisabled: toolMeta?.disabled === true,
428 - commandOverride: toolMeta?.installation?.command ?? toolkitMeta?.installation?.command,
429 - });
430 - })
431 - );
432 - const status = toolkitSupported
433 - ? toolkitDisabled
434 - ? 'disabled'
435 - : aggregateStatus(tools.map(tool => tool.status))
436 - : 'unsupported';
437 - return {
438 - slug: toolkit.slug,
439 - name: toolkit.name,
440 - description: toolkit.description,
441 - platforms: toolkit.platforms,
442 - supported: toolkitSupported,
443 - status,
444 - source: toolkit.source,
445 - setup: toolkit.setup,
446 - tools,
447 - messages: toolkitSupported
448 - ? toolkitDisabled
449 - ? ['Disabled by ~/composio/local_tools.json metadata.']
450 - : []
451 - : [
452 - `Unsupported on ${currentPlatform}; toolkit platforms: ${formatSupportedPlatforms(toolkit.platforms)}.`,
453 - ],
454 - hints: status === 'ready' ? [] : setupHintsForToolkit(toolkit),
455 - } satisfies LocalToolkitReadiness;
456 - })
457 - );
458 -
459 - return { currentPlatform, toolkits: reports };
460 -};
ts/packages/cli-local-tools/src/registry.test.ts deleted
-135
@@ -1,135 +0,0 @@
1 -import os from 'node:os';
2 -import path from 'node:path';
3 -import { describe, expect, it } from 'vitest';
4 -import { z } from 'zod/v3';
5 -import {
6 - createLocalToolRouterExperimentalPayload,
7 - getLocalCustomToolkits,
8 - getLocalToolkitDeclarations,
9 - getLocalToolInputDefinition,
10 - localToolkitDeclarations,
11 - normalizeLocalToolSlug,
12 -} from './registry';
13 -import { checkLocalToolkitsReadiness } from './readiness';
14 -import type { LocalToolkitDeclaration } from './types';
15 -
16 -const fixtureToolkit: LocalToolkitDeclaration = {
17 - slug: 'FIXTURE_APP',
18 - name: 'Fixture App',
19 - description: 'Fixture local toolkit for registry tests.',
20 - platforms: ['darwin-arm64', 'linux-x64'],
21 - tools: [
22 - {
23 - slug: 'RUN_COMMAND',
24 - name: 'Run fixture command',
25 - description: 'Runs a fixture command.',
26 - platforms: ['darwin-arm64', 'linux-x64'],
27 - inputParams: z.object({
28 - args: z.array(z.string()).default([]),
29 - }),
30 - execution: {
31 - kind: 'command',
32 - command: 'node',
33 - args: input => (Array.isArray(input.args) ? input.args.map(String) : []),
34 - },
35 - },
36 - ],
37 -};
38 -
39 -const findToolkit = (
40 - payload: ReturnType<typeof createLocalToolRouterExperimentalPayload>,
41 - slug: string
42 -) => payload?.custom_toolkits?.find(toolkit => toolkit.slug === slug);
43 -
44 -describe('@composio/cli-local-tools registry', () => {
45 - it('registers concrete local toolkits in the integration layer', () => {
46 - expect(localToolkitDeclarations.map(toolkit => toolkit.slug)).toEqual(
47 - expect.arrayContaining(['BEEPER_IMESSAGE', 'CHROME_DEVTOOLS', 'PEEKABOO'])
48 - );
49 - expect(
50 - localToolkitDeclarations
51 - .find(toolkit => toolkit.slug === 'BEEPER_IMESSAGE')
52 - ?.tools.map(tool => tool.slug)
53 - ).toEqual(expect.arrayContaining(['LIST_THREADS', 'SEND_MESSAGE', 'AUTHORIZE']));
54 - expect(
55 - localToolkitDeclarations
56 - .find(toolkit => toolkit.slug === 'CHROME_DEVTOOLS')
57 - ?.tools.map(tool => tool.slug)
58 - ).toEqual(expect.arrayContaining(['LIST_PAGES', 'NEW_PAGE', 'EVALUATE_SCRIPT']));
59 - expect(
60 - localToolkitDeclarations
61 - .find(toolkit => toolkit.slug === 'PEEKABOO')
62 - ?.tools.map(tool => tool.slug)
63 - ).toEqual(expect.arrayContaining(['PERMISSIONS_STATUS', 'SEE', 'CLICK']));
64 - });
65 -
66 - it('normalizes local tool slugs to the Tool Router LOCAL_<TOOLKIT>_<TOOL> shape', () => {
67 - expect(normalizeLocalToolSlug('RUN_CLI', 'EXAMPLE_APP')).toBe('LOCAL_EXAMPLE_APP_RUN_CLI');
68 - });
69 -
70 - it('filters declarations by platform', () => {
71 - expect(
72 - getLocalToolkitDeclarations({
73 - currentPlatform: 'linux-x64',
74 - declarations: [fixtureToolkit],
75 - }).map(toolkit => toolkit.slug)
76 - ).toEqual(['FIXTURE_APP']);
77 - expect(
78 - getLocalToolkitDeclarations({
79 - currentPlatform: 'win32-x64',
80 - declarations: [fixtureToolkit],
81 - }).map(toolkit => toolkit.slug)
82 - ).toEqual([]);
83 - });
84 -
85 - it('builds core custom toolkit handles for supported local toolkits', () => {
86 - const [toolkit] = getLocalCustomToolkits({
87 - currentPlatform: 'linux-x64',
88 - toolkits: ['fixture_app'],
89 - declarations: [fixtureToolkit],
90 - });
91 -
92 - expect(toolkit?.slug).toBe('FIXTURE_APP');
93 - expect(toolkit?.tools[0]?.slug).toBe('RUN_COMMAND');
94 - expect(toolkit?.tools[0]?.inputSchema.properties).toHaveProperty('args');
95 - expect(typeof toolkit?.tools[0]?.execute).toBe('function');
96 - });
97 -
98 - it('builds Tool Router custom toolkit payloads for supported local toolkits', () => {
99 - const payload = createLocalToolRouterExperimentalPayload({
100 - currentPlatform: 'darwin-arm64',
101 - toolkits: ['fixture_app'],
102 - declarations: [fixtureToolkit],
103 - });
104 -
105 - expect(payload?.custom_toolkits).toHaveLength(1);
106 - expect(findToolkit(payload, 'FIXTURE_APP')?.tools.map(tool => tool.slug)).toEqual([
107 - 'RUN_COMMAND',
108 - ]);
109 - });
110 -
111 - it('exposes local input schemas for CLI --get-schema and dry-run validation', () => {
112 - const definition = getLocalToolInputDefinition('LOCAL_FIXTURE_APP_RUN_COMMAND', {
113 - declarations: [fixtureToolkit],
114 - });
115 - expect(definition?.version).toBe('local');
116 - expect(definition?.schema.properties).toHaveProperty('args');
117 - });
118 -
119 - it('reports platform readiness for supplied local toolkit declarations', async () => {
120 - const report = await checkLocalToolkitsReadiness({
121 - currentPlatform: 'linux-x64',
122 - includeUnsupported: true,
123 - declarations: [fixtureToolkit],
124 - metaOptions: {
125 - path: path.join(os.tmpdir(), `composio-local-tools-test-${Date.now()}.json`),
126 - },
127 - });
128 -
129 - expect(report.toolkits.find(toolkit => toolkit.slug === 'FIXTURE_APP')?.tools).toEqual(
130 - expect.arrayContaining([
131 - expect.objectContaining({ finalSlug: 'LOCAL_FIXTURE_APP_RUN_COMMAND' }),
132 - ])
133 - );
134 - });
135 -});
ts/packages/cli-local-tools/src/registry.ts deleted
-253
@@ -1,253 +0,0 @@
1 -import {
2 - experimental_createTool as createCustomTool,
3 - experimental_createToolkit as createCustomToolkit,
4 - type CustomToolkit,
5 -} from '@composio/core/experimental';
6 -import { beeperImessageToolkit } from './toolkits/beeper-imessage';
7 -import { chromeDevtoolsToolkit } from './toolkits/chrome-devtools';
8 -import { peekabooToolkit } from './toolkits/peekaboo';
9 -import { formatSupportedPlatforms, detectCliPlatform, supportsCliPlatform } from './platform';
10 -import { executeLocalTool } from './runtime';
11 -import type {
12 - LocalCliPlatform,
13 - LocalToolkitDeclaration,
14 - LocalToolDeclaration,
15 - LocalToolResolution,
16 - LocalToolRouterExperimentalPayload,
17 -} from './types';
18 -
19 -export const LOCAL_TOOL_PREFIX = 'LOCAL_';
20 -
21 -/** Built-in local toolkits shipped with @composio/cli-local-tools. */
22 -export const localToolkitDeclarations: ReadonlyArray<LocalToolkitDeclaration> = [
23 - beeperImessageToolkit,
24 - chromeDevtoolsToolkit,
25 - peekabooToolkit,
26 -];
27 -
28 -const normalizeSegment = (value: string): string =>
29 - value
30 - .toUpperCase()
31 - .replace(/[^A-Z0-9]+/g, '_')
32 - .replace(/^_+|_+$/g, '');
33 -
34 -export const normalizeLocalToolSlug = (toolSlug: string, toolkitSlug?: string): string =>
35 - toolkitSlug
36 - ? `${LOCAL_TOOL_PREFIX}${normalizeSegment(toolkitSlug)}_${normalizeSegment(toolSlug)}`
37 - : `${LOCAL_TOOL_PREFIX}${normalizeSegment(toolSlug)}`;
38 -
39 -const descriptionWithPlatform = (
40 - description: string,
41 - platforms: ReadonlyArray<LocalCliPlatform>
42 -): string => `${description}\n\nLocal CLI platforms: ${formatSupportedPlatforms(platforms)}.`;
43 -
44 -const toCustomTool = (
45 - toolkit: LocalToolkitDeclaration,
46 - tool: LocalToolDeclaration,
47 - currentPlatform: LocalCliPlatform
48 -) =>
49 - createCustomTool(tool.slug, {
50 - name: tool.name,
51 - description: descriptionWithPlatform(tool.description, tool.platforms),
52 - inputParams: tool.inputParams,
53 - ...(tool.outputParams ? { outputParams: tool.outputParams } : {}),
54 - execute: async input =>
55 - executeLocalTool(tool.execution, input as Record<string, unknown>, {
56 - toolkit,
57 - tool,
58 - finalSlug: normalizeLocalToolSlug(tool.slug, toolkit.slug),
59 - platform: currentPlatform,
60 - }),
61 - });
62 -
63 -const toCustomToolkit = (
64 - toolkit: LocalToolkitDeclaration,
65 - currentPlatform: LocalCliPlatform
66 -): CustomToolkit =>
67 - createCustomToolkit(toolkit.slug, {
68 - name: toolkit.name,
69 - description: descriptionWithPlatform(toolkit.description, toolkit.platforms),
70 - tools: toolkit.tools.map(tool => toCustomTool(toolkit, tool, currentPlatform)),
71 - });
72 -
73 -const toolkitMatchesFilter = (
74 - toolkit: LocalToolkitDeclaration,
75 - requestedToolkits?: ReadonlyArray<string>
76 -): boolean => {
77 - if (!requestedToolkits || requestedToolkits.length === 0) return true;
78 - const requested = new Set(requestedToolkits.map(slug => slug.toLowerCase()));
79 - return requested.has(toolkit.slug.toLowerCase());
80 -};
81 -
82 -const declarationsFor = (
83 - declarations: ReadonlyArray<LocalToolkitDeclaration> | undefined
84 -): ReadonlyArray<LocalToolkitDeclaration> => declarations ?? localToolkitDeclarations;
85 -
86 -export const getAllLocalToolkitSlugs = (
87 - options: {
88 - readonly declarations?: ReadonlyArray<LocalToolkitDeclaration>;
89 - } = {}
90 -): ReadonlyArray<string> =>
91 - declarationsFor(options.declarations).map(toolkit => toolkit.slug.toLowerCase());
92 -
93 -export const isLocalToolkitSlug = (
94 - toolkitSlug: string | undefined,
95 - options: { readonly declarations?: ReadonlyArray<LocalToolkitDeclaration> } = {}
96 -): boolean => {
97 - if (!toolkitSlug) return false;
98 - const lower = toolkitSlug.toLowerCase();
99 - return getAllLocalToolkitSlugs(options).includes(lower);
100 -};
101 -
102 -export const isLocalToolSlug = (
103 - toolSlug: string,
104 - options: { readonly declarations?: ReadonlyArray<LocalToolkitDeclaration> } = {}
105 -): boolean => {
106 - const upper = toolSlug.toUpperCase();
107 - if (!upper.startsWith(LOCAL_TOOL_PREFIX)) return false;
108 - return (
109 - resolveLocalTool(toolSlug, { includeUnsupported: true, declarations: options.declarations }) !==
110 - null
111 - );
112 -};
113 -
114 -export const getLocalToolkitDeclarations = (
115 - options: {
116 - readonly currentPlatform?: LocalCliPlatform;
117 - readonly toolkits?: ReadonlyArray<string>;
118 - readonly declarations?: ReadonlyArray<LocalToolkitDeclaration>;
119 - } = {}
120 -): ReadonlyArray<LocalToolkitDeclaration> => {
121 - const currentPlatform = options.currentPlatform ?? detectCliPlatform();
122 - return declarationsFor(options.declarations)
123 - .filter(toolkit => toolkitMatchesFilter(toolkit, options.toolkits))
124 - .filter(toolkit => supportsCliPlatform(toolkit.platforms, currentPlatform))
125 - .map(toolkit => ({
126 - ...toolkit,
127 - tools: toolkit.tools.filter(tool => supportsCliPlatform(tool.platforms, currentPlatform)),
128 - }))
129 - .filter(toolkit => toolkit.tools.length > 0);
130 -};
131 -
132 -export const getLocalCustomToolkits = (
133 - options: {
134 - readonly currentPlatform?: LocalCliPlatform;
135 - readonly toolkits?: ReadonlyArray<string>;
136 - readonly declarations?: ReadonlyArray<LocalToolkitDeclaration>;
137 - } = {}
138 -): ReadonlyArray<CustomToolkit> => {
139 - const currentPlatform = options.currentPlatform ?? detectCliPlatform();
140 - return getLocalToolkitDeclarations({ ...options, currentPlatform }).map(toolkit =>
141 - toCustomToolkit(toolkit, currentPlatform)
142 - );
143 -};
144 -
145 -const customToolkitToPayload = (
146 - toolkit: CustomToolkit
147 -): NonNullable<LocalToolRouterExperimentalPayload['custom_toolkits']>[number] => ({
148 - slug: toolkit.slug,
149 - name: toolkit.name,
150 - description: toolkit.description,
151 - tools: toolkit.tools.map(tool => ({
152 - slug: tool.slug,
153 - name: tool.name,
154 - description: tool.description,
155 - input_schema: tool.inputSchema,
156 - ...(tool.outputSchema ? { output_schema: tool.outputSchema } : {}),
157 - })),
158 -});
159 -
160 -export const createLocalToolRouterExperimentalPayload = (
161 - options: {
162 - readonly currentPlatform?: LocalCliPlatform;
163 - readonly toolkits?: ReadonlyArray<string>;
164 - readonly declarations?: ReadonlyArray<LocalToolkitDeclaration>;
165 - } = {}
166 -): LocalToolRouterExperimentalPayload | undefined => {
167 - const customToolkits = getLocalCustomToolkits(options).map(customToolkitToPayload);
168 - if (customToolkits.length === 0) return undefined;
169 - return { custom_toolkits: customToolkits };
170 -};
171 -
172 -export const resolveLocalTool = (
173 - slug: string,
174 - options: {
175 - readonly currentPlatform?: LocalCliPlatform;
176 - readonly includeUnsupported?: boolean;
177 - readonly declarations?: ReadonlyArray<LocalToolkitDeclaration>;
178 - } = {}
179 -): LocalToolResolution | null => {
180 - const currentPlatform = options.currentPlatform ?? detectCliPlatform();
181 - const target = normalizeSegment(slug);
182 -
183 - for (const toolkit of declarationsFor(options.declarations)) {
184 - for (const tool of toolkit.tools) {
185 - const finalSlug = normalizeLocalToolSlug(tool.slug, toolkit.slug);
186 - const matches =
187 - normalizeSegment(finalSlug) === target ||
188 - normalizeSegment(tool.slug) === target ||
189 - normalizeSegment(`${toolkit.slug}_${tool.slug}`) === target;
190 - if (!matches) continue;
191 -
192 - const supported =
193 - supportsCliPlatform(toolkit.platforms, currentPlatform) &&
194 - supportsCliPlatform(tool.platforms, currentPlatform);
195 - if (!supported && !options.includeUnsupported) return null;
196 - return { toolkit, tool, finalSlug, supported, currentPlatform };
197 - }
198 - }
199 -
200 - return null;
201 -};
202 -
203 -export const getLocalToolInputDefinition = (
204 - slug: string,
205 - options: { readonly declarations?: ReadonlyArray<LocalToolkitDeclaration> } = {}
206 -): {
207 - readonly finalSlug: string;
208 - readonly toolkit: string;
209 - readonly schema: Record<string, unknown>;
210 - readonly version: 'local';
211 -} | null => {
212 - const resolution = resolveLocalTool(slug, {
213 - includeUnsupported: true,
214 - declarations: options.declarations,
215 - });
216 - if (!resolution) return null;
217 - return {
218 - finalSlug: resolution.finalSlug,
219 - toolkit: resolution.toolkit.slug,
220 - schema: toCustomTool(resolution.toolkit, resolution.tool, resolution.currentPlatform)
221 - .inputSchema,
222 - version: 'local',
223 - };
224 -};
225 -
226 -export const executeLocalToolBySlug = async (
227 - slug: string,
228 - args: Record<string, unknown>
229 -): Promise<Record<string, unknown> | null> => {
230 - const resolution = resolveLocalTool(slug, { includeUnsupported: true });
231 - if (!resolution) return null;
232 - if (!resolution.supported) {
233 - throw new Error(
234 - `Local tool ${resolution.finalSlug} is not supported on ${resolution.currentPlatform}. Supported platforms: ${formatSupportedPlatforms(resolution.tool.platforms)}.`
235 - );
236 - }
237 -
238 - const parsed = resolution.tool.inputParams.safeParse(args);
239 - if (!parsed.success) {
240 - throw new Error(
241 - `Invalid arguments for local tool ${resolution.finalSlug}: ${parsed.error.issues
242 - .map(issue => `${issue.path.join('.') || '<root>'}: ${issue.message}`)
243 - .join('; ')}`
244 - );
245 - }
246 -
247 - return executeLocalTool(resolution.tool.execution, parsed.data as Record<string, unknown>, {
248 - toolkit: resolution.toolkit,
249 - tool: resolution.tool,
250 - finalSlug: resolution.finalSlug,
251 - platform: resolution.currentPlatform,
252 - });
253 -};
ts/packages/cli-local-tools/src/runtime.ts deleted
-294
@@ -1,294 +0,0 @@
1 -import { spawn } from 'node:child_process';
2 -import { once } from 'node:events';
3 -import { ensureBundledBinaryExecutable, resolveBundledBinary } from './bundled-binaries';
4 -import type {
5 - LocalBundledBinaryRef,
6 - LocalCommandExecution,
7 - LocalCommandInvocation,
8 - LocalCommandValue,
9 - LocalExecutionContext,
10 - LocalExecutionResult,
11 - LocalFfiExecution,
12 - LocalFfiLibraryHandle,
13 - LocalFfiType,
14 - LocalMcpExecution,
15 - LocalToolExecution,
16 -} from './types';
17 -import { getLocalToolkitMeta, getLocalToolMeta } from './meta';
18 -
19 -const toErrorMessage = (error: unknown): string =>
20 - error instanceof Error ? error.message : String(error);
21 -
22 -const compactEnv = (env: Record<string, string | undefined> | undefined): Record<string, string> =>
23 - Object.fromEntries(
24 - Object.entries(env ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined)
25 - );
26 -
27 -const resolveValue = <T>(
28 - value: T | ((input: Record<string, unknown>) => T),
29 - input: Record<string, unknown>
30 -): T =>
31 - typeof value === 'function' ? (value as (input: Record<string, unknown>) => T)(input) : value;
32 -
33 -const parseJsonIfRequested = (stdout: string, parseJson: boolean): unknown => {
34 - if (!parseJson || stdout.trim().length === 0) return stdout;
35 - try {
36 - return JSON.parse(stdout) as unknown;
37 - } catch {
38 - return stdout;
39 - }
40 -};
41 -
42 -const isBundledBinaryRef = (value: unknown): value is LocalBundledBinaryRef =>
43 - typeof value === 'object' &&
44 - value !== null &&
45 - 'bundledBinary' in value &&
46 - typeof (value as { bundledBinary?: unknown }).bundledBinary === 'string';
47 -
48 -const commandValueToInvocation = async (
49 - value: LocalCommandValue,
50 - context: LocalExecutionContext
51 -): Promise<LocalCommandInvocation> => {
52 - if (typeof value === 'string') return { command: value };
53 -
54 - if (isBundledBinaryRef(value)) {
55 - const resolved = await resolveBundledBinary(context.toolkit, value, {
56 - currentPlatform: context.platform,
57 - });
58 - const command = resolved?.exists ? resolved.path : value.fallbackCommand;
59 - if (!command) {
60 - throw new Error(
61 - `Bundled binary ${value.bundledBinary} was not found for ${context.platform} and no fallback command was provided.`
62 - );
63 - }
64 - if (resolved?.exists && resolved.source === 'bundled') {
65 - await ensureBundledBinaryExecutable(resolved.path);
66 - }
67 - return { ...value, command };
68 - }
69 -
70 - return value;
71 -};
72 -
73 -const resolveCommandInvocation = async (
74 - execution: LocalCommandExecution,
75 - input: Record<string, unknown>,
76 - context: LocalExecutionContext
77 -): Promise<LocalCommandInvocation> => {
78 - const commandValue = resolveValue(execution.command, input);
79 - const baseInvocation = await commandValueToInvocation(commandValue, context);
80 -
81 - const toolMeta = await getLocalToolMeta(context.finalSlug);
82 - const toolkitMeta = await getLocalToolkitMeta(context.toolkit.slug);
83 - const commandOverride = toolMeta?.installation?.command ?? toolkitMeta?.installation?.command;
84 -
85 - return {
86 - ...baseInvocation,
87 - command: commandOverride ?? baseInvocation.command,
88 - args: baseInvocation.args ?? (execution.args ? resolveValue(execution.args, input) : []),
89 - env: {
90 - ...compactEnv(execution.env ? resolveValue(execution.env, input) : undefined),
91 - ...compactEnv(baseInvocation.env),
92 - },
93 - cwd: baseInvocation.cwd ?? (execution.cwd ? resolveValue(execution.cwd, input) : undefined),
94 - stdin:
95 - baseInvocation.stdin ?? (execution.stdin ? resolveValue(execution.stdin, input) : undefined),
96 - timeoutMs: baseInvocation.timeoutMs ?? execution.timeoutMs,
97 - };
98 -};
99 -
100 -export const runLocalCommand = async (
101 - execution: LocalCommandExecution,
102 - input: Record<string, unknown>,
103 - context: LocalExecutionContext
104 -): Promise<LocalExecutionResult> => {
105 - const invocation = await resolveCommandInvocation(execution, input, context);
106 - const child = spawn(invocation.command, [...(invocation.args ?? [])], {
107 - cwd: invocation.cwd,
108 - env: { ...process.env, ...compactEnv(invocation.env) },
109 - stdio: ['pipe', 'pipe', 'pipe'],
110 - });
111 -
112 - let stdout = '';
113 - let stderr = '';
114 - child.stdout.setEncoding('utf8');
115 - child.stderr.setEncoding('utf8');
116 - child.stdout.on('data', chunk => {
117 - stdout += chunk;
118 - });
119 - child.stderr.on('data', chunk => {
120 - stderr += chunk;
121 - });
122 -
123 - if (invocation.stdin !== undefined) {
124 - child.stdin.end(invocation.stdin);
125 - } else {
126 - child.stdin.end();
127 - }
128 -
129 - let timeout: NodeJS.Timeout | undefined;
130 - if (invocation.timeoutMs && invocation.timeoutMs > 0) {
131 - timeout = setTimeout(() => child.kill('SIGTERM'), invocation.timeoutMs);
132 - }
133 -
134 - const exitPromise = once(child, 'exit') as Promise<[number | null, NodeJS.Signals | null]>;
135 - const errorPromise = once(child, 'error').then(([error]) => {
136 - throw error;
137 - }) as Promise<[number | null, NodeJS.Signals | null]>;
138 - const [exitCode, signal] = await Promise.race([exitPromise, errorPromise]);
139 - if (timeout) clearTimeout(timeout);
140 -
141 - if (exitCode !== 0) {
142 - throw new Error(
143 - [
144 - `Local command failed for ${context.finalSlug}: ${invocation.command} ${(invocation.args ?? []).join(' ')}`,
145 - `exitCode=${exitCode ?? 'null'} signal=${signal ?? 'null'}`,
146 - stderr.trim() ? `stderr: ${stderr.trim()}` : undefined,
147 - ]
148 - .filter(Boolean)
149 - .join('\n')
150 - );
151 - }
152 -
153 - return {
154 - command: invocation.command,
155 - args: invocation.args ?? [],
156 - stdout,
157 - stderr,
158 - exitCode,
159 - parsed: parseJsonIfRequested(stdout, execution.parseJson ?? false),
160 - };
161 -};
162 -
163 -export const runLocalMcpTool = async (
164 - execution: LocalMcpExecution,
165 - input: Record<string, unknown>
166 -): Promise<LocalExecutionResult> => {
167 - const [{ Client }, { StdioClientTransport }] = await Promise.all([
168 - import('@modelcontextprotocol/sdk/client/index.js'),
169 - import('@modelcontextprotocol/sdk/client/stdio.js'),
170 - ]);
171 -
172 - const server =
173 - typeof execution.server === 'function' ? execution.server(input) : execution.server;
174 - const client = new Client({ name: 'composio-cli-local-tools', version: '0.0.1' });
175 - const transport = new StdioClientTransport({
176 - command: server.command,
177 - args: [...(server.args ?? [])],
178 - env: { ...compactEnv(process.env), ...compactEnv(server.env) },
179 - cwd: server.cwd,
180 - });
181 -
182 - await client.connect(transport);
183 - try {
184 - const toolName = execution.toolName
185 - ? typeof execution.toolName === 'function'
186 - ? execution.toolName(input)
187 - : execution.toolName
188 - : undefined;
189 -
190 - if (!toolName) {
191 - const result = await client.listTools();
192 - return { tools: result.tools };
193 - }
194 -
195 - const args = execution.arguments
196 - ? typeof execution.arguments === 'function'
197 - ? execution.arguments(input)
198 - : execution.arguments
199 - : input;
200 - const result = await client.callTool({ name: toolName, arguments: args });
201 - return { toolName, result: result as unknown as Record<string, unknown> };
202 - } finally {
203 - await client.close().catch(() => undefined);
204 - }
205 -};
206 -
207 -const ffiTypeMap: Record<LocalFfiType, string> = {
208 - char: 'char',
209 - uchar: 'uchar',
210 - i8: 'i8',
211 - u8: 'u8',
212 - i16: 'i16',
213 - u16: 'u16',
214 - i32: 'i32',
215 - u32: 'u32',
216 - i64: 'i64',
217 - u64: 'u64',
218 - f32: 'f32',
219 - f64: 'f64',
220 - bool: 'bool',
221 - ptr: 'ptr',
222 - cstring: 'cstring',
223 - void: 'void',
224 -};
225 -
226 -const isBun = typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined';
227 -
228 -const resolveFfiLibraryPath = async (
229 - execution: LocalFfiExecution,
230 - context: LocalExecutionContext
231 -): Promise<string> => {
232 - if (typeof execution.library === 'string') return execution.library;
233 - const resolved = await resolveBundledBinary(context.toolkit, execution.library, {
234 - currentPlatform: context.platform,
235 - });
236 - if (resolved?.exists) return resolved.path;
237 - if (execution.library.fallbackCommand) return execution.library.fallbackCommand;
238 - throw new Error(
239 - `Bundled FFI library ${execution.library.bundledBinary} was not found for ${context.platform}.`
240 - );
241 -};
242 -
243 -const runLocalFfiTool = async (
244 - execution: LocalFfiExecution,
245 - input: Record<string, unknown>,
246 - context: LocalExecutionContext
247 -): Promise<LocalExecutionResult> => {
248 - if (!isBun) {
249 - throw new Error(
250 - 'Local FFI execution requires the Bun runtime used by the packaged Composio CLI.'
251 - );
252 - }
253 -
254 - const { dlopen, FFIType } = (await import('bun:ffi')) as typeof import('bun:ffi');
255 - const libraryPath = await resolveFfiLibraryPath(execution, context);
256 - const bindings = Object.fromEntries(
257 - Object.entries(execution.symbols).map(([name, symbol]) => [
258 - name,
259 - {
260 - args: symbol.args.map(type => FFIType[ffiTypeMap[type] as keyof typeof FFIType]),
261 - returns: FFIType[ffiTypeMap[symbol.returns] as keyof typeof FFIType],
262 - },
263 - ])
264 - );
265 - const library = dlopen(libraryPath, bindings);
266 - const handle: LocalFfiLibraryHandle = {
267 - path: libraryPath,
268 - symbols: library.symbols as Record<string, (...args: ReadonlyArray<unknown>) => unknown>,
269 - };
270 - return execution.execute(input, context, handle);
271 -};
272 -
273 -export const executeLocalTool = async (
274 - execution: LocalToolExecution,
275 - input: Record<string, unknown>,
276 - context: LocalExecutionContext
277 -): Promise<LocalExecutionResult> => {
278 - try {
279 - if (execution.kind === 'native') {
280 - return await execution.execute(input, context);
281 - }
282 - if (execution.kind === 'command') {
283 - return await runLocalCommand(execution, input, context);
284 - }
285 - if (execution.kind === 'mcp') {
286 - return await runLocalMcpTool(execution, input);
287 - }
288 - return await runLocalFfiTool(execution, input, context);
289 - } catch (error) {
290 - throw new Error(`Failed to execute local tool ${context.finalSlug}: ${toErrorMessage(error)}`, {
291 - cause: error,
292 - });
293 - }
294 -};
ts/packages/cli-local-tools/src/toolkits/beeper-imessage.test.ts deleted
-39
@@ -1,39 +0,0 @@
1 -import { describe, expect, it } from 'vitest';
2 -import { resolveBundledBinary } from '../bundled-binaries';
3 -import { executeLocalToolBySlug, getLocalToolInputDefinition } from '../registry';
4 -import { beeperImessageToolkit } from './beeper-imessage';
5 -
6 -describe('@composio/cli-local-tools Beeper iMessage toolkit', () => {
7 - it('exposes first-class schemas for Beeper iMessage tools', () => {
8 - expect(beeperImessageToolkit.tools.map(tool => tool.slug)).toEqual(
9 - expect.arrayContaining(['LIST_THREADS', 'FIND_THREAD', 'SEND_MESSAGE', 'AUTHORIZE'])
10 - );
11 -
12 - const sendSchema = getLocalToolInputDefinition('LOCAL_BEEPER_IMESSAGE_SEND_MESSAGE');
13 - expect(sendSchema?.schema.properties).toHaveProperty('threadId');
14 - expect(sendSchema?.schema.properties).toHaveProperty('text');
15 - expect(sendSchema?.schema.properties).toHaveProperty('verifySent');
16 -
17 - const listSchema = getLocalToolInputDefinition('LOCAL_BEEPER_IMESSAGE_LIST_THREADS');
18 - expect(listSchema?.schema.properties).toHaveProperty('compact');
19 - expect(listSchema?.schema.properties).toHaveProperty('resolveContactNames');
20 -
21 - const reactSchema = getLocalToolInputDefinition('LOCAL_BEEPER_IMESSAGE_REACT_TO_MESSAGE');
22 - expect(reactSchema?.schema.properties).toHaveProperty('prepareTranscript');
23 - });
24 -
25 - it.runIf(process.env.COMPOSIO_REAL_LOCAL_TOOLS_TESTS === '1' && process.platform === 'darwin')(
26 - 'resolves generated bundled imessage-cli and executes the bootstrap-free version command',
27 - async () => {
28 - const resolved = await resolveBundledBinary(
29 - beeperImessageToolkit,
30 - { bundledBinary: 'beeper-imessage-cli' },
31 - { currentPlatform: process.arch === 'x64' ? 'darwin-x64' : 'darwin-arm64' }
32 - );
33 - expect(resolved?.exists).toBe(true);
34 -
35 - const result = await executeLocalToolBySlug('LOCAL_BEEPER_IMESSAGE_VERSION', {});
36 - expect(result?.resultText).toContain('platform-imessage 0.21.0');
37 - }
38 - );
39 -});
ts/packages/cli-local-tools/src/toolkits/beeper-imessage.ts deleted
-1295
@@ -1,1295 +0,0 @@
1 -import { spawn } from 'node:child_process';
2 -import { z } from 'zod/v3';
3 -import { runLocalCommand } from '../runtime';
4 -import type {
5 - LocalCommandExecution,
6 - LocalExecutionContext,
7 - LocalExecutionResult,
8 - LocalToolkitDeclaration,
9 - LocalToolDeclaration,
10 -} from '../types';
11 -
12 -const IMESSAGE_CLI_BINARY_ID = 'beeper-imessage-cli';
13 -const IMESSAGE_CLI_VERSION = '0.21.0';
14 -const COMMAND_TIMEOUT_MS = 120_000;
15 -const SEND_VERIFY_TIMEOUT_MS = 8_000;
16 -const SEND_VERIFY_INTERVAL_MS = 500;
17 -const THREAD_SCAN_DEFAULT_MAX_PAGES = 10;
18 -const THREAD_SCAN_MAX_PAGES = 50;
19 -const CONTACT_LOOKUP_TIMEOUT_MS = 5_000;
20 -const REACTION_PREPARE_TIMEOUT_MS = 5_000;
21 -const REACTION_TIMEOUT_MS = 20_000;
22 -
23 -const baseInput = z.object({
24 - dataDir: z
25 - .string()
26 - .min(1)
27 - .optional()
28 - .describe('Optional directory for imessage-cli state. Defaults to a temporary directory.'),
29 - useSecondaryInstance: z
30 - .boolean()
31 - .default(true)
32 - .describe(
33 - 'Use a secondary Messages.app instance. This is usually fine for read/send/list tools. UI-dependent tools such as reactions default to the primary Messages.app instance because they need the transcript view to be visible.'
34 - ),
35 - verbose: z.boolean().default(false).describe('Enable verbose imessage-cli logging.'),
36 -});
37 -
38 -const primaryInstanceInput = baseInput.extend({
39 - useSecondaryInstance: z
40 - .boolean()
41 - .default(false)
42 - .describe(
43 - 'Use a secondary Messages.app instance. Defaults to false for reactions because the upstream UI automation needs the primary transcript view to be visible.'
44 - ),
45 -});
46 -
47 -const cursorInput = z.object({
48 - before: z
49 - .string()
50 - .min(1)
51 - .optional()
52 - .describe(
53 - 'Fetch items older than this cursor. For LIST_THREADS, use result.pageInfo.nextBefore.'
54 - ),
55 - after: z.string().min(1).optional().describe('Fetch items newer than this cursor.'),
56 -});
57 -
58 -const cliOutput = z.object({
59 - ok: z.boolean(),
60 - commandName: z.string(),
61 - callId: z.string().optional(),
62 - durationMs: z.number().optional(),
63 - result: z.unknown().optional(),
64 - resultText: z.string().optional(),
65 - stdout: z.string(),
66 - stderr: z.string(),
67 -});
68 -
69 -const stringArray = (value: unknown): string[] =>
70 - Array.isArray(value) ? value.map(item => String(item)) : [];
71 -
72 -const stringValue = (value: unknown): string => String(value ?? '');
73 -
74 -const optionalString = (value: unknown): string | undefined => {
75 - const text = typeof value === 'string' ? value.trim() : '';
76 - return text.length > 0 ? text : undefined;
77 -};
78 -
79 -const absolutePath = (value: unknown): string => stringValue(value);
80 -
81 -const isRecord = (value: unknown): value is Record<string, unknown> =>
82 - typeof value === 'object' && value !== null && !Array.isArray(value);
83 -
84 -const toRecordArray = (value: unknown): Record<string, unknown>[] => {
85 - if (Array.isArray(value)) return value.filter(isRecord);
86 - if (isRecord(value) && Array.isArray(value.items)) return value.items.filter(isRecord);
87 - return [];
88 -};
89 -
90 -const normalizePhone = (value: string): string => value.replace(/[^0-9]/g, '');
91 -
92 -const normalizeIdentifier = (value: unknown): string => {
93 - const text = String(value ?? '')
94 - .trim()
95 - .toLowerCase();
96 - if (!text) return '';
97 - if (text.includes('@')) return text;
98 - const digits = normalizePhone(text);
99 - return digits || text;
100 -};
101 -
102 -const unique = <T>(values: ReadonlyArray<T>): T[] => [...new Set(values)];
103 -
104 -const compactRecord = (record: Record<string, unknown>, keys: ReadonlyArray<string>) =>
105 - Object.fromEntries(keys.filter(key => record[key] !== undefined).map(key => [key, record[key]]));
106 -
107 -const messageIdOf = (message: unknown): string | undefined =>
108 - isRecord(message) ? optionalString(message.id) : undefined;
109 -
110 -const messageTextOf = (message: unknown): string =>
111 - isRecord(message) ? stringValue(message.text ?? '') : '';
112 -
113 -const messageIsSender = (message: unknown): boolean =>
114 - isRecord(message) && message.isSender === true;
115 -
116 -const messageMatchesSentText = (message: unknown, text: string): boolean =>
117 - messageIsSender(message) && messageTextOf(message) === text;
118 -
119 -const extractPageItems = (result: unknown): Record<string, unknown>[] =>
120 - isRecord(result) ? toRecordArray(result.items) : [];
121 -
122 -const extractThreadId = (value: unknown): string | undefined => {
123 - if (!isRecord(value)) return undefined;
124 - return optionalString(value.id ?? value.threadId ?? value.threadID ?? value.chatId);
125 -};
126 -
127 -const participantIdentifiers = (thread: Record<string, unknown>): string[] => {
128 - const participants = toRecordArray(thread.participants);
129 - return unique(
130 - participants.flatMap(participant =>
131 - [participant.email, participant.phoneNumber, participant.handle, participant.id]
132 - .map(optionalString)
133 - .filter((value): value is string => Boolean(value))
134 - )
135 - );
136 -};
137 -
138 -const latestMessage = (thread: Record<string, unknown>): Record<string, unknown> | undefined => {
139 - const messages = toRecordArray(thread.messages);
140 - return messages[0];
141 -};
142 -
143 -const buildGlobalArgs = (input: Record<string, unknown>): string[] => {
144 - const args: string[] = [];
145 - const dataDir = optionalString(input.dataDir);
146 - if (dataDir) args.push('--data-dir', dataDir);
147 - if (input.useSecondaryInstance === false) args.push('--no-use-secondary-instance');
148 - // Local tools are one-shot calls. Avoid keeping DB event watchers open unless a
149 - // future streaming tool explicitly opts in.
150 - args.push('--no-events');
151 - if (input.verbose === true) args.push('--verbose');
152 - return args;
153 -};
154 -
155 -const withCursorArgs = (input: Record<string, unknown>, args: string[]): string[] => {
156 - const before = optionalString(input.before);
157 - const after = optionalString(input.after);
158 - if (before && after) throw new Error('Use only one of before or after.');
159 - if (before) args.push('--before', before);
160 - if (after) args.push('--after', after);
161 - return args;
162 -};
163 -
164 -const stripAnsi = (text: string): string => text.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, '');
165 -
166 -const parseImessageCliOutput = (
167 - commandName: string,
168 - stdout: string,
169 - stderr: string
170 -): LocalExecutionResult => {
171 - const cleanStdout = stripAnsi(stdout);
172 - const lines = cleanStdout.split(/\r?\n/);
173 - const okIndex = lines.findIndex(line => /^\[\d+\] ok /.test(line));
174 - const okLine = okIndex >= 0 ? lines[okIndex] : undefined;
175 - const match = okLine?.match(/^\[(\d+)\] ok \S+ \((\d+(?:\.\d+)?)ms\)$/);
176 -
177 - const resultLines = okIndex >= 0 ? lines.slice(okIndex + 1) : lines;
178 - const resultText = resultLines
179 - .filter(line => line.trim() !== 'Exiting...')
180 - .join('\n')
181 - .trim();
182 -
183 - let parsed: unknown;
184 - if (resultText) {
185 - try {
186 - parsed = JSON.parse(resultText) as unknown;
187 - } catch {
188 - parsed = undefined;
189 - }
190 - }
191 -
192 - return {
193 - ok: true,
194 - commandName,
195 - ...(match?.[1] ? { callId: match[1] } : {}),
196 - ...(match?.[2] ? { durationMs: Number(match[2]) } : {}),
197 - ...(parsed !== undefined ? { result: parsed } : {}),
198 - ...(resultText ? { resultText } : {}),
199 - stdout,
200 - stderr,
201 - };
202 -};
203 -
204 -const runImessageCli = async (
205 - commandName: string,
206 - commandArgs: ReadonlyArray<string>,
207 - input: Record<string, unknown>,
208 - context: LocalExecutionContext,
209 - options: { readonly timeoutMs?: number } = {}
210 -): Promise<LocalExecutionResult> => {
211 - const execution: LocalCommandExecution = {
212 - kind: 'command',
213 - command: {
214 - bundledBinary: IMESSAGE_CLI_BINARY_ID,
215 - fallbackCommand: 'imessage-cli',
216 - },
217 - args: [...buildGlobalArgs(input), commandName, ...commandArgs],
218 - timeoutMs: options.timeoutMs ?? COMMAND_TIMEOUT_MS,
219 - };
220 - const result = await runLocalCommand(execution, input, context);
221 - return parseImessageCliOutput(
222 - commandName,
223 - String(result.stdout ?? ''),
224 - String(result.stderr ?? '')
225 - );
226 -};
227 -
228 -const runProcess = async (
229 - command: string,
230 - args: ReadonlyArray<string>,
231 - timeoutMs: number
232 -): Promise<{ readonly stdout: string; readonly stderr: string }> => {
233 - const child = spawn(command, [...args], {
234 - env: process.env,
235 - stdio: ['ignore', 'pipe', 'pipe'],
236 - });
237 -
238 - let stdout = '';
239 - let stderr = '';
240 - child.stdout.setEncoding('utf8');
241 - child.stderr.setEncoding('utf8');
242 - child.stdout.on('data', chunk => {
243 - stdout += chunk;
244 - });
245 - child.stderr.on('data', chunk => {
246 - stderr += chunk;
247 - });
248 -
249 - const exitPromise = new Promise<{
250 - readonly exitCode: number | null;
251 - readonly signal: string | null;
252 - }>((resolve, reject) => {
253 - child.once('error', reject);
254 - child.once('exit', (exitCode, signal) => resolve({ exitCode, signal }));
255 - });
256 - const timeout = setTimeout(() => child.kill('SIGTERM'), timeoutMs);
257 - const { exitCode, signal } = await exitPromise.finally(() => clearTimeout(timeout));
258 - if (exitCode !== 0) {
259 - throw new Error(
260 - `${command} failed with exitCode=${exitCode ?? 'null'} signal=${signal ?? 'null'}${
261 - stderr.trim() ? `: ${stderr.trim()}` : ''
262 - }`
263 - );
264 - }
265 - return { stdout, stderr };
266 -};
267 -
268 -const contactLookupScript = `
269 -function normalizePhone(value) {
270 - return String(value || '').replace(/[^0-9]/g, '');
271 -}
272 -function normalizeIdentifier(value) {
273 - const text = String(value || '').trim().toLowerCase();
274 - if (!text) return '';
275 - if (text.indexOf('@') >= 0) return text;
276 - return normalizePhone(text) || text;
277 -}
278 -function valuesOf(collection) {
279 - try { return collection().map(item => String(item.value())); } catch (_) { return []; }
280 -}
281 -function personName(person) {
282 - try { return String(person.name() || '').trim(); } catch (_) { return ''; }
283 -}
284 -function run(argv) {
285 - const mode = argv[0] || 'query';
286 - const payload = JSON.parse(argv[1] || '{}');
287 - const query = String(payload.query || '').toLowerCase();
288 - const requestedIdentifiers = (payload.identifiers || []).map(normalizeIdentifier).filter(Boolean);
289 - const requestedSet = new Set(requestedIdentifiers);
290 - const Contacts = Application('Contacts');
291 - const people = Contacts.people();
292 - const matches = [];
293 - const labels = {};
294 - for (const person of people) {
295 - const name = personName(person);
296 - const emails = valuesOf(person.emails);
297 - const phones = valuesOf(person.phones);
298 - const identifiers = emails.concat(phones);
299 - const normalized = identifiers.map(normalizeIdentifier).filter(Boolean);
300 - const haystack = [name].concat(identifiers).join(' ').toLowerCase();
301 - if (mode === 'query' && query && haystack.indexOf(query) >= 0) {
302 - matches.push({ name, emails, phones, identifiers });
303 - }
304 - if (mode === 'labels') {
305 - for (let index = 0; index < normalized.length; index += 1) {
306 - const value = normalized[index];
307 - if (requestedSet.has(value)) labels[value] = name || identifiers[index] || value;
308 - }
309 - }
310 - }
311 - return JSON.stringify({ matches: matches.slice(0, 25), labels });
312 -}
313 -`;
314 -
315 -interface ContactLookupResult {
316 - readonly matches: ReadonlyArray<{
317 - readonly name?: string;
318 - readonly emails?: ReadonlyArray<string>;
319 - readonly phones?: ReadonlyArray<string>;
320 - readonly identifiers?: ReadonlyArray<string>;
321 - }>;
322 - readonly labels: Record<string, string>;
323 - readonly error?: string;
324 -}
325 -
326 -const emptyContactLookup = (error?: string): ContactLookupResult => ({
327 - matches: [],
328 - labels: {},
329 - ...(error ? { error } : {}),
330 -});
331 -
332 -const lookupContacts = async (
333 - mode: 'query' | 'labels',
334 - payload: Record<string, unknown>
335 -): Promise<ContactLookupResult> => {
336 - if (process.platform !== 'darwin') return emptyContactLookup('Contacts lookup requires macOS.');
337 - try {
338 - const result = await runProcess(
339 - 'osascript',
340 - ['-l', 'JavaScript', '-e', contactLookupScript, mode, JSON.stringify(payload)],
341 - CONTACT_LOOKUP_TIMEOUT_MS
342 - );
343 - const parsed = JSON.parse(result.stdout.trim()) as unknown;
344 - if (!isRecord(parsed))
345 - return emptyContactLookup('Contacts lookup returned a non-object result.');
346 - return {
347 - matches: Array.isArray(parsed.matches) ? parsed.matches.filter(isRecord) : [],
348 - labels: isRecord(parsed.labels)
349 - ? Object.fromEntries(
350 - Object.entries(parsed.labels).map(([key, value]) => [key, String(value)])
351 - )
352 - : {},
353 - };
354 - } catch (error) {
355 - return emptyContactLookup(error instanceof Error ? error.message : String(error));
356 - }
357 -};
358 -
359 -const contactIdentifiersFromMatches = (lookup: ContactLookupResult): string[] =>
360 - unique(
361 - lookup.matches.flatMap(match =>
362 - [...(match.identifiers ?? []), ...(match.emails ?? []), ...(match.phones ?? [])]
363 - .map(normalizeIdentifier)
364 - .filter(Boolean)
365 - )
366 - );
367 -
368 -const labelsForThreads = async (
369 - threads: ReadonlyArray<Record<string, unknown>>,
370 - enabled: boolean
371 -): Promise<Record<string, string>> => {
372 - if (!enabled || threads.length === 0) return {};
373 - const identifiers = unique(threads.flatMap(thread => participantIdentifiers(thread))).map(
374 - normalizeIdentifier
375 - );
376 - if (identifiers.length === 0) return {};
377 - return (await lookupContacts('labels', { identifiers })).labels;
378 -};
379 -
380 -const compactParticipant = (
381 - participant: Record<string, unknown>,
382 - labels: Record<string, string>
383 -): Record<string, unknown> => {
384 - const identifier = optionalString(
385 - participant.email ?? participant.phoneNumber ?? participant.handle
386 - );
387 - const normalized = normalizeIdentifier(identifier);
388 - return {
389 - ...compactRecord(participant, ['isSelf', 'email', 'phoneNumber', 'handle']),
390 - ...(identifier && labels[normalized] ? { label: labels[normalized] } : {}),
391 - };
392 -};
393 -
394 -const compactMessage = (message: unknown): Record<string, unknown> | undefined => {
395 - if (!isRecord(message)) return undefined;
396 - return compactRecord(message, [
397 - 'id',
398 - 'text',
399 - 'isSender',
400 - 'timestamp',
401 - 'isDelivered',
402 - 'isErrored',
403 - 'seen',
404 - ]);
405 -};
406 -
407 -const compactThread = (thread: Record<string, unknown>, labels: Record<string, string>) => {
408 - const participants = toRecordArray(thread.participants).map(participant =>
409 - compactParticipant(participant, labels)
410 - );
411 - const lastMessage = compactMessage(latestMessage(thread));
412 - const participantLabels = unique(
413 - participants
414 - .map(participant =>
415 - optionalString(participant.label ?? participant.email ?? participant.phoneNumber)
416 - )
417 - .filter((value): value is string => Boolean(value))
418 - );
419 - return {
420 - ...compactRecord(thread, [
421 - 'id',
422 - 'title',
423 - 'type',
424 - 'timestamp',
425 - 'folderName',
426 - 'unreadCount',
427 - 'isUnread',
428 - 'isReadOnly',
429 - 'isPinned',
430 - 'isMarkedUnread',
431 - 'isLowPriority',
432 - 'lastReadMessageSortKey',
433 - ]),
434 - participantLabels,
435 - participants,
436 - ...(lastMessage ? { lastMessage } : {}),
437 - };
438 -};
439 -
440 -const pageInfoFor = (result: unknown) => {
441 - const record = isRecord(result) ? result : {};
442 - const oldestCursor = optionalString(record.oldestCursor);
443 - return {
444 - hasMore: record.hasMore === true,
445 - oldestCursor,
446 - nextBefore: oldestCursor,
447 - nextSteps: oldestCursor
448 - ? `Fetch older threads with { "before": "${oldestCursor}" }.`
449 - : 'No older cursor was returned.',
450 - };
451 -};
452 -
453 -const compactThreadsResult = async (
454 - rawResult: LocalExecutionResult,
455 - options: {
456 - readonly compact: boolean;
457 - readonly includeRaw: boolean;
458 - readonly resolveContactNames: boolean;
459 - }
460 -): Promise<LocalExecutionResult> => {
461 - if (!options.compact || !isRecord(rawResult.result)) return rawResult;
462 - const threads = extractPageItems(rawResult.result);
463 - const labels = await labelsForThreads(threads, options.resolveContactNames);
464 - const compactResult = {
465 - items: threads.map(thread => compactThread(thread, labels)),
466 - pageInfo: pageInfoFor(rawResult.result),
467 - contactResolution: {
468 - enabled: options.resolveContactNames,
469 - resolvedLabels: Object.keys(labels).length,
470 - },
471 - ...(options.includeRaw ? { raw: rawResult.result } : {}),
472 - };
473 - return {
474 - ...rawResult,
475 - result: compactResult,
476 - resultText: undefined,
477 - stdout: options.includeRaw ? rawResult.stdout : '',
478 - };
479 -};
480 -
481 -const delay = (ms: number): Promise<void> => new Promise(resolve => setTimeout(resolve, ms));
482 -
483 -const fetchMessages = async (
484 - threadId: string,
485 - input: Record<string, unknown>,
486 - context: LocalExecutionContext
487 -): Promise<LocalExecutionResult> => runImessageCli('messages', [threadId], input, context);
488 -
489 -const pollForSentMessage = async (params: {
490 - readonly threadId: string;
491 - readonly text: string;
492 - readonly input: Record<string, unknown>;
493 - readonly context: LocalExecutionContext;
494 - readonly timeoutMs: number;
495 - readonly excludeMessageIds?: ReadonlySet<string>;
496 -}): Promise<{
497 - readonly message?: Record<string, unknown>;
498 - readonly messagesResult?: LocalExecutionResult;
499 - readonly attempts: number;
500 -}> => {
501 - const deadline = Date.now() + params.timeoutMs;
502 - let attempts = 0;
503 - let lastResult: LocalExecutionResult | undefined;
504 -
505 - do {
506 - attempts += 1;
507 - lastResult = await fetchMessages(params.threadId, params.input, params.context);
508 - const messages = extractPageItems(lastResult.result);
509 - const message = messages.find(candidate => {
510 - const candidateId = messageIdOf(candidate);
511 - return (
512 - messageMatchesSentText(candidate, params.text) &&
513 - (!candidateId || !params.excludeMessageIds?.has(candidateId))
514 - );
515 - });
516 - if (message) return { message, messagesResult: lastResult, attempts };
517 - if (Date.now() < deadline) await delay(SEND_VERIFY_INTERVAL_MS);
518 - } while (Date.now() < deadline);
519 -
520 - return { messagesResult: lastResult, attempts };
521 -};
522 -
523 -const enhanceSendResult = (params: {
524 - readonly commandResult: LocalExecutionResult;
525 - readonly threadId?: string;
526 - readonly sentText: string;
527 - readonly sentMessage?: Record<string, unknown>;
528 - readonly messagesResult?: LocalExecutionResult;
529 - readonly attempts: number;
530 - readonly verify: boolean;
531 -}): LocalExecutionResult => {
532 - const sentMessageId = messageIdOf(params.sentMessage);
533 - const sendVerification = {
534 - commandSucceeded: params.commandResult.ok === true,
535 - verified: Boolean(params.sentMessage),
536 - status: params.sentMessage
537 - ? 'observed_sent_message'
538 - : params.verify
539 - ? 'command_succeeded_but_sent_message_not_observed_yet'
540 - : 'not_requested',
541 - attempts: params.attempts,
542 - threadId: params.threadId,
543 - sentMessageId,
544 - };
545 -
546 - let enhancedResult = params.commandResult.result;
547 - if (isRecord(enhancedResult) && params.sentMessage) {
548 - const messagesPage = isRecord(params.messagesResult?.result)
549 - ? params.messagesResult?.result
550 - : { items: [params.sentMessage], hasMore: false };
551 - enhancedResult = {
552 - ...enhancedResult,
553 - messages: messagesPage,
554 - sentMessage: params.sentMessage,
555 - sentMessageId,
556 - sendVerification,
557 - };
558 - } else if (isRecord(enhancedResult)) {
559 - enhancedResult = {
560 - ...enhancedResult,
561 - sentMessage: params.sentMessage ?? null,
562 - sentMessageId,
563 - sendVerification,
564 - };
565 - } else {
566 - enhancedResult = {
567 - originalResult: enhancedResult,
568 - sentMessage: params.sentMessage ?? null,
569 - sentMessageId,
570 - sendVerification,
571 - };
572 - }
573 -
574 - return {
575 - ...params.commandResult,
576 - result: enhancedResult,
577 - sentMessage: params.sentMessage ?? null,
578 - sentMessageId,
579 - sendVerification,
580 - resultText: JSON.stringify(enhancedResult, null, 2),
581 - };
582 -};
583 -
584 -const threadMatches = (params: {
585 - readonly thread: Record<string, unknown>;
586 - readonly query?: string;
587 - readonly recipientIdentifiers: ReadonlySet<string>;
588 - readonly contactIdentifiers: ReadonlySet<string>;
589 - readonly labels: Record<string, string>;
590 -}): boolean => {
591 - const identifiers = participantIdentifiers(params.thread);
592 - const normalizedIdentifiers = identifiers.map(normalizeIdentifier).filter(Boolean);
593 - const labels = normalizedIdentifiers.map(identifier => params.labels[identifier]).filter(Boolean);
594 - const query = params.query?.trim().toLowerCase();
595 -
596 - if (params.recipientIdentifiers.size > 0) {
597 - const normalizedSet = new Set(normalizedIdentifiers);
598 - const hasAllRecipients = [...params.recipientIdentifiers].every(identifier =>
599 - normalizedSet.has(identifier)
600 - );
601 - if (hasAllRecipients) return true;
602 - }
603 -
604 - if (params.contactIdentifiers.size > 0) {
605 - const normalizedSet = new Set(normalizedIdentifiers);
606 - if ([...params.contactIdentifiers].some(identifier => normalizedSet.has(identifier)))
607 - return true;
608 - }
609 -
610 - if (!query) return false;
611 - const searchable = [
612 - optionalString(params.thread.title),
613 - optionalString(params.thread.id),
614 - ...identifiers,
615 - ...labels,
616 - ]
617 - .filter((value): value is string => Boolean(value))
618 - .join(' ')
619 - .toLowerCase();
620 - return searchable.includes(query);
621 -};
622 -
623 -const scanThreads = async (params: {
624 - readonly input: Record<string, unknown>;
625 - readonly context: LocalExecutionContext;
626 - readonly query?: string;
627 - readonly recipients?: ReadonlyArray<string>;
628 - readonly maxPages?: number;
629 - readonly resolveContactNames?: boolean;
630 -}): Promise<{
631 - readonly matches: ReadonlyArray<Record<string, unknown>>;
632 - readonly pagesScanned: number;
633 - readonly nextBefore?: string;
634 - readonly hasMore: boolean;
635 - readonly contactLookup?: ContactLookupResult;
636 - readonly labels: Record<string, string>;
637 -}> => {
638 - const maxPages = Math.min(
639 - Math.max(1, Number(params.maxPages ?? THREAD_SCAN_DEFAULT_MAX_PAGES)),
640 - THREAD_SCAN_MAX_PAGES
641 - );
642 - const recipients = params.recipients ?? [];
643 - const recipientIdentifiers = new Set(recipients.map(normalizeIdentifier).filter(Boolean));
644 - const contactLookup =
645 - params.resolveContactNames && params.query
646 - ? await lookupContacts('query', { query: params.query })
647 - : undefined;
648 - const contactIdentifiers = new Set(
649 - contactLookup ? contactIdentifiersFromMatches(contactLookup) : []
650 - );
651 -
652 - let before: string | undefined = optionalString(params.input.before);
653 - let hasMore = true;
654 - let pagesScanned = 0;
655 - let nextBefore: string | undefined;
656 - const matches: Record<string, unknown>[] = [];
657 - const labelTargets: Record<string, unknown>[] = [];
658 -
659 - while (pagesScanned < maxPages && hasMore) {
660 - pagesScanned += 1;
661 - const pageInput = { ...params.input, ...(before ? { before } : {}) };
662 - const page = await runImessageCli(
663 - 'threads',
664 - withCursorArgs(pageInput, []),
665 - pageInput,
666 - params.context
667 - );
668 - const result = isRecord(page.result) ? page.result : {};
669 - const threads = extractPageItems(result);
670 - labelTargets.push(...threads);
671 - const labels = await labelsForThreads(threads, params.resolveContactNames ?? true);
672 - matches.push(
673 - ...threads.filter(thread =>
674 - threadMatches({
675 - thread,
676 - query: params.query,
677 - recipientIdentifiers,
678 - contactIdentifiers,
679 - labels,
680 - })
681 - )
682 - );
683 - hasMore = result.hasMore === true;
684 - nextBefore = optionalString(result.oldestCursor);
685 - before = nextBefore;
686 - if (!before) break;
687 - }
688 -
689 - const labels = await labelsForThreads(labelTargets, params.resolveContactNames ?? true);
690 - return { matches, pagesScanned, nextBefore, hasMore, contactLookup, labels };
691 -};
692 -
693 -const commandTool = <TInput extends z.ZodTypeAny>(definition: {
694 - readonly slug: string;
695 - readonly name: string;
696 - readonly description: string;
697 - readonly inputParams: TInput;
698 - readonly command: string;
699 - readonly args: (input: z.infer<TInput>) => ReadonlyArray<string>;
700 -}): LocalToolDeclaration<TInput> => ({
701 - slug: definition.slug,
702 - name: definition.name,
703 - description: definition.description,
704 - platforms: ['darwin-arm64'],
705 - inputParams: definition.inputParams,
706 - outputParams: cliOutput,
707 - execution: {
708 - kind: 'native',
709 - execute: (input, context) =>
710 - runImessageCli(definition.command, definition.args(input as z.infer<TInput>), input, context),
711 - },
712 -});
713 -
714 -const nativeTool = <TInput extends z.ZodTypeAny>(definition: {
715 - readonly slug: string;
716 - readonly name: string;
717 - readonly description: string;
718 - readonly inputParams: TInput;
719 - readonly execute: (
720 - input: z.infer<TInput>,
721 - context: LocalExecutionContext
722 - ) => Promise<LocalExecutionResult>;
723 -}): LocalToolDeclaration<TInput> => ({
724 - slug: definition.slug,
725 - name: definition.name,
726 - description: definition.description,
727 - platforms: ['darwin-arm64'],
728 - inputParams: definition.inputParams,
729 - outputParams: cliOutput,
730 - execution: {
731 - kind: 'native',
732 - execute: (input, context) => definition.execute(input as z.infer<TInput>, context),
733 - },
734 -});
735 -
736 -const threadId = z
737 - .string()
738 - .min(1)
739 - .describe('platform-imessage chat/thread ID, e.g. any;-;user@example.com.');
740 -const messageId = z.string().min(1).describe('platform-imessage message ID.');
741 -const text = z.string().min(1).describe('Message text.');
742 -const filePath = z.string().min(1).describe('Local file path to attach.');
743 -
744 -const listThreadsInput = baseInput.merge(cursorInput).extend({
745 - compact: z
746 - .boolean()
747 - .default(true)
748 - .describe(
749 - 'Return a compact thread shape with id/title/type/participant labels/lastMessage/pageInfo. Set false to return the raw upstream CLI response.'
750 - ),
751 - includeRaw: z
752 - .boolean()
753 - .default(false)
754 - .describe('When compact=true, include the raw upstream thread page under result.raw.'),
755 - resolveContactNames: z
756 - .boolean()
757 - .default(true)
758 - .describe('Best-effort macOS Contacts lookup for participant labels in compact output.'),
759 -});
760 -
761 -const findThreadInput = baseInput.extend({
762 - query: z
763 - .string()
764 - .min(1)
765 - .optional()
766 - .describe('Contact name, phone/email, thread title, or participant identifier to search for.'),
767 - recipients: z
768 - .array(z.string().min(1))
769 - .optional()
770 - .describe('Phone numbers or emails that must be present in the thread participants.'),
771 - maxPages: z
772 - .number()
773 - .int()
774 - .positive()
775 - .max(THREAD_SCAN_MAX_PAGES)
776 - .default(THREAD_SCAN_DEFAULT_MAX_PAGES)
777 - .describe('Maximum 25-thread pages to scan.'),
778 - compact: z.boolean().default(true).describe('Return compact thread matches.'),
779 - resolveContactNames: z
780 - .boolean()
781 - .default(true)
782 - .describe(
783 - 'Best-effort macOS Contacts lookup so names like “Mustafa” can resolve to phone/email participants.'
784 - ),
785 -});
786 -
787 -const sendVerificationInput = {
788 - verifySent: z
789 - .boolean()
790 - .default(true)
791 - .describe(
792 - 'After the send command succeeds, poll the local Messages DB for the newly sent message.'
793 - ),
794 - verificationTimeoutMs: z
795 - .number()
796 - .int()
797 - .min(0)
798 - .max(30_000)
799 - .default(SEND_VERIFY_TIMEOUT_MS)
800 - .describe(
801 - 'How long to poll for the sent message before returning command_succeeded_but_not_observed.'
802 - ),
803 -};
804 -
805 -const reactionInput = primaryInstanceInput.extend({
806 - threadId,
807 - messageId,
808 - reaction: z
809 - .string()
810 - .min(1)
811 - .describe(
812 - 'Reaction key or emoji. Standard keys: heart, like, dislike, laugh, emphasize, question.'
813 - ),
814 - prepareTranscript: z
815 - .boolean()
816 - .default(true)
817 - .describe('Run select-thread before reacting so the transcript is visible for UI automation.'),
818 - prepareTimeoutMs: z
819 - .number()
820 - .int()
821 - .positive()
822 - .max(30_000)
823 - .default(REACTION_PREPARE_TIMEOUT_MS)
824 - .describe('Timeout for select-thread transcript preparation.'),
825 - reactionTimeoutMs: z
826 - .number()
827 - .int()
828 - .positive()
829 - .max(60_000)
830 - .default(REACTION_TIMEOUT_MS)
831 - .describe('Timeout for the reaction command itself.'),
832 -});
833 -
834 -const sendMessageInput = baseInput.extend({ threadId, text, ...sendVerificationInput });
835 -
836 -const createThreadAndSendInput = baseInput.extend({
837 - recipients: z.array(z.string().min(1)).min(1).describe('Recipient phone numbers or emails.'),
838 - message: text,
839 - ...sendVerificationInput,
840 -});
841 -
842 -export const beeperImessageToolkit: LocalToolkitDeclaration = {
843 - slug: 'BEEPER_IMESSAGE',
844 - name: 'Beeper iMessage (local)',
845 - description:
846 - 'Local macOS iMessage tools backed by Beeper platform-imessage imessage-cli. Reads ~/Library/Messages and automates Messages.app for send/reaction/chat mutations.',
847 - platforms: ['darwin-arm64'],
848 - source: {
849 - type: 'cli',
850 - repository: 'https://github.com/ComposioHQ/platform-imessage',
851 - command: 'imessage-cli',
852 - },
853 - bundledBinaries: [
854 - {
855 - id: IMESSAGE_CLI_BINARY_ID,
856 - description: `Beeper platform-imessage imessage-cli ${IMESSAGE_CLI_VERSION}.`,
857 - targets: [
858 - {
859 - platforms: ['darwin-arm64'],
860 - path: 'beeper-imessage/darwin-arm64/imessage-cli',
861 - },
862 - ],
863 - },
864 - ],
865 - setup: {
866 - install:
867 - 'The CLI ships a bundled imessage-cli binary built from the ts/packages/cli-local-tools/vendor/platform-imessage submodule. Alternatively install/build imessage-cli and set a command override in ~/composio/local_tools.json.',
868 - commandOverrides: [
869 - 'composio local-tools configure BEEPER_IMESSAGE --command /path/to/imessage-cli',
870 - ],
871 - notes: [
872 - 'Requires macOS with Messages.app configured for iMessage.',
873 - 'Read-only tools require Messages Data access. Mutating tools require Messages Data and Accessibility; some setup flows may also request Contacts or Automation.',
874 - 'Run LOCAL_BEEPER_IMESSAGE_AUTHORIZE (or imessage-cli authorize) to inspect/request permissions. A future local-tool auth abstraction should route this through composio link BEEPER_IMESSAGE.',
875 - 'Most read/send tools work with the secondary Messages instance. Reaction tools default to the primary instance and prepare the transcript because upstream UI automation requires a visible reply transcript.',
876 - ],
877 - },
878 - tools: [
879 - commandTool({
880 - slug: 'VERSION',
881 - name: 'Get imessage-cli version',
882 - description:
883 - 'Print the bundled Beeper platform-imessage CLI version without touching Messages.app.',
884 - inputParams: baseInput,
885 - command: 'version',
886 - args: () => [],
887 - }),
888 - commandTool({
889 - slug: 'AUTHORIZE',
890 - name: 'Inspect or request iMessage local permissions',
891 - description:
892 - 'Run imessage-cli authorize for Accessibility, Contacts, Messages Data, and Automation permissions. This may open macOS prompts or System Settings. This is the local equivalent of linking/authorizing the iMessage toolkit.',
893 - inputParams: baseInput.extend({
894 - target: z
895 - .enum(['all', 'accessibility', 'contacts', 'messages-data', 'automation'])
896 - .default('all')
897 - .describe('Permission target to inspect/request.'),
898 - }),
899 - command: 'authorize',
900 - args: input => [input.target],
901 - }),
902 - commandTool({
903 - slug: 'CURRENT_USER',
904 - name: 'Get current iMessage user',
905 - description:
906 - 'Return the iMessage identity known to the local platform-imessage backend. Requires Messages Data access.',
907 - inputParams: baseInput,
908 - command: 'current-user',
909 - args: () => [],
910 - }),
911 - nativeTool({
912 - slug: 'LIST_THREADS',
913 - name: 'List iMessage threads',
914 - description:
915 - 'List normal-inbox iMessage chats from the local Messages database. Defaults to compact output with pageInfo.nextBefore for pagination; set compact=false for raw upstream output.',
916 - inputParams: listThreadsInput,
917 - execute: async (input, context) => {
918 - const raw = await runImessageCli('threads', withCursorArgs(input, []), input, context);
919 - return compactThreadsResult(raw, {
920 - compact: input.compact,
921 - includeRaw: input.includeRaw,
922 - resolveContactNames: input.resolveContactNames,
923 - });
924 - },
925 - }),
926 - nativeTool({
927 - slug: 'FIND_THREAD',
928 - name: 'Find iMessage thread',
929 - description:
930 - 'Find threads by contact name, phone/email, thread title, or participants without doing a manual LIST_THREADS pagination/filter dance.',
931 - inputParams: findThreadInput,
932 - execute: async (input, context) => {
933 - if (!input.query && (!input.recipients || input.recipients.length === 0)) {
934 - throw new Error('Provide query or recipients to find an iMessage thread.');
935 - }
936 - const scan = await scanThreads({
937 - input,
938 - context,
939 - query: input.query,
940 - recipients: input.recipients,
941 - maxPages: input.maxPages,
942 - resolveContactNames: input.resolveContactNames,
943 - });
944 - const result = {
945 - items: input.compact
946 - ? scan.matches.map(thread => compactThread(thread, scan.labels))
947 - : scan.matches,
948 - pageInfo: {
949 - pagesScanned: scan.pagesScanned,
950 - hasMore: scan.hasMore,
951 - nextBefore: scan.nextBefore,
952 - },
953 - contactResolution: {
954 - enabled: input.resolveContactNames,
955 - matchedContacts: scan.contactLookup?.matches.length ?? 0,
956 - error: scan.contactLookup?.error,
957 - },
958 - };
959 - return {
960 - ok: true,
961 - commandName: 'find-thread',
962 - result,
963 - resultText: JSON.stringify(result, null, 2),
964 - stdout: '',
965 - stderr: '',
966 - };
967 - },
968 - }),
969 - commandTool({
970 - slug: 'GET_THREAD',
971 - name: 'Get iMessage thread',
972 - description: 'Fetch a single iMessage chat/thread by platform-imessage thread ID.',
973 - inputParams: baseInput.extend({ threadId }),
974 - command: 'thread',
975 - args: input => [input.threadId],
976 - }),
977 - commandTool({
978 - slug: 'LIST_MESSAGES',
979 - name: 'List iMessage messages',
980 - description:
981 - 'List messages in a chat from the local Messages database, optionally using cursors.',
982 - inputParams: baseInput.merge(cursorInput).extend({ threadId }),
983 - command: 'messages',
984 - args: input => withCursorArgs(input, [input.threadId]),
985 - }),
986 - commandTool({
987 - slug: 'GET_MESSAGE',
988 - name: 'Get iMessage message',
989 - description: 'Fetch a single message by chat/thread ID and message ID.',
990 - inputParams: baseInput.extend({ threadId, messageId }),
991 - command: 'message',
992 - args: input => [input.threadId, input.messageId],
993 - }),
994 - nativeTool({
995 - slug: 'SEARCH_MESSAGES',
996 - name: 'Search local iMessage messages',
997 - description:
998 - 'Search local iMessage messages by text and, by default, also search thread participants/contact names so queries like “Nikos” can find matching chats.',
999 - inputParams: baseInput.extend({
1000 - query: z
1001 - .string()
1002 - .min(1)
1003 - .describe('Text, participant name, phone/email, or thread title to search for.'),
1004 - includeThreadMatches: z
1005 - .boolean()
1006 - .default(true)
1007 - .describe(
1008 - 'Also scan threads/participants/contact names in addition to upstream message text search.'
1009 - ),
1010 - maxThreadPages: z
1011 - .number()
1012 - .int()
1013 - .positive()
1014 - .max(THREAD_SCAN_MAX_PAGES)
1015 - .default(THREAD_SCAN_DEFAULT_MAX_PAGES)
1016 - .describe('Maximum 25-thread pages to scan when includeThreadMatches=true.'),
1017 - compactThreads: z
1018 - .boolean()
1019 - .default(true)
1020 - .describe('Return compact matching thread records.'),
1021 - resolveContactNames: z
1022 - .boolean()
1023 - .default(true)
1024 - .describe('Best-effort macOS Contacts lookup for participant/name matching.'),
1025 - }),
1026 - execute: async (input, context) => {
1027 - const searchResult = await runImessageCli('search', [input.query], input, context);
1028 - const threadScan = input.includeThreadMatches
1029 - ? await scanThreads({
1030 - input,
1031 - context,
1032 - query: input.query,
1033 - maxPages: input.maxThreadPages,
1034 - resolveContactNames: input.resolveContactNames,
1035 - })
1036 - : undefined;
1037 - const result = {
1038 - messageSearch: searchResult.result,
1039 - matchingThreads: threadScan
1040 - ? input.compactThreads
1041 - ? threadScan.matches.map(thread => compactThread(thread, threadScan.labels))
1042 - : threadScan.matches
1043 - : [],
1044 - threadSearch: threadScan
1045 - ? {
1046 - pagesScanned: threadScan.pagesScanned,
1047 - hasMore: threadScan.hasMore,
1048 - nextBefore: threadScan.nextBefore,
1049 - contactResolution: {
1050 - enabled: input.resolveContactNames,
1051 - matchedContacts: threadScan.contactLookup?.matches.length ?? 0,
1052 - error: threadScan.contactLookup?.error,
1053 - },
1054 - }
1055 - : { enabled: false },
1056 - };
1057 - return {
1058 - ...searchResult,
1059 - result,
1060 - resultText: JSON.stringify(result, null, 2),
1061 - };
1062 - },
1063 - }),
1064 - nativeTool({
1065 - slug: 'CREATE_THREAD_AND_SEND',
1066 - name: 'Create iMessage thread and send message',
1067 - description:
1068 - 'Create or resolve a chat for one or more recipients and send the initial message. After the send command succeeds, this verifies the newly sent message and returns sentMessage/sentMessageId to avoid stale existing-thread ambiguity.',
1069 - inputParams: createThreadAndSendInput,
1070 - execute: async (input, context) => {
1071 - const createResult = await runImessageCli(
1072 - 'create-thread',
1073 - [...stringArray(input.recipients), '--message', input.message],
1074 - input,
1075 - context
1076 - );
1077 - const threadId = extractThreadId(createResult.result);
1078 - const verification =
1079 - input.verifySent && threadId
1080 - ? await pollForSentMessage({
1081 - threadId,
1082 - text: input.message,
1083 - input,
1084 - context,
1085 - timeoutMs: input.verificationTimeoutMs,
1086 - })
1087 - : { attempts: 0 };
1088 - return enhanceSendResult({
1089 - commandResult: createResult,
1090 - threadId,
1091 - sentText: input.message,
1092 - sentMessage: verification.message,
1093 - messagesResult: verification.messagesResult,
1094 - attempts: verification.attempts,
1095 - verify: input.verifySent,
1096 - });
1097 - },
1098 - }),
1099 - nativeTool({
1100 - slug: 'SEND_MESSAGE',
1101 - name: 'Send iMessage text',
1102 - description:
1103 - 'Send a text message to an existing chat/thread. Returns sendVerification plus sentMessage/sentMessageId when the local DB observes the new message, so callers should not retry solely because a thread preview is stale.',
1104 - inputParams: sendMessageInput,
1105 - execute: async (input, context) => {
1106 - const beforeMessages = input.verifySent
1107 - ? await fetchMessages(input.threadId, input, context)
1108 - : undefined;
1109 - const excludeMessageIds = new Set(
1110 - extractPageItems(beforeMessages?.result)
1111 - .map(messageIdOf)
1112 - .filter((value): value is string => Boolean(value))
1113 - );
1114 - const sendResult = await runImessageCli(
1115 - 'send',
1116 - [input.threadId, input.text],
1117 - input,
1118 - context
1119 - );
1120 - const verification = input.verifySent
1121 - ? await pollForSentMessage({
1122 - threadId: input.threadId,
1123 - text: input.text,
1124 - input,
1125 - context,
1126 - timeoutMs: input.verificationTimeoutMs,
1127 - excludeMessageIds,
1128 - })
1129 - : { attempts: 0 };
1130 - return enhanceSendResult({
1131 - commandResult: sendResult,
1132 - threadId: input.threadId,
1133 - sentText: input.text,
1134 - sentMessage: verification.message,
1135 - messagesResult: verification.messagesResult,
1136 - attempts: verification.attempts,
1137 - verify: input.verifySent,
1138 - });
1139 - },
1140 - }),
1141 - commandTool({
1142 - slug: 'REPLY_TO_MESSAGE',
1143 - name: 'Reply to iMessage message',
1144 - description: 'Reply to a specific iMessage with text. Mutates real Messages state.',
1145 - inputParams: baseInput.extend({ threadId, messageId, text }),
1146 - command: 'reply',
1147 - args: input => [input.threadId, input.messageId, input.text],
1148 - }),
1149 - commandTool({
1150 - slug: 'SEND_FILE',
1151 - name: 'Send iMessage file attachment',
1152 - description:
1153 - 'Send a local file attachment to an existing chat/thread. Mutates real Messages state.',
1154 - inputParams: baseInput.extend({ threadId, filePath }),
1155 - command: 'send-file',
1156 - args: input => [input.threadId, absolutePath(input.filePath)],
1157 - }),
1158 - commandTool({
1159 - slug: 'REPLY_WITH_FILE',
1160 - name: 'Reply to iMessage with file attachment',
1161 - description:
1162 - 'Reply to a specific message with a local file attachment. Mutates real Messages state.',
1163 - inputParams: baseInput.extend({ threadId, messageId, filePath }),
1164 - command: 'reply-file',
1165 - args: input => [input.threadId, input.messageId, absolutePath(input.filePath)],
1166 - }),
1167 - commandTool({
1168 - slug: 'EDIT_MESSAGE',
1169 - name: 'Edit sent iMessage',
1170 - description:
1171 - 'Edit a previously sent iMessage. Supported by upstream on macOS Ventura or later.',
1172 - inputParams: baseInput.extend({ threadId, messageId, text }),
1173 - command: 'edit',
1174 - args: input => [input.threadId, input.messageId, input.text],
1175 - }),
1176 - commandTool({
1177 - slug: 'UNDO_SEND',
1178 - name: 'Undo sent iMessage',
1179 - description:
1180 - 'Undo send for a previously sent iMessage. Upstream supports this on macOS Ventura or later within the Messages time limit.',
1181 - inputParams: baseInput.extend({ threadId, messageId }),
1182 - command: 'undo-send',
1183 - args: input => [input.threadId, input.messageId],
1184 - }),
1185 - nativeTool({
1186 - slug: 'REACT_TO_MESSAGE',
1187 - name: 'React to iMessage',
1188 - description:
1189 - 'Add a standard reaction to a message using a supported key or emoji. Defaults to the primary Messages.app instance and runs select-thread first because upstream reaction automation needs a visible transcript.',
1190 - inputParams: reactionInput,
1191 - execute: async (input, context) => {
1192 - const effectiveInput = { ...input, useSecondaryInstance: input.useSecondaryInstance };
1193 - if (input.prepareTranscript) {
1194 - await runImessageCli('select-thread', [input.threadId], effectiveInput, context, {
1195 - timeoutMs: input.prepareTimeoutMs,
1196 - });
1197 - }
1198 - return runImessageCli(
1199 - 'react',
1200 - [input.threadId, input.messageId, input.reaction],
1201 - effectiveInput,
1202 - context,
1203 - { timeoutMs: input.reactionTimeoutMs }
1204 - );
1205 - },
1206 - }),
1207 - nativeTool({
1208 - slug: 'UNREACT_FROM_MESSAGE',
1209 - name: 'Remove iMessage reaction',
1210 - description:
1211 - 'Remove a standard reaction from a message. Defaults to the primary Messages.app instance and runs select-thread first because upstream reaction automation needs a visible transcript.',
1212 - inputParams: reactionInput,
1213 - execute: async (input, context) => {
1214 - const effectiveInput = { ...input, useSecondaryInstance: input.useSecondaryInstance };
1215 - if (input.prepareTranscript) {
1216 - await runImessageCli('select-thread', [input.threadId], effectiveInput, context, {
1217 - timeoutMs: input.prepareTimeoutMs,
1218 - });
1219 - }
1220 - return runImessageCli(
1221 - 'unreact',
1222 - [input.threadId, input.messageId, input.reaction],
1223 - effectiveInput,
1224 - context,
1225 - { timeoutMs: input.reactionTimeoutMs }
1226 - );
1227 - },
1228 - }),
1229 - commandTool({
1230 - slug: 'MARK_READ',
1231 - name: 'Mark iMessage thread read',
1232 - description:
1233 - 'Mark a chat/thread as read by sending a read receipt. Mutates real Messages state.',
1234 - inputParams: baseInput.extend({ threadId }),
1235 - command: 'mark-read',
1236 - args: input => [input.threadId],
1237 - }),
1238 - commandTool({
1239 - slug: 'MARK_UNREAD',
1240 - name: 'Mark iMessage thread unread',
1241 - description: 'Mark a chat/thread as unread. Mutates real Messages state.',
1242 - inputParams: baseInput.extend({ threadId }),
1243 - command: 'mark-unread',
1244 - args: input => [input.threadId],
1245 - }),
1246 - commandTool({
1247 - slug: 'MUTE_THREAD',
1248 - name: 'Mute iMessage thread',
1249 - description: 'Mute a chat/thread indefinitely. Mutates real Messages state.',
1250 - inputParams: baseInput.extend({ threadId }),
1251 - command: 'mute',
1252 - args: input => [input.threadId],
1253 - }),
1254 - commandTool({
1255 - slug: 'UNMUTE_THREAD',
1256 - name: 'Unmute iMessage thread',
1257 - description: 'Unmute a chat/thread. Mutates real Messages state.',
1258 - inputParams: baseInput.extend({ threadId }),
1259 - command: 'unmute',
1260 - args: input => [input.threadId],
1261 - }),
1262 - commandTool({
1263 - slug: 'SEND_TYPING_STATUS',
1264 - name: 'Send iMessage typing status',
1265 - description: 'Send typing on/off status for a chat/thread. Mutates real Messages state.',
1266 - inputParams: baseInput.extend({
1267 - threadId,
1268 - status: z.enum(['on', 'off']).describe('Typing status to send.'),
1269 - }),
1270 - command: 'typing',
1271 - args: input => [input.threadId, input.status],
1272 - }),
1273 - commandTool({
1274 - slug: 'NOTIFY_ANYWAY',
1275 - name: 'Notify anyway for iMessage thread',
1276 - description:
1277 - 'Trigger the Messages "notify anyway" action for a chat/thread. Mutates real Messages state.',
1278 - inputParams: baseInput.extend({ threadId }),
1279 - command: 'notify-anyway',
1280 - args: input => [input.threadId],
1281 - }),
1282 - commandTool({
1283 - slug: 'DELETE_THREAD',
1284 - name: 'Delete iMessage thread',
1285 - description:
1286 - 'Delete a chat/thread from Messages. Requires confirm=true because this mutates real Messages state.',
1287 - inputParams: baseInput.extend({
1288 - threadId,
1289 - confirm: z.literal(true).describe('Must be true to delete the thread.'),
1290 - }),
1291 - command: 'delete-thread',
1292 - args: input => [input.threadId],
1293 - }),
1294 - ],
1295 -};
ts/packages/cli-local-tools/src/toolkits/chrome-devtools.test.ts deleted
-65
@@ -1,65 +0,0 @@
1 -import { describe, expect, it } from 'vitest';
2 -import { executeLocalToolBySlug, getLocalToolInputDefinition } from '../registry';
3 -import { chromeDevtoolsToolkit } from './chrome-devtools';
4 -
5 -describe('@composio/cli-local-tools Chrome DevTools toolkit', () => {
6 - it('exposes first-class schemas for documented Chrome DevTools tools', () => {
7 - expect(chromeDevtoolsToolkit.source?.type).toBe('mcp');
8 - expect(chromeDevtoolsToolkit.tools.map(tool => tool.slug)).toEqual(
9 - expect.arrayContaining([
10 - 'LIST_PAGES',
11 - 'NEW_PAGE',
12 - 'NAVIGATE_PAGE',
13 - 'TAKE_SNAPSHOT',
14 - 'EVALUATE_SCRIPT',
15 - 'CLICK',
16 - 'DRAG',
17 - 'HANDLE_DIALOG',
18 - 'LIST_NETWORK_REQUESTS',
19 - 'LIST_EXTENSIONS',
20 - ])
21 - );
22 -
23 - const newPageSchema = getLocalToolInputDefinition('LOCAL_CHROME_DEVTOOLS_NEW_PAGE');
24 - expect(newPageSchema?.schema.properties).toHaveProperty('url');
25 - expect(newPageSchema?.schema.required).toContain('url');
26 -
27 - const evaluateSchema = getLocalToolInputDefinition('LOCAL_CHROME_DEVTOOLS_EVALUATE_SCRIPT');
28 - expect(evaluateSchema?.schema.properties).toHaveProperty('function');
29 - expect(evaluateSchema?.schema.properties).toHaveProperty('args');
30 - });
31 -
32 - it.runIf(process.env.COMPOSIO_REAL_LOCAL_TOOLS_TESTS === '1')(
33 - 'validates against a real chrome-devtools-mcp daemon',
34 - async () => {
35 - try {
36 - const start = await executeLocalToolBySlug('LOCAL_CHROME_DEVTOOLS_START_DAEMON', {
37 - headless: true,
38 - usageStatistics: false,
39 - performanceCrux: false,
40 - });
41 - expect(start?.ok).toBe(true);
42 -
43 - const page = await executeLocalToolBySlug('LOCAL_CHROME_DEVTOOLS_NEW_PAGE', {
44 - url: 'data:text/html,<title>Composio Chrome Local Tools</title><h1>Hello from Chrome</h1>',
45 - });
46 - expect(page?.ok).toBe(true);
47 -
48 - const evaluated = await executeLocalToolBySlug('LOCAL_CHROME_DEVTOOLS_EVALUATE_SCRIPT', {
49 - function: '() => document.title',
50 - });
51 - expect(evaluated?.result).toEqual(
52 - expect.objectContaining({
53 - message: expect.stringContaining('Composio Chrome Local Tools'),
54 - })
55 - );
56 -
57 - const pages = await executeLocalToolBySlug('LOCAL_CHROME_DEVTOOLS_LIST_PAGES', {});
58 - expect(pages?.result).toEqual(expect.objectContaining({ pages: expect.any(Array) }));
59 - } finally {
60 - await executeLocalToolBySlug('LOCAL_CHROME_DEVTOOLS_STOP_DAEMON', {});
61 - }
62 - },
63 - 120_000
64 - );
65 -});
ts/packages/cli-local-tools/src/toolkits/chrome-devtools.ts deleted
-788
@@ -1,788 +0,0 @@
1 -import { z } from 'zod/v3';
2 -import { runLocalCommand } from '../runtime';
3 -import type {
4 - LocalCommandExecution,
5 - LocalExecutionContext,
6 - LocalExecutionResult,
7 - LocalToolkitDeclaration,
8 - LocalToolDeclaration,
9 -} from '../types';
10 -
11 -const CHROME_DEVTOOLS_MCP_VERSION = '1.4.0';
12 -const COMMAND_TIMEOUT_MS = 180_000;
13 -
14 -const cliOutput = z.object({
15 - ok: z.boolean(),
16 - commandName: z.string(),
17 - result: z.unknown().optional(),
18 - resultText: z.string().optional(),
19 - stdout: z.string(),
20 - stderr: z.string(),
21 -});
22 -
23 -const baseInput = z.object({
24 - debug: z.boolean().default(false).describe('Set DEBUG=* for the chrome-devtools command.'),
25 - sessionId: z
26 - .string()
27 - .optional()
28 - .describe('Optional upstream chrome-devtools CLI session id for isolated daemon state.'),
29 -});
30 -
31 -const pageId = z.number().int().nonnegative().describe('Page ID from LIST_PAGES.');
32 -const uid = z.string().min(1).describe('Element uid from TAKE_SNAPSHOT.');
33 -
34 -const npxArgs = [
35 - '-y',
36 - '--package',
37 - `chrome-devtools-mcp@${CHROME_DEVTOOLS_MCP_VERSION}`,
38 - 'chrome-devtools',
39 -];
40 -
41 -const addOption = (args: string[], name: string, value: unknown): string[] => {
42 - if (value === undefined || value === null || value === '') return args;
43 - args.push(`--${name}`, String(value));
44 - return args;
45 -};
46 -
47 -const addBooleanFlag = (args: string[], name: string, value: unknown): string[] => {
48 - if (value === true) args.push(`--${name}`);
49 - return args;
50 -};
51 -
52 -const addBooleanOption = (args: string[], name: string, value: unknown): string[] => {
53 - if (value === true) args.push(`--${name}`);
54 - if (value === false) args.push(`--no-${name}`);
55 - return args;
56 -};
57 -
58 -const addRepeated = (args: string[], name: string, values: unknown): string[] => {
59 - if (!Array.isArray(values)) return args;
60 - for (const value of values) {
61 - if (value === undefined || value === null || value === '') continue;
62 - args.push(`--${name}`, String(value));
63 - }
64 - return args;
65 -};
66 -
67 -const extractJson = (text: string): unknown | undefined => {
68 - const candidates = [text.indexOf('{'), text.indexOf('[')].filter(index => index >= 0);
69 - if (!candidates.length) return undefined;
70 -
71 - const start = Math.min(...candidates);
72 - let depth = 0;
73 - let inString = false;
74 - let escaped = false;
75 -
76 - for (let index = start; index < text.length; index += 1) {
77 - const char = text[index];
78 - if (inString) {
79 - if (escaped) {
80 - escaped = false;
81 - } else if (char === '\\') {
82 - escaped = true;
83 - } else if (char === '"') {
84 - inString = false;
85 - }
86 - continue;
87 - }
88 - if (char === '"') {
89 - inString = true;
90 - continue;
91 - }
92 - if (char === '{' || char === '[') {
93 - depth += 1;
94 - continue;
95 - }
96 - if (char === '}' || char === ']') {
97 - depth -= 1;
98 - if (depth === 0) {
99 - try {
100 - return JSON.parse(text.slice(start, index + 1)) as unknown;
101 - } catch {
102 - return undefined;
103 - }
104 - }
105 - }
106 - }
107 -
108 - return undefined;
109 -};
110 -
111 -const parseChromeDevtoolsOutput = (
112 - commandName: string,
113 - stdout: string,
114 - stderr: string,
115 - parseJson: boolean
116 -): LocalExecutionResult => {
117 - const trimmed = stdout.trim();
118 - const result = parseJson ? extractJson(trimmed) : undefined;
119 - return {
120 - ok: true,
121 - commandName,
122 - ...(result !== undefined ? { result } : {}),
123 - ...(result === undefined && trimmed ? { resultText: trimmed } : {}),
124 - stdout,
125 - stderr,
126 - };
127 -};
128 -
129 -const runChromeDevtools = async (
130 - commandName: string,
131 - commandArgs: ReadonlyArray<string>,
132 - input: Record<string, unknown>,
133 - context: LocalExecutionContext,
134 - options: { readonly json?: boolean } = { json: true }
135 -): Promise<LocalExecutionResult> => {
136 - const args = [...npxArgs];
137 - addOption(args, 'sessionId', input.sessionId);
138 - args.push(commandName, ...commandArgs);
139 - if (options.json !== false) args.push('--output-format=json');
140 - const execution: LocalCommandExecution = {
141 - kind: 'command',
142 - command: 'npx',
143 - args,
144 - env: {
145 - CHROME_DEVTOOLS_MCP_NO_UPDATE_CHECKS: '1',
146 - ...(input.usageStatistics === true ? {} : { CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS: '1' }),
147 - ...(input.debug === true ? { DEBUG: '*' } : {}),
148 - },
149 - timeoutMs: COMMAND_TIMEOUT_MS,
150 - };
151 - const result = await runLocalCommand(execution, input, context);
152 - return parseChromeDevtoolsOutput(
153 - commandName,
154 - String(result.stdout ?? ''),
155 - String(result.stderr ?? ''),
156 - options.json !== false
157 - );
158 -};
159 -
160 -const commandTool = <TInput extends z.ZodTypeAny>(definition: {
161 - readonly slug: string;
162 - readonly name: string;
163 - readonly description: string;
164 - readonly inputParams: TInput;
165 - readonly command: string;
166 - readonly args: (input: z.infer<TInput>) => ReadonlyArray<string>;
167 - readonly json?: boolean;
168 -}): LocalToolDeclaration<TInput> => ({
169 - slug: definition.slug,
170 - name: definition.name,
171 - description: definition.description,
172 - platforms: ['darwin-arm64', 'linux-arm64', 'linux-x64', 'win32-arm64', 'win32-x64'],
173 - inputParams: definition.inputParams,
174 - outputParams: cliOutput,
175 - execution: {
176 - kind: 'native',
177 - readiness: {
178 - command: 'npx',
179 - args: npxArgs,
180 - },
181 - execute: (input, context) =>
182 - runChromeDevtools(
183 - definition.command,
184 - definition.args(input as z.infer<TInput>),
185 - input,
186 - context,
187 - { json: definition.json }
188 - ),
189 - },
190 -});
191 -
192 -export const chromeDevtoolsToolkit: LocalToolkitDeclaration = {
193 - slug: 'CHROME_DEVTOOLS',
194 - name: 'Chrome DevTools (local)',
195 - description:
196 - 'Local Chrome automation and debugging tools backed by the official chrome-devtools-mcp package and its chrome-devtools CLI daemon.',
197 - platforms: ['darwin-arm64', 'linux-arm64', 'linux-x64', 'win32-arm64', 'win32-x64'],
198 - source: {
199 - type: 'mcp',
200 - package: `chrome-devtools-mcp@${CHROME_DEVTOOLS_MCP_VERSION}`,
201 - repository: 'https://github.com/ChromeDevTools/chrome-devtools-mcp',
202 - command: `npx -y --package chrome-devtools-mcp@${CHROME_DEVTOOLS_MCP_VERSION} chrome-devtools`,
203 - },
204 - setup: {
205 - install: `Requires Node.js/npm and a supported Chrome installation. Tools run via npx --package chrome-devtools-mcp@${CHROME_DEVTOOLS_MCP_VERSION} chrome-devtools.`,
206 - commandOverrides: [],
207 - notes: [
208 - 'The upstream chrome-devtools CLI automatically starts and reuses a background chrome-devtools-mcp daemon for stateful browser sessions.',
209 - 'Use START_DAEMON to configure headless/browserUrl/userDataDir before invoking page tools, or let the first tool auto-start the daemon with upstream defaults.',
210 - 'Use STOP_DAEMON when finished to close the background MCP/browser process.',
211 - 'Chrome DevTools MCP can inspect and modify browser contents; avoid using it on sensitive sessions.',
212 - ],
213 - },
214 - tools: [
215 - commandTool({
216 - slug: 'START_DAEMON',
217 - name: 'Start Chrome DevTools MCP daemon',
218 - description:
219 - 'Start or restart the background chrome-devtools-mcp daemon and browser with optional launch settings.',
220 - inputParams: baseInput.extend({
221 - browserUrl: z
222 - .string()
223 - .optional()
224 - .describe('Connect to an existing debuggable Chrome URL, e.g. http://127.0.0.1:9222.'),
225 - wsEndpoint: z
226 - .string()
227 - .optional()
228 - .describe('Connect to an existing Chrome DevTools WebSocket endpoint.'),
229 - headless: z.boolean().optional().describe('Run Chrome headless. Upstream default is true.'),
230 - executablePath: z.string().optional().describe('Custom Chrome executable path.'),
231 - userDataDir: z.string().optional().describe('Chrome user data directory.'),
232 - channel: z
233 - .enum(['canary', 'dev', 'beta', 'stable'])
234 - .optional()
235 - .describe('Chrome release channel.'),
236 - isolated: z.boolean().optional().describe('Use an isolated temporary user data dir.'),
237 - acceptInsecureCerts: z
238 - .boolean()
239 - .optional()
240 - .describe('Ignore self-signed/expired certificate errors.'),
241 - proxyServer: z.string().optional().describe('Chrome proxy server setting.'),
242 - performanceCrux: z
243 - .boolean()
244 - .optional()
245 - .describe('Allow CrUX field data lookups for performance tools.'),
246 - usageStatistics: z
247 - .boolean()
248 - .optional()
249 - .describe('Allow Google usage statistics for the MCP server.'),
250 - slim: z.boolean().optional().describe('Expose the upstream slim tool set.'),
251 - categoryExtensions: z
252 - .boolean()
253 - .optional()
254 - .describe('Enable or disable Chrome extension tools in the upstream daemon.'),
255 - }),
256 - command: 'start',
257 - json: false,
258 - args: input => {
259 - const args: string[] = [];
260 - addOption(args, 'browserUrl', input.browserUrl);
261 - addOption(args, 'wsEndpoint', input.wsEndpoint);
262 - addBooleanOption(args, 'headless', input.headless);
263 - addOption(args, 'executablePath', input.executablePath);
264 - addOption(args, 'userDataDir', input.userDataDir);
265 - addOption(args, 'channel', input.channel);
266 - addBooleanOption(args, 'isolated', input.isolated);
267 - addBooleanFlag(args, 'acceptInsecureCerts', input.acceptInsecureCerts);
268 - addOption(args, 'proxyServer', input.proxyServer);
269 - addBooleanOption(args, 'performanceCrux', input.performanceCrux);
270 - addBooleanOption(args, 'usageStatistics', input.usageStatistics);
271 - addBooleanFlag(args, 'slim', input.slim);
272 - addBooleanOption(args, 'categoryExtensions', input.categoryExtensions);
273 - return args;
274 - },
275 - }),
276 - commandTool({
277 - slug: 'STOP_DAEMON',
278 - name: 'Stop Chrome DevTools MCP daemon',
279 - description: 'Stop the background chrome-devtools-mcp daemon/browser if running.',
280 - inputParams: baseInput,
281 - command: 'stop',
282 - json: false,
283 - args: () => [],
284 - }),
285 - commandTool({
286 - slug: 'STATUS_DAEMON',
287 - name: 'Get Chrome DevTools MCP daemon status',
288 - description: 'Check whether the chrome-devtools-mcp daemon is running.',
289 - inputParams: baseInput,
290 - command: 'status',
291 - json: false,
292 - args: () => [],
293 - }),
294 - commandTool({
295 - slug: 'LIST_PAGES',
296 - name: 'List Chrome pages',
297 - description: 'Get pages open in the browser controlled by Chrome DevTools MCP.',
298 - inputParams: baseInput,
299 - command: 'list_pages',
300 - args: () => [],
301 - }),
302 - commandTool({
303 - slug: 'NEW_PAGE',
304 - name: 'Open new Chrome page',
305 - description: 'Open a new Chrome tab and load a URL.',
306 - inputParams: baseInput.extend({
307 - url: z.string().url().describe('URL to load in a new page.'),
308 - background: z.boolean().optional().describe('Open in background.'),
309 - isolatedContext: z.string().optional().describe('Named isolated browser context.'),
310 - timeout: z
311 - .number()
312 - .int()
313 - .nonnegative()
314 - .optional()
315 - .describe('Maximum wait time in milliseconds.'),
316 - }),
317 - command: 'new_page',
318 - args: input => {
319 - const args = [input.url];
320 - addBooleanFlag(args, 'background', input.background);
321 - addOption(args, 'isolatedContext', input.isolatedContext);
322 - addOption(args, 'timeout', input.timeout);
323 - return args;
324 - },
325 - }),
326 - commandTool({
327 - slug: 'NAVIGATE_PAGE',
328 - name: 'Navigate Chrome page',
329 - description: 'Navigate selected page by URL, back, forward, or reload.',
330 - inputParams: baseInput.extend({
331 - type: z.enum(['url', 'back', 'forward', 'reload']).optional().describe('Navigation type.'),
332 - url: z.string().optional().describe('Target URL for type=url.'),
333 - ignoreCache: z.boolean().optional().describe('Ignore cache on reload.'),
334 - handleBeforeUnload: z
335 - .enum(['accept', 'decline'])
336 - .optional()
337 - .describe('Handle beforeunload dialogs.'),
338 - initScript: z
339 - .string()
340 - .optional()
341 - .describe('Script to run before the next navigation document loads.'),
342 - timeout: z
343 - .number()
344 - .int()
345 - .nonnegative()
346 - .optional()
347 - .describe('Maximum wait time in milliseconds.'),
348 - }),
349 - command: 'navigate_page',
350 - args: input => {
351 - const args: string[] = [];
352 - addOption(args, 'type', input.type);
353 - addOption(args, 'url', input.url);
354 - addBooleanFlag(args, 'ignoreCache', input.ignoreCache);
355 - addOption(args, 'handleBeforeUnload', input.handleBeforeUnload);
356 - addOption(args, 'initScript', input.initScript);
357 - addOption(args, 'timeout', input.timeout);
358 - return args;
359 - },
360 - }),
361 - commandTool({
362 - slug: 'SELECT_PAGE',
363 - name: 'Select Chrome page',
364 - description: 'Select a page as context for future Chrome DevTools tool calls.',
365 - inputParams: baseInput.extend({ pageId, bringToFront: z.boolean().optional() }),
366 - command: 'select_page',
367 - args: input => {
368 - const args = [String(input.pageId)];
369 - addBooleanFlag(args, 'bringToFront', input.bringToFront);
370 - return args;
371 - },
372 - }),
373 - commandTool({
374 - slug: 'CLOSE_PAGE',
375 - name: 'Close Chrome page',
376 - description: 'Close a page by ID. The last open page cannot be closed.',
377 - inputParams: baseInput.extend({ pageId }),
378 - command: 'close_page',
379 - args: input => [String(input.pageId)],
380 - }),
381 - commandTool({
382 - slug: 'TAKE_SNAPSHOT',
383 - name: 'Take Chrome accessibility snapshot',
384 - description:
385 - 'Take a text snapshot of the selected page, including element uids for automation.',
386 - inputParams: baseInput.extend({
387 - filePath: z.string().optional().describe('Optional path to save the snapshot.'),
388 - verbose: z.boolean().optional().describe('Include all a11y tree details.'),
389 - }),
390 - command: 'take_snapshot',
391 - args: input => {
392 - const args: string[] = [];
393 - addOption(args, 'filePath', input.filePath);
394 - addBooleanFlag(args, 'verbose', input.verbose);
395 - return args;
396 - },
397 - }),
398 - commandTool({
399 - slug: 'TAKE_SCREENSHOT',
400 - name: 'Take Chrome screenshot',
401 - description: 'Take a screenshot of the selected page or element.',
402 - inputParams: baseInput.extend({
403 - filePath: z.string().optional(),
404 - format: z.enum(['png', 'jpeg', 'webp']).optional(),
405 - quality: z.number().min(0).max(100).optional(),
406 - fullPage: z.boolean().optional(),
407 - uid: z.string().optional(),
408 - }),
409 - command: 'take_screenshot',
410 - args: input => {
411 - const args: string[] = [];
412 - addOption(args, 'filePath', input.filePath);
413 - addOption(args, 'format', input.format);
414 - addOption(args, 'quality', input.quality);
415 - addBooleanFlag(args, 'fullPage', input.fullPage);
416 - addOption(args, 'uid', input.uid);
417 - return args;
418 - },
419 - }),
420 - commandTool({
421 - slug: 'EVALUATE_SCRIPT',
422 - name: 'Evaluate JavaScript in Chrome page',
423 - description:
424 - 'Evaluate a JavaScript function in the selected page and return a JSON-serializable result.',
425 - inputParams: baseInput.extend({
426 - function: z.string().min(1).describe('Function declaration, e.g. () => document.title.'),
427 - args: z.array(z.unknown()).optional().describe('Arguments passed to the function.'),
428 - dialogAction: z
429 - .string()
430 - .optional()
431 - .describe('Dialog action: accept, dismiss, or prompt response.'),
432 - }),
433 - command: 'evaluate_script',
434 - args: input => {
435 - const args = [input.function];
436 - if (input.args !== undefined) addOption(args, 'args', JSON.stringify(input.args));
437 - addOption(args, 'dialogAction', input.dialogAction);
438 - return args;
439 - },
440 - }),
441 - commandTool({
442 - slug: 'LIST_CONSOLE_MESSAGES',
443 - name: 'List Chrome console messages',
444 - description: 'List console messages for the selected page since the last navigation.',
445 - inputParams: baseInput.extend({
446 - pageSize: z.number().int().positive().optional(),
447 - pageIdx: z.number().int().nonnegative().optional(),
448 - types: z.array(z.string()).optional(),
449 - includePreservedMessages: z.boolean().optional(),
450 - }),
451 - command: 'list_console_messages',
452 - args: input => {
453 - const args: string[] = [];
454 - addOption(args, 'pageSize', input.pageSize);
455 - addOption(args, 'pageIdx', input.pageIdx);
456 - addRepeated(args, 'types', input.types);
457 - addBooleanFlag(args, 'includePreservedMessages', input.includePreservedMessages);
458 - return args;
459 - },
460 - }),
461 - commandTool({
462 - slug: 'GET_CONSOLE_MESSAGE',
463 - name: 'Get Chrome console message',
464 - description: 'Get a console message by ID from LIST_CONSOLE_MESSAGES.',
465 - inputParams: baseInput.extend({ msgid: z.number().int().nonnegative() }),
466 - command: 'get_console_message',
467 - args: input => [String(input.msgid)],
468 - }),
469 - commandTool({
470 - slug: 'LIST_NETWORK_REQUESTS',
471 - name: 'List Chrome network requests',
472 - description: 'List network requests for the selected page since the last navigation.',
473 - inputParams: baseInput.extend({
474 - pageSize: z.number().int().positive().optional(),
475 - pageIdx: z.number().int().nonnegative().optional(),
476 - resourceTypes: z.array(z.string()).optional(),
477 - includePreservedRequests: z.boolean().optional(),
478 - }),
479 - command: 'list_network_requests',
480 - args: input => {
481 - const args: string[] = [];
482 - addOption(args, 'pageSize', input.pageSize);
483 - addOption(args, 'pageIdx', input.pageIdx);
484 - addRepeated(args, 'resourceTypes', input.resourceTypes);
485 - addBooleanFlag(args, 'includePreservedRequests', input.includePreservedRequests);
486 - return args;
487 - },
488 - }),
489 - commandTool({
490 - slug: 'GET_NETWORK_REQUEST',
491 - name: 'Get Chrome network request',
492 - description:
493 - 'Get a selected or specific network request and optionally save bodies to files.',
494 - inputParams: baseInput.extend({
495 - reqid: z.number().int().nonnegative().optional(),
496 - requestFilePath: z.string().optional(),
497 - responseFilePath: z.string().optional(),
498 - }),
499 - command: 'get_network_request',
500 - args: input => {
501 - const args: string[] = [];
502 - addOption(args, 'reqid', input.reqid);
503 - addOption(args, 'requestFilePath', input.requestFilePath);
504 - addOption(args, 'responseFilePath', input.responseFilePath);
505 - return args;
506 - },
507 - }),
508 - commandTool({
509 - slug: 'CLICK',
510 - name: 'Click Chrome page element',
511 - description: 'Click an element by uid from TAKE_SNAPSHOT.',
512 - inputParams: baseInput.extend({
513 - uid,
514 - dblClick: z.boolean().optional(),
515 - includeSnapshot: z.boolean().optional(),
516 - }),
517 - command: 'click',
518 - args: input => {
519 - const args = [input.uid];
520 - addBooleanFlag(args, 'dblClick', input.dblClick);
521 - addBooleanFlag(args, 'includeSnapshot', input.includeSnapshot);
522 - return args;
523 - },
524 - }),
525 - commandTool({
526 - slug: 'FILL',
527 - name: 'Fill Chrome page field',
528 - description: 'Fill an input, textarea, or select element by uid from TAKE_SNAPSHOT.',
529 - inputParams: baseInput.extend({
530 - uid,
531 - value: z.string(),
532 - includeSnapshot: z.boolean().optional(),
533 - }),
534 - command: 'fill',
535 - args: input => {
536 - const args = [input.uid, input.value];
537 - addBooleanFlag(args, 'includeSnapshot', input.includeSnapshot);
538 - return args;
539 - },
540 - }),
541 - commandTool({
542 - slug: 'DRAG',
543 - name: 'Drag Chrome page element',
544 - description: 'Drag an element by uid onto another element by uid.',
545 - inputParams: baseInput.extend({
546 - from_uid: z.string().min(1).describe('Uid of the element to drag.'),
547 - to_uid: z.string().min(1).describe('Uid of the drop target element.'),
548 - includeSnapshot: z.boolean().optional(),
549 - }),
550 - command: 'drag',
551 - args: input => {
552 - const args = [input.from_uid, input.to_uid];
553 - addBooleanFlag(args, 'includeSnapshot', input.includeSnapshot);
554 - return args;
555 - },
556 - }),
557 - commandTool({
558 - slug: 'HANDLE_DIALOG',
559 - name: 'Handle Chrome dialog',
560 - description: 'Accept or dismiss a browser dialog, optionally providing prompt text.',
561 - inputParams: baseInput.extend({
562 - action: z.enum(['accept', 'dismiss']),
563 - promptText: z.string().optional(),
564 - }),
565 - command: 'handle_dialog',
566 - args: input => {
567 - const args = [input.action];
568 - addOption(args, 'promptText', input.promptText);
569 - return args;
570 - },
571 - }),
572 - commandTool({
573 - slug: 'HOVER',
574 - name: 'Hover Chrome page element',
575 - description: 'Hover an element by uid from TAKE_SNAPSHOT.',
576 - inputParams: baseInput.extend({ uid, includeSnapshot: z.boolean().optional() }),
577 - command: 'hover',
578 - args: input => {
579 - const args = [input.uid];
580 - addBooleanFlag(args, 'includeSnapshot', input.includeSnapshot);
581 - return args;
582 - },
583 - }),
584 - commandTool({
585 - slug: 'PRESS_KEY',
586 - name: 'Press key in Chrome page',
587 - description: 'Press a key or key combination in the selected page.',
588 - inputParams: baseInput.extend({
589 - key: z.string().min(1),
590 - includeSnapshot: z.boolean().optional(),
591 - }),
592 - command: 'press_key',
593 - args: input => {
594 - const args = [input.key];
595 - addBooleanFlag(args, 'includeSnapshot', input.includeSnapshot);
596 - return args;
597 - },
598 - }),
599 - commandTool({
600 - slug: 'TYPE_TEXT',
601 - name: 'Type text in Chrome page',
602 - description: 'Type text with the keyboard into the currently focused input.',
603 - inputParams: baseInput.extend({
604 - text: z.string(),
605 - submitKey: z
606 - .string()
607 - .optional()
608 - .describe('Optional key pressed after typing, e.g. Enter, Tab, Escape.'),
609 - }),
610 - command: 'type_text',
611 - args: input => {
612 - const args = [input.text];
613 - addOption(args, 'submitKey', input.submitKey);
614 - return args;
615 - },
616 - }),
617 - commandTool({
618 - slug: 'UPLOAD_FILE',
619 - name: 'Upload file in Chrome page',
620 - description: 'Upload a local file through a file input or element that opens a file chooser.',
621 - inputParams: baseInput.extend({
622 - uid,
623 - filePath: z.string().min(1),
624 - includeSnapshot: z.boolean().optional(),
625 - }),
626 - command: 'upload_file',
627 - args: input => {
628 - const args = [input.uid, input.filePath];
629 - addBooleanFlag(args, 'includeSnapshot', input.includeSnapshot);
630 - return args;
631 - },
632 - }),
633 - commandTool({
634 - slug: 'RESIZE_PAGE',
635 - name: 'Resize Chrome page',
636 - description: 'Resize the selected page window to specific dimensions.',
637 - inputParams: baseInput.extend({
638 - width: z.number().positive(),
639 - height: z.number().positive(),
640 - }),
641 - command: 'resize_page',
642 - args: input => [String(input.width), String(input.height)],
643 - }),
644 - commandTool({
645 - slug: 'EMULATE',
646 - name: 'Emulate Chrome page conditions',
647 - description:
648 - 'Emulate color scheme, CPU/network throttling, geolocation, user agent, or viewport.',
649 - inputParams: baseInput.extend({
650 - colorScheme: z.enum(['dark', 'light', 'auto']).optional(),
651 - cpuThrottlingRate: z.number().positive().optional(),
652 - geolocation: z
653 - .string()
654 - .optional()
655 - .describe('Latitude/longitude as <latitude>x<longitude>, or omit to clear.'),
656 - networkConditions: z
657 - .enum(['Offline', 'Slow 3G', 'Fast 3G', 'Slow 4G', 'Fast 4G'])
658 - .optional(),
659 - userAgent: z.string().optional(),
660 - viewport: z
661 - .string()
662 - .optional()
663 - .describe('<width>x<height>x<devicePixelRatio>[,mobile][,touch][,landscape].'),
664 - }),
665 - command: 'emulate',
666 - args: input => {
667 - const args: string[] = [];
668 - addOption(args, 'colorScheme', input.colorScheme);
669 - addOption(args, 'cpuThrottlingRate', input.cpuThrottlingRate);
670 - addOption(args, 'geolocation', input.geolocation);
671 - addOption(args, 'networkConditions', input.networkConditions);
672 - addOption(args, 'userAgent', input.userAgent);
673 - addOption(args, 'viewport', input.viewport);
674 - return args;
675 - },
676 - }),
677 - commandTool({
678 - slug: 'LIGHTHOUSE_AUDIT',
679 - name: 'Run Chrome Lighthouse audit',
680 - description:
681 - 'Run an accessibility/SEO/best-practices/agentic-browsing Lighthouse audit on the selected page.',
682 - inputParams: baseInput.extend({
683 - mode: z.enum(['navigation', 'snapshot']).optional(),
684 - device: z.enum(['desktop', 'mobile']).optional(),
685 - outputDirPath: z.string().optional(),
686 - }),
687 - command: 'lighthouse_audit',
688 - args: input => {
689 - const args: string[] = [];
690 - addOption(args, 'mode', input.mode);
691 - addOption(args, 'device', input.device);
692 - addOption(args, 'outputDirPath', input.outputDirPath);
693 - return args;
694 - },
695 - }),
696 - commandTool({
697 - slug: 'PERFORMANCE_START_TRACE',
698 - name: 'Start Chrome performance trace',
699 - description: 'Start a Chrome DevTools performance trace on the selected page.',
700 - inputParams: baseInput.extend({
701 - reload: z.boolean().optional(),
702 - autoStop: z.boolean().optional(),
703 - filePath: z.string().optional(),
704 - }),
705 - command: 'performance_start_trace',
706 - args: input => {
707 - const args: string[] = [];
708 - addBooleanFlag(args, 'reload', input.reload);
709 - addBooleanFlag(args, 'autoStop', input.autoStop);
710 - addOption(args, 'filePath', input.filePath);
711 - return args;
712 - },
713 - }),
714 - commandTool({
715 - slug: 'PERFORMANCE_STOP_TRACE',
716 - name: 'Stop Chrome performance trace',
717 - description: 'Stop the active Chrome DevTools performance trace and return insights.',
718 - inputParams: baseInput.extend({ filePath: z.string().optional() }),
719 - command: 'performance_stop_trace',
720 - args: input => {
721 - const args: string[] = [];
722 - addOption(args, 'filePath', input.filePath);
723 - return args;
724 - },
725 - }),
726 - commandTool({
727 - slug: 'PERFORMANCE_ANALYZE_INSIGHT',
728 - name: 'Analyze Chrome performance insight',
729 - description:
730 - 'Return detailed information for a specific performance insight from a trace result.',
731 - inputParams: baseInput.extend({
732 - insightSetId: z.string().min(1),
733 - insightName: z.string().min(1),
734 - }),
735 - command: 'performance_analyze_insight',
736 - args: input => [input.insightSetId, input.insightName],
737 - }),
738 - commandTool({
739 - slug: 'LIST_EXTENSIONS',
740 - name: 'List Chrome extensions',
741 - description: 'List Chrome extensions installed in the controlled browser.',
742 - inputParams: baseInput,
743 - command: 'list_extensions',
744 - args: () => [],
745 - }),
746 - commandTool({
747 - slug: 'INSTALL_EXTENSION',
748 - name: 'Install Chrome extension',
749 - description: 'Install an unpacked Chrome extension from an absolute local path.',
750 - inputParams: baseInput.extend({ path: z.string().min(1) }),
751 - command: 'install_extension',
752 - args: input => [input.path],
753 - }),
754 - commandTool({
755 - slug: 'RELOAD_EXTENSION',
756 - name: 'Reload Chrome extension',
757 - description: 'Reload an unpacked Chrome extension by extension id.',
758 - inputParams: baseInput.extend({ id: z.string().min(1) }),
759 - command: 'reload_extension',
760 - args: input => [input.id],
761 - }),
762 - commandTool({
763 - slug: 'TRIGGER_EXTENSION_ACTION',
764 - name: 'Trigger Chrome extension action',
765 - description: 'Trigger the default toolbar action for a Chrome extension by id.',
766 - inputParams: baseInput.extend({ id: z.string().min(1) }),
767 - command: 'trigger_extension_action',
768 - args: input => [input.id],
769 - }),
770 - commandTool({
771 - slug: 'UNINSTALL_EXTENSION',
772 - name: 'Uninstall Chrome extension',
773 - description: 'Uninstall a Chrome extension by extension id.',
774 - inputParams: baseInput.extend({ id: z.string().min(1) }),
775 - command: 'uninstall_extension',
776 - args: input => [input.id],
777 - }),
778 - commandTool({
779 - slug: 'TAKE_MEMORY_SNAPSHOT',
780 - name: 'Take Chrome memory snapshot',
781 - description:
782 - 'Capture a heap snapshot of the selected page to a local file for memory analysis.',
783 - inputParams: baseInput.extend({ filePath: z.string().min(1) }),
784 - command: 'take_memory_snapshot',
785 - args: input => [input.filePath],
786 - }),
787 - ],
788 -};
ts/packages/cli-local-tools/src/toolkits/peekaboo.test.ts deleted
-60
@@ -1,60 +0,0 @@
1 -import { describe, expect, it } from 'vitest';
2 -import { resolveBundledBinary } from '../bundled-binaries';
3 -import { executeLocalToolBySlug, getLocalToolInputDefinition } from '../registry';
4 -import { peekabooToolkit } from './peekaboo';
5 -
6 -describe('@composio/cli-local-tools Peekaboo toolkit', () => {
7 - it('exposes first-class schemas for Peekaboo tools', () => {
8 - expect(peekabooToolkit.tools.map(tool => tool.slug)).toEqual(
9 - expect.arrayContaining([
10 - 'PERMISSIONS_STATUS',
11 - 'LIST_APPS',
12 - 'SEE',
13 - 'IMAGE',
14 - 'CLICK',
15 - 'TYPE',
16 - 'WINDOW_FOCUS',
17 - 'APP_LAUNCH',
18 - ])
19 - );
20 -
21 - const seeSchema = getLocalToolInputDefinition('LOCAL_PEEKABOO_SEE');
22 - expect(seeSchema?.schema.properties).toHaveProperty('app');
23 - expect(seeSchema?.schema.properties).toHaveProperty('annotate');
24 -
25 - const clickSchema = getLocalToolInputDefinition('LOCAL_PEEKABOO_CLICK');
26 - expect(clickSchema?.schema.properties).toHaveProperty('on');
27 - expect(clickSchema?.schema.properties).toHaveProperty('coords');
28 - });
29 -
30 - it.runIf(process.env.COMPOSIO_REAL_LOCAL_TOOLS_TESTS === '1' && process.platform === 'darwin')(
31 - 'resolves generated bundled Peekaboo CLI and executes version without permissions',
32 - async () => {
33 - const resolved = await resolveBundledBinary(
34 - peekabooToolkit,
35 - { bundledBinary: 'peekaboo-cli' },
36 - { currentPlatform: process.arch === 'x64' ? 'darwin-x64' : 'darwin-arm64' }
37 - );
38 - expect(resolved?.exists).toBe(true);
39 -
40 - const result = await executeLocalToolBySlug('LOCAL_PEEKABOO_VERSION', {});
41 - expect(result?.resultText).toContain('Peekaboo 3.0.0');
42 - }
43 - );
44 -
45 - it.runIf(process.env.COMPOSIO_REAL_LOCAL_TOOLS_TESTS === '1' && process.platform === 'darwin')(
46 - 'validates against real Peekaboo permission and app-list commands',
47 - async () => {
48 - const permissions = await executeLocalToolBySlug('LOCAL_PEEKABOO_PERMISSIONS_STATUS', {});
49 - expect(permissions?.result).toEqual(expect.objectContaining({ success: true }));
50 -
51 - const apps = await executeLocalToolBySlug('LOCAL_PEEKABOO_LIST_APPS', {});
52 - expect(apps?.result).toEqual(
53 - expect.objectContaining({
54 - data: expect.objectContaining({ applications: expect.any(Array) }),
55 - })
56 - );
57 - },
58 - 120_000
59 - );
60 -});
ts/packages/cli-local-tools/src/toolkits/peekaboo.ts deleted
-961
@@ -1,961 +0,0 @@
1 -import { z } from 'zod/v3';
2 -import { runLocalCommand } from '../runtime';
3 -import type {
4 - LocalCommandExecution,
5 - LocalExecutionContext,
6 - LocalExecutionResult,
7 - LocalToolkitDeclaration,
8 - LocalToolDeclaration,
9 -} from '../types';
10 -
11 -const PEEKABOO_VERSION = '3.0.0-beta4';
12 -const COMMAND_TIMEOUT_MS = 180_000;
13 -
14 -const cliOutput = z.object({
15 - ok: z.boolean(),
16 - commandName: z.string(),
17 - result: z.unknown().optional(),
18 - resultText: z.string().optional(),
19 - stdout: z.string(),
20 - stderr: z.string(),
21 -});
22 -
23 -const baseInput = z.object({
24 - verbose: z.boolean().default(false).describe('Enable verbose Peekaboo logging.'),
25 - noRemote: z
26 - .boolean()
27 - .default(false)
28 - .describe('Force local Peekaboo services and skip the XPC helper.'),
29 - logLevel: z
30 - .enum(['trace', 'verbose', 'debug', 'info', 'warning', 'error', 'critical'])
31 - .optional(),
32 - xpcService: z.string().optional().describe('Override Peekaboo XPC helper mach service name.'),
33 -});
34 -
35 -const targetInput = {
36 - app: z.string().optional().describe('Application name, bundle id, or PID:1234 target.'),
37 - pid: z.number().int().positive().optional().describe('Target application process id.'),
38 - windowTitle: z.string().optional().describe('Target window title.'),
39 - windowIndex: z.number().int().nonnegative().optional().describe('0-based target window index.'),
40 -} as const;
41 -
42 -const focusInput = {
43 - noAutoFocus: z.boolean().optional().describe('Disable automatic focus before interaction.'),
44 - spaceSwitch: z.boolean().optional().describe("Switch to the target window's Space if needed."),
45 - bringToCurrentSpace: z
46 - .boolean()
47 - .optional()
48 - .describe('Move target window to current Space instead.'),
49 - focusTimeoutSeconds: z.number().positive().optional(),
50 - focusRetryCountValue: z.number().int().nonnegative().optional(),
51 -} as const;
52 -
53 -const extractJson = (text: string): unknown | undefined => {
54 - const candidates = [text.indexOf('{'), text.indexOf('[')].filter(index => index >= 0);
55 - if (!candidates.length) return undefined;
56 -
57 - const start = Math.min(...candidates);
58 - let depth = 0;
59 - let inString = false;
60 - let escaped = false;
61 -
62 - for (let index = start; index < text.length; index += 1) {
63 - const char = text[index];
64 - if (inString) {
65 - if (escaped) {
66 - escaped = false;
67 - } else if (char === '\\') {
68 - escaped = true;
69 - } else if (char === '"') {
70 - inString = false;
71 - }
72 - continue;
73 - }
74 - if (char === '"') {
75 - inString = true;
76 - continue;
77 - }
78 - if (char === '{' || char === '[') {
79 - depth += 1;
80 - continue;
81 - }
82 - if (char === '}' || char === ']') {
83 - depth -= 1;
84 - if (depth === 0) {
85 - try {
86 - return JSON.parse(text.slice(start, index + 1)) as unknown;
87 - } catch {
88 - return undefined;
89 - }
90 - }
91 - }
92 - }
93 -
94 - return undefined;
95 -};
96 -
97 -const addOption = (args: string[], name: string, value: unknown): string[] => {
98 - if (value === undefined || value === null || value === '') return args;
99 - args.push(`--${name}`, String(value));
100 - return args;
101 -};
102 -
103 -const addBooleanFlag = (args: string[], name: string, value: unknown): string[] => {
104 - if (value === true) args.push(`--${name}`);
105 - return args;
106 -};
107 -
108 -const addRepeated = (args: string[], name: string, values: unknown): string[] => {
109 - if (!Array.isArray(values)) return args;
110 - for (const value of values) {
111 - if (value === undefined || value === null || value === '') continue;
112 - args.push(`--${name}`, String(value));
113 - }
114 - return args;
115 -};
116 -
117 -const addGlobalOptions = (args: string[], input: Record<string, unknown>, json: boolean) => {
118 - if (json) args.push('--json');
119 - addBooleanFlag(args, 'verbose', input.verbose);
120 - addBooleanFlag(args, 'no-remote', input.noRemote);
121 - addOption(args, 'log-level', input.logLevel);
122 - addOption(args, 'xpc-service', input.xpcService);
123 -};
124 -
125 -const addTargetOptions = (args: string[], input: Record<string, unknown>) => {
126 - addOption(args, 'app', input.app);
127 - addOption(args, 'pid', input.pid);
128 - addOption(args, 'window-title', input.windowTitle);
129 - addOption(args, 'window-index', input.windowIndex);
130 -};
131 -
132 -const addFocusOptions = (args: string[], input: Record<string, unknown>) => {
133 - addBooleanFlag(args, 'no-auto-focus', input.noAutoFocus);
134 - addBooleanFlag(args, 'space-switch', input.spaceSwitch);
135 - addBooleanFlag(args, 'bring-to-current-space', input.bringToCurrentSpace);
136 - addOption(args, 'focus-timeout-seconds', input.focusTimeoutSeconds);
137 - addOption(args, 'focus-retry-count-value', input.focusRetryCountValue);
138 -};
139 -
140 -const parsePeekabooOutput = (
141 - commandName: string,
142 - stdout: string,
143 - stderr: string,
144 - parseJson: boolean
145 -): LocalExecutionResult => {
146 - const trimmed = stdout.trim();
147 - const result = parseJson ? extractJson(trimmed) : undefined;
148 - return {
149 - ok: true,
150 - commandName,
151 - ...(result !== undefined ? { result } : {}),
152 - ...(result === undefined && trimmed ? { resultText: trimmed } : {}),
153 - stdout,
154 - stderr,
155 - };
156 -};
157 -
158 -const runPeekaboo = async (
159 - commandName: string,
160 - commandArgs: ReadonlyArray<string>,
161 - input: Record<string, unknown>,
162 - context: LocalExecutionContext,
163 - options: { readonly json?: boolean } = { json: true }
164 -): Promise<LocalExecutionResult> => {
165 - const args = [...commandArgs];
166 - const parseJson = options.json !== false;
167 - addGlobalOptions(args, input, parseJson);
168 - const execution: LocalCommandExecution = {
169 - kind: 'command',
170 - command: { bundledBinary: 'peekaboo-cli', fallbackCommand: 'peekaboo' },
171 - args,
172 - timeoutMs: COMMAND_TIMEOUT_MS,
173 - };
174 - const result = await runLocalCommand(execution, input, context);
175 - return parsePeekabooOutput(
176 - commandName,
177 - String(result.stdout ?? ''),
178 - String(result.stderr ?? ''),
179 - parseJson
180 - );
181 -};
182 -
183 -const commandTool = <TInput extends z.ZodTypeAny>(definition: {
184 - readonly slug: string;
185 - readonly name: string;
186 - readonly description: string;
187 - readonly inputParams: TInput;
188 - readonly args: (input: z.infer<TInput>) => ReadonlyArray<string>;
189 - readonly json?: boolean;
190 -}): LocalToolDeclaration<TInput> => ({
191 - slug: definition.slug,
192 - name: definition.name,
193 - description: definition.description,
194 - platforms: ['darwin-arm64'],
195 - inputParams: definition.inputParams,
196 - outputParams: cliOutput,
197 - execution: {
198 - kind: 'native',
199 - execute: (input, context) =>
200 - runPeekaboo(definition.slug, definition.args(input as z.infer<TInput>), input, context, {
201 - json: definition.json,
202 - }),
203 - },
204 -});
205 -
206 -const listDetails = z
207 - .array(z.enum(['bounds', 'ids', 'off_screen']))
208 - .optional()
209 - .describe('Window details to include when listing windows.');
210 -
211 -export const peekabooToolkit: LocalToolkitDeclaration = {
212 - slug: 'PEEKABOO',
213 - name: 'Peekaboo (local)',
214 - description: 'Local macOS screen capture and GUI automation tools backed by the Peekaboo CLI.',
215 - platforms: ['darwin-arm64'],
216 - source: {
217 - type: 'cli',
218 - package: `@steipete/peekaboo@${PEEKABOO_VERSION}`,
219 - repository: 'https://github.com/steipete/Peekaboo',
220 - command: 'peekaboo',
221 - },
222 - bundledBinaries: [
223 - {
224 - id: 'peekaboo-cli',
225 - description: 'Peekaboo macOS automation CLI',
226 - targets: [
227 - {
228 - platforms: ['darwin-arm64'],
229 - path: 'peekaboo/darwin-arm64/peekaboo',
230 - },
231 - ],
232 - },
233 - ],
234 - setup: {
235 - install:
236 - 'Requires macOS 15+, Screen Recording permission for capture/read tools, and Accessibility permission for click/type/window/menu automation. macOS Peekaboo binaries are generated for CLI release artifacts from the pinned upstream submodule; alternatively install with `brew install steipete/tap/peekaboo`.',
237 - commandOverrides: [],
238 - notes: [
239 - 'Run PERMISSIONS_STATUS before UI automation and grant missing permissions in System Settings.',
240 - 'Use SEE to capture a snapshot and element ids before CLICK, TYPE, SCROLL, MOVE, or DRAG.',
241 - 'Most tools are one-shot CLI wrappers that return Peekaboo JSON output when upstream supports --json.',
242 - 'Automation tools can control the local GUI; avoid sensitive screens unless intended.',
243 - ],
244 - },
245 - tools: [
246 - commandTool({
247 - slug: 'VERSION',
248 - name: 'Get Peekaboo version',
249 - description: 'Return the bundled or installed Peekaboo CLI version.',
250 - inputParams: baseInput,
251 - json: false,
252 - args: () => ['--version'],
253 - }),
254 - commandTool({
255 - slug: 'PERMISSIONS_STATUS',
256 - name: 'Check Peekaboo permissions',
257 - description: 'Check macOS Screen Recording, Accessibility, and Automation permissions.',
258 - inputParams: baseInput,
259 - args: () => ['permissions', 'status'],
260 - }),
261 - commandTool({
262 - slug: 'PERMISSIONS_GRANT',
263 - name: 'Show Peekaboo permission grant instructions',
264 - description: 'Return grant instructions for missing macOS permissions.',
265 - inputParams: baseInput,
266 - args: () => ['permissions', 'grant'],
267 - }),
268 - commandTool({
269 - slug: 'LIST_APPS',
270 - name: 'List running macOS apps',
271 - description: 'Enumerate running GUI applications with process and focus metadata.',
272 - inputParams: baseInput,
273 - args: () => ['list', 'apps'],
274 - }),
275 - commandTool({
276 - slug: 'LIST_WINDOWS',
277 - name: 'List macOS app windows',
278 - description: 'List windows for a target application with optional bounds/id details.',
279 - inputParams: baseInput.extend({
280 - app: z.string().min(1).describe('Application name, bundle id, or PID:1234.'),
281 - includeDetails: listDetails,
282 - }),
283 - args: input => {
284 - const args = ['list', 'windows'];
285 - addOption(args, 'app', input.app);
286 - if (input.includeDetails?.length)
287 - addOption(args, 'include-details', input.includeDetails.join(','));
288 - return args;
289 - },
290 - }),
291 - commandTool({
292 - slug: 'LIST_SCREENS',
293 - name: 'List macOS screens',
294 - description: 'List connected displays, resolution, scaling, and main/secondary state.',
295 - inputParams: baseInput,
296 - args: () => ['list', 'screens'],
297 - }),
298 - commandTool({
299 - slug: 'LIST_MENUBAR',
300 - name: 'List macOS menu bar items',
301 - description: 'List menu bar/status items and indices for menu-bar automation.',
302 - inputParams: baseInput,
303 - args: () => ['list', 'menubar'],
304 - }),
305 - commandTool({
306 - slug: 'LIST_PERMISSIONS',
307 - name: 'List Peekaboo permission status',
308 - description: 'List the same permission state exposed by `peekaboo list permissions`.',
309 - inputParams: baseInput,
310 - args: () => ['list', 'permissions'],
311 - }),
312 - commandTool({
313 - slug: 'TOOLS',
314 - name: 'List Peekaboo tool catalog',
315 - description: 'Return Peekaboo native/MCP tool catalog for discovery and auditing.',
316 - inputParams: baseInput.extend({ noSort: z.boolean().optional() }),
317 - args: input => {
318 - const args = ['tools'];
319 - addBooleanFlag(args, 'no-sort', input.noSort);
320 - return args;
321 - },
322 - }),
323 - commandTool({
324 - slug: 'SEE',
325 - name: 'Capture annotated UI snapshot',
326 - description:
327 - 'Capture UI accessibility metadata and optional annotated screenshot for automation.',
328 - inputParams: baseInput.extend({
329 - app: z.string().optional(),
330 - pid: z.number().int().positive().optional(),
331 - windowTitle: z.string().optional(),
332 - mode: z.enum(['screen', 'window', 'frontmost']).optional(),
333 - path: z.string().optional(),
334 - captureEngine: z.enum(['auto', 'classic', 'cg', 'modern', 'sckit']).optional(),
335 - screenIndex: z.number().int().nonnegative().optional(),
336 - analyze: z.string().optional(),
337 - annotate: z.boolean().optional(),
338 - }),
339 - args: input => {
340 - const args = ['see'];
341 - addOption(args, 'app', input.app);
342 - addOption(args, 'pid', input.pid);
343 - addOption(args, 'window-title', input.windowTitle);
344 - addOption(args, 'mode', input.mode);
345 - addOption(args, 'path', input.path);
346 - addOption(args, 'capture-engine', input.captureEngine);
347 - addOption(args, 'screen-index', input.screenIndex);
348 - addOption(args, 'analyze', input.analyze);
349 - addBooleanFlag(args, 'annotate', input.annotate);
350 - return args;
351 - },
352 - }),
353 - commandTool({
354 - slug: 'IMAGE',
355 - name: 'Capture raw screenshot',
356 - description: 'Capture a screen/window/frontmost image and optionally save or analyze it.',
357 - inputParams: baseInput.extend({
358 - app: z.string().optional(),
359 - pid: z.number().int().positive().optional(),
360 - path: z.string().optional(),
361 - mode: z.enum(['auto', 'screen', 'window', 'frontmost']).optional(),
362 - windowTitle: z.string().optional(),
363 - windowIndex: z.number().int().nonnegative().optional(),
364 - screenIndex: z.number().int().nonnegative().optional(),
365 - format: z.enum(['png', 'jpg']).optional(),
366 - captureFocus: z.enum(['auto', 'background', 'foreground']).optional(),
367 - analyze: z.string().optional(),
368 - retina: z.boolean().optional(),
369 - }),
370 - args: input => {
371 - const args = ['image'];
372 - addOption(args, 'app', input.app);
373 - addOption(args, 'pid', input.pid);
374 - addOption(args, 'path', input.path);
375 - addOption(args, 'mode', input.mode);
376 - addOption(args, 'window-title', input.windowTitle);
377 - addOption(args, 'window-index', input.windowIndex);
378 - addOption(args, 'screen-index', input.screenIndex);
379 - addOption(args, 'format', input.format);
380 - addOption(args, 'capture-focus', input.captureFocus);
381 - addOption(args, 'analyze', input.analyze);
382 - addBooleanFlag(args, 'retina', input.retina);
383 - return args;
384 - },
385 - }),
386 - commandTool({
387 - slug: 'CLICK',
388 - name: 'Click UI element or coordinates',
389 - description: 'Click by fuzzy query, Peekaboo element id, or x,y coordinates.',
390 - inputParams: baseInput.extend({
391 - query: z.string().optional(),
392 - session: z.string().optional(),
393 - on: z.string().optional().describe('Element id from SEE.'),
394 - id: z.string().optional().describe('Alias for on.'),
395 - app: z.string().optional(),
396 - coords: z.string().optional().describe('Coordinates as x,y.'),
397 - waitFor: z.number().int().positive().optional(),
398 - double: z.boolean().optional(),
399 - right: z.boolean().optional(),
400 - ...focusInput,
401 - }),
402 - args: input => {
403 - const args = ['click'];
404 - if (input.query) args.push(input.query);
405 - addOption(args, 'session', input.session);
406 - addOption(args, 'on', input.on);
407 - addOption(args, 'id', input.id);
408 - addOption(args, 'app', input.app);
409 - addOption(args, 'coords', input.coords);
410 - addOption(args, 'wait-for', input.waitFor);
411 - addBooleanFlag(args, 'double', input.double);
412 - addBooleanFlag(args, 'right', input.right);
413 - addFocusOptions(args, input);
414 - return args;
415 - },
416 - }),
417 - commandTool({
418 - slug: 'TYPE',
419 - name: 'Type text or keyboard input',
420 - description: 'Type text, clear fields, and append return/tab/escape/delete key actions.',
421 - inputParams: baseInput.extend({
422 - text: z.string().optional(),
423 - session: z.string().optional(),
424 - delay: z.number().int().nonnegative().optional(),
425 - profile: z.enum(['human', 'linear']).optional(),
426 - wpm: z.number().int().min(80).max(220).optional(),
427 - tab: z.number().int().positive().optional(),
428 - app: z.string().optional(),
429 - return: z.boolean().optional(),
430 - escape: z.boolean().optional(),
431 - delete: z.boolean().optional(),
432 - clear: z.boolean().optional(),
433 - ...focusInput,
434 - }),
435 - args: input => {
436 - const args = ['type'];
437 - if (input.text) args.push(input.text);
438 - addOption(args, 'session', input.session);
439 - addOption(args, 'delay', input.delay);
440 - addOption(args, 'profile', input.profile);
441 - addOption(args, 'wpm', input.wpm);
442 - addOption(args, 'tab', input.tab);
443 - addOption(args, 'app', input.app);
444 - addBooleanFlag(args, 'return', input.return);
445 - addBooleanFlag(args, 'escape', input.escape);
446 - addBooleanFlag(args, 'delete', input.delete);
447 - addBooleanFlag(args, 'clear', input.clear);
448 - addFocusOptions(args, input);
449 - return args;
450 - },
451 - }),
452 - commandTool({
453 - slug: 'PRESS',
454 - name: 'Press special keys',
455 - description: 'Press one or more special keys such as return, tab, arrows, or function keys.',
456 - inputParams: baseInput.extend({
457 - keys: z.array(z.string().min(1)).min(1),
458 - count: z.number().int().positive().optional(),
459 - delay: z.number().int().nonnegative().optional(),
460 - hold: z.number().int().nonnegative().optional(),
461 - session: z.string().optional(),
462 - app: z.string().optional(),
463 - ...focusInput,
464 - }),
465 - args: input => {
466 - const args = ['press', ...input.keys];
467 - addOption(args, 'count', input.count);
468 - addOption(args, 'delay', input.delay);
469 - addOption(args, 'hold', input.hold);
470 - addOption(args, 'session', input.session);
471 - addOption(args, 'app', input.app);
472 - addFocusOptions(args, input);
473 - return args;
474 - },
475 - }),
476 - commandTool({
477 - slug: 'HOTKEY',
478 - name: 'Press key combination',
479 - description: 'Press modifier combos such as cmd,c or cmd,shift,t.',
480 - inputParams: baseInput.extend({
481 - keys: z.string().min(1).describe('Comma- or space-separated key combo.'),
482 - holdDuration: z.number().int().nonnegative().optional(),
483 - app: z.string().optional(),
484 - snapshot: z.string().optional(),
485 - ...focusInput,
486 - }),
487 - args: input => {
488 - const args = ['hotkey', input.keys];
489 - addOption(args, 'hold-duration', input.holdDuration);
490 - addOption(args, 'app', input.app);
491 - addOption(args, 'snapshot', input.snapshot);
492 - addFocusOptions(args, input);
493 - return args;
494 - },
495 - }),
496 - commandTool({
497 - slug: 'SCROLL',
498 - name: 'Scroll UI',
499 - description: 'Scroll up, down, left, or right at pointer position or a captured element.',
500 - inputParams: baseInput.extend({
501 - direction: z.enum(['up', 'down', 'left', 'right']),
502 - amount: z.number().int().positive().optional(),
503 - on: z.string().optional(),
504 - snapshot: z.string().optional(),
505 - app: z.string().optional(),
506 - delay: z.number().int().nonnegative().optional(),
507 - smooth: z.boolean().optional(),
508 - ...focusInput,
509 - }),
510 - args: input => {
511 - const args = ['scroll'];
512 - addOption(args, 'direction', input.direction);
513 - addOption(args, 'amount', input.amount);
514 - addOption(args, 'on', input.on);
515 - addOption(args, 'snapshot', input.snapshot);
516 - addOption(args, 'app', input.app);
517 - addOption(args, 'delay', input.delay);
518 - addBooleanFlag(args, 'smooth', input.smooth);
519 - addFocusOptions(args, input);
520 - return args;
521 - },
522 - }),
523 - commandTool({
524 - slug: 'MOVE',
525 - name: 'Move cursor',
526 - description: 'Move cursor to coordinates, element id/query, or screen center.',
527 - inputParams: baseInput.extend({
528 - coords: z.string().optional().describe('Coordinates as x,y.'),
529 - id: z.string().optional(),
530 - to: z.string().optional().describe('Fuzzy element query.'),
531 - center: z.boolean().optional(),
532 - snapshot: z.string().optional(),
533 - app: z.string().optional(),
534 - smooth: z.boolean().optional(),
535 - duration: z.number().int().nonnegative().optional(),
536 - steps: z.number().int().positive().optional(),
537 - profile: z.enum(['linear', 'human']).optional(),
538 - ...focusInput,
539 - }),
540 - args: input => {
541 - const args = ['move'];
542 - if (input.coords) args.push(input.coords);
543 - addOption(args, 'id', input.id);
544 - addOption(args, 'to', input.to);
545 - addBooleanFlag(args, 'center', input.center);
546 - addOption(args, 'snapshot', input.snapshot);
547 - addOption(args, 'app', input.app);
548 - addBooleanFlag(args, 'smooth', input.smooth);
549 - addOption(args, 'duration', input.duration);
550 - addOption(args, 'steps', input.steps);
551 - addOption(args, 'profile', input.profile);
552 - addFocusOptions(args, input);
553 - return args;
554 - },
555 - }),
556 - commandTool({
557 - slug: 'DRAG',
558 - name: 'Drag and drop',
559 - description: 'Drag from an element/coordinate to another element/coordinate or app.',
560 - inputParams: baseInput.extend({
561 - from: z.string().optional(),
562 - fromCoords: z.string().optional().describe('Start coordinates as x,y.'),
563 - to: z.string().optional(),
564 - toCoords: z.string().optional().describe('End coordinates as x,y.'),
565 - toApp: z.string().optional(),
566 - snapshot: z.string().optional(),
567 - app: z.string().optional(),
568 - duration: z.number().int().nonnegative().optional(),
569 - steps: z.number().int().positive().optional(),
570 - modifiers: z.string().optional().describe('Comma-separated modifiers such as cmd,shift.'),
571 - profile: z.enum(['linear', 'human']).optional(),
572 - ...focusInput,
573 - }),
574 - args: input => {
575 - const args = ['drag'];
576 - addOption(args, 'from', input.from);
577 - addOption(args, 'from-coords', input.fromCoords);
578 - addOption(args, 'to', input.to);
579 - addOption(args, 'to-coords', input.toCoords);
580 - addOption(args, 'to-app', input.toApp);
581 - addOption(args, 'snapshot', input.snapshot);
582 - addOption(args, 'app', input.app);
583 - addOption(args, 'duration', input.duration);
584 - addOption(args, 'steps', input.steps);
585 - addOption(args, 'modifiers', input.modifiers);
586 - addOption(args, 'profile', input.profile);
587 - addFocusOptions(args, input);
588 - return args;
589 - },
590 - }),
591 - commandTool({
592 - slug: 'APP_LAUNCH',
593 - name: 'Launch macOS app',
594 - description: 'Launch an app by name/path or bundle id and optionally open documents/URLs.',
595 - inputParams: baseInput.extend({
596 - app: z.string().optional(),
597 - bundleId: z.string().optional(),
598 - open: z.array(z.string()).optional(),
599 - waitUntilReady: z.boolean().optional(),
600 - noFocus: z.boolean().optional(),
601 - }),
602 - args: input => {
603 - const args = ['app', 'launch'];
604 - if (input.app) args.push(input.app);
605 - addOption(args, 'bundle-id', input.bundleId);
606 - addRepeated(args, 'open', input.open);
607 - addBooleanFlag(args, 'wait-until-ready', input.waitUntilReady);
608 - addBooleanFlag(args, 'no-focus', input.noFocus);
609 - return args;
610 - },
611 - }),
612 - commandTool({
613 - slug: 'APP_QUIT',
614 - name: 'Quit macOS app',
615 - description: 'Quit one target app or all regular apps with exclusions.',
616 - inputParams: baseInput.extend({
617 - app: z.string().optional(),
618 - pid: z.number().int().positive().optional(),
619 - all: z.boolean().optional(),
620 - except: z.string().optional().describe('Comma-separated app exclusions when all=true.'),
621 - force: z.boolean().optional(),
622 - }),
623 - args: input => {
624 - const args = ['app', 'quit'];
625 - addOption(args, 'app', input.app);
626 - addOption(args, 'pid', input.pid);
627 - addBooleanFlag(args, 'all', input.all);
628 - addOption(args, 'except', input.except);
629 - addBooleanFlag(args, 'force', input.force);
630 - return args;
631 - },
632 - }),
633 - commandTool({
634 - slug: 'APP_SWITCH',
635 - name: 'Switch macOS app',
636 - description: 'Activate a specific app or cycle with Cmd+Tab behavior.',
637 - inputParams: baseInput.extend({ to: z.string().optional(), cycle: z.boolean().optional() }),
638 - args: input => {
639 - const args = ['app', 'switch'];
640 - addOption(args, 'to', input.to);
641 - addBooleanFlag(args, 'cycle', input.cycle);
642 - return args;
643 - },
644 - }),
645 - commandTool({
646 - slug: 'WINDOW_FOCUS',
647 - name: 'Focus macOS window',
648 - description: 'Bring a target app/window to foreground with optional Space handling.',
649 - inputParams: baseInput.extend({ ...targetInput, ...focusInput }),
650 - args: input => {
651 - const args = ['window', 'focus'];
652 - addTargetOptions(args, input);
653 - addFocusOptions(args, input);
654 - return args;
655 - },
656 - }),
657 - commandTool({
658 - slug: 'WINDOW_MOVE',
659 - name: 'Move macOS window',
660 - description: 'Move a target window to a new x,y origin.',
661 - inputParams: baseInput.extend({ ...targetInput, x: z.number(), y: z.number() }),
662 - args: input => {
663 - const args = ['window', 'move'];
664 - addTargetOptions(args, input);
665 - addOption(args, 'x', input.x);
666 - addOption(args, 'y', input.y);
667 - return args;
668 - },
669 - }),
670 - commandTool({
671 - slug: 'WINDOW_RESIZE',
672 - name: 'Resize macOS window',
673 - description: 'Resize a target window while keeping its origin.',
674 - inputParams: baseInput.extend({ ...targetInput, width: z.number(), height: z.number() }),
675 - args: input => {
676 - const args = ['window', 'resize'];
677 - addTargetOptions(args, input);
678 - addOption(args, 'width', input.width);
679 - addOption(args, 'height', input.height);
680 - return args;
681 - },
682 - }),
683 - commandTool({
684 - slug: 'WINDOW_SET_BOUNDS',
685 - name: 'Set macOS window bounds',
686 - description: 'Set target window origin and size in one operation.',
687 - inputParams: baseInput.extend({
688 - ...targetInput,
689 - x: z.number(),
690 - y: z.number(),
691 - width: z.number(),
692 - height: z.number(),
693 - }),
694 - args: input => {
695 - const args = ['window', 'set-bounds'];
696 - addTargetOptions(args, input);
697 - addOption(args, 'x', input.x);
698 - addOption(args, 'y', input.y);
699 - addOption(args, 'width', input.width);
700 - addOption(args, 'height', input.height);
701 - return args;
702 - },
703 - }),
704 - ...(['close', 'minimize', 'maximize'] as const).map(action =>
705 - commandTool({
706 - slug: `WINDOW_${action.toUpperCase()}`,
707 - name: `${action[0]?.toUpperCase()}${action.slice(1)} macOS window`,
708 - description: `${action[0]?.toUpperCase()}${action.slice(1)} a target macOS window.`,
709 - inputParams: baseInput.extend(targetInput),
710 - args: input => {
711 - const args = ['window', action];
712 - addTargetOptions(args, input);
713 - return args;
714 - },
715 - })
716 - ),
717 - commandTool({
718 - slug: 'MENU_LIST',
719 - name: 'List app menus',
720 - description: 'List menu tree for a target app.',
721 - inputParams: baseInput.extend({ ...targetInput, includeDisabled: z.boolean().optional() }),
722 - args: input => {
723 - const args = ['menu', 'list'];
724 - addTargetOptions(args, input);
725 - addBooleanFlag(args, 'include-disabled', input.includeDisabled);
726 - return args;
727 - },
728 - }),
729 - commandTool({
730 - slug: 'MENU_CLICK',
731 - name: 'Click app menu item',
732 - description: 'Click an application menu item by item name or path such as File > Save.',
733 - inputParams: baseInput.extend({
734 - ...targetInput,
735 - ...focusInput,
736 - item: z.string().optional(),
737 - path: z.string().optional(),
738 - }),
739 - args: input => {
740 - const args = ['menu', 'click'];
741 - addTargetOptions(args, input);
742 - addFocusOptions(args, input);
743 - addOption(args, 'item', input.item);
744 - addOption(args, 'path', input.path);
745 - return args;
746 - },
747 - }),
748 - commandTool({
749 - slug: 'MENU_LIST_ALL',
750 - name: 'List frontmost menus and menu extras',
751 - description: 'Snapshot frontmost app menus and system menu extras.',
752 - inputParams: baseInput.extend({
753 - includeDisabled: z.boolean().optional(),
754 - includeFrames: z.boolean().optional(),
755 - }),
756 - args: input => {
757 - const args = ['menu', 'list-all'];
758 - addBooleanFlag(args, 'include-disabled', input.includeDisabled);
759 - addBooleanFlag(args, 'include-frames', input.includeFrames);
760 - return args;
761 - },
762 - }),
763 - commandTool({
764 - slug: 'CLIPBOARD',
765 - name: 'Read or write macOS clipboard',
766 - description: 'Get, set, clear, save, restore, or load macOS clipboard contents.',
767 - inputParams: baseInput.extend({
768 - action: z.enum(['get', 'set', 'clear', 'save', 'restore', 'load']),
769 - text: z.string().optional(),
770 - filePath: z.string().optional(),
771 - imagePath: z.string().optional(),
772 - dataBase64: z.string().optional(),
773 - uti: z.string().optional(),
774 - prefer: z.string().optional(),
775 - output: z.string().optional(),
776 - slot: z.string().optional(),
777 - alsoText: z.string().optional(),
778 - allowLarge: z.boolean().optional(),
779 - verify: z.boolean().optional(),
780 - }),
781 - args: input => {
782 - const args = ['clipboard'];
783 - addOption(args, 'action', input.action);
784 - addOption(args, 'text', input.text);
785 - addOption(args, 'file-path', input.filePath);
786 - addOption(args, 'image-path', input.imagePath);
787 - addOption(args, 'data-base64', input.dataBase64);
788 - addOption(args, 'uti', input.uti);
789 - addOption(args, 'prefer', input.prefer);
790 - addOption(args, 'output', input.output);
791 - addOption(args, 'slot', input.slot);
792 - addOption(args, 'also-text', input.alsoText);
793 - addBooleanFlag(args, 'allow-large', input.allowLarge);
794 - addBooleanFlag(args, 'verify', input.verify);
795 - return args;
796 - },
797 - }),
798 - commandTool({
799 - slug: 'APP_HIDE',
800 - name: 'Hide macOS app',
801 - description: 'Hide a target application.',
802 - inputParams: baseInput.extend({ app: z.string().min(1) }),
803 - args: input => ['app', 'hide', '--app', input.app],
804 - }),
805 - commandTool({
806 - slug: 'APP_UNHIDE',
807 - name: 'Unhide macOS app',
808 - description: 'Show/unhide a target application.',
809 - inputParams: baseInput.extend({ app: z.string().min(1) }),
810 - args: input => ['app', 'unhide', '--app', input.app],
811 - }),
812 - commandTool({
813 - slug: 'APP_RELAUNCH',
814 - name: 'Relaunch macOS app',
815 - description: 'Quit and relaunch a target application.',
816 - inputParams: baseInput.extend({
817 - app: z.string().min(1),
818 - wait: z.number().nonnegative().optional(),
819 - force: z.boolean().optional(),
820 - waitUntilReady: z.boolean().optional(),
821 - }),
822 - args: input => {
823 - const args = ['app', 'relaunch', input.app];
824 - addOption(args, 'wait', input.wait);
825 - addBooleanFlag(args, 'force', input.force);
826 - addBooleanFlag(args, 'wait-until-ready', input.waitUntilReady);
827 - return args;
828 - },
829 - }),
830 - commandTool({
831 - slug: 'DIALOG',
832 - name: 'Interact with system dialog',
833 - description: 'List, click, input into, select files for, or dismiss system dialogs.',
834 - inputParams: baseInput.extend({
835 - action: z.enum(['list', 'click', 'input', 'file', 'dismiss']),
836 - button: z.string().optional(),
837 - text: z.string().optional(),
838 - field: z.string().optional(),
839 - path: z.string().optional(),
840 - name: z.string().optional(),
841 - select: z.string().optional(),
842 - force: z.boolean().optional(),
843 - }),
844 - args: input => {
845 - const args = ['dialog', input.action];
846 - addOption(args, 'button', input.button);
847 - addOption(args, 'text', input.text);
848 - addOption(args, 'field', input.field);
849 - addOption(args, 'path', input.path);
850 - addOption(args, 'name', input.name);
851 - addOption(args, 'select', input.select);
852 - addBooleanFlag(args, 'force', input.force);
853 - return args;
854 - },
855 - }),
856 - commandTool({
857 - slug: 'DOCK',
858 - name: 'Interact with macOS Dock',
859 - description:
860 - 'List Dock items, launch apps from Dock, right-click items, or show/hide the Dock.',
861 - inputParams: baseInput.extend({
862 - action: z.enum(['list', 'launch', 'right-click', 'hide', 'show']),
863 - app: z.string().optional(),
864 - select: z.string().optional(),
865 - }),
866 - args: input => {
867 - const args = ['dock', input.action];
868 - if (input.action === 'launch' && input.app) args.push(input.app);
869 - if (input.action !== 'launch') addOption(args, 'app', input.app);
870 - addOption(args, 'select', input.select);
871 - return args;
872 - },
873 - }),
874 - commandTool({
875 - slug: 'SPACE',
876 - name: 'Manage macOS Spaces',
877 - description: 'List Spaces, switch Spaces, or move windows between Spaces.',
878 - inputParams: baseInput.extend({
879 - action: z.enum(['list', 'switch', 'move-window']),
880 - to: z.number().int().positive().optional(),
881 - toCurrent: z.boolean().optional(),
882 - ...targetInput,
883 - }),
884 - args: input => {
885 - const args = ['space', input.action];
886 - addOption(args, 'to', input.to);
887 - addBooleanFlag(args, 'to-current', input.toCurrent);
888 - addTargetOptions(args, input);
889 - return args;
890 - },
891 - }),
892 - commandTool({
893 - slug: 'MENUBAR',
894 - name: 'Interact with macOS menu bar items',
895 - description: 'List or click status/menu-bar items by name or index.',
896 - inputParams: baseInput.extend({
897 - action: z.enum(['list', 'click']),
898 - itemName: z.string().optional(),
899 - index: z.number().int().nonnegative().optional(),
900 - includeRawDebug: z.boolean().optional(),
901 - }),
902 - args: input => {
903 - const args = ['menubar', input.action];
904 - if (input.itemName) args.push(input.itemName);
905 - addOption(args, 'index', input.index);
906 - addBooleanFlag(args, 'include-raw-debug', input.includeRawDebug);
907 - return args;
908 - },
909 - }),
910 - commandTool({
911 - slug: 'OPEN',
912 - name: 'Open URL or file',
913 - description: 'Open a URL or local file with its default or specified application.',
914 - inputParams: baseInput.extend({
915 - target: z.string().min(1),
916 - app: z.string().optional(),
917 - bundleId: z.string().optional(),
918 - waitUntilReady: z.boolean().optional(),
919 - noFocus: z.boolean().optional(),
920 - }),
921 - args: input => {
922 - const args = ['open', input.target];
923 - addOption(args, 'app', input.app);
924 - addOption(args, 'bundle-id', input.bundleId);
925 - addBooleanFlag(args, 'wait-until-ready', input.waitUntilReady);
926 - addBooleanFlag(args, 'no-focus', input.noFocus);
927 - return args;
928 - },
929 - }),
930 - commandTool({
931 - slug: 'SLEEP',
932 - name: 'Sleep in Peekaboo flow',
933 - description: 'Pause for a number of milliseconds between GUI actions.',
934 - inputParams: baseInput.extend({ duration: z.number().int().nonnegative() }),
935 - args: input => ['sleep', String(input.duration)],
936 - }),
937 - commandTool({
938 - slug: 'CLEAN',
939 - name: 'Clean Peekaboo caches',
940 - description: 'Prune Peekaboo session cache and temporary files.',
941 - inputParams: baseInput.extend({
942 - allSessions: z.boolean().optional(),
943 - olderThan: z
944 - .number()
945 - .positive()
946 - .optional()
947 - .describe('Remove sessions older than this many hours.'),
948 - session: z.string().optional(),
949 - dryRun: z.boolean().optional(),
950 - }),
951 - args: input => {
952 - const args = ['clean'];
953 - addBooleanFlag(args, 'all-sessions', input.allSessions);
954 - addOption(args, 'older-than', input.olderThan);
955 - addOption(args, 'session', input.session);
956 - addBooleanFlag(args, 'dry-run', input.dryRun);
957 - return args;
958 - },
959 - }),
960 - ],
961 -};
ts/packages/cli-local-tools/src/types.ts deleted
-202
@@ -1,202 +0,0 @@
1 -import type { z } from 'zod/v3';
2 -
3 -export type LocalCliPlatform =
4 - | 'all'
5 - | 'darwin'
6 - | 'linux'
7 - | 'win32'
8 - | 'darwin-arm64'
9 - | 'darwin-x64'
10 - | 'linux-arm64'
11 - | 'linux-x64'
12 - | 'win32-arm64'
13 - | 'win32-x64';
14 -
15 -export type LocalExecutionResult = Record<string, unknown>;
16 -
17 -export interface LocalBundledBinaryTarget {
18 - /** Platform selectors that can use this artifact. */
19 - readonly platforms: ReadonlyArray<LocalCliPlatform>;
20 - /** Path relative to the local-tools bundle root. */
21 - readonly path: string;
22 - /** Mark executable before running. Defaults to true for command binaries. */
23 - readonly executable?: boolean;
24 -}
25 -
26 -export interface LocalBundledBinaryDeclaration {
27 - /** Stable id used by command/FFI declarations, e.g. `peekaboo-cli`. */
28 - readonly id: string;
29 - readonly description?: string;
30 - readonly targets: ReadonlyArray<LocalBundledBinaryTarget>;
31 -}
32 -
33 -export interface LocalBundledBinaryRef {
34 - readonly bundledBinary: string;
35 - /** PATH command or absolute path to use when the bundled artifact is absent. */
36 - readonly fallbackCommand?: string;
37 -}
38 -
39 -export interface LocalExecutionContext {
40 - readonly toolkit: LocalToolkitDeclaration;
41 - readonly tool: LocalToolDeclaration;
42 - readonly finalSlug: string;
43 - readonly platform: LocalCliPlatform;
44 -}
45 -
46 -export interface LocalCommandInvocation {
47 - readonly command: string;
48 - readonly args?: ReadonlyArray<string>;
49 - readonly env?: Record<string, string | undefined>;
50 - readonly cwd?: string;
51 - readonly stdin?: string;
52 - readonly timeoutMs?: number;
53 -}
54 -
55 -export type LocalCommandValue =
56 - | string
57 - | LocalBundledBinaryRef
58 - | LocalCommandInvocation
59 - | (LocalCommandInvocation & LocalBundledBinaryRef);
60 -
61 -export interface LocalCommandExecution {
62 - readonly kind: 'command';
63 - readonly command: LocalCommandValue | ((input: Record<string, unknown>) => LocalCommandValue);
64 - readonly args?:
65 - | ReadonlyArray<string>
66 - | ((input: Record<string, unknown>) => ReadonlyArray<string>);
67 - readonly env?:
68 - | Record<string, string | undefined>
69 - | ((input: Record<string, unknown>) => Record<string, string | undefined>);
70 - readonly cwd?: string | ((input: Record<string, unknown>) => string | undefined);
71 - readonly stdin?: string | ((input: Record<string, unknown>) => string | undefined);
72 - readonly timeoutMs?: number;
73 - /** Parse stdout as JSON when possible. Defaults to false. */
74 - readonly parseJson?: boolean;
75 -}
76 -
77 -export interface LocalNativeExecution {
78 - readonly kind: 'native';
79 - /** Optional prerequisite command used by `composio local-tools doctor` for native wrappers. */
80 - readonly readiness?: LocalCommandInvocation;
81 - readonly execute: (
82 - input: Record<string, unknown>,
83 - context: LocalExecutionContext
84 - ) => Promise<LocalExecutionResult> | LocalExecutionResult;
85 -}
86 -
87 -export interface LocalMcpServerSpec {
88 - readonly command: string;
89 - readonly args?: ReadonlyArray<string>;
90 - readonly env?: Record<string, string | undefined>;
91 - readonly cwd?: string;
92 -}
93 -
94 -export interface LocalMcpExecution {
95 - readonly kind: 'mcp';
96 - readonly server: LocalMcpServerSpec | ((input: Record<string, unknown>) => LocalMcpServerSpec);
97 - /** Tool name to call. If omitted, the wrapper returns `listTools()`. */
98 - readonly toolName?: string | ((input: Record<string, unknown>) => string | undefined);
99 - readonly arguments?:
100 - | Record<string, unknown>
101 - | ((input: Record<string, unknown>) => Record<string, unknown>);
102 -}
103 -
104 -export type LocalFfiType =
105 - | 'char'
106 - | 'uchar'
107 - | 'i8'
108 - | 'u8'
109 - | 'i16'
110 - | 'u16'
111 - | 'i32'
112 - | 'u32'
113 - | 'i64'
114 - | 'u64'
115 - | 'f32'
116 - | 'f64'
117 - | 'bool'
118 - | 'ptr'
119 - | 'cstring'
120 - | 'void';
121 -
122 -export interface LocalFfiSymbolDeclaration {
123 - readonly args: ReadonlyArray<LocalFfiType>;
124 - readonly returns: LocalFfiType;
125 -}
126 -
127 -export interface LocalFfiLibraryHandle {
128 - readonly path: string;
129 - readonly symbols: Record<string, (...args: ReadonlyArray<unknown>) => unknown>;
130 -}
131 -
132 -export interface LocalFfiExecution {
133 - readonly kind: 'ffi';
134 - /** Absolute library path or bundled binary reference for a .dylib/.so/.dll. */
135 - readonly library: string | LocalBundledBinaryRef;
136 - readonly symbols: Record<string, LocalFfiSymbolDeclaration>;
137 - readonly execute: (
138 - input: Record<string, unknown>,
139 - context: LocalExecutionContext,
140 - library: LocalFfiLibraryHandle
141 - ) => Promise<LocalExecutionResult> | LocalExecutionResult;
142 -}
143 -
144 -export type LocalToolExecution =
145 - | LocalCommandExecution
146 - | LocalNativeExecution
147 - | LocalMcpExecution
148 - | LocalFfiExecution;
149 -
150 -export interface LocalToolDeclaration<TInput extends z.ZodTypeAny = z.ZodTypeAny> {
151 - readonly slug: string;
152 - readonly name: string;
153 - readonly description: string;
154 - readonly inputParams: TInput;
155 - readonly outputParams?: z.ZodTypeAny;
156 - readonly platforms: ReadonlyArray<LocalCliPlatform>;
157 - readonly execution: LocalToolExecution;
158 - readonly tags?: ReadonlyArray<string>;
159 -}
160 -
161 -export interface LocalToolkitDeclaration {
162 - readonly slug: string;
163 - readonly name: string;
164 - readonly description: string;
165 - readonly platforms: ReadonlyArray<LocalCliPlatform>;
166 - readonly tools: ReadonlyArray<LocalToolDeclaration>;
167 - readonly bundledBinaries?: ReadonlyArray<LocalBundledBinaryDeclaration>;
168 - readonly source?: {
169 - readonly type: 'cli' | 'mcp' | 'native' | 'ffi';
170 - readonly package?: string;
171 - readonly repository?: string;
172 - readonly command?: string;
173 - };
174 - readonly setup?: {
175 - readonly install?: string;
176 - readonly commandOverrides?: ReadonlyArray<string>;
177 - readonly notes?: ReadonlyArray<string>;
178 - };
179 -}
180 -
181 -export interface LocalToolResolution {
182 - readonly toolkit: LocalToolkitDeclaration;
183 - readonly tool: LocalToolDeclaration;
184 - readonly finalSlug: string;
185 - readonly supported: boolean;
186 - readonly currentPlatform: LocalCliPlatform;
187 -}
188 -
189 -export type LocalToolRouterExperimentalPayload = {
190 - custom_toolkits?: Array<{
191 - slug: string;
192 - name: string;
193 - description: string;
194 - tools: Array<{
195 - slug: string;
196 - name: string;
197 - description: string;
198 - input_schema: Record<string, unknown>;
199 - output_schema?: Record<string, unknown>;
200 - }>;
201 - }>;
202 -};
ts/packages/cli-local-tools/src/zip-fixtures/benign.zip
Binary files a/ts/packages/cli-local-tools/src/zip-fixtures/benign.zip and /dev/null differ
ts/packages/cli-local-tools/src/zip-fixtures/symlink-absolute.zip
Binary files a/ts/packages/cli-local-tools/src/zip-fixtures/symlink-absolute.zip and /dev/null differ
ts/packages/cli-local-tools/src/zip-fixtures/symlink-relative.zip
Binary files a/ts/packages/cli-local-tools/src/zip-fixtures/symlink-relative.zip and /dev/null differ
ts/packages/cli-local-tools/tsconfig.json deleted
-9
@@ -1,9 +0,0 @@
1 -{
2 - "extends": "./tsconfig.src.json",
3 - "compilerOptions": {
4 - "composite": true,
5 - "rootDir": "./src"
6 - },
7 - "include": ["src/**/*.ts"],
8 - "exclude": ["src/**/*.test.ts", "dist"]
9 -}
ts/packages/cli-local-tools/tsconfig.options.json deleted
-23
@@ -1,23 +0,0 @@
1 -{
2 - "$schema": "https://json.schemastore.org/tsconfig",
3 - "extends": "../../../tsconfig.base.json",
4 - "compilerOptions": {
5 - "declaration": true,
6 - "outDir": "./dist",
7 - "rootDir": ".",
8 - "strict": true,
9 - "esModuleInterop": true,
10 - "moduleResolution": "bundler",
11 - "skipLibCheck": true,
12 - "resolveJsonModule": true,
13 - "verbatimModuleSyntax": true,
14 - "pretty": true,
15 - "noImplicitReturns": true,
16 - "noFallthroughCasesInSwitch": true,
17 - "noUnusedLocals": false,
18 - "noUnusedParameters": false,
19 - "types": ["node"]
20 - },
21 - "include": ["src"],
22 - "exclude": ["**/dist", "test/__fixtures__/**"]
23 -}
ts/packages/cli-local-tools/tsconfig.src.json deleted
-13
@@ -1,13 +0,0 @@
1 -{
2 - "$schema": "https://json.schemastore.org/tsconfig",
3 - "extends": "./tsconfig.options.json",
4 - "compilerOptions": {
5 - "outDir": "./dist",
6 - "rootDir": ".",
7 - "paths": {
8 - "src/*": ["./src/*"]
9 - }
10 - },
11 - "include": ["src"],
12 - "exclude": ["src/**/*.test.ts"]
13 -}
ts/packages/cli-local-tools/tsdown.config.ts deleted
-11
@@ -1,11 +0,0 @@
1 -import { defineConfig } from 'tsdown';
2 -import { baseConfig, baseNeverBundle } from '../../../tsdown.config.base.ts';
3 -
4 -export default defineConfig({
5 - ...baseConfig,
6 - tsconfig: 'tsconfig.src.json',
7 - deps: {
8 - ...baseConfig.deps,
9 - neverBundle: [...baseNeverBundle, /^bun:/, /^@composio\/core(\/.*)?$/],
10 - },
11 -});
ts/packages/cli-local-tools/vendor/peekaboo deleted
-1
@@ -1 +0,0 @@
1 -Subproject commit 31e66e8d02656141d18f60bf3b46b24c2b9bc785
ts/packages/cli-local-tools/vendor/platform-imessage deleted
-1
@@ -1 +0,0 @@
1 -Subproject commit a199162cff3f9e0a0c8ef29f271a3238fb87f69f
ts/packages/cli-local-tools/vitest.config.ts deleted
-22
@@ -1,22 +0,0 @@
1 -import { defineConfig } from 'vitest/config';
2 -import path from 'node:path';
3 -
4 -const __dirname = path.resolve(path.dirname(new URL(import.meta.url).pathname));
5 -const coreDir = path.resolve(__dirname, '../core');
6 -
7 -export default defineConfig({
8 - resolve: {
9 - alias: {
10 - '@composio/core/experimental': path.join(coreDir, 'src/experimental/index.ts'),
11 - '@composio/core': path.join(coreDir, 'src/index.ts'),
12 - '#config_defaults': path.join(coreDir, 'src/utils/config-defaults/ConfigDefaults.node.ts'),
13 - '#platform': path.join(coreDir, 'src/platform/node.ts'),
14 - '#files': path.join(coreDir, 'src/models/Files.node.ts'),
15 - '#file_tool_modifier': path.join(coreDir, 'src/utils/modifiers/FileToolModifier.node.ts'),
16 - },
17 - },
18 - test: {
19 - include: ['src/**/*.test.ts', 'scripts/**/*.test.ts'],
20 - exclude: ['vendor/**', 'dist/**', 'node_modules/**'],
21 - },
22 -});
ts/packages/cli/AGENTS.md
+2 -3
@@ -51,7 +51,6 @@ Each command uses `effect/unstable/cli`'s `Command.make()` pattern. Top-level co
51 | `connections` | Alias / helper for connected-account flows |
52 | `orgs` | Manage organizations |
53 | `projects` | Manage projects |
54 -| `local-tools` | Manage local toolkits (via `@composio/cli-local-tools`) |
54 | `logs` | View tool-execution logs (`logs-cmd/`) |
55 | `config` | Read/write CLI config |
56 | `listen` | Listen for events |
@@ -111,7 +110,7 @@ Steps 3–4 (and the TypeScript compiler they need) ship as the `generation-runt
110
111 ### Key Dependencies
112
114 -`effect` (pinned `4.0.0-rc.115`; `@effect/cli` and `@effect/platform` no longer exist as separate packages — folded into `effect`'s barrel and `effect/unstable/{cli,http,process}`), `@effect/platform-bun`, `@effect/vitest` (same exact pin), `@clack/prompts` (terminal UI — stderr by default), `picocolors`, `@composio/client` (owned Composio API client, `2.0.0-rc.8` via the workspace catalog), `@composio/core` (types), `@composio/ts-builders` (AST gen), `@composio/cli-keyring` (OS credential store), `@composio/cli-local-tools` (local toolkit defs), `@composio/json-schema-to-effect-schema`, `semver`, `open`, `extract-zip`.
113 +`effect` (pinned `4.0.0-rc.115`; `@effect/cli` and `@effect/platform` no longer exist as separate packages — folded into `effect`'s barrel and `effect/unstable/{cli,http,process}`), `@effect/platform-bun`, `@effect/vitest` (same exact pin), `@clack/prompts` (terminal UI — stderr by default), `picocolors`, `@composio/client` (owned Composio API client, `2.0.0-rc.8` via the workspace catalog), `@composio/core` (types), `@composio/ts-builders` (AST gen), `@composio/cli-keyring` (OS credential store), `@composio/json-schema-to-effect-schema`, `semver`, `open`, `extract-zip`.
114
115 ## Output Conventions: Composable CLI Output
116
@@ -241,7 +240,7 @@ Use the repo-local `cli-release` skill before building or publishing first-party
240
241 - A push to `next` touching CLI paths publishes a rolling beta automatically.
242 - The normal stable path promotes an existing tested beta through the `promote-stable` workflow action.
244 -- `@composio/cli` and `@composio/cli-local-tools` are ignored by Changesets. Never add a changeset targeting either package; it wedges the TypeScript SDK release action. Put human-facing CLI notes in `CHANGELOG.md` directly.
243 +- `@composio/cli` is ignored by Changesets. Never add a changeset targeting it; it wedges the TypeScript SDK release action. Put human-facing CLI notes in `CHANGELOG.md` directly.
244 - `package.json` uses a private development sentinel and is never a
245 binary-release authority. For an intentional minor or major release,
246 dispatch `build-beta` with its optional version input, verify that beta, then
ts/packages/cli/CHANGELOG.md
+8
@@ -4,6 +4,14 @@
4
5 ### Patch Changes
6
7 +- Remove the experimental local-tools stack: the `local-tools` command group,
8 + the `local_tools` experimental flag, `LOCAL_*` tool execution, `dev native-ui`,
9 + and the bundled macOS sidecars (peekaboo, imessage-cli, composio-native-ui).
10 + Release archives no longer ship `local-tools-binaries/`; `composio upgrade`
11 + and the installer delete one left by an older install. CI no longer installs
12 + Swift. Permission prompts always use the browser approval page. A
13 + stored `local_tools` setting is now listed as an unknown feature and has no
14 + effect.
15 - Every Composio API call now goes through the `@composio/client` 2.0 runtime,
16 the same client `@composio/core` uses. Org, project, session-info, and
17 consumer lookups gain the client's retries and redirect handling, and API
ts/packages/cli/package.json
+1 -2
@@ -35,7 +35,7 @@
35 "generate:toolkit-slugs": "bun run ./scripts/generate-toolkit-slugs.ts",
36 "mock": "bun run ./scripts/copy-mocks-from-cache.ts",
37 "prebuild": "pnpm run typecheck",
38 - "build": "tsdown && bun run ./scripts/copy-local-tools-assets.ts ./dist",
38 + "build": "tsdown",
39 "bin": "./dist/composio",
40 "test": "pnpm run validate:skills && pnpm run validate:boundaries && vitest run",
41 "prepublishOnly": "pnpm run build && pnpm run build:binary",
@@ -67,7 +67,6 @@
67 "@clack/core": "catalog:",
68 "@clack/prompts": "catalog:",
69 "@composio/cli-keyring": "workspace:*",
70 - "@composio/cli-local-tools": "workspace:*",
70 "@composio/client": "catalog:",
71 "@composio/core": "workspace:*",
72 "@composio/json-schema-to-effect-schema": "workspace:*",
ts/packages/cli/scripts/_shared.ts
-28
@@ -69,40 +69,12 @@ export const hostCodexAcpBinaryTargets = (): ReadonlyArray<RunCodexAcpBinaryTarg
69 return hostTarget ? [hostTarget] : [];
70 };
71
72 -export const LOCAL_TOOLS_BINARY_ASSET_DIRNAME = 'local-tools-binaries';
73 -
72 // Kept out of --env: Bun honors only the last --env, which would clobber DEBUG_OVERRIDE_*.
73 export const posthogBakeArgs = (): ReadonlyArray<string> => {
74 const key = process.env.COMPOSIO_POSTHOG_PROJECT_API_KEY?.trim();
75 return key ? ['--define', `COMPOSIO_POSTHOG_PROJECT_API_KEY_BAKED=${JSON.stringify(key)}`] : [];
76 };
77
80 -const localToolsBinaryAssetsSourceDir = (): string =>
81 - path.resolve(process.cwd(), '../cli-local-tools', LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
82 -
83 -const copyLocalToolBinaryAssetsDirectory = async (outputDir: string): Promise<boolean> => {
84 - const sourceDir = localToolsBinaryAssetsSourceDir();
85 - const sourceExists = await stat(sourceDir)
86 - .then(stats => stats.isDirectory())
87 - .catch(() => false);
88 - if (!sourceExists) return false;
89 -
90 - const outputAssetDir = path.join(outputDir, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
91 - await rm(outputAssetDir, { force: true, recursive: true });
92 - await copyDirectoryRecursive(sourceDir, outputAssetDir);
93 - return true;
94 -};
95 -
96 -export const copyLocalToolBinaryAssets = (outputDir: string) =>
97 - Effect.gen(function* () {
98 - const copied = yield* Effect.tryPromise(() => copyLocalToolBinaryAssetsDirectory(outputDir));
99 - if (copied) {
100 - yield* Effect.logDebug(
101 - `Copied local tool binary assets into ${path.join(outputDir, LOCAL_TOOLS_BINARY_ASSET_DIRNAME)}`
102 - );
103 - }
104 - });
105 -
78 const isAllowedRuntimeSpecifier = (specifier: string): boolean =>
79 specifier.startsWith('.') ||
80 specifier.startsWith('/') ||
ts/packages/cli/scripts/build-all-binaries.ts
+1 -8
@@ -16,12 +16,7 @@ import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, Referen
16 import { ChildProcess as Command } from 'effect/unstable/process';
17 import * as BunServices from '@effect/platform-bun/BunServices';
18 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
19 -import {
20 - buildCompanionModules,
21 - copyLocalToolBinaryAssets,
22 - posthogBakeArgs,
23 - teardown,
24 -} from './_shared';
19 +import { buildCompanionModules, posthogBakeArgs, teardown } from './_shared';
20 import { BinaryBuildError } from './build-error';
21 import { buildCliReleaseVersionDefineArgs } from '../src/utils/cli-release-version';
22
@@ -97,8 +92,6 @@ export function buildAllBinaries() {
92 yield* Console.log(`\nBuilding run companion modules in ${companionOutputDir}...`);
93 yield* buildCompanionModules(companionOutputDir);
94
100 - yield* copyLocalToolBinaryAssets('./dist/binaries');
101 -
95 yield* Console.log(`\nAll ${TARGETS.length} binaries built successfully.`);
96 });
97 }
ts/packages/cli/scripts/build-binary-cross.ts
+1 -7
@@ -19,12 +19,7 @@ import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, Referen
19 import { ChildProcess as Command } from 'effect/unstable/process';
20 import * as BunServices from '@effect/platform-bun/BunServices';
21 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
22 -import {
23 - buildCompanionModules,
24 - copyLocalToolBinaryAssets,
25 - posthogBakeArgs,
26 - teardown,
27 -} from './_shared';
22 +import { buildCompanionModules, posthogBakeArgs, teardown } from './_shared';
23 import { BinaryBuildError } from './build-error';
24 import { buildCliReleaseVersionDefineArgs } from '../src/utils/cli-release-version';
25
@@ -117,7 +112,6 @@ export function buildBinaryCross() {
112
113 const companionOutputDir = './dist/binaries/companions';
114 yield* buildCompanionModules(companionOutputDir);
120 - yield* copyLocalToolBinaryAssets('./dist/binaries');
115
116 yield* Console.log(`Binary cross-compiled: ${outfile}`);
117 });
ts/packages/cli/scripts/build-binary.ts
+1 -11
@@ -3,12 +3,7 @@ import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, Referen
3 import { ChildProcess as Command } from 'effect/unstable/process';
4 import * as BunServices from '@effect/platform-bun/BunServices';
5 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
6 -import {
7 - buildCompanionModules,
8 - copyLocalToolBinaryAssets,
9 - posthogBakeArgs,
10 - teardown,
11 -} from './_shared';
6 +import { buildCompanionModules, posthogBakeArgs, teardown } from './_shared';
7 import { BinaryBuildError } from './build-error';
8 import { buildCliReleaseVersionDefineArgs } from '../src/utils/cli-release-version';
9
@@ -88,11 +83,6 @@ export function buildBinary() {
83 yield* buildCompanionModules('./dist');
84
85 yield* Effect.logDebug('', 'Companion modules built successfully');
91 -
92 - // Copy local-tool executable/library assets next to the standalone CLI so
93 - // command and FFI local tools can resolve platform-specific bundled binaries
94 - // at runtime.
95 - yield* copyLocalToolBinaryAssets('./dist');
86 });
87 }
88
ts/packages/cli/scripts/copy-local-tools-assets.ts deleted
-15
@@ -1,15 +0,0 @@
1 -#!/usr/bin/env bun
2 -
3 -import process from 'node:process';
4 -import { Effect } from 'effect';
5 -import * as BunServices from '@effect/platform-bun/BunServices';
6 -import * as BunRuntime from '@effect/platform-bun/BunRuntime';
7 -import { copyLocalToolBinaryAssets, teardown } from './_shared';
8 -
9 -const outputDir = process.argv[2] ?? './dist';
10 -
11 -copyLocalToolBinaryAssets(outputDir).pipe(
12 - Effect.provide(BunServices.layer),
13 - Effect.scoped,
14 - BunRuntime.runMain({ teardown })
15 -);
ts/packages/cli/scripts/package-binaries.ts
+1 -8
@@ -18,7 +18,7 @@ import process from 'node:process';
18 import { Config, ConfigProvider, Console, Effect, Logger, Layer, References } from 'effect';
19 import * as BunServices from '@effect/platform-bun/BunServices';
20 import * as BunRuntime from '@effect/platform-bun/BunRuntime';
21 -import { LOCAL_TOOLS_BINARY_ASSET_DIRNAME, teardown } from './_shared';
21 +import { teardown } from './_shared';
22 import { $ } from 'bun';
23 import { readdir, stat, writeFile } from 'node:fs/promises';
24 import path from 'node:path';
@@ -34,7 +34,6 @@ import {
34
35 const BINARIES_DIR = './dist/binaries';
36 const COMPANIONS_DIR = path.join(BINARIES_DIR, 'companions');
37 -const LOCAL_TOOLS_BINARY_ASSETS_DIR = path.join(BINARIES_DIR, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
37 const RELEASE_TAG = process.env.RELEASE_TAG?.trim();
38
39 export function packageBinaries() {
@@ -99,12 +98,6 @@ export function packageBinaries() {
98 }
99 await $`cp ${path.join(COMPANIONS_DIR, relativePath)} ${destinationPath}`.quiet();
100 }
102 - const hasLocalToolsBinaryAssets = await stat(LOCAL_TOOLS_BINARY_ASSETS_DIR)
103 - .then(stats => stats.isDirectory())
104 - .catch(() => false);
105 - if (hasLocalToolsBinaryAssets) {
106 - await $`cp -R ${LOCAL_TOOLS_BINARY_ASSETS_DIR} ${path.join(nestedDir, LOCAL_TOOLS_BINARY_ASSET_DIRNAME)}`.quiet();
107 - }
101 if (RELEASE_TAG) {
102 await writeFile(path.join(nestedDir, 'release-tag.txt'), `${RELEASE_TAG}\n`, 'utf8');
103 }
ts/packages/cli/skills-src/composio-cli/reference-schema.ts
-5
@@ -43,7 +43,6 @@ const TOP_LEVEL_COMMANDS = new Set([
43 'execute',
44 'link',
45 'listen',
46 - 'local-tools',
46 'login',
47 'logout',
48 'proxy',
@@ -63,10 +62,6 @@ export const resolveSkillBuildContext = (
62 CLI_EXPERIMENTAL_FEATURES.LISTEN,
63 channel
64 ),
66 - [CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS]: isExperimentalFeatureEnabledByDefault(
67 - CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,
68 - channel
69 - ),
65 ...overrides,
66 },
67 });
ts/packages/cli/src/commands/dev.cmd.ts
-2
@@ -9,7 +9,6 @@ import { authConfigsCmd } from './auth-configs/auth-configs.cmd';
9 import { connectedAccountsCmd } from './connected-accounts/connected-accounts.cmd';
10 import { triggersCmd } from './triggers/triggers.cmd';
11 import { projectsCmd } from './projects/projects.cmd';
12 -import { devNativeUiCmd } from './dev/dev.native-ui.cmd';
12 import { ComposioCliUserConfig, resolveCliConfigPath } from 'src/services/cli-user-config';
13 import { Stdin } from 'src/services/stdin';
14 import { TerminalUI } from 'src/services/terminal-ui';
@@ -30,7 +29,6 @@ export const devSubcommands = [
29 connectedAccountsCmd,
30 triggersCmd,
31 projectsCmd,
33 - devNativeUiCmd,
32 ] as const;
33
34 const describeCurrentMode = (enabled: boolean) =>
ts/packages/cli/src/commands/dev/dev.native-ui.cmd.ts deleted
-78
@@ -1,78 +0,0 @@
1 -import { Command, Flag } from 'effect/unstable/cli';
2 -import { Data, Effect, Option, Predicate } from 'effect';
3 -import { ensureBundledBinaryExecutable } from '@composio/cli-local-tools';
4 -import { spawnDetached } from 'src/services/detached-process';
5 -import { TerminalUI } from 'src/services/terminal-ui';
6 -import { resolveNativeUiBinary } from 'src/services/native-ui-sidecar';
7 -
8 -class NativeUiSetupError extends Data.TaggedError('commands/NativeUiSetupError')<{
9 - readonly message: string;
10 - readonly cause: unknown;
11 -}> {}
12 -
13 -const title = Flag.String('title').pipe(
14 - Flag.withDefault('Composio'),
15 - Flag.withDescription('Title for the native sidecar window.')
16 -);
17 -
18 -const message = Flag.String('message').pipe(
19 - Flag.withDefault('Native UI sidecar scaffold'),
20 - Flag.withDescription('Primary text displayed in the native sidecar window.')
21 -);
22 -
23 -const detail = Flag.String('detail').pipe(
24 - Flag.withDefault('This window is rendered by a Swift sidecar bundled with the CLI.'),
25 - Flag.withDescription('Secondary text displayed in the native sidecar window.')
26 -);
27 -
28 -const timeout = Flag.optional(Flag.String('timeout')).pipe(
29 - Flag.withDescription('Optional auto-close timeout in seconds.')
30 -);
31 -
32 -export const devNativeUiCmd = Command.make('native-ui', { title, message, detail, timeout }).pipe(
33 - Command.withDescription('Open the experimental native macOS UI sidecar.'),
34 - Command.withHandler(({ title, message, detail, timeout }) =>
35 - Effect.gen(function* () {
36 - const ui = yield* TerminalUI;
37 - const resolved = yield* resolveNativeUiBinary;
38 -
39 - if (Predicate.isTagged(resolved, 'unsupported')) {
40 - yield* ui.log.error(
41 - `The native UI sidecar is currently only available on macOS (detected ${resolved.platform}).`
42 - );
43 - return;
44 - }
45 -
46 - if (Predicate.isTagged(resolved, 'missing')) {
47 - yield* ui.log.error('The native UI sidecar binary was not found.');
48 - yield* ui.log.step(
49 - `Build it with: pnpm --filter @composio/cli-local-tools build:composio-native-ui -- --target ${resolved.platform}`
50 - );
51 - yield* ui.log.step(`Checked: ${resolved.candidates.join(', ')}`);
52 - return;
53 - }
54 -
55 - yield* Effect.tryPromise({
56 - try: () => ensureBundledBinaryExecutable(resolved.binaryPath),
57 - catch: cause =>
58 - new NativeUiSetupError({
59 - message: `Failed to make the native UI sidecar binary executable: ${resolved.binaryPath}`,
60 - cause,
61 - }),
62 - });
63 -
64 - const args = ['--title', title, '--message', message, '--detail', detail];
65 - const timeoutValue = Option.getOrUndefined(timeout)?.trim();
66 - if (timeoutValue) {
67 - args.push('--timeout', timeoutValue);
68 - }
69 -
70 - // The sidecar window must outlive the CLI process, so it goes through
71 - // the sanctioned detached-spawn boundary instead of @effect/platform
72 - // Command (whose processes are killed when their scope closes).
73 - yield* spawnDetached(resolved.binaryPath, args);
74 -
75 - yield* ui.log.success('Opened native UI sidecar.');
76 - })
77 - )
78 -);
ts/packages/cli/src/commands/index.ts
-2
@@ -19,7 +19,6 @@ import {
19 import { proxyCmd } from './proxy.cmd';
20 import { artifactsCmd } from './artifacts.cmd';
21 import { installCmd } from './install.cmd';
22 -import { localToolsCmd } from './local-tools/local-tools.cmd';
22 import { generateCmd } from './generate/generate.cmd';
23 import { buildDevCommand } from './dev.cmd';
24 import {
@@ -73,7 +72,6 @@ const ROOT_COMMANDS = [
72 tagged(proxyCmd),
73 tagged(artifactsCmd),
74 tagged(installCmd),
76 - experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, localToolsCmd),
75 tagged(rootToolsCmd),
76 tagged(rootTriggersCmd),
77 tagged(rootToolsCmd$Search),
ts/packages/cli/src/commands/local-tools/commands/local-tools.configure.cmd.ts deleted
-220
@@ -1,220 +0,0 @@
1 -import { Argument, Command, Flag } from 'effect/unstable/cli';
2 -import {
3 - getLocalToolsMetaPath,
4 - isLocalToolkitSlug,
5 - resolveLocalTool,
6 - updateLocalToolkitMeta,
7 - updateLocalToolMeta,
8 - type LocalToolMetaEntry,
9 -} from '@composio/cli-local-tools';
10 -import { Data, Effect, Option, Predicate } from 'effect';
11 -import { TerminalUI } from 'src/services/terminal-ui';
12 -import { bold, gray } from 'src/ui/colors';
13 -
14 -const selector = Argument.String('selector').pipe(
15 - Argument.withDescription('Local toolkit slug or LOCAL_* tool slug to configure')
16 -);
17 -
18 -const command = Flag.String('command').pipe(
19 - Flag.optional,
20 - Flag.withDescription('Override the local binary/launcher command')
21 -);
22 -
23 -const disable = Flag.Boolean('disable').pipe(
24 - Flag.withDefault(false),
25 - Flag.withDescription('Disable this local toolkit/tool')
26 -);
27 -
28 -const enable = Flag.Boolean('enable').pipe(
29 - Flag.withDefault(false),
30 - Flag.withDescription('Enable this local toolkit/tool by clearing disabled=false')
31 -);
32 -
33 -const authenticated = Flag.Boolean('authenticated').pipe(
34 - Flag.withDefault(false),
35 - Flag.withDescription('Mark this local toolkit/tool as authenticated in metadata')
36 -);
37 -
38 -const unauthenticated = Flag.Boolean('unauthenticated').pipe(
39 - Flag.withDefault(false),
40 - Flag.withDescription('Mark this local toolkit/tool as unauthenticated in metadata')
41 -);
42 -
43 -const json = Flag.Boolean('json').pipe(
44 - Flag.withDefault(false),
45 - Flag.withDescription('Print the updated metadata entry as JSON')
46 -);
47 -
48 -type ConfigureTarget =
49 - | {
50 - readonly kind: 'toolkit';
51 - readonly key: string;
52 - readonly label: string;
53 - }
54 - | {
55 - readonly kind: 'tool';
56 - readonly key: string;
57 - readonly label: string;
58 - readonly toolkitSlug: string;
59 - };
60 -
61 -export class LocalToolsConfigureError extends Data.TaggedError(
62 - 'commands/local-tools/LocalToolsConfigureError'
63 -)<{
64 - readonly message: string;
65 - readonly target: ConfigureTarget;
66 - readonly cause: unknown;
67 -}> {}
68 -
69 -const errorMessage = (error: unknown): string =>
70 - Predicate.isError(error) ? error.message : String(error);
71 -
72 -/**
73 - * Business-level validation failure for `local-tools configure` inputs
74 - * (unknown selector, conflicting/empty flag combinations) that are only
75 - * knowable after parsing. See the analogous comment on `LinkInputError` in
76 - * `connected-accounts.link.cmd.ts` for why this is a plain typed domain
77 - * error rather than a `CliError.InvalidValue` in v4.
78 - */
79 -class LocalToolsConfigureInputError extends Data.TaggedError(
80 - 'commands/local-tools/LocalToolsConfigureInputError'
81 -)<{
82 - readonly message: string;
83 -}> {}
84 -
85 -const invalidValue = (message: string) => new LocalToolsConfigureInputError({ message });
86 -
87 -const resolveTarget = (value: string): ConfigureTarget | null => {
88 - const localTool = resolveLocalTool(value, { includeUnsupported: true });
89 - if (localTool) {
90 - return {
91 - kind: 'tool',
92 - key: localTool.finalSlug,
93 - label: localTool.finalSlug,
94 - toolkitSlug: localTool.toolkit.slug,
95 - };
96 - }
97 -
98 - if (isLocalToolkitSlug(value)) {
99 - return {
100 - kind: 'toolkit',
101 - key: value.toLowerCase(),
102 - label: value.toUpperCase(),
103 - };
104 - }
105 -
106 - return null;
107 -};
108 -
109 -const buildPatch = (params: {
110 - readonly command: Option.Option<string>;
111 - readonly disable: boolean;
112 - readonly enable: boolean;
113 - readonly authenticated: boolean;
114 - readonly unauthenticated: boolean;
115 -}): LocalToolMetaEntry | { readonly error: string } => {
116 - if (params.disable && params.enable) {
117 - return { error: 'Pass only one of --disable or --enable.' };
118 - }
119 - if (params.authenticated && params.unauthenticated) {
120 - return { error: 'Pass only one of --authenticated or --unauthenticated.' };
121 - }
122 -
123 - const commandOverride = Option.getOrUndefined(params.command)?.trim();
124 - const hasCommandOverride = commandOverride !== undefined && commandOverride.length > 0;
125 - const hasChanges =
126 - hasCommandOverride ||
127 - params.disable ||
128 - params.enable ||
129 - params.authenticated ||
130 - params.unauthenticated;
131 - if (!hasChanges) {
132 - return {
133 - error:
134 - 'Nothing to configure. Pass --command, --enable/--disable, or --authenticated/--unauthenticated.',
135 - };
136 - }
137 -
138 - return {
139 - ...(hasCommandOverride ? { installation: { command: commandOverride } } : {}),
140 - ...(params.disable ? { disabled: true } : {}),
141 - ...(params.enable ? { disabled: false } : {}),
142 - ...(params.authenticated ? { authenticated: true } : {}),
143 - ...(params.unauthenticated ? { authenticated: false } : {}),
144 - };
145 -};
146 -
147 -const formatEntry = (target: ConfigureTarget, entry: LocalToolMetaEntry, metadataPath: string) =>
148 - [
149 - `${bold('Target:')} ${target.kind} ${target.label}`,
150 - `${bold('Path:')} ${metadataPath}`,
151 - `${bold('Command:')} ${entry.installation?.command ?? '-'}`,
152 - `${bold('Disabled:')} ${entry.disabled === undefined ? '-' : String(entry.disabled)}`,
153 - `${bold('Authenticated:')} ${entry.authenticated === undefined ? '-' : String(entry.authenticated)}`,
154 - `${gray('Next:')} run \`composio local-tools doctor --toolkits ${target.kind === 'toolkit' ? target.key : target.toolkitSlug}\``,
155 - ].join('\n');
156 -
157 -export const localToolsCmd$Configure = Command.make(
158 - 'configure',
159 - { selector, command, disable, enable, authenticated, unauthenticated, json },
160 - ({ selector, command, disable, enable, authenticated, unauthenticated, json }) =>
161 - Effect.gen(function* () {
162 - const ui = yield* TerminalUI;
163 - const target = resolveTarget(selector);
164 - if (!target) {
165 - return yield* Effect.fail(
166 - invalidValue(
167 - `Unknown local toolkit/tool "${selector}". Run \`composio local-tools list --all-platforms\` to inspect valid selectors.`
168 - )
169 - );
170 - }
171 -
172 - const patch = buildPatch({ command, disable, enable, authenticated, unauthenticated });
173 - if ('error' in patch) {
174 - return yield* Effect.fail(invalidValue(patch.error));
175 - }
176 -
177 - const metadata = yield* Effect.tryPromise({
178 - try: () =>
179 - target.kind === 'toolkit'
180 - ? updateLocalToolkitMeta(target.key, patch)
181 - : updateLocalToolMeta(target.key, patch),
182 - catch: cause =>
183 - new LocalToolsConfigureError({
184 - message: errorMessage(cause),
185 - target,
186 - cause,
187 - }),
188 - });
189 - const entry =
190 - target.kind === 'toolkit' ? metadata.toolkits[target.key] : metadata.tools[target.key];
191 - if (!entry) {
192 - return yield* Effect.die(
193 - new Error(
194 - `Local tools metadata invariant violated: ${target.kind} ${target.key} was not updated`
195 - )
196 - );
197 - }
198 - const metadataPath = getLocalToolsMetaPath();
199 - const payload = { metadataPath, target, entry };
200 -
201 - if (json) {
202 - yield* ui.output(JSON.stringify(payload, null, 2), { force: true });
203 - return;
204 - }
205 -
206 - yield* ui.log.success(`Updated local ${target.kind} metadata.`);
207 - yield* ui.log.message(formatEntry(target, entry, metadataPath));
208 - })
209 -).pipe(
210 - Command.withDescription(
211 - [
212 - 'Configure local toolkit/tool metadata without hand-editing ~/composio/local_tools.json.',
213 - '',
214 - 'Examples:',
215 - ' composio local-tools configure <toolkit> --command /path/to/tool',
216 - ' composio local-tools configure LOCAL_EXAMPLE_RUN --disable',
217 - ' composio local-tools configure <toolkit> --authenticated --json',
218 - ].join('\n')
219 - )
220 -);
ts/packages/cli/src/commands/local-tools/commands/local-tools.doctor.cmd.ts deleted
-175
@@ -1,175 +0,0 @@
1 -import { Command, Flag } from 'effect/unstable/cli';
2 -import {
3 - checkLocalToolkitsReadiness,
4 - formatSupportedPlatforms,
5 - getLocalToolsMetaPath,
6 - type LocalReadinessStatus,
7 - type LocalToolsReadinessReport,
8 -} from '@composio/cli-local-tools';
9 -import { Data, Effect, Option, Predicate } from 'effect';
10 -import { TerminalUI } from 'src/services/terminal-ui';
11 -import { bold, gray, green, red } from 'src/ui/colors';
12 -import { truncate } from 'src/ui/truncate';
13 -
14 -const json = Flag.Boolean('json').pipe(
15 - Flag.withDefault(false),
16 - Flag.withDescription('Print readiness report as JSON')
17 -);
18 -
19 -const allPlatforms = Flag.Boolean('all-platforms').pipe(
20 - Flag.withDefault(false),
21 - Flag.withDescription('Include local toolkits that are not supported on this CLI platform')
22 -);
23 -
24 -const strict = Flag.Boolean('strict').pipe(
25 - Flag.withDefault(false),
26 - Flag.withDescription('Exit with an error when any visible local tool is not ready')
27 -);
28 -
29 -const toolkits = Flag.String('toolkits').pipe(
30 - Flag.optional,
31 - Flag.withDescription('Filter by local toolkit slugs, comma-separated')
32 -);
33 -
34 -export class LocalToolsDoctorError extends Data.TaggedError(
35 - 'commands/local-tools/LocalToolsDoctorError'
36 -)<{
37 - readonly message: string;
38 - readonly operation: 'check' | 'strict';
39 - readonly notReadyTools: ReadonlyArray<string>;
40 - readonly cause?: unknown;
41 -}> {}
42 -
43 -const errorMessage = (error: unknown): string =>
44 - Predicate.isError(error) ? error.message : String(error);
45 -
46 -const parseToolkitFilter = (value: Option.Option<string>): ReadonlyArray<string> | undefined => {
47 - const raw = Option.getOrUndefined(value);
48 - if (!raw?.trim()) return undefined;
49 - return raw
50 - .split(',')
51 - .map(part => part.trim())
52 - .filter(Boolean);
53 -};
54 -
55 -const statusIcon = (status: LocalReadinessStatus): string => {
56 - switch (status) {
57 - case 'ready':
58 - return green('✓');
59 - case 'unsupported':
60 - return gray('○');
61 - case 'unknown':
62 - return gray('?');
63 - default:
64 - return red('✗');
65 - }
66 -};
67 -
68 -const statusLabel = (status: LocalReadinessStatus): string => {
69 - if (status === 'ready') return green(status);
70 - if (status === 'unsupported' || status === 'unknown') return gray(status);
71 - return red(status);
72 -};
73 -
74 -const notReadyTools = (report: LocalToolsReadinessReport): ReadonlyArray<string> =>
75 - report.toolkits.flatMap(toolkit =>
76 - toolkit.tools
77 - .filter(tool => tool.status !== 'ready' && tool.status !== 'unsupported')
78 - .map(tool => tool.finalSlug)
79 - );
80 -
81 -const formatDoctorReport = (report: LocalToolsReadinessReport, metadataPath: string): string => {
82 - const lines: string[] = [];
83 - lines.push(`${bold('Local tools doctor')} (${report.currentPlatform})`);
84 - lines.push(`${gray('Metadata:')} ${metadataPath}`);
85 -
86 - if (report.toolkits.length === 0) {
87 - lines.push('No registered local toolkits match this platform/filter.');
88 - return lines.join('\n');
89 - }
90 -
91 - for (const toolkit of report.toolkits) {
92 - lines.push('');
93 - lines.push(
94 - `${statusIcon(toolkit.status)} ${bold(toolkit.slug)} ${gray(`(${toolkit.name}; ${statusLabel(toolkit.status)}; ${formatSupportedPlatforms(toolkit.platforms)})`)}`
95 - );
96 - lines.push(` ${gray(truncate(toolkit.description, 96))}`);
97 - for (const message of toolkit.messages) {
98 - lines.push(` ${gray('note:')} ${message}`);
99 - }
100 -
101 - for (const tool of toolkit.tools) {
102 - const command = tool.command
103 - ? tool.command.found
104 - ? `${tool.command.command}${tool.command.path ? gray(` -> ${tool.command.path}`) : ''}`
105 - : `${tool.command.command} ${red('(missing)')}`
106 - : tool.executionKind;
107 - lines.push(
108 - ` ${statusIcon(tool.status)} ${tool.finalSlug.padEnd(36)} ${statusLabel(tool.status).padEnd(15)} ${gray(command)}`
109 - );
110 - for (const message of tool.messages) {
111 - lines.push(` ${gray(message)}`);
112 - }
113 - }
114 -
115 - const hints = [...new Set([...toolkit.hints, ...toolkit.tools.flatMap(tool => tool.hints)])];
116 - for (const hint of hints) {
117 - lines.push(` ${gray('hint:')} ${hint}`);
118 - }
119 - }
120 -
121 - return lines.join('\n');
122 -};
123 -
124 -export const localToolsCmd$Doctor = Command.make(
125 - 'doctor',
126 - { json, allPlatforms, strict, toolkits },
127 - ({ json, allPlatforms, strict, toolkits }) =>
128 - Effect.gen(function* () {
129 - const ui = yield* TerminalUI;
130 - const toolkitFilter = parseToolkitFilter(toolkits);
131 - const metadataPath = getLocalToolsMetaPath();
132 - const report = yield* Effect.tryPromise({
133 - try: () =>
134 - checkLocalToolkitsReadiness({
135 - includeUnsupported: allPlatforms,
136 - toolkits: toolkitFilter,
137 - }),
138 - catch: cause =>
139 - new LocalToolsDoctorError({
140 - message: errorMessage(cause),
141 - operation: 'check',
142 - notReadyTools: [],
143 - cause,
144 - }),
145 - });
146 -
147 - if (json) {
148 - yield* ui.output(JSON.stringify({ metadataPath, ...report }, null, 2), { force: true });
149 - } else {
150 - yield* ui.log.message(formatDoctorReport(report, metadataPath));
151 - }
152 -
153 - if (strict) {
154 - const problems = notReadyTools(report);
155 - if (problems.length > 0) {
156 - return yield* new LocalToolsDoctorError({
157 - message: 'One or more local tools are not ready. Run without --strict for setup hints.',
158 - operation: 'strict',
159 - notReadyTools: problems,
160 - });
161 - }
162 - }
163 - })
164 -).pipe(
165 - Command.withDescription(
166 - [
167 - 'Check whether registered local toolkits have the commands and platform support needed to run.',
168 - '',
169 - 'Examples:',
170 - ' composio local-tools doctor',
171 - ' composio local-tools doctor --json',
172 - ' composio local-tools doctor --toolkits <toolkit> --strict',
173 - ].join('\n')
174 - )
175 -);
ts/packages/cli/src/commands/local-tools/commands/local-tools.list.cmd.ts deleted
-158
@@ -1,158 +0,0 @@
1 -import { Command, Flag } from 'effect/unstable/cli';
2 -import {
3 - detectCliPlatform,
4 - formatSupportedPlatforms,
5 - getLocalToolkitDeclarations,
6 - getLocalToolsMetaPath,
7 - localToolkitDeclarations,
8 - normalizeLocalToolSlug,
9 - supportsCliPlatform,
10 -} from '@composio/cli-local-tools';
11 -import { Effect, Option } from 'effect';
12 -import { TerminalUI } from 'src/services/terminal-ui';
13 -import { bold, gray } from 'src/ui/colors';
14 -import { truncate } from 'src/ui/truncate';
15 -
16 -const json = Flag.Boolean('json').pipe(
17 - Flag.withDefault(false),
18 - Flag.withDescription('Print local tool declarations as JSON')
19 -);
20 -
21 -const allPlatforms = Flag.Boolean('all-platforms').pipe(
22 - Flag.withDefault(false),
23 - Flag.withDescription('Include local toolkits that are not supported on this CLI platform')
24 -);
25 -
26 -const toolkits = Flag.String('toolkits').pipe(
27 - Flag.optional,
28 - Flag.withDescription('Filter by local toolkit slugs, comma-separated')
29 -);
30 -
31 -const parseToolkitFilter = (value: Option.Option<string>): ReadonlyArray<string> | undefined => {
32 - const raw = Option.getOrUndefined(value);
33 - if (!raw?.trim()) return undefined;
34 - return raw
35 - .split(',')
36 - .map(part => part.trim())
37 - .filter(Boolean);
38 -};
39 -
40 -const toolkitMatchesFilter = (
41 - toolkitSlug: string,
42 - toolkitFilter: ReadonlyArray<string> | undefined
43 -): boolean => {
44 - if (!toolkitFilter || toolkitFilter.length === 0) return true;
45 - const allowed = new Set(toolkitFilter.map(slug => slug.toLowerCase()));
46 - return allowed.has(toolkitSlug.toLowerCase());
47 -};
48 -
49 -const buildLocalToolkitRows = (params: {
50 - readonly includeAllPlatforms: boolean;
51 - readonly toolkitFilter?: ReadonlyArray<string>;
52 -}) => {
53 - const currentPlatform = detectCliPlatform();
54 - const sourceToolkits = params.includeAllPlatforms
55 - ? localToolkitDeclarations.filter(toolkit =>
56 - toolkitMatchesFilter(toolkit.slug, params.toolkitFilter)
57 - )
58 - : getLocalToolkitDeclarations({ toolkits: params.toolkitFilter });
59 -
60 - return sourceToolkits.map(toolkit => {
61 - const toolkitSupported = supportsCliPlatform(toolkit.platforms, currentPlatform);
62 - return {
63 - slug: toolkit.slug,
64 - name: toolkit.name,
65 - description: toolkit.description,
66 - platforms: toolkit.platforms,
67 - supported: toolkitSupported,
68 - source: toolkit.source,
69 - tools: toolkit.tools.map(tool => ({
70 - slug: tool.slug,
71 - finalSlug: normalizeLocalToolSlug(tool.slug, toolkit.slug),
72 - name: tool.name,
73 - description: tool.description,
74 - platforms: tool.platforms,
75 - supported: toolkitSupported && supportsCliPlatform(tool.platforms, currentPlatform),
76 - executionKind: tool.execution.kind,
77 - tags: tool.tags ?? [],
78 - })),
79 - };
80 - });
81 -};
82 -
83 -const formatHumanRows = (
84 - rows: ReturnType<typeof buildLocalToolkitRows>,
85 - metaPath: string
86 -): string => {
87 - const lines: string[] = [];
88 - const currentPlatform = detectCliPlatform();
89 - lines.push(`${bold('Local tools')} (${currentPlatform})`);
90 - lines.push(`${gray('Metadata:')} ${metaPath}`);
91 -
92 - if (rows.length === 0) {
93 - lines.push('No registered local toolkits match this platform/filter.');
94 - return lines.join('\n');
95 - }
96 -
97 - for (const toolkit of rows) {
98 - const supportLabel = toolkit.supported ? 'supported' : 'unsupported';
99 - lines.push('');
100 - lines.push(
101 - `${bold(toolkit.slug)} ${gray(`(${toolkit.name}; ${supportLabel}; ${formatSupportedPlatforms(toolkit.platforms)})`)}`
102 - );
103 - lines.push(` ${gray(truncate(toolkit.description, 96))}`);
104 - if (toolkit.source?.repository) {
105 - lines.push(` ${gray('source:')} ${toolkit.source.repository}`);
106 - } else if (toolkit.source?.package) {
107 - lines.push(` ${gray('source:')} ${toolkit.source.package}`);
108 - }
109 -
110 - for (const tool of toolkit.tools) {
111 - const toolSupport = tool.supported ? '' : ` ${gray('(unsupported)')}`;
112 - lines.push(
113 - ` ${tool.finalSlug.padEnd(36)} ${truncate(tool.name, 24).padEnd(24)} ${gray(tool.executionKind)}${toolSupport}`
114 - );
115 - }
116 - }
117 -
118 - return lines.join('\n');
119 -};
120 -
121 -export const localToolsCmd$List = Command.make(
122 - 'list',
123 - { json, allPlatforms, toolkits },
124 - ({ json, allPlatforms, toolkits }) =>
125 - Effect.gen(function* () {
126 - const ui = yield* TerminalUI;
127 - const toolkitFilter = parseToolkitFilter(toolkits);
128 - const rows = buildLocalToolkitRows({
129 - includeAllPlatforms: allPlatforms,
130 - toolkitFilter,
131 - });
132 - const metaPath = getLocalToolsMetaPath();
133 -
134 - const payload = {
135 - currentPlatform: detectCliPlatform(),
136 - metadataPath: metaPath,
137 - toolkits: rows,
138 - };
139 -
140 - if (json) {
141 - yield* ui.output(JSON.stringify(payload, null, 2), { force: true });
142 - return;
143 - }
144 -
145 - yield* ui.log.message(formatHumanRows(rows, metaPath));
146 - })
147 -).pipe(
148 - Command.withDescription(
149 - [
150 - 'List registered local CLI toolkits and tools that can be injected into Tool Router search sessions.',
151 - '',
152 - 'Examples:',
153 - ' composio local-tools list',
154 - ' composio local-tools list --json',
155 - ' composio local-tools list --toolkits <toolkit> --all-platforms',
156 - ].join('\n')
157 - )
158 -);
ts/packages/cli/src/commands/local-tools/commands/local-tools.meta.cmd.ts deleted
-102
@@ -1,102 +0,0 @@
1 -import { Command, Flag } from 'effect/unstable/cli';
2 -import {
3 - createEmptyLocalToolsMeta,
4 - getLocalToolsMetaPath,
5 - readLocalToolsMeta,
6 - writeLocalToolsMeta,
7 -} from '@composio/cli-local-tools';
8 -import { Data, Effect } from 'effect';
9 -import { TerminalUI } from 'src/services/terminal-ui';
10 -import { bold, gray } from 'src/ui/colors';
11 -
12 -class LocalToolsMetaError extends Data.TaggedError('commands/LocalToolsMetaError')<{
13 - readonly message: string;
14 - readonly cause: unknown;
15 -}> {}
16 -
17 -const json = Flag.Boolean('json').pipe(
18 - Flag.withDefault(false),
19 - Flag.withDescription('Print the metadata file contents as JSON')
20 -);
21 -
22 -const init = Flag.Boolean('init').pipe(
23 - Flag.withDefault(false),
24 - Flag.withDescription('Create ~/composio/local_tools.json if it does not exist')
25 -);
26 -
27 -export const localToolsCmd$Meta = Command.make('meta', { json, init }, ({ json, init }) =>
28 - Effect.gen(function* () {
29 - const ui = yield* TerminalUI;
30 - const metadataPath = getLocalToolsMetaPath();
31 - const meta = init
32 - ? yield* Effect.tryPromise({
33 - try: async () => {
34 - const existing = await readLocalToolsMeta();
35 - const next =
36 - Object.keys(existing.tools).length === 0 &&
37 - Object.keys(existing.toolkits).length === 0
38 - ? createEmptyLocalToolsMeta()
39 - : existing;
40 - await writeLocalToolsMeta(next);
41 - return next;
42 - },
43 - catch: cause =>
44 - new LocalToolsMetaError({
45 - message: `Failed to initialize the local tools metadata file at ${metadataPath}.`,
46 - cause,
47 - }),
48 - })
49 - : yield* Effect.tryPromise({
50 - try: () => readLocalToolsMeta(),
51 - catch: cause =>
52 - new LocalToolsMetaError({
53 - message: `Failed to read the local tools metadata file at ${metadataPath}.`,
54 - cause,
55 - }),
56 - });
57 -
58 - const payload = {
59 - metadataPath,
60 - ...meta,
61 - };
62 -
63 - if (json) {
64 - yield* ui.output(JSON.stringify(payload, null, 2), { force: true });
65 - return;
66 - }
67 -
68 - yield* ui.log.message(
69 - [
70 - `${bold('Local tools metadata')}`,
71 - `${gray('Path:')} ${metadataPath}`,
72 - `${gray('Version:')} ${meta.version}`,
73 - `${gray('Toolkits:')} ${Object.keys(meta.toolkits).length}`,
74 - `${gray('Tools:')} ${Object.keys(meta.tools).length}`,
75 - init ? `${gray('Status:')} initialized` : undefined,
76 - '',
77 - 'Use this file for local auth/install state, for example:',
78 - '{',
79 - ' "toolkits": {',
80 - ' "example_toolkit": { "installation": { "command": "/path/to/tool" } }',
81 - ' },',
82 - ' "tools": {',
83 - ' "LOCAL_EXAMPLE_TOOLKIT_RUN": { "authenticated": true }',
84 - ' }',
85 - '}',
86 - ]
87 - .filter((line): line is string => line !== undefined)
88 - .join('\n')
89 - );
90 - })
91 -).pipe(
92 - Command.withDescription(
93 - [
94 - 'Inspect or initialize the local tools metadata file at ~/composio/local_tools.json.',
95 - '',
96 - 'Examples:',
97 - ' composio local-tools meta',
98 - ' composio local-tools meta --init',
99 - ' composio local-tools meta --json',
100 - ].join('\n')
101 - )
102 -);
ts/packages/cli/src/commands/local-tools/local-tools.cmd.ts deleted
-15
@@ -1,15 +0,0 @@
1 -import { Command } from 'effect/unstable/cli';
2 -import { localToolsCmd$Configure } from './commands/local-tools.configure.cmd';
3 -import { localToolsCmd$Doctor } from './commands/local-tools.doctor.cmd';
4 -import { localToolsCmd$List } from './commands/local-tools.list.cmd';
5 -import { localToolsCmd$Meta } from './commands/local-tools.meta.cmd';
6 -
7 -export const localToolsCmd = Command.make('local-tools').pipe(
8 - Command.withDescription('Inspect and configure registered local CLI tools.'),
9 - Command.withSubcommands([
10 - localToolsCmd$List,
11 - localToolsCmd$Doctor,
12 - localToolsCmd$Configure,
13 - localToolsCmd$Meta,
14 - ])
15 -);
ts/packages/cli/src/commands/root-help.ts
+2 -116
@@ -196,26 +196,6 @@ const FULL_COMMANDS: ReadonlyArray<TaggedValue<CompactCommand>> = [
196 full({ name: 'triggers info', description: 'Inspect a trigger type and schema summary' }),
197 full({ name: 'connections list', description: 'Print toolkit connection statuses as JSON' }),
198 full({ name: 'connections remove', description: 'Interactively remove a toolkit connection' }),
199 - full({ name: 'local-tools list', description: 'List registered local CLI toolkits and tools' }, [
200 - CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,
201 - ]),
202 - full(
203 - {
204 - name: 'local-tools doctor',
205 - description: 'Check local toolkit readiness and setup hints',
206 - },
207 - [CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS]
208 - ),
209 - full(
210 - {
211 - name: 'local-tools configure',
212 - description: 'Set local toolkit/tool metadata overrides',
213 - },
214 - [CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS]
215 - ),
216 - full({ name: 'local-tools meta', description: 'Inspect or initialize local tools metadata' }, [
217 - CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,
218 - ]),
199 full({ name: 'generate ts', description: 'Generate TypeScript stubs for selected toolkits' }),
200 full({ name: 'generate py', description: 'Generate Python stubs for selected toolkits' }),
201 full({
@@ -623,100 +603,6 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHel
603 'composio link <toolkit> Reconnect a toolkit account',
604 ],
605 },
626 - 'local-tools': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
627 - usage: 'composio local-tools <list|doctor|configure|meta>',
628 - description:
629 - 'Inspect local CLI tools that the Tool Router can search and execute alongside hosted Composio tools.',
630 - examples: [
631 - 'composio local-tools list',
632 - 'composio local-tools doctor',
633 - 'composio local-tools configure <toolkit> --command /path/to/tool',
634 - ],
635 - seeAlso: [
636 - 'composio local-tools doctor Check installed local tool readiness',
637 - 'composio local-tools meta --init Initialize local tools metadata',
638 - ],
639 - }),
640 - 'local-tools list': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
641 - usage: 'composio local-tools list [--json] [--all-platforms] [--toolkits <text>]',
642 - description:
643 - 'List registered local toolkits and the exact LOCAL_* tool slugs exposed to Tool Router.',
644 - options: [
645 - { name: '--json', description: 'Print structured declarations' },
646 - {
647 - name: '--all-platforms',
648 - description: 'Include unsupported toolkits for the current platform',
649 - },
650 - { name: '--toolkits <text>', description: 'Comma-separated local toolkit slug filter' },
651 - ],
652 - examples: [
653 - 'composio local-tools list',
654 - 'composio local-tools list --json',
655 - 'composio local-tools list --toolkits <toolkit> --all-platforms',
656 - ],
657 - seeAlso: ['composio local-tools meta Inspect local metadata state'],
658 - }),
659 - 'local-tools doctor': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
660 - usage: 'composio local-tools doctor [--json] [--all-platforms] [--toolkits <text>] [--strict]',
661 - description:
662 - 'Check command availability, platform support, and setup hints for registered local toolkits.',
663 - options: [
664 - { name: '--json', description: 'Print structured readiness report' },
665 - {
666 - name: '--all-platforms',
667 - description: 'Include unsupported toolkits for the current platform',
668 - },
669 - { name: '--toolkits <text>', description: 'Comma-separated local toolkit slug filter' },
670 - { name: '--strict', description: 'Exit non-zero if any visible local tool is not ready' },
671 - ],
672 - examples: [
673 - 'composio local-tools doctor',
674 - 'composio local-tools doctor --json',
675 - 'composio local-tools doctor --toolkits <toolkit> --strict',
676 - ],
677 - seeAlso: ['composio local-tools meta Inspect local metadata state'],
678 - }),
679 - 'local-tools configure': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
680 - usage:
681 - 'composio local-tools configure <selector> [--command <text>] [--enable|--disable] [--authenticated|--unauthenticated] [--json]',
682 - description:
683 - 'Configure ~/composio/local_tools.json for a local toolkit slug or LOCAL_* tool slug without hand-editing JSON.',
684 - args: [
685 - {
686 - name: '<selector>',
687 - description: 'Local toolkit slug or LOCAL_* tool slug',
688 - },
689 - ],
690 - options: [
691 - { name: '--command <text>', description: 'Override the local binary/launcher command' },
692 - { name: '--json', description: 'Print the updated metadata entry as JSON' },
693 - ],
694 - flags: [
695 - { name: '--enable', description: 'Clear disabled state' },
696 - { name: '--disable', description: 'Disable this local toolkit/tool' },
697 - { name: '--authenticated', description: 'Mark this local toolkit/tool authenticated' },
698 - { name: '--unauthenticated', description: 'Mark this local toolkit/tool unauthenticated' },
699 - ],
700 - examples: [
701 - 'composio local-tools configure <toolkit> --command /path/to/tool',
702 - 'composio local-tools configure LOCAL_EXAMPLE_RUN --disable',
703 - 'composio local-tools configure <toolkit> --authenticated --json',
704 - ],
705 - seeAlso: ['composio local-tools doctor Validate the configured command'],
706 - }),
707 - 'local-tools meta': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
708 - usage: 'composio local-tools meta [--json] [--init]',
709 - description: 'Inspect or initialize ~/composio/local_tools.json for local auth/install state.',
710 - options: [
711 - { name: '--json', description: 'Print metadata state as JSON' },
712 - { name: '--init', description: 'Create the metadata file if needed' },
713 - ],
714 - examples: [
715 - 'composio local-tools meta',
716 - 'composio local-tools meta --init',
717 - 'composio local-tools meta --json',
718 - ],
719 - }),
606 run: {
607 usage: 'composio run <code> [-- ...args] | run -f <file> [-- ...args]',
608 description:
@@ -1427,13 +1313,13 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHel
1313 usage: 'composio config experimental [<feature>] [on|off]',
1314 description: 'View or toggle experimental feature flags.',
1315 args: [
1430 - { name: '<feature>', description: 'Feature name (e.g., listen, local_tools)' },
1316 + { name: '<feature>', description: 'Feature name (e.g., listen)' },
1317 { name: 'on|off', description: 'Enable or disable the feature' },
1318 ],
1319 examples: [
1320 'composio config experimental # List all features',
1321 'composio config experimental listen # Show current state',
1436 - 'composio config experimental local_tools on # Enable local toolkits',
1322 + 'composio config experimental listen on # Enable listen',
1323 ],
1324 },
1325 'dev logs triggers': {
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+7 -68
@@ -1,5 +1,4 @@
1 import { Argument, Command, Flag } from 'effect/unstable/cli';
2 -import { isLocalToolSlug } from '@composio/cli-local-tools';
2 import util from 'node:util';
3 import { Cause, Data, Effect, Exit, Fiber, HashSet, Option, Result } from 'effect';
4 import { redact } from 'src/ui/redact';
@@ -18,11 +17,7 @@ import {
17 } from 'src/services/tool-input-validation';
18 import { TerminalUI } from 'src/services/terminal-ui';
19 import { logToolDebug, makePerfDebugLogger } from 'src/services/runtime-debug-logger';
21 -import {
22 - LocalToolsDisabledError,
23 - ToolsExecutor,
24 - detectInBandWarning,
25 -} from 'src/services/tools-executor';
20 +import { ToolsExecutor, detectInBandWarning } from 'src/services/tools-executor';
21 import type { ToolExecuteParams, ToolExecuteResponse } from 'src/services/tools-executor';
22 import {
23 ComposioToolkitsRepository,
@@ -64,8 +59,6 @@ import {
59 normalizeCliError,
60 } from 'src/services/composio-error-overrides';
61 import * as constants from 'src/constants';
67 -import { ComposioCliUserConfig } from 'src/services/cli-user-config';
68 -import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
62 import { APP_CONFIG } from 'src/effects/app-config';
63
64 const slug = Argument.String('slug').pipe(
@@ -154,7 +147,6 @@ type ToolExecutionErrorFields = {
147 | 'file_input'
148 | 'connected_account'
149 | 'missing_user_id'
157 - | 'unsupported_local_file'
150 | 'connection_check'
151 | 'execution_failed'
152 | 'parallel_failed';
@@ -1034,47 +1026,8 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
1026 const executor = yield* ToolsExecutor;
1027 const input = (yield* resolveInput(params.data)) ?? '{}';
1028 const parsedArgs = yield* parseArguments(input);
1037 - const cliConfig = yield* ComposioCliUserConfig;
1029 const runOutputDirectory = yield* APP_CONFIG.RUN_OUTPUT_DIR;
1030
1040 - if (
1041 - isLocalToolSlug(params.slug) &&
1042 - !cliConfig.isExperimentalFeatureEnabled(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS)
1043 - ) {
1044 - return yield* new LocalToolsDisabledError({
1045 - toolSlug: params.slug,
1046 - feature: CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,
1047 - message: `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${params.slug}.`,
1048 - });
1049 - }
1050 -
1051 - if (isLocalToolSlug(params.slug)) {
1052 - if (Option.isSome(params.file)) {
1053 - return yield* new ToolExecutionError({
1054 - reason: 'unsupported_local_file',
1055 - toolSlug: params.slug,
1056 - message: '--file is not supported for local tools yet.',
1057 - });
1058 - }
1059 - return {
1060 - ui,
1061 - executor,
1062 - resolvedProject: {
1063 - orgId: 'local',
1064 - projectId: 'local',
1065 - projectType: 'DEVELOPER',
1066 - },
1067 - args: parsedArgs,
1068 - resolvedUserId: 'local',
1069 - selectedConnectedAccountId: undefined,
1070 - executeOutputDir: runOutputDirectory,
1071 - executeParams: {
1072 - userId: 'local',
1073 - arguments: parsedArgs,
1074 - },
1075 - } satisfies ResolvedExecuteContext;
1076 - }
1077 -
1031 const resolvedProject = yield* resolveCommandProject({
1032 mode: params.projectMode,
1033 projectName:
@@ -1111,9 +1064,10 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
1064 orgId: resolvedProject.orgId,
1065 projectId: resolvedProject.projectId,
1066 });
1114 - const toolkitSlug = isLocalToolSlug(params.slug)
1115 - ? undefined
1116 - : yield* toolkitFromToolSlug(params.slug, toolkitProjectScope(resolvedProject));
1067 + const toolkitSlug = yield* toolkitFromToolSlug(
1068 + params.slug,
1069 + toolkitProjectScope(resolvedProject)
1070 + );
1071 const selectedConnectedAccountId = yield* resolveConnectedAccountForToolkit({
1072 client,
1073 toolkitSlug,
@@ -1212,7 +1166,6 @@ const runConnectedToolkitFailFast = (params: {
1166 return;
1167 }
1168 if (params.resolvedProject.projectType !== 'CONSUMER') return;
1215 - if (isLocalToolSlug(params.slug)) return;
1169
1170 yield* perfDebugLog('execute.connected_toolkits.refresh_start', {
1171 slug: params.slug,
@@ -1323,8 +1276,7 @@ const runExecuteWithSpinner = (params: {
1276 readonly skipChecks: boolean;
1277 }) =>
1278 Effect.gen(function* () {
1326 - const verificationDisabled =
1327 - params.skipChecks || params.skipToolParamsCheck || isLocalToolSlug(params.slug);
1279 + const verificationDisabled = params.skipChecks || params.skipToolParamsCheck;
1280 const cachedDefinition = verificationDisabled
1281 ? null
1282 : yield* getCachedToolInputDefinition(params.slug);
@@ -1554,19 +1506,7 @@ const runExecuteWithSpinner = (params: {
1506
1507 const runToolsExecute = (params: RunToolsExecuteParams) =>
1508 Effect.gen(function* () {
1557 - if (!isLocalToolSlug(params.slug) && !(yield* requireAuth)) return;
1558 -
1559 - const cliConfig = yield* ComposioCliUserConfig;
1560 - if (
1561 - isLocalToolSlug(params.slug) &&
1562 - !cliConfig.isExperimentalFeatureEnabled(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS)
1563 - ) {
1564 - return yield* new LocalToolsDisabledError({
1565 - toolSlug: params.slug,
1566 - feature: CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,
1567 - message: `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${params.slug}.`,
1568 - });
1569 - }
1509 + if (!(yield* requireAuth)) return;
1510
1511 if (params.getSchema) {
1512 const context = yield* resolveSchemaContext(params);
@@ -1840,7 +1780,6 @@ const checkConnectedToolkitOrFail = (params: {
1780 Effect.gen(function* () {
1781 if (params.skipConnectionCheck || params.skipChecks) return;
1782 if (params.resolvedProject.projectType !== 'CONSUMER') return;
1843 - if (isLocalToolSlug(params.slug)) return;
1783
1784 yield* refreshConsumerConnectedToolkitsCache({
1785 orgId: params.resolvedProject.orgId,
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+12 -18
@@ -1,5 +1,4 @@
1 import { Argument, Command, Flag } from 'effect/unstable/cli';
2 -import { isLocalToolkitSlug } from '@composio/cli-local-tools';
2 import type { SessionSearchResponse } from '@composio/client/resources/tool-router';
3 import { Data, Effect, Option } from 'effect';
4 import { TerminalUI } from 'src/services/terminal-ui';
@@ -147,7 +146,7 @@ const buildSearchNextSteps = (params: {
146 rootOnly: boolean;
147 }) => {
148 const steps: Array<{ action: string; command: string }> = [];
150 - if (params.firstToolkit && !isLocalToolkitSlug(params.firstToolkit)) {
149 + if (params.firstToolkit) {
150 steps.push({
151 action: 'Link a user account',
152 command: params.rootOnly
@@ -360,24 +359,19 @@ const runToolsSearch = (params: {
359 consumerUserId: resolvedUserId.value,
360 });
361 }
363 - const { sessionId, localExperimentalPayload } = yield* resolveToolRouterSession(
364 - client,
365 - resolvedUserId.value,
366 - {
367 - toolkits: toolkitList,
368 - cacheScope:
369 - resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
370 - ? {
371 - orgId: resolvedProject.orgId,
372 - projectId: resolvedProject.projectId,
373 - consumerUserId: resolvedProject.consumerUserId,
374 - }
375 - : undefined,
376 - }
377 - );
362 + const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
363 + toolkits: toolkitList,
364 + cacheScope:
365 + resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
366 + ? {
367 + orgId: resolvedProject.orgId,
368 + projectId: resolvedProject.projectId,
369 + consumerUserId: resolvedProject.consumerUserId,
370 + }
371 + : undefined,
372 + });
373 const searchPayload = {
374 queries: queries.map(query => ({ use_case: query })),
380 - ...(localExperimentalPayload ? { experimental: localExperimentalPayload } : {}),
375 };
376 const searchResponse = yield* Effect.tryPromise({
377 try: () => client.toolRouter.session.search(sessionId, searchPayload),
ts/packages/cli/src/effects/create-tool-router-session.ts
+9 -62
@@ -1,9 +1,5 @@
1 import { Data, Effect, Option } from 'effect';
2 import type { Composio } from '@composio/client';
3 -import {
4 - createLocalToolRouterExperimentalPayload,
5 - getAllLocalToolkitSlugs,
6 -} from '@composio/cli-local-tools';
3 import {
4 getFreshConsumerToolRouterAuthConfigsFromCache,
5 getFreshConsumerToolRouterConnectedAccountsFromCache,
@@ -13,8 +9,6 @@ import {
9 resolveToolRouterSessionConnections,
10 type ToolRouterSessionConnectionContext,
11 } from 'src/services/tool-router-session-connections';
16 -import { ComposioCliUserConfig } from 'src/services/cli-user-config';
17 -import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
12 import {
13 ENHANCED_LINK_URL_OVERWRITE,
14 getConsumerPermissionSnapshot,
@@ -42,28 +36,15 @@ export interface CreateToolRouterSessionOptions {
36 readonly maxAccountsPerToolkit?: number;
37 readonly requireExplicitSelection?: boolean;
38 };
45 - /** Include bundled local CLI toolkits as Tool Router custom toolkits. Default: true. */
46 - readonly localTools?: {
47 - readonly enable?: boolean;
48 - };
39 }
40
41 export interface CreatedToolRouterSession {
42 readonly sessionId: string;
53 - /** Inline local-tool custom definitions that should be forwarded to v3.1 search/execute calls. */
54 - readonly localExperimentalPayload?: ReturnType<typeof createLocalToolRouterExperimentalPayload>;
43 readonly permissionSnapshot?: ConsumerPermissionSnapshot;
44 readonly connectedAccounts?: Record<string, string>;
45 readonly connectedAccountWordIds?: Record<string, string>;
46 }
47
60 -export class LocalToolRouterDisabledError extends Data.TaggedError(
61 - 'effects/LocalToolRouterDisabledError'
62 -)<{
63 - readonly message: string;
64 - readonly requestedToolkits: ReadonlyArray<string>;
65 -}> {}
66 -
48 export class ToolRouterSessionCreateError extends Data.TaggedError(
49 'effects/ToolRouterSessionCreateError'
50 )<{
@@ -73,7 +54,7 @@ export class ToolRouterSessionCreateError extends Data.TaggedError(
54
55 /**
56 * Create an ephemeral Tool Router session for the given user ID.
76 - * Returns the session id plus any local-tool custom payload bound to the session.
57 + * Returns the session id plus the permission and connected-account context bound to it.
58 *
59 * Accepts a pre-resolved client instance (from ComposioClientSingleton)
60 * so callers can resolve the dependency at layer construction time.
@@ -90,33 +71,6 @@ export const createToolRouterSessionContext = (
71 return Object.keys(merged).length > 0 ? merged : undefined;
72 };
73 const requestedToolkits = options?.toolkits ?? [];
93 - const cliConfig = yield* ComposioCliUserConfig;
94 - const localToolsEnabled =
95 - options?.localTools?.enable ??
96 - cliConfig.isExperimentalFeatureEnabled(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS);
97 - const localToolkitSlugs = new Set(getAllLocalToolkitSlugs());
98 - const requestedLocalToolkits = requestedToolkits.filter(toolkit =>
99 - localToolkitSlugs.has(toolkit.toLowerCase())
100 - );
101 - const remoteToolkits = requestedToolkits.filter(
102 - toolkit => !localToolkitSlugs.has(toolkit.toLowerCase())
103 - );
104 - const shouldIncludeLocalToolkits =
105 - requestedToolkits.length === 0 || requestedLocalToolkits.length > 0;
106 - if (!localToolsEnabled && requestedLocalToolkits.length > 0) {
107 - return yield* Effect.fail(
108 - new LocalToolRouterDisabledError({
109 - message: `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before using toolkit filter(s): ${requestedLocalToolkits.join(', ')}.`,
110 - requestedToolkits: requestedLocalToolkits,
111 - })
112 - );
113 - }
114 - const localExperimentalPayload =
115 - !localToolsEnabled || !shouldIncludeLocalToolkits
116 - ? undefined
117 - : createLocalToolRouterExperimentalPayload({
118 - toolkits: requestedToolkits.length > 0 ? requestedLocalToolkits : undefined,
119 - });
74 const excludedToolkits = new Set(
75 (options?.excludeConnectedAccountsForToolkits ?? []).map(toolkit => toolkit.toLowerCase())
76 );
@@ -147,20 +101,20 @@ export const createToolRouterSessionContext = (
101 ? yield* getFreshConsumerToolRouterAuthConfigsFromCache({
102 orgId: options.cacheScope.orgId,
103 consumerUserId: options.cacheScope.consumerUserId,
150 - toolkits: remoteToolkits.length > 0 ? remoteToolkits : undefined,
104 + toolkits: requestedToolkits.length > 0 ? requestedToolkits : undefined,
105 })
106 : Option.none();
107 const cachedConnectedAccounts = options?.cacheScope
108 ? yield* getFreshConsumerToolRouterConnectedAccountsFromCache({
109 orgId: options.cacheScope.orgId,
110 consumerUserId: options.cacheScope.consumerUserId,
157 - toolkits: remoteToolkits.length > 0 ? remoteToolkits : undefined,
111 + toolkits: requestedToolkits.length > 0 ? requestedToolkits : undefined,
112 })
113 : Option.none();
114
115 const connectionContext = Option.isSome(cachedAuthConfigs)
116 ? {
163 - connectedToolkits: remoteToolkits,
117 + connectedToolkits: requestedToolkits,
118 authConfigs: cachedAuthConfigs.value.authConfigs,
119 connectedAccounts: mergeConnectedAccounts(
120 filterConnectedAccounts(
@@ -175,7 +129,7 @@ export const createToolRouterSessionContext = (
129 : undefined,
130 }
131 : yield* resolveToolRouterSessionConnections(client, userId, {
178 - toolkits: remoteToolkits.length > 0 ? remoteToolkits : undefined,
132 + toolkits: requestedToolkits.length > 0 ? requestedToolkits : undefined,
133 }).pipe(
134 Effect.map(connectionContext => ({
135 ...connectionContext,
@@ -212,13 +166,6 @@ export const createToolRouterSessionContext = (
166 connectedAccountIds,
167 })
168 : undefined;
215 - const experimentalPayload = {
216 - ...(localExperimentalPayload ?? {}),
217 - ...(permissionSnapshot?.enhancedControlsEnabled
218 - ? { link_url_overwrite: ENHANCED_LINK_URL_OVERWRITE }
219 - : {}),
220 - };
221 -
169 return yield* Effect.tryPromise({
170 try: () =>
171 client.toolRouter.session.create({
@@ -233,9 +180,10 @@ export const createToolRouterSessionContext = (
180 require_explicit_selection: options.multiAccount.requireExplicitSelection,
181 }
182 : undefined,
236 - toolkits: remoteToolkits.length > 0 ? { enable: [...remoteToolkits] } : undefined,
237 - experimental:
238 - Object.keys(experimentalPayload).length > 0 ? experimentalPayload : undefined,
183 + toolkits: requestedToolkits.length > 0 ? { enable: [...requestedToolkits] } : undefined,
184 + experimental: permissionSnapshot?.enhancedControlsEnabled
185 + ? { link_url_overwrite: ENHANCED_LINK_URL_OVERWRITE }
186 + : undefined,
187 }),
188 catch: cause =>
189 new ToolRouterSessionCreateError({
@@ -245,7 +193,6 @@ export const createToolRouterSessionContext = (
193 }).pipe(
194 Effect.map((session): CreatedToolRouterSession => ({
195 sessionId: session.session_id,
248 - localExperimentalPayload,
196 permissionSnapshot,
197 connectedAccounts: connectionContext.connectedAccounts,
198 connectedAccountWordIds: resolveConnectedAccountWordIds(
ts/packages/cli/src/experimental-features.ts
-2
@@ -7,7 +7,6 @@
7 */
8 export const CLI_EXPERIMENTAL_FEATURES = {
9 LISTEN: 'listen',
10 - LOCAL_TOOLS: 'local_tools',
10 } as const;
11
12 export const CLI_RELEASE_CHANNELS = ['stable', 'beta'] as const;
@@ -23,7 +22,6 @@ export const isExperimentalFeatureEnabledByDefault = (
22 ) => {
23 switch (feature) {
24 case CLI_EXPERIMENTAL_FEATURES.LISTEN:
26 - case CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS:
25 return channel === 'beta';
26 default:
27 return channel === 'beta';
ts/packages/cli/src/services/native-ui-sidecar.ts deleted
-331
@@ -1,331 +0,0 @@
1 -import * as BunServices from '@effect/platform-bun/BunServices';
2 -import {
3 - Cause,
4 - Config,
5 - Data,
6 - Duration,
7 - Effect,
8 - Exit,
9 - FileSystem,
10 - Option,
11 - Path,
12 - Predicate,
13 - Schema,
14 - Stream,
15 -} from 'effect';
16 -import { ChildProcess, ChildProcessSpawner } from 'effect/unstable/process';
17 -import {
18 - detectCliPlatform,
19 - ensureBundledBinaryExecutable,
20 - getLocalToolsBundleRootCandidates,
21 -} from '@composio/cli-local-tools';
22 -import { UNPREFIXED_CONFIG } from 'src/effects/app-config';
23 -import { loadHostConfig } from 'src/services/config';
24 -
25 -const NATIVE_UI_BINARY_NAME = 'composio-native-ui';
26 -
27 -export type NativeUiPermissionDecision = 'allow_once' | 'allow_session' | 'deny' | 'dismissed';
28 -export type NativeUiCallerAgent = 'claude' | 'codex' | 'openclaw' | 'composio';
29 -
30 -export type NativeUiBinaryResolution =
31 - | {
32 - readonly _tag: 'found';
33 - readonly binaryPath: string;
34 - }
35 - | {
36 - readonly _tag: 'missing';
37 - readonly platform: string;
38 - readonly candidates: ReadonlyArray<string>;
39 - }
40 - | {
41 - readonly _tag: 'unsupported';
42 - readonly platform: string;
43 - };
44 -
45 -export class NativeUiBinarySetupError extends Data.TaggedError(
46 - 'services/NativeUiBinarySetupError'
47 -)<{
48 - readonly binaryPath: string;
49 - readonly cause: unknown;
50 -}> {
51 - override get message(): string {
52 - return `Failed to make the native UI sidecar binary executable: ${this.binaryPath}`;
53 - }
54 -}
55 -
56 -export class NativeUiDecisionMissingError extends Data.TaggedError(
57 - 'services/NativeUiDecisionMissingError'
58 -)<{
59 - readonly binaryPath: string;
60 -}> {
61 - override get message(): string {
62 - return 'Native permission prompt exited without a decision.';
63 - }
64 -}
65 -
66 -/**
67 - * Interactive permission UI (the native sidecar dialog and the browser
68 - * approval page) must never spawn from automated environments. The explicit
69 - * COMPOSIO_DISABLE_PERMISSION_UI knob wins in both directions; without it,
70 - * CI and Vitest runs disable the UI.
71 - */
72 -export const interactivePermissionUiDisabledConfig =
73 - UNPREFIXED_CONFIG.INTERACTIVE_PERMISSION_UI_DISABLED;
74 -
75 -export const isInteractivePermissionUiDisabled: Effect.Effect<boolean> = loadHostConfig(
76 - interactivePermissionUiDisabledConfig
77 -);
78 -
79 -const normalizeCallerAgent = (value?: string): NativeUiCallerAgent | undefined => {
80 - const normalized = value?.toLowerCase().replace(/[^a-z]/g, '');
81 - if (normalized === 'claude' || normalized === 'codex' || normalized === 'openclaw') {
82 - return normalized;
83 - }
84 - return undefined;
85 -};
86 -
87 -const PS_TREE_MAX_DEPTH = 8;
88 -
89 -// Mirrors the former execFileSync('ps', ...) lookup: any spawn failure (or a
90 -// non-zero exit, which leaves stdout empty) resolves to undefined.
91 -const psParentEntry = (
92 - pid: number
93 -): Effect.Effect<string | undefined, never, ChildProcessSpawner.ChildProcessSpawner> =>
94 - Effect.scoped(
95 - Effect.gen(function* () {
96 - // The child never reads interactive input: hand it an immediately-closed
97 - // stdin pipe (EOF), matching the previous `stdio: ['ignore', ...]` spawn.
98 - const handle = yield* ChildProcess.make(
99 - 'ps',
100 - ['-o', 'ppid=', '-o', 'comm=', '-p', String(pid)],
101 - { stdin: Stream.empty, extendEnv: true }
102 - );
103 - const output = yield* Stream.mkString(Stream.decodeText(handle.stdout));
104 - return output.trim();
105 - })
106 - ).pipe(Effect.orElseSucceed(() => undefined));
107 -
108 -const detectCallerAgentFromProcessTree: Effect.Effect<
109 - NativeUiCallerAgent | undefined,
110 - never,
111 - ChildProcessSpawner.ChildProcessSpawner
112 -> = Effect.gen(function* () {
113 - if (process.platform === 'win32') return undefined;
114 -
115 - let pid = process.ppid;
116 - for (let depth = 0; depth < PS_TREE_MAX_DEPTH && pid > 1; depth += 1) {
117 - const output = yield* psParentEntry(pid);
118 - if (output === undefined || output === '') return undefined;
119 -
120 - const match = output.match(/^(\d+)\s+(.+)$/);
121 - if (!match) return undefined;
122 -
123 - const command = match[2]?.toLowerCase() ?? '';
124 - if (command.includes('openclaw') || command.includes('open-claw')) return 'openclaw';
125 - if (command.includes('claude')) return 'claude';
126 - if (command.includes('codex')) return 'codex';
127 -
128 - pid = Number(match[1]);
129 - }
130 -
131 - return undefined;
132 -});
133 -
134 -export type NativeUiCallerAgentSignals = Config.Success<
135 - typeof UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS
136 ->;
137 -
138 -const detectCallerAgentFromSignals = (
139 - signals: NativeUiCallerAgentSignals
140 -): NativeUiCallerAgent | undefined => {
141 - const explicit = normalizeCallerAgent(signals.explicit);
142 - if (explicit) return explicit;
143 -
144 - if (signals.openclaw) return 'openclaw';
145 - if (signals.claude) return 'claude';
146 - if (signals.codex) return 'codex';
147 -
148 - return undefined;
149 -};
150 -
151 -export const detectNativeUiCallerAgentEffect = (
152 - providedSignals?: NativeUiCallerAgentSignals
153 -): Effect.Effect<NativeUiCallerAgent, never, ChildProcessSpawner.ChildProcessSpawner> =>
154 - Effect.gen(function* () {
155 - const signals =
156 - providedSignals ?? (yield* loadHostConfig(UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS));
157 - const fromEnv = detectCallerAgentFromSignals(signals);
158 - if (fromEnv !== undefined) return fromEnv;
159 -
160 - return (yield* detectCallerAgentFromProcessTree) ?? 'composio';
161 - });
162 -
163 -export const detectNativeUiCallerAgent = (): Promise<NativeUiCallerAgent> =>
164 - Effect.runPromise(Effect.provide(detectNativeUiCallerAgentEffect(), BunServices.layer));
165 -
166 -export const resolveNativeUiBinary: Effect.Effect<
167 - NativeUiBinaryResolution,
168 - never,
169 - FileSystem.FileSystem | Path.Path
170 -> = Effect.gen(function* () {
171 - const platform = detectCliPlatform();
172 - if (!platform.startsWith('darwin-')) {
173 - return {
174 - _tag: 'unsupported',
175 - platform,
176 - };
177 - }
178 -
179 - const fs = yield* FileSystem.FileSystem;
180 - const path = yield* Path.Path;
181 -
182 - const candidates = getLocalToolsBundleRootCandidates().map(root =>
183 - path.join(root, NATIVE_UI_BINARY_NAME, platform, NATIVE_UI_BINARY_NAME)
184 - );
185 - const binaryPath = yield* Effect.findFirst(candidates, candidate =>
186 - fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))
187 - );
188 -
189 - return Option.match(binaryPath, {
190 - onNone: (): NativeUiBinaryResolution => ({
191 - _tag: 'missing',
192 - platform,
193 - candidates,
194 - }),
195 - onSome: (binaryPath): NativeUiBinaryResolution => ({
196 - _tag: 'found',
197 - binaryPath,
198 - }),
199 - });
200 -});
201 -
202 -const NativeUiDecisionPayloadSchema = Schema.fromJsonString(
203 - Schema.Struct({ decision: Schema.String })
204 -);
205 -
206 -const parseDecisionPayload = (raw: string): NativeUiPermissionDecision | undefined => {
207 - const decision = Option.getOrUndefined(
208 - Schema.decodeUnknownOption(NativeUiDecisionPayloadSchema)(raw)
209 - )?.decision;
210 - return decision === 'allow_once' ||
211 - decision === 'allow_session' ||
212 - decision === 'deny' ||
213 - decision === 'dismissed'
214 - ? decision
215 - : undefined;
216 -};
217 -
218 -type DialogExit =
219 - | {
220 - readonly _tag: 'exited';
221 - // undefined when the dialog was terminated by a signal, which the
222 - // previous 'exit' handler saw as `code === null` (treated as non-zero).
223 - readonly exitCode: number | undefined;
224 - }
225 - | {
226 - readonly _tag: 'timedOut';
227 - };
228 -
229 -const requestNativeUiPermissionDecisionEffect = (params: {
230 - readonly toolSlug: string;
231 - readonly accountLabel?: string;
232 - readonly timeoutSeconds?: number;
233 -}) =>
234 - Effect.gen(function* () {
235 - if (yield* isInteractivePermissionUiDisabled) return undefined;
236 -
237 - const resolved = yield* resolveNativeUiBinary;
238 - if (!Predicate.isTagged(resolved, 'found')) return undefined;
239 -
240 - yield* Effect.tryPromise({
241 - try: () => ensureBundledBinaryExecutable(resolved.binaryPath),
242 - catch: cause => new NativeUiBinarySetupError({ binaryPath: resolved.binaryPath, cause }),
243 - });
244 -
245 - const fs = yield* FileSystem.FileSystem;
246 - const path = yield* Path.Path;
247 -
248 - // Removed when the surrounding scope closes, replacing the try/finally rm.
249 - const tempDir = yield* fs.makeTempDirectoryScoped({
250 - prefix: 'composio-native-ui-decision-',
251 - });
252 - const callbackFile = path.join(tempDir, 'decision.json');
253 - const timeoutSeconds = params.timeoutSeconds ?? 30;
254 - const callerAgent = yield* detectNativeUiCallerAgentEffect();
255 -
256 - const args = [
257 - '--tool',
258 - params.toolSlug,
259 - '--account',
260 - params.accountLabel ?? 'default connection',
261 - '--caller-agent',
262 - callerAgent,
263 - '--subtitle',
264 - 'Approve once, allow for 1 hour, or deny.',
265 - '--allow-session-label',
266 - 'Allow for 1 hr',
267 - '--callback-file',
268 - callbackFile,
269 - '--timeout',
270 - String(timeoutSeconds),
271 - ];
272 -
273 - // The dialog never reads interactive input: hand it an immediately-closed
274 - // stdin pipe (EOF), matching the previous `stdio: 'ignore'` spawn.
275 - const child = yield* ChildProcess.make(resolved.binaryPath, args, {
276 - stdin: Stream.empty,
277 - extendEnv: true,
278 - });
279 -
280 - // The previous spawn ignored the dialog's output entirely; drain the pipes
281 - // so the dialog can never block on a full pipe buffer.
282 - yield* Effect.forkScoped(Effect.ignore(Stream.runDrain(child.stdout)));
283 - yield* Effect.forkScoped(Effect.ignore(Stream.runDrain(child.stderr)));
284 -
285 - const dialogExit = yield* child.exitCode.pipe(
286 - Effect.map((exitCode): DialogExit => ({ _tag: 'exited', exitCode })),
287 - // exitCode fails when the dialog was terminated by a signal; fold it into
288 - // the signal-termination shape instead of surfacing a PlatformError.
289 - Effect.orElseSucceed((): DialogExit => ({ _tag: 'exited', exitCode: undefined })),
290 - Effect.timeoutOrElse({
291 - duration: Duration.seconds(timeoutSeconds + 5),
292 - orElse: (): Effect.Effect<DialogExit> => Effect.succeed({ _tag: 'timedOut' }),
293 - })
294 - );
295 -
296 - // SIGKILL rather than leaving the scope finalizer's SIGTERM to clean up:
297 - // the finalizer awaits the child's exit, so a dialog that ignored SIGTERM
298 - // would stall this permission gate instead of resolving as dismissed.
299 - if (dialogExit._tag === 'timedOut') {
300 - yield* Effect.ignore(child.kill({ killSignal: 'SIGKILL' }));
301 - return 'dismissed';
302 - }
303 -
304 - // If the sidecar exits without writing a callback file, treat a non-zero
305 - // exit as a dismissal. A zero exit without a callback is unexpected.
306 - const decision = yield* fs.readFileString(callbackFile).pipe(
307 - Effect.map(parseDecisionPayload),
308 - Effect.orElseSucceed(() => undefined)
309 - );
310 - if (decision !== undefined) return decision;
311 -
312 - if (dialogExit.exitCode === 0) {
313 - return yield* new NativeUiDecisionMissingError({ binaryPath: resolved.binaryPath });
314 - }
315 - return 'dismissed';
316 - }).pipe(Effect.scoped);
317 -
318 -export const requestNativeUiPermissionDecision = async (params: {
319 - readonly toolSlug: string;
320 - readonly accountLabel?: string;
321 - readonly timeoutSeconds?: number;
322 -}): Promise<NativeUiPermissionDecision | undefined> => {
323 - const exit = await Effect.runPromiseExit(
324 - Effect.provide(requestNativeUiPermissionDecisionEffect(params), BunServices.layer)
325 - );
326 - if (Exit.isSuccess(exit)) return exit.value;
327 -
328 - // Surface the original error instance (callers recover from any rejection),
329 - // not a FiberFailure wrapper.
330 - throw Cause.squash(exit.cause);
331 -};
ts/packages/cli/src/services/permission-ui.ts new
+110
@@ -0,0 +1,110 @@
1 +import * as BunServices from '@effect/platform-bun/BunServices';
2 +import { Config, Effect, Stream } from 'effect';
3 +import { ChildProcess, ChildProcessSpawner } from 'effect/unstable/process';
4 +import { UNPREFIXED_CONFIG } from 'src/effects/app-config';
5 +import { loadHostConfig } from 'src/services/config';
6 +
7 +export type PermissionCallerAgent = 'claude' | 'codex' | 'openclaw' | 'composio';
8 +
9 +/**
10 + * The browser approval page must never open from automated environments. The
11 + * explicit COMPOSIO_DISABLE_PERMISSION_UI knob wins in both directions; without
12 + * it, CI and Vitest runs disable the UI.
13 + */
14 +export const interactivePermissionUiDisabledConfig =
15 + UNPREFIXED_CONFIG.INTERACTIVE_PERMISSION_UI_DISABLED;
16 +
17 +export const isInteractivePermissionUiDisabled: Effect.Effect<boolean> = loadHostConfig(
18 + interactivePermissionUiDisabledConfig
19 +);
20 +
21 +// Enhanced controls are not offered on Intel Macs (#3421).
22 +export const isEnhancedControlsPlatformSupported = (): boolean =>
23 + !(process.platform === 'darwin' && process.arch === 'x64');
24 +
25 +const normalizeCallerAgent = (value?: string): PermissionCallerAgent | undefined => {
26 + const normalized = value?.toLowerCase().replace(/[^a-z]/g, '');
27 + if (normalized === 'claude' || normalized === 'codex' || normalized === 'openclaw') {
28 + return normalized;
29 + }
30 + return undefined;
31 +};
32 +
33 +const PS_TREE_MAX_DEPTH = 8;
34 +
35 +// Mirrors the former execFileSync('ps', ...) lookup: any spawn failure (or a
36 +// non-zero exit, which leaves stdout empty) resolves to undefined.
37 +const psParentEntry = (
38 + pid: number
39 +): Effect.Effect<string | undefined, never, ChildProcessSpawner.ChildProcessSpawner> =>
40 + Effect.scoped(
41 + Effect.gen(function* () {
42 + // The child never reads interactive input: hand it an immediately-closed
43 + // stdin pipe (EOF), matching the previous `stdio: ['ignore', ...]` spawn.
44 + const handle = yield* ChildProcess.make(
45 + 'ps',
46 + ['-o', 'ppid=', '-o', 'comm=', '-p', String(pid)],
47 + { stdin: Stream.empty, extendEnv: true }
48 + );
49 + const output = yield* Stream.mkString(Stream.decodeText(handle.stdout));
50 + return output.trim();
51 + })
52 + ).pipe(Effect.orElseSucceed(() => undefined));
53 +
54 +const detectCallerAgentFromProcessTree: Effect.Effect<
55 + PermissionCallerAgent | undefined,
56 + never,
57 + ChildProcessSpawner.ChildProcessSpawner
58 +> = Effect.gen(function* () {
59 + if (process.platform === 'win32') return undefined;
60 +
61 + let pid = process.ppid;
62 + for (let depth = 0; depth < PS_TREE_MAX_DEPTH && pid > 1; depth += 1) {
63 + const output = yield* psParentEntry(pid);
64 + if (output === undefined || output === '') return undefined;
65 +
66 + const match = output.match(/^(\d+)\s+(.+)$/);
67 + if (!match) return undefined;
68 +
69 + const command = match[2]?.toLowerCase() ?? '';
70 + if (command.includes('openclaw') || command.includes('open-claw')) return 'openclaw';
71 + if (command.includes('claude')) return 'claude';
72 + if (command.includes('codex')) return 'codex';
73 +
74 + pid = Number(match[1]);
75 + }
76 +
77 + return undefined;
78 +});
79 +
80 +export type PermissionCallerAgentSignals = Config.Success<
81 + typeof UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS
82 +>;
83 +
84 +const detectCallerAgentFromSignals = (
85 + signals: PermissionCallerAgentSignals
86 +): PermissionCallerAgent | undefined => {
87 + const explicit = normalizeCallerAgent(signals.explicit);
88 + if (explicit) return explicit;
89 +
90 + if (signals.openclaw) return 'openclaw';
91 + if (signals.claude) return 'claude';
92 + if (signals.codex) return 'codex';
93 +
94 + return undefined;
95 +};
96 +
97 +export const detectPermissionCallerAgentEffect = (
98 + providedSignals?: PermissionCallerAgentSignals
99 +): Effect.Effect<PermissionCallerAgent, never, ChildProcessSpawner.ChildProcessSpawner> =>
100 + Effect.gen(function* () {
101 + const signals =
102 + providedSignals ?? (yield* loadHostConfig(UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS));
103 + const fromEnv = detectCallerAgentFromSignals(signals);
104 + if (fromEnv !== undefined) return fromEnv;
105 +
106 + return (yield* detectCallerAgentFromProcessTree) ?? 'composio';
107 + });
108 +
109 +export const detectPermissionCallerAgent = (): Promise<PermissionCallerAgent> =>
110 + Effect.runPromise(Effect.provide(detectPermissionCallerAgentEffect(), BunServices.layer));
ts/packages/cli/src/services/run-companion-modules.ts
+1 -1
@@ -597,7 +597,7 @@ const toRepairError = (error: unknown) =>
597 });
598
599 // Self-repair honors the unprefixed GITHUB_* contract (set by CI and the binary
600 -// build workflow, mirrored by cli-local-tools) first, then falls back to the
600 +// build workflow) first, then falls back to the
601 // CLI-wide COMPOSIO_-prefixed spelling installed by cli-main's config provider.
602 //
603 // Built lazily (a function, not a memoized module-level constant): each
ts/packages/cli/src/services/tool-input-validation.ts
+1 -18
@@ -1,7 +1,6 @@
1 import * as FileSystem from 'effect/FileSystem';
2 import * as Path from 'effect/Path';
3 import { Data, Effect, Option, Predicate, Schema, SchemaIssue } from 'effect';
4 -import { getLocalToolInputDefinition } from '@composio/cli-local-tools';
4 import {
5 jsonSchemaToEffectSchema,
6 type JsonSchemaValidationIssue,
@@ -238,25 +237,9 @@ const fetchAndCacheToolInputDefinition = (
237 const path = yield* Path.Path;
238 const repo = yield* ComposioToolkitsRepository;
239 const cacheDir = yield* setupCacheDir;
241 - const localDefinition = getLocalToolInputDefinition(slug);
242 - const schemaPath = toolDefinitionPath(path, cacheDir, localDefinition?.finalSlug ?? slug);
240 + const schemaPath = toolDefinitionPath(path, cacheDir, slug);
241 yield* ensureToolDefinitionsDir(fs, path, cacheDir);
242
245 - if (localDefinition) {
246 - yield* fs.writeFileString(
247 - schemaPath,
248 - serializeCachedToolDefinition({
249 - version: localDefinition.version,
250 - inputSchema: localDefinition.schema,
251 - })
252 - );
253 - return {
254 - schemaPath,
255 - schema: localDefinition.schema,
256 - version: localDefinition.version,
257 - };
258 - }
259 -
243 const [tool, latestVersion] = yield* Effect.all(
244 [
245 repo.getToolDetailed(slug),
ts/packages/cli/src/services/tool-permissions.ts
+15 -30
@@ -3,7 +3,6 @@ import * as FileSystem from 'effect/FileSystem';
3 import * as Path from 'effect/Path';
4 import type { Composio as RawComposioClient } from '@composio/client';
5 import open from 'open';
6 -import { detectCliPlatform } from '@composio/cli-local-tools';
6 import {
7 Data,
8 Effect,
@@ -18,19 +17,14 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
17 import { atomicWriteFileString } from 'src/utils/atomic-write';
18 import { collectDecodedEntries } from 'src/utils/collect-decoded-entries';
19 import {
21 - detectNativeUiCallerAgent,
20 + detectPermissionCallerAgent,
21 + isEnhancedControlsPlatformSupported,
22 isInteractivePermissionUiDisabled,
23 - requestNativeUiPermissionDecision,
24 - type NativeUiCallerAgent,
25 -} from 'src/services/native-ui-sidecar';
23 + type PermissionCallerAgent,
24 +} from 'src/services/permission-ui';
25 import { ComposioClientSingleton, type ClientError } from 'src/services/composio-clients';
26 import { ComposioUserContext } from 'src/services/user-context';
27
29 -const ENHANCED_CONTROLS_UNSUPPORTED_PLATFORMS: ReadonlySet<string> = new Set(['darwin-x64']);
30 -
31 -const isEnhancedControlsPlatformSupported = (): boolean =>
32 - !ENHANCED_CONTROLS_UNSUPPORTED_PLATFORMS.has(detectCliPlatform());
33 -
28 export const ENHANCED_LINK_URL_OVERWRITE = 'https://connect.composio.dev/enhanced';
29
30 const CACHE_FILE_NAME = 'tool-permissions-cache.json';
@@ -648,25 +642,23 @@ const escapeHtml = (value: string): string =>
642 }
643 });
644
651 -// Agent glyphs — same SVGs the macOS sidecar embeds (see
652 -// `ts/packages/cli-local-tools/native/composio-native-ui/Sources/ComposioNativeUI/main.swift`).
653 -// Kept verbatim so the browser fallback shows the same brand mark.
654 -const AGENT_SVGS: Readonly<Record<NativeUiCallerAgent, string>> = {
645 +// Agent glyphs shown next to the caller agent's name on the approval page.
646 +const AGENT_SVGS: Readonly<Record<PermissionCallerAgent, string>> = {
647 composio: `<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#clip0_2367_5)"><path d="M91.7032 28.1801L35.3611 16.6572C31.6669 15.8988 28.1929 18.7367 28.1929 22.5043V49.1954V50.6144V77.3052C28.1929 81.0729 31.6669 83.9112 35.3611 83.1526L91.7032 71.6296" stroke="black" stroke-width="2.8556" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/><path d="M48.1992 7.38531C48.1993 2.09223 53.6097 -1.44765 58.4546 0.57874L58.6851 0.679333L58.6902 0.68227L88.8308 14.6023C91.4759 15.7947 93.1338 18.4366 93.1346 21.3053V33.0975C93.1346 37.3994 89.4707 40.797 85.1902 40.4658L51.0547 37.918V61.8914L85.185 59.3435L85.585 59.323C89.6842 59.2231 93.1331 62.5334 93.109 66.6876V78.4797C93.109 81.3707 91.4075 83.9737 88.8105 85.1812L88.806 85.1827L58.691 99.0774L58.6917 99.0782C53.7808 101.351 48.1992 97.7714 48.1992 92.3759V81.1383C47.9779 81.2256 47.741 81.2834 47.4921 81.3015L30.8347 82.5007C29.4429 82.6007 28.2584 81.4977 28.2582 80.1023V67.7354C28.2583 67.256 28.4014 66.8063 28.6474 66.4277L14.9439 67.4513H14.9388C10.6701 67.7539 7.00001 64.3671 7 60.0823V39.7271C7.00031 35.4239 10.6671 32.0248 14.9491 32.3589H14.9483L28.3486 33.3589C28.2905 33.152 28.2583 32.9345 28.2582 32.7099V19.6826C28.2582 17.7807 29.9597 16.3299 31.8377 16.6304L47.6992 19.168C47.8735 19.1959 48.0404 19.2435 48.1992 19.3059V7.38531ZM85.4075 62.191H85.4023L51.0547 64.755V79.6601L90.2541 71.4669V66.6774L90.2496 66.435C90.1323 63.9438 87.9489 61.9928 85.4075 62.191ZM27.7075 36.1748C27.9471 36.5495 28.0863 36.9936 28.0864 37.4678V62.7813C28.0864 63.0748 28.0314 63.3559 27.9344 63.6169L48.1992 62.1044V37.7043L27.7075 36.1748ZM51.0547 35.0544L85.4023 37.6183L85.4075 37.6191L85.6511 37.6316C88.1632 37.6928 90.279 35.6595 90.279 33.0975V28.1405L51.0547 19.9411V35.0544Z" fill="black"/></g><defs><clipPath id="clip0_2367_5"><rect width="86.4662" height="100" fill="white" transform="translate(7)"/></clipPath></defs></svg>`,
648 claude: `<svg preserveAspectRatio="xMidYMid" viewBox="0 0 256 257" xmlns="http://www.w3.org/2000/svg"><path fill="#D97757" d="m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0 82.05 1.426l4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999-.064.065Z"/></svg>`,
649 codex: `<svg height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M9.064 3.344a4.578 4.578 0 012.285-.312c1 .115 1.891.54 2.673 1.275.01.01.024.017.037.021a.09.09 0 00.043 0 4.55 4.55 0 013.046.275l.047.022.116.057a4.581 4.581 0 012.188 2.399c.209.51.313 1.041.315 1.595a4.24 4.24 0 01-.134 1.223.123.123 0 00.03.115c.594.607.988 1.33 1.183 2.17.289 1.425-.007 2.71-.887 3.854l-.136.166a4.548 4.548 0 01-2.201 1.388.123.123 0 00-.081.076c-.191.551-.383 1.023-.74 1.494-.9 1.187-2.222 1.846-3.711 1.838-1.187-.006-2.239-.44-3.157-1.302a.107.107 0 00-.105-.024c-.388.125-.78.143-1.204.138a4.441 4.441 0 01-1.945-.466 4.544 4.544 0 01-1.61-1.335c-.152-.202-.303-.392-.414-.617a5.81 5.81 0 01-.37-.961 4.582 4.582 0 01-.014-2.298.124.124 0 00.006-.056.085.085 0 00-.027-.048 4.467 4.467 0 01-1.034-1.651 3.896 3.896 0 01-.251-1.192 5.189 5.189 0 01.141-1.6c.337-1.112.982-1.985 1.933-2.618.212-.141.413-.251.601-.33.215-.089.43-.164.646-.227a.098.098 0 00.065-.066 4.51 4.51 0 01.829-1.615 4.535 4.535 0 011.837-1.388zm3.482 10.565a.637.637 0 000 1.272h3.636a.637.637 0 100-1.272h-3.636zM8.462 9.23a.637.637 0 00-1.106.631l1.272 2.224-1.266 2.136a.636.636 0 101.095.649l1.454-2.455a.636.636 0 00.005-.64L8.462 9.23z" fill="url(#lobe-icons-codex-_R_0_)"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-codex-_R_0_" x1="12" x2="12" y1="3" y2="21"><stop stop-color="#B1A7FF"></stop><stop offset=".5" stop-color="#7A9DFF"></stop><stop offset="1" stop-color="#3941FF"></stop></linearGradient></defs></svg>`,
650 openclaw: `<svg viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="openclaw__lobster-gradient" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="#ff4d4d"/><stop offset="100%" stop-color="#991b1b"/></linearGradient></defs><path d="M60 10 C30 10 15 35 15 55 C15 75 30 95 45 100 L45 110 L55 110 L55 100 C55 100 60 102 65 100 L65 110 L75 110 L75 100 C90 95 105 75 105 55 C105 35 90 10 60 10Z" fill="url(#openclaw__lobster-gradient)"/><path d="M20 45 C5 40 0 50 5 60 C10 70 20 65 25 55 C28 48 25 45 20 45Z" fill="url(#openclaw__lobster-gradient)"/><path d="M100 45 C115 40 120 50 115 60 C110 70 100 65 95 55 C92 48 95 45 100 45Z" fill="url(#openclaw__lobster-gradient)"/><path d="M45 15 Q35 5 30 8" stroke="#ff4d4d" stroke-width="3" stroke-linecap="round"/><path d="M75 15 Q85 5 90 8" stroke="#ff4d4d" stroke-width="3" stroke-linecap="round"/><circle cx="45" cy="35" r="6" fill="#050810"/><circle cx="75" cy="35" r="6" fill="#050810"/><circle cx="46" cy="34" r="2.5" fill="#00e5cc"/><circle cx="76" cy="34" r="2.5" fill="#00e5cc"/></svg>`,
651 };
652
661 -const AGENT_DISPLAY_NAMES: Readonly<Record<NativeUiCallerAgent, string>> = {
653 +const AGENT_DISPLAY_NAMES: Readonly<Record<PermissionCallerAgent, string>> = {
654 composio: 'Composio',
655 claude: 'Claude',
656 codex: 'Codex',
657 openclaw: 'OpenClaw',
658 };
659
668 -// 8x8 Bayer matrix encoded as a tiny SVG, matching the sidecar's ordered-dither
669 -// shader. Tiled across the card as a multiply-blended background.
660 +// 8x8 Bayer matrix encoded as a tiny SVG for an ordered-dither texture.
661 +// Tiled across the card as a multiply-blended background.
662 const DITHER_SVG = `<svg xmlns='http://www.w3.org/2000/svg' width='8' height='8'><g fill='%23000' fill-opacity='0.10'>${[
663 [0, 0],
664 [4, 0],
@@ -709,7 +701,7 @@ const approvalHtml = (params: {
701 toolSlug: string;
702 accountLabel?: string;
703 token: string;
712 - agent: NativeUiCallerAgent;
704 + agent: PermissionCallerAgent;
705 }) => {
706 const toolSlug = escapeHtml(params.toolSlug);
707 const account = escapeHtml(params.accountLabel ?? 'default connection');
@@ -717,8 +709,8 @@ const approvalHtml = (params: {
709 const agent = params.agent;
710 const agentName = AGENT_DISPLAY_NAMES[agent];
711 const agentSvg = AGENT_SVGS[agent];
720 - // The sidecar uses "wants to use TOOL" when an agent is detected and falls
721 - // back to "The composio cli wants to execute TOOL" in CLI mode. Mirror it.
712 + // "AGENT wants to use TOOL" when an agent is detected; otherwise
713 + // "The composio cli wants to execute TOOL".
714 const titleBody =
715 agent === 'composio'
716 ? `The composio cli wants to execute <code>${toolSlug}</code>`
@@ -765,8 +757,7 @@ const approvalHtml = (params: {
757 0 18px 50px rgba(0, 0, 0, 0.16),
758 0 2px 6px rgba(0, 0, 0, 0.06);
759 }
768 - /* Dithered Bayer pattern, multiplied beneath the wash — same recipe the
769 - Metal shader uses in the macOS sidecar. */
760 + /* Dithered Bayer pattern, multiplied beneath the wash. */
761 .card::before {
762 content: "";
763 position: absolute;
@@ -983,7 +974,7 @@ const completionHtml = (decision: PermissionDecision) => {
974 const requestPermissionInBrowser = (params: {
975 readonly toolSlug: string;
976 readonly accountLabel?: string;
986 - readonly agent: NativeUiCallerAgent;
977 + readonly agent: PermissionCallerAgent;
978 }): Promise<PermissionDecision> =>
979 new Promise((resolve, reject) => {
980 const token = crypto.randomUUID();
@@ -1072,13 +1063,7 @@ const requestPermissionDecision = async (params: {
1063 );
1064 }
1065
1075 - // Prefer the bundled macOS native sidecar when it is available. The browser
1076 - // prompt remains the cross-platform fallback and is only opened when the
1077 - // native sidecar is missing or fails before returning a decision.
1078 - const nativeDecision = await requestNativeUiPermissionDecision(params).catch(() => undefined);
1079 - if (nativeDecision === 'allow_once' || nativeDecision === 'allow_session') return nativeDecision;
1080 - if (nativeDecision === 'deny' || nativeDecision === 'dismissed') return 'deny';
1081 - return requestPermissionInBrowser({ ...params, agent: await detectNativeUiCallerAgent() });
1066 + return requestPermissionInBrowser({ ...params, agent: await detectPermissionCallerAgent() });
1067 };
1068
1069 export const gateToolExecution = (params: GateParams) =>
ts/packages/cli/src/services/tools-executor.ts
+10 -53
@@ -1,8 +1,7 @@
1 import * as FileSystem from 'effect/FileSystem';
2 import * as Path from 'effect/Path';
3 -import { Context, Data, Effect, Layer } from 'effect';
3 +import { Context, Effect, Layer } from 'effect';
4 import type { Composio } from '@composio/client';
5 -import { executeLocalToolBySlug, resolveLocalTool } from '@composio/cli-local-tools';
5 import type {
6 SessionExecuteResponse,
7 SessionExecuteMetaResponse,
@@ -25,8 +24,7 @@ import type { NodeProcess } from 'src/services/node-process';
24 import type { ComposioUserContext } from 'src/services/user-context';
25 import type { ComposioToolkitsRepository } from 'src/services/composio-clients';
26 import type { TerminalUI } from 'src/services/terminal-ui';
28 -import { ComposioCliUserConfig } from 'src/services/cli-user-config';
29 -import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
27 +import type { ComposioCliUserConfig } from 'src/services/cli-user-config';
28
29 /**
30 * Parameters accepted by the Tool Router-based executor.
@@ -97,12 +95,6 @@ export interface ToolsExecutor {
95
96 export const ToolsExecutor = Context.Service<ToolsExecutor>('services/ToolsExecutor');
97
100 -export class LocalToolsDisabledError extends Data.TaggedError('services/LocalToolsDisabledError')<{
101 - readonly toolSlug: string;
102 - readonly feature: string;
103 - readonly message: string;
104 -}> {}
105 -
98 /**
99 * Normalize the raw Tool Router response into the shape the CLI commands expect.
100 */
@@ -165,50 +157,17 @@ export const ToolsExecutorLive = Layer.effect(
157 return ToolsExecutor.of({
158 execute: (slug, params) =>
159 Effect.gen(function* () {
168 - const cliConfig = yield* ComposioCliUserConfig;
169 - const localToolResolution = resolveLocalTool(slug, { includeUnsupported: true });
170 - const localToolsEnabled = cliConfig.isExperimentalFeatureEnabled(
171 - CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS
172 - );
173 - if (localToolResolution && !localToolsEnabled) {
174 - return yield* new LocalToolsDisabledError({
175 - toolSlug: slug,
176 - feature: CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,
177 - message: `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${slug}.`,
178 - });
179 - }
180 -
181 - if (localToolResolution) {
182 - const localResult = yield* Effect.tryPromise({
183 - try: () => executeLocalToolBySlug(slug, params.arguments),
184 - catch: cause => cause,
185 - });
186 - if (localResult) {
187 - return {
188 - successful: true,
189 - data: localResult,
190 - error: null,
191 - logId: '',
192 - } satisfies ToolExecuteResponse;
193 - }
194 - }
195 -
160 // Resolved lazily: `get()` walks the project context off disk, and every
161 // caller on the execute path already hands in a client built for the
162 // resolved org/project.
163 const resolvedClient = params.client ?? (yield* clientSingleton.get());
164 // One session per invocation — CLI runs one tool per process.
201 - const {
202 - sessionId,
203 - localExperimentalPayload,
204 - permissionSnapshot,
205 - connectedAccounts,
206 - connectedAccountWordIds,
207 - } = yield* createToolRouterSessionContext(resolvedClient, params.userId, {
208 - manageConnections: true,
209 - connectedAccounts: params.connectedAccounts,
210 - cacheScope: params.cacheScope,
211 - });
165 + const { sessionId, permissionSnapshot, connectedAccounts, connectedAccountWordIds } =
166 + yield* createToolRouterSessionContext(resolvedClient, params.userId, {
167 + manageConnections: true,
168 + connectedAccounts: params.connectedAccounts,
169 + cacheScope: params.cacheScope,
170 + });
171 const toolkitSlug = yield* toolkitFromToolSlug(slug, toolkitProjectScope(params));
172 const permissionGateResult = yield* gateToolExecution({
173 toolSlug: slug,
@@ -261,12 +220,10 @@ export const ToolsExecutorLive = Layer.effect(
220 arguments: normalizedArguments,
221 });
222 }
264 - const executePayload = {
223 + return resolvedClient.toolRouter.session.execute(sessionId, {
224 tool_slug: slug,
225 arguments: normalizedArguments,
267 - ...(localExperimentalPayload ? { experimental: localExperimentalPayload } : {}),
268 - };
269 - return resolvedClient.toolRouter.session.execute(sessionId, executePayload);
226 + });
227 },
228 catch: cause => cause,
229 }
ts/packages/cli/src/services/upgrade-binary.ts
+13 -22
@@ -21,11 +21,7 @@ import { detectPlatform, type PlatformArch } from 'src/effects/detect-platform';
21 import { CompareSemverError, semverComparator } from 'src/effects/compare-semver';
22 import { fetchLatestCliRelease, GitHubRelease } from 'src/effects/resolve-cli-release';
23 import { parseChecksumsText, sha256Hex } from 'src/utils/checksums';
24 -import {
25 - atomicReplaceDirectory,
26 - atomicReplaceFile,
27 - type AtomicReplaceError,
28 -} from 'src/utils/atomic-replace';
24 +import { atomicReplaceFile, type AtomicReplaceError } from 'src/utils/atomic-replace';
25
26 // Note: `node:zlib` does not support Github's zip files
27 import { extractZipSafely } from 'src/utils/extract-zip-safely';
@@ -47,7 +43,9 @@ export class UpgradeBinaryError extends Data.TaggedError('services/UpgradeBinary
43 * CLI binary name constant
44 */
45 export const CLI_BINARY_NAME = 'composio';
50 -const LOCAL_TOOLS_BINARY_ASSET_DIRNAME = 'local-tools-binaries';
46 +// Older releases shipped macOS local-tool sidecars in this directory next to the
47 +// binary. Current archives omit it, so upgrades remove what an old install left.
48 +const LEGACY_LOCAL_TOOLS_DIRNAME = 'local-tools-binaries';
49
50 const getBinaryAssetName = (platformArch: PlatformArch) =>
51 `${CLI_BINARY_NAME}-${platformArch.platform}-${platformArch.arch}.zip`;
@@ -554,12 +552,6 @@ const replaceBinary = (
552 });
553 }
554
557 - const localToolsAssetSource = path.join(sourceDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
558 - const localToolsAssetExists = yield* fs
559 - .exists(localToolsAssetSource)
560 - .pipe(Effect.catch(() => Effect.succeed(false)));
561 - const localToolsAssetTarget = path.join(targetDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
562 -
555 const releaseTag = options.releaseTag;
556 const stagedReleaseTagPath = path.join(sourceDirectory, RUN_COMPANION_RELEASE_TAG_FILENAME);
557 if (releaseTag) {
@@ -600,16 +592,6 @@ const replaceBinary = (
592 );
593 }
594
603 - if (localToolsAssetExists) {
604 - yield* provideFsAndPath(
605 - ctx,
606 - atomicReplaceDirectory({
607 - sourcePath: localToolsAssetSource,
608 - targetPath: localToolsAssetTarget,
609 - })
610 - ).pipe(Effect.mapError(mapAtomicReplaceError('Failed to replace local-tool binary assets')));
611 - }
612 -
595 if (releaseTag) {
596 yield* provideFsAndPath(
597 ctx,
@@ -623,6 +605,15 @@ const replaceBinary = (
605 yield* provideFsAndPath(ctx, atomicReplaceFile({ sourcePath, targetPath, mode: 0o755 })).pipe(
606 Effect.mapError(mapAtomicReplaceError('Failed to replace binary'))
607 );
608 +
609 + const legacyLocalToolsPath = path.join(targetDirectory, LEGACY_LOCAL_TOOLS_DIRNAME);
610 + yield* fs
611 + .remove(legacyLocalToolsPath, { recursive: true, force: true })
612 + .pipe(
613 + Effect.catch(cause =>
614 + Effect.logDebug(`Could not remove obsolete ${legacyLocalToolsPath}: ${String(cause)}`)
615 + )
616 + );
617 });
618
619 /**
ts/packages/cli/src/utils/atomic-replace.ts
-96
@@ -12,11 +12,6 @@ type AtomicReplaceFileOptions = {
12 readonly mode?: number;
13 };
14
15 -type AtomicReplaceDirectoryOptions = {
16 - readonly sourcePath: string;
17 - readonly targetPath: string;
18 -};
19 -
15 export const atomicReplaceFile = ({
16 sourcePath,
17 targetPath,
@@ -50,94 +45,3 @@ export const atomicReplaceFile = ({
45 })
46 )
47 );
53 -
54 -/**
55 - * Replaces a directory with a staged copy using two renames. The old directory
56 - * is restored when publishing the replacement fails. An abrupt process exit
57 - * between the renames can leave the target temporarily absent, with its prior
58 - * contents retained in a same-directory recovery path.
59 - */
60 -export const atomicReplaceDirectory = ({
61 - sourcePath,
62 - targetPath,
63 -}: AtomicReplaceDirectoryOptions): Effect.Effect<
64 - void,
65 - AtomicReplaceError,
66 - FileSystem.FileSystem | Path.Path | Scope.Scope
67 -> =>
68 - Effect.gen(function* () {
69 - const fs = yield* FileSystem.FileSystem;
70 - const path = yield* Path.Path;
71 - const targetDirectory = path.dirname(targetPath);
72 - const stagingDirectory = yield* fs.makeTempDirectoryScoped({
73 - directory: targetDirectory,
74 - prefix: '.composio-atomic-replace-',
75 - });
76 - const targetName = path.basename(targetPath);
77 - const stagedPath = path.join(stagingDirectory, targetName);
78 -
79 - yield* fs.copy(sourcePath, stagedPath);
80 -
81 - if (!(yield* fs.exists(targetPath))) {
82 - yield* fs.rename(stagedPath, targetPath);
83 - return;
84 - }
85 -
86 - yield* Effect.uninterruptible(
87 - Effect.gen(function* () {
88 - const recoveryDirectory = yield* fs.makeTempDirectory({
89 - directory: targetDirectory,
90 - prefix: '.composio-atomic-recovery-',
91 - });
92 - const asidePath = path.join(recoveryDirectory, targetName);
93 - yield* fs
94 - .rename(targetPath, asidePath)
95 - .pipe(
96 - Effect.tapError(() =>
97 - fs.remove(recoveryDirectory, { recursive: true }).pipe(Effect.ignore)
98 - )
99 - );
100 - yield* fs.rename(stagedPath, targetPath).pipe(
101 - Effect.matchEffect({
102 - onSuccess: () =>
103 - fs
104 - .remove(recoveryDirectory, { recursive: true })
105 - .pipe(
106 - Effect.catch(cause =>
107 - Effect.logWarning(
108 - `Published replacement at ${targetPath}; previous contents remain at ${asidePath}: ${String(cause)}`
109 - )
110 - )
111 - ),
112 - onFailure: publishCause =>
113 - fs.rename(asidePath, targetPath).pipe(
114 - Effect.matchEffect({
115 - onSuccess: () =>
116 - fs
117 - .remove(recoveryDirectory, { recursive: true })
118 - .pipe(Effect.andThen(Effect.fail(publishCause))),
119 - onFailure: restoreCause =>
120 - Effect.fail(
121 - new AtomicReplaceError({
122 - targetPath,
123 - message: `Failed to replace directory at ${targetPath}. Previous contents retained at ${asidePath}`,
124 - cause: { publishCause, restoreCause },
125 - })
126 - ),
127 - })
128 - ),
129 - })
130 - );
131 - })
132 - );
133 - }).pipe(
134 - Effect.mapError(cause =>
135 - cause instanceof AtomicReplaceError
136 - ? cause
137 - : new AtomicReplaceError({
138 - targetPath,
139 - message: `Failed to replace directory at ${targetPath}`,
140 - cause,
141 - })
142 - )
143 - );
ts/packages/cli/test/src/cli-main.test.ts
+4 -17
@@ -5,16 +5,12 @@ import { describe, expect, it } from 'vitest';
5 import * as tempy from 'tempy';
6
7 describe('CLI process error handling', () => {
8 - it('prints unreported ToolExecutionError failures and exits non-zero', () => {
8 + it('prints unreported typed execute failures and exits non-zero', () => {
9 const configDirectory = tempy.temporaryDirectory();
10 - fs.writeFileSync(
11 - path.join(configDirectory, 'config.json'),
12 - JSON.stringify({ experimental_features: { local_tools: true } })
13 - );
10 fs.writeFileSync(
11 path.join(configDirectory, 'user_data.json'),
12 JSON.stringify({
17 - api_key: null,
13 + api_key: 'test-api-key',
14 base_url: 'https://backend.composio.dev',
15 web_url: 'https://platform.composio.dev',
16 org_id: null,
@@ -24,16 +20,7 @@ describe('CLI process error handling', () => {
20
21 const result = spawnSync(
22 'bun',
27 - [
28 - 'run',
29 - 'src/bin.ts',
30 - 'execute',
31 - 'LOCAL_PEEKABOO_VERSION',
32 - '--file',
33 - '/tmp/does-not-matter',
34 - '-d',
35 - '{}',
36 - ],
23 + ['run', 'src/bin.ts', 'execute', 'GITHUB_GET_THE_AUTHENTICATED_USER', '-d', '[]'],
24 {
25 cwd: process.cwd(),
26 encoding: 'utf8',
@@ -48,7 +35,7 @@ describe('CLI process error handling', () => {
35
36 expect(result.status).toBe(1);
37 expect(`${result.stdout}\n${result.stderr}`).toContain(
51 - '--file is not supported for local tools yet.'
38 + 'Expected a JSON object for tool arguments'
39 );
40 });
41
ts/packages/cli/test/src/commands/config/config.experimental.cmd.test.ts
+1 -1
@@ -116,7 +116,7 @@ describe('config experimental skill discovery', () => {
116 layer(TestLive())('config experimental state validation', it => {
117 it.effect('reports an invalid state as a structured domain failure', () =>
118 Effect.gen(function* () {
119 - const exit = yield* Effect.exit(cli(['config', 'experimental', 'local_tools', 'sometimes']));
119 + const exit = yield* Effect.exit(cli(['config', 'experimental', 'listen', 'sometimes']));
120
121 expect(Exit.isFailure(exit)).toBe(true);
122 if (Exit.isFailure(exit)) {
ts/packages/cli/test/src/commands/feature-visibility.test.ts
-11
@@ -26,9 +26,7 @@ const getSubcommandNames = (visibility: typeof stableVisibility) =>
26 describe('CLI experimental feature visibility', () => {
27 it('hides experimental root commands from the stable root command graph', () => {
28 expect(getSubcommandNames(stableVisibility)).not.toContain('listen');
29 - expect(getSubcommandNames(stableVisibility)).not.toContain('local-tools');
29 expect(getSubcommandNames(betaVisibility)).toContain('listen');
31 - expect(getSubcommandNames(betaVisibility)).toContain('local-tools');
30 });
31
32 it('hides listen help when the feature is disabled', () => {
@@ -45,15 +43,6 @@ describe('CLI experimental feature visibility', () => {
43 expect(matchCommandFromArgv(['bun', 'composio', 'listen'], betaVisibility)).toBe('listen');
44 expect(getCommandHelpText('listen', stableVisibility)).toBe(undefined);
45 expect(getCommandHelpText('listen', betaVisibility)).toContain('composio listen');
48 -
49 - expect(matchCommandFromArgv(['bun', 'composio', 'local-tools'], stableVisibility)).toBe(
50 - undefined
51 - );
52 - expect(matchCommandFromArgv(['bun', 'composio', 'local-tools'], betaVisibility)).toBe(
53 - 'local-tools'
54 - );
55 - expect(getCommandHelpText('local-tools', stableVisibility)).toBe(undefined);
56 - expect(getCommandHelpText('local-tools', betaVisibility)).toContain('composio local-tools');
46 });
47
48 it('shows stable account selection for execute and proxy', () => {
ts/packages/cli/test/src/commands/local-tools.cmd.test.ts deleted
-141
@@ -1,141 +0,0 @@
1 -import fs from 'node:fs/promises';
2 -import os from 'node:os';
3 -import path from 'node:path';
4 -import { describe, expect, layer } from '@effect/vitest';
5 -import { Cause, Effect, Exit } from 'effect';
6 -import { LocalToolsDoctorError } from 'src/commands/local-tools/commands/local-tools.doctor.cmd';
7 -import { cli, MockConsole, TestLive } from 'test/__utils__';
8 -
9 -const withLocalToolsPath = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
10 - Effect.acquireUseRelease(
11 - Effect.sync(() => {
12 - const previous = process.env.COMPOSIO_LOCAL_TOOLS_PATH;
13 - process.env.COMPOSIO_LOCAL_TOOLS_PATH = path.join(
14 - os.tmpdir(),
15 - `composio-local-tools-${crypto.randomUUID()}.json`
16 - );
17 - return previous;
18 - }),
19 - () => effect,
20 - previous =>
21 - Effect.sync(() => {
22 - if (previous === undefined) {
23 - delete process.env.COMPOSIO_LOCAL_TOOLS_PATH;
24 - } else {
25 - process.env.COMPOSIO_LOCAL_TOOLS_PATH = previous;
26 - }
27 - })
28 - );
29 -
30 -describe('CLI: composio local-tools', () => {
31 - layer(TestLive())(it => {
32 - it.effect('[Given] --json [Then] lists bundled local toolkits', () =>
33 - Effect.gen(function* () {
34 - yield* cli(['local-tools', 'list', '--json', '--all-platforms']);
35 -
36 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
37 - const payload = JSON.parse(lines.at(-1) ?? '') as {
38 - currentPlatform: string;
39 - metadataPath: string;
40 - toolkits: Array<{ slug: string }>;
41 - };
42 -
43 - expect(payload.currentPlatform).toBeTruthy();
44 - expect(payload.metadataPath).toContain('local_tools.json');
45 - expect(payload.toolkits.map(toolkit => toolkit.slug)).toEqual(
46 - expect.arrayContaining(['BEEPER_IMESSAGE', 'CHROME_DEVTOOLS', 'PEEKABOO'])
47 - );
48 - })
49 - );
50 -
51 - it.effect('[Given] doctor --json [Then] reports local toolkit readiness', () =>
52 - Effect.gen(function* () {
53 - yield* cli(['local-tools', 'doctor', '--json', '--all-platforms']);
54 -
55 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
56 - const payload = JSON.parse(lines.at(-1) ?? '') as {
57 - metadataPath: string;
58 - toolkits: Array<{ slug: string }>;
59 - };
60 -
61 - expect(payload.metadataPath).toContain('local_tools.json');
62 - expect(payload.toolkits.map(toolkit => toolkit.slug)).toEqual(
63 - expect.arrayContaining(['BEEPER_IMESSAGE', 'CHROME_DEVTOOLS', 'PEEKABOO'])
64 - );
65 - })
66 - );
67 -
68 - // v4 migration note: this business-level validation (only knowable after parsing) is a
69 - // plain typed domain error (`LocalToolsConfigureInputError`), not a `CliError.InvalidValue`
70 - // — see the migration note above it in `local-tools.configure.cmd.ts`.
71 - it.effect('[Given] an unknown configure selector [Then] reports CLI input validation', () =>
72 - Effect.gen(function* () {
73 - const exit = yield* Effect.exit(
74 - cli(['local-tools', 'configure', 'NOT_A_LOCAL_TOOL', '--disable'])
75 - );
76 -
77 - expect(Exit.isFailure(exit)).toBe(true);
78 - if (Exit.isFailure(exit)) {
79 - const failure = Cause.squash(exit.cause);
80 - expect(failure).toMatchObject({
81 - _tag: 'commands/local-tools/LocalToolsConfigureInputError',
82 - });
83 - }
84 - })
85 - );
86 -
87 - it.effect(
88 - '[Given] strict doctor finds a disabled tool [Then] reports structured readiness',
89 - () =>
90 - withLocalToolsPath(
91 - Effect.gen(function* () {
92 - yield* cli(['local-tools', 'configure', 'CHROME_DEVTOOLS', '--disable']);
93 - const exit = yield* Effect.exit(
94 - cli([
95 - 'local-tools',
96 - 'doctor',
97 - '--toolkits',
98 - 'CHROME_DEVTOOLS',
99 - '--all-platforms',
100 - '--strict',
101 - ])
102 - );
103 -
104 - expect(Exit.isFailure(exit)).toBe(true);
105 - if (Exit.isFailure(exit)) {
106 - const failure = Cause.squash(exit.cause);
107 - expect(failure).toBeInstanceOf(LocalToolsDoctorError);
108 - if (failure instanceof LocalToolsDoctorError) {
109 - expect(failure.operation).toBe('strict');
110 - expect(failure.notReadyTools.length).toBeGreaterThan(0);
111 - }
112 - }
113 - })
114 - )
115 - );
116 -
117 - it.effect('[Given] meta --init --json [Then] writes local metadata file', () =>
118 - withLocalToolsPath(
119 - Effect.gen(function* () {
120 - yield* cli(['local-tools', 'meta', '--init', '--json']);
121 -
122 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
123 - const payload = JSON.parse(lines.at(-1) ?? '') as {
124 - metadataPath: string;
125 - version: number;
126 - toolkits: Record<string, unknown>;
127 - tools: Record<string, unknown>;
128 - };
129 - const file = JSON.parse(
130 - yield* Effect.tryPromise(() => fs.readFile(payload.metadataPath, 'utf8'))
131 - ) as typeof payload;
132 -
133 - expect(payload.version).toBe(1);
134 - expect(payload.toolkits).toEqual({});
135 - expect(payload.tools).toEqual({});
136 - expect(file.version).toBe(1);
137 - })
138 - )
139 - );
140 - });
141 -});
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
-28
@@ -147,34 +147,6 @@ describe('CLI: composio execute', () => {
147 recordedProjectToolkitScopes = [];
148 });
149
150 - layer(
151 - TestLive({
152 - stdin: { isTTY: true, data: '' },
153 - toolsExecutor: {
154 - respondWith: {
155 - successful: true,
156 - data: { ok: true, echoed: 'local' },
157 - error: null,
158 - logId: '',
159 - },
160 - },
161 - })
162 - )('[Given] a local tool slug without auth [Then] it executes locally', it => {
163 - it.effect('does not require login or Tool Router context', () =>
164 - Effect.gen(function* () {
165 - yield* cli(['execute', 'LOCAL_BEEPER_IMESSAGE_VERSION', '-d', '{ value: 1 }']);
166 -
167 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
168 - const output = parseLastJson(lines);
169 - expect(output).toMatchObject({
170 - successful: true,
171 - data: { ok: true, echoed: 'local' },
172 - error: null,
173 - });
174 - })
175 - );
176 - });
177 -
150 layer(
151 TestLive({
152 baseConfigProvider: testConfigProvider,
ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
-87
@@ -609,93 +609,6 @@ describe('CLI: composio search', () => {
609 });
610 }
611
612 - {
613 - let createParams: SessionCreateParams | undefined;
614 - let searchParams:
615 - (SessionSearchParams & { experimental?: SessionCreateParams['experimental'] }) | undefined;
616 -
617 - layer(
618 - TestLive({
619 - baseConfigProvider: testConfigProvider,
620 - toolkitsData,
621 - fixture: 'global-test-user-id',
622 - toolRouter: {
623 - create: async params => {
624 - createParams = params;
625 - return {
626 - session_id: 'trs_test_session',
627 - config: {
628 - user_id: params.user_id,
629 - execute: {},
630 - search: {},
631 - preload: { tools: [] },
632 - premium_usage: false,
633 - },
634 - config_version: 1,
635 - mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
636 - tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
637 - };
638 - },
639 - search: async (_sessionId, params) => {
640 - searchParams = params;
641 - return {
642 - success: true,
643 - error: null,
644 - results: [
645 - {
646 - index: 1,
647 - use_case: params.queries[0]?.use_case ?? '',
648 - primary_tool_slugs: ['LOCAL_CHROME_DEVTOOLS_LIST_PAGES'],
649 - related_tool_slugs: [],
650 - toolkits: ['CHROME_DEVTOOLS'],
651 - },
652 - ],
653 - tool_schemas: {
654 - LOCAL_CHROME_DEVTOOLS_LIST_PAGES: {
655 - tool_slug: 'LOCAL_CHROME_DEVTOOLS_LIST_PAGES',
656 - toolkit: 'CHROME_DEVTOOLS',
657 - description: 'List local Chrome pages',
658 - hasFullSchema: true,
659 - input_schema: { type: 'object', properties: {} },
660 - output_schema: { type: 'object', properties: {} },
661 - },
662 - },
663 - toolkit_connection_statuses: [
664 - {
665 - toolkit: 'CHROME_DEVTOOLS',
666 - description: 'Chrome DevTools local toolkit',
667 - has_active_connection: true,
668 - status_message: 'Local toolkit available',
669 - },
670 - ],
671 - next_steps_guidance: [],
672 - session: {
673 - id: 'trs_test_session',
674 - generate_id: false,
675 - instructions: 'Reuse this session id for follow-up calls.',
676 - },
677 - time_info: {
678 - current_time_utc: '2026-01-01T00:00:00.000Z',
679 - current_time_utc_epoch_seconds: 1767225600,
680 - message: 'UTC time',
681 - },
682 - };
683 - },
684 - },
685 - })
686 - )('[Given] local toolkit filter [Then] it is sent as a custom toolkit', it => {
687 - it.effect('injects and forwards local custom toolkit payloads', () =>
688 - Effect.gen(function* () {
689 - yield* cli(['search', 'browser page', '--toolkits', 'chrome_devtools']);
690 -
691 - expect(createParams?.toolkits).toBeUndefined();
692 - expect(createParams?.experimental?.custom_toolkits?.[0]?.slug).toBe('CHROME_DEVTOOLS');
693 - expect(searchParams?.experimental?.custom_toolkits?.[0]?.slug).toBe('CHROME_DEVTOOLS');
694 - })
695 - );
696 - });
697 - }
698 -
612 {
613 let createParams: SessionCreateParams | undefined;
614
ts/packages/cli/test/src/services/cli-user-config.test.ts
-1
@@ -61,7 +61,6 @@ describe('ComposioCliUserConfig', () => {
61 const config = yield* ComposioCliUserConfig;
62 assertEquals(config.channel, 'beta');
63 assertEquals(config.isExperimentalFeatureEnabled('listen'), true);
64 - assertEquals(config.isExperimentalFeatureEnabled('local_tools'), true);
64 } finally {
65 execPathSpy.mockRestore();
66 }
ts/packages/cli/test/src/services/permission-ui.test.ts renamed
+4 -4
@@ -2,9 +2,9 @@ import { describe, expect, it } from '@effect/vitest';
2 import { ChildProcessSpawner } from 'effect/unstable/process';
3 import { ConfigProvider, Effect, Layer, PlatformError } from 'effect';
4 import {
5 - detectNativeUiCallerAgentEffect,
5 + detectPermissionCallerAgentEffect,
6 interactivePermissionUiDisabledConfig,
7 -} from 'src/services/native-ui-sidecar';
7 +} from 'src/services/permission-ui';
8 import { UNPREFIXED_CONFIG } from 'src/effects/app-config';
9
10 const loadFlag = (entries: Record<string, string>) =>
@@ -33,10 +33,10 @@ const detectAgent = (
33 const signals = yield* UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS.pipe(
34 Effect.provideService(ConfigProvider.ConfigProvider, ConfigProvider.fromEnv({ env }))
35 );
36 - return yield* detectNativeUiCallerAgentEffect(signals);
36 + return yield* detectPermissionCallerAgentEffect(signals);
37 }).pipe(Effect.provide(layer));
38
39 -describe('native UI sidecar', () => {
39 +describe('permission UI', () => {
40 it.effect('disables interactive permission UI in CI and Vitest environments', () =>
41 Effect.gen(function* () {
42 expect(yield* loadFlag({})).toBe(false);
ts/packages/cli/test/src/services/tool-permissions.test.ts
+3 -3
@@ -9,9 +9,9 @@ import { Composio as RawComposioClient } from '@composio/client';
9
10 // Enhanced controls are disabled on darwin-x64, so pin the platform: these
11 // scenarios are about the transport, not about where the CLI runs.
12 -vi.mock('@composio/cli-local-tools', async importOriginal => ({
13 - ...(await importOriginal<typeof import('@composio/cli-local-tools')>()),
14 - detectCliPlatform: () => 'linux-x64',
12 +vi.mock('src/services/permission-ui', async importOriginal => ({
13 + ...(await importOriginal<typeof import('src/services/permission-ui')>()),
14 + isEnhancedControlsPlatformSupported: () => true,
15 }));
16 import {
17 decodeCacheFileTolerant,
ts/packages/cli/test/src/services/upgrade-binary.test.ts
+7 -33
@@ -451,43 +451,26 @@ describe('UpgradeBinary', () => {
451 }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
452 });
453
454 - it.effect('copies local-tool bundled binary assets during local-target upgrades', () => {
454 + it.effect('replaces the binary during local-target upgrades', () => {
455 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
456
457 return Effect.gen(function* () {
458 const fs = yield* FileSystem.FileSystem;
459 const path = yield* Path.Path;
460 const installDir = yield* fs.makeTempDirectoryScoped({
461 - prefix: 'composio-local-tool-upgrade-target-',
461 + prefix: 'composio-local-upgrade-target-',
462 });
463 const sourceDir = yield* fs.makeTempDirectoryScoped({
464 - prefix: 'composio-local-tool-upgrade-source-',
464 + prefix: 'composio-local-upgrade-source-',
465 });
466 const fakeExecPath = path.join(installDir, 'composio');
467 const sourceBinaryPath = path.join(sourceDir, 'composio');
468 - const sourceLocalToolPath = path.join(
469 - sourceDir,
470 - 'local-tools-binaries',
471 - 'beeper-imessage',
472 - 'darwin-arm64',
473 - 'imessage-cli'
474 - );
475 - const installedLocalToolPath = path.join(
476 - installDir,
477 - 'local-tools-binaries',
478 - 'beeper-imessage',
479 - 'darwin-arm64',
480 - 'imessage-cli'
481 - );
482 - const staleLocalToolPath = path.join(installDir, 'local-tools-binaries', 'stale-tool');
468 + const legacyLocalToolsPath = path.join(installDir, 'local-tools-binaries');
469
470 yield* fs.writeFileString(fakeExecPath, 'old-binary');
471 yield* fs.writeFileString(sourceBinaryPath, 'new-binary');
486 - yield* fs.makeDirectory(path.dirname(sourceLocalToolPath), { recursive: true });
487 - yield* fs.writeFileString(sourceLocalToolPath, 'imessage-sidecar');
488 - yield* fs.makeDirectory(path.dirname(installedLocalToolPath), { recursive: true });
489 - yield* fs.writeFileString(installedLocalToolPath, 'old-imessage-sidecar');
490 - yield* fs.writeFileString(staleLocalToolPath, 'stale');
472 + yield* fs.makeDirectory(path.join(legacyLocalToolsPath, 'peekaboo'), { recursive: true });
473 + yield* fs.writeFileString(path.join(legacyLocalToolsPath, 'peekaboo', 'peekaboo'), 'old');
474 const originalBinaryInfo = yield* fs.stat(fakeExecPath);
475
476 vi.spyOn(process, 'execPath', 'get').mockReturnValue(fakeExecPath);
@@ -512,9 +495,7 @@ describe('UpgradeBinary', () => {
495 Option.getOrThrow(originalBinaryInfo.ino)
496 );
497 expect(replacedBinaryInfo.mode & 0o777).toBe(0o755);
515 - expect(yield* fs.exists(installedLocalToolPath)).toBe(true);
516 - expect(yield* fs.readFileString(installedLocalToolPath)).toBe('imessage-sidecar');
517 - expect(yield* fs.exists(staleLocalToolPath)).toBe(false);
498 + expect(yield* fs.exists(legacyLocalToolsPath)).toBe(false);
499 }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
500 });
501
@@ -610,12 +591,6 @@ describe('UpgradeBinary', () => {
591 yield* fs.makeDirectory(path.dirname(observedCompanionPath), { recursive: true });
592 yield* fs.writeFileString(observedCompanionPath, 'old-support-file');
593
613 - const sourceLocalToolPath = path.join(sourceDir, 'local-tools-binaries', 'test-tool');
614 - const installedLocalToolPath = path.join(installDir, 'local-tools-binaries', 'test-tool');
615 - yield* fs.makeDirectory(path.dirname(sourceLocalToolPath), { recursive: true });
616 - yield* fs.writeFileString(sourceLocalToolPath, 'new-local-tool');
617 - yield* fs.makeDirectory(path.dirname(installedLocalToolPath), { recursive: true });
618 - yield* fs.writeFileString(installedLocalToolPath, 'old-local-tool');
594 vi.spyOn(process, 'execPath', 'get').mockReturnValue(fakeExecPath);
595
596 const error = yield* runUpgrade([['DEBUG_OVERRIDE_UPGRADE_TARGET', sourceBinaryPath]], {
@@ -630,7 +605,6 @@ describe('UpgradeBinary', () => {
605 expect(String(error.cause)).toContain(missingRelativePath);
606 expect(yield* fs.readFileString(fakeExecPath)).toBe('old-binary');
607 expect(yield* fs.readFileString(observedCompanionPath)).toBe('old-support-file');
633 - expect(yield* fs.readFileString(installedLocalToolPath)).toBe('old-local-tool');
608 expect(yield* fs.readFileString(releaseTagPath)).toBe('@composio/cli@0.2.31\n');
609 }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
610 });
ts/packages/cli/test/src/skills/composio-cli/reference-schema.test.ts
-1
@@ -7,6 +7,5 @@ describe('composio-cli skill build context', () => {
7 const build = resolveSkillBuildContext('stable');
8
9 expect(build.experimentalFeatures[CLI_EXPERIMENTAL_FEATURES.LISTEN]).toBe(false);
10 - expect(build.experimentalFeatures[CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS]).toBe(false);
10 });
11 });
ts/packages/cli/test/src/utils/atomic-replace.test.ts
+2 -175
@@ -1,94 +1,11 @@
1 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
2 import * as BunPath from '@effect/platform-bun/BunPath';
3 import { describe, expect, layer } from '@effect/vitest';
4 -import { Effect, FileSystem, Layer, Option, Path, PlatformError } from 'effect';
5 -
6 -type RemoveOptions = Parameters<FileSystem.FileSystem['remove']>[1];
7 -import {
8 - AtomicReplaceError,
9 - atomicReplaceDirectory,
10 - atomicReplaceFile,
11 -} from 'src/utils/atomic-replace';
4 +import { Effect, FileSystem, Layer, Option, Path } from 'effect';
5 +import { AtomicReplaceError, atomicReplaceFile } from 'src/utils/atomic-replace';
6
7 const TestPlatform = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);
8
15 -const failDirectoryPublish = (targetPath: string, failRestore = false) =>
16 - Layer.effect(
17 - FileSystem.FileSystem,
18 - Effect.map(
19 - FileSystem.FileSystem,
20 - fs =>
21 - new Proxy(fs, {
22 - get(target, property, receiver) {
23 - if (property !== 'rename') {
24 - return Reflect.get(target, property, receiver);
25 - }
26 -
27 - return (oldPath: string, newPath: string) => {
28 - const shouldFail =
29 - newPath === targetPath &&
30 - (oldPath.includes('.composio-atomic-replace-') ||
31 - (failRestore && oldPath.includes('.composio-atomic-recovery-')));
32 - return shouldFail
33 - ? Effect.fail(
34 - PlatformError.systemError({
35 - _tag: 'Busy',
36 - module: 'FileSystem',
37 - method: 'rename',
38 - pathOrDescriptor: newPath,
39 - })
40 - )
41 - : target.rename(oldPath, newPath);
42 - };
43 - },
44 - })
45 - )
46 - ).pipe(Layer.provide(BunFileSystem.layer));
47 -
48 -const failDirectoryCleanup = () =>
49 - Layer.effect(
50 - FileSystem.FileSystem,
51 - Effect.map(
52 - FileSystem.FileSystem,
53 - fs =>
54 - new Proxy(fs, {
55 - get(target, property, receiver) {
56 - if (property !== 'remove') {
57 - return Reflect.get(target, property, receiver);
58 - }
59 -
60 - return (path: string, options?: RemoveOptions) =>
61 - path.includes('.composio-atomic-recovery-')
62 - ? Effect.fail(
63 - PlatformError.systemError({
64 - _tag: 'Busy',
65 - module: 'FileSystem',
66 - method: 'remove',
67 - pathOrDescriptor: path,
68 - })
69 - )
70 - : target.remove(path, options);
71 - },
72 - })
73 - )
74 - ).pipe(Layer.provide(BunFileSystem.layer));
75 -
76 -const makeDirectoryFixture = (withTarget = true) =>
77 - Effect.gen(function* () {
78 - const fs = yield* FileSystem.FileSystem;
79 - const path = yield* Path.Path;
80 - const directory = yield* fs.makeTempDirectoryScoped();
81 - const sourcePath = path.join(directory, 'source');
82 - const targetPath = path.join(directory, 'target');
83 - yield* fs.makeDirectory(sourcePath);
84 - yield* fs.writeFileString(path.join(sourcePath, 'new.txt'), 'new contents');
85 - if (withTarget) {
86 - yield* fs.makeDirectory(targetPath);
87 - yield* fs.writeFileString(path.join(targetPath, 'old.txt'), 'old contents');
88 - }
89 - return { directory, fs, path, sourcePath, targetPath };
90 - });
91 -
9 describe('atomic replace', () => {
10 layer(TestPlatform)(it => {
11 it.effect('replaces an existing file without modifying its open inode', () =>
@@ -152,95 +69,5 @@ describe('atomic replace', () => {
69 expect(yield* fs.readDirectory(directory)).toEqual(['target']);
70 })
71 );
155 -
156 - it.effect('replaces an existing non-empty directory without leaving residue', () =>
157 - Effect.gen(function* () {
158 - const fs = yield* FileSystem.FileSystem;
159 - const path = yield* Path.Path;
160 - const directory = yield* fs.makeTempDirectoryScoped();
161 - const sourcePath = path.join(directory, 'source');
162 - const targetPath = path.join(directory, 'target');
163 - yield* fs.makeDirectory(path.join(sourcePath, 'nested'), { recursive: true });
164 - yield* fs.writeFileString(path.join(sourcePath, 'nested', 'new.txt'), 'new contents');
165 - yield* fs.makeDirectory(targetPath);
166 - yield* fs.writeFileString(path.join(targetPath, 'old.txt'), 'old contents');
167 -
168 - yield* Effect.scoped(atomicReplaceDirectory({ sourcePath, targetPath }));
169 -
170 - expect(yield* fs.readFileString(path.join(targetPath, 'nested', 'new.txt'))).toBe(
171 - 'new contents'
172 - );
173 - expect(yield* fs.exists(path.join(targetPath, 'old.txt'))).toBe(false);
174 - expect((yield* fs.readDirectory(directory)).sort()).toEqual(['source', 'target']);
175 - })
176 - );
177 -
178 - it.effect('creates a directory target that does not exist', () =>
179 - Effect.gen(function* () {
180 - const { directory, fs, path, sourcePath, targetPath } = yield* makeDirectoryFixture(false);
181 -
182 - yield* Effect.scoped(atomicReplaceDirectory({ sourcePath, targetPath }));
183 -
184 - expect(yield* fs.readFileString(path.join(targetPath, 'new.txt'))).toBe('new contents');
185 - expect((yield* fs.readDirectory(directory)).sort()).toEqual(['source', 'target']);
186 - })
187 - );
188 -
189 - it.effect('restores the previous directory when publishing fails', () =>
190 - Effect.gen(function* () {
191 - const { directory, fs, path, sourcePath, targetPath } = yield* makeDirectoryFixture();
192 -
193 - const error = yield* Effect.flip(
194 - Effect.scoped(atomicReplaceDirectory({ sourcePath, targetPath })).pipe(
195 - Effect.provide(failDirectoryPublish(targetPath))
196 - )
197 - );
198 -
199 - expect(error).toBeInstanceOf(AtomicReplaceError);
200 - expect(yield* fs.readFileString(path.join(targetPath, 'old.txt'))).toBe('old contents');
201 - expect((yield* fs.readDirectory(directory)).sort()).toEqual(['source', 'target']);
202 - })
203 - );
204 -
205 - it.effect('keeps the published directory when old-content cleanup fails', () =>
206 - Effect.gen(function* () {
207 - const { directory, fs, path, sourcePath, targetPath } = yield* makeDirectoryFixture();
208 -
209 - yield* Effect.scoped(atomicReplaceDirectory({ sourcePath, targetPath })).pipe(
210 - Effect.provide(failDirectoryCleanup())
211 - );
212 -
213 - const recoveryDirectory = (yield* fs.readDirectory(directory)).find(entry =>
214 - entry.startsWith('.composio-atomic-recovery-')
215 - );
216 - expect(yield* fs.readFileString(path.join(targetPath, 'new.txt'))).toBe('new contents');
217 - expect(recoveryDirectory).toBeDefined();
218 - expect(
219 - yield* fs.readFileString(path.join(directory, recoveryDirectory!, 'target', 'old.txt'))
220 - ).toBe('old contents');
221 - })
222 - );
223 -
224 - it.effect('retains the previous directory when publishing and restoration fail', () =>
225 - Effect.gen(function* () {
226 - const { directory, fs, path, sourcePath, targetPath } = yield* makeDirectoryFixture();
227 -
228 - const error = yield* Effect.flip(
229 - Effect.scoped(atomicReplaceDirectory({ sourcePath, targetPath })).pipe(
230 - Effect.provide(failDirectoryPublish(targetPath, true))
231 - )
232 - );
233 - const recoveryDirectory = (yield* fs.readDirectory(directory)).find(entry =>
234 - entry.startsWith('.composio-atomic-recovery-')
235 - );
236 -
237 - expect(error).toBeInstanceOf(AtomicReplaceError);
238 - expect(recoveryDirectory).toBeDefined();
239 - expect(error.message).toContain('Previous contents retained at');
240 - expect(
241 - yield* fs.readFileString(path.join(directory, recoveryDirectory!, 'target', 'old.txt'))
242 - ).toBe('old contents');
243 - })
244 - );
72 });
73 });
ts/packages/cli/tsconfig.src.json
+1 -2
@@ -9,8 +9,7 @@
9 "compilerOptions": {
10 "paths": {
11 "src/*": ["./src/*"],
12 - "effect-errors/*": ["./src/effect-errors/*"],
13 - "@composio/cli-local-tools": ["../cli-local-tools/src/index.ts"]
12 + "effect-errors/*": ["./src/effect-errors/*"]
13 },
14 "types": ["@types/bun"]
15 },
ts/packages/cli/tsconfig.test.json
-1
@@ -10,7 +10,6 @@
10 "paths": {
11 "src/*": ["./src/*"],
12 "effect-errors/*": ["./src/effect-errors/*"],
13 - "@composio/cli-local-tools": ["../cli-local-tools/src/index.ts"],
13 "test/*": ["./test/*"]
14 },
15 "types": ["@types/bun", "vitest/importMeta"]
ts/packages/cli/tsdown.config.ts
-1
@@ -19,7 +19,6 @@ export default defineConfig({
19 neverBundle: [/^bun:/, /^node:/],
20 alwaysBundle: [
21 '@composio/core',
22 - '@composio/cli-local-tools',
22 /^zod(?:\/.*)?$/,
23 /^@agentclientprotocol\/sdk(?:\/.*)?$/,
24 /^@modelcontextprotocol\/sdk(?:\/.*)?$/,
ts/packages/cli/vitest.config.ts
-2
@@ -8,7 +8,6 @@ const coreDir = path.resolve(__dirname, '../core');
8 const tsBuildersDir = path.resolve(__dirname, '../ts-builders');
9 const jsonSchemaToEffectSchemaDir = path.resolve(__dirname, '../json-schema-to-effect-schema');
10 const jsonSchemaToZodDir = path.resolve(__dirname, '../json-schema-to-zod');
11 -const cliLocalToolsDir = path.resolve(__dirname, '../cli-local-tools');
11
12 export default defineConfig({
13 resolve: {
@@ -25,7 +24,6 @@ export default defineConfig({
24 'src/index.ts'
25 ),
26 '@composio/json-schema-to-zod': path.join(jsonSchemaToZodDir, 'src/index.ts'),
28 - '@composio/cli-local-tools': path.join(cliLocalToolsDir, 'src/index.ts'),
27 'effect-errors': path.resolve(__dirname, './src/effect-errors'),
28 // @composio/core uses package.json "imports" (#config_defaults, #platform, etc.)
29 // Vitest/Vite does not resolve these for workspace deps, so alias them explicitly