@devries-cameron20 / composio-1 / commits / 09f76b1c9
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.

refactor(cli): eliminate raw environment access (#4134)

This PR: - routes Composio-prefixed runtime configuration through `APP_CONFIG` and normalizes unprefixed host values through `HOST_CONFIG` in `app-config.ts` - removes `loadOptionalAppConfig`-style fallback loading so optional strings, booleans, and CLI flag precedence resolve at the configuration boundary - removes every executable `process.env` reference from CLI source; child commands inherit the ambient environment through `@effect/platform` and receive explicit normalized overrides - preserves arbitrary `CODEX_*`, `CLAUDE_*`, and `OPENCLAW_*` detection through Effect config enumeration without exposing the raw environment map - propagates telemetry debug state through worker arguments instead of mutating the process environment - replaces removable filesystem, OS, subprocess, and error-handling exceptions with Effect services and typed control flow - documents supported and internal CLI environment variables, including their `user_data.json` and `config.json` mappings - reduces registered CLI lint boundaries from 45 to 4; the retained entries are the detached-spawn, Node OS, synchronous preload filesystem, and MD5 checksum implementations - verifies the result with 1,201 passing CLI tests (1 skipped), strict Oxlint, boundary validation, root typechecking across 19 packages, the CLI build, and real `composio run` child-process checks

Alberto Schiabel committed Aug 18, 2026 at 12:54 UTC 09f76b1c9fb24ac0a3f5bf8fbc788f8c07ad90c4
71 files changed +3302 -1124
.oxlintrc.json
+36 -11
@@ -274,17 +274,6 @@
274 }
275 ]
276 }
277 - ],
278 - "eslint-js/no-restricted-syntax": [
279 - "error",
280 - {
281 - "selector": "MemberExpression[object.name='process'][property.name='stdout']",
282 - "message": "Write output and read terminal capabilities through TerminalUI."
283 - },
284 - {
285 - "selector": "MemberExpression[object.name='process'][property.name='stderr']",
286 - "message": "Write errors and read terminal capabilities through TerminalUI."
287 - }
277 ]
278 }
279 },
@@ -329,6 +318,42 @@
318 ],
319 "eslint-js/no-restricted-syntax": [
320 "error",
321 + {
322 + "selector": "TryStatement",
323 + "message": "Use Effect.try, Effect.tryPromise, or typed Effect error recovery instead of try/catch."
324 + },
325 + {
326 + "selector": "MemberExpression[object.name='process'][computed=false][property.name='env']",
327 + "message": "Read environment variables through effect/Config instead of process.env."
328 + },
329 + {
330 + "selector": "MemberExpression[object.name='process'][computed=true][property.value='env']",
331 + "message": "Read environment variables through effect/Config instead of process.env."
332 + },
333 + {
334 + "selector": "VariableDeclarator[init.name='process'] > ObjectPattern > Property[key.name='env']",
335 + "message": "Read environment variables through effect/Config instead of process.env."
336 + },
337 + {
338 + "selector": "VariableDeclarator[init.name='process'] > ObjectPattern > Property[key.value='env']",
339 + "message": "Read environment variables through effect/Config instead of process.env."
340 + },
341 + {
342 + "selector": "AssignmentExpression[right.name='process'] > ObjectPattern > Property[key.name='env']",
343 + "message": "Read environment variables through effect/Config instead of process.env."
344 + },
345 + {
346 + "selector": "AssignmentExpression[right.name='process'] > ObjectPattern > Property[key.value='env']",
347 + "message": "Read environment variables through effect/Config instead of process.env."
348 + },
349 + {
350 + "selector": "AssignmentPattern[right.name='process'] > ObjectPattern > Property[key.name='env']",
351 + "message": "Read environment variables through effect/Config instead of process.env."
352 + },
353 + {
354 + "selector": "AssignmentPattern[right.name='process'] > ObjectPattern > Property[key.value='env']",
355 + "message": "Read environment variables through effect/Config instead of process.env."
356 + },
357 {
358 "selector": "MemberExpression[object.name='process'][property.name='stdout']",
359 "message": "Write output and read terminal capabilities through TerminalUI."
pnpm-lock.yaml
+6
@@ -228,6 +228,12 @@ importers:
228 specifier: 'catalog:'
229 version: 1.3.14
230
231 + ts/e2e-tests/cli/run:
232 + devDependencies:
233 + '@e2e-tests/utils':
234 + specifier: workspace:*
235 + version: link:../../_utils
236 +
237 ts/e2e-tests/cli/setup-plugins:
238 devDependencies:
239 '@e2e-tests/utils':
ts/e2e-tests/_utils/Dockerfile.cli
+17 -2
@@ -61,6 +61,20 @@ RUN bun build ./src/bin.ts \
61 --production \
62 --outfile /out/composio
63
64 +# Build the `composio run` companion modules next to the binary. Without the
65 +# run-*.mjs wrappers every `composio run` treats the install as broken and
66 +# enters the GitHub self-repair path. `--host-only` restricts the bundled
67 +# codex-acp binary to this image's own platform; shipping all four costs ~870MB
68 +# and ~2min of build time for binaries this image can never execute.
69 +#
70 +# The acp-adapters are dropped afterwards: they are only needed when a script
71 +# invokes an ACP sub-agent, which is checked lazily at the invocation site, and
72 +# no CLI e2e test does. Keeping them would add ~224MB to the image. The build
73 +# script still produces them (it asserts on its own output), so the removal
74 +# happens in the same layer to keep it out of the image entirely.
75 +RUN bun scripts/build-companion-modules.ts /out --host-only && \
76 + rm -rf /out/acp-adapters
77 +
78 # Copy CLI e2e tests last (changes frequently)
79 WORKDIR /app
80 COPY ts/e2e-tests/cli/ /app/ts/e2e-tests/cli/
@@ -75,8 +89,9 @@ ENV HOME="/tmp"
89
90 WORKDIR /app
91
78 -# CLI binary
79 -COPY --from=builder /out/composio /usr/local/bin/composio
92 +# CLI binary plus the `composio run` companion modules, which must stay siblings
93 +# of the executable (they are resolved from dirname(process.execPath)).
94 +COPY --from=builder /out/ /usr/local/bin/
95
96 # CLI e2e tests
97 COPY --from=builder /app/ts/e2e-tests/cli/ /app/ts/e2e-tests/cli/
ts/e2e-tests/cli/run/README.md new
+39
@@ -0,0 +1,39 @@
1 +# CLI `composio run` Test
2 +
3 +Verifies that `composio run` forwards the child script's exit status to the caller and that
4 +the run log it advertises survives the process.
5 +
6 +## Why This Exists
7 +
8 +`composio run` never exits by itself: the handler sets `process.exitCode` and returns a
9 +successful Effect, and the CLI teardown hands that code to `runMain`, which force-exits only
10 +when the code is non-zero. Unit tests run in-process and can only observe `process.exitCode`,
11 +so they cannot tell whether the code ever reached the OS. An Effect upgrade or a teardown
12 +change could turn every failing script into exit 0 without failing a single unit test.
13 +
14 +The `RUN_LOG_FILE=` path printed on stderr has the same problem: it is only useful if the file
15 +outlives the process that printed it, which regressed once when the log lived inside a scoped
16 +temp directory.
17 +
18 +## What It Tests
19 +
20 +| Test | Description |
21 +| ------------------ | ---------------------------------------------------------------------- |
22 +| Exit forwarding | `composio run 'process.exit(7)'` exits 7 |
23 +| Successful run | An inline script exits 0 and its stdout reaches the caller |
24 +| Missing script | `composio run` with no code and no `--file` exits non-zero and says so |
25 +| Run log durability | The announced `RUN_LOG_FILE` path still exists after the process exits |
26 +
27 +## Requirements
28 +
29 +None. This suite does not require any environment variables or network access.
30 +
31 +## Isolation Tool
32 +
33 +**Docker** with the CLI built from the current monorepo source.
34 +
35 +## Running
36 +
37 +```bash
38 +pnpm test:e2e:cli
39 +```
ts/e2e-tests/cli/run/e2e.test.ts new
+99
@@ -0,0 +1,99 @@
1 +/**
2 + * CLI run command e2e test
3 + *
4 + * `composio run` spawns the user's script as a child process and forwards its exit
5 + * status to the caller. The forwarding path is process-level: the command handler sets
6 + * `process.exitCode` and returns a *successful* Effect, and the CLI teardown hands that
7 + * code to `runMain`, which force-exits only for a non-zero code. Nothing in-process can
8 + * observe whether that hand-off actually reached the OS, so a `wait`/`$?` assertion
9 + * against the real binary is the only guard against a failing script silently becoming
10 + * exit 0.
11 + *
12 + * The same applies to the `RUN_LOG_FILE=` path announced on stderr: it is only useful if
13 + * the file outlives the process that printed it, which cannot be checked from inside the
14 + * run.
15 + */
16 +
17 +import { e2e, sanitizeOutput, type E2ETestResult } from '@e2e-tests/utils';
18 +import { TIMEOUTS } from '@e2e-tests/utils/const';
19 +import { describe, it, expect, beforeAll } from 'bun:test';
20 +
21 +/** Marker printed by the successful inline script, unique enough to grep for. */
22 +const STDOUT_MARKER = 'composio-run-e2e-stdout-marker';
23 +
24 +/**
25 + * Runs a successful script, then — after the CLI process has exited — reports whether the
26 + * `RUN_LOG_FILE=` path it advertised on stderr still exists. Probe results go to stdout as
27 + * `KEY=value` lines; the CLI's own stderr is parked in a file so it cannot mix in.
28 + */
29 +const runLogProbeCommand = [
30 + `composio run 'console.log("run-log-probe")' 2> run-stderr.txt`,
31 + 'run_status=$?',
32 + `run_log_path=$(grep '^RUN_LOG_FILE=' run-stderr.txt | head -n 1 | cut -d= -f2-)`,
33 + 'echo "RUN_STATUS=$run_status"',
34 + 'if [ -n "$run_log_path" ]; then echo "RUN_LOG_ANNOUNCED=yes"; else echo "RUN_LOG_ANNOUNCED=no"; fi',
35 + 'if [ -f "$run_log_path" ]; then echo "RUN_LOG_EXISTS=yes"; else echo "RUN_LOG_EXISTS=no"; fi',
36 +].join('; ');
37 +
38 +e2e(import.meta.url, {
39 + versions: {
40 + cli: ['current'],
41 + },
42 + defineTests: ({ runCmd }) => {
43 + let failingScriptResult: E2ETestResult;
44 + let successfulScriptResult: E2ETestResult;
45 + let missingScriptResult: E2ETestResult;
46 + let runLogResult: E2ETestResult;
47 +
48 + beforeAll(async () => {
49 + failingScriptResult = await runCmd(`composio run 'process.exit(7)'`);
50 + successfulScriptResult = await runCmd(`composio run 'console.log("${STDOUT_MARKER}")'`);
51 + missingScriptResult = await runCmd('composio run');
52 + runLogResult = await runCmd(runLogProbeCommand);
53 + }, TIMEOUTS.FIXTURE);
54 +
55 + describe('composio run with a failing script', () => {
56 + it('forwards the script exit status to the caller', () => {
57 + expect(failingScriptResult.exitCode).toBe(7);
58 + });
59 + });
60 +
61 + describe('composio run with a successful script', () => {
62 + it('exits successfully', () => {
63 + expect(successfulScriptResult.exitCode).toBe(0);
64 + });
65 +
66 + it('forwards script stdout to the caller', () => {
67 + expect(sanitizeOutput(successfulScriptResult.stdout)).toContain(STDOUT_MARKER);
68 + });
69 + });
70 +
71 + describe('composio run without inline code or --file', () => {
72 + it('exits non-zero', () => {
73 + expect(missingScriptResult.exitCode).not.toBe(0);
74 + });
75 +
76 + it('explains what is missing on stderr', () => {
77 + expect(sanitizeOutput(missingScriptResult.stderr)).toContain(
78 + 'Provide inline code or use --file to run a script file.'
79 + );
80 + });
81 +
82 + it('writes no data to stdout', () => {
83 + expect(sanitizeOutput(missingScriptResult.stdout)).toBe('');
84 + });
85 + });
86 +
87 + describe('the RUN_LOG_FILE path announced on stderr', () => {
88 + it('is announced', () => {
89 + expect(runLogResult.exitCode).toBe(0);
90 + expect(sanitizeOutput(runLogResult.stdout)).toContain('RUN_STATUS=0');
91 + expect(sanitizeOutput(runLogResult.stdout)).toContain('RUN_LOG_ANNOUNCED=yes');
92 + });
93 +
94 + it('still exists after the CLI process exits', () => {
95 + expect(sanitizeOutput(runLogResult.stdout)).toContain('RUN_LOG_EXISTS=yes');
96 + });
97 + });
98 + },
99 +});
ts/e2e-tests/cli/run/package.json new
+14
@@ -0,0 +1,14 @@
1 +{
2 + "name": "@e2e-tests/cli-run",
3 + "version": "0.0.0",
4 + "private": true,
5 + "type": "module",
6 + "scripts": {
7 + "typecheck": "tsc --noEmit",
8 + "test:e2e": "bun test e2e.test.ts",
9 + "test:e2e:cli": "bun test e2e.test.ts"
10 + },
11 + "devDependencies": {
12 + "@e2e-tests/utils": "workspace:*"
13 + }
14 +}
ts/e2e-tests/cli/upgrade/e2e.test.ts
+1 -1
@@ -15,7 +15,7 @@ const companionRelativePaths = [
15 'run-subagent-acp.mjs',
16 'run-subagent-legacy.mjs',
17 'run-subagent-output-mcp.mjs',
18 - // RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS
18 + // RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS
19 'acp-adapters/claude-code-acp.mjs',
20 'acp-adapters/cli.js',
21 'acp-adapters/codex/darwin-arm64/codex-acp',
ts/packages/cli/README.md
+33 -16
@@ -50,22 +50,39 @@ composio [--log-level all|trace|debug|info|warning|error|fatal|none]
50
51 ## Configuration
52
53 -The Composio CLI supports configuration via environment variables.
54 -Additionally, for storing and retrieving user session context, a `user_data.json` JSON configuration file is used.
55 -
56 -By default, this file is stored in `~/.composio`, but you can specify a custom location using the `COMPOSIO_CACHE_DIR` environment variable.
57 -
58 -| Environment Variable | User JSON config | Description | Default |
59 -| ---------------------- | ---------------- | ------------------------------------------------------------------ | -------------------------------- |
60 -| COMPOSIO_API_KEY | `api_key` | Composio backend API key | None |
61 -| COMPOSIO_BASE_URL | `base_url` | The base URL of the Composio backend API | https://backend.composio.dev |
62 -| COMPOSIO_WEB_URL | `web_url` | The base URL of the Composio web app | https://dashboard.composio.dev/ |
63 -| COMPOSIO_CACHE_DIR | - | The directory where the Composio CLI stores cache files | ~/.composio |
64 -| COMPOSIO_BIN_DIR | - | The directory `composio install` adds to `PATH` (see below) | Resolved from the running binary |
65 -| COMPOSIO_LOG_LEVEL | - | The log level for the Composio CLI | None |
66 -| DEBUG_OVERRIDE_VERSION | - | The version to use when upgrading the Composio CLI (for debugging) | None |
67 -| FORCE_USE_CACHE | - | Whether to force the use of previously cached HTTP responses | None |
68 -| NO_COLOR | - | If set, disables color output in the CLI (https://no-color.org/) | None |
53 +The Composio CLI supports configuration via environment variables. It stores authenticated user context in `user_data.json` and general CLI settings in `config.json`.
54 +
55 +By default, both files are stored in `~/.composio`, but you can specify a custom location using the `COMPOSIO_CACHE_DIR` environment variable.
56 +
57 +| Environment Variable | JSON config | Description | Default |
58 +| ---------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
59 +| COMPOSIO_USER_API_KEY | `user_data.json`: `api_key` | Composio user API key | None |
60 +| COMPOSIO_ENVIRONMENT | - | Selects the production or staging URL defaults | production |
61 +| COMPOSIO_BASE_URL | `user_data.json`: `base_url` | The base URL of the Composio backend API | https://backend.composio.dev |
62 +| COMPOSIO_WEB_URL | `user_data.json`: `web_url` | The base URL of the Composio web app | https://dashboard.composio.dev/ |
63 +| COMPOSIO_CACHE_DIR | - | The directory where the Composio CLI stores cache files | ~/.composio |
64 +| COMPOSIO_SESSION_DIR | `config.json`: `artifact_directory` | The root directory for CLI session artifacts | `COMPOSIO_CACHE_DIR`, then `artifact_directory`, then `$TMPDIR/composio` |
65 +| COMPOSIO_BIN_DIR | - | The directory `composio install` adds to `PATH` (see below) | Resolved from the running binary |
66 +| COMPOSIO_LOG_LEVEL | - | The log level for the Composio CLI | None |
67 +| COMPOSIO_ORG_ID | - | The organization ID used for project-scoped commands | Active project |
68 +| COMPOSIO_PROJECT_ID | - | The project ID used for project-scoped commands | Active project |
69 +| COMPOSIO_AGENTS_BASE_URL | - | The base URL of the Composio agents service | https://agents.composio.dev |
70 +| COMPOSIO_WEBHOOK_SECRET | - | The signing secret for events forwarded by `composio dev triggers listen` | Generated for the current session |
71 +| COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE | - | Disables the connected-account cache | true |
72 +| COMPOSIO_PERF_DEBUG | - | Set to `1` to write performance diagnostics | 0 |
73 +| COMPOSIO_TOOL_DEBUG | - | Set to `1` to write tool diagnostics | 0 |
74 +| DEBUG_OVERRIDE_VERSION | - | The version to use when upgrading the Composio CLI (for debugging) | None |
75 +| FORCE_USE_CACHE | - | Whether to force the use of previously cached HTTP responses | None |
76 +| NO_COLOR | - | If set, disables color output in the CLI (https://no-color.org/) | None |
77 +
78 +The CLI and its installer use these variables to coordinate nested commands. They aren't intended for manual configuration.
79 +
80 +| Environment Variable | Description | Default |
81 +| ------------------------------ | -------------------------------------------------------------------------- | ------- |
82 +| COMPOSIO_CLI_INVOCATION_ORIGIN | Identifies whether another CLI surface, such as `composio run`, invoked it | cli |
83 +| COMPOSIO_CLI_PARENT_RUN_ID | Reuses the parent run ID for nested command telemetry | None |
84 +| COMPOSIO_RUN_ACP_ONLY | Set to `1` to disable the legacy sub-agent fallback | 0 |
85 +| COMPOSIO_RUN_OUTPUT_DIR | Shares one artifact directory across nested `composio run` commands | None |
86
87 Additionally, `composio upgrade` supports the following environment variables:
88
ts/packages/cli/lint-boundaries.json
-241
@@ -1,149 +1,4 @@
1 {
2 - "src/analytics/events.ts": [
3 - {
4 - "rule": "eslint-js/no-restricted-syntax",
5 - "reason": "spawn-time env handoff from parent run",
6 - "target": "(process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID())"
7 - },
8 - {
9 - "rule": "eslint-js/no-restricted-syntax",
10 - "reason": "spawn-time env handoff read outside Effect",
11 - "target": "const getInvocationOrigin = (): string => process.env.COMPOSIO_CLI_INVOCATION_ORIGIN ?? 'cli';"
12 - },
13 - {
14 - "rule": "eslint-js/no-restricted-syntax",
15 - "reason": "spawn-time env handoff read outside Effect",
16 - "target": "const getParentRunId = (): string | undefined => process.env.COMPOSIO_CLI_PARENT_RUN_ID;"
17 - }
18 - ],
19 - "src/bin.ts": [
20 - {
21 - "rule": "eslint-js/no-restricted-syntax",
22 - "reason": "pre-runtime env write during bootstrap",
23 - "target": "process.env[CLI_TELEMETRY_DEBUG_ENV_VAR] = 'true';"
24 - }
25 - ],
26 - "src/cli-main.ts": [
27 - {
28 - "rule": "eslint-js/no-restricted-syntax",
29 - "reason": "env write propagates run id to children",
30 - "target": "process.env.COMPOSIO_CLI_PARENT_RUN_ID = commandTelemetryContext.runId;"
31 - }
32 - ],
33 - "src/commands/index.ts": [
34 - {
35 - "rule": "eslint-js/no-restricted-syntax",
36 - "reason": "env delete clears a stale hidden-flag value",
37 - "target": "delete process.env.COMPOSIO_RUN_ACP_ONLY;"
38 - },
39 - {
40 - "rule": "eslint-js/no-restricted-syntax",
41 - "reason": "env write hands the stripped flag to run.cmd",
42 - "target": "process.env.COMPOSIO_RUN_ACP_ONLY = acpOnly ? '1' : '0';"
43 - }
44 - ],
45 - "src/commands/run.cmd.ts": [
46 - {
47 - "rule": "eslint-js/no-restricted-syntax",
48 - "reason": "honors the same COMPOSIO_CACHE_DIR/CACHE_DIR overrides the run-helpers child runtime reads, so the sandbox read roots match the child's cache location",
49 - "target": "process.env.COMPOSIO_CACHE_DIR?.trim() || process.env.CACHE_DIR?.trim() || defaultComposioDir;"
50 - },
51 - {
52 - "rule": "eslint-js/no-restricted-syntax",
53 - "reason": "reads the COMPOSIO_RUN_ACP_ONLY flag a parent process sets to force the ACP-only subagent path in the child run",
54 - "target": "const acpOnly = process.env.COMPOSIO_RUN_ACP_ONLY === '1';"
55 - },
56 - {
57 - "rule": "eslint-js/no-restricted-syntax",
58 - "reason": "reuses the run ID a parent `composio run` process passed via env so nested runs share one run identity",
59 - "target": "const runId = process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID();"
60 - },
61 - {
62 - "rule": "eslint-js/no-restricted-syntax",
63 - "reason": "spreads the caller's full environment into the spawned script so user-provided variables reach the child process",
64 - "target": "...process.env,"
65 - },
66 - {
67 - "rule": "eslint-js/no-restricted-syntax",
68 - "reason": "try/finally removes the temp preload and wrapper files around the imperative Bun.spawn block, whose success path ends in process.exit",
69 - "target": "try {"
70 - },
71 - {
72 - "rule": "no-restricted-imports",
73 - "reason": "os.tmpdir and os.homedir locate the preload scratch directory and ~/.composio in the same synchronous helpers",
74 - "target": "import * as os from 'node:os';"
75 - },
76 - {
77 - "rule": "no-restricted-imports",
78 - "reason": "synchronous fs (mkdtempSync/writeFileSync/rmSync/existsSync) builds and tears down the run preload files in plain helpers that execute outside the Effect runtime",
79 - "target": "import * as fs from 'node:fs';"
80 - }
81 - ],
82 - "src/commands/tools/commands/tools.execute.cmd.ts": [
83 - {
84 - "rule": "eslint-js/no-restricted-syntax",
85 - "reason": "COMPOSIO_CLI_INVOCATION_ORIGIN is a spawn-time handshake the parent `composio run` process injects into nested CLI invocations, not user configuration, and it must be read fresh at call time",
86 - "target": "const shouldStoreLargeExecuteOutput = () => process.env.COMPOSIO_CLI_INVOCATION_ORIGIN !== 'run';"
87 - },
88 - {
89 - "rule": "eslint-js/no-restricted-syntax",
90 - "reason": "COMPOSIO_RUN_OUTPUT_DIR is injected per-subprocess by the parent `composio run` and must take precedence over the session artifacts directory; inter-process plumbing, not user configuration",
91 - "target": "process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim() ||"
92 - },
93 - {
94 - "rule": "eslint-js/no-restricted-syntax",
95 - "reason": "COMPOSIO_RUN_OUTPUT_DIR is injected per-subprocess by the parent `composio run` so nested executions share one output directory; it is inter-process plumbing, not user configuration",
96 - "target": "directoryPath: sharedDirectory?.trim() || process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim(),"
97 - },
98 - {
99 - "rule": "eslint-js/no-restricted-syntax",
100 - "reason": "COMPOSIO_RUN_OUTPUT_DIR is injected per-subprocess by the parent `composio run` so nested local-tool executions write into its shared output directory; inter-process plumbing, not user configuration",
101 - "target": "executeOutputDir: process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim() || undefined,"
102 - }
103 - ],
104 - "src/commands/triggers/commands/triggers.listen.cmd.ts": [
105 - {
106 - "rule": "eslint-js/no-restricted-syntax",
107 - "reason": "re-checks the same raw env var to tell the user whether they supplied a secret or this session generated one",
108 - "target": "if (process.env.COMPOSIO_WEBHOOK_SECRET) {"
109 - },
110 - {
111 - "rule": "eslint-js/no-restricted-syntax",
112 - "reason": "the forward signing secret is an optional raw passthrough from the user's shell; its literal presence/absence selects the generated-secret fallback",
113 - "target": "const webhookSecret = process.env.COMPOSIO_WEBHOOK_SECRET ?? generatedWebhookSecret;"
114 - }
115 - ],
116 - "src/services/agents.ts": [
117 - {
118 - "rule": "eslint-js/no-restricted-syntax",
119 - "reason": "read lazily at request time inside a plain sync helper so tests can repoint agents.composio.dev per call without rebuilding a Config layer",
120 - "target": "(process.env.COMPOSIO_AGENTS_BASE_URL ?? DEFAULT_AGENTS_BASE_URL).replace(/\\/+$/, '');"
121 - }
122 - ],
123 - "src/services/cli-session-artifacts.ts": [
124 - {
125 - "rule": "eslint-js/no-restricted-syntax",
126 - "reason": "COMPOSIO_CACHE_DIR is the second rung of the same fall-through chain: env overrides must beat the persisted artifactDirectory before the tmpdir default",
127 - "target": "process.env.COMPOSIO_CACHE_DIR?.trim() ||"
128 - },
129 - {
130 - "rule": "eslint-js/no-restricted-syntax",
131 - "reason": "read inline so a blank/whitespace-only COMPOSIO_SESSION_DIR falls through the || precedence chain (session dir > cache dir > user config > tmpdir)",
132 - "target": "process.env.COMPOSIO_SESSION_DIR?.trim() ||"
133 - }
134 - ],
135 - "src/services/cli-user-config.ts": [
136 - {
137 - "rule": "eslint-js/no-restricted-syntax",
138 - "reason": "this resolver is called from synchronous non-Effect code, so the COMPOSIO_CACHE_DIR override cannot come from effect/Config here",
139 - "target": "process.env.COMPOSIO_CACHE_DIR?.trim() ||"
140 - },
141 - {
142 - "rule": "no-restricted-imports",
143 - "reason": "os.homedir feeds resolveCliConfigDirectorySync, which runs from synchronous non-Effect call sites (dev.cmd messages, run-helpers-runtime readFileSync) where the NodeOs service is unavailable",
144 - "target": "import os from 'node:os';"
145 - }
146 - ],
2 "src/services/detached-process.ts": [
3 {
4 "rule": "no-restricted-imports",
@@ -151,20 +6,6 @@
6 "target": "import { spawn } from 'node:child_process';"
7 }
8 ],
154 - "src/services/master-detector.ts": [
155 - {
156 - "rule": "eslint-js/no-restricted-syntax",
157 - "reason": "classifies the driving agent by scanning every env key for CODEX_/CLAUDE_ prefixes; effect/Config reads known keys and cannot enumerate the whole environment",
158 - "target": "export const detectMaster = (env: Record<string, string | undefined> = process.env): MasterKind => {"
159 - }
160 - ],
161 - "src/services/native-ui-sidecar.ts": [
162 - {
163 - "rule": "eslint-js/no-restricted-syntax",
164 - "reason": "Sole raw-env boundary of this module: prefix scanning needs the full environment map, which effect/Config cannot enumerate.",
165 - "target": "const rawProcessEnv: NodeJS.ProcessEnv = process.env;"
166 - }
167 - ],
9 "src/services/node-os.ts": [
10 {
11 "rule": "no-restricted-imports",
@@ -172,100 +13,18 @@
13 "target": "import os from 'node:os';"
14 }
15 ],
175 - "src/services/project-environment-detector.ts": [
176 - {
177 - "rule": "eslint-js/no-restricted-syntax",
178 - "reason": "npm_config_user_agent is transient metadata injected by the package manager that spawned this process, not CLI configuration; read once as the last-resort heuristic when no lockfile or manifest evidence exists",
179 - "target": "const userAgent = parseUserAgent(process.env.npm_config_user_agent);"
180 - }
181 - ],
16 "src/services/run-helpers-runtime.ts": [
183 - {
184 - "rule": "eslint-js/no-restricted-syntax",
185 - "reason": "JSON.stringify throws on circular user values in this sync formatter injected into user code; String() is the entire fallback",
186 - "target": "try {"
187 - },
188 - {
189 - "rule": "eslint-js/no-restricted-syntax",
190 - "reason": "async fallback chain in the user's child process: ACP invoke errors route to the legacy sub-agent path, everything else rethrows",
191 - "target": "try {"
192 - },
193 - {
194 - "rule": "eslint-js/no-restricted-syntax",
195 - "reason": "debug flag reaches the child process via inherited environment; the CLI's Config provider is not available here",
196 - "target": "helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === '1';"
197 - },
198 - {
199 - "rule": "eslint-js/no-restricted-syntax",
200 - "reason": "debug flag reaches the child process via inherited environment; the CLI's Config provider is not available here",
201 - "target": "helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === '1';"
202 - },
203 - {
204 - "rule": "eslint-js/no-restricted-syntax",
205 - "reason": "sync config read at the child-process boundary; a missing or malformed CLI config file just means the 'auto' target",
206 - "target": "try {"
207 - },
208 - {
209 - "rule": "eslint-js/no-restricted-syntax",
210 - "reason": "the spawned CLI child must inherit the caller's full environment before Composio-specific overrides are layered on top",
211 - "target": "...process.env,"
212 - },
213 - {
214 - "rule": "no-restricted-imports",
215 - "reason": "os.tmpdir() locates the fallback run-files directory in the child process, outside the Effect runtime",
216 - "target": "import * as os from 'node:os';"
217 - },
17 {
18 "rule": "no-restricted-imports",
19 "reason": "sync fs for run-log appends, run-file writes, and CLI config reads in the child process, outside the Effect runtime",
20 "target": "import * as fs from 'node:fs';"
21 }
22 ],
224 - "src/services/run-subagent-output-mcp.ts": [
225 - {
226 - "rule": "no-restricted-imports",
227 - "reason": "standalone MCP stdio sidecar entrypoint runs outside the CLI's Effect runtime; sync fs reads the schema file and writes the structured result file",
228 - "target": "import * as fs from 'node:fs';"
229 - }
230 - ],
231 - "src/services/runtime-debug-flags.ts": [
232 - {
233 - "rule": "eslint-js/no-restricted-syntax",
234 - "reason": "called from sync non-Effect helper code in spawned child processes, where the flag arrives via inherited environment rather than a Config provider",
235 - "target": "runtimeDebugFlags.perfDebug || process.env.COMPOSIO_PERF_DEBUG === '1';"
236 - },
237 - {
238 - "rule": "eslint-js/no-restricted-syntax",
239 - "reason": "called from sync non-Effect helper code in spawned child processes, where the flag arrives via inherited environment rather than a Config provider",
240 - "target": "runtimeDebugFlags.toolDebug || process.env.COMPOSIO_TOOL_DEBUG === '1';"
241 - }
242 - ],
23 "src/services/tool-file-uploads.ts": [
24 {
25 "rule": "no-restricted-imports",
26 "reason": "MD5 for the presigned-upload checksum is not available in Web Crypto",
27 "target": "const { createHash } = await import('node:crypto');"
28 }
249 - ],
250 - "src/services/tool-permissions.ts": [
251 - {
252 - "rule": "eslint-js/no-restricted-syntax",
253 - "reason": "node:http listen callback inside a Promise executor: on failure to open the browser, close the server and reject the surrounding Promise; Effect's error channel is not available here",
254 - "target": "try {"
255 - }
256 - ],
257 - "src/ui/colors.ts": [
258 - {
259 - "rule": "eslint-js/no-restricted-syntax",
260 - "reason": "palette is created eagerly at import time, before any Effect runtime; honors the NO_COLOR convention",
261 - "target": "} = color.createColors(!Boolean(process.env.NO_COLOR));"
262 - }
263 - ],
264 - "src/ui/redact.ts": [
265 - {
266 - "rule": "eslint-js/no-restricted-syntax",
267 - "reason": "plain sync string helper called from formatting code; CI flag toggles redaction in recorded CLI output",
268 - "target": "if (process.env.CI !== 'true') return value as `${Prefix}${string}`;"
269 - }
29 ]
30 }
ts/packages/cli/package.json
+1
@@ -22,6 +22,7 @@
22 "clean": "git clean -xdf node_modules",
23 "cli": "bun run src/bin.ts",
24 "build:binary": "bun run ./scripts/build-binary.ts",
25 + "build:companions": "bun run ./scripts/build-companion-modules.ts",
26 "build:binary:cross": "bun run ./scripts/build-binary-cross.ts",
27 "build:binary:all": "bun run ./scripts/build-all-binaries.ts",
28 "build:binary:package": "bun run ./scripts/package-binaries.ts",
ts/packages/cli/scripts/_acp-adapters.ts
+20 -5
@@ -2,7 +2,10 @@ import { chmod, copyFile, mkdir, mkdtemp, readFile, rename, rm, writeFile } from
2 import { createRequire } from 'node:module';
3 import * as path from 'node:path';
4 import { extract as extractTarball } from 'tar';
5 -import { RUN_CODEX_ACP_BINARY_TARGETS } from '../src/services/run-companion-modules';
5 +import {
6 + RUN_CODEX_ACP_BINARY_TARGETS,
7 + type RunCodexAcpBinaryTarget,
8 +} from '../src/services/run-companion-modules';
9
10 const GENERATED_ROOT_DIR = path.resolve('./.generated');
11 const ACP_ADAPTERS_CACHE_DIR = path.join(GENERATED_ROOT_DIR, 'acp-adapters');
@@ -82,12 +85,14 @@ const resolveClaudeAgentSdkPackageJsonPath = (): string => {
85 return nestedRequire.resolve('@anthropic-ai/claude-agent-sdk/package.json');
86 };
87
85 -const buildCacheManifest = async (): Promise<AcpAdaptersManifest> => {
88 +const buildCacheManifest = async (
89 + codexBinaryTargets: ReadonlyArray<RunCodexAcpBinaryTarget>
90 +): Promise<AcpAdaptersManifest> => {
91 const claudePackage = await readInstalledPackageJson('@zed-industries/claude-code-acp');
92 const agentSdkPackage = await readJsonFile<PackageJson>(resolveClaudeAgentSdkPackageJsonPath());
93 const codexLauncherPackage = await readInstalledPackageJson('@zed-industries/codex-acp');
94
90 - const codexTargets = RUN_CODEX_ACP_BINARY_TARGETS.map(target => {
95 + const codexTargets = codexBinaryTargets.map(target => {
96 const version = codexLauncherPackage.optionalDependencies?.[target.packageName];
97 if (!version) {
98 throw new Error(
@@ -296,8 +301,18 @@ const materializeCodexAdapters = async (
301 );
302 };
303
299 -export const materializeAcpAdaptersCache = async (): Promise<string> => {
300 - const manifest = await buildCacheManifest();
304 +/**
305 + * Materializes the ACP adapter cache.
306 + *
307 + * `codexBinaryTargets` narrows which codex-acp binaries are downloaded; release
308 + * builds keep the default (every supported platform), while a build that only
309 + * has to run on the building machine — e.g. the CLI e2e image — passes just its
310 + * own target to avoid downloading ~200MB per foreign platform.
311 + */
312 +export const materializeAcpAdaptersCache = async (
313 + codexBinaryTargets: ReadonlyArray<RunCodexAcpBinaryTarget> = RUN_CODEX_ACP_BINARY_TARGETS
314 +): Promise<string> => {
315 + const manifest = await buildCacheManifest(codexBinaryTargets);
316 const existingManifest = await readExistingManifest();
317
318 if (
ts/packages/cli/scripts/_release-artifacts.ts new
+87
@@ -0,0 +1,87 @@
1 +/**
2 + * Release artifact identity: which platform/arch each published archive targets,
3 + * and which companion assets belong inside it.
4 + *
5 + * Deliberately free of Bun-only imports so the packaging rules stay unit-testable
6 + * under Node.
7 + */
8 +
9 +import { Data, Either } from 'effect';
10 +import {
11 + RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,
12 + runCompanionStaticAssetRelativePathsFor,
13 +} from '../src/services/run-companion-modules';
14 +
15 +export type ReleaseArtifactTarget = {
16 + readonly artifactName: string;
17 + readonly platform: NodeJS.Platform;
18 + readonly arch: string;
19 +};
20 +
21 +/**
22 + * Every published binary artifact, mapped to the Node `platform`/`arch` pair its
23 + * archive runs on. Artifact names use the `aarch64` spelling; Node calls the same
24 + * architecture `arm64`.
25 + */
26 +export const RELEASE_ARTIFACT_TARGETS: ReadonlyArray<ReleaseArtifactTarget> = [
27 + { artifactName: 'composio-darwin-aarch64', platform: 'darwin', arch: 'arm64' },
28 + { artifactName: 'composio-darwin-x64', platform: 'darwin', arch: 'x64' },
29 + { artifactName: 'composio-linux-x64', platform: 'linux', arch: 'x64' },
30 + { artifactName: 'composio-linux-aarch64', platform: 'linux', arch: 'arm64' },
31 +];
32 +
33 +/**
34 + * Known binary artifact names (without extension).
35 + */
36 +export const ARTIFACT_NAMES: ReadonlyArray<string> = RELEASE_ARTIFACT_TARGETS.map(
37 + target => target.artifactName
38 +);
39 +
40 +export class UnknownReleaseArtifactError extends Data.TaggedError(
41 + 'scripts/UnknownReleaseArtifactError'
42 +)<{
43 + readonly artifactName: string;
44 +}> {
45 + get message(): string {
46 + return `Unknown release artifact ${this.artifactName}. Expected one of: ${ARTIFACT_NAMES.join(', ')}.`;
47 + }
48 +}
49 +
50 +/**
51 + * Resolve an artifact name to its platform/arch. The mapping is total over
52 + * {@link RELEASE_ARTIFACT_TARGETS}; anything else fails instead of silently
53 + * producing an archive with no platform-specific assets.
54 + */
55 +export const releaseArtifactTargetFor = (
56 + artifactName: string
57 +): Either.Either<ReleaseArtifactTarget, UnknownReleaseArtifactError> =>
58 + Either.fromNullable(
59 + RELEASE_ARTIFACT_TARGETS.find(target => target.artifactName === artifactName),
60 + () => new UnknownReleaseArtifactError({ artifactName })
61 + );
62 +
63 +/**
64 + * Narrow the full multi-platform companion asset list down to the assets one
65 + * archive should ship: the portable ones plus the single codex-acp binary that
66 + * archive's platform can execute.
67 + *
68 + * An archive already carries a platform-specific `composio` binary, so a
69 + * darwin-arm64 archive is unusable on linux-x64 no matter which codex-acp
70 + * binaries travel with it. Shipping foreign ones only inflates the download.
71 + */
72 +export const archiveCompanionRelativePaths = ({
73 + allRelativePaths,
74 + target,
75 +}: {
76 + readonly allRelativePaths: ReadonlyArray<string>;
77 + readonly target: ReleaseArtifactTarget;
78 +}): ReadonlyArray<string> => {
79 + const included = new Set(runCompanionStaticAssetRelativePathsFor(target));
80 + const excluded = new Set(
81 + RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS.filter(
82 + relativePath => !included.has(relativePath)
83 + )
84 + );
85 +
86 + return allRelativePaths.filter(relativePath => !excluded.has(relativePath));
87 +};
ts/packages/cli/scripts/_shared.ts
+30 -5
@@ -3,7 +3,12 @@ import { chmod, copyFile, mkdir, readdir, rm, stat, writeFile } from 'node:fs/pr
3 import * as path from 'node:path';
4 import process from 'node:process';
5 import { Effect } from 'effect';
6 -import { RUN_COMPANION_MODULE_BASENAMES } from '../src/services/run-companion-modules';
6 +import {
7 + codexAcpBinaryTargetFor,
8 + RUN_CODEX_ACP_BINARY_TARGETS,
9 + RUN_COMPANION_MODULE_BASENAMES,
10 + type RunCodexAcpBinaryTarget,
11 +} from '../src/services/run-companion-modules';
12 import { materializeAcpAdaptersCache } from './_acp-adapters';
13
14 export { teardown } from './_teardown';
@@ -43,13 +48,26 @@ const copyDirectoryRecursive = async (sourceDir: string, targetDir: string): Pro
48 }
49 };
50
46 -const copyBundledAcpAdapters = async (outputDir: string): Promise<void> => {
47 - const acpAdaptersCacheDir = await materializeAcpAdaptersCache();
51 +const copyBundledAcpAdapters = async (
52 + outputDir: string,
53 + codexBinaryTargets: ReadonlyArray<RunCodexAcpBinaryTarget>
54 +): Promise<void> => {
55 + const acpAdaptersCacheDir = await materializeAcpAdaptersCache(codexBinaryTargets);
56 const acpOutputDir = path.join(outputDir, 'acp-adapters');
57 await rm(acpOutputDir, { force: true, recursive: true });
58 await copyDirectoryRecursive(acpAdaptersCacheDir, acpOutputDir);
59 };
60
61 +// The codex-acp binary the building machine can actually execute. Unsupported
62 +// hosts get an empty list, matching the host requirement set the CLI checks.
63 +export const hostCodexAcpBinaryTargets = (): ReadonlyArray<RunCodexAcpBinaryTarget> => {
64 + const hostTarget = codexAcpBinaryTargetFor({
65 + platform: process.platform,
66 + arch: process.arch,
67 + });
68 + return hostTarget ? [hostTarget] : [];
69 +};
70 +
71 export const LOCAL_TOOLS_BINARY_ASSET_DIRNAME = 'local-tools-binaries';
72
73 // Kept out of --env: Bun honors only the last --env, which would clobber DEBUG_OVERRIDE_*.
@@ -302,7 +320,12 @@ const buildCompanionServiceBundles = async (outputDir: string): Promise<void> =>
320 }
321 };
322
305 -export const buildCompanionModules = (outputDir: string) =>
323 +export const buildCompanionModules = (
324 + outputDir: string,
325 + options: {
326 + readonly codexBinaryTargets?: ReadonlyArray<RunCodexAcpBinaryTarget>;
327 + } = {}
328 +) =>
329 Effect.gen(function* () {
330 yield* Effect.tryPromise(() => mkdir(outputDir, { recursive: true }));
331
@@ -314,6 +337,8 @@ export const buildCompanionModules = (outputDir: string) =>
337 yield* Effect.tryPromise(() => writeFile(wrapperPath, wrapperSource, 'utf8'));
338 }
339
317 - yield* Effect.tryPromise(() => copyBundledAcpAdapters(outputDir));
340 + yield* Effect.tryPromise(() =>
341 + copyBundledAcpAdapters(outputDir, options.codexBinaryTargets ?? RUN_CODEX_ACP_BINARY_TARGETS)
342 + );
343 yield* Effect.tryPromise(() => assertBundledRuntimeFiles(outputDir));
344 });
ts/packages/cli/scripts/build-companion-modules.ts new
+67
@@ -0,0 +1,67 @@
1 +#!/usr/bin/env bun
2 +
3 +/**
4 + * Build the `composio run` companion modules next to an already-compiled binary.
5 + *
6 + * `scripts/build-binary.ts` does this as part of a full release build, shipping
7 + * every platform's codex-acp binary. This entry point exists for builds whose
8 + * output only ever runs on the building machine — the CLI e2e image — where
9 + * downloading three foreign codex-acp binaries costs ~600MB and minutes of build
10 + * time for files that machine can never execute.
11 + *
12 + * Usage: `bun scripts/build-companion-modules.ts <OUTPUT_DIR> [--host-only]`
13 + */
14 +
15 +import process from 'node:process';
16 +import { Config, ConfigProvider, Console, Effect, Logger, Layer, LogLevel } from 'effect';
17 +import { BunContext, BunRuntime } from '@effect/platform-bun';
18 +import { buildCompanionModules, hostCodexAcpBinaryTargets, teardown } from './_shared';
19 +import { BinaryBuildError } from './build-error';
20 +
21 +export function buildCompanionModulesCommand() {
22 + return Effect.gen(function* () {
23 + const args = process.argv.slice(2);
24 + const outputDir = args.find(arg => !arg.startsWith('--'));
25 +
26 + if (!outputDir) {
27 + return yield* new BinaryBuildError({
28 + message: 'Missing <OUTPUT_DIR> argument',
29 + exitCode: 1,
30 + });
31 + }
32 +
33 + const hostOnly = args.includes('--host-only');
34 + const codexBinaryTargets = hostOnly ? hostCodexAcpBinaryTargets() : undefined;
35 +
36 + yield* buildCompanionModules(outputDir, { codexBinaryTargets });
37 +
38 + yield* Console.log(
39 + `Companion modules built in ${outputDir}${
40 + hostOnly
41 + ? ` (codex-acp: ${codexBinaryTargets?.map(target => target.relativePath).join(', ') || 'none for this host'})`
42 + : ''
43 + }`
44 + );
45 + });
46 +}
47 +
48 +const ConfigLive = Effect.gen(function* () {
49 + const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(
50 + Config.withDefault(LogLevel.Info)
51 + );
52 +
53 + return Logger.minimumLogLevel(logLevel);
54 +}).pipe(Layer.unwrapEffect, Layer.merge(Layer.setConfigProvider(ConfigProvider.fromEnv())));
55 +
56 +if (require.main === module) {
57 + buildCompanionModulesCommand().pipe(
58 + Effect.provide(ConfigLive),
59 + Effect.provide(Logger.pretty),
60 + Effect.provide(BunContext.layer),
61 + Effect.scoped,
62 + Effect.map(() => ({ message: 'Process completed successfully.' })),
63 + BunRuntime.runMain({
64 + teardown,
65 + })
66 + );
67 +}
ts/packages/cli/scripts/package-binaries.ts
+25 -14
@@ -21,23 +21,21 @@ import { LOCAL_TOOLS_BINARY_ASSET_DIRNAME, teardown } from './_shared';
21 import { $ } from 'bun';
22 import { readdir, stat, writeFile } from 'node:fs/promises';
23 import path from 'node:path';
24 -import { collectExpectedRunCompanionAssetRelativePaths } from '../src/services/run-companion-modules';
24 +import {
25 + collectExpectedRunCompanionAssetRelativePaths,
26 + RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,
27 +} from '../src/services/run-companion-modules';
28 +import {
29 + archiveCompanionRelativePaths,
30 + ARTIFACT_NAMES,
31 + releaseArtifactTargetFor,
32 +} from './_release-artifacts';
33
34 const BINARIES_DIR = './dist/binaries';
35 const COMPANIONS_DIR = path.join(BINARIES_DIR, 'companions');
36 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
31 -/**
32 - * Known binary artifact names (without extension).
33 - */
34 -const ARTIFACT_NAMES = [
35 - 'composio-darwin-aarch64',
36 - 'composio-darwin-x64',
37 - 'composio-linux-x64',
38 - 'composio-linux-aarch64',
39 -];
40 -
39 export function packageBinaries() {
40 return Effect.gen(function* () {
41 const entries = yield* Effect.tryPromise(() => readdir(BINARIES_DIR));
@@ -50,9 +48,14 @@ export function packageBinaries() {
48 return;
49 }
50
53 - const companionRelativePaths =
54 - yield* collectExpectedRunCompanionAssetRelativePaths(COMPANIONS_DIR);
55 - for (const relativePath of companionRelativePaths) {
51 + // One packaging host produces all four archives, so `COMPANIONS_DIR` must hold
52 + // every platform's codex-acp binary before packaging starts. Validate that full
53 + // set up front; each archive then receives only the slice it can execute.
54 + const allCompanionRelativePaths = yield* collectExpectedRunCompanionAssetRelativePaths(
55 + COMPANIONS_DIR,
56 + { staticAssetRelativePaths: RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS }
57 + );
58 + for (const relativePath of allCompanionRelativePaths) {
59 const companionPath = path.join(COMPANIONS_DIR, relativePath);
60 const exists = yield* Effect.tryPromise(() => Bun.file(companionPath).exists());
61 if (!exists) {
@@ -67,6 +70,14 @@ export function packageBinaries() {
70 yield* Console.log(`Packaging ${binaries.length} binaries...`);
71
72 for (const binary of binaries) {
73 + // An archive's `composio` binary is already platform-specific, so a foreign
74 + // codex-acp binary inside it could never run. Ship only this platform's.
75 + const target = yield* releaseArtifactTargetFor(binary);
76 + const companionRelativePaths = archiveCompanionRelativePaths({
77 + allRelativePaths: allCompanionRelativePaths,
78 + target,
79 + });
80 +
81 const binaryPath = path.join(BINARIES_DIR, binary);
82 const zipPath = path.join(BINARIES_DIR, `${binary}.zip`);
83 const absoluteZipPath = path.resolve(zipPath);
ts/packages/cli/src/analytics/dispatch.ts
+23 -19
@@ -13,12 +13,16 @@ import {
13 Schema,
14 } from 'effect';
15 import * as constants from 'src/constants';
16 +import { APP_CONFIG } from 'src/effects/app-config';
17 import { getDetachedWorkerSpawnArgs, spawnDetached } from 'src/services/detached-process';
18 +import { extendConfigProvider } from 'src/services/config';
19 import { atomicWriteFileString } from 'src/utils/atomic-write';
20 import { sha256Hex } from 'src/utils/checksums';
21 import { djb2Hash } from 'src/utils/djb2';
22 import { NodeOs } from 'src/services/node-os';
23 import { TerminalUI } from 'src/services/terminal-ui';
24 +import { isTelemetryDebugEnabled, TELEMETRY_DEBUG_FLAG } from 'src/services/runtime-flags';
25 +import { CliRunId } from 'src/services/runtime-cli-context';
26 import type { AnalyticsEnvelope, TrackEvent } from './types';
27
28 const INTERNAL_ANALYTICS_WORKER_FLAG = '__analytics-worker';
@@ -79,10 +83,6 @@ const configuredString = (value: Option.Option<string>): string | undefined =>
83 Option.getOrUndefined
84 );
85
82 -const telemetryDebugEnabled = environmentProvider.load(
83 - booleanWithDefault('COMPOSIO_CLI_TELEMETRY_DEBUG')
84 -);
85 -
86 const analyticsDisabled = environmentProvider.load(
87 Config.all({
88 cliTelemetryDisabled: booleanWithDefault('COMPOSIO_CLI_TELEMETRY_DISABLED'),
@@ -140,7 +140,7 @@ const encodePrettyJson = Schema.encode(prettyJsonFromString);
140
141 const telemetryDebugLog = (label: string, payload: Record<string, unknown>) =>
142 Effect.gen(function* () {
143 - if (!(yield* telemetryDebugEnabled)) {
143 + if (!(yield* isTelemetryDebugEnabled)) {
144 return;
145 }
146
@@ -523,8 +523,9 @@ const getCliCodactFailuresEndpoint = Effect.map(readApiBaseUrl, baseUrl =>
523 // Delivery is best effort: a failed spawn is swallowed, never surfaced.
524 const spawnWorker = (command: string, args: ReadonlyArray<string>) =>
525 Effect.gen(function* () {
526 - const debugEnabled = yield* telemetryDebugEnabled;
527 - return yield* spawnDetached(command, args, { inheritStderr: debugEnabled }).pipe(
526 + const debugEnabled = yield* isTelemetryDebugEnabled;
527 + const workerArgs = debugEnabled ? [...args, TELEMETRY_DEBUG_FLAG] : args;
528 + return yield* spawnDetached(command, workerArgs, { inheritStderr: debugEnabled }).pipe(
529 Effect.as(true),
530 Effect.catchTag('services/DetachedProcessSpawnError', () => Effect.succeed(false))
531 );
@@ -563,7 +564,7 @@ const captureToPostHog = (envelope: AnalyticsEnvelope) =>
564 );
565 const response = yield* httpClient.execute(request);
566 const responseOk = response.status >= 200 && response.status < 300;
566 - const debugEnabled = yield* telemetryDebugEnabled;
567 + const debugEnabled = yield* isTelemetryDebugEnabled;
568 const responseBody = !responseOk && debugEnabled ? yield* response.text : undefined;
569
570 yield* telemetryDebugLog(
@@ -592,19 +593,22 @@ type CliInvocationContext = {
593 readonly parentRunId?: string;
594 };
595
595 -const getCliInvocationContext = environmentProvider
596 - .load(
596 +// The COMPOSIO_CLI_PARENT_RUN_ID handshake only exists in processes `composio run` spawned. The
597 +// root run process holds its freshly minted id in the CliRunId service instead, so failures it
598 +// reports carry the same run id its children stamp from the environment.
599 +const getCliInvocationContext = Effect.gen(function* () {
600 + const environment = yield* environmentProvider.pipe(extendConfigProvider).load(
601 Config.all({
598 - origin: optionalString('COMPOSIO_CLI_INVOCATION_ORIGIN'),
599 - parentRunId: optionalString('COMPOSIO_CLI_PARENT_RUN_ID'),
602 + origin: APP_CONFIG.CLI_INVOCATION_ORIGIN,
603 + parentRunId: APP_CONFIG.CLI_PARENT_RUN_ID,
604 })
601 - )
602 - .pipe(
603 - Effect.map(({ origin, parentRunId }) => ({
604 - origin: configuredString(origin),
605 - parentRunId: configuredString(parentRunId),
606 - }))
605 );
606 + const mintedRunId = Option.flatten(yield* Effect.serviceOption(CliRunId));
607 + return {
608 + origin: environment.origin,
609 + parentRunId: environment.parentRunId ?? Option.getOrUndefined(mintedRunId),
610 + };
611 +});
612
613 export const createCliCodactFailureBody = (
614 failure: CliCodactFailure,
@@ -658,7 +662,7 @@ const captureToComposioCodactFailures = (failure: CliCodactFailure) =>
662 );
663 const response = yield* httpClient.execute(request);
664 const responseOk = response.status >= 200 && response.status < 300;
661 - const debugEnabled = yield* telemetryDebugEnabled;
665 + const debugEnabled = yield* isTelemetryDebugEnabled;
666 const responseBody = !responseOk && debugEnabled ? yield* response.text : undefined;
667
668 yield* telemetryDebugLog(responseOk ? 'codact_delivery_succeeded' : 'codact_delivery_failed', {
ts/packages/cli/src/analytics/events.ts
+46 -36
@@ -1,6 +1,7 @@
1 import type { CliCommandTelemetryContext, TrackEvent } from './types';
2 import { APP_VERSION } from 'src/constants';
3 import { inferSkillReleaseChannel } from 'src/effects/install-skill';
4 +import type { CliInvocationContext } from 'src/services/runtime-cli-context';
5 import { ToolInputValidationError } from 'src/services/tool-input-validation';
6 import { guessToolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
7
@@ -179,13 +180,6 @@ const TOOL_VALIDATION_CODES: ReadonlySet<number> = new Set([
180 1607, // Upstream_ValidationError
181 3702, // ComposioTools_ValidationError
182 ]);
182 -// A parent `composio run` process hands these values to child CLI invocations through the
183 -// environment at spawn time; the event builders below are plain synchronous functions that
184 -// run outside any Effect context, so effect/Config is not available here.
185 -// eslint-disable-next-line eslint-js/no-restricted-syntax -- spawn-time env handoff read outside Effect
186 -const getInvocationOrigin = (): string => process.env.COMPOSIO_CLI_INVOCATION_ORIGIN ?? 'cli';
187 -// eslint-disable-next-line eslint-js/no-restricted-syntax -- spawn-time env handoff read outside Effect
188 -const getParentRunId = (): string | undefined => process.env.COMPOSIO_CLI_PARENT_RUN_ID;
183
184 const extractCommandPath = (argv: ReadonlyArray<string>): string => {
185 const commandTokens: string[] = [];
@@ -306,9 +300,9 @@ const getExecuteCommandProperties = (context: CliCommandTelemetryContext) => {
300 const slug = getTrailingPositionals(context)[0];
301 return {
302 source: 'cli',
309 - invocation_origin: getInvocationOrigin(),
310 - parent_run_id: getParentRunId(),
311 - parent_command: getParentRunId() ? 'run' : undefined,
303 + invocation_origin: context.invocationOrigin,
304 + parent_run_id: context.parentRunId,
305 + parent_command: context.parentRunId ? 'run' : undefined,
306 cli_version: context.cliVersion,
307 command_path: context.commandPath,
308 duration_ms: Date.now() - context.startedAt,
@@ -332,9 +326,9 @@ const getSearchCommandProperties = (context: CliCommandTelemetryContext) => {
326 const query = getTrailingPositionals(context)[0] ?? '';
327 return {
328 source: 'cli',
335 - invocation_origin: getInvocationOrigin(),
336 - parent_run_id: getParentRunId(),
337 - parent_command: getParentRunId() ? 'run' : undefined,
329 + invocation_origin: context.invocationOrigin,
330 + parent_run_id: context.parentRunId,
331 + parent_command: context.parentRunId ? 'run' : undefined,
332 cli_version: context.cliVersion,
333 command_path: context.commandPath,
334 duration_ms: Date.now() - context.startedAt,
@@ -349,9 +343,9 @@ const getLinkCommandProperties = (context: CliCommandTelemetryContext) => {
343 const firstPositional = getTrailingPositionals(context)[0];
344 return {
345 source: 'cli',
352 - invocation_origin: getInvocationOrigin(),
353 - parent_run_id: getParentRunId(),
354 - parent_command: getParentRunId() ? 'run' : undefined,
346 + invocation_origin: context.invocationOrigin,
347 + parent_run_id: context.parentRunId,
348 + parent_command: context.parentRunId ? 'run' : undefined,
349 cli_version: context.cliVersion,
350 command_path: context.commandPath,
351 duration_ms: Date.now() - context.startedAt,
@@ -364,7 +358,7 @@ const getLinkCommandProperties = (context: CliCommandTelemetryContext) => {
358
359 const getRunCommandProperties = (context: CliCommandTelemetryContext) => ({
360 source: 'cli',
367 - invocation_origin: getInvocationOrigin(),
361 + invocation_origin: context.invocationOrigin,
362 run_id: context.runId,
363 cli_version: context.cliVersion,
364 command_path: context.commandPath,
@@ -380,7 +374,7 @@ const getRunCommandProperties = (context: CliCommandTelemetryContext) => ({
374
375 const getInstallCommandProperties = (context: CliCommandTelemetryContext) => ({
376 source: 'cli',
383 - invocation_origin: getInvocationOrigin(),
377 + invocation_origin: context.invocationOrigin,
378 cli_version: context.cliVersion,
379 command_path: context.commandPath,
380 duration_ms: Date.now() - context.startedAt,
@@ -390,7 +384,7 @@ const getInstallCommandProperties = (context: CliCommandTelemetryContext) => ({
384
385 const getSetupCommandProperties = (context: CliCommandTelemetryContext) => ({
386 source: 'cli',
393 - invocation_origin: getInvocationOrigin(),
387 + invocation_origin: context.invocationOrigin,
388 cli_version: context.cliVersion,
389 command_path: context.commandPath,
390 duration_ms: Date.now() - context.startedAt,
@@ -403,7 +397,7 @@ const getSetupCommandProperties = (context: CliCommandTelemetryContext) => ({
397
398 const getLoginCommandProperties = (context: CliCommandTelemetryContext) => ({
399 source: 'cli',
406 - invocation_origin: getInvocationOrigin(),
400 + invocation_origin: context.invocationOrigin,
401 cli_version: context.cliVersion,
402 command_path: context.commandPath,
403 duration_ms: Date.now() - context.startedAt,
@@ -415,7 +409,7 @@ const getLoginCommandProperties = (context: CliCommandTelemetryContext) => ({
409
410 const getLogoutCommandProperties = (context: CliCommandTelemetryContext) => ({
411 source: 'cli',
418 - invocation_origin: getInvocationOrigin(),
412 + invocation_origin: context.invocationOrigin,
413 cli_version: context.cliVersion,
414 command_path: context.commandPath,
415 duration_ms: Date.now() - context.startedAt,
@@ -423,7 +417,7 @@ const getLogoutCommandProperties = (context: CliCommandTelemetryContext) => ({
417
418 const getProxyCommandProperties = (context: CliCommandTelemetryContext) => ({
419 source: 'cli',
426 - invocation_origin: getInvocationOrigin(),
420 + invocation_origin: context.invocationOrigin,
421 cli_version: context.cliVersion,
422 command_path: context.commandPath,
423 duration_ms: Date.now() - context.startedAt,
@@ -470,13 +464,22 @@ export const getExecuteCommandToolSlug = (
464 ): string | undefined =>
465 isExecuteCommand(context.commandPath) ? getTrailingPositionals(context)[0] : undefined;
466
467 +/**
468 + * Builds the telemetry context of the running command.
469 + *
470 + * `invocation` is read from config by the caller and stamped here so every synchronous event
471 + * builder below takes the origin as an input rather than consulting process-wide state.
472 + */
473 export const createCliCommandTelemetryContext = (
474 argv: ReadonlyArray<string>,
475 cliVersion: string,
476 - terminal: { readonly stdoutIsTTY: boolean; readonly stderrIsTTY: boolean }
476 + terminal: { readonly stdoutIsTTY: boolean; readonly stderrIsTTY: boolean },
477 + invocation: CliInvocationContext
478 ): CliCommandTelemetryContext => ({
479 argv,
480 cliVersion,
481 + invocationOrigin: invocation.invocationOrigin,
482 + parentRunId: invocation.parentRunId,
483 commandPath: extractCommandPath(argv),
484 flagNames: extractFlagNames(argv),
485 stdoutIsTTY: terminal.stdoutIsTTY,
@@ -484,15 +487,14 @@ export const createCliCommandTelemetryContext = (
487 startedAt: Date.now(),
488 runId:
489 extractCommandPath(argv) === 'run'
487 - ? // eslint-disable-next-line eslint-js/no-restricted-syntax -- spawn-time env handoff from parent run
488 - (process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID())
490 + ? (invocation.parentRunId ?? crypto.randomUUID())
491 : undefined,
492 });
493
494 const getCliCommandInvokedEvent = (context: CliCommandTelemetryContext): TrackEvent =>
495 buildEvent(CLI_ANALYTICS_EVENTS.CLI_COMMAND_INVOKED, {
496 source: 'cli',
495 - invocation_origin: getInvocationOrigin(),
497 + invocation_origin: context.invocationOrigin,
498 cli_version: context.cliVersion,
499 command_path: context.commandPath,
500 flag_names: context.flagNames,
@@ -504,7 +506,7 @@ const getCliCommandInvokedEvent = (context: CliCommandTelemetryContext): TrackEv
506 const getCliCommandSucceededEvent = (context: CliCommandTelemetryContext): TrackEvent =>
507 buildEvent(CLI_ANALYTICS_EVENTS.CLI_COMMAND_SUCCEEDED, {
508 source: 'cli',
507 - invocation_origin: getInvocationOrigin(),
509 + invocation_origin: context.invocationOrigin,
510 cli_version: context.cliVersion,
511 command_path: context.commandPath,
512 duration_ms: Date.now() - context.startedAt,
@@ -517,7 +519,7 @@ const getCliCommandFailedEvent = (
519 ): TrackEvent =>
520 buildEvent(CLI_ANALYTICS_EVENTS.CLI_COMMAND_FAILED, {
521 source: 'cli',
520 - invocation_origin: getInvocationOrigin(),
522 + invocation_origin: context.invocationOrigin,
523 cli_version: context.cliVersion,
524 command_path: context.commandPath,
525 duration_ms: Date.now() - context.startedAt,
@@ -640,6 +642,7 @@ export const getPluginLifecycleSucceededEvent = (params: {
642 readonly operation: 'setup' | 'uninstall';
643 readonly target: 'claude' | 'codex';
644 readonly action: 'installed' | 'enabled' | 'configured' | 'uninstalled';
645 + readonly invocationOrigin: string;
646 readonly cliVersion: string;
647 }): TrackEvent =>
648 buildEvent(
@@ -648,7 +651,7 @@ export const getPluginLifecycleSucceededEvent = (params: {
651 : CLI_ANALYTICS_EVENTS.CLI_PLUGIN_SETUP_SUCCEEDED,
652 {
653 source: 'cli',
651 - invocation_origin: getInvocationOrigin(),
654 + invocation_origin: params.invocationOrigin,
655 cli_version: params.cliVersion,
656 command_path: 'setup',
657 operation: params.operation,
@@ -662,11 +665,12 @@ export const getPluginLifecycleFailedEvent = (params: {
665 readonly target: 'claude' | 'codex';
666 readonly phase: 'install' | 'uninstall';
667 readonly error: unknown;
668 + readonly invocationOrigin: string;
669 readonly cliVersion: string;
670 }): TrackEvent =>
671 buildEvent(CLI_ANALYTICS_EVENTS.CLI_PLUGIN_SETUP_FAILED, {
672 source: 'cli',
669 - invocation_origin: getInvocationOrigin(),
673 + invocation_origin: params.invocationOrigin,
674 cli_version: params.cliVersion,
675 command_path: 'setup',
676 operation: params.operation,
@@ -684,11 +688,12 @@ export const getSetupHostDetectedEvent = (params: {
688 readonly hostVersion?: string;
689 readonly unsupportedReasonCode?:
690 'codex_too_old' | 'no_json_inspection' | 'host_command_failed' | 'unknown';
691 + readonly invocationOrigin: string;
692 readonly cliVersion: string;
693 }): TrackEvent =>
694 buildEvent(CLI_ANALYTICS_EVENTS.CLI_SETUP_HOST_DETECTED, {
695 source: 'cli',
691 - invocation_origin: getInvocationOrigin(),
696 + invocation_origin: params.invocationOrigin,
697 cli_version: params.cliVersion,
698 command_path: 'setup',
699 operation: params.operation,
@@ -703,11 +708,12 @@ export const getSetupHostDetectedEvent = (params: {
708 export const getSetupCancelledEvent = (params: {
709 readonly operation: 'setup' | 'uninstall';
710 readonly requestedTarget: 'auto' | 'claude' | 'codex' | 'all';
711 + readonly invocationOrigin: string;
712 readonly cliVersion: string;
713 }): TrackEvent =>
714 buildEvent(CLI_ANALYTICS_EVENTS.CLI_SETUP_CANCELLED, {
715 source: 'cli',
710 - invocation_origin: getInvocationOrigin(),
716 + invocation_origin: params.invocationOrigin,
717 cli_version: params.cliVersion,
718 command_path: 'setup',
719 operation: params.operation,
@@ -718,11 +724,12 @@ export const getSetupCancelledEvent = (params: {
724 export const getSetupSkippedEvent = (params: {
725 readonly operation: 'setup' | 'uninstall';
726 readonly requestedTarget: 'auto' | 'claude' | 'codex' | 'all';
727 + readonly invocationOrigin: string;
728 readonly cliVersion: string;
729 }): TrackEvent =>
730 buildEvent(CLI_ANALYTICS_EVENTS.CLI_SETUP_SKIPPED, {
731 source: 'cli',
725 - invocation_origin: getInvocationOrigin(),
732 + invocation_origin: params.invocationOrigin,
733 cli_version: params.cliVersion,
734 command_path: 'setup',
735 operation: params.operation,
@@ -735,6 +742,7 @@ export const getToolExecuteValidationFailedEvent = (params: {
742 readonly toolkitSlug?: string;
743 readonly args: Record<string, unknown>;
744 readonly error: ToolInputValidationError;
745 + readonly invocationOrigin: string;
746 readonly surface: 'root' | 'dev';
747 readonly projectMode: 'consumer' | 'developer';
748 readonly stage: 'dry_run' | 'validation' | 'execution';
@@ -743,7 +751,7 @@ export const getToolExecuteValidationFailedEvent = (params: {
751 }): TrackEvent =>
752 buildEvent(CLI_ANALYTICS_EVENTS.CLI_TOOL_INVOCATION_VALIDATION_FAILED, {
753 source: 'cli',
746 - invocation_origin: getInvocationOrigin(),
754 + invocation_origin: params.invocationOrigin,
755 tool_slug: params.toolSlug,
756 toolkit_slug: params.toolkitSlug ?? guessToolkitFromToolSlug(params.toolSlug),
757 surface: params.surface,
@@ -785,6 +793,7 @@ export const getToolExecuteToolNotFoundEvent = (params: {
793 readonly toolSlug: string;
794 readonly toolkitSlug?: string;
795 readonly args: Record<string, unknown>;
796 + readonly invocationOrigin: string;
797 readonly surface: 'root' | 'dev';
798 readonly projectMode: 'consumer' | 'developer';
799 readonly stage: 'schema_fetch' | 'dry_run' | 'execution';
@@ -797,7 +806,7 @@ export const getToolExecuteToolNotFoundEvent = (params: {
806 }): TrackEvent =>
807 buildEvent(CLI_ANALYTICS_EVENTS.CLI_TOOL_INVOCATION_TOOL_NOT_FOUND, {
808 source: 'cli',
800 - invocation_origin: getInvocationOrigin(),
809 + invocation_origin: params.invocationOrigin,
810 tool_slug: params.toolSlug,
811 toolkit_slug: params.toolkitSlug ?? guessToolkitFromToolSlug(params.toolSlug),
812 surface: params.surface,
@@ -815,6 +824,7 @@ export const getToolExecuteFailedEvent = (params: {
824 readonly toolSlug: string;
825 readonly toolkitSlug?: string;
826 readonly args: Record<string, unknown>;
827 + readonly invocationOrigin: string;
828 readonly surface: 'root' | 'dev';
829 readonly projectMode: 'consumer' | 'developer';
830 readonly stage: 'schema_fetch' | 'dry_run' | 'execution';
@@ -829,7 +839,7 @@ export const getToolExecuteFailedEvent = (params: {
839 }): TrackEvent =>
840 buildEvent(CLI_ANALYTICS_EVENTS.CLI_TOOL_INVOCATION_FAILED, {
841 source: 'cli',
832 - invocation_origin: getInvocationOrigin(),
842 + invocation_origin: params.invocationOrigin,
843 tool_slug: params.toolSlug,
844 toolkit_slug: params.toolkitSlug ?? guessToolkitFromToolSlug(params.toolSlug),
845 surface: params.surface,
ts/packages/cli/src/analytics/types.ts
+4
@@ -15,6 +15,10 @@ export type AnalyticsEnvelope = {
15 export type CliCommandTelemetryContext = {
16 readonly argv: ReadonlyArray<string>;
17 readonly cliVersion: string;
18 + /** Who invoked this CLI process (`cli`, `run`, `installer`, …). */
19 + readonly invocationOrigin: string;
20 + /** Run id of the `composio run` that spawned this process, when there is one. */
21 + readonly parentRunId: string | undefined;
22 readonly commandPath: string;
23 readonly flagNames: ReadonlyArray<string>;
24 readonly stdoutIsTTY: boolean;
ts/packages/cli/src/bin.ts
+18 -27
@@ -5,35 +5,25 @@ import { BunFileSystem, BunPath, BunRuntime } from '@effect/platform-bun';
5 import { isBackgroundWorkerInvocation, runBackgroundWorkerFromArgv } from 'src/analytics/dispatch';
6 import { NodeOs } from 'src/services/node-os';
7 import { TerminalUILive } from 'src/services/terminal-ui';
8 +import { stripTelemetryDebugFlag, telemetryDebugModeLayer } from 'src/services/runtime-flags';
9
9 -const TELEMETRY_DEBUG_FLAG = '--telemetry-debug';
10 -const CLI_TELEMETRY_DEBUG_ENV_VAR = 'COMPOSIO_CLI_TELEMETRY_DEBUG';
10 +const bootstrap = stripTelemetryDebugFlag(process.argv);
11 +process.argv = [...bootstrap.argv];
12
12 -const stripTelemetryDebugFlag = (argv: ReadonlyArray<string>): string[] => {
13 - const normalizedArgv = [...argv];
14 - const flagIndex = normalizedArgv.indexOf(TELEMETRY_DEBUG_FLAG);
15 - if (flagIndex < 0) {
16 - return normalizedArgv;
17 - }
13 +const workerLayers = Layer.mergeAll(
14 + BunFileSystem.layer,
15 + BunPath.layer,
16 + FetchHttpClient.layer,
17 + NodeOs.Default,
18 + TerminalUILive
19 +);
20
19 - normalizedArgv.splice(flagIndex, 1);
20 - // Bootstrap runs before the Effect runtime and ConfigProvider exist; the stripped flag is
21 - // persisted as an env var so later effect/Config reads and child processes observe it.
22 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- pre-runtime env write during bootstrap
23 - process.env[CLI_TELEMETRY_DEBUG_ENV_VAR] = 'true';
24 - return normalizedArgv;
25 -};
26 -
27 -if (isBackgroundWorkerInvocation(process.argv)) {
28 - runBackgroundWorkerFromArgv(process.argv).pipe(
21 +if (isBackgroundWorkerInvocation(bootstrap.argv)) {
22 + runBackgroundWorkerFromArgv(bootstrap.argv).pipe(
23 Effect.provide(
30 - Layer.mergeAll(
31 - BunFileSystem.layer,
32 - BunPath.layer,
33 - FetchHttpClient.layer,
34 - NodeOs.Default,
35 - TerminalUILive
36 - )
24 + bootstrap.telemetryDebug
25 + ? Layer.merge(workerLayers, telemetryDebugModeLayer(true))
26 + : workerLayers
27 ),
28 effect =>
29 BunRuntime.runMain(effect, {
@@ -42,6 +32,7 @@ if (isBackgroundWorkerInvocation(process.argv)) {
32 })
33 );
34 } else {
45 - process.argv = stripTelemetryDebugFlag(process.argv);
46 - void import('./cli-main');
35 + void import('./cli-main').then(({ runCli }) =>
36 + runCli({ telemetryDebug: bootstrap.telemetryDebug })
37 + );
38 }
ts/packages/cli/src/cli-main.ts
+59 -20
@@ -5,7 +5,7 @@ import { CliConfig, HelpDoc, ValidationError } from '@effect/cli';
5 import { FetchHttpClient } from '@effect/platform';
6 import { BunContext, BunRuntime, BunFileSystem, BunPath } from '@effect/platform-bun';
7 import type { Teardown } from '@effect/platform/Runtime';
8 -import { buildRootCommand, runWithConfig } from 'src/commands';
8 +import { buildRootCommand, runWithConfig, type RootCommandBootstrap } from 'src/commands';
9 import { collectValueOptionNames } from 'src/commands/command-introspection';
10 import { matchCommandFromArgv, getCommandHelpText } from 'src/commands/root-help';
11 import * as constants from 'src/constants';
@@ -48,6 +48,9 @@ import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overri
48 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
49 import { SetupCommandError } from 'src/services/setup';
50 import { ShellSetupAbortError } from 'src/commands/install.cmd';
51 +import { MissingRunSourceError } from 'src/commands/run.cmd';
52 +import { cliInvocationContext } from 'src/services/runtime-cli-context';
53 +import { telemetryDebugModeLayer } from 'src/services/runtime-flags';
54
55 // Layer is contravariant in ROut and covariant in E, so `never`/`unknown` accept any
56 // produced context and error type while still pinning the requirements (RIn) to `never`.
@@ -146,15 +149,19 @@ const layers = Layer.mergeAll(
149
150 export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: number) => void) => {
151 const shouldFail = Exit.isFailure(exit) && !Cause.isInterruptedOnly(exit.cause);
149 - const errorCode = Number(process.exitCode ?? 1);
150 - onExit(shouldFail ? errorCode : 0);
152 + // A command that proxies another process (`composio run`) reports its status by assigning
153 + // `process.exitCode`, so honor that on every path. It matters most on interrupt: the runtime
154 + // force-exits with whatever code teardown yields once a signal has been received, which would
155 + // otherwise turn a cancelled run into a success.
156 + onExit(Number(process.exitCode ?? (shouldFail ? 1 : 0)));
157 };
158
153 -const runWithArgs = Effect.flatMap(runWithConfig, run => run(process.argv)) satisfies Effect.Effect<
154 - void,
155 - unknown,
156 - unknown
157 ->;
159 +const runWithArgs = (bootstrap: RootCommandBootstrap) =>
160 + Effect.flatMap(runWithConfig, run => run(process.argv, bootstrap)) satisfies Effect.Effect<
161 + void,
162 + unknown,
163 + unknown
164 + >;
165
166 const runWithTelemetry = Effect.gen(function* () {
167 const ui = yield* TerminalUI;
@@ -162,21 +169,25 @@ const runWithTelemetry = Effect.gen(function* () {
169
170 const version = yield* getVersion;
171 configureCliAnalyticsReleaseVersion(version);
165 - const baseTelemetryContext = createCliCommandTelemetryContext(process.argv, version, terminal);
172 + const baseTelemetryContext = createCliCommandTelemetryContext(
173 + process.argv,
174 + version,
175 + terminal,
176 + yield* cliInvocationContext
177 + );
178 const executeToolSlug = getExecuteCommandToolSlug(baseTelemetryContext);
179 const commandTelemetryContext =
180 executeToolSlug === undefined
181 ? baseTelemetryContext
182 : { ...baseTelemetryContext, toolkitSlug: yield* toolkitFromToolSlug(executeToolSlug) };
171 - if (commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId) {
172 - // effect/Config is read-only; the run id must be written into the environment so the run
173 - // command and the child processes it spawns observe the same telemetry run id.
174 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- env write propagates run id to children
175 - process.env.COMPOSIO_CLI_PARENT_RUN_ID = commandTelemetryContext.runId;
176 - }
177 -
183 + // `composio run` mints its run id here so the lifecycle events and the id the spawned script
184 + // inherits are the same value; every other command leaves it unset.
185 + const bootstrap: RootCommandBootstrap =
186 + commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId
187 + ? { runId: commandTelemetryContext.runId }
188 + : {};
189 return yield* trackCliEventEffect(getPrimaryLifecycleInvokedEvent(commandTelemetryContext)).pipe(
179 - Effect.andThen(runWithArgs),
190 + Effect.andThen(runWithArgs(bootstrap)),
191 Effect.scoped,
192 Effect.mapError(error =>
193 ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })
@@ -192,7 +203,15 @@ const runWithTelemetry = Effect.gen(function* () {
203 );
204 });
205
195 -showUpdateNotice.pipe(
206 +/**
207 + * Values `src/bin.ts` resolved before the Effect runtime existed and hands to it here.
208 + */
209 +export type CliBootstrapOptions = {
210 + /** `--telemetry-debug` was on the command line, and was stripped from argv before parsing. */
211 + readonly telemetryDebug: boolean;
212 +};
213 +
214 +const cliProgram = showUpdateNotice.pipe(
215 Effect.andThen(showPluginAcquisitionHint(process.argv)),
216 Effect.andThen(runWithTelemetry),
217 Effect.catchIf(ValidationError.isValidationError, error => {
@@ -242,6 +261,17 @@ showUpdateNotice.pipe(
261 process.exitCode = 1;
262 })
263 ),
264 + // A bare `composio run` is a usage mistake, not a broken invariant: print the one-line fix and
265 + // exit non-zero instead of routing it through the defect reporter below.
266 + Effect.catchIf(
267 + (error): error is MissingRunSourceError => error instanceof MissingRunSourceError,
268 + error =>
269 + Effect.gen(function* () {
270 + const ui = yield* TerminalUI;
271 + yield* ui.error(error.message);
272 + process.exitCode = 1;
273 + })
274 + ),
275 Effect.catchIf(
276 (error): error is ShellSetupAbortError => error instanceof ShellSetupAbortError,
277 // `composio install` already printed the abort reason; the typed failure
@@ -296,6 +326,15 @@ showUpdateNotice.pipe(
326 })
327 ),
328 Effect.provide(layers),
299 - Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive)),
300 - BunRuntime.runMain({ teardown })
329 + Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive))
330 );
331 +
332 +export const runCli = (options: CliBootstrapOptions): void => {
333 + cliProgram.pipe(
334 + // Only provided when the flag was actually present: without it telemetry debugging falls back
335 + // to `COMPOSIO_CLI_TELEMETRY_DEBUG`.
336 + effect =>
337 + options.telemetryDebug ? Effect.provide(effect, telemetryDebugModeLayer(true)) : effect,
338 + BunRuntime.runMain({ teardown })
339 + );
340 +};
ts/packages/cli/src/commands/index.ts
+37 -29
@@ -1,5 +1,4 @@
1 -import process from 'node:process';
2 -import { Array as Arr, Data, Effect, HashSet, Option } from 'effect';
1 +import { Array as Arr, Data, Effect, HashSet, Layer, Option } from 'effect';
2 import { Command, HelpDoc, ValidationError } from '@effect/cli';
3 import {
4 hasCommandName,
@@ -45,11 +44,12 @@ import { configCmd } from './config/config.cmd';
44 import { rootConnectionsCmd } from './connections/connections.cmd';
45 import { agentCmd } from './agent/agent.cmd';
46 import { renderCommandHintGraph } from 'src/services/command-hints';
48 -import { resetRuntimeDebugFlags, setRuntimeDebugFlags } from 'src/services/runtime-debug-flags';
47 +import { cliDebugFlagsLayer, type CliDebugFlagOverrides } from 'src/services/runtime-flags';
48 +import { cliRunIdLayer } from 'src/services/runtime-cli-context';
49 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
50 import { ComposioUserContext } from 'src/services/user-context';
51 import { TerminalUI } from 'src/services/terminal-ui';
52 -import { detectMaster } from 'src/services/master-detector';
52 +import { detectMasterFromHost } from 'src/services/master-detector';
53 import {
54 formatResolveCommandProjectError,
55 resolveCommandProject,
@@ -285,7 +285,16 @@ const parseBooleanFlag = (argument: string, name: string): Option.Option<boolean
285 return argument === `${name}=false` ? Option.some(false) : Option.none();
286 };
287
288 -const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
288 +/**
289 + * Splits the hidden debug flags off argv and returns their parsed values.
290 + *
291 + * The values are inputs to the command that follows — `src/commands/index.ts` provides them as
292 + * `CliDebugFlags` — rather than process-wide state, so an explicit `--perf-debug=false` on one
293 + * invocation cannot leak into the next.
294 + */
295 +const normalizeHiddenDebugFlags = (
296 + argv: ReadonlyArray<string>
297 +): { readonly argv: ReadonlyArray<string>; readonly overrides: CliDebugFlagOverrides } => {
298 const retainedArgs: Array<string> = [];
299 let perfDebug: boolean | undefined;
300 let toolDebug: boolean | undefined;
@@ -310,22 +319,10 @@ const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<s
319 retainedArgs.push(argument);
320 }
321
313 - resetRuntimeDebugFlags();
314 - setRuntimeDebugFlags({
315 - ...(perfDebug === undefined ? {} : { perfDebug }),
316 - ...(toolDebug === undefined ? {} : { toolDebug }),
317 - });
318 - // The hidden --acp-only flag is stripped from argv before @effect/cli parses it, so its value
319 - // travels to run.cmd.ts through the environment; effect/Config cannot write or delete env vars.
320 - if (acpOnly === undefined) {
321 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- env delete clears a stale hidden-flag value
322 - delete process.env.COMPOSIO_RUN_ACP_ONLY;
323 - } else {
324 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- env write hands the stripped flag to run.cmd
325 - process.env.COMPOSIO_RUN_ACP_ONLY = acpOnly ? '1' : '0';
326 - }
327 -
328 - return Arr.appendAll(Arr.take(argv, 2), retainedArgs);
322 + return {
323 + argv: Arr.appendAll(Arr.take(argv, 2), retainedArgs),
324 + overrides: { perfDebug, toolDebug, acpOnly },
325 + };
326 };
327
328 const isRootHelp = (argv: ReadonlyArray<string>): boolean => {
@@ -435,11 +432,11 @@ const printDebugApiInfo = Effect.gen(function* () {
432 );
433 });
434
438 -const printDetectedMaster = Effect.suspend(() =>
439 - Effect.flatMap(TerminalUI, ui =>
440 - ui.output(JSON.stringify({ master: detectMaster() }, null, 2), { force: true })
441 - )
442 -);
435 +const printDetectedMaster = Effect.gen(function* () {
436 + const ui = yield* TerminalUI;
437 + const master = yield* detectMasterFromHost;
438 + yield* ui.output(JSON.stringify({ master }, null, 2), { force: true });
439 +});
440
441 const printDevModeDisabled = Effect.gen(function* () {
442 const ui = yield* TerminalUI;
@@ -447,6 +444,16 @@ const printDevModeDisabled = Effect.gen(function* () {
444 yield* ui.log.step('Run `composio dev --mode on` in an interactive terminal to enable it.');
445 });
446
447 +/**
448 + * Values the CLI bootstrap resolved before the root command runs and that the command tree needs
449 + * as an input. Empty for callers that drive the root command on their own (tests, `--install-skill`
450 + * style entry points), which is why every field is optional.
451 + */
452 +export type RootCommandBootstrap = {
453 + /** Run id minted for a `composio run` invocation, shared with its telemetry events. */
454 + readonly runId?: string;
455 +};
456 +
457 export const runWithConfig = Effect.gen(function* () {
458 const cliUserConfig = yield* ComposioCliUserConfig;
459 const visibility: CommandVisibility = {
@@ -521,10 +528,10 @@ export const runWithConfig = Effect.gen(function* () {
528 );
529 };
530
524 - return (argv: ReadonlyArray<string>) => {
531 + return (argv: ReadonlyArray<string>, bootstrap: RootCommandBootstrap = {}) => {
532 const { argv: argvWithoutDangerouslyAllow, dangerouslyAllow } =
533 normalizeDangerouslyAllowFlag(argv);
527 - const normalizedArgv = normalizeHiddenDebugFlags(
534 + const { argv: normalizedArgv, overrides } = normalizeHiddenDebugFlags(
535 normalizeListenStreamFlag(normalizeVersionShortFlag(argvWithoutDangerouslyAllow))
536 );
537
@@ -534,7 +541,8 @@ export const runWithConfig = Effect.gen(function* () {
541 onNone: () => routeRootCommand(normalizedArgv, dangerouslyAllow),
542 onSome: installSkill,
543 })
537 - )
544 + ),
545 + Effect.provide(Layer.merge(cliDebugFlagsLayer(overrides), cliRunIdLayer(bootstrap.runId)))
546 );
547 };
548 });
ts/packages/cli/src/commands/install.cmd.ts
+5 -15
@@ -2,6 +2,7 @@ import { Command, Options } from '@effect/cli';
2 import { FileSystem, Path } from '@effect/platform';
3 import type { PlatformError } from '@effect/platform/Error';
4 import { Array as Arr, Config, ConfigProvider, Data, Effect, Option } from 'effect';
5 +import { APP_CONFIG } from 'src/effects/app-config';
6 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
7 import { NodeOs } from 'src/services/node-os';
8 import { NodeProcess } from 'src/services/node-process';
@@ -83,21 +84,10 @@ const COMPLETIONS_MARKER = '# Composio CLI completions';
84 const UNSAFE_PATH_CHARS = /[`$"\\\n\r:]/;
85 const isUnsafePath = (p: string): boolean => UNSAFE_PATH_CHARS.test(p);
86
86 -// SHELL, PATH, and COMPOSIO_BIN_DIR are read from the literal environment: SHELL
87 -// and PATH are POSIX-standard (no app prefix applies to them), and COMPOSIO_BIN_DIR
88 -// is already the full env var name, not a suffix the app's `COMPOSIO_`-prefixing
89 -// ambient config provider should prefix again. Read them from a raw provider
90 -// instead (precedent: `src/analytics/dispatch.ts`'s `environmentProvider`).
87 +// SHELL and PATH are POSIX-standard host variables, so the CLI's COMPOSIO_
88 +// prefix does not apply to them.
89 const environmentProvider = ConfigProvider.fromEnv();
90
93 -/** Read an optional env var from the raw environment; provider errors die rather than fail the command. */
94 -const readOptionalEnv = (name: string): Effect.Effect<string | undefined> =>
95 - Effect.orDie(
96 - environmentProvider.load(
97 - Config.option(Config.string(name)).pipe(Config.map(Option.getOrUndefined))
98 - )
99 - );
100 -
91 /** Read an env var from the raw environment, falling back when unset. */
92 const readEnvWithDefault = (name: string, fallback: string): Effect.Effect<string> =>
93 Effect.orDie(environmentProvider.load(Config.string(name).pipe(Config.withDefault(fallback))));
@@ -658,7 +648,7 @@ export const installShellIntegration = (params: {
648
649 // Resolve the entry-point bin dir: explicit env, then a ~/.local/bin/composio
650 // that is this executable, then the runtime executable's own directory.
661 - const envBinDir = yield* readOptionalEnv('COMPOSIO_BIN_DIR');
651 + const envBinDir = yield* APP_CONFIG.BIN_DIR.pipe(Effect.orDie);
652 const localBinDir = path.join(os.homedir, '.local', 'bin');
653 const execPath = nodeProcess.execPath;
654 const localBinComposioIsCurrentExecutable = yield* resolvesToCurrentExecutable(
@@ -696,7 +686,7 @@ export const installShellIntegration = (params: {
686 // prints the final action block itself. Keep the concise per-file status
687 // lines but suppress the boxed restart hint so the CLI never prints a
688 // competing instruction.
699 - const invocationOrigin = yield* readOptionalEnv('COMPOSIO_CLI_INVOCATION_ORIGIN');
689 + const invocationOrigin = yield* APP_CONFIG.CLI_INVOCATION_ORIGIN.pipe(Effect.orDie);
690 const installerOwnsFinalMessaging = invocationOrigin === 'installer';
691
692 const shellEnv = yield* readEnvWithDefault('SHELL', '');
ts/packages/cli/src/commands/run.cmd.ts
+334 -174
@@ -1,20 +1,23 @@
1 -// eslint-disable-next-line no-restricted-imports -- synchronous fs (mkdtempSync/writeFileSync/rmSync/existsSync) builds and tears down the run preload files in plain helpers that execute outside the Effect runtime
2 -import * as fs from 'node:fs';
3 -// eslint-disable-next-line no-restricted-imports -- os.tmpdir and os.homedir locate the preload scratch directory and ~/.composio in the same synchronous helpers
4 -import * as os from 'node:os';
1 import process from 'node:process';
6 -import { pathToFileURL } from 'node:url';
2 import { Args, Command, Options } from '@effect/cli';
8 -import { FileSystem, Path } from '@effect/platform';
9 -import { Effect, Option } from 'effect';
3 +import { Command as PlatformCommand, CommandExecutor, FileSystem, Path } from '@effect/platform';
4 +import { Data, Deferred, Duration, Effect, Either, MutableRef, Option } from 'effect';
5 import { ts } from 'ts-morph';
6 import { APP_VERSION } from 'src/constants';
7 +import { APP_CONFIG, UNPREFIXED_CONFIG } from 'src/effects/app-config';
8 import { resolveCommandProject } from 'src/services/command-project';
9 import { type RunHelperContext } from 'src/services/run-helpers-runtime';
10 import { warmToolInputDefinitions } from 'src/services/tool-input-validation';
11 import { ComposioUserContext } from 'src/services/user-context';
16 -import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';
17 -import { detectMaster } from 'src/services/master-detector';
12 +import {
13 + debugFlagsToChildEnv,
14 + isAcpOnlyEnabled,
15 + isPerfDebugEnabled,
16 + isTelemetryDebugEnabled,
17 + isToolDebugEnabled,
18 +} from 'src/services/runtime-flags';
19 +import { detectMasterFromHost } from 'src/services/master-detector';
20 +import { cliInvocationContext, CliRunId } from 'src/services/runtime-cli-context';
21 import {
22 repairMissingInstalledRunCompanionModules,
23 resolveRunCompanionModulePath,
@@ -25,6 +28,9 @@ import {
28 } from 'src/services/cli-session-artifacts';
29 import { USER_COMPOSIO_DIR } from 'src/constants';
30 import { TerminalUI } from 'src/services/terminal-ui';
31 +import { loadHostConfig } from 'src/services/config';
32 +import { resolveCliConfigPath } from 'src/services/cli-user-config';
33 +import { NodeOs } from 'src/services/node-os';
34
35 const file = Options.text('file').pipe(
36 Options.withAlias('f'),
@@ -152,24 +158,26 @@ export const wrapFileSourceForRun = (source: string): string => {
158 export const inferCliInvocationPrefix = (
159 path: Path.Path,
160 argv: ReadonlyArray<string> = process.argv
155 -): ReadonlyArray<string> => {
156 - const entrypoint = argv[1];
157 - if (!entrypoint) {
158 - return [process.execPath];
159 - }
161 +) =>
162 + Effect.gen(function* () {
163 + const entrypoint = argv[1];
164 + if (!entrypoint) {
165 + return [process.execPath];
166 + }
167
161 - // Compiled Bun binaries report an internal $bunfs entrypoint which cannot be
162 - // re-executed as a real filesystem path. In that case the binary itself is
163 - // the CLI entrypoint.
164 - if (entrypoint.startsWith('/$bunfs/')) {
165 - return [process.execPath];
166 - }
168 + // Compiled Bun binaries report an internal $bunfs entrypoint which cannot be
169 + // re-executed as a real filesystem path. In that case the binary itself is
170 + // the CLI entrypoint.
171 + if (entrypoint.startsWith('/$bunfs/')) {
172 + return [process.execPath];
173 + }
174
168 - const resolvedEntrypoint = path.resolve(entrypoint);
169 - return fs.existsSync(resolvedEntrypoint)
170 - ? [process.execPath, resolvedEntrypoint]
171 - : [process.execPath];
172 -};
175 + const fs = yield* FileSystem.FileSystem;
176 + const resolvedEntrypoint = path.resolve(entrypoint);
177 + return (yield* fs.exists(resolvedEntrypoint))
178 + ? [process.execPath, resolvedEntrypoint]
179 + : [process.execPath];
180 + });
181
182 type RunHelperModuleUrls = {
183 readonly helpersRuntimeModuleUrl: string;
@@ -179,14 +187,16 @@ const resolveRunHelperModuleUrls: Effect.Effect<
187 RunHelperModuleUrls,
188 never,
189 FileSystem.FileSystem | Path.Path
182 -> = Effect.map(
183 - resolveRunCompanionModulePath({
190 +> = Effect.gen(function* () {
191 + const path = yield* Path.Path;
192 + const modulePath = yield* resolveRunCompanionModulePath({
193 callerImportMetaUrl: import.meta.url,
194 execPath: process.execPath,
195 relativeNoExtensionFromCaller: '../services/run-helpers-runtime',
187 - }),
188 - modulePath => ({ helpersRuntimeModuleUrl: pathToFileURL(modulePath).href })
189 -);
196 + });
197 + const moduleUrl = yield* Effect.orDie(path.toFileUrl(modulePath));
198 + return { helpersRuntimeModuleUrl: moduleUrl.href };
199 +});
200 export const buildRunHelpersSource = (
201 cliPrefix: ReadonlyArray<string>,
202 context: RunHelperContext = {},
@@ -203,40 +213,64 @@ const createRunHelpersPreloadFile = (
213 cliPrefix: ReadonlyArray<string>,
214 context: RunHelperContext,
215 moduleUrls: RunHelperModuleUrls
206 -) => {
207 - const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-'));
208 - const preloadPath = path.join(directory, 'globals.mjs');
209 - const runOutputDir =
210 - typeof context.runOutputDir === 'string' && context.runOutputDir.length > 0
211 - ? context.runOutputDir
212 - : path.join(directory, 'artifacts');
213 - const runLogFilePath = path.join(runOutputDir, 'run.log');
214 - const readAccessRoots = [
215 - ...new Set(
216 - [
217 - ...(Array.isArray(context.readAccessRoots) ? context.readAccessRoots : []),
218 - runOutputDir,
219 - ].map(value => path.resolve(value))
220 - ),
221 - ];
222 - fs.mkdirSync(runOutputDir, { recursive: true });
223 - fs.writeFileSync(runLogFilePath, '', 'utf8');
224 - fs.writeFileSync(
225 - preloadPath,
226 - buildRunHelpersSource(
227 - cliPrefix,
228 - {
229 - ...context,
230 - runOutputDir,
231 - runLogFilePath,
232 - readAccessRoots,
233 - },
234 - moduleUrls
235 - ),
236 - 'utf8'
237 - );
238 - return { directory, preloadPath, runOutputDir, runLogFilePath };
239 -};
216 +) =>
217 + Effect.gen(function* () {
218 + const fs = yield* FileSystem.FileSystem;
219 + const os = yield* NodeOs;
220 + const directory = yield* fs.makeTempDirectoryScoped({
221 + directory: os.tmpdir,
222 + prefix: 'composio-run-',
223 + });
224 + const preloadPath = path.join(directory, 'globals.mjs');
225 + // The preload directory is scoped and removed when the run ends, but the run log and any
226 + // large tool outputs are advertised to the caller on stderr (`RUN_LOG_FILE=`) and must
227 + // outlive the process that printed them, so they get their own unscoped directory.
228 + const runOutputDir =
229 + typeof context.runOutputDir === 'string' && context.runOutputDir.length > 0
230 + ? context.runOutputDir
231 + : yield* fs.makeTempDirectory({ directory: os.tmpdir, prefix: 'composio-run-artifacts-' });
232 + const runLogFilePath = path.join(runOutputDir, 'run.log');
233 + const readAccessRoots = [
234 + ...new Set(
235 + [
236 + ...(Array.isArray(context.readAccessRoots) ? context.readAccessRoots : []),
237 + runOutputDir,
238 + ].map(value => path.resolve(value))
239 + ),
240 + ];
241 + yield* fs.makeDirectory(runOutputDir, { recursive: true });
242 + yield* fs.writeFileString(runLogFilePath, '');
243 + yield* fs.writeFileString(
244 + preloadPath,
245 + buildRunHelpersSource(
246 + cliPrefix,
247 + {
248 + ...context,
249 + runOutputDir,
250 + runLogFilePath,
251 + readAccessRoots,
252 + },
253 + moduleUrls
254 + )
255 + );
256 + return { directory, preloadPath, runOutputDir, runLogFilePath };
257 + });
258 +
259 +/**
260 + * `composio run` was given neither inline code nor `--file`.
261 + *
262 + * An ordinary usage mistake rather than a broken invariant, so it is a typed failure with a
263 + * one-line message instead of a defect: the caller sees the fix, not a stack trace.
264 + */
265 +export class MissingRunSourceError extends Data.TaggedError('commands/MissingRunSourceError')<{
266 + readonly message: string;
267 +}> {}
268 +
269 +const MISSING_RUN_SOURCE_MESSAGE = [
270 + 'Provide inline code or use --file to run a script file.',
271 + ` composio run 'console.log(1)'`,
272 + ' composio run --file ./script.ts',
273 +].join('\n');
274
275 export const buildRunCommand = ({
276 path,
@@ -250,59 +284,64 @@ export const buildRunCommand = ({
284 args: ReadonlyArray<string>;
285 preloadPath: string;
286 preloadDirectory: string;
253 -}) => {
254 - // Use process.execPath directly — the child is spawned with BUN_BE_BUN=1
255 - // which makes compiled Bun binaries act as a plain Bun runtime.
256 - // Avoid the `run` subcommand entirely since Bun intercepts it as its own
257 - // built-in; `bun --preload <file> <script>` works without it.
258 - const base = [process.execPath, '--preload', preloadPath];
259 - if (Option.isSome(file)) {
260 - const filePath = path.resolve(file.value);
261 - const wrapperFilePath = path.join(
262 - path.dirname(filePath),
263 - `.composio-run-${path.basename(preloadDirectory)}${path.extname(filePath) || '.ts'}`
264 - );
265 - fs.writeFileSync(
266 - wrapperFilePath,
267 - wrapFileSourceForRun(fs.readFileSync(filePath, 'utf8')),
268 - 'utf8'
269 - );
270 - return {
271 - cmd: [...base, wrapperFilePath, ...withArgDelimiter(args)],
272 - cleanupPaths: [wrapperFilePath],
273 - };
274 - }
287 +}) =>
288 + Effect.gen(function* () {
289 + const fs = yield* FileSystem.FileSystem;
290 + // Use process.execPath directly — the child is spawned with BUN_BE_BUN=1
291 + // which makes compiled Bun binaries act as a plain Bun runtime.
292 + // Avoid the `run` subcommand entirely since Bun intercepts it as its own
293 + // built-in; `bun --preload <file> <script>` works without it.
294 + const base = [process.execPath, '--preload', preloadPath];
295 + if (Option.isSome(file)) {
296 + const filePath = path.resolve(file.value);
297 + const wrapperFilePath = path.join(
298 + path.dirname(filePath),
299 + `.composio-run-${path.basename(preloadDirectory)}${path.extname(filePath) || '.ts'}`
300 + );
301 + yield* fs.writeFileString(
302 + wrapperFilePath,
303 + wrapFileSourceForRun(yield* fs.readFileString(filePath, 'utf8'))
304 + );
305 + return {
306 + cmd: [...base, wrapperFilePath, ...withArgDelimiter(args)],
307 + cleanupPaths: [wrapperFilePath],
308 + };
309 + }
310
276 - const [inlineCode, ...scriptArgs] = args;
277 - if (inlineCode) {
278 - const wrappedInlineCode = [
279 - '(async () => {',
280 - wrapInlineCodeForRun(inlineCode),
281 - '})().then((__composioResult) => {',
282 - ' if (__composioResult !== undefined) {',
283 - ' console.log(__composioResult);',
284 - ' }',
285 - '});',
286 - ].join('\n');
287 - return {
288 - cmd: [...base, '--eval', wrappedInlineCode, ...withArgDelimiter(scriptArgs)],
289 - cleanupPaths: [],
290 - };
291 - }
311 + const [inlineCode, ...scriptArgs] = args;
312 + if (inlineCode) {
313 + const wrappedInlineCode = [
314 + '(async () => {',
315 + wrapInlineCodeForRun(inlineCode),
316 + '})().then((__composioResult) => {',
317 + ' if (__composioResult !== undefined) {',
318 + ' console.log(__composioResult);',
319 + ' }',
320 + '});',
321 + ].join('\n');
322 + return {
323 + cmd: [...base, '--eval', wrappedInlineCode, ...withArgDelimiter(scriptArgs)],
324 + cleanupPaths: [],
325 + };
326 + }
327
293 - throw new Error('Provide inline code or use --file to run a script file.');
294 -};
328 + return yield* Effect.fail(new MissingRunSourceError({ message: MISSING_RUN_SOURCE_MESSAGE }));
329 + });
330
331 const resolveRunHelperContext = () =>
332 Effect.gen(function* () {
333 const path = yield* Path.Path;
334 + const os = yield* NodeOs;
335 const userContext = yield* ComposioUserContext;
336 const apiKey = Option.getOrUndefined(userContext.data.apiKey);
337 const orgId = Option.getOrUndefined(userContext.data.orgId);
302 - const defaultComposioDir = path.join(os.homedir(), USER_COMPOSIO_DIR);
303 - const configuredCacheDir =
304 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- honors the same COMPOSIO_CACHE_DIR/CACHE_DIR overrides the run-helpers child runtime reads, so the sandbox read roots match the child's cache location
305 - process.env.COMPOSIO_CACHE_DIR?.trim() || process.env.CACHE_DIR?.trim() || defaultComposioDir;
338 + const defaultComposioDir = path.join(os.homedir, USER_COMPOSIO_DIR);
339 + // Honors the same COMPOSIO_CACHE_DIR-then-CACHE_DIR precedence the spawned
340 + // run-helpers child applies when locating its cache, so the sandbox read
341 + // roots below always include the directory the child actually uses.
342 + const composioCacheDir = yield* APP_CONFIG.CACHE_DIR;
343 + const hostCacheDir = yield* loadHostConfig(UNPREFIXED_CONFIG.CACHE_DIR);
344 + const configuredCacheDir = composioCacheDir || hostCacheDir || defaultComposioDir;
345 const baseReadAccessRoots = [
346 ...new Set([defaultComposioDir, configuredCacheDir].map(value => path.resolve(value))),
347 ];
@@ -312,6 +351,7 @@ const resolveRunHelperContext = () =>
351 baseURL: userContext.data.baseURL,
352 webURL: userContext.data.webURL,
353 orgId,
354 + cliConfigPath: yield* resolveCliConfigPath,
355 readAccessRoots: baseReadAccessRoots,
356 } satisfies RunHelperContext;
357
@@ -324,28 +364,22 @@ const resolveRunHelperContext = () =>
364 return baseContext;
365 }
366
367 + const sessionArtifactsDir = Option.getOrUndefined(
368 + yield* resolveCliSessionArtifacts({
369 + orgId,
370 + consumerUserId: consumerProject.value.consumerUserId,
371 + }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
372 + );
373 +
374 return {
375 ...baseContext,
376 consumerUserId: consumerProject.value.consumerUserId,
377 consumerProjectId: consumerProject.value.projectId,
378 consumerProjectName: consumerProject.value.projectName,
332 - runOutputDir: Option.getOrUndefined(
333 - yield* resolveCliSessionArtifacts({
334 - orgId,
335 - consumerUserId: consumerProject.value.consumerUserId,
336 - }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
337 - ),
379 + runOutputDir: sessionArtifactsDir,
380 readAccessRoots: [
381 ...new Set(
340 - [
341 - ...baseReadAccessRoots,
342 - Option.getOrUndefined(
343 - yield* resolveCliSessionArtifacts({
344 - orgId,
345 - consumerUserId: consumerProject.value.consumerUserId,
346 - }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
347 - ),
348 - ]
382 + [...baseReadAccessRoots, sessionArtifactsDir]
383 .filter((value): value is string => typeof value === 'string' && value.length > 0)
384 .map(value => path.resolve(value))
385 ),
@@ -353,6 +387,102 @@ const resolveRunHelperContext = () =>
387 } satisfies RunHelperContext;
388 });
389
390 +/**
391 + * Signals the CLI forwards to the script it runs. Anything else (SIGHUP, SIGQUIT, …) keeps the
392 + * platform default: the executor's finalizer still tears the child's process group down.
393 + */
394 +const FORWARDED_SIGNALS = ['SIGINT', 'SIGTERM'] as const;
395 +
396 +type ForwardedSignal = (typeof FORWARDED_SIGNALS)[number];
397 +
398 +/**
399 + * How long the CLI waits for the script to finish its own signal handling before the platform
400 + * executor's finalizer sends SIGTERM to the process group.
401 + */
402 +const CHILD_SIGNAL_GRACE_PERIOD = Duration.seconds(2);
403 +
404 +class ChildSignalError extends Data.TaggedError('ChildSignalError')<{
405 + readonly pid: number;
406 + readonly signal: ForwardedSignal;
407 + readonly cause: unknown;
408 +}> {}
409 +
410 +/**
411 + * Sends `signal` to the child's process group and reports whether it was delivered.
412 + *
413 + * The @effect/platform executor spawns with `detached: true` on POSIX, so the script leads its
414 + * own process group and a negative pid is what reaches it (and anything it spawned). Delivery
415 + * fails with ESRCH when the group is already gone, which is a normal race, not a run failure.
416 + */
417 +const signalChildProcessGroup = (pid: number, signal: ForwardedSignal): boolean =>
418 + Either.try({
419 + try: () => process.kill(-pid, signal),
420 + catch: cause => new ChildSignalError({ pid, signal, cause }),
421 + }).pipe(Either.getOrElse(() => false));
422 +
423 +/**
424 + * Waits for the script to exit, giving up after `duration`.
425 + *
426 + * `Effect.timeout` cannot express this here: the wait runs in a release, while the fiber is
427 + * already interrupted, and the timer `Effect.timeout` forks as a child of that fiber is
428 + * interrupted along with it — leaving the wait hanging until the script exits on its own.
429 + * Daemon fibers are detached from the interrupted fiber, so their deadline still fires.
430 + */
431 +const awaitChildExitWithin = (child: CommandExecutor.Process, duration: Duration.Duration) =>
432 + Effect.gen(function* () {
433 + const settled = yield* Deferred.make<void>();
434 + const complete = Deferred.succeed(settled, undefined);
435 + yield* Effect.forkDaemon(Effect.zipRight(Effect.ignore(child.exitCode), complete));
436 + yield* Effect.forkDaemon(Effect.zipRight(Effect.sleep(duration), complete));
437 + yield* Deferred.await(settled);
438 + });
439 +
440 +/**
441 + * Forwards terminal signals to the running script for as long as it is alive.
442 + *
443 + * A terminal Ctrl-C only reaches the CLI's process group, so without this the script never
444 + * observes SIGINT and its `process.on('SIGINT')` cleanup never runs — it is reached later and
445 + * only as the executor's SIGTERM. Handlers are registered and removed with the scope so they
446 + * never leak into a later run.
447 + */
448 +const forwardSignalsToChild = (child: CommandExecutor.Process) =>
449 + Effect.gen(function* () {
450 + const os = yield* NodeOs;
451 + // Windows has no process groups and the executor does not detach there.
452 + if (os.platform === 'win32') {
453 + return;
454 + }
455 +
456 + const pid = Number(child.pid);
457 + const forwarded = MutableRef.make(false);
458 +
459 + yield* Effect.acquireRelease(
460 + Effect.sync(() =>
461 + FORWARDED_SIGNALS.map(signal => {
462 + const listener = () => {
463 + if (signalChildProcessGroup(pid, signal)) {
464 + MutableRef.set(forwarded, true);
465 + }
466 + };
467 + process.on(signal, listener);
468 + return { signal, listener } as const;
469 + })
470 + ),
471 + listeners =>
472 + Effect.sync(() => {
473 + for (const { signal, listener } of listeners) {
474 + process.removeListener(signal, listener);
475 + }
476 + }).pipe(
477 + Effect.zipRight(
478 + MutableRef.get(forwarded)
479 + ? awaitChildExitWithin(child, CHILD_SIGNAL_GRACE_PERIOD)
480 + : Effect.void
481 + )
482 + )
483 + );
484 + });
485 +
486 export const runCmd = Command.make('run', {
487 file,
488 dryRun,
@@ -429,13 +559,25 @@ export const runCmd = Command.make('run', {
559 args,
560 }) =>
561 Effect.gen(function* () {
562 + // Checked before any setup work so a bare `composio run` neither creates a run-artifacts
563 + // directory nor advertises a log file for a script that will never start.
564 + if (Option.isNone(file) && !args[0]) {
565 + return yield* Effect.fail(
566 + new MissingRunSourceError({ message: MISSING_RUN_SOURCE_MESSAGE })
567 + );
568 + }
569 +
570 + const fs = yield* FileSystem.FileSystem;
571 const path = yield* Path.Path;
433 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- reuses the run ID a parent `composio run` process passed via env so nested runs share one run identity
434 - const runId = process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID();
435 - const perfDebug = isPerfDebugEnabled();
436 - const toolDebug = isToolDebugEnabled();
437 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- reads the COMPOSIO_RUN_ACP_ONLY flag a parent process sets to force the ACP-only subagent path in the child run
438 - const acpOnly = process.env.COMPOSIO_RUN_ACP_ONLY === '1';
572 + const invocation = yield* cliInvocationContext;
573 + const runId = Option.getOrElse(
574 + yield* CliRunId,
575 + () => invocation.parentRunId ?? crypto.randomUUID()
576 + );
577 + const perfDebug = yield* isPerfDebugEnabled;
578 + const toolDebug = yield* isToolDebugEnabled;
579 + const acpOnly = yield* isAcpOnlyEnabled;
580 + const telemetryDebug = yield* isTelemetryDebugEnabled;
581 if (Option.isNone(file)) {
582 const [inlineCode] = args;
583 const preloadSlugs = extractInlineExecuteToolSlugs(inlineCode ?? '');
@@ -450,9 +592,10 @@ export const runCmd = Command.make('run', {
592 const helperContext: RunHelperContext = {
593 ...(yield* resolveRunHelperContext()),
594 runId,
453 - master: detectMaster(),
595 + master: yield* detectMasterFromHost,
596 perfDebug,
597 toolDebug,
598 + telemetryDebug,
599 debug,
600 logsOff,
601 acpOnly,
@@ -469,57 +612,74 @@ export const runCmd = Command.make('run', {
612 Effect.mapError(error => new Error(error.message)),
613 Effect.andThen(resolveRunHelperModuleUrls)
614 );
472 - const preload = createRunHelpersPreloadFile(
615 + const cliPrefix = yield* inferCliInvocationPrefix(path);
616 + const preload = yield* createRunHelpersPreloadFile(
617 path,
474 - inferCliInvocationPrefix(path),
618 + cliPrefix,
619 helperContext,
620 runHelperModuleUrls
621 );
622 const ui = yield* TerminalUI;
479 - let cleanupPaths: ReadonlyArray<string> = [];
480 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- try/finally removes the temp preload and wrapper files around the imperative Bun.spawn block, whose success path ends in process.exit
481 - try {
482 - yield* appendCliSessionHistory({
483 - orgId: helperContext.orgId,
484 - consumerUserId: helperContext.consumerUserId,
485 - entry: {
486 - command: 'run',
487 - status: 'start',
488 - file: Option.getOrUndefined(file),
489 - args,
490 - debug,
491 - },
492 - }).pipe(Effect.catchAll(() => Effect.void));
493 - yield* ui.error(`RUN_LOG_FILE=${preload.runLogFilePath}`);
494 - const runCommand = buildRunCommand({
495 - path,
496 - file,
623 + yield* appendCliSessionHistory({
624 + orgId: helperContext.orgId,
625 + consumerUserId: helperContext.consumerUserId,
626 + entry: {
627 + command: 'run',
628 + status: 'start',
629 + file: Option.getOrUndefined(file),
630 args,
498 - preloadPath: preload.preloadPath,
499 - preloadDirectory: preload.directory,
500 - });
501 - cleanupPaths = runCommand.cleanupPaths;
502 - const child = Bun.spawn({
503 - cmd: runCommand.cmd,
504 - env: {
505 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- spreads the caller's full environment into the spawned script so user-provided variables reach the child process
506 - ...process.env,
631 + debug,
632 + },
633 + }).pipe(Effect.catchAll(() => Effect.void));
634 + yield* ui.error(`RUN_LOG_FILE=${preload.runLogFilePath}`);
635 + const runCommand = yield* buildRunCommand({
636 + path,
637 + file,
638 + args,
639 + preloadPath: preload.preloadPath,
640 + preloadDirectory: preload.directory,
641 + });
642 + const exitCode = yield* Effect.gen(function* () {
643 + const [executable, ...commandArgs] = runCommand.cmd;
644 + const command = PlatformCommand.make(executable, ...commandArgs).pipe(
645 + PlatformCommand.env({
646 BUN_BE_BUN: '1',
647 COMPOSIO_CLI_PARENT_RUN_ID: runId,
509 - ...(perfDebug ? { COMPOSIO_PERF_DEBUG: '1' } : {}),
510 - ...(toolDebug ? { COMPOSIO_TOOL_DEBUG: '1' } : {}),
511 - },
512 - stdio: ['inherit', 'inherit', 'inherit'],
513 - });
514 -
515 - const exitCode = yield* Effect.promise(() => child.exited);
516 - process.exit(exitCode);
517 - } finally {
518 - for (const cleanupPath of cleanupPaths) {
519 - fs.rmSync(cleanupPath, { force: true });
520 - }
521 - fs.rmSync(preload.directory, { recursive: true, force: true });
522 - }
523 - })
648 + ...debugFlagsToChildEnv({ perfDebug, toolDebug, acpOnly, telemetryDebug }),
649 + }),
650 + PlatformCommand.stdin('inherit'),
651 + PlatformCommand.stdout('inherit'),
652 + PlatformCommand.stderr('inherit')
653 + );
654 + // Start the process instead of running it to completion: only a started process
655 + // exposes the pid the signal forwarding below needs.
656 + const child = yield* PlatformCommand.start(command);
657 + yield* forwardSignalsToChild(child);
658 + return Number(yield* child.exitCode);
659 + }).pipe(
660 + Effect.scoped,
661 + Effect.ensuring(
662 + Effect.forEach(
663 + runCommand.cleanupPaths,
664 + cleanupPath => fs.remove(cleanupPath, { force: true }),
665 + { discard: true }
666 + ).pipe(
667 + // The wrapper file sits next to the user's script, so removal can fail on a
668 + // read-only or locked directory. That must not turn an already-successful run
669 + // into a failure, which is what the previous `Effect.orDie` did.
670 + Effect.ignore
671 + )
672 + ),
673 + // Interruption (Ctrl-C) skips the assignment below, and the default teardown reports
674 + // an interrupt-only exit as success. Report the conventional 128+SIGINT instead so
675 + // wrappers and `set -e` scripts do not read a cancelled run as a passing one.
676 + Effect.onInterrupt(() =>
677 + Effect.sync(() => {
678 + process.exitCode = 130;
679 + })
680 + )
681 + );
682 + process.exitCode = exitCode;
683 + }).pipe(Effect.scoped)
684 )
685 );
ts/packages/cli/src/commands/setup.cmd.ts
+17 -2
@@ -21,6 +21,7 @@ import {
21 } from 'src/services/setup';
22 import { TerminalUI } from 'src/services/terminal-ui';
23 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
24 +import { cliInvocationContext } from 'src/services/runtime-cli-context';
25
26 const target = Options.choice('target', SETUP_TARGETS).pipe(
27 Options.withDefault('auto'),
@@ -63,6 +64,7 @@ const setupBaseCmd = Command.make(
64 Effect.gen(function* () {
65 const ui = yield* TerminalUI;
66 const terminal = yield* ui.capabilities;
67 + const { invocationOrigin } = yield* cliInvocationContext;
68 const operation = uninstall ? 'uninstall' : 'setup';
69 yield* ui.intro(uninstall ? 'composio setup --uninstall' : 'composio setup');
70
@@ -80,6 +82,7 @@ const setupBaseCmd = Command.make(
82 detection.available && !detection.supported
83 ? (detection.unsupportedReasonCode ?? 'unknown')
84 : undefined,
85 + invocationOrigin,
86 cliVersion: APP_VERSION,
87 })
88 )
@@ -117,7 +120,12 @@ const setupBaseCmd = Command.make(
120 if (supported.length === 0) {
121 if (ifPresent) {
122 yield* trackCliEventEffect(
120 - getSetupSkippedEvent({ operation, requestedTarget: target, cliVersion: APP_VERSION })
123 + getSetupSkippedEvent({
124 + operation,
125 + requestedTarget: target,
126 + invocationOrigin,
127 + cliVersion: APP_VERSION,
128 + })
129 );
130 yield* ui.outro(
131 `No supported agent host detected; plugin ${uninstall ? 'uninstall' : 'setup'} skipped.`
@@ -141,7 +149,12 @@ const setupBaseCmd = Command.make(
149 );
150 }
151 yield* trackCliEventEffect(
144 - getSetupSkippedEvent({ operation, requestedTarget: target, cliVersion: APP_VERSION })
152 + getSetupSkippedEvent({
153 + operation,
154 + requestedTarget: target,
155 + invocationOrigin,
156 + cliVersion: APP_VERSION,
157 + })
158 );
159 yield* ui.outro(
160 `No supported agent host detected; plugin ${uninstall ? 'uninstall' : 'setup'} skipped.`
@@ -191,6 +204,7 @@ const setupBaseCmd = Command.make(
204 getSetupCancelledEvent({
205 operation,
206 requestedTarget: target,
207 + invocationOrigin,
208 cliVersion: APP_VERSION,
209 })
210 );
@@ -241,6 +255,7 @@ const setupBaseCmd = Command.make(
255 getSetupCancelledEvent({
256 operation,
257 requestedTarget: target,
258 + invocationOrigin,
259 cliVersion: APP_VERSION,
260 })
261 );
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+20 -9
@@ -29,6 +29,7 @@ import { ComposioToolkitsRepository } from 'src/services/composio-clients';
29 import { ComposioUserContext } from 'src/services/user-context';
30 import { ProjectContext } from 'src/services/project-context';
31 import { trackCliCodactFailureEffect, trackCliEventEffect } from 'src/analytics/dispatch';
32 +import { cliInvocationContext } from 'src/services/runtime-cli-context';
33 import {
34 getToolExecuteFailedEvent,
35 getToolExecuteToolNotFoundEvent,
@@ -63,6 +64,7 @@ import {
64 import * as constants from 'src/constants';
65 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
66 import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
67 +import { APP_CONFIG } from 'src/effects/app-config';
68
69 const slug = Args.text({ name: 'slug' }).pipe(
70 Args.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')
@@ -315,8 +317,10 @@ const getExecuteOutputEncoder = () => {
317 return executeOutputEncoder;
318 };
319
318 -// eslint-disable-next-line eslint-js/no-restricted-syntax -- COMPOSIO_CLI_INVOCATION_ORIGIN is a spawn-time handshake the parent `composio run` process injects into nested CLI invocations, not user configuration, and it must be read fresh at call time
319 -const shouldStoreLargeExecuteOutput = () => process.env.COMPOSIO_CLI_INVOCATION_ORIGIN !== 'run';
320 +const shouldStoreLargeExecuteOutput = APP_CONFIG.CLI_INVOCATION_ORIGIN.pipe(
321 + Effect.orDie,
322 + Effect.map(origin => origin !== 'run')
323 +);
324
325 type StoredExecuteOutputSummary = {
326 readonly successful: true;
@@ -362,12 +366,12 @@ const executionSuccessSuffix = (result: {
366
367 const persistLargeExecuteOutput = (toolSlug: string, json: string, sharedDirectory?: string) =>
368 Effect.gen(function* () {
369 + const runOutputDirectory = yield* APP_CONFIG.RUN_OUTPUT_DIR;
370 const outputFilePath = yield* storeCliSessionArtifact({
371 contents: json,
372 name: `${toolSlug}_OUTPUT`,
373 extension: 'json',
369 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- COMPOSIO_RUN_OUTPUT_DIR is injected per-subprocess by the parent `composio run` so nested executions share one output directory; it is inter-process plumbing, not user configuration
370 - directoryPath: sharedDirectory?.trim() || process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim(),
374 + directoryPath: sharedDirectory?.trim() || runOutputDirectory,
375 });
376
377 return {
@@ -390,7 +394,10 @@ const prepareExecuteOutput = (
394 Effect.gen(function* () {
395 const json = serializeExecuteOutput(result);
396 const tokenCount = getExecuteOutputEncoder().encode(json).length;
393 - if (tokenCount <= EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD || !shouldStoreLargeExecuteOutput()) {
397 + if (
398 + tokenCount <= EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD ||
399 + !(yield* shouldStoreLargeExecuteOutput)
400 + ) {
401 return {
402 kind: 'inline',
403 json,
@@ -418,6 +425,7 @@ const emitExecuteFailureTelemetry = (params: {
425 }) =>
426 Effect.gen(function* () {
427 const toolkitSlug = yield* toolkitFromToolSlug(params.toolSlug);
428 + const { invocationOrigin } = yield* cliInvocationContext;
429 const normalized = params.mappedError?.normalized ?? normalizeCliError(params.error);
430 const failureOrigin: 'fast_fail' | 'main_endpoint' =
431 normalized instanceof ToolInputValidationError || params.stage !== 'execution'
@@ -431,6 +439,7 @@ const emitExecuteFailureTelemetry = (params: {
439 toolkitSlug,
440 args: params.args,
441 error: normalized,
442 + invocationOrigin,
443 surface: params.surface,
444 projectMode: params.projectMode,
445 stage: params.stage === 'dry_run' ? 'dry_run' : 'validation',
@@ -489,6 +498,7 @@ const emitExecuteFailureTelemetry = (params: {
498 schemaPath: 'server',
499 issues: [message],
500 }),
501 + invocationOrigin,
502 surface: params.surface,
503 projectMode: params.projectMode,
504 stage:
@@ -510,6 +520,7 @@ const emitExecuteFailureTelemetry = (params: {
520 toolSlug: params.toolSlug,
521 toolkitSlug,
522 args: params.args,
523 + invocationOrigin,
524 surface: params.surface,
525 projectMode: params.projectMode,
526 stage: params.stage === 'validation' ? 'execution' : params.stage,
@@ -524,6 +535,7 @@ const emitExecuteFailureTelemetry = (params: {
535 toolSlug: params.toolSlug,
536 toolkitSlug,
537 args: params.args,
538 + invocationOrigin,
539 surface: params.surface,
540 projectMode: params.projectMode,
541 stage: params.stage === 'validation' ? 'execution' : params.stage,
@@ -978,6 +990,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
990 const input = (yield* resolveInput(params.data)) ?? '{}';
991 const parsedArgs = yield* parseArguments(input);
992 const cliConfig = yield* ComposioCliUserConfig;
993 + const runOutputDirectory = yield* APP_CONFIG.RUN_OUTPUT_DIR;
994
995 if (
996 isLocalToolSlug(params.slug) &&
@@ -1009,8 +1022,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
1022 args: parsedArgs,
1023 resolvedUserId: 'local',
1024 selectedConnectedAccountId: undefined,
1012 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- COMPOSIO_RUN_OUTPUT_DIR is injected per-subprocess by the parent `composio run` so nested local-tool executions write into its shared output directory; inter-process plumbing, not user configuration
1013 - executeOutputDir: process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim() || undefined,
1025 + executeOutputDir: runOutputDirectory,
1026 executeParams: {
1027 userId: 'local',
1028 arguments: parsedArgs,
@@ -1079,8 +1091,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
1091 )
1092 : parsedArgs;
1093 const executeOutputDir =
1082 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- COMPOSIO_RUN_OUTPUT_DIR is injected per-subprocess by the parent `composio run` and must take precedence over the session artifacts directory; inter-process plumbing, not user configuration
1083 - process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim() ||
1094 + runOutputDirectory ||
1095 Option.getOrUndefined(
1096 yield* resolveCliSessionArtifacts({
1097 orgId: resolvedProject.projectType === 'CONSUMER' ? resolvedProject.orgId : undefined,
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+4 -4
@@ -1,6 +1,7 @@
1 import { Command, Options } from '@effect/cli';
2 import { FileSystem, Path } from '@effect/platform';
3 import { Deferred, Effect, Option, Runtime } from 'effect';
4 +import { APP_CONFIG } from 'src/effects/app-config';
5 import { requireAuth } from 'src/effects/require-auth';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 import { TriggersRealtime } from 'src/services/triggers-realtime';
@@ -184,8 +185,8 @@ export const triggersCmd$Listen = Command.make(
185 const runtime = yield* Effect.runtime<never>();
186 const forwardUrl = Option.getOrUndefined(forward);
187 const generatedWebhookSecret = `composio-forward-secret-${randomUUID()}`;
187 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- the forward signing secret is an optional raw passthrough from the user's shell; its literal presence/absence selects the generated-secret fallback
188 - const webhookSecret = process.env.COMPOSIO_WEBHOOK_SECRET ?? generatedWebhookSecret;
188 + const configuredWebhookSecret = yield* APP_CONFIG.WEBHOOK_SECRET;
189 + const webhookSecret = configuredWebhookSecret ?? generatedWebhookSecret;
190 const outputFilePathOption = Option.getOrUndefined(out);
191 const outputFilePath = outputFilePathOption ? path.resolve(outputFilePathOption) : undefined;
192
@@ -211,8 +212,7 @@ export const triggersCmd$Listen = Command.make(
212
213 yield* ui.intro('composio dev triggers listen');
214 if (forwardUrl) {
214 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- re-checks the same raw env var to tell the user whether they supplied a secret or this session generated one
215 - if (process.env.COMPOSIO_WEBHOOK_SECRET) {
215 + if (configuredWebhookSecret) {
216 yield* ui.note(
217 `Forward URL: ${forwardUrl}\nSigning secret: ${webhookSecret}`,
218 'Forwarding'
ts/packages/cli/src/effects/app-config.ts
+150 -6
@@ -1,4 +1,4 @@
1 -import { Config, LogLevel, Option } from 'effect';
1 +import { Config, HashMap, LogLevel, Option } from 'effect';
2 import * as constants from 'src/constants';
3
4 type APP_CONFIG = Config.Config.Wrap<{
@@ -6,13 +6,95 @@ type APP_CONFIG = Config.Config.Wrap<{
6 ENVIRONMENT: Option.Option<string>;
7 BASE_URL: string;
8 WEB_URL: string;
9 - CACHE_DIR: Option.Option<string>;
9 + CACHE_DIR: string | undefined;
10 + SESSION_DIR: string | undefined;
11 + BIN_DIR: string | undefined;
12 LOG_LEVEL: Option.Option<LogLevel.LogLevel>;
13 ORG_ID: Option.Option<string>;
14 PROJECT_ID: Option.Option<string>;
15 + AGENTS_BASE_URL: string | undefined;
16 + WEBHOOK_SECRET: string | undefined;
17 + CLI_INVOCATION_ORIGIN: string | undefined;
18 + CLI_PARENT_RUN_ID: string | undefined;
19 + RUN_ACP_ONLY: boolean;
20 + RUN_OUTPUT_DIR: string | undefined;
21 + PERF_DEBUG: boolean;
22 + TOOL_DEBUG: boolean;
23 DISABLE_CONNECTED_ACCOUNT_CACHE: boolean;
24 }>;
25
26 +type UNPREFIXED_CONFIG = Config.Config.Wrap<{
27 + CACHE_DIR: string | undefined;
28 + NPM_CONFIG_USER_AGENT: string | undefined;
29 + CI_REDACTION_ENABLED: boolean;
30 + INTERACTIVE_PERMISSION_UI_DISABLED: boolean;
31 + NO_COLOR: boolean;
32 + TELEMETRY_DEBUG: boolean;
33 + MASTER_SIGNALS: {
34 + readonly codex: boolean;
35 + readonly claude: boolean;
36 + };
37 + CALLER_AGENT_SIGNALS: {
38 + readonly explicit: string | undefined;
39 + readonly openclaw: boolean;
40 + readonly claude: boolean;
41 + readonly codex: boolean;
42 + };
43 +}>;
44 +
45 +const optionalString = (name: string): Config.Config<string | undefined> =>
46 + Config.option(Config.string(name)).pipe(Config.map(Option.getOrUndefined));
47 +
48 +const optionalTrimmedString = (name: string): Config.Config<string | undefined> =>
49 + optionalString(name).pipe(
50 + Config.map(value => {
51 + if (value === undefined) return undefined;
52 + const trimmed = value.trim();
53 + return trimmed.length > 0 ? trimmed : undefined;
54 + })
55 + );
56 +
57 +const ENV_FLAG_OFF_SPELLINGS = new Set(['0', 'false', 'no', 'off']);
58 +
59 +// A flag that is set counts as enabled unless it spells out one of the usual
60 +// "off" values, compared case-insensitively (`OFF` disables like `off`).
61 +const isEnvFlagEnabled = (value: string): boolean =>
62 + !ENV_FLAG_OFF_SPELLINGS.has(value.toLowerCase());
63 +
64 +/**
65 + * Tri-state read of a boolean environment flag:
66 + *
67 + * unset, or set to blank (`COMPOSIO_X=`) → `undefined` — absent, caller picks the default
68 + * `0` / `false` / `no` / `off`, any casing → `false`
69 + * anything else (`1`, `true`, even a typo) → `true`
70 + */
71 +const optionalEnvironmentFlag = (name: string): Config.Config<boolean | undefined> =>
72 + optionalTrimmedString(name).pipe(
73 + Config.map(value => (value === undefined ? undefined : isEnvFlagEnabled(value)))
74 + );
75 +
76 +// Deliberately tolerant rather than `Config.boolean`: these flags arrive from the ambient
77 +// environment, where a blank (`COMPOSIO_PERF_DEBUG=`) or unexpected value is routine.
78 +// `Config.boolean` rejects both with `InvalidData`, and `Config.withDefault` only recovers
79 +// `MissingData`, so a stray value would surface as an unrecoverable defect instead of `false`.
80 +const booleanFlag = (name: string, defaultValue = false): Config.Config<boolean> =>
81 + optionalEnvironmentFlag(name).pipe(Config.map(value => value ?? defaultValue));
82 +
83 +// `Config.hashMap` enumerates the provider's root keys instead of reading one
84 +// named variable, so it depends on how `ConfigProvider.fromEnv` derives them:
85 +// every `process.env` key is uppercased and split on `_`, and the first segment
86 +// becomes a root. `CODEX_HOME`, `codex_home`, and a bare `CODEX` therefore all
87 +// surface as the root `CODEX`. Matching is consequently case-insensitive and no
88 +// longer requires a trailing underscore, unlike the
89 +// `Object.keys(env).some(key => key.startsWith('CODEX_'))` scan it replaced.
90 +const agentPrefixSignals = Config.hashMap(Config.succeed(true)).pipe(
91 + Config.map(environmentRoots => ({
92 + codex: HashMap.has(environmentRoots, 'CODEX'),
93 + claude: HashMap.has(environmentRoots, 'CLAUDE'),
94 + openclaw: HashMap.has(environmentRoots, 'OPENCLAW'),
95 + }))
96 +);
97 +
98 /**
99 * Derives a URL default based on the `COMPOSIO_ENVIRONMENT` config key.
100 * Returns `stagingDefault` when ENVIRONMENT is `"staging"`, otherwise `prodDefault`.
@@ -56,7 +138,13 @@ export const APP_CONFIG = {
138 ),
139
140 // The cache directory for the Composio CLI
59 - CACHE_DIR: Config.option(Config.string('CACHE_DIR')),
141 + CACHE_DIR: optionalTrimmedString('CACHE_DIR'),
142 +
143 + // Override the root directory for CLI session artifacts
144 + SESSION_DIR: optionalTrimmedString('SESSION_DIR'),
145 +
146 + // Override the directory added to PATH by `composio install`
147 + BIN_DIR: optionalTrimmedString('BIN_DIR'),
148
149 // The log level for the Composio CLI
150 LOG_LEVEL: Config.option(Config.logLevel('LOG_LEVEL')),
@@ -67,8 +155,64 @@ export const APP_CONFIG = {
155 // The project ID for multi-project auth (overrides file-based config)
156 PROJECT_ID: Config.option(Config.string('PROJECT_ID')),
157
158 + // Override the Composio agents service URL
159 + AGENTS_BASE_URL: optionalString('AGENTS_BASE_URL'),
160 +
161 + // Sign forwarded trigger payloads with this secret
162 + WEBHOOK_SECRET: optionalString('WEBHOOK_SECRET'),
163 +
164 + // Internal context propagated between CLI processes
165 + CLI_INVOCATION_ORIGIN: optionalTrimmedString('CLI_INVOCATION_ORIGIN'),
166 + CLI_PARENT_RUN_ID: optionalTrimmedString('CLI_PARENT_RUN_ID'),
167 + RUN_ACP_ONLY: booleanFlag('RUN_ACP_ONLY'),
168 + RUN_OUTPUT_DIR: optionalTrimmedString('RUN_OUTPUT_DIR'),
169 +
170 + // Runtime debug flags
171 + PERF_DEBUG: booleanFlag('PERF_DEBUG'),
172 + TOOL_DEBUG: booleanFlag('TOOL_DEBUG'),
173 +
174 // Disable connected account cache (defaults to true — cache is off by default)
71 - DISABLE_CONNECTED_ACCOUNT_CACHE: Config.boolean('DISABLE_CONNECTED_ACCOUNT_CACHE').pipe(
72 - Config.withDefault(true)
73 - ),
175 + DISABLE_CONNECTED_ACCOUNT_CACHE: booleanFlag('DISABLE_CONNECTED_ACCOUNT_CACHE', true),
176 } satisfies APP_CONFIG;
177 +
178 +/**
179 + * Configuration whose keys are spelled out in full and are therefore loaded
180 + * through the raw `ConfigProvider.fromEnv()` provider (`loadHostConfig` in
181 + * `src/services/config.ts`) rather than the `COMPOSIO_`-prefixing provider that
182 + * serves `APP_CONFIG`. Several keys do carry the `COMPOSIO_` prefix; what unites
183 + * them is that the prefix is written here instead of being applied by the
184 + * provider. Keep their string-to-domain normalization here so consumers never
185 + * inspect raw environment strings.
186 + */
187 +export const UNPREFIXED_CONFIG = {
188 + // The cache directory of the host tool driving the CLI (not `COMPOSIO_CACHE_DIR`)
189 + CACHE_DIR: optionalTrimmedString('CACHE_DIR'),
190 +
191 + // The package manager that invoked the CLI, as reported by npm-compatible clients
192 + NPM_CONFIG_USER_AGENT: optionalString('npm_config_user_agent'),
193 +
194 + // Stricter than the `booleanFlag` family on purpose: output redaction is for
195 + // recorded CI sessions and keys off the exact `CI=true` convention. A looser
196 + // parse would also start redacting under `CI=1`-style environments, changing
197 + // long-standing behavior. `INTERACTIVE_PERMISSION_UI_DISABLED` below reads
198 + // the same variable tolerantly because failing closed there is the safe
199 + // reading of any non-falsy `CI` value.
200 + CI_REDACTION_ENABLED: optionalTrimmedString('CI').pipe(
201 + Config.map(value => value?.toLowerCase() === 'true')
202 + ),
203 + INTERACTIVE_PERMISSION_UI_DISABLED: Config.all({
204 + explicit: optionalEnvironmentFlag('COMPOSIO_DISABLE_PERMISSION_UI'),
205 + ci: optionalEnvironmentFlag('CI'),
206 + vitest: optionalEnvironmentFlag('VITEST'),
207 + }).pipe(Config.map(({ explicit, ci, vitest }) => explicit ?? (ci === true || vitest === true))),
208 + NO_COLOR: optionalString('NO_COLOR').pipe(Config.map(Boolean)),
209 + TELEMETRY_DEBUG: booleanFlag('COMPOSIO_CLI_TELEMETRY_DEBUG'),
210 + MASTER_SIGNALS: agentPrefixSignals.pipe(Config.map(({ codex, claude }) => ({ codex, claude }))),
211 + CALLER_AGENT_SIGNALS: Config.all({
212 + explicit: Config.all({
213 + callerAgent: optionalTrimmedString('COMPOSIO_CALLER_AGENT'),
214 + legacyAgent: optionalTrimmedString('COMPOSIO_AGENT'),
215 + }).pipe(Config.map(({ callerAgent, legacyAgent }) => callerAgent ?? legacyAgent)),
216 + prefixes: agentPrefixSignals,
217 + }).pipe(Config.map(({ explicit, prefixes }) => ({ explicit, ...prefixes }))),
218 +} satisfies UNPREFIXED_CONFIG;
ts/packages/cli/src/effects/setup-cache-dir.ts
+3 -5
@@ -1,4 +1,4 @@
1 -import { Effect, pipe, Option } from 'effect';
1 +import { Effect } from 'effect';
2 import { FileSystem, Path } from '@effect/platform';
3 import * as constants from 'src/constants';
4 import { APP_CONFIG } from 'src/effects/app-config';
@@ -10,10 +10,8 @@ export const setupCacheDir = Effect.gen(function* () {
10 const path = yield* Path.Path;
11 const os = yield* NodeOs;
12
13 - const cacheDir = yield* pipe(
14 - APP_CONFIG.CACHE_DIR,
15 - Effect.map(Option.getOrElse(() => path.join(os.homedir, constants.USER_COMPOSIO_DIR)))
16 - );
13 + const cacheDir =
14 + (yield* APP_CONFIG.CACHE_DIR) ?? path.join(os.homedir, constants.USER_COMPOSIO_DIR);
15
16 // Ensure cache directory exists
17 yield* fs.makeDirectory(cacheDir, { recursive: true }).pipe(Effect.catchAll(() => Effect.void));
ts/packages/cli/src/services/agents.ts
+7 -4
@@ -1,5 +1,6 @@
1 import { FileSystem, Path } from '@effect/platform';
2 import { Data, Effect, Either, Option, Predicate, Schema } from 'effect';
3 +import { APP_CONFIG } from 'src/effects/app-config';
4 import { JsonRecordSchema } from 'src/effects/json';
5 import { setupCacheDir } from 'src/effects/setup-cache-dir';
6 import { ComposioUserContext } from 'src/services/user-context';
@@ -81,9 +82,10 @@ export class AgentResponseDecodeError extends Data.TaggedError(
82 readonly cause: unknown;
83 }> {}
84
84 -const agentsBaseURL = (): string =>
85 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- read lazily at request time inside a plain sync helper so tests can repoint agents.composio.dev per call without rebuilding a Config layer
86 - (process.env.COMPOSIO_AGENTS_BASE_URL ?? DEFAULT_AGENTS_BASE_URL).replace(/\/+$/, '');
85 +const agentsBaseURL = APP_CONFIG.AGENTS_BASE_URL.pipe(
86 + Effect.orDie,
87 + Effect.map(value => (value ?? DEFAULT_AGENTS_BASE_URL).replace(/\/+$/, ''))
88 +);
89
90 const decodeAgentResponse =
91 <A, I>(pathname: string, schema: Schema.Schema<A, I>) =>
@@ -197,9 +199,10 @@ export const removeStoredAgentIdentity = Effect.gen(function* () {
199
200 const fetchAgentJson = (pathname: string, init: RequestInit = {}) =>
201 Effect.gen(function* () {
202 + const baseURL = yield* agentsBaseURL;
203 const response = yield* Effect.tryPromise({
204 try: () =>
202 - fetch(`${agentsBaseURL()}${pathname}`, {
205 + fetch(`${baseURL}${pathname}`, {
206 redirect: 'error',
207 ...init,
208 headers: {
ts/packages/cli/src/services/cli-session-artifacts.ts
+5 -4
@@ -1,5 +1,6 @@
1 import { FileSystem, Path } from '@effect/platform';
2 import { Effect, Option } from 'effect';
3 +import { APP_CONFIG } from 'src/effects/app-config';
4 import { getOrCreateProbablyMyCliSessionIdForCurrentCwd } from 'src/services/consumer-short-term-cache';
5 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
6 import { NodeOs } from 'src/services/node-os';
@@ -8,12 +9,12 @@ export const resolveArtifactsRoot = Effect.gen(function* () {
9 const path = yield* Path.Path;
10 const os = yield* NodeOs;
11 const cliUserConfig = yield* ComposioCliUserConfig;
12 + const sessionDirectory = yield* APP_CONFIG.SESSION_DIR;
13 + const cacheDirectory = yield* APP_CONFIG.CACHE_DIR;
14
15 return (
13 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- read inline so a blank/whitespace-only COMPOSIO_SESSION_DIR falls through the || precedence chain (session dir > cache dir > user config > tmpdir)
14 - process.env.COMPOSIO_SESSION_DIR?.trim() ||
15 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- COMPOSIO_CACHE_DIR is the second rung of the same fall-through chain: env overrides must beat the persisted artifactDirectory before the tmpdir default
16 - process.env.COMPOSIO_CACHE_DIR?.trim() ||
16 + sessionDirectory ||
17 + cacheDirectory ||
18 cliUserConfig.data.artifactDirectory?.trim() ||
19 path.join(os.tmpdir, 'composio')
20 );
ts/packages/cli/src/services/cli-user-config.ts
-20
@@ -2,8 +2,6 @@ import { FileSystem, Path } from '@effect/platform';
2 import type { PlatformError } from '@effect/platform/Error';
3 import { Context, Effect, Layer, Option, Predicate, Schema } from 'effect';
4 import type { ParseError } from 'effect/ParseResult';
5 -// eslint-disable-next-line no-restricted-imports -- os.homedir feeds resolveCliConfigDirectorySync, which runs from synchronous non-Effect call sites (dev.cmd messages, run-helpers-runtime readFileSync) where the NodeOs service is unavailable
6 -import os from 'node:os';
5 import { JsonRecordSchema } from 'src/effects/json';
6 import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 import { getVersion } from 'src/effects/version';
@@ -48,24 +46,6 @@ const DEFAULT_CLI_USER_CONFIG = CliUserConfig.make({
46
47 const decodeConfigJson = Schema.decodeUnknown(Schema.parseJson(JsonRecordSchema));
48
51 -// The sync resolvers below run from non-Effect call sites (the
52 -// run-helpers-runtime child process), so the Path service is materialized once
53 -// from its pure default layer instead of being yielded from context.
54 -const syncPath = Effect.runSync(Path.Path.pipe(Effect.provide(Path.layer)));
55 -
56 -export const resolveCliConfigDirectorySync = (): string =>
57 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- this resolver is called from synchronous non-Effect code, so the COMPOSIO_CACHE_DIR override cannot come from effect/Config here
58 - process.env.COMPOSIO_CACHE_DIR?.trim() ||
59 - syncPath.join(os.homedir(), constants.USER_COMPOSIO_DIR);
60 -
61 -export const resolveCliConfigPathSync = (): string =>
62 - syncPath.join(resolveCliConfigDirectorySync(), constants.CLI_CONFIG_FILE_NAME);
63 -
64 -/**
65 - * Effect-based resolver for the CLI config file path. Prefer this over
66 - * `resolveCliConfigPathSync` inside Effect-hosted code: it honors the
67 - * COMPOSIO_CACHE_DIR override via `effect/Config` and the NodeOs service.
68 - */
49 export const resolveCliConfigPath = Effect.gen(function* () {
50 const path = yield* Path.Path;
51 const configDir = yield* setupCacheDir;
ts/packages/cli/src/services/command-runner.ts
+2 -1
@@ -7,7 +7,8 @@ export interface CommandResult {
7 readonly stderr: string;
8 }
9
10 -const collectText = (stream: Stream.Stream<Uint8Array, unknown>) =>
10 +/** Drains a child-process output stream into one string; shared with the run-helpers runtime. */
11 +export const collectText = (stream: Stream.Stream<Uint8Array, unknown>) =>
12 stream.pipe(Stream.decodeText(), Stream.runFold(String.empty, String.concat));
13
14 export class CommandRunner extends Effect.Service<CommandRunner>()('services/CommandRunner', {
ts/packages/cli/src/services/config.ts
+8 -1
@@ -1,4 +1,4 @@
1 -import { Option, Effect, ConfigProvider, Layer, Logger } from 'effect';
1 +import { Config, Option, Effect, ConfigProvider, Layer, Logger } from 'effect';
2 import * as constants from 'src/constants';
3 import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
4 import { APP_CONFIG } from 'src/effects/app-config';
@@ -23,6 +23,13 @@ import { APP_CONFIG } from 'src/effects/app-config';
23
24 export const BaseConfigProviderLive = ConfigProvider.fromEnv();
25
26 +/**
27 + * Load a config whose keys are spelled out in full, through the raw provider
28 + * that applies no `COMPOSIO_` prefix mapping. Pair it with `UNPREFIXED_CONFIG`.
29 + */
30 +export const loadHostConfig = <A>(config: Config.Config<A>): Effect.Effect<A> =>
31 + BaseConfigProviderLive.load(config).pipe(Effect.orDie);
32 +
33 export function extendConfigProvider(baseConfigProvider: ConfigProvider.ConfigProvider) {
34 return baseConfigProvider.pipe(
35 ConfigProvider.mapInputPath(key => {
ts/packages/cli/src/services/master-detector.ts
+15 -6
@@ -1,15 +1,24 @@
1 +import { Effect } from 'effect';
2 +import { UNPREFIXED_CONFIG } from 'src/effects/app-config';
3 +import { loadHostConfig } from 'src/services/config';
4 +
5 export type MasterKind = 'claude' | 'codex' | 'user';
6
3 -export const hasEnvPrefix = (env: Record<string, string | undefined>, prefix: string): boolean =>
4 - Object.keys(env).some(key => key.startsWith(prefix));
7 +export type MasterSignals = {
8 + readonly codex: boolean;
9 + readonly claude: boolean;
10 +};
11
6 -// eslint-disable-next-line eslint-js/no-restricted-syntax -- classifies the driving agent by scanning every env key for CODEX_/CLAUDE_ prefixes; effect/Config reads known keys and cannot enumerate the whole environment
7 -export const detectMaster = (env: Record<string, string | undefined> = process.env): MasterKind => {
8 - if (hasEnvPrefix(env, 'CODEX_')) {
12 +export const detectMaster = (signals: MasterSignals): MasterKind => {
13 + if (signals.codex) {
14 return 'codex';
15 }
11 - if (hasEnvPrefix(env, 'CLAUDE_')) {
16 + if (signals.claude) {
17 return 'claude';
18 }
19 return 'user';
20 };
21 +
22 +export const detectMasterFromHost: Effect.Effect<MasterKind> = loadHostConfig(
23 + UNPREFIXED_CONFIG.MASTER_SIGNALS
24 +).pipe(Effect.map(detectMaster));
ts/packages/cli/src/services/native-ui-sidecar.ts
+24 -64
@@ -3,7 +3,6 @@ import { BunContext } from '@effect/platform-bun';
3 import {
4 Cause,
5 Config,
6 - ConfigProvider,
6 Data,
7 Duration,
8 Effect,
@@ -18,7 +17,8 @@ import {
17 ensureBundledBinaryExecutable,
18 getLocalToolsBundleRootCandidates,
19 } from '@composio/cli-local-tools';
21 -import { hasEnvPrefix } from 'src/services/master-detector';
20 +import { UNPREFIXED_CONFIG } from 'src/effects/app-config';
21 +import { loadHostConfig } from 'src/services/config';
22
23 const NATIVE_UI_BINARY_NAME = 'composio-native-ui';
24
@@ -61,64 +61,18 @@ export class NativeUiDecisionMissingError extends Data.TaggedError(
61 }
62 }
63
64 -// Caller-agent detection scans the whole environment for agent-specific
65 -// prefixes (OPENCLAW_*, CLAUDE_*, CODEX_*). effect/Config can only read named
66 -// keys, so this module keeps a single raw-env boundary, mirroring the
67 -// node-os.ts precedent.
68 -// eslint-disable-next-line eslint-js/no-restricted-syntax -- Sole raw-env boundary of this module: prefix scanning needs the full environment map, which effect/Config cannot enumerate.
69 -const rawProcessEnv: NodeJS.ProcessEnv = process.env;
70 -
71 -const FALSY_ENV_FLAG_VALUES: ReadonlyArray<string> = ['0', 'false', 'no', 'off'];
72 -
73 -// Any other non-empty value counts as set (`CI=woohoo` still disables the UI)
74 -// rather than failing config decoding the way `Config.boolean` would.
75 -const EnvFlagFromString = Schema.transform(
76 - Schema.compose(Schema.Trim, Schema.Lowercase),
77 - Schema.Boolean,
78 - {
79 - decode: value => !FALSY_ENV_FLAG_VALUES.includes(value),
80 - encode: enabled => (enabled ? '1' : '0'),
81 - strict: true,
82 - }
83 -);
84 -const decodeEnvFlag = Schema.decodeOption(EnvFlagFromString);
85 -
86 -// None when the variable is unset or blank, so callers can distinguish
87 -// "not configured" from an explicit true/false.
88 -const envFlag = (name: string): Config.Config<Option.Option<boolean>> =>
89 - Config.string(name).pipe(
90 - Config.map(value => value.trim()),
91 - Config.option,
92 - Config.map(Option.filter(value => value.length > 0)),
93 - Config.map(Option.flatMap(decodeEnvFlag))
94 - );
95 -
64 /**
65 * Interactive permission UI (the native sidecar dialog and the browser
66 * approval page) must never spawn from automated environments. The explicit
67 * COMPOSIO_DISABLE_PERMISSION_UI knob wins in both directions; without it,
68 * CI and Vitest runs disable the UI.
69 */
102 -export const interactivePermissionUiDisabledConfig: Config.Config<boolean> = Config.all({
103 - explicit: envFlag('COMPOSIO_DISABLE_PERMISSION_UI'),
104 - ci: envFlag('CI'),
105 - vitest: envFlag('VITEST'),
106 -}).pipe(
107 - Config.map(({ explicit, ci, vitest }) =>
108 - Option.getOrElse(
109 - explicit,
110 - () => Option.getOrElse(ci, () => false) || Option.getOrElse(vitest, () => false)
111 - )
112 - )
113 -);
114 -
115 -// CI / VITEST / COMPOSIO_DISABLE_PERMISSION_UI are read verbatim, so load them
116 -// through a raw env provider rather than the CLI's COMPOSIO_-prefixed one.
117 -const environmentProvider = ConfigProvider.fromEnv();
70 +export const interactivePermissionUiDisabledConfig =
71 + UNPREFIXED_CONFIG.INTERACTIVE_PERMISSION_UI_DISABLED;
72
119 -export const isInteractivePermissionUiDisabled: Effect.Effect<boolean> = environmentProvider
120 - .load(interactivePermissionUiDisabledConfig)
121 - .pipe(Effect.orDie);
73 +export const isInteractivePermissionUiDisabled: Effect.Effect<boolean> = loadHostConfig(
74 + interactivePermissionUiDisabledConfig
75 +);
76
77 const normalizeCallerAgent = (value?: string): NativeUiCallerAgent | undefined => {
78 const normalized = value?.toLowerCase().replace(/[^a-z]/g, '');
@@ -170,31 +124,37 @@ const detectCallerAgentFromProcessTree: Effect.Effect<
124 return undefined;
125 });
126
173 -const detectCallerAgentFromEnv = (env: NodeJS.ProcessEnv): NativeUiCallerAgent | undefined => {
174 - const explicit = normalizeCallerAgent(env.COMPOSIO_CALLER_AGENT ?? env.COMPOSIO_AGENT);
127 +export type NativeUiCallerAgentSignals = Config.Config.Success<
128 + typeof UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS
129 +>;
130 +
131 +const detectCallerAgentFromSignals = (
132 + signals: NativeUiCallerAgentSignals
133 +): NativeUiCallerAgent | undefined => {
134 + const explicit = normalizeCallerAgent(signals.explicit);
135 if (explicit) return explicit;
136
177 - if (hasEnvPrefix(env, 'OPENCLAW_')) return 'openclaw';
178 - if (hasEnvPrefix(env, 'CLAUDE_')) return 'claude';
179 - if (hasEnvPrefix(env, 'CODEX_')) return 'codex';
137 + if (signals.openclaw) return 'openclaw';
138 + if (signals.claude) return 'claude';
139 + if (signals.codex) return 'codex';
140
141 return undefined;
142 };
143
144 export const detectNativeUiCallerAgentEffect = (
185 - env: NodeJS.ProcessEnv = rawProcessEnv
145 + providedSignals?: NativeUiCallerAgentSignals
146 ): Effect.Effect<NativeUiCallerAgent, never, CommandExecutor.CommandExecutor> =>
147 Effect.gen(function* () {
188 - const fromEnv = detectCallerAgentFromEnv(env);
148 + const signals =
149 + providedSignals ?? (yield* loadHostConfig(UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS));
150 + const fromEnv = detectCallerAgentFromSignals(signals);
151 if (fromEnv !== undefined) return fromEnv;
152
153 return (yield* detectCallerAgentFromProcessTree) ?? 'composio';
154 });
155
194 -export const detectNativeUiCallerAgent = (
195 - env: NodeJS.ProcessEnv = rawProcessEnv
196 -): Promise<NativeUiCallerAgent> =>
197 - Effect.runPromise(Effect.provide(detectNativeUiCallerAgentEffect(env), BunContext.layer));
156 +export const detectNativeUiCallerAgent = (): Promise<NativeUiCallerAgent> =>
157 + Effect.runPromise(Effect.provide(detectNativeUiCallerAgentEffect(), BunContext.layer));
158
159 export const resolveNativeUiBinary: Effect.Effect<
160 NativeUiBinaryResolution,
ts/packages/cli/src/services/plugin-hint.ts
+5 -5
@@ -1,6 +1,7 @@
1 import { FileSystem, Path } from '@effect/platform';
2 import { BunFileSystem } from '@effect/platform-bun';
3 import { Config, ConfigProvider, Effect, Layer, Option, Schema } from 'effect';
4 +import { APP_CONFIG } from 'src/effects/app-config';
5 import { setupCacheDir } from 'src/effects/setup-cache-dir';
6 import { AGENT_HOST_LABELS, COMPOSIO_AGENT_PLUGIN_ID, type AgentHost } from './agent-host';
7 import { NodeOs } from './node-os';
@@ -153,18 +154,16 @@ export function findRootCommandName(argv: ReadonlyArray<string>): string | undef
154
155 // Host-owned variables must bypass the CLI ConfigProvider, which prefixes
156 // application keys with COMPOSIO_.
156 -const rawEnvironment = Effect.gen(function* () {
157 +const rawHostEnvironment = Effect.gen(function* () {
158 const claudeCode = yield* readOptionalEnv('CLAUDECODE');
159 const codexThreadId = yield* readOptionalEnv('CODEX_THREAD_ID');
160 const codexSandbox = yield* readOptionalEnv('CODEX_SANDBOX');
160 - const invocationOrigin = yield* readOptionalEnv('COMPOSIO_CLI_INVOCATION_ORIGIN');
161 const claudeConfigDir = nonBlankOrUndefined(yield* readOptionalEnv('CLAUDE_CONFIG_DIR'));
162 const codexHome = nonBlankOrUndefined(yield* readOptionalEnv('CODEX_HOME'));
163 return {
164 claudeCode,
165 codexThreadId,
166 codexSandbox,
167 - invocationOrigin,
167 claudeConfigDir,
168 codexHome,
169 };
@@ -175,11 +174,12 @@ export const resolvePluginHintConfig = (argv: ReadonlyArray<string>) =>
174 const path = yield* Path.Path;
175 const os = yield* NodeOs;
176 const cacheDir = yield* setupCacheDir;
178 - const env = yield* rawEnvironment;
177 + const invocationOrigin = yield* APP_CONFIG.CLI_INVOCATION_ORIGIN;
178 + const env = yield* rawHostEnvironment;
179 return {
180 stateDirectory: path.join(cacheDir, 'plugin-hints'),
181 host: detectPluginHost(env),
182 - invocationOrigin: env.invocationOrigin,
182 + invocationOrigin,
183 commandName: findRootCommandName(argv),
184 claudeInstalledPluginsFile: path.join(
185 env.claudeConfigDir ?? path.join(os.homedir, '.claude'),
ts/packages/cli/src/services/project-environment-detector.ts
+5 -3
@@ -1,8 +1,9 @@
1 import { BunFileSystem } from '@effect/platform-bun';
2 import { FileSystem, Path } from '@effect/platform';
3 import { Data, Effect, Match } from 'effect';
4 -import process from 'node:process';
4 import { getAncestors } from 'src/utils/get-ancestors';
5 +import { UNPREFIXED_CONFIG } from 'src/effects/app-config';
6 +import { loadHostConfig } from 'src/services/config';
7
8 const toError = (e: unknown): Error => (e instanceof Error ? e : new Error(String(e)));
9
@@ -498,8 +499,9 @@ const detectJsPackageManager = (fs: FileSystem.FileSystem, cwd: string) =>
499 if (fileSet.has('pnpm-workspace.yaml')) return 'pnpm' as const;
500 }
501
501 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- npm_config_user_agent is transient metadata injected by the package manager that spawned this process, not CLI configuration; read once as the last-resort heuristic when no lockfile or manifest evidence exists
502 - const userAgent = parseUserAgent(process.env.npm_config_user_agent);
502 + const userAgent = parseUserAgent(
503 + yield* loadHostConfig(UNPREFIXED_CONFIG.NPM_CONFIG_USER_AGENT)
504 + );
505 if (userAgent) return userAgent;
506
507 return 'npm' as const;
ts/packages/cli/src/services/run-companion-modules.ts
+115 -11
@@ -2,7 +2,6 @@
2 // the bundled `composio run` companion modules, and the binary build scripts. Every
3 // helper is an Effect over the @effect/platform FileSystem/Path services; consumers
4 // outside the CLI runtime (companion runtimes, scripts) provide their own platform layers.
5 -import { fileURLToPath } from 'node:url';
5 import { FileSystem, Path } from '@effect/platform';
6 import type { PlatformError } from '@effect/platform/Error';
7 import { Config, ConfigProvider, Data, Effect, Option, Schema } from 'effect';
@@ -10,6 +9,7 @@ import extractZip from 'extract-zip';
9 import { IS_RELEASE_BUILD } from 'src/constants';
10 import { GitHubRelease } from 'src/effects/resolve-cli-release';
11 import { BaseConfigProviderLive, extendConfigProvider } from 'src/services/config';
12 +import { NodeOs } from 'src/services/node-os';
13 import { atomicReplaceFile } from 'src/utils/atomic-replace';
14 import { parseChecksumsText, sha256Hex } from 'src/utils/checksums';
15 import { CLI_RELEASE_TAG_PREFIX } from 'src/utils/cli-release-version';
@@ -27,7 +27,7 @@ export const RUN_COMPANION_MODULE_FILENAMES = RUN_COMPANION_MODULE_BASENAMES.map
27 );
28
29 export const RUN_COMPANION_RELEASE_TAG_FILENAME = 'release-tag.txt';
30 -type RunCodexAcpBinaryTarget = {
30 +export type RunCodexAcpBinaryTarget = {
31 readonly platform: NodeJS.Platform;
32 readonly arch: string;
33 readonly packageName: string;
@@ -65,14 +65,62 @@ export const RUN_CODEX_ACP_BINARY_TARGETS: ReadonlyArray<RunCodexAcpBinaryTarget
65 relativePath: 'acp-adapters/codex/linux-x64/codex-acp',
66 },
67 ];
68 -export const RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS: ReadonlyArray<string> = [
68 +export const codexAcpBinaryTargetFor = ({
69 + platform,
70 + arch,
71 +}: {
72 + readonly platform: string;
73 + readonly arch: string;
74 +}): RunCodexAcpBinaryTarget | undefined =>
75 + RUN_CODEX_ACP_BINARY_TARGETS.find(target => target.platform === platform && target.arch === arch);
76 +
77 +// Portable ACP assets: any install that invokes an ACP sub-agent needs these
78 +// regardless of platform/arch. They belong to the lazy tier — see
79 +// `listMissingInstalledRunCompanionModules` for the two-tier split.
80 +export const RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS: ReadonlyArray<string> = [
81 'acp-adapters/claude-code-acp.mjs',
82 // cli.js from @anthropic-ai/claude-agent-sdk must live next to claude-code-acp.mjs.
83 // The bundled adapter uses import.meta.url to locate it at runtime.
84 'acp-adapters/cli.js',
85 +];
86 +
87 +// Every asset a release archive ships, across all supported platforms. Only the
88 +// packaging step cares about this: a single machine can execute exactly one of
89 +// the codex-acp binaries.
90 +export const RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS: ReadonlyArray<string> = [
91 + ...RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
92 ...RUN_CODEX_ACP_BINARY_TARGETS.map(target => target.relativePath),
93 ];
94
95 +/**
96 + * ACP assets an install must contain to be complete on the given platform/arch:
97 + * the portable ones plus at most the single codex-acp binary this host can run.
98 + * Unsupported platform/arch pairs simply have no codex-acp requirement.
99 + *
100 + * These are the *lazy* tier: `composio run` only needs them when the script it
101 + * runs actually invokes an ACP sub-agent, so startup never demands them.
102 + */
103 +export const runCompanionStaticAssetRelativePathsFor = ({
104 + platform,
105 + arch,
106 +}: {
107 + readonly platform: string;
108 + readonly arch: string;
109 +}): ReadonlyArray<string> => {
110 + const hostTarget = codexAcpBinaryTargetFor({ platform, arch });
111 +
112 + return hostTarget
113 + ? [...RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS, hostTarget.relativePath]
114 + : RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS;
115 +};
116 +
117 +// NodeOs is the sanctioned platform/arch boundary; self-provided so callers keep
118 +// their existing FileSystem/Path-only requirements.
119 +export const hostRunCompanionStaticAssetRelativePaths: Effect.Effect<ReadonlyArray<string>> =
120 + Effect.map(NodeOs, os =>
121 + runCompanionStaticAssetRelativePathsFor({ platform: os.platform, arch: os.arch })
122 + ).pipe(Effect.provide(NodeOs.Default));
123 +
124 export class RunCompanionRepairError extends Data.TaggedError('services/RunCompanionRepairError')<{
125 readonly message: string;
126 readonly cause?: unknown;
@@ -86,6 +134,9 @@ const isImportGraphFile = (relativePath: string) => /\.(?:m?js|ts)$/.test(relati
134 const fileExists = (fs: FileSystem.FileSystem, filePath: string) =>
135 fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
136
137 +const filePathFromUrl = (path: Path.Path, url: string): Effect.Effect<string> =>
138 + Schema.decodeUnknown(Schema.URL)(url).pipe(Effect.flatMap(path.fromFileUrl), Effect.orDie);
139 +
140 const collectRelativeImportPaths = ({
141 fs,
142 path,
@@ -174,7 +225,7 @@ export const collectRunCompanionAssetRelativePaths = (
225 }
226 }
227
177 - for (const relativePath of RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS) {
228 + for (const relativePath of yield* hostRunCompanionStaticAssetRelativePaths) {
229 yield* collectRelativeImportPaths({
230 fs,
231 path,
@@ -199,7 +250,7 @@ export const resolveRunCompanionAssetPath = ({
250 Effect.gen(function* () {
251 const fs = yield* FileSystem.FileSystem;
252 const path = yield* Path.Path;
202 - const currentFilePath = fileURLToPath(callerImportMetaUrl);
253 + const currentFilePath = yield* filePathFromUrl(path, callerImportMetaUrl);
254 const currentDirectory = path.dirname(currentFilePath);
255 const executableDirectory = path.dirname(execPath);
256
@@ -213,13 +264,24 @@ export const resolveRunCompanionAssetPath = ({
264 return Option.getOrNull(found);
265 });
266
267 +/**
268 + * Relative paths an install rooted at `rootDir` is expected to contain.
269 + *
270 + * `staticAssetRelativePaths` defaults to the host's requirement set, so a
271 + * missing codex-acp binary for a foreign platform never counts as a broken
272 + * install. Release packaging passes `RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS`
273 + * because one packaging host builds archives for every platform.
274 + */
275 export const collectExpectedRunCompanionAssetRelativePaths = (
217 - rootDir: string
276 + rootDir: string,
277 + options: { readonly staticAssetRelativePaths?: ReadonlyArray<string> } = {}
278 ): Effect.Effect<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> =>
279 Effect.gen(function* () {
280 const fs = yield* FileSystem.FileSystem;
281 const path = yield* Path.Path;
282 const collected = new Set<string>();
283 + const staticAssetRelativePaths =
284 + options.staticAssetRelativePaths ?? (yield* hostRunCompanionStaticAssetRelativePaths);
285
286 for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
287 yield* collectRelativeImportPaths({
@@ -232,7 +294,7 @@ export const collectExpectedRunCompanionAssetRelativePaths = (
294 });
295 }
296
235 - for (const relativePath of RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS) {
297 + for (const relativePath of staticAssetRelativePaths) {
298 yield* collectRelativeImportPaths({
299 fs,
300 path,
@@ -358,6 +420,16 @@ export const writeInstalledReleaseTag = (
420 );
421 });
422
423 +/**
424 + * Startup tier: the `run-*.mjs` companion wrappers and their import graph.
425 + *
426 + * Every `composio run` preloads these into the spawned child, so a missing one
427 + * really is a broken install and justifies the self-repair download. The ACP
428 + * adapter assets are deliberately excluded — a script like
429 + * `composio run 'console.log(1)'` never invokes a sub-agent, and requiring
430 + * ~224MB of adapters for it turned a working install into a hard failure.
431 + * `run-subagent-acp` checks the ACP tier lazily at the invocation site instead.
432 + */
433 export const listMissingInstalledRunCompanionModules = (
434 execPath: string
435 ): Effect.Effect<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> =>
@@ -365,13 +437,37 @@ export const listMissingInstalledRunCompanionModules = (
437 const fs = yield* FileSystem.FileSystem;
438 const path = yield* Path.Path;
439 const installDirectory = path.dirname(execPath);
368 - const expectedRelativePaths =
369 - yield* collectExpectedRunCompanionAssetRelativePaths(installDirectory);
440 + const expectedRelativePaths = yield* collectExpectedRunCompanionAssetRelativePaths(
441 + installDirectory,
442 + { staticAssetRelativePaths: [] }
443 + );
444 return yield* Effect.filter(expectedRelativePaths, relativePath =>
445 Effect.map(fileExists(fs, path.join(installDirectory, relativePath)), exists => !exists)
446 );
447 });
448
449 +/**
450 + * Whether the companion wrappers sit next to the executable, which is how
451 + * packaged installs ship them.
452 + *
453 + * This distinguishes an install whose shipped assets went missing (report the
454 + * fix: reinstall / `composio upgrade`) from a source checkout that never had
455 + * them, where the CLI runs through `bun` and the npx/PATH adapter fallbacks are
456 + * the intended route.
457 + */
458 +export const hasInstalledRunCompanionModules = (
459 + execPath: string
460 +): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>
461 + Effect.gen(function* () {
462 + const fs = yield* FileSystem.FileSystem;
463 + const path = yield* Path.Path;
464 + const installDirectory = path.dirname(execPath);
465 + const missing = yield* Effect.findFirst(RUN_COMPANION_MODULE_FILENAMES, fileName =>
466 + Effect.map(fileExists(fs, path.join(installDirectory, fileName)), exists => !exists)
467 + );
468 + return Option.isNone(missing);
469 + });
470 +
471 const fetchGitHubJson = async <A, I>(
472 schema: Schema.Schema<A, I>,
473 {
@@ -493,6 +589,14 @@ const githubRepairConfig = Effect.orDie(
589 })
590 ).pipe(Effect.withConfigProvider(repairConfigProvider));
591
592 +/**
593 + * Restores a packaged install whose companion wrappers went missing.
594 + *
595 + * Triggered by the startup tier only (`listMissingInstalledRunCompanionModules`),
596 + * so a plain `composio run` never downloads a release just because the ACP
597 + * adapters are absent. Once it does run it restores the host's full asset set,
598 + * ACP adapters included, so a repaired install is a complete one.
599 + */
600 export const repairMissingInstalledRunCompanionModules = ({
601 callerImportMetaUrl,
602 execPath,
@@ -510,7 +614,7 @@ export const repairMissingInstalledRunCompanionModules = ({
614 const fs = yield* FileSystem.FileSystem;
615 const path = yield* Path.Path;
616
513 - const currentFilePath = fileURLToPath(callerImportMetaUrl);
617 + const currentFilePath = yield* filePathFromUrl(path, callerImportMetaUrl);
618 if (!currentFilePath.startsWith('/$bunfs/')) {
619 return { repaired: false as const };
620 }
@@ -666,7 +770,7 @@ export const resolveRunCompanionModulePath = ({
770 Effect.gen(function* () {
771 const fs = yield* FileSystem.FileSystem;
772 const path = yield* Path.Path;
669 - const currentFilePath = fileURLToPath(callerImportMetaUrl);
773 + const currentFilePath = yield* filePathFromUrl(path, callerImportMetaUrl);
774 const currentDirectory = path.dirname(currentFilePath);
775 const executableDirectory = path.dirname(execPath);
776 const baseName = path.basename(relativeNoExtensionFromCaller);
ts/packages/cli/src/services/run-helpers-runtime.ts
+110 -71
@@ -2,15 +2,12 @@
2 // runtime or @effect/platform layers are provided, so it uses sync Node builtins.
3 // eslint-disable-next-line no-restricted-imports -- sync fs for run-log appends, run-file writes, and CLI config reads in the child process, outside the Effect runtime
4 import * as fs from 'node:fs';
5 -// eslint-disable-next-line no-restricted-imports -- os.tmpdir() locates the fallback run-files directory in the child process, outside the Effect runtime
6 -import * as os from 'node:os';
7 -import process from 'node:process';
8 -import { Path } from '@effect/platform';
9 -import { Effect, Predicate, Schema } from 'effect';
5 +import { Command, Path } from '@effect/platform';
6 +import { BunContext } from '@effect/platform-bun';
7 +import { Effect, Either, ManagedRuntime, Predicate, Schema } from 'effect';
8 import { z } from 'zod';
9 import { JsonRecordSchema } from 'src/effects/json';
12 -import { resolveCliConfigPathSync } from 'src/services/cli-user-config';
13 -import { detectMaster, type MasterKind } from 'src/services/master-detector';
10 +import type { MasterKind } from 'src/services/master-detector';
11 import {
12 isAcpInvokeError,
13 parseJson,
@@ -20,6 +17,14 @@ import {
17 import { invokeAcpSubAgent } from 'src/services/run-subagent-acp';
18 import { invokeLegacySubAgent } from 'src/services/run-subagent-legacy';
19 import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';
20 +import { NodeOs } from 'src/services/node-os';
21 +import { collectText } from 'src/services/command-runner';
22 +import { debugFlagsToChildEnv } from 'src/services/runtime-flags';
23 +
24 +// One Bun platform runtime shared by every CLI child process this module spawns. ManagedRuntime
25 +// builds the layer lazily on first use, so importers that never spawn a child pay nothing, and a
26 +// run script that spawns many does not rebuild the platform services per call.
27 +const bunCommandRuntime = ManagedRuntime.make(BunContext.layer);
28
29 export type RunHelperContext = {
30 readonly apiKey?: string;
@@ -32,6 +37,7 @@ export type RunHelperContext = {
37 readonly consumerProjectName?: string;
38 readonly perfDebug?: boolean;
39 readonly toolDebug?: boolean;
40 + readonly telemetryDebug?: boolean;
41 readonly dryRun?: boolean;
42 readonly skipConnectionCheck?: boolean;
43 readonly skipToolParamsCheck?: boolean;
@@ -43,6 +49,7 @@ export type RunHelperContext = {
49 readonly runOutputDir?: string;
50 readonly runLogFilePath?: string;
51 readonly readAccessRoots?: ReadonlyArray<string>;
52 + readonly cliConfigPath?: string;
53 };
54
55 type RunHelpersInstallParams = {
@@ -262,12 +269,10 @@ const stringifyForPrompt = (value: unknown): string => {
269 if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
270 return String(value);
271 }
265 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- JSON.stringify throws on circular user values in this sync formatter injected into user code; String() is the entire fallback
266 - try {
267 - return JSON.stringify(value, null, 2);
268 - } catch {
269 - return String(value);
270 - }
272 + return Either.getOrElse(
273 + Either.try(() => JSON.stringify(value, null, 2)),
274 + () => String(value)
275 + );
276 };
277
278 const attachPromptMethod = <T>(value: T): T => {
@@ -318,16 +323,20 @@ const summarizeCliResultPreview = (result: RunCliResult): unknown => {
323 return result;
324 };
325
321 -const readConfiguredExperimentalSubagentTarget = (): 'auto' | 'claude' | 'codex' => {
322 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- sync config read at the child-process boundary; a missing or malformed CLI config file just means the 'auto' target
323 - try {
324 - const raw = fs.readFileSync(resolveCliConfigPathSync(), 'utf8');
325 - const parsed = decodeExperimentalSubagentConfig(raw);
326 - const target = parsed.experimental_subagent?.target;
327 - return target === 'claude' || target === 'codex' || target === 'auto' ? target : 'auto';
328 - } catch {
329 - return 'auto';
330 - }
326 +const readConfiguredExperimentalSubagentTarget = (
327 + cliConfigPath: string | undefined
328 +): 'auto' | 'claude' | 'codex' => {
329 + if (!cliConfigPath) return 'auto';
330 +
331 + return Either.getOrElse(
332 + Either.try(() => {
333 + const raw = fs.readFileSync(cliConfigPath, 'utf8');
334 + const parsed = decodeExperimentalSubagentConfig(raw);
335 + const target = parsed.experimental_subagent?.target;
336 + return target === 'claude' || target === 'codex' || target === 'auto' ? target : 'auto';
337 + }),
338 + () => 'auto' as const
339 + );
340 };
341
342 const normalizeInvokeAgentOptions = (
@@ -506,12 +515,13 @@ const createRunHelperLoggers = (params: {
515
516 const createExecutePayloadMaterializer = (params: {
517 readonly path: Path.Path;
518 + readonly tmpdir: string;
519 readonly sharedRunOutputDir: string | null;
520 }): ((value: unknown) => Promise<unknown>) => {
511 - const { path, sharedRunOutputDir } = params;
521 + const { path, tmpdir, sharedRunOutputDir } = params;
522
523 const writeTempExecuteFile = async (value: unknown): Promise<unknown> => {
514 - const outputDir = sharedRunOutputDir || path.join(os.tmpdir(), 'composio-run-files');
524 + const outputDir = sharedRunOutputDir || path.join(tmpdir, 'composio-run-files');
525 fs.mkdirSync(outputDir, { recursive: true });
526 if (typeof File !== 'undefined' && value instanceof File) {
527 const safeName =
@@ -612,32 +622,59 @@ const createCliRunner = (params: {
622 });
623 };
624
625 + // Invariant for the life of the run session, so built once rather than per
626 + // spawned CLI call.
627 + const env: Record<string, string> = {
628 + // The platform command inherits the ambient environment by default. An
629 + // empty BUN_BE_BUN masks the parent run process's Bun compatibility flag
630 + // without copying or enumerating unrelated values.
631 + BUN_BE_BUN: '',
632 + ...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),
633 + ...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),
634 + ...(helperContext.webURL ? { COMPOSIO_WEB_URL: helperContext.webURL } : {}),
635 + COMPOSIO_CLI_INVOCATION_ORIGIN: 'run',
636 + ...(helperContext.runId ? { COMPOSIO_CLI_PARENT_RUN_ID: helperContext.runId } : {}),
637 + ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}),
638 + ...debugFlagsToChildEnv({
639 + perfDebug: perfDebugEnabled,
640 + toolDebug: toolDebugEnabled,
641 + acpOnly: helperContext.acpOnly === true,
642 + telemetryDebug: helperContext.telemetryDebug === true,
643 + }),
644 + };
645 +
646 const runCliJson = async (args: ReadonlyArray<string>): Promise<RunCliResult> => {
647 const requestId = `${args[0] ?? 'cli'}#${++perfDebugSeq}`;
648 helperDebugLog('cli.start', { requestId, args });
618 - const env: Record<string, string | undefined> = {
619 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- the spawned CLI child must inherit the caller's full environment before Composio-specific overrides are layered on top
620 - ...process.env,
621 - ...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),
622 - ...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),
623 - ...(helperContext.webURL ? { COMPOSIO_WEB_URL: helperContext.webURL } : {}),
624 - COMPOSIO_CLI_INVOCATION_ORIGIN: 'run',
625 - ...(helperContext.runId ? { COMPOSIO_CLI_PARENT_RUN_ID: helperContext.runId } : {}),
626 - ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}),
627 - ...(perfDebugEnabled ? { COMPOSIO_PERF_DEBUG: '1' } : {}),
628 - ...(toolDebugEnabled ? { COMPOSIO_TOOL_DEBUG: '1' } : {}),
629 - };
630 - delete env.BUN_BE_BUN;
649 perfDebugLog('start', requestId, { cmd: args });
632 - const child = Bun.spawn({
633 - cmd: [...cliPrefix, ...args],
634 - env,
635 - stdio: ['inherit', 'pipe', perfDebugEnabled || toolDebugEnabled ? 'inherit' : 'pipe'],
636 - });
637 - const stdout = child.stdout ? await new Response(child.stdout).text() : '';
638 - const stderr = child.stderr ? await new Response(child.stderr).text() : '';
650 + const [executable, ...commandArgs] = [...cliPrefix, ...args];
651 + const inheritStderr = perfDebugEnabled || toolDebugEnabled;
652 + const { exitCode, stderr, stdout } = await bunCommandRuntime.runPromise(
653 + Effect.scoped(
654 + Effect.gen(function* () {
655 + const command = Command.make(executable, ...commandArgs).pipe(
656 + Command.env(env),
657 + Command.stdin('inherit'),
658 + Command.stderr(inheritStderr ? 'inherit' : 'pipe')
659 + );
660 + const child = yield* Command.start(command);
661 + const [childExitCode, childStdout, childStderr] = yield* Effect.all(
662 + [
663 + child.exitCode,
664 + collectText(child.stdout),
665 + inheritStderr ? Effect.succeed('') : collectText(child.stderr),
666 + ],
667 + { concurrency: 'unbounded' }
668 + );
669 + return {
670 + exitCode: Number(childExitCode),
671 + stdout: childStdout,
672 + stderr: childStderr,
673 + };
674 + })
675 + )
676 + );
677 const result = maybeLoadStoredCliResult(parseJson(stdout));
640 - const exitCode = await child.exited;
678 if (exitCode !== 0) {
679 perfDebugLog('error', requestId, { exitCode, stderr: stderr.trim() || undefined });
680 helperDebugLog('cli.error', {
@@ -762,6 +799,10 @@ const createExperimentalSubAgent = (params: {
799 }) => {
800 const { helperContext, helperDebugLog } = params;
801
802 + // The parent CLI resolves the master via `detectMasterFromHost` and serializes
803 + // it into `helperContext` (see run.cmd.ts), so a missing or unrecognized value
804 + // deliberately falls back to 'user' instead of re-detecting from this child
805 + // process's environment.
806 const detectInvokeAgentMaster = (): MasterKind | 'user' => {
807 if (
808 helperContext.master === 'claude' ||
@@ -770,12 +811,12 @@ const createExperimentalSubAgent = (params: {
811 ) {
812 return helperContext.master;
813 }
773 - return detectMaster();
814 + return 'user';
815 };
816
817 const resolveInvokeAgentTarget = (requestedTarget?: string): 'claude' | 'codex' => {
818 if (requestedTarget === 'claude' || requestedTarget === 'codex') return requestedTarget;
778 - const configuredTarget = readConfiguredExperimentalSubagentTarget();
819 + const configuredTarget = readConfiguredExperimentalSubagentTarget(helperContext.cliConfigPath);
820 if (configuredTarget === 'claude' || configuredTarget === 'codex') return configuredTarget;
821 const detected = requestedTarget === 'user' ? 'user' : detectInvokeAgentMaster();
822 if (detected === 'codex' || detected === 'claude') return detected;
@@ -805,20 +846,20 @@ const createExperimentalSubAgent = (params: {
846 resolvedTarget: target,
847 master,
848 });
808 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- async fallback chain in the user's child process: ACP invoke errors route to the legacy sub-agent path, everything else rethrows
809 - try {
810 - const response = await invokeAcpSubAgent({
811 - prompt: prompt.trim(),
812 - options: normalizedOptions,
813 - master,
814 - target,
815 - allowedReadRoots: Array.isArray(helperContext.readAccessRoots)
816 - ? helperContext.readAccessRoots
817 - : [],
818 - helperDebugLog,
819 - });
820 - return logFilePath ? { ...response, logFilePath } : response;
821 - } catch (error) {
849 + const response = await invokeAcpSubAgent({
850 + prompt: prompt.trim(),
851 + options: normalizedOptions,
852 + master,
853 + target,
854 + allowedReadRoots: Array.isArray(helperContext.readAccessRoots)
855 + ? helperContext.readAccessRoots
856 + : [],
857 + helperDebugLog,
858 + }).catch(error => {
859 + // Only ACP protocol failures fall back to the legacy sub-agent. A damaged
860 + // install (MissingAcpAdapterAssetsError) is not one of them: its message
861 + // names the repair, and swapping in a different sub-agent implementation
862 + // would hide the fact that the install needs fixing.
863 if (!isAcpInvokeError(error)) throw error;
864 if (helperContext.acpOnly === true) throw error;
865 helperDebugLog('subAgent.acp.fallback', {
@@ -826,15 +867,15 @@ const createExperimentalSubAgent = (params: {
867 code: error.code,
868 message: error.message,
869 });
829 - const response = await invokeLegacySubAgent({
870 + return invokeLegacySubAgent({
871 prompt: prompt.trim(),
872 options: normalizedOptions,
873 master,
874 target,
875 helperDebugLog,
876 });
836 - return logFilePath ? { ...response, logFilePath } : response;
837 - }
877 + });
878 + return logFilePath ? { ...response, logFilePath } : response;
879 };
880
881 Object.defineProperty(experimentalSubAgentImpl, 'schema', { value: experimentalSubAgentSchema });
@@ -965,17 +1006,14 @@ export const installRunHelpers = async ({
1006 // Resolve the live services once at that boundary and keep all writes centralized.
1007 const terminal = Effect.runSync(TerminalUI.pipe(Effect.provide(TerminalUILive)));
1008 const path = Effect.runSync(Path.Path.pipe(Effect.provide(Path.layer)));
1009 + const nodeOs = Effect.runSync(NodeOs.pipe(Effect.provide(NodeOs.Default)));
1010 const writeError = (line: string) => Effect.runSync(terminal.error(line));
1011
1012 Reflect.set(globalThis, 'z', z);
1013 Reflect.set(globalThis, 'zod', z);
1014
973 - const perfDebugEnabled =
974 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- debug flag reaches the child process via inherited environment; the CLI's Config provider is not available here
975 - helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === '1';
976 - const toolDebugEnabled =
977 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- debug flag reaches the child process via inherited environment; the CLI's Config provider is not available here
978 - helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === '1';
1015 + const perfDebugEnabled = helperContext.perfDebug === true;
1016 + const toolDebugEnabled = helperContext.toolDebug === true;
1017 const perfDebugStart = Date.now();
1018 const composioBaseURL = (helperContext.baseURL || 'https://backend.composio.dev').replace(
1019 /\/$/,
@@ -1001,6 +1039,7 @@ export const installRunHelpers = async ({
1039
1040 const materializeExecutePayload = createExecutePayloadMaterializer({
1041 path,
1042 + tmpdir: nodeOs.tmpdir,
1043 sharedRunOutputDir,
1044 });
1045 const runCliJson = createCliRunner({
ts/packages/cli/src/services/run-subagent-acp.ts
+120 -33
@@ -3,13 +3,15 @@ import type { Readable } from 'node:stream';
3 import * as acp from '@agentclientprotocol/sdk';
4 import { Command, FileSystem, Path } from '@effect/platform';
5 import { BunContext } from '@effect/platform-bun';
6 -import { Cause, Config, Effect, Exit, Layer, Option, Predicate, Queue, Stream } from 'effect';
6 +import { Cause, Config, Data, Effect, Exit, Layer, Option, Predicate, Queue, Stream } from 'effect';
7 import type { MasterKind } from 'src/services/master-detector';
8 import { NodeOs } from 'src/services/node-os';
9 import {
10 + codexAcpBinaryTargetFor,
11 + hasInstalledRunCompanionModules,
12 resolveRunCompanionAssetPath,
13 resolveRunCompanionModulePath,
12 - RUN_CODEX_ACP_BINARY_TARGETS,
14 + RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
15 } from 'src/services/run-companion-modules';
16 import {
17 ACP_STRUCTURED_OUTPUT_TOOL_NAME,
@@ -105,30 +107,95 @@ const writableStreamFromQueue = (queue: Queue.Queue<Uint8Array>): WritableStream
107 abort: () => Effect.runPromise(Queue.shutdown(queue)),
108 });
109
108 -const resolveShippedAdapterAsset = (
109 - target: InvokeAgentTarget
110 -): Effect.Effect<string | null, never, FileSystem.FileSystem | Path.Path> => {
111 - if (target === 'claude') {
112 - return resolveRunCompanionAssetPath({
113 - callerImportMetaUrl: import.meta.url,
114 - execPath: process.execPath,
115 - relativePathFromRoot: 'acp-adapters/claude-code-acp.mjs',
110 +/**
111 + * The ACP adapter assets are the lazy tier of the companion install: `composio
112 + * run` no longer requires them at startup, so this is the first place that can
113 + * observe them missing. When a packaged install has lost them, say so with the
114 + * fix instead of silently falling through to an npx download or a 404 from the
115 + * startup repair path.
116 + */
117 +export class MissingAcpAdapterAssetsError extends Data.TaggedError(
118 + 'services/MissingAcpAdapterAssetsError'
119 +)<{
120 + readonly message: string;
121 + readonly target: InvokeAgentTarget;
122 + readonly missingRelativePaths: ReadonlyArray<string>;
123 + readonly installDirectory: string;
124 +}> {
125 + // The error crosses into the user's script as a rejection, so it reports its
126 + // own name rather than the internal `services/`-prefixed tag.
127 + override readonly name = 'MissingAcpAdapterAssetsError';
128 +}
129 +
130 +type ShippedAdapterAsset = {
131 + /** Absolute path to the adapter shipped with this install, when present. */
132 + readonly resolvedPath: string | null;
133 + /**
134 + * Asset paths a complete install ships for this target on this host, relative
135 + * to the install root. Empty when this platform has no shipped adapter at all
136 + * (no codex-acp binary is built for it), which is not a broken install.
137 + */
138 + readonly expectedRelativePaths: ReadonlyArray<string>;
139 +};
140 +
141 +const resolveShippedAdapterAsset = ({
142 + target,
143 + execPath,
144 +}: {
145 + target: InvokeAgentTarget;
146 + execPath: string;
147 +}): Effect.Effect<ShippedAdapterAsset, never, FileSystem.FileSystem | Path.Path> =>
148 + Effect.gen(function* () {
149 + if (target === 'claude') {
150 + return {
151 + resolvedPath: yield* resolveRunCompanionAssetPath({
152 + callerImportMetaUrl: import.meta.url,
153 + execPath,
154 + relativePathFromRoot: 'acp-adapters/claude-code-acp.mjs',
155 + }),
156 + // cli.js has no separate resolution step: the bundled adapter finds it
157 + // through import.meta.url, so name it as part of the requirement.
158 + expectedRelativePaths: RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
159 + };
160 + }
161 +
162 + const binaryTarget = codexAcpBinaryTargetFor({
163 + platform: process.platform,
164 + arch: process.arch,
165 });
117 - }
166 + if (!binaryTarget) {
167 + return { resolvedPath: null, expectedRelativePaths: [] };
168 + }
169
119 - const binaryTarget = RUN_CODEX_ACP_BINARY_TARGETS.find(
120 - candidate => candidate.platform === process.platform && candidate.arch === process.arch
121 - );
122 - if (!binaryTarget) {
123 - return Effect.succeed(null);
124 - }
170 + return {
171 + resolvedPath: yield* resolveRunCompanionAssetPath({
172 + callerImportMetaUrl: import.meta.url,
173 + execPath,
174 + relativePathFromRoot: binaryTarget.relativePath,
175 + }),
176 + expectedRelativePaths: [binaryTarget.relativePath],
177 + };
178 + });
179
126 - return resolveRunCompanionAssetPath({
127 - callerImportMetaUrl: import.meta.url,
128 - execPath: process.execPath,
129 - relativePathFromRoot: binaryTarget.relativePath,
180 +const missingAcpAdapterAssetsError = ({
181 + target,
182 + installDirectory,
183 + missingRelativePaths,
184 +}: {
185 + target: InvokeAgentTarget;
186 + installDirectory: string;
187 + missingRelativePaths: ReadonlyArray<string>;
188 +}) =>
189 + new MissingAcpAdapterAssetsError({
190 + target,
191 + installDirectory,
192 + missingRelativePaths,
193 + message: [
194 + `This Composio install cannot run a ${target} sub-agent: the ACP adapter files are missing from ${installDirectory}.`,
195 + ...missingRelativePaths.map(relativePath => ` - ${relativePath}`),
196 + `Run 'composio upgrade' to restore them, or reinstall the CLI.`,
197 + ].join('\n'),
198 });
131 -};
199
200 const resolveInstalledAdapter = (target: InvokeAgentTarget): string | null => {
201 const specifier =
@@ -140,25 +207,31 @@ const resolveInstalledAdapter = (target: InvokeAgentTarget): string | null => {
207 };
208
209 export const resolveAcpAdapterCommand = (
143 - target: InvokeAgentTarget
144 -): Effect.Effect<AcpAdapterCommand, never, FileSystem.FileSystem | Path.Path> =>
210 + target: InvokeAgentTarget,
211 + { execPath = process.execPath }: { readonly execPath?: string } = {}
212 +): Effect.Effect<
213 + AcpAdapterCommand,
214 + MissingAcpAdapterAssetsError,
215 + FileSystem.FileSystem | Path.Path
216 +> =>
217 Effect.gen(function* () {
218 + const path = yield* Path.Path;
219 const binary = target === 'claude' ? 'claude-code-acp' : 'codex-acp';
220 const packageName =
221 target === 'claude' ? '@zed-industries/claude-code-acp' : '@zed-industries/codex-acp';
222
223 // 1. Prefer shipped companion assets next to the CLI binary / dist bundle.
151 - const shipped = yield* resolveShippedAdapterAsset(target);
152 - if (shipped) {
224 + const shipped = yield* resolveShippedAdapterAsset({ target, execPath });
225 + if (shipped.resolvedPath) {
226 if (target === 'codex') {
227 return {
155 - cmd: [shipped],
228 + cmd: [shipped.resolvedPath],
229 source: 'shipped',
230 } satisfies AcpAdapterCommand;
231 }
232
233 return {
161 - cmd: [process.execPath, shipped],
234 + cmd: [execPath, shipped.resolvedPath],
235 env: {
236 BUN_BE_BUN: '1',
237 },
@@ -166,11 +239,26 @@ export const resolveAcpAdapterCommand = (
239 } satisfies AcpAdapterCommand;
240 }
241
242 + // A packaged install ships both the companion wrappers and the adapters. If
243 + // the wrappers are there and the adapters are not, the install is damaged —
244 + // report the repair instead of quietly downloading an adapter through npx.
245 + // A source checkout has no wrappers next to `bun`, so it keeps falling back.
246 + if (
247 + shipped.expectedRelativePaths.length > 0 &&
248 + (yield* hasInstalledRunCompanionModules(execPath))
249 + ) {
250 + return yield* missingAcpAdapterAssetsError({
251 + target,
252 + installDirectory: path.dirname(execPath),
253 + missingRelativePaths: shipped.expectedRelativePaths,
254 + });
255 + }
256 +
257 // 2. Try the installed dependency bundle next (no npx overhead).
258 const bundled = resolveInstalledAdapter(target);
259 if (bundled) {
260 return {
173 - cmd: [process.execPath, bundled],
261 + cmd: [execPath, bundled],
262 env: {
263 BUN_BE_BUN: '1',
264 },
@@ -741,10 +829,9 @@ const invokeAcpSubAgentEffect = ({
829 args: resolved.cmd.slice(1),
830 });
831
744 - // The Claude Code CLI refuses to start when it inherits CLAUDECODE=1 (its
745 - // nested-session guard checks `process.env.CLAUDECODE === "1"`). The
746 - // platform Command executor always spreads process.env into the child, so
747 - // the variable cannot be dropped; mask it with an empty string instead —
832 + // The Claude Code CLI refuses to start when it inherits CLAUDECODE=1. The
833 + // platform Command executor inherits the parent environment, so the
834 + // variable cannot be dropped; mask it with an empty string instead —
835 // falsy and distinct from the guarded "1" — only when the parent has it set.
836 const claudeCode = yield* Config.option(Config.string('CLAUDECODE'));
837 const childEnv: Record<string, string> = {
ts/packages/cli/src/services/run-subagent-output-mcp.ts
+5 -4
@@ -1,7 +1,7 @@
1 -// eslint-disable-next-line no-restricted-imports -- standalone MCP stdio sidecar entrypoint runs outside the CLI's Effect runtime; sync fs reads the schema file and writes the structured result file
2 -import * as fs from 'node:fs';
1 import process from 'node:process';
2 import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
3 +import { FileSystem } from '@effect/platform';
4 +import { BunFileSystem } from '@effect/platform-bun';
5 import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
6 import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7 import { Effect } from 'effect';
@@ -22,9 +22,10 @@ const readFlag = (name: string): string => {
22 };
23
24 const main = async (): Promise<void> => {
25 + const fs = Effect.runSync(FileSystem.FileSystem.pipe(Effect.provide(BunFileSystem.layer)));
26 const schemaFilePath = readFlag('--schema-file');
27 const resultFilePath = readFlag('--result-file');
27 - const schemaText = fs.readFileSync(schemaFilePath, 'utf8');
28 + const schemaText = await Effect.runPromise(fs.readFileString(schemaFilePath));
29 const structuredSchema = decodeStructuredSchemaJson(schemaText);
30 const toolInputSchema = jsonSchemaToZod(buildStructuredOutputToolSchema(structuredSchema));
31
@@ -42,7 +43,7 @@ const main = async (): Promise<void> => {
43 inputSchema: toolInputSchema,
44 },
45 async (payload: unknown) => {
45 - fs.writeFileSync(resultFilePath, JSON.stringify(payload), 'utf8');
46 + await Effect.runPromise(fs.writeFileString(resultFilePath, JSON.stringify(payload)));
47 return {
48 content: [
49 {
ts/packages/cli/src/services/runtime-cli-context.ts new
+40
@@ -0,0 +1,40 @@
1 +import { Context, Effect, Layer, Option } from 'effect';
2 +import { APP_CONFIG } from 'src/effects/app-config';
3 +
4 +export const DEFAULT_CLI_INVOCATION_ORIGIN = 'cli';
5 +
6 +export type CliInvocationContext = {
7 + readonly invocationOrigin: string;
8 + readonly parentRunId: string | undefined;
9 +};
10 +
11 +/**
12 + * Who invoked this CLI process, and under which parent run.
13 + *
14 + * Both values arrive as the `COMPOSIO_CLI_INVOCATION_ORIGIN` / `COMPOSIO_CLI_PARENT_RUN_ID`
15 + * handshake `composio run` and `install.sh` set on the processes they spawn, so `effect/Config`
16 + * already is their injection point: a test overrides them with a config provider.
17 + */
18 +export const cliInvocationContext: Effect.Effect<CliInvocationContext> = Effect.all({
19 + invocationOrigin: APP_CONFIG.CLI_INVOCATION_ORIGIN,
20 + parentRunId: APP_CONFIG.CLI_PARENT_RUN_ID,
21 +}).pipe(
22 + Effect.orDie,
23 + Effect.map(({ invocationOrigin, parentRunId }) => ({
24 + invocationOrigin: invocationOrigin ?? DEFAULT_CLI_INVOCATION_ORIGIN,
25 + parentRunId,
26 + }))
27 +);
28 +
29 +/**
30 + * Run id the bootstrap resolved for a `composio run` invocation.
31 + *
32 + * `cli-main.ts` mints it while building the run's telemetry context and hands it to the command,
33 + * so the `CLI_RUN_*` events and the `COMPOSIO_CLI_PARENT_RUN_ID` the script's child process
34 + * inherits carry the same id. `None` for every other command, and for callers that drive the root
35 + * command directly.
36 + */
37 +export class CliRunId extends Context.Tag('services/CliRunId')<CliRunId, Option.Option<string>>() {}
38 +
39 +export const cliRunIdLayer = (runId: string | undefined): Layer.Layer<CliRunId> =>
40 + Layer.succeed(CliRunId, Option.fromNullable(runId));
ts/packages/cli/src/services/runtime-debug-flags.ts deleted
-31
@@ -1,31 +0,0 @@
1 -type RuntimeDebugFlags = {
2 - readonly perfDebug: boolean;
3 - readonly toolDebug: boolean;
4 -};
5 -
6 -let runtimeDebugFlags: RuntimeDebugFlags = {
7 - perfDebug: false,
8 - toolDebug: false,
9 -};
10 -
11 -export const setRuntimeDebugFlags = (flags: Partial<RuntimeDebugFlags>) => {
12 - runtimeDebugFlags = {
13 - perfDebug: flags.perfDebug ?? runtimeDebugFlags.perfDebug,
14 - toolDebug: flags.toolDebug ?? runtimeDebugFlags.toolDebug,
15 - };
16 -};
17 -
18 -export const resetRuntimeDebugFlags = () => {
19 - runtimeDebugFlags = {
20 - perfDebug: false,
21 - toolDebug: false,
22 - };
23 -};
24 -
25 -export const isPerfDebugEnabled = () =>
26 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- called from sync non-Effect helper code in spawned child processes, where the flag arrives via inherited environment rather than a Config provider
27 - runtimeDebugFlags.perfDebug || process.env.COMPOSIO_PERF_DEBUG === '1';
28 -
29 -export const isToolDebugEnabled = () =>
30 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- called from sync non-Effect helper code in spawned child processes, where the flag arrives via inherited environment rather than a Config provider
31 - runtimeDebugFlags.toolDebug || process.env.COMPOSIO_TOOL_DEBUG === '1';
ts/packages/cli/src/services/runtime-debug-logger.ts
+5 -5
@@ -1,5 +1,5 @@
1 import { Effect } from 'effect';
2 -import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';
2 +import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-flags';
3 import { TerminalUI } from 'src/services/terminal-ui';
4
5 const writeJsonDebugLine = (channel: string, payload: Record<string, unknown>) =>
@@ -9,15 +9,15 @@ const writeJsonDebugLine = (channel: string, payload: Record<string, unknown>) =
9 });
10
11 export const logToolDebug = (label: string, details: Record<string, unknown> = {}) =>
12 - Effect.suspend(() =>
13 - isToolDebugEnabled() ? writeJsonDebugLine('tool-debug', { label, ...details }) : Effect.void
12 + Effect.flatMap(isToolDebugEnabled, enabled =>
13 + enabled ? writeJsonDebugLine('tool-debug', { label, ...details }) : Effect.void
14 );
15
16 export const makePerfDebugLogger =
17 (startedAt: number = Date.now()) =>
18 (label: string, details: Record<string, unknown> = {}) =>
19 - Effect.suspend(() =>
20 - isPerfDebugEnabled()
19 + Effect.flatMap(isPerfDebugEnabled, enabled =>
20 + enabled
21 ? writeJsonDebugLine('perf', {
22 phase: 'event',
23 label,
ts/packages/cli/src/services/runtime-flags.ts new
+142
@@ -0,0 +1,142 @@
1 +import { Context, Effect, Layer, Option } from 'effect';
2 +import { APP_CONFIG, UNPREFIXED_CONFIG } from 'src/effects/app-config';
3 +import { loadHostConfig } from 'src/services/config';
4 +
5 +export const TELEMETRY_DEBUG_FLAG = '--telemetry-debug';
6 +
7 +export type StrippedTelemetryDebugArgv = {
8 + readonly argv: ReadonlyArray<string>;
9 + readonly telemetryDebug: boolean;
10 +};
11 +
12 +/**
13 + * Removes `--telemetry-debug` from the CLI's own arguments and reports whether it was there.
14 + *
15 + * Only arguments before the first `--` are considered: everything after the delimiter belongs to
16 + * the process `composio run` spawns, so `composio run -- my-agent --telemetry-debug` has to reach
17 + * `my-agent` untouched.
18 + *
19 + * `src/bin.ts` runs this before the Effect runtime exists, which is why the answer travels into
20 + * the runtime as the `TelemetryDebugMode` service instead of module state.
21 + */
22 +export const stripTelemetryDebugFlag = (
23 + argv: ReadonlyArray<string>
24 +): StrippedTelemetryDebugArgv => {
25 + const delimiterIndex = argv.indexOf('--');
26 + const searchEnd = delimiterIndex < 0 ? argv.length : delimiterIndex;
27 + const flagIndex = argv.findIndex(
28 + (token, index) => index < searchEnd && token === TELEMETRY_DEBUG_FLAG
29 + );
30 + if (flagIndex < 0) {
31 + return { argv, telemetryDebug: false };
32 + }
33 +
34 + return {
35 + argv: [...argv.slice(0, flagIndex), ...argv.slice(flagIndex + 1)],
36 + telemetryDebug: true,
37 + };
38 +};
39 +
40 +/**
41 + * Values parsed from the hidden `--perf-debug` / `--tool-debug` / `--acp-only` flags.
42 + *
43 + * `undefined` means "the flag was absent", which is what lets the corresponding `COMPOSIO_*`
44 + * config value through; an explicit `true`/`false` always wins over it.
45 + */
46 +export type CliDebugFlagOverrides = {
47 + readonly perfDebug: boolean | undefined;
48 + readonly toolDebug: boolean | undefined;
49 + readonly acpOnly: boolean | undefined;
50 +};
51 +
52 +export const NO_CLI_DEBUG_FLAG_OVERRIDES: CliDebugFlagOverrides = {
53 + perfDebug: undefined,
54 + toolDebug: undefined,
55 + acpOnly: undefined,
56 +};
57 +
58 +/**
59 + * Hidden debug flags of the current invocation.
60 + *
61 + * `src/commands/index.ts` parses them out of argv in one place and provides this service for the
62 + * command it then routes to, so every reader takes the values as an input instead of reaching for
63 + * process-wide state.
64 + */
65 +export class CliDebugFlags extends Context.Tag('services/CliDebugFlags')<
66 + CliDebugFlags,
67 + CliDebugFlagOverrides
68 +>() {}
69 +
70 +export const cliDebugFlagsLayer = (
71 + overrides: CliDebugFlagOverrides = NO_CLI_DEBUG_FLAG_OVERRIDES
72 +): Layer.Layer<CliDebugFlags> => Layer.succeed(CliDebugFlags, overrides);
73 +
74 +const debugFlagOr = (
75 + select: (overrides: CliDebugFlagOverrides) => boolean | undefined,
76 + configured: Effect.Effect<boolean, never, never>
77 +): Effect.Effect<boolean, never, CliDebugFlags> =>
78 + Effect.map(
79 + Effect.all([CliDebugFlags, configured]),
80 + ([overrides, configuredValue]) => select(overrides) ?? configuredValue
81 + );
82 +
83 +export const isPerfDebugEnabled = debugFlagOr(
84 + overrides => overrides.perfDebug,
85 + Effect.orDie(APP_CONFIG.PERF_DEBUG)
86 +);
87 +
88 +export const isToolDebugEnabled = debugFlagOr(
89 + overrides => overrides.toolDebug,
90 + Effect.orDie(APP_CONFIG.TOOL_DEBUG)
91 +);
92 +
93 +export const isAcpOnlyEnabled = debugFlagOr(
94 + overrides => overrides.acpOnly,
95 + Effect.orDie(APP_CONFIG.RUN_ACP_ONLY)
96 +);
97 +
98 +/**
99 + * Debug state a parent CLI process resolved for the processes it spawns.
100 + *
101 + * Flags reach the parent as hidden CLI options or `COMPOSIO_*` variables, but a child only sees
102 + * the environment, so every spawn site has to serialize the resolved values back into it. Keeping
103 + * the mapping here means a flag added to this file cannot be forwarded from one spawn site and
104 + * forgotten at another.
105 + */
106 +export type ChildProcessDebugFlags = {
107 + readonly perfDebug: boolean;
108 + readonly toolDebug: boolean;
109 + readonly acpOnly: boolean;
110 + readonly telemetryDebug: boolean;
111 +};
112 +
113 +export const debugFlagsToChildEnv = (flags: ChildProcessDebugFlags): Record<string, string> => ({
114 + COMPOSIO_PERF_DEBUG: flags.perfDebug ? '1' : '0',
115 + COMPOSIO_TOOL_DEBUG: flags.toolDebug ? '1' : '0',
116 + COMPOSIO_RUN_ACP_ONLY: flags.acpOnly ? '1' : '0',
117 + COMPOSIO_CLI_TELEMETRY_DEBUG: flags.telemetryDebug ? '1' : '0',
118 +});
119 +
120 +/**
121 + * Set when `--telemetry-debug` was found on the command line.
122 + *
123 + * The flag is stripped in `src/bin.ts` before the Effect runtime exists, so its value is handed to
124 + * the runtime as this service. Telemetry dispatch runs from service constructors and from the
125 + * detached worker process, where a hard requirement could not be satisfied, so readers resolve it
126 + * with `Effect.serviceOption` and fall back to `COMPOSIO_CLI_TELEMETRY_DEBUG`.
127 + */
128 +export class TelemetryDebugMode extends Context.Tag('services/TelemetryDebugMode')<
129 + TelemetryDebugMode,
130 + boolean
131 +>() {}
132 +
133 +export const telemetryDebugModeLayer = (enabled: boolean): Layer.Layer<TelemetryDebugMode> =>
134 + Layer.succeed(TelemetryDebugMode, enabled);
135 +
136 +export const isTelemetryDebugEnabled: Effect.Effect<boolean> = Effect.flatMap(
137 + Effect.serviceOption(TelemetryDebugMode),
138 + Option.match({
139 + onNone: () => loadHostConfig(UNPREFIXED_CONFIG.TELEMETRY_DEBUG),
140 + onSome: Effect.succeed,
141 + })
142 +);
ts/packages/cli/src/services/setup.ts
+4
@@ -15,6 +15,7 @@ import {
15 } from './agent-host';
16 import { CommandRunner, type CommandResult } from './command-runner';
17 import { SetupSkillInstaller } from './setup-skill-installer';
18 +import { cliInvocationContext } from './runtime-cli-context';
19
20 export const SETUP_TARGETS = ['auto', ...AGENT_HOSTS, 'all'] as const;
21 export type SetupTarget = (typeof SETUP_TARGETS)[number];
@@ -829,6 +830,7 @@ const runSetupTargets = <E, R>(
830 Effect.gen(function* () {
831 const operation = verb === 'Uninstall' ? 'uninstall' : 'setup';
832 const phase = verb === 'Uninstall' ? 'uninstall' : 'install';
833 + const { invocationOrigin } = yield* cliInvocationContext;
834 const completed: SetupTargetResult[] = [];
835 for (const status of inspected) {
836 const result = yield* runAdapter(ADAPTERS[status.target], status).pipe(
@@ -839,6 +841,7 @@ const runSetupTargets = <E, R>(
841 target: status.target,
842 phase,
843 error,
844 + invocationOrigin,
845 cliVersion: APP_VERSION,
846 })
847 )
@@ -868,6 +871,7 @@ const runSetupTargets = <E, R>(
871 operation,
872 target: result.target,
873 action,
874 + invocationOrigin,
875 cliVersion: APP_VERSION,
876 })
877 );
ts/packages/cli/src/services/tool-permissions.ts
+49 -27
@@ -4,7 +4,7 @@ import open from 'open';
4 import { detectCliPlatform } from '@composio/cli-local-tools';
5 import { Data, Effect, Option, Record as EffectRecord, Schema } from 'effect';
6 import { JsonRecordSchema } from 'src/effects/json';
7 -import { resolveCliConfigDirectorySync } from 'src/services/cli-user-config';
7 +import { setupCacheDir } from 'src/effects/setup-cache-dir';
8 import { atomicWriteFileString } from 'src/utils/atomic-write';
9 import { collectDecodedEntries } from 'src/utils/collect-decoded-entries';
10 import {
@@ -170,7 +170,8 @@ interface GateParams {
170
171 const allowDecisionMemoryCache = new Map<string, number>();
172
173 -const cachePath = (path: Path.Path) => path.join(resolveCliConfigDirectorySync(), CACHE_FILE_NAME);
173 +const cachePath = (path: Path.Path, cacheDirectory: string) =>
174 + path.join(cacheDirectory, CACHE_FILE_NAME);
175 const cacheKey = (params: { orgId: string; projectId: string; consumerUserId: string }) =>
176 [params.orgId, params.projectId, params.consumerUserId].join(':');
177 const normalizeBaseUrl = (baseURL: string) => baseURL.replace(/\/$/, '');
@@ -189,8 +190,12 @@ const pruneAllowEntries = (
190 );
191
192 // A missing or unreadable cache file degrades to an empty cache.
192 -const readCacheFile = (fs: FileSystem.FileSystem, path: Path.Path): Effect.Effect<CacheFile> =>
193 - fs.readFileString(cachePath(path)).pipe(
193 +const readCacheFile = (
194 + fs: FileSystem.FileSystem,
195 + path: Path.Path,
196 + cacheDirectory: string
197 +): Effect.Effect<CacheFile> =>
198 + fs.readFileString(cachePath(path, cacheDirectory)).pipe(
199 Effect.map((raw): CacheFile => {
200 const parsed = decodeCacheFileTolerant(raw);
201 return {
@@ -201,9 +206,14 @@ const readCacheFile = (fs: FileSystem.FileSystem, path: Path.Path): Effect.Effec
206 Effect.orElseSucceed((): CacheFile => ({ entries: {} }))
207 );
208
204 -const writeCacheFile = (fs: FileSystem.FileSystem, path: Path.Path, cache: CacheFile) =>
209 +const writeCacheFile = (
210 + fs: FileSystem.FileSystem,
211 + path: Path.Path,
212 + cacheDirectory: string,
213 + cache: CacheFile
214 +) =>
215 Effect.gen(function* () {
206 - const targetPath = cachePath(path);
216 + const targetPath = cachePath(path, cacheDirectory);
217 yield* fs.makeDirectory(path.dirname(targetPath), { recursive: true });
218
219 // Atomic write: on failure the temp file is dropped (best effort) and the
@@ -230,20 +240,22 @@ const cacheWriteSemaphore = Effect.unsafeMakeSemaphore(1);
240 const updateCacheFile = (
241 fs: FileSystem.FileSystem,
242 path: Path.Path,
243 + cacheDirectory: string,
244 update: (current: CacheFile) => CacheFile
245 ) =>
246 cacheWriteSemaphore.withPermits(1)(
236 - readCacheFile(fs, path).pipe(
237 - Effect.flatMap(current => writeCacheFile(fs, path, update(current)))
247 + readCacheFile(fs, path, cacheDirectory).pipe(
248 + Effect.flatMap(current => writeCacheFile(fs, path, cacheDirectory, update(current)))
249 )
250 );
251
252 const writeCacheEntry = (
253 fs: FileSystem.FileSystem,
254 path: Path.Path,
255 + cacheDirectory: string,
256 entry: ConsumerPermissionSnapshot
257 ) =>
246 - updateCacheFile(fs, path, current => ({
258 + updateCacheFile(fs, path, cacheDirectory, current => ({
259 entries: {
260 ...current.entries,
261 [cacheKey(entry)]: entry,
@@ -254,13 +266,16 @@ const writeCacheEntry = (
266 const readCachedEntry = (
267 fs: FileSystem.FileSystem,
268 path: Path.Path,
269 + cacheDirectory: string,
270 params: {
271 orgId: string;
272 projectId: string;
273 consumerUserId: string;
274 }
275 ): Effect.Effect<ConsumerPermissionSnapshot | undefined> =>
263 - readCacheFile(fs, path).pipe(Effect.map(cache => cache.entries[cacheKey(params)]));
276 + readCacheFile(fs, path, cacheDirectory).pipe(
277 + Effect.map(cache => cache.entries[cacheKey(params)])
278 + );
279
280 const isFreshForAccounts = (
281 entry: ConsumerPermissionSnapshot | undefined,
@@ -324,6 +339,7 @@ export const refreshConsumerPermissionSnapshot = (params: {
339 Effect.gen(function* () {
340 const fs = yield* FileSystem.FileSystem;
341 const path = yield* Path.Path;
342 + const cacheDirectory = yield* setupCacheDir;
343 const userContext = yield* ComposioUserContext;
344 const apiKey = Option.getOrUndefined(userContext.data.apiKey);
345 if (!apiKey) return undefined;
@@ -410,7 +426,7 @@ export const refreshConsumerPermissionSnapshot = (params: {
426 // A fail-closed snapshot is not persisted, so a healthy fetch replaces it
427 // on the next command instead of pinning ask_every_call for the TTL.
428 if (!resolved.resolveFailed) {
413 - yield* writeCacheEntry(fs, path, snapshot).pipe(
429 + yield* writeCacheEntry(fs, path, cacheDirectory, snapshot).pipe(
430 Effect.catchAll(cause =>
431 Effect.logDebug(
432 'Failed to write the tool permissions cache',
@@ -442,10 +458,11 @@ export const getConsumerPermissionSnapshot = (params: {
458 Effect.gen(function* () {
459 const fs = yield* FileSystem.FileSystem;
460 const path = yield* Path.Path;
461 + const cacheDirectory = yield* setupCacheDir;
462 const connectedAccountIds = uniq(params.connectedAccountIds ?? []);
463 // Read failures are absorbed inside readCacheFile (empty cache), so an
464 // unreadable cache file behaves exactly like a cache miss here.
448 - const cached = yield* readCachedEntry(fs, path, params);
465 + const cached = yield* readCachedEntry(fs, path, cacheDirectory, params);
466
467 if (isFreshForAccounts(cached, connectedAccountIds)) {
468 yield* refreshConsumerPermissionSnapshot({ ...params, connectedAccountIds }).pipe(
@@ -554,13 +571,14 @@ const isAllowCachedInMemory = (cacheKey: string, now = Date.now()): boolean => {
571 const isAllowCached = (
572 fs: FileSystem.FileSystem,
573 path: Path.Path,
574 + cacheDirectory: string,
575 cacheKey: string,
576 now = Date.now()
577 ): Effect.Effect<boolean> =>
578 Effect.suspend(() => {
579 if (isAllowCachedInMemory(cacheKey, now)) return Effect.succeed(true);
580
563 - return readCacheFile(fs, path).pipe(
581 + return readCacheFile(fs, path, cacheDirectory).pipe(
582 Effect.map(cache => {
583 const expiresAt = cache.allowEntries?.[cacheKey]?.expiresAt;
584 if (expiresAt === undefined || expiresAt <= now) return false;
@@ -574,6 +592,7 @@ const isAllowCached = (
592 const cacheAllowDecision = (
593 fs: FileSystem.FileSystem,
594 path: Path.Path,
595 + cacheDirectory: string,
596 cacheKey: string,
597 now = Date.now()
598 ) =>
@@ -581,7 +600,7 @@ const cacheAllowDecision = (
600 const expiresAt = now + ALLOW_FOR_DURATION_MS;
601 allowDecisionMemoryCache.set(cacheKey, expiresAt);
602
584 - return updateCacheFile(fs, path, current => ({
603 + return updateCacheFile(fs, path, cacheDirectory, current => ({
604 entries: current.entries,
605 allowEntries: {
606 ...current.allowEntries,
@@ -1002,19 +1021,21 @@ const requestPermissionInBrowser = (params: {
1021 clearTimeout(timeout);
1022 reject(error);
1023 });
1005 - server.listen(0, '127.0.0.1', async () => {
1006 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- node:http listen callback inside a Promise executor: on failure to open the browser, close the server and reject the surrounding Promise; Effect's error channel is not available here
1007 - try {
1008 - const address = server.address();
1009 - const port = typeof address === 'object' && address ? address.port : undefined;
1010 - if (!port) throw new Error('Unable to allocate permission callback port.');
1011 - await open(`http://127.0.0.1:${port}/?token=${encodeURIComponent(token)}`, {
1012 - wait: false,
1013 - });
1014 - } catch (error) {
1024 + server.listen(0, '127.0.0.1', () => {
1025 + const address = server.address();
1026 + const port = typeof address === 'object' && address ? address.port : undefined;
1027 + if (!port) {
1028 server.close();
1016 - reject(error);
1029 + reject(new Error('Unable to allocate permission callback port.'));
1030 + return;
1031 }
1032 +
1033 + void open(`http://127.0.0.1:${port}/?token=${encodeURIComponent(token)}`, {
1034 + wait: false,
1035 + }).catch(error => {
1036 + server.close();
1037 + reject(error);
1038 + });
1039 });
1040 });
1041
@@ -1055,10 +1076,11 @@ export const gateToolExecution = (params: GateParams) =>
1076
1077 const fs = yield* FileSystem.FileSystem;
1078 const path = yield* Path.Path;
1079 + const cacheDirectory = yield* setupCacheDir;
1080 const cacheKey = allowCacheKey(params);
1081 // Read failures are absorbed inside readCacheFile (empty cache), so an
1082 // unreadable allow cache behaves exactly like "no cached allow decision".
1061 - const hasCachedAllow = yield* isAllowCached(fs, path, cacheKey);
1083 + const hasCachedAllow = yield* isAllowCached(fs, path, cacheDirectory, cacheKey);
1084 if (hasCachedAllow) {
1085 return { approvalStatus: 'cached_approved' } satisfies PermissionGateResult;
1086 }
@@ -1096,7 +1118,7 @@ export const gateToolExecution = (params: GateParams) =>
1118 }
1119 const cachesAllowOnce = state === 'ask_once' || state === 'ask_once_per_session';
1120 if (decision === 'allow_session' || (cachesAllowOnce && decision === 'allow_once')) {
1099 - yield* cacheAllowDecision(fs, path, cacheKey).pipe(
1121 + yield* cacheAllowDecision(fs, path, cacheDirectory, cacheKey).pipe(
1122 Effect.catchAll(cause =>
1123 Effect.logDebug(
1124 'Failed to cache tool permission allow decision',
ts/packages/cli/src/services/tools-executor.ts
+3
@@ -14,6 +14,7 @@ import {
14 mapComposioError,
15 } from 'src/services/composio-error-overrides';
16 import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
17 +import type { CliDebugFlags } from 'src/services/runtime-flags';
18 import { ToolFileUploadError, uploadToolInputFiles } from 'src/services/tool-file-uploads';
19 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
20 import { ToolkitSlugCatalog } from 'src/services/toolkit-slug-catalog';
@@ -67,6 +68,8 @@ export interface ToolsExecutor {
68 | ComposioToolkitsRepository
69 | ComposioCliUserConfig
70 | TerminalUI
71 + // Tool-schema resolution emits `--tool-debug` diagnostics, whose flag values the caller owns.
72 + | CliDebugFlags
73 >;
74 }
75
ts/packages/cli/src/ui/colors.ts
+6 -2
@@ -1,4 +1,9 @@
1 import color from 'picocolors';
2 +import { Effect } from 'effect';
3 +import { UNPREFIXED_CONFIG } from 'src/effects/app-config';
4 +import { loadHostConfig } from 'src/services/config';
5 +
6 +const colorsEnabled = !Effect.runSync(loadHostConfig(UNPREFIXED_CONFIG.NO_COLOR));
7
8 export const {
9 bold,
@@ -14,5 +19,4 @@ export const {
19 white,
20 blue,
21 cyanBright,
17 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- palette is created eagerly at import time, before any Effect runtime; honors the NO_COLOR convention
18 -} = color.createColors(!Boolean(process.env.NO_COLOR));
22 +} = color.createColors(colorsEnabled);
ts/packages/cli/src/ui/redact.ts
+9 -3
@@ -1,4 +1,11 @@
1 -import process from 'node:process';
1 +import { Effect } from 'effect';
2 +import { UNPREFIXED_CONFIG } from 'src/effects/app-config';
3 +import { loadHostConfig } from 'src/services/config';
4 +
5 +// Read once at import time, like `ui/colors.ts`: `redact` runs per formatted
6 +// value, and spinning up a fiber per call to read a single environment
7 +// variable is pure overhead.
8 +const ciRedactionEnabled = Effect.runSync(loadHostConfig(UNPREFIXED_CONFIG.CI_REDACTION_ENABLED));
9
10 /**
11 * Redact a value when running in CI (e.g., CLI recordings).
@@ -12,7 +19,6 @@ export function redact<const Prefix extends string = string>({
19 value: string;
20 prefix?: Prefix;
21 }): `${Prefix}${string}` {
15 - // eslint-disable-next-line eslint-js/no-restricted-syntax -- plain sync string helper called from formatting code; CI flag toggles redaction in recorded CLI output
16 - if (process.env.CI !== 'true') return value as `${Prefix}${string}`;
22 + if (!ciRedactionEnabled) return value as `${Prefix}${string}`;
23 return `${prefix ?? ''}<REDACTED>` as `${Prefix}${string}`;
24 }
ts/packages/cli/test/__utils__/cli.ts
+4 -3
@@ -1,6 +1,7 @@
1 import { Effect } from 'effect';
2 import * as Cli from 'src/commands';
3
4 -// Run CLI in test environment
5 -export const cli = (args: ReadonlyArray<string>) =>
6 - Effect.flatMap(Cli.runWithConfig, run => run(['node', '<CMD>', ...args]));
4 +// Run CLI in test environment. `bootstrap` stands in for the values `cli-main.ts` resolves before
5 +// routing the root command (currently the `composio run` id).
6 +export const cli = (args: ReadonlyArray<string>, bootstrap?: Cli.RootCommandBootstrap) =>
7 + Effect.flatMap(Cli.runWithConfig, run => run(['node', '<CMD>', ...args], bootstrap));
ts/packages/cli/test/__utils__/services/test-layer.ts
+13 -9
@@ -23,6 +23,7 @@ import * as MockTerminal from './mock-terminal';
23 import { TerminalUITest } from './terminal-ui-test';
24 import type { Toolkits, ToolkitDetailed } from 'src/models/toolkits';
25 import { NodeProcess } from 'src/services/node-process';
26 +import { cliDebugFlagsLayer } from 'src/services/runtime-flags';
27 import {
28 ComposioClientSingleton,
29 ComposioSessionRepository,
@@ -99,15 +100,15 @@ export interface TestLiveInput {
100 execPath?: string;
101
102 /**
102 - * Mock toolkit-related data to use in test.
103 - */
104 -toolkitsData?: {
105 - toolkits?: Toolkits;
106 - detailedToolkits?: ToolkitDetailed[];
107 - tools?: Tools;
108 - triggerTypesAsEnums?: TriggerTypesAsEnums;
109 - triggerTypes?: TriggerTypes;
110 -};
103 + * Mock toolkit-related data to use in test.
104 + */
105 + toolkitsData?: {
106 + toolkits?: Toolkits;
107 + detailedToolkits?: ToolkitDetailed[];
108 + tools?: Tools;
109 + triggerTypesAsEnums?: TriggerTypesAsEnums;
110 + triggerTypes?: TriggerTypes;
111 + };
112
113 /**
114 * Mock auth-config data to use in test.
@@ -1315,6 +1316,9 @@ export const TestLayer = (input?: TestLiveInput) =>
1316 ConsumerProjectResolveFetchMock,
1317 StdinTest,
1318 TerminalUILayer,
1319 + // `src/commands/index.ts` provides these for real invocations; direct-effect tests that
1320 + // never route through the root command still need the "no CLI flag override" default.
1321 + cliDebugFlagsLayer(),
1322 Layer.provide(
1323 ProjectContext.Default,
1324 Layer.mergeAll(BunFileSystem.layer, NodeOsTest, NodeProcessTest)
ts/packages/cli/test/src/analytics.dispatch.test.ts
+53
@@ -17,6 +17,7 @@ import {
17 trackCliEventEffect,
18 } from 'src/analytics/dispatch';
19 import { CLI_ANALYTICS_EVENTS } from 'src/analytics/events';
20 +import { cliRunIdLayer } from 'src/services/runtime-cli-context';
21 import { APP_VERSION, USER_CONFIG_FILE_NAME } from 'src/constants';
22 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
23 import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
@@ -305,6 +306,30 @@ describe('CLI analytics dispatch', () => {
306 }).pipe(Effect.provide(makePlatformLayer(home)));
307 });
308
309 + it.effect('propagates telemetry debug to the detached worker without an env write', () => {
310 + const home = tempy.temporaryDirectory();
311 + const scriptPath = `${home}/composio.ts`;
312 + enableTelemetry();
313 + vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DEBUG', 'true');
314 + process.argv[1] = scriptPath;
315 +
316 + return Effect.gen(function* () {
317 + const fs = yield* FileSystem.FileSystem;
318 + yield* fs.writeFileString(scriptPath, '');
319 + yield* trackCliEventEffect({ name: 'producer_event' });
320 +
321 + const [, args, options] = childProcessMocks.spawn.mock.calls[0] as unknown as [
322 + string,
323 + string[],
324 + { detached: boolean; stdio: unknown },
325 + ];
326 + expect(args).toHaveLength(4);
327 + expect(args.at(-1)).toBe('--telemetry-debug');
328 + expect(options.stdio).toEqual(['ignore', 'ignore', 'inherit']);
329 + expect(options).not.toHaveProperty('env');
330 + }).pipe(Effect.provide(makePlatformLayer(home)));
331 + });
332 +
333 it.effect('spawns a detached codact worker with a decodable failure body', () => {
334 const home = tempy.temporaryDirectory();
335 const scriptPath = `${home}/composio.ts`;
@@ -360,6 +385,34 @@ describe('CLI analytics dispatch', () => {
385 }).pipe(Effect.provide(makePlatformLayer(home)));
386 });
387
388 + it.effect(
389 + 'stamps codact failures with the minted CliRunId when no parent run id is inherited',
390 + () => {
391 + const home = tempy.temporaryDirectory();
392 + const scriptPath = `${home}/composio.ts`;
393 + enableTelemetry();
394 + process.argv[1] = scriptPath;
395 +
396 + return Effect.gen(function* () {
397 + const fs = yield* FileSystem.FileSystem;
398 + yield* fs.writeFileString(scriptPath, '');
399 + yield* trackCliCodactFailureEffect({
400 + failureType: 'wrong_tool_slug',
401 + ctx: { slug: 'MISSING_TOOL' },
402 + });
403 +
404 + expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
405 + const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];
406 + expect(decodeWorkerPayload(args[2]!)).toMatchObject({
407 + failure_type: 'wrong_tool_slug',
408 + session: {
409 + parent_run_id: 'run_minted',
410 + },
411 + });
412 + }).pipe(Effect.provide(cliRunIdLayer('run_minted')), Effect.provide(makePlatformLayer(home)));
413 + }
414 + );
415 +
416 it.effect('keeps both producer effects non-fatal when spawn throws', () => {
417 const home = tempy.temporaryDirectory();
418 enableTelemetry();
ts/packages/cli/test/src/analytics.events.test.ts
+65 -17
@@ -29,15 +29,26 @@ import {
29 import { APP_VERSION } from 'src/constants';
30 import { inferSkillReleaseChannel } from 'src/effects/install-skill';
31 import { CLI_RELEASE_CHANNELS } from 'src/experimental-features';
32 +import {
33 + DEFAULT_CLI_INVOCATION_ORIGIN,
34 + type CliInvocationContext,
35 +} from 'src/services/runtime-cli-context';
36 import { ToolInputValidationError } from 'src/services/tool-input-validation';
37 import { resolveInstalledCliVersion } from 'src/services/run-companion-modules';
38
39 +const CLI_INVOCATION = {
40 + invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,
41 + parentRunId: undefined,
42 +} as const;
43 +
44 describe('CLI analytics execute failure events', () => {
45 it('records terminal capabilities supplied by the terminal service', () => {
37 - const context = createCliCommandTelemetryContext(['bun', 'composio'], '0.3.0', {
38 - stdoutIsTTY: true,
39 - stderrIsTTY: false,
40 - });
46 + const context = createCliCommandTelemetryContext(
47 + ['bun', 'composio'],
48 + '0.3.0',
49 + { stdoutIsTTY: true, stderrIsTTY: false },
50 + CLI_INVOCATION
51 + );
52
53 const event = getPrimaryLifecycleInvokedEvent(context);
54
@@ -58,6 +69,7 @@ describe('CLI analytics execute failure events', () => {
69 toolSlug: 'GMAIL_SEND_EMAIL',
70 args: { recipient: 'a@example.com' },
71 error,
72 + invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,
73 surface: 'root',
74 projectMode: 'consumer',
75 stage: 'validation',
@@ -73,6 +85,7 @@ describe('CLI analytics execute failure events', () => {
85 const event = getToolExecuteToolNotFoundEvent({
86 toolSlug: 'FAKE_TOOL',
87 args: {},
88 + invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,
89 surface: 'root',
90 projectMode: 'consumer',
91 stage: 'execution',
@@ -91,6 +104,7 @@ describe('CLI analytics execute failure events', () => {
104 const event = getToolExecuteFailedEvent({
105 toolSlug: 'GMAIL_SEND_EMAIL',
106 args: { to: 'a@example.com' },
107 + invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,
108 surface: 'root',
109 projectMode: 'consumer',
110 stage: 'execution',
@@ -172,7 +186,8 @@ describe('CLI analytics setup and install lifecycle events', () => {
186 const context = createCliCommandTelemetryContext(
187 ['bun', 'composio', 'setup', '--target', 'codex', '--uninstall', '--yes'],
188 APP_VERSION,
175 - { stdoutIsTTY: false, stderrIsTTY: false }
189 + { stdoutIsTTY: false, stderrIsTTY: false },
190 + CLI_INVOCATION
191 );
192
193 const invoked = getPrimaryLifecycleInvokedEvent(context);
@@ -196,7 +211,8 @@ describe('CLI analytics setup and install lifecycle events', () => {
211 const context = createCliCommandTelemetryContext(
212 ['bun', 'composio', 'install', '--completions'],
213 APP_VERSION,
199 - { stdoutIsTTY: false, stderrIsTTY: false }
214 + { stdoutIsTTY: false, stderrIsTTY: false },
215 + CLI_INVOCATION
216 );
217
218 expect(getPrimaryLifecycleInvokedEvent(context)).toMatchObject({
@@ -215,14 +231,16 @@ describe('CLI analytics setup and install lifecycle events', () => {
231 createCliCommandTelemetryContext(
232 ['bun', 'composio', 'search', 'customer@example.com secret'],
233 APP_VERSION,
218 - terminal
234 + terminal,
235 + CLI_INVOCATION
236 )
237 );
238 const proxy = getPrimaryLifecycleInvokedEvent(
239 createCliCommandTelemetryContext(
240 ['bun', 'composio', 'proxy', 'https://user:password@example.com/private?token=small'],
241 APP_VERSION,
225 - terminal
242 + terminal,
243 + CLI_INVOCATION
244 )
245 );
246
@@ -242,6 +260,7 @@ describe('CLI analytics setup and install lifecycle events', () => {
260 operation: 'setup',
261 target: 'claude',
262 action: 'installed',
263 + invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,
264 cliVersion: APP_VERSION,
265 })
266 ).toMatchObject({
@@ -266,6 +285,7 @@ describe('CLI analytics setup runtime-context events', () => {
285 available: true,
286 supported: true,
287 hostVersion: '2.1.0',
288 + invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,
289 cliVersion: APP_VERSION,
290 })
291 ).toMatchObject({
@@ -294,6 +314,7 @@ describe('CLI analytics setup runtime-context events', () => {
314 supported: false,
315 hostVersion: 'codex-cli 0.137.0',
316 unsupportedReasonCode: 'codex_too_old',
317 + invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,
318 cliVersion: APP_VERSION,
319 })
320 ).toMatchObject({
@@ -315,6 +336,7 @@ describe('CLI analytics setup runtime-context events', () => {
336 target: 'claude',
337 phase: 'install',
338 error,
339 + invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,
340 cliVersion: APP_VERSION,
341 });
342
@@ -336,6 +358,7 @@ describe('CLI analytics setup runtime-context events', () => {
358 getSetupCancelledEvent({
359 operation: 'setup',
360 requestedTarget: 'claude',
361 + invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,
362 cliVersion: APP_VERSION,
363 })
364 ).toMatchObject({
@@ -352,6 +375,7 @@ describe('CLI analytics setup runtime-context events', () => {
375 getSetupSkippedEvent({
376 operation: 'uninstall',
377 requestedTarget: 'auto',
378 + invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,
379 cliVersion: APP_VERSION,
380 })
381 ).toMatchObject({
@@ -372,11 +396,16 @@ describe('CLI analytics journey taxonomy', () => {
396 vi.unstubAllEnvs();
397 });
398
375 - const contextFor = (argv: ReadonlyArray<string>) =>
376 - createCliCommandTelemetryContext(['bun', 'composio', ...argv], APP_VERSION, {
377 - stdoutIsTTY: false,
378 - stderrIsTTY: false,
379 - });
399 + const contextFor = (
400 + argv: ReadonlyArray<string>,
401 + invocation: CliInvocationContext = CLI_INVOCATION
402 + ) =>
403 + createCliCommandTelemetryContext(
404 + ['bun', 'composio', ...argv],
405 + APP_VERSION,
406 + { stdoutIsTTY: false, stderrIsTTY: false },
407 + invocation
408 + );
409
410 const lifecycleCases: ReadonlyArray<[ReadonlyArray<string>, string]> = [
411 [['execute', 'GMAIL_SEND_EMAIL'], 'execute'],
@@ -413,6 +442,7 @@ describe('CLI analytics journey taxonomy', () => {
442 operation: 'setup',
443 target: 'claude',
444 action: 'installed',
445 + invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,
446 cliVersion: APP_VERSION,
447 })?.properties?.journey_stage
448 ).toBe('setup');
@@ -421,6 +451,7 @@ describe('CLI analytics journey taxonomy', () => {
451 getSetupSkippedEvent({
452 operation: 'setup',
453 requestedTarget: 'auto',
454 + invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,
455 cliVersion: APP_VERSION,
456 })?.properties?.journey_stage
457 ).toBe('setup');
@@ -429,6 +460,7 @@ describe('CLI analytics journey taxonomy', () => {
460 getToolExecuteFailedEvent({
461 toolSlug: 'GMAIL_SEND_EMAIL',
462 args: {},
463 + invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,
464 surface: 'root',
465 projectMode: 'consumer',
466 stage: 'execution',
@@ -457,13 +489,15 @@ describe('CLI analytics journey taxonomy', () => {
489 const context = createCliCommandTelemetryContext(
490 ['bun', 'composio', 'login'],
491 resolvedVersion,
460 - { stdoutIsTTY: false, stderrIsTTY: false }
492 + { stdoutIsTTY: false, stderrIsTTY: false },
493 + CLI_INVOCATION
494 );
495 const properties = getPrimaryLifecycleInvokedEvent(context)?.properties;
496 const pluginProperties = getPluginLifecycleSucceededEvent({
497 operation: 'setup',
498 target: 'codex',
499 action: 'installed',
500 + invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,
501 cliVersion: APP_VERSION,
502 })?.properties;
503 expect(inferSkillReleaseChannel(APP_VERSION)).toBe('stable');
@@ -472,15 +506,29 @@ describe('CLI analytics journey taxonomy', () => {
506 }).pipe(Effect.provide(Layer.merge(BunFileSystem.layer, BunPath.layer)));
507 });
508
475 - it('propagates the installer invocation origin from the environment', () => {
476 - vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'installer');
509 + it('propagates the configured installer invocation origin', () => {
510 + const installerInvocation = { invocationOrigin: 'installer', parentRunId: undefined };
511
478 - expect(getPrimaryLifecycleInvokedEvent(contextFor(['install']))?.properties).toMatchObject({
512 + expect(
513 + getPrimaryLifecycleInvokedEvent(contextFor(['install'], installerInvocation))?.properties
514 + ).toMatchObject({
515 invocation_origin: 'installer',
516 journey_stage: 'install',
517 });
518 });
519
520 + it('uses the configured parent run id for nested run telemetry', () => {
521 + const context = contextFor(['run', 'console.log("hi")'], {
522 + invocationOrigin: 'run',
523 + parentRunId: 'run_parent',
524 + });
525 + expect(context.runId).toBe('run_parent');
526 + expect(getPrimaryLifecycleInvokedEvent(context)?.properties).toMatchObject({
527 + invocation_origin: 'run',
528 + run_id: 'run_parent',
529 + });
530 + });
531 +
532 it('keeps the base installer install-only and marks shell-setup delegation as installer-origin', () => {
533 const installScript = readFileSync(
534 new URL('../../../../../install.sh', import.meta.url),
ts/packages/cli/test/src/cli-main.test.ts
+55
@@ -51,4 +51,59 @@ describe('CLI process error handling', () => {
51 '--file is not supported for local tools yet.'
52 );
53 });
54 +
55 + it('reports a bare `composio run` as a usage error without a defect dump', () => {
56 + const configDirectory = tempy.temporaryDirectory();
57 +
58 + const result = spawnSync('bun', ['run', 'src/bin.ts', 'run'], {
59 + cwd: process.cwd(),
60 + encoding: 'utf8',
61 + env: {
62 + ...process.env,
63 + CI: '1',
64 + NO_COLOR: '1',
65 + COMPOSIO_CACHE_DIR: configDirectory,
66 + },
67 + });
68 +
69 + const output = `${result.stdout}\n${result.stderr}`;
70 + expect(result.status).toBe(1);
71 + expect(output).toContain('Provide inline code or use --file to run a script file.');
72 + // No defect banner, no source-mapped stack, and no run artifacts for a script that never ran.
73 + expect(output).not.toContain('MissingRunSourceError');
74 + expect(output).not.toContain('Sources');
75 + expect(output).not.toContain('RUN_LOG_FILE=');
76 + });
77 +
78 + it('normalizes telemetry debug before dispatching a background worker', () => {
79 + const configDirectory = tempy.temporaryDirectory();
80 + const encodedPayload = Buffer.from(
81 + JSON.stringify({
82 + event: 'worker_bootstrap_test',
83 + sentAt: '2026-08-14T00:00:00.000Z',
84 + source: 'cli',
85 + distinctId: 'install_test',
86 + installId: 'install_test',
87 + })
88 + ).toString('base64url');
89 +
90 + const result = spawnSync(
91 + 'bun',
92 + ['run', 'src/bin.ts', '__analytics-worker', encodedPayload, '--telemetry-debug'],
93 + {
94 + cwd: process.cwd(),
95 + encoding: 'utf8',
96 + env: {
97 + ...process.env,
98 + CI: 'true',
99 + NO_COLOR: '1',
100 + COMPOSIO_CACHE_DIR: configDirectory,
101 + },
102 + }
103 + );
104 +
105 + expect(result.status).toBe(0);
106 + expect(`${result.stdout}\n${result.stderr}`).toContain('[telemetry-debug]');
107 + expect(`${result.stdout}\n${result.stderr}`).toContain('posthog_delivery_skipped');
108 + });
109 });
ts/packages/cli/test/src/commands/install.cmd.test.ts
+9 -3
@@ -2,7 +2,7 @@ import path from 'node:path';
2 import { Writable } from 'node:stream';
3 import { beforeEach, vi } from 'vitest';
4 import { describe, expect, layer } from '@effect/vitest';
5 -import { Effect, Exit } from 'effect';
5 +import { ConfigProvider, Effect, Exit } from 'effect';
6 import { FileSystem } from '@effect/platform';
7 import { NodeOs } from 'src/services/node-os';
8 import {
@@ -11,6 +11,7 @@ import {
11 type Shell,
12 } from 'src/commands/install.cmd';
13 import { makeTerminalUI } from 'src/services/terminal-ui';
14 +import { extendConfigProvider } from 'src/services/config';
15 import { cli, TestLive, MockConsole } from 'test/__utils__';
16
17 const makeSink = (isTTY: boolean) => {
@@ -40,7 +41,11 @@ const SAFE_PATH = '/usr/bin:/bin';
41 const TEST_EXEC_PATH = '/usr/local/bin/composio';
42 const expectedRuntimeBinDir = (): string => path.dirname(TEST_EXEC_PATH);
43 const InstallTestLive = (input: Parameters<typeof TestLive>[0] = {}) =>
43 - TestLive({ execPath: TEST_EXEC_PATH, ...input });
44 + TestLive({
45 + baseConfigProvider: ConfigProvider.fromEnv().pipe(extendConfigProvider),
46 + execPath: TEST_EXEC_PATH,
47 + ...input,
48 + });
49 const install = (
50 params: {
51 readonly completions?: boolean;
@@ -76,6 +81,7 @@ describe('CLI: composio install', () => {
81 // below is automatically reverted after each test — no manual save/restore.
82 vi.stubEnv('PATH', SAFE_PATH);
83 vi.stubEnv('COMPOSIO_BIN_DIR', '');
84 + vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', undefined);
85 capturedStdout.chunks.length = 0;
86 capturedStderr.chunks.length = 0;
87 });
@@ -1335,7 +1341,7 @@ describe('CLI: composio install', () => {
1341 });
1342
1343 describe('[When] COMPOSIO_BIN_DIR is set and ~/.local/bin/composio is also the running executable', () => {
1338 - layer(TestLive({ execPath: '.local/bin/composio' }))(it => {
1344 + layer(InstallTestLive({ execPath: '.local/bin/composio' }))(it => {
1345 it.scoped('[Then] the env var wins over the ~/.local/bin fallback', () =>
1346 Effect.gen(function* () {
1347 const os = yield* NodeOs;
ts/packages/cli/test/src/commands/run.cmd.test.ts
+360 -84
@@ -3,19 +3,33 @@ import * as os from 'node:os';
3 import * as path from 'node:path';
4 import { pathToFileURL } from 'node:url';
5 import { describe, expect, layer } from '@effect/vitest';
6 -import { Path } from '@effect/platform';
6 +import { Command as PlatformCommand, CommandExecutor, Path } from '@effect/platform';
7 import { BunContext } from '@effect/platform-bun';
8 -import { Effect, Exit } from 'effect';
8 +import {
9 + Cause,
10 + ConfigProvider,
11 + Effect,
12 + Exit,
13 + HashMap,
14 + Inspectable,
15 + Layer,
16 + Option,
17 + Sink,
18 + Stream,
19 +} from 'effect';
20 import { afterEach, it, vi } from 'vitest';
21 +import { createCliCommandTelemetryContext } from 'src/analytics/events';
22 import {
23 buildRunHelpersSource,
24 extractInlineExecuteToolSlugs,
25 inferCliInvocationPrefix,
26 + MissingRunSourceError,
27 wrapInlineCodeForRun,
28 } from 'src/commands/run.cmd';
29 import {
30 RUN_COMPANION_MODULE_FILENAMES,
18 - RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS,
31 + hasInstalledRunCompanionModules,
32 + hostRunCompanionStaticAssetRelativePaths,
33 listMissingInstalledRunCompanionModules,
34 readInstalledReleaseTag,
35 resolveRunCompanionModulePath,
@@ -29,32 +43,171 @@ import {
43 buildStructuredToolPrompt,
44 finalizeInvokeAgentText,
45 } from 'src/services/run-subagent-shared';
46 +import { extendConfigProvider } from 'src/services/config';
47 +import { telemetryDebugModeLayer } from 'src/services/runtime-flags';
48 +import { DEFAULT_CLI_INVOCATION_ORIGIN } from 'src/services/runtime-cli-context';
49 import { cli, MockConsole, TestLive } from 'test/__utils__';
50 +import { CommandRunner } from 'src/services/command-runner';
51 +
52 +const acpOnlyConfigProvider = ConfigProvider.fromMap(
53 + new Map([['COMPOSIO_RUN_ACP_ONLY', '1']])
54 +).pipe(extendConfigProvider);
55 +
56 +const enabledRuntimeFlagsConfigProvider = ConfigProvider.fromMap(
57 + new Map([
58 + ['COMPOSIO_RUN_ACP_ONLY', '1'],
59 + ['COMPOSIO_PERF_DEBUG', '1'],
60 + ['COMPOSIO_TOOL_DEBUG', '1'],
61 + ])
62 +).pipe(extendConfigProvider);
63 +
64 +const readRunPreloadSource = (command: ReadonlyArray<string>): string => {
65 + const preloadPath = command[2];
66 + if (preloadPath === undefined) {
67 + throw new Error('Expected the run command to include a preload file.');
68 + }
69 + return fs.readFileSync(preloadPath, 'utf8');
70 +};
71 +
72 +const commandRuns = vi.fn((_: PlatformCommand.Command) =>
73 + Effect.succeed(CommandExecutor.ExitCode(0))
74 +);
75 +
76 +// `composio run` starts the child through the platform `CommandExecutor` so it owns the pid it
77 +// forwards signals to, so the stub has to replace the executor rather than `CommandRunner`.
78 +// `exitCode` stays suspended: the command only awaits it after the signal handlers are
79 +// registered, which is what makes the forwarding observable below.
80 +const STUB_CHILD_PID = 987_654;
81 +
82 +const stubProcess = (command: PlatformCommand.Command): CommandExecutor.Process => ({
83 + [CommandExecutor.ProcessTypeId]: CommandExecutor.ProcessTypeId,
84 + pid: CommandExecutor.ProcessId(STUB_CHILD_PID),
85 + exitCode: Effect.suspend(() => commandRuns(command)),
86 + isRunning: Effect.succeed(false),
87 + kill: () => Effect.void,
88 + stdin: Sink.drain,
89 + stdout: Stream.empty,
90 + stderr: Stream.empty,
91 + toJSON: () => ({ _id: 'StubProcess' }),
92 + toString: () => 'StubProcess',
93 + [Inspectable.NodeInspectSymbol]: () => ({ _id: 'StubProcess' }),
94 +});
95 +
96 +const StubCommandExecutor = Layer.succeed(
97 + CommandExecutor.CommandExecutor,
98 + CommandExecutor.makeExecutor(command => Effect.succeed(stubProcess(command)))
99 +);
100 +
101 +const RunTestLive = (input: Parameters<typeof TestLive>[0] = {}) =>
102 + Layer.merge(
103 + TestLive({
104 + ...input,
105 + commandRunner: new CommandRunner({
106 + run: command => commandRuns(command),
107 + capture: () => Effect.succeed({ exitCode: 0, stdout: '', stderr: '' }),
108 + }),
109 + }),
110 + StubCommandExecutor
111 + );
112 +
113 +const inspectRunCommand = (command: PlatformCommand.Command) => {
114 + const [standard] = PlatformCommand.flatten(command);
115 + return {
116 + cmd: [standard.command, ...standard.args],
117 + env: Object.fromEntries(HashMap.entries(standard.env)),
118 + extendEnv: standard.extendEnv,
119 + stdio: [standard.stdin, standard.stdout, standard.stderr],
120 + };
121 +};
122
123 describe('CLI: composio run', () => {
124 afterEach(() => {
125 + process.exitCode = undefined;
126 + commandRuns.mockReset().mockImplementation(() => Effect.succeed(CommandExecutor.ExitCode(0)));
127 vi.unstubAllGlobals();
128 vi.restoreAllMocks();
129 });
130
40 - layer(TestLive())(it => {
131 + layer(RunTestLive())(it => {
132 + it.scoped('[Given] a root run telemetry id [Then] the child receives the same run id', () =>
133 + Effect.gen(function* () {
134 + const telemetryContext = createCliCommandTelemetryContext(
135 + ['bun', 'composio', 'run', 'console.log("hi")'],
136 + '0.0.0-test',
137 + { stdoutIsTTY: false, stderrIsTTY: false },
138 + { invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN, parentRunId: undefined }
139 + );
140 + const runId = telemetryContext.runId;
141 + expect(runId).toBeDefined();
142 + if (runId === undefined) return;
143 +
144 + commandRuns.mockImplementation(command => {
145 + expect(inspectRunCommand(command).env.COMPOSIO_CLI_PARENT_RUN_ID).toBe(runId);
146 + return Effect.succeed(CommandExecutor.ExitCode(0));
147 + });
148 +
149 + // The bootstrap hands the run id it minted for telemetry to the command, the way
150 + // `cli-main.ts` does, instead of publishing it through process-wide state.
151 + yield* cli(['run', 'console.log("hi")'], { runId });
152 +
153 + expect(commandRuns).toHaveBeenCalledTimes(1);
154 + })
155 + );
156 + });
157 +
158 + layer(RunTestLive())(it => {
159 + it.scoped(
160 + '[Given] a terminal interrupt [Then] it forwards the signal to the child process group and unregisters its handlers',
161 + () =>
162 + Effect.gen(function* () {
163 + const signalled: Array<readonly [number, string]> = [];
164 + vi.spyOn(process, 'kill').mockImplementation((pid, signal) => {
165 + signalled.push([Number(pid), String(signal)]);
166 + return true;
167 + });
168 +
169 + const sigintBaseline = process.listenerCount('SIGINT');
170 + const sigtermBaseline = process.listenerCount('SIGTERM');
171 + const registeredWhileRunning: Array<{ sigint: number; sigterm: number }> = [];
172 +
173 + commandRuns.mockImplementation(() =>
174 + Effect.sync(() => {
175 + registeredWhileRunning.push({
176 + sigint: process.listenerCount('SIGINT') - sigintBaseline,
177 + sigterm: process.listenerCount('SIGTERM') - sigtermBaseline,
178 + });
179 + // Stand in for the terminal delivering Ctrl-C to the CLI only: the child is
180 + // detached into its own process group and never sees it directly.
181 + for (const listener of process.listeners('SIGINT').slice(sigintBaseline)) {
182 + listener('SIGINT');
183 + }
184 + return CommandExecutor.ExitCode(0);
185 + })
186 + );
187 +
188 + yield* cli(['run', 'console.log("hi")']);
189 +
190 + expect(registeredWhileRunning[0]).toEqual({ sigint: 1, sigterm: 1 });
191 + // Negative pid: the detached child leads its own process group.
192 + expect(signalled).toEqual([[-STUB_CHILD_PID, 'SIGINT']]);
193 + expect(process.listenerCount('SIGINT')).toBe(sigintBaseline);
194 + expect(process.listenerCount('SIGTERM')).toBe(sigtermBaseline);
195 + })
196 + );
197 + });
198 +
199 + layer(RunTestLive())(it => {
200 it.scoped(
201 '[Given] inline code and args [Then] it forwards them to the embedded Bun runtime',
202 () =>
203 Effect.gen(function* () {
45 - const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(7) }));
46 - const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
47 - vi.stubGlobal('Bun', { spawn });
204 + commandRuns.mockImplementation(() => Effect.succeed(CommandExecutor.ExitCode(7)));
205
206 yield* cli(['run', 'console.log("hi")', '--flag', 'value']);
207 const output = yield* MockConsole.getLines();
208
52 - expect(spawn).toHaveBeenCalledTimes(1);
53 - const spawnConfig = spawn.mock.calls[0][0] as {
54 - cmd: string[];
55 - env: unknown;
56 - stdio: string[];
57 - };
209 + expect(commandRuns).toHaveBeenCalledTimes(1);
210 + const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
211 expect(spawnConfig.cmd[0]).toBe(process.execPath);
212 expect(spawnConfig.cmd[1]).toBe('--preload');
213 expect(spawnConfig.cmd[2]).toMatch(/globals\.mjs$/);
@@ -63,62 +216,161 @@ describe('CLI: composio run', () => {
216 expect(spawnConfig.cmd[4]).toContain('return (console.log("hi"));');
217 expect(spawnConfig.cmd[4]).toContain('if (__composioResult !== undefined) {');
218 expect(spawnConfig.cmd.slice(5)).toEqual(['--', '--flag', 'value']);
66 - expect(spawnConfig.env).toEqual(
67 - expect.objectContaining({
68 - ...process.env,
69 - BUN_BE_BUN: '1',
70 - })
71 - );
219 + expect(spawnConfig.env).toEqual(expect.objectContaining({ BUN_BE_BUN: '1' }));
220 + expect(spawnConfig.extendEnv).toBe(true);
221 expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);
222 expect(output).toContainEqual(expect.stringMatching(/^RUN_LOG_FILE=.*run\.log$/));
74 - expect(exit).toHaveBeenCalledWith(7);
223 + // The preload file lives in a scoped directory and is removed with it, ...
224 + expect(fs.existsSync(spawnConfig.cmd[2]!)).toBe(false);
225 + // ... but the run log is advertised to the caller on stderr, so it has to outlive
226 + // the run that printed it.
227 + const runLogPath = output
228 + .find(line => line.startsWith('RUN_LOG_FILE='))
229 + ?.slice('RUN_LOG_FILE='.length);
230 + expect(runLogPath).toBeDefined();
231 + expect(fs.existsSync(runLogPath!)).toBe(true);
232 + fs.rmSync(path.dirname(runLogPath!), { recursive: true, force: true });
233 + expect(process.exitCode).toBe(7);
234 + })
235 + );
236 + });
237 +
238 + layer(RunTestLive({ baseConfigProvider: acpOnlyConfigProvider }))(it => {
239 + it.scoped(
240 + '[Given] COMPOSIO_RUN_ACP_ONLY=1 [Then] run enables ACP-only execution without a flag',
241 + () =>
242 + Effect.gen(function* () {
243 + commandRuns.mockImplementation(command => {
244 + expect(readRunPreloadSource(inspectRunCommand(command).cmd)).toContain(
245 + '"acpOnly":true'
246 + );
247 + return Effect.succeed(CommandExecutor.ExitCode(0));
248 + });
249 +
250 + yield* cli(['run', 'console.log("hi")']);
251 +
252 + expect(commandRuns).toHaveBeenCalledTimes(1);
253 + })
254 + );
255 +
256 + it.scoped('[Given] --acp-only=false and configured ACP-only mode [Then] the flag wins', () =>
257 + Effect.gen(function* () {
258 + commandRuns.mockImplementation(command => {
259 + expect(readRunPreloadSource(inspectRunCommand(command).cmd)).toContain('"acpOnly":false');
260 + return Effect.succeed(CommandExecutor.ExitCode(0));
261 + });
262 +
263 + yield* cli(['run', '--acp-only=false', 'console.log("hi")']);
264 +
265 + expect(commandRuns).toHaveBeenCalledTimes(1);
266 + })
267 + );
268 + });
269 +
270 + layer(RunTestLive({ baseConfigProvider: enabledRuntimeFlagsConfigProvider }))(it => {
271 + it.scoped('[Given] explicit false flags [Then] inherited true values are cleared', () =>
272 + Effect.gen(function* () {
273 + let preloadSource = '';
274 + commandRuns.mockImplementation(command => {
275 + preloadSource = readRunPreloadSource(inspectRunCommand(command).cmd);
276 + return Effect.succeed(CommandExecutor.ExitCode(0));
277 + });
278 +
279 + yield* cli([
280 + 'run',
281 + '--perf-debug=false',
282 + '--tool-debug=false',
283 + '--acp-only=false',
284 + 'console.log("hi")',
285 + ]);
286 +
287 + const command = inspectRunCommand(commandRuns.mock.calls[0]![0]);
288 + expect(command.env).toMatchObject({
289 + COMPOSIO_PERF_DEBUG: '0',
290 + COMPOSIO_TOOL_DEBUG: '0',
291 + COMPOSIO_RUN_ACP_ONLY: '0',
292 + COMPOSIO_CLI_TELEMETRY_DEBUG: '0',
293 + });
294 + expect(preloadSource).toContain('"acpOnly":false');
295 + })
296 + );
297 + });
298 +
299 + layer(Layer.merge(RunTestLive(), telemetryDebugModeLayer(true)))(it => {
300 + it.scoped(
301 + '[Given] --telemetry-debug [Then] the spawned script and its children observe it',
302 + () =>
303 + Effect.gen(function* () {
304 + let preloadSource = '';
305 + commandRuns.mockImplementation(command => {
306 + preloadSource = readRunPreloadSource(inspectRunCommand(command).cmd);
307 + return Effect.succeed(CommandExecutor.ExitCode(0));
308 + });
309 +
310 + yield* cli(['run', 'console.log("hi")']);
311 +
312 + const command = inspectRunCommand(commandRuns.mock.calls[0]![0]);
313 + expect(command.env.COMPOSIO_CLI_TELEMETRY_DEBUG).toBe('1');
314 + expect(preloadSource).toContain('"telemetryDebug":true');
315 })
316 );
317 });
318
79 - layer(TestLive())(it => {
319 + layer(RunTestLive())(it => {
320 it.scoped(
321 '[Given] --acp-only [Then] run accepts the flag and forwards execution normally',
322 () =>
323 Effect.gen(function* () {
84 - const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));
85 - const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
86 - vi.stubGlobal('Bun', { spawn });
324 + commandRuns.mockImplementation(command => {
325 + expect(readRunPreloadSource(inspectRunCommand(command).cmd)).toContain(
326 + '"acpOnly":true'
327 + );
328 + return Effect.succeed(CommandExecutor.ExitCode(0));
329 + });
330
331 yield* cli(['run', '--acp-only', 'console.log("hi")']);
332
90 - expect(spawn).toHaveBeenCalledTimes(1);
91 - const spawnConfig = spawn.mock.calls[0][0] as {
92 - cmd: string[];
93 - };
333 + expect(commandRuns).toHaveBeenCalledTimes(1);
334 + const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
335 expect(spawnConfig.cmd[3]).toBe('--eval');
95 - expect(exit).toHaveBeenCalledWith(0);
336 + expect(process.exitCode).toBe(0);
337 })
338 );
339 +
340 + it.scoped('[Given] repeated invocations [Then] hidden flags do not leak', () =>
341 + Effect.gen(function* () {
342 + const preloadSources: string[] = [];
343 + commandRuns.mockImplementation(command => {
344 + preloadSources.push(readRunPreloadSource(inspectRunCommand(command).cmd));
345 + return Effect.succeed(CommandExecutor.ExitCode(0));
346 + });
347 +
348 + yield* cli(['run', '--acp-only', 'console.log("first")']);
349 + yield* cli(['run', 'console.log("second")']);
350 +
351 + expect(preloadSources).toHaveLength(2);
352 + expect(preloadSources[0]).toContain('"acpOnly":true');
353 + expect(preloadSources[1]).toContain('"acpOnly":false');
354 + })
355 + );
356 });
357
100 - layer(TestLive())(it => {
358 + layer(RunTestLive())(it => {
359 it.scoped(
360 '[Given] --logs-off [Then] run accepts the flag and forwards execution normally',
361 () =>
362 Effect.gen(function* () {
105 - const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));
106 - const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
107 - vi.stubGlobal('Bun', { spawn });
108 -
363 yield* cli(['run', '--logs-off', 'console.log("hi")']);
364
111 - expect(spawn).toHaveBeenCalledTimes(1);
112 - const spawnConfig = spawn.mock.calls[0][0] as {
113 - cmd: string[];
114 - };
365 + expect(commandRuns).toHaveBeenCalledTimes(1);
366 + const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
367 expect(spawnConfig.cmd[3]).toBe('--eval');
116 - expect(exit).toHaveBeenCalledWith(0);
368 + expect(process.exitCode).toBe(0);
369 })
370 );
371 });
372
121 - layer(TestLive())(it => {
373 + layer(RunTestLive())(it => {
374 it.scoped(
375 '[Given] a multiline structured experimental_subAgent script [Then] run preserves the inline TypeScript source',
376 () =>
@@ -140,16 +392,10 @@ describe('CLI: composio run', () => {
392 console.log(JSON.stringify(brief));
393 console.log(JSON.stringify(brief.structuredOutput));
394 `;
143 - const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));
144 - const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
145 - vi.stubGlobal('Bun', { spawn });
146 -
395 yield* cli(['run', '--logs-off', script]);
396
149 - expect(spawn).toHaveBeenCalledTimes(1);
150 - const spawnConfig = spawn.mock.calls[0][0] as {
151 - cmd: string[];
152 - };
397 + expect(commandRuns).toHaveBeenCalledTimes(1);
398 + const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
399 expect(spawnConfig.cmd[3]).toBe('--eval');
400 expect(spawnConfig.cmd[4]).toContain('const brief = await experimental_subAgent(');
401 expect(spawnConfig.cmd[4]).toContain('"Do not run terminal commands."');
@@ -160,44 +406,34 @@ describe('CLI: composio run', () => {
406 'return (console.log(JSON.stringify(brief.structuredOutput)));'
407 );
408 expect(spawnConfig.cmd[4]).not.toContain('"Do not run terminal\n');
163 - expect(exit).toHaveBeenCalledWith(0);
409 + expect(process.exitCode).toBe(0);
410 })
411 );
412 });
413
168 - layer(TestLive())(it => {
414 + layer(RunTestLive())(it => {
415 it.scoped('[Given] --file [Then] it forwards file execution to the embedded Bun runtime', () =>
416 Effect.gen(function* () {
417 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-test-'));
418 const scriptPath = path.join(tempDir, 'script.ts');
419 fs.writeFileSync(scriptPath, 'const value = 1 + 1;\nvalue * 2;\n', 'utf8');
174 - const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));
175 - const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
176 - vi.stubGlobal('Bun', { spawn });
177 -
420 try {
421 yield* cli(['run', '--file', scriptPath, '--', 'hello']);
422
181 - expect(spawn).toHaveBeenCalledTimes(1);
182 - const spawnConfig = spawn.mock.calls[0][0] as {
183 - cmd: string[];
184 - env: unknown;
185 - stdio: string[];
186 - };
423 + expect(commandRuns).toHaveBeenCalledTimes(1);
424 + const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);
425 expect(spawnConfig.cmd[0]).toBe(process.execPath);
426 expect(spawnConfig.cmd[1]).toBe('--preload');
427 expect(spawnConfig.cmd[2]).toMatch(/globals\.mjs$/);
428 expect(spawnConfig.cmd[3]).toMatch(/\.composio-run-.*\.ts$/);
429 expect(spawnConfig.cmd[4]).toBe('--');
430 expect(spawnConfig.cmd[5]).toBe('hello');
193 - expect(spawnConfig.env).toEqual(
194 - expect.objectContaining({
195 - ...process.env,
196 - BUN_BE_BUN: '1',
197 - })
198 - );
431 + expect(spawnConfig.env).toEqual(expect.objectContaining({ BUN_BE_BUN: '1' }));
432 + expect(spawnConfig.extendEnv).toBe(true);
433 expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);
200 - expect(exit).toHaveBeenCalledWith(0);
434 + expect(fs.existsSync(spawnConfig.cmd[2]!)).toBe(false);
435 + expect(fs.existsSync(spawnConfig.cmd[3]!)).toBe(false);
436 + expect(process.exitCode).toBe(0);
437 } finally {
438 fs.rmSync(tempDir, { recursive: true, force: true });
439 }
@@ -205,16 +441,28 @@ describe('CLI: composio run', () => {
441 );
442 });
443
208 - layer(TestLive())(it => {
209 - it.scoped('[Given] no inline code and no --file [Then] it fails with a clear error', () =>
210 - Effect.gen(function* () {
211 - const exit = yield* cli(['run']).pipe(Effect.exit);
212 - expect(Exit.isFailure(exit)).toBe(true);
213 - })
444 + layer(RunTestLive())(it => {
445 + it.scoped(
446 + '[Given] no inline code and no --file [Then] it fails with a typed usage error, not a defect',
447 + () =>
448 + Effect.gen(function* () {
449 + const exit = yield* cli(['run']).pipe(Effect.exit);
450 + expect(Exit.isFailure(exit)).toBe(true);
451 + if (!Exit.isFailure(exit)) return;
452 +
453 + const failure = Cause.failureOption(exit.cause);
454 + expect(Option.isSome(failure)).toBe(true);
455 + expect(failure.pipe(Option.getOrThrow)).toBeInstanceOf(MissingRunSourceError);
456 + expect(
457 + String((failure.pipe(Option.getOrThrow) as MissingRunSourceError).message)
458 + ).toContain('Provide inline code or use --file to run a script file.');
459 + // Nothing was set up before the check, so no child process was started.
460 + expect(commandRuns).not.toHaveBeenCalled();
461 + })
462 );
463 });
464
217 - layer(TestLive())(it => {
465 + layer(RunTestLive())(it => {
466 it.scoped(
467 '[Given] run help [Then] it documents injected execute, search, proxy, experimental_subAgent, and z helpers',
468 () =>
@@ -386,15 +634,15 @@ describe('run-subagent-shared', () => {
634 });
635
636 describe('inferCliInvocationPrefix', () => {
389 - layer(Path.layer)(it => {
637 + layer(BunContext.layer)(it => {
638 it.effect(
639 '[Given] a compiled bunfs entrypoint [Then] it falls back to the binary path only',
640 () =>
641 Effect.gen(function* () {
642 const pathService = yield* Path.Path;
395 - expect(inferCliInvocationPrefix(pathService, ['node', '/$bunfs/root/composio'])).toEqual([
396 - process.execPath,
397 - ]);
643 + expect(
644 + yield* inferCliInvocationPrefix(pathService, ['node', '/$bunfs/root/composio'])
645 + ).toEqual([process.execPath]);
646 })
647 );
648 });
@@ -469,16 +717,44 @@ describe('run companion install metadata', () => {
717 fs.writeFileSync(path.join(tempDir, RUN_COMPANION_MODULE_FILENAMES[0]!), '', 'utf8');
718
719 expect(yield* listMissingInstalledRunCompanionModules(execPath)).toEqual(
472 - [
473 - ...RUN_COMPANION_MODULE_FILENAMES.slice(1),
474 - ...RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS,
475 - ]
476 - .slice()
477 - .sort()
720 + RUN_COMPANION_MODULE_FILENAMES.slice(1).slice().sort()
721 );
722 })
723 );
724
725 + it.effect(
726 + '[Given] an install without ACP adapters [Then] the startup tier reports nothing missing',
727 + () =>
728 + Effect.gen(function* () {
729 + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-no-acp-'));
730 + const execPath = path.join(tempDir, 'composio');
731 + for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
732 + fs.writeFileSync(path.join(tempDir, fileName), '', 'utf8');
733 + }
734 +
735 + // The ACP adapters are the lazy tier: a plain `composio run` must not
736 + // treat an install without them as broken.
737 + const hostStaticAssets = yield* hostRunCompanionStaticAssetRelativePaths;
738 + expect(hostStaticAssets.length).toBeGreaterThan(0);
739 + for (const relativePath of hostStaticAssets) {
740 + expect(fs.existsSync(path.join(tempDir, relativePath))).toBe(false);
741 + }
742 +
743 + expect(yield* listMissingInstalledRunCompanionModules(execPath)).toEqual([]);
744 + expect(yield* hasInstalledRunCompanionModules(execPath)).toBe(true);
745 + })
746 + );
747 +
748 + it.effect(
749 + '[Given] a source checkout [Then] the executable has no companion modules next to it',
750 + () =>
751 + Effect.gen(function* () {
752 + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-no-install-'));
753 +
754 + expect(yield* hasInstalledRunCompanionModules(path.join(tempDir, 'bun'))).toBe(false);
755 + })
756 + );
757 +
758 it.effect(
759 '[Given] a nested companion dependency is missing [Then] it reports the missing helper asset',
760 () =>
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+32 -10
@@ -22,10 +22,40 @@ import { ComposioCliUserConfig } from 'src/services/cli-user-config';
22 import type { ToolkitDetailed } from 'src/models/toolkits';
23 import { makeToolkitFixture } from 'test/__utils__/models/toolkits';
24
25 +// Disable CI redaction so tests see raw values. `src/ui/redact` reads `CI` once
26 +// at import time, so the variable has to be gone before the imports above run —
27 +// `vi.hoisted` executes ahead of them. The explicit CI-redaction test overrides
28 +// via `vi.spyOn` and is unaffected.
29 +vi.hoisted(() => {
30 + delete process.env.CI;
31 +});
32 +
33 const testConfigProvider = ConfigProvider.fromMap(
34 new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
35 ).pipe(extendConfigProvider);
36
37 +const runInvocationConfigProvider = ConfigProvider.fromMap(
38 + new Map([
39 + ['COMPOSIO_USER_API_KEY', 'test_api_key'],
40 + ['COMPOSIO_CLI_INVOCATION_ORIGIN', 'run'],
41 + ])
42 +).pipe(extendConfigProvider);
43 +
44 +// Reuse the suite-managed cache directory for artifacts without exposing the
45 +// empty test cache as the CLI's authenticated config directory.
46 +const testArtifactConfigProvider = ConfigProvider.fromEnv().pipe(
47 + ConfigProvider.mapInputPath(key =>
48 + key === 'COMPOSIO_SESSION_DIR' ? 'COMPOSIO_CACHE_DIR' : `UNSET_${key}`
49 + )
50 +);
51 +
52 +const largeOutputConfigProvider = ConfigProvider.fromMap(
53 + new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
54 +).pipe(
55 + ConfigProvider.orElse(() => testArtifactConfigProvider),
56 + extendConfigProvider
57 +);
58 +
59 const expectInvalidValueMessage = (failure: unknown, message: string) => {
60 expect(ValidationError.isValidationError(failure)).toBe(true);
61 if (!ValidationError.isValidationError(failure)) return;
@@ -68,12 +98,7 @@ describe('CLI: composio execute', () => {
98 })
99 );
100
71 - // Disable CI redaction so tests see raw values.
72 - // The explicit CI-redaction test overrides via vi.spyOn and is unaffected.
73 - let savedCI: string | undefined;
101 beforeEach(() => {
75 - savedCI = process.env.CI;
76 - delete process.env.CI;
102 vi.spyOn(composioClients, 'getLatestToolVersion').mockImplementation(() =>
103 Effect.fail(new composioClients.HttpServerError({}))
104 );
@@ -86,7 +111,6 @@ describe('CLI: composio execute', () => {
111 });
112 afterEach(() => {
113 vi.restoreAllMocks();
89 - if (savedCI !== undefined) process.env.CI = savedCI;
114 });
115
116 let recordedSessionCreateParams: Array<Record<string, unknown>> = [];
@@ -191,7 +215,7 @@ describe('CLI: composio execute', () => {
215
216 layer(
217 TestLive({
194 - baseConfigProvider: testConfigProvider,
218 + baseConfigProvider: runInvocationConfigProvider,
219 fixture: 'global-test-user-id',
220 stdin: { isTTY: true, data: '' },
221 toolsExecutor: {
@@ -210,8 +234,6 @@ describe('CLI: composio execute', () => {
234 it => {
235 it.scoped('returns the full JSON payload when invocation origin is run', () =>
236 Effect.gen(function* () {
213 - vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'run');
214 -
237 yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
238 const lines = yield* MockConsole.getLines({ stripAnsi: true });
239 const output = parseLastJson(lines) as unknown as {
@@ -1076,7 +1098,7 @@ describe('CLI: composio execute', () => {
1098
1099 layer(
1100 TestLive({
1079 - baseConfigProvider: testConfigProvider,
1101 + baseConfigProvider: largeOutputConfigProvider,
1102 fixture: 'global-test-user-id',
1103 stdin: { isTTY: true, data: '' },
1104 toolsExecutor: {
ts/packages/cli/test/src/scripts/release-artifacts.test.ts new
+140
@@ -0,0 +1,140 @@
1 +import { Either, Option } from 'effect';
2 +import { describe, expect, it } from 'vitest';
3 +
4 +import {
5 + RUN_CODEX_ACP_BINARY_TARGETS,
6 + RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,
7 + RUN_COMPANION_MODULE_FILENAMES,
8 + RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
9 +} from '../../../src/services/run-companion-modules';
10 +import {
11 + archiveCompanionRelativePaths,
12 + ARTIFACT_NAMES,
13 + RELEASE_ARTIFACT_TARGETS,
14 + releaseArtifactTargetFor,
15 + UnknownReleaseArtifactError,
16 +} from '../../../scripts/_release-artifacts';
17 +
18 +/**
19 + * Everything `collectExpectedRunCompanionAssetRelativePaths` yields for a fully
20 + * populated companions directory: the wrappers, their bundled services, and the
21 + * multi-platform static asset set.
22 + */
23 +const ALL_COMPANION_RELATIVE_PATHS: ReadonlyArray<string> = [
24 + ...RUN_COMPANION_MODULE_FILENAMES,
25 + ...RUN_COMPANION_MODULE_FILENAMES.map(fileName => `services/${fileName}`),
26 + ...RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,
27 +].sort();
28 +
29 +const codexAcpRelativePathsIn = (relativePaths: ReadonlyArray<string>): ReadonlyArray<string> =>
30 + relativePaths.filter(relativePath => relativePath.endsWith('/codex-acp'));
31 +
32 +describe('releaseArtifactTargetFor', () => {
33 + it('maps every published artifact name to a Node platform/arch pair', () => {
34 + expect(
35 + RELEASE_ARTIFACT_TARGETS.map(({ artifactName, platform, arch }) => [
36 + artifactName,
37 + `${platform}-${arch}`,
38 + ])
39 + ).toEqual([
40 + ['composio-darwin-aarch64', 'darwin-arm64'],
41 + ['composio-darwin-x64', 'darwin-x64'],
42 + ['composio-linux-x64', 'linux-x64'],
43 + ['composio-linux-aarch64', 'linux-arm64'],
44 + ]);
45 + });
46 +
47 + it.each(ARTIFACT_NAMES)('resolves %s', artifactName => {
48 + const target = releaseArtifactTargetFor(artifactName);
49 +
50 + expect(Either.isRight(target)).toBe(true);
51 + });
52 +
53 + it('covers every codex-acp binary target exactly once', () => {
54 + const artifactTargets = RELEASE_ARTIFACT_TARGETS.map(
55 + ({ platform, arch }) => `${platform}-${arch}`
56 + ).sort();
57 + const codexTargets = RUN_CODEX_ACP_BINARY_TARGETS.map(
58 + ({ platform, arch }) => `${platform}-${arch}`
59 + ).sort();
60 +
61 + expect(artifactTargets).toEqual(codexTargets);
62 + });
63 +
64 + it.each(['composio-linux-arm64', 'composio-windows-x64', 'composio', ''])(
65 + 'rejects the unknown artifact name %o',
66 + artifactName => {
67 + const target = releaseArtifactTargetFor(artifactName);
68 +
69 + const error = Option.getOrUndefined(Either.getLeft(target));
70 +
71 + expect(error).toBeInstanceOf(UnknownReleaseArtifactError);
72 + expect(error?.message).toContain('Unknown release artifact');
73 + }
74 + );
75 +});
76 +
77 +describe('archiveCompanionRelativePaths', () => {
78 + it.each(RELEASE_ARTIFACT_TARGETS)(
79 + 'ships only $platform-$arch codex-acp in $artifactName',
80 + target => {
81 + const selected = archiveCompanionRelativePaths({
82 + allRelativePaths: ALL_COMPANION_RELATIVE_PATHS,
83 + target,
84 + });
85 +
86 + expect(codexAcpRelativePathsIn(selected)).toEqual([
87 + `acp-adapters/codex/${target.platform}-${target.arch}/codex-acp`,
88 + ]);
89 + }
90 + );
91 +
92 + it.each(RELEASE_ARTIFACT_TARGETS)('keeps portable assets in $artifactName', target => {
93 + const selected = archiveCompanionRelativePaths({
94 + allRelativePaths: ALL_COMPANION_RELATIVE_PATHS,
95 + target,
96 + });
97 +
98 + expect(selected).toEqual(
99 + expect.arrayContaining([
100 + ...RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
101 + ...RUN_COMPANION_MODULE_FILENAMES,
102 + ...RUN_COMPANION_MODULE_FILENAMES.map(fileName => `services/${fileName}`),
103 + ])
104 + );
105 + });
106 +
107 + it.each(RELEASE_ARTIFACT_TARGETS)(
108 + 'drops exactly the foreign codex-acp binaries from $artifactName',
109 + target => {
110 + const selected = archiveCompanionRelativePaths({
111 + allRelativePaths: ALL_COMPANION_RELATIVE_PATHS,
112 + target,
113 + });
114 +
115 + const dropped = ALL_COMPANION_RELATIVE_PATHS.filter(
116 + relativePath => !selected.includes(relativePath)
117 + );
118 +
119 + expect(dropped).toEqual(
120 + RUN_CODEX_ACP_BINARY_TARGETS.filter(
121 + codexTarget =>
122 + codexTarget.platform !== target.platform || codexTarget.arch !== target.arch
123 + )
124 + .map(codexTarget => codexTarget.relativePath)
125 + .sort()
126 + );
127 + expect(dropped).toHaveLength(RUN_CODEX_ACP_BINARY_TARGETS.length - 1);
128 + }
129 + );
130 +
131 + it('leaves an already-narrowed list untouched', () => {
132 + const target = RELEASE_ARTIFACT_TARGETS[0]!;
133 + const selected = archiveCompanionRelativePaths({
134 + allRelativePaths: ALL_COMPANION_RELATIVE_PATHS,
135 + target,
136 + });
137 +
138 + expect(archiveCompanionRelativePaths({ allRelativePaths: selected, target })).toEqual(selected);
139 + });
140 +});
ts/packages/cli/test/src/services/cli-session-artifacts.test.ts
+13 -3
@@ -1,6 +1,6 @@
1 import { FileSystem, Path } from '@effect/platform';
2 import { describe, expect, layer } from '@effect/vitest';
3 -import { afterEach, vi } from 'vitest';
3 +import { afterEach, beforeEach, vi } from 'vitest';
4 import { ConfigProvider, Effect, Option } from 'effect';
5 import * as tempy from 'tempy';
6 import {
@@ -16,14 +16,24 @@ import { TestLive } from 'test/__utils__';
16
17 const cacheEnabledTestConfigProvider = ConfigProvider.fromMap(
18 new Map([['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false']])
19 -).pipe(extendConfigProvider);
19 +).pipe(
20 + ConfigProvider.orElse(() => ConfigProvider.fromEnv()),
21 + extendConfigProvider
22 +);
23 +
24 +const environmentTestConfigProvider = ConfigProvider.fromEnv().pipe(extendConfigProvider);
25
26 describe('CLI session artifacts', () => {
27 + beforeEach(() => {
28 + vi.stubEnv('COMPOSIO_SESSION_DIR', undefined);
29 + vi.stubEnv('COMPOSIO_CACHE_DIR', undefined);
30 + });
31 +
32 afterEach(() => {
33 vi.unstubAllEnvs();
34 });
35
26 - layer(TestLive())(it => {
36 + layer(TestLive({ baseConfigProvider: environmentTestConfigProvider }))(it => {
37 it.scoped('resolves artifact roots in documented precedence order', () =>
38 Effect.gen(function* () {
39 const path = yield* Path.Path;
ts/packages/cli/test/src/services/cli-user-config.test.ts
+1 -18
@@ -8,11 +8,7 @@ import { BunFileSystem, BunPath } from '@effect/platform-bun';
8 import { ConfigProvider, Effect, Layer } from 'effect';
9 import { extendConfigProvider } from 'src/services/config';
10 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
11 -import {
12 - ComposioCliUserConfig,
13 - ComposioCliUserConfigLive,
14 - resolveCliConfigPathSync,
15 -} from 'src/services/cli-user-config';
11 +import { ComposioCliUserConfig, ComposioCliUserConfigLive } from 'src/services/cli-user-config';
12
13 describe('ComposioCliUserConfig', () => {
14 const withMapConfigProvider = (map: Map<string, string>) =>
@@ -224,17 +220,4 @@ describe('ComposioCliUserConfig', () => {
220 assertEquals(Array.isArray(JSON.parse(persisted)), false);
221 }).pipe(Effect.provide(CliUserConfigTest));
222 });
227 -
228 - it.effect('resolves sync config path from COMPOSIO_CACHE_DIR when provided', () => {
229 - const cacheDir = tempy.temporaryDirectory();
230 - process.env.COMPOSIO_CACHE_DIR = cacheDir;
231 -
232 - return Effect.sync(() => {
233 - try {
234 - assertEquals(resolveCliConfigPathSync(), path.join(cacheDir, 'config.json'));
235 - } finally {
236 - delete process.env.COMPOSIO_CACHE_DIR;
237 - }
238 - });
239 - });
223 });
ts/packages/cli/test/src/services/config.test.ts
+224 -17
@@ -1,12 +1,26 @@
1 -import { beforeEach, describe, it, vi } from '@effect/vitest';
1 +import { beforeEach, describe, expect, it, vi } from '@effect/vitest';
2 import { assertEquals } from '@effect/vitest/utils';
3
4 import { Config, ConfigProvider, Effect, Option, Data, LogLevel } from 'effect';
5 -import { APP_CONFIG } from 'src/effects/app-config';
5 +import { APP_CONFIG, UNPREFIXED_CONFIG } from 'src/effects/app-config';
6 import { extendConfigProvider } from 'src/services/config';
7 import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
8 import * as constants from 'src/constants';
9
10 +const NORMALIZED_APP_CONFIG_DEFAULTS = {
11 + CACHE_DIR: undefined,
12 + SESSION_DIR: undefined,
13 + BIN_DIR: undefined,
14 + AGENTS_BASE_URL: undefined,
15 + WEBHOOK_SECRET: undefined,
16 + CLI_INVOCATION_ORIGIN: undefined,
17 + CLI_PARENT_RUN_ID: undefined,
18 + RUN_ACP_ONLY: false,
19 + RUN_OUTPUT_DIR: undefined,
20 + PERF_DEBUG: false,
21 + TOOL_DEBUG: false,
22 +};
23 +
24 describe('Config', () => {
25 describe('[When] using `ConfigProvider.fromMap`', () => {
26 const withMapConfigProvider = (map: Map<string, string>) =>
@@ -25,9 +39,9 @@ describe('Config', () => {
39 actual,
40 Data.struct({
41 USER_API_KEY: Option.none(),
42 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
43 ENVIRONMENT: Option.none(),
44 BASE_URL: 'https://backend.composio.dev',
30 - CACHE_DIR: Option.none(),
45 LOG_LEVEL: Option.none(),
46 ORG_ID: Option.none(),
47 PROJECT_ID: Option.none(),
@@ -55,9 +69,9 @@ describe('Config', () => {
69 actual,
70 Data.struct({
71 USER_API_KEY: Option.none(),
72 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
73 ENVIRONMENT: Option.none(),
74 BASE_URL: 'https://backend.composio.dev',
60 - CACHE_DIR: Option.none(),
75 LOG_LEVEL: Option.none(),
76 ORG_ID: Option.none(),
77 PROJECT_ID: Option.none(),
@@ -75,7 +89,17 @@ describe('Config', () => {
89 ['COMPOSIO_BASE_URL', 'https://test.localhost'],
90 ['COMPOSIO_WEB_URL', 'https://test.localhost'],
91 ['COMPOSIO_CACHE_DIR', '~/.composio'],
92 + ['COMPOSIO_SESSION_DIR', '/tmp/composio-sessions'],
93 + ['COMPOSIO_BIN_DIR', '/usr/local/bin'],
94 ['COMPOSIO_LOG_LEVEL', 'info'],
95 + ['COMPOSIO_AGENTS_BASE_URL', 'https://agents.test.localhost'],
96 + ['COMPOSIO_WEBHOOK_SECRET', 'secret'],
97 + ['COMPOSIO_CLI_INVOCATION_ORIGIN', 'run'],
98 + ['COMPOSIO_CLI_PARENT_RUN_ID', 'run_parent'],
99 + ['COMPOSIO_RUN_ACP_ONLY', '1'],
100 + ['COMPOSIO_RUN_OUTPUT_DIR', '/tmp/composio-output'],
101 + ['COMPOSIO_PERF_DEBUG', '1'],
102 + ['COMPOSIO_TOOL_DEBUG', '1'],
103 ]) satisfies Map<string, string>;
104
105 const actual = yield* withMapConfigProvider(map)(
@@ -89,16 +113,112 @@ describe('Config', () => {
113 ENVIRONMENT: Option.none(),
114 BASE_URL: 'https://test.localhost',
115 WEB_URL: 'https://test.localhost',
92 - CACHE_DIR: Option.some('~/.composio'),
116 + CACHE_DIR: '~/.composio',
117 + SESSION_DIR: '/tmp/composio-sessions',
118 + BIN_DIR: '/usr/local/bin',
119 LOG_LEVEL: Option.some(LogLevel.Info),
120 ORG_ID: Option.none(),
121 PROJECT_ID: Option.none(),
122 + AGENTS_BASE_URL: 'https://agents.test.localhost',
123 + WEBHOOK_SECRET: 'secret',
124 + CLI_INVOCATION_ORIGIN: 'run',
125 + CLI_PARENT_RUN_ID: 'run_parent',
126 + RUN_ACP_ONLY: true,
127 + RUN_OUTPUT_DIR: '/tmp/composio-output',
128 + PERF_DEBUG: true,
129 + TOOL_DEBUG: true,
130 DISABLE_CONNECTED_ACCOUNT_CACHE: true,
131 })
132 );
133 })
134 );
135
136 + it.effect('[When] optional directory values contain whitespace', () =>
137 + Effect.gen(function* () {
138 + const map = new Map([
139 + ['COMPOSIO_CACHE_DIR', ' /tmp/composio-cache '],
140 + ['COMPOSIO_SESSION_DIR', ' '],
141 + ['COMPOSIO_BIN_DIR', ' /usr/local/bin '],
142 + ['COMPOSIO_RUN_OUTPUT_DIR', '\t/tmp/composio-output\n'],
143 + ]) satisfies Map<string, string>;
144 +
145 + const actual = yield* withMapConfigProvider(map)(
146 + Config.all({
147 + cacheDirectory: APP_CONFIG.CACHE_DIR,
148 + sessionDirectory: APP_CONFIG.SESSION_DIR,
149 + binDirectory: APP_CONFIG.BIN_DIR,
150 + runOutputDirectory: APP_CONFIG.RUN_OUTPUT_DIR,
151 + }).pipe(Effect.andThen(Data.struct))
152 + );
153 +
154 + assertEquals(
155 + actual,
156 + Data.struct({
157 + cacheDirectory: '/tmp/composio-cache',
158 + sessionDirectory: undefined,
159 + binDirectory: '/usr/local/bin',
160 + runOutputDirectory: '/tmp/composio-output',
161 + })
162 + );
163 + })
164 + );
165 +
166 + it.effect('[When] boolean flags carry blank or unrecognized values', () =>
167 + Effect.gen(function* () {
168 + // These arrive from the ambient environment, where `COMPOSIO_PERF_DEBUG=` and
169 + // stray values are routine. They must resolve to a boolean rather than failing
170 + // config decoding, which would surface as an unrecoverable defect at the call site.
171 + const map = new Map([
172 + ['COMPOSIO_PERF_DEBUG', ''],
173 + ['COMPOSIO_TOOL_DEBUG', ' '],
174 + ['COMPOSIO_RUN_ACP_ONLY', 'maybe'],
175 + ['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', ''],
176 + ]) satisfies Map<string, string>;
177 +
178 + const actual = yield* withMapConfigProvider(map)(
179 + Config.all({
180 + perfDebug: APP_CONFIG.PERF_DEBUG,
181 + toolDebug: APP_CONFIG.TOOL_DEBUG,
182 + acpOnly: APP_CONFIG.RUN_ACP_ONLY,
183 + disableConnectedAccountCache: APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE,
184 + }).pipe(Effect.andThen(Data.struct))
185 + );
186 +
187 + assertEquals(
188 + actual,
189 + Data.struct({
190 + // Blank falls back to the flag's own default, ...
191 + perfDebug: false,
192 + toolDebug: false,
193 + // ... which must hold for a default-true flag too, ...
194 + disableConnectedAccountCache: true,
195 + // ... while any other non-falsy value counts as set.
196 + acpOnly: true,
197 + })
198 + );
199 + })
200 + );
201 +
202 + it.effect('[When] boolean flags carry explicit falsy words', () =>
203 + Effect.gen(function* () {
204 + const map = new Map([
205 + ['COMPOSIO_PERF_DEBUG', '0'],
206 + ['COMPOSIO_TOOL_DEBUG', 'false'],
207 + ['COMPOSIO_RUN_ACP_ONLY', 'OFF'],
208 + ]) satisfies Map<string, string>;
209 +
210 + const actual = yield* withMapConfigProvider(map)(
211 + Config.all({
212 + perfDebug: APP_CONFIG.PERF_DEBUG,
213 + toolDebug: APP_CONFIG.TOOL_DEBUG,
214 + acpOnly: APP_CONFIG.RUN_ACP_ONLY,
215 + }).pipe(Effect.andThen(Data.struct))
216 + );
217 +
218 + assertEquals(actual, Data.struct({ perfDebug: false, toolDebug: false, acpOnly: false }));
219 + })
220 + );
221 +
222 it.effect('[When] COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE is "false"', () =>
223 Effect.gen(function* () {
224 const map = new Map([
@@ -113,10 +233,10 @@ describe('Config', () => {
233 actual,
234 Data.struct({
235 USER_API_KEY: Option.none(),
236 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
237 ENVIRONMENT: Option.none(),
238 BASE_URL: 'https://backend.composio.dev',
239 WEB_URL: 'https://dashboard.composio.dev/',
119 - CACHE_DIR: Option.none(),
240 LOG_LEVEL: Option.none(),
241 ORG_ID: Option.none(),
242 PROJECT_ID: Option.none(),
@@ -141,10 +261,10 @@ describe('Config', () => {
261 actual,
262 Data.struct({
263 USER_API_KEY: Option.none(),
264 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
265 ENVIRONMENT: Option.some('production'),
266 BASE_URL: constants.DEFAULT_BASE_URL,
267 WEB_URL: constants.DEFAULT_WEB_URL,
147 - CACHE_DIR: Option.none(),
268 LOG_LEVEL: Option.none(),
269 ORG_ID: Option.none(),
270 PROJECT_ID: Option.none(),
@@ -166,10 +286,10 @@ describe('Config', () => {
286 actual,
287 Data.struct({
288 USER_API_KEY: Option.none(),
289 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
290 ENVIRONMENT: Option.some('staging'),
291 BASE_URL: constants.STAGING_BASE_URL,
292 WEB_URL: 'https://staging-dashboard.composio.dev/',
172 - CACHE_DIR: Option.none(),
293 LOG_LEVEL: Option.none(),
294 ORG_ID: Option.none(),
295 PROJECT_ID: Option.none(),
@@ -196,10 +316,10 @@ describe('Config', () => {
316 actual,
317 Data.struct({
318 USER_API_KEY: Option.none(),
319 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
320 ENVIRONMENT: Option.some('staging'),
321 BASE_URL: 'https://custom-backend.localhost',
322 WEB_URL: constants.STAGING_WEB_URL,
202 - CACHE_DIR: Option.none(),
323 LOG_LEVEL: Option.none(),
324 ORG_ID: Option.none(),
325 PROJECT_ID: Option.none(),
@@ -226,10 +346,10 @@ describe('Config', () => {
346 actual,
347 Data.struct({
348 USER_API_KEY: Option.none(),
349 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
350 ENVIRONMENT: Option.some('staging'),
351 BASE_URL: constants.STAGING_BASE_URL,
352 WEB_URL: 'https://custom-web.localhost',
232 - CACHE_DIR: Option.none(),
353 LOG_LEVEL: Option.none(),
354 ORG_ID: Option.none(),
355 PROJECT_ID: Option.none(),
@@ -251,10 +371,10 @@ describe('Config', () => {
371 actual,
372 Data.struct({
373 USER_API_KEY: Option.none(),
374 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
375 ENVIRONMENT: Option.some('unknown'),
376 BASE_URL: constants.DEFAULT_BASE_URL,
377 WEB_URL: constants.DEFAULT_WEB_URL,
257 - CACHE_DIR: Option.none(),
378 LOG_LEVEL: Option.none(),
379 ORG_ID: Option.none(),
380 PROJECT_ID: Option.none(),
@@ -348,6 +468,63 @@ describe('Config', () => {
468 })
469 );
470 });
471 +
472 + describe('UNPREFIXED_CONFIG', () => {
473 + it.effect('[Then] it normalizes unprefixed host values into runtime facts', () =>
474 + Effect.gen(function* () {
475 + const provider = ConfigProvider.fromMap(
476 + new Map([
477 + ['CACHE_DIR', ' /host/cache '],
478 + ['npm_config_user_agent', 'pnpm/9.0.0 npm/? node/v22.0.0 darwin arm64'],
479 + ['CI', ' TRUE '],
480 + ['NO_COLOR', '1'],
481 + ['COMPOSIO_CLI_TELEMETRY_DEBUG', 'true'],
482 + ['CODEX_FUTURE_MARKER', 'thread_test'],
483 + ['CLAUDE_FUTURE_MARKER', 'cli'],
484 + ['COMPOSIO_CALLER_AGENT', 'Open-Claw'],
485 + ['VITEST', 'off'],
486 + ]),
487 + { pathDelim: '_' }
488 + );
489 +
490 + const actual = yield* provider.load(Config.all(UNPREFIXED_CONFIG));
491 +
492 + expect(actual).toEqual({
493 + CACHE_DIR: '/host/cache',
494 + NPM_CONFIG_USER_AGENT: 'pnpm/9.0.0 npm/? node/v22.0.0 darwin arm64',
495 + CI_REDACTION_ENABLED: true,
496 + INTERACTIVE_PERMISSION_UI_DISABLED: true,
497 + NO_COLOR: true,
498 + TELEMETRY_DEBUG: true,
499 + MASTER_SIGNALS: { codex: true, claude: true },
500 + CALLER_AGENT_SIGNALS: {
501 + explicit: 'Open-Claw',
502 + openclaw: false,
503 + claude: true,
504 + codex: true,
505 + },
506 + });
507 + })
508 + );
509 +
510 + it.effect('[Then] an explicit permission UI value overrides CI detection', () =>
511 + Effect.gen(function* () {
512 + const provider = ConfigProvider.fromMap(
513 + new Map([
514 + ['COMPOSIO_DISABLE_PERMISSION_UI', 'false'],
515 + ['CI', 'true'],
516 + ['VITEST', 'true'],
517 + ]),
518 + { pathDelim: '_' }
519 + );
520 +
521 + assertEquals(
522 + yield* provider.load(UNPREFIXED_CONFIG.INTERACTIVE_PERMISSION_UI_DISABLED),
523 + false
524 + );
525 + })
526 + );
527 + });
528 });
529
530 describe('[When] using `ConfigProvider.env`', () => {
@@ -364,9 +541,19 @@ describe('Config', () => {
541 vi.stubEnv('COMPOSIO_BASE_URL', undefined);
542 vi.stubEnv('COMPOSIO_WEB_URL', undefined);
543 vi.stubEnv('COMPOSIO_CACHE_DIR', undefined);
544 + vi.stubEnv('COMPOSIO_SESSION_DIR', undefined);
545 + vi.stubEnv('COMPOSIO_BIN_DIR', undefined);
546 vi.stubEnv('COMPOSIO_LOG_LEVEL', undefined);
547 vi.stubEnv('COMPOSIO_ORG_ID', undefined);
548 vi.stubEnv('COMPOSIO_PROJECT_ID', undefined);
549 + vi.stubEnv('COMPOSIO_AGENTS_BASE_URL', undefined);
550 + vi.stubEnv('COMPOSIO_WEBHOOK_SECRET', undefined);
551 + vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', undefined);
552 + vi.stubEnv('COMPOSIO_CLI_PARENT_RUN_ID', undefined);
553 + vi.stubEnv('COMPOSIO_RUN_ACP_ONLY', undefined);
554 + vi.stubEnv('COMPOSIO_RUN_OUTPUT_DIR', undefined);
555 + vi.stubEnv('COMPOSIO_PERF_DEBUG', undefined);
556 + vi.stubEnv('COMPOSIO_TOOL_DEBUG', undefined);
557 vi.stubEnv('COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', undefined);
558 });
559
@@ -381,10 +568,10 @@ describe('Config', () => {
568 actual,
569 Data.struct({
570 USER_API_KEY: Option.none(),
571 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
572 ENVIRONMENT: Option.none(),
573 BASE_URL: 'https://backend.composio.dev',
574 WEB_URL: 'https://dashboard.composio.dev/',
387 - CACHE_DIR: Option.none(),
575 LOG_LEVEL: Option.none(),
576 ORG_ID: Option.none(),
577 PROJECT_ID: Option.none(),
@@ -409,10 +596,10 @@ describe('Config', () => {
596 actual,
597 Data.struct({
598 USER_API_KEY: Option.none(),
599 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
600 ENVIRONMENT: Option.none(),
601 BASE_URL: 'https://backend.composio.dev',
602 WEB_URL: 'https://dashboard.composio.dev/',
415 - CACHE_DIR: Option.none(),
603 LOG_LEVEL: Option.none(),
604 ORG_ID: Option.none(),
605 PROJECT_ID: Option.none(),
@@ -428,7 +615,17 @@ describe('Config', () => {
615 vi.stubEnv('COMPOSIO_BASE_URL', 'https://test.localhost');
616 vi.stubEnv('COMPOSIO_WEB_URL', 'https://test.localhost');
617 vi.stubEnv('COMPOSIO_CACHE_DIR', '~/.composio');
618 + vi.stubEnv('COMPOSIO_SESSION_DIR', '/tmp/composio-sessions');
619 + vi.stubEnv('COMPOSIO_BIN_DIR', '/usr/local/bin');
620 vi.stubEnv('COMPOSIO_LOG_LEVEL', 'info');
621 + vi.stubEnv('COMPOSIO_AGENTS_BASE_URL', 'https://agents.test.localhost');
622 + vi.stubEnv('COMPOSIO_WEBHOOK_SECRET', 'secret');
623 + vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'run');
624 + vi.stubEnv('COMPOSIO_CLI_PARENT_RUN_ID', 'run_parent');
625 + vi.stubEnv('COMPOSIO_RUN_ACP_ONLY', '1');
626 + vi.stubEnv('COMPOSIO_RUN_OUTPUT_DIR', '/tmp/composio-output');
627 + vi.stubEnv('COMPOSIO_PERF_DEBUG', '1');
628 + vi.stubEnv('COMPOSIO_TOOL_DEBUG', '1');
629
630 const actual = yield* withEnvConfigProvider(
631 Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))
@@ -441,10 +638,20 @@ describe('Config', () => {
638 ENVIRONMENT: Option.none(),
639 BASE_URL: 'https://test.localhost',
640 WEB_URL: 'https://test.localhost',
444 - CACHE_DIR: Option.some('~/.composio'),
641 + CACHE_DIR: '~/.composio',
642 + SESSION_DIR: '/tmp/composio-sessions',
643 + BIN_DIR: '/usr/local/bin',
644 LOG_LEVEL: Option.some(LogLevel.Info),
645 ORG_ID: Option.none(),
646 PROJECT_ID: Option.none(),
647 + AGENTS_BASE_URL: 'https://agents.test.localhost',
648 + WEBHOOK_SECRET: 'secret',
649 + CLI_INVOCATION_ORIGIN: 'run',
650 + CLI_PARENT_RUN_ID: 'run_parent',
651 + RUN_ACP_ONLY: true,
652 + RUN_OUTPUT_DIR: '/tmp/composio-output',
653 + PERF_DEBUG: true,
654 + TOOL_DEBUG: true,
655 DISABLE_CONNECTED_ACCOUNT_CACHE: true,
656 })
657 );
@@ -463,10 +670,10 @@ describe('Config', () => {
670 actual,
671 Data.struct({
672 USER_API_KEY: Option.none(),
673 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
674 ENVIRONMENT: Option.none(),
675 BASE_URL: 'https://backend.composio.dev',
676 WEB_URL: 'https://dashboard.composio.dev/',
469 - CACHE_DIR: Option.none(),
677 LOG_LEVEL: Option.none(),
678 ORG_ID: Option.none(),
679 PROJECT_ID: Option.none(),
@@ -488,10 +695,10 @@ describe('Config', () => {
695 actual,
696 Data.struct({
697 USER_API_KEY: Option.none(),
698 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
699 ENVIRONMENT: Option.some('staging'),
700 BASE_URL: constants.STAGING_BASE_URL,
701 WEB_URL: 'https://staging-dashboard.composio.dev/',
494 - CACHE_DIR: Option.none(),
702 LOG_LEVEL: Option.none(),
703 ORG_ID: Option.none(),
704 PROJECT_ID: Option.none(),
@@ -515,10 +722,10 @@ describe('Config', () => {
722 actual,
723 Data.struct({
724 USER_API_KEY: Option.none(),
725 + ...NORMALIZED_APP_CONFIG_DEFAULTS,
726 ENVIRONMENT: Option.some('staging'),
727 BASE_URL: 'https://custom.localhost',
728 WEB_URL: 'https://custom-web.localhost',
521 - CACHE_DIR: Option.none(),
729 LOG_LEVEL: Option.none(),
730 ORG_ID: Option.none(),
731 PROJECT_ID: Option.none(),
ts/packages/cli/test/src/services/master-detector.test.ts
+7 -5
@@ -6,7 +6,8 @@ describe('master-detector', () => {
6 it('detects codex when codex env markers are present', () => {
7 expect(
8 detectMaster({
9 - CODEX_THREAD_ID: 'thread_123',
9 + codex: true,
10 + claude: false,
11 })
12 ).toBe('codex');
13 });
@@ -14,7 +15,8 @@ describe('master-detector', () => {
15 it('detects claude when claude env markers are present without codex markers', () => {
16 expect(
17 detectMaster({
17 - CLAUDE_CODE_ENTRYPOINT: 'sdk-ts',
18 + codex: false,
19 + claude: true,
20 })
21 ).toBe('claude');
22 });
@@ -22,13 +24,13 @@ describe('master-detector', () => {
24 it('prefers codex when both codex and claude markers are present', () => {
25 expect(
26 detectMaster({
25 - CLAUDE_CODE_ENTRYPOINT: 'sdk-ts',
26 - CODEX_THREAD_ID: 'thread_123',
27 + codex: true,
28 + claude: true,
29 })
30 ).toBe('codex');
31 });
32
33 it('falls back to user when no known agent markers are present', () => {
32 - expect(detectMaster({})).toBe('user');
34 + expect(detectMaster({ codex: false, claude: false })).toBe('user');
35 });
36 });
ts/packages/cli/test/src/services/native-ui-sidecar.test.ts
+13 -4
@@ -5,6 +5,7 @@ import {
5 detectNativeUiCallerAgentEffect,
6 interactivePermissionUiDisabledConfig,
7 } from 'src/services/native-ui-sidecar';
8 +import { UNPREFIXED_CONFIG } from 'src/effects/app-config';
9
10 const loadFlag = (entries: Record<string, string>) =>
11 ConfigProvider.fromMap(new Map(Object.entries(entries))).load(
@@ -29,7 +30,13 @@ const processTreeUnavailable = executorLayer(() =>
30 const detectAgent = (
31 env: Record<string, string>,
32 layer: Layer.Layer<CommandExecutor.CommandExecutor>
32 -) => detectNativeUiCallerAgentEffect(env).pipe(Effect.provide(layer));
33 +) =>
34 + Effect.gen(function* () {
35 + const signals = yield* ConfigProvider.fromMap(new Map(Object.entries(env)), {
36 + pathDelim: '_',
37 + }).load(UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS);
38 + return yield* detectNativeUiCallerAgentEffect(signals);
39 + }).pipe(Effect.provide(layer));
40
41 describe('native UI sidecar', () => {
42 it.effect('disables interactive permission UI in CI and Vitest environments', () =>
@@ -76,11 +83,13 @@ describe('native UI sidecar', () => {
83
84 it.effect('detects the caller agent from environment prefixes', () =>
85 Effect.gen(function* () {
79 - expect(yield* detectAgent({ OPENCLAW_GATEWAY: '1' }, processTreeMustNotRun)).toBe('openclaw');
80 - expect(yield* detectAgent({ CLAUDE_CODE_ENTRYPOINT: 'cli' }, processTreeMustNotRun)).toBe(
86 + expect(yield* detectAgent({ OPENCLAW_FUTURE_MARKER: '1' }, processTreeMustNotRun)).toBe(
87 + 'openclaw'
88 + );
89 + expect(yield* detectAgent({ CLAUDE_FUTURE_MARKER: 'cli' }, processTreeMustNotRun)).toBe(
90 'claude'
91 );
83 - expect(yield* detectAgent({ CODEX_HOME: '/tmp/codex' }, processTreeMustNotRun)).toBe('codex');
92 + expect(yield* detectAgent({ CODEX_FUTURE_MARKER: '1' }, processTreeMustNotRun)).toBe('codex');
93 })
94 );
95
ts/packages/cli/test/src/services/run-companion-modules.test.ts
+128 -3
@@ -2,14 +2,19 @@ import * as fs from 'node:fs';
2 import * as os from 'node:os';
3 import * as path from 'node:path';
4 import { BunContext } from '@effect/platform-bun';
5 -import { afterEach, describe, expect, layer } from '@effect/vitest';
5 +import { afterEach, describe, expect, it, layer } from '@effect/vitest';
6 import { Effect } from 'effect';
7 import { vi } from 'vitest';
8 import {
9 + hostRunCompanionStaticAssetRelativePaths,
10 + listMissingInstalledRunCompanionModules,
11 repairMissingInstalledRunCompanionModules,
12 + RUN_CODEX_ACP_BINARY_TARGETS,
13 + RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,
14 RUN_COMPANION_MODULE_FILENAMES,
15 RUN_COMPANION_RELEASE_TAG_FILENAME,
12 - RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS,
16 + RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,
17 + runCompanionStaticAssetRelativePathsFor,
18 } from 'src/services/run-companion-modules';
19 import { BaseConfigProviderLive, extendConfigProvider } from 'src/services/config';
20
@@ -23,9 +28,10 @@ const TEST_BINARY_ASSET_NAMES = [
28 'composio-linux-aarch64.zip',
29 'composio-linux-x64.zip',
30 ];
31 +// A release archive ships every platform's codex-acp binary.
32 const TEST_COMPANION_RELATIVE_PATHS = [
33 ...RUN_COMPANION_MODULE_FILENAMES,
28 - ...RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS,
34 + ...RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,
35 ].sort();
36
37 const stubRepairFetch = () => {
@@ -71,7 +77,126 @@ describe('run-companion-modules', () => {
77 vi.unstubAllEnvs();
78 });
79
80 + describe('runCompanionStaticAssetRelativePathsFor', () => {
81 + it('[Given] a supported host [Then] it requires only that host codex-acp binary', () => {
82 + for (const target of RUN_CODEX_ACP_BINARY_TARGETS) {
83 + expect(
84 + runCompanionStaticAssetRelativePathsFor({
85 + platform: target.platform,
86 + arch: target.arch,
87 + })
88 + ).toEqual([...RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS, target.relativePath]);
89 + }
90 + });
91 +
92 + it('[Given] an unsupported host [Then] it requires only the portable assets', () => {
93 + expect(runCompanionStaticAssetRelativePathsFor({ platform: 'win32', arch: 'x64' })).toEqual(
94 + RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS
95 + );
96 + });
97 + });
98 +
99 layer(BunContext.layer)(it => {
100 + it.effect(
101 + "[Given] an install lacking another platform's codex-acp binary [Then] nothing needs repair",
102 + () =>
103 + Effect.gen(function* () {
104 + const hostStaticAssets = yield* hostRunCompanionStaticAssetRelativePaths;
105 + const foreignRelativePaths = RUN_CODEX_ACP_BINARY_TARGETS.map(
106 + target => target.relativePath
107 + ).filter(relativePath => !hostStaticAssets.includes(relativePath));
108 +
109 + expect(foreignRelativePaths.length).toBe(RUN_CODEX_ACP_BINARY_TARGETS.length - 1);
110 +
111 + const installDirectory = fs.mkdtempSync(
112 + path.join(os.tmpdir(), 'composio-run-host-scope-')
113 + );
114 + const execPath = path.join(installDirectory, 'composio');
115 + for (const relativePath of [...RUN_COMPANION_MODULE_FILENAMES, ...hostStaticAssets]) {
116 + const filePath = path.join(installDirectory, relativePath);
117 + fs.mkdirSync(path.dirname(filePath), { recursive: true });
118 + fs.writeFileSync(filePath, `installed:${relativePath}`);
119 + }
120 + const fetchMock = stubRepairFetch();
121 +
122 + return yield* Effect.gen(function* () {
123 + expect(yield* listMissingInstalledRunCompanionModules(execPath)).toEqual([]);
124 + expect(
125 + yield* repairMissingInstalledRunCompanionModules({
126 + callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
127 + execPath,
128 + appVersion: '0.0.0-test',
129 + })
130 + ).toEqual({ repaired: false });
131 + expect(fetchMock).not.toHaveBeenCalled();
132 + }).pipe(
133 + Effect.ensuring(
134 + Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
135 + )
136 + );
137 + })
138 + );
139 +
140 + it.effect(
141 + '[Given] an install without ACP adapters [Then] a plain run neither reports nor repairs anything',
142 + () =>
143 + Effect.gen(function* () {
144 + const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-no-acp-'));
145 + const execPath = path.join(installDirectory, 'composio');
146 + for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
147 + fs.writeFileSync(path.join(installDirectory, fileName), '', 'utf8');
148 + }
149 + const fetchMock = stubRepairFetch();
150 +
151 + return yield* Effect.gen(function* () {
152 + expect(yield* listMissingInstalledRunCompanionModules(execPath)).toEqual([]);
153 + expect(
154 + yield* repairMissingInstalledRunCompanionModules({
155 + callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
156 + execPath,
157 + appVersion: '0.0.0-test',
158 + })
159 + ).toEqual({ repaired: false });
160 + // The self-repair download is what 404s on a dev build; the ACP tier
161 + // must never reach it.
162 + expect(fetchMock).not.toHaveBeenCalled();
163 + }).pipe(
164 + Effect.ensuring(
165 + Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
166 + )
167 + );
168 + })
169 + );
170 +
171 + it.effect(
172 + '[Given] a missing companion wrapper [Then] repair still restores the ACP tier too',
173 + () => {
174 + const installDirectory = fs.mkdtempSync(
175 + path.join(os.tmpdir(), 'composio-run-tier-repair-')
176 + );
177 + const execPath = path.join(installDirectory, 'composio');
178 + stubRepairFetch();
179 + mockArchiveContents();
180 +
181 + return Effect.gen(function* () {
182 + const result = yield* repairMissingInstalledRunCompanionModules({
183 + callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
184 + execPath,
185 + appVersion: '0.0.0-test',
186 + });
187 +
188 + expect(result).toEqual({ repaired: true, releaseTag: TEST_RELEASE_TAG });
189 + for (const relativePath of yield* hostRunCompanionStaticAssetRelativePaths) {
190 + expect(fs.existsSync(path.join(installDirectory, relativePath))).toBe(true);
191 + }
192 + }).pipe(
193 + Effect.ensuring(
194 + Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
195 + )
196 + );
197 + }
198 + );
199 +
200 it.effect('[Given] a complete archive [Then] repair atomically replaces companions', () => {
201 const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-repair-test-'));
202 const execPath = path.join(installDirectory, 'composio');
ts/packages/cli/test/src/services/run-helpers-runtime.test.ts
+46
@@ -61,4 +61,50 @@ describe('run-helpers-runtime', () => {
61 await expect(installedGlobals.proxy('github')).rejects.toThrow(/session_id/);
62 expect(fetchMock).toHaveBeenCalledOnce();
63 });
64 +
65 + it('[Given] normalized false flags [Then] nested CLI children receive false explicitly', async () => {
66 + vi.stubEnv('COMPOSIO_RUN_ENV_SENTINEL', 'forwarded');
67 + vi.stubEnv('COMPOSIO_PERF_DEBUG', '1');
68 + vi.stubEnv('COMPOSIO_TOOL_DEBUG', '1');
69 + vi.stubEnv('COMPOSIO_RUN_ACP_ONLY', '1');
70 + vi.stubEnv('BUN_BE_BUN', '1');
71 +
72 + const childScript = [
73 + 'console.log(JSON.stringify({',
74 + ' successful: true,',
75 + ' data: {',
76 + ' sentinel: process.env.COMPOSIO_RUN_ENV_SENTINEL,',
77 + ' perfDebug: process.env.COMPOSIO_PERF_DEBUG,',
78 + ' toolDebug: process.env.COMPOSIO_TOOL_DEBUG,',
79 + ' acpOnly: process.env.COMPOSIO_RUN_ACP_ONLY,',
80 + ' bunBeBun: process.env.BUN_BE_BUN,',
81 + ' },',
82 + '}));',
83 + ].join('\n');
84 +
85 + await installRunHelpers({
86 + cliPrefix: [process.execPath, '-e', childScript],
87 + helperContext: { perfDebug: false, toolDebug: false, acpOnly: false },
88 + });
89 +
90 + const installedGlobals: unknown = globalThis;
91 + expect(Predicate.hasProperty(installedGlobals, 'search')).toBe(true);
92 + if (
93 + !Predicate.hasProperty(installedGlobals, 'search') ||
94 + typeof installedGlobals.search !== 'function'
95 + ) {
96 + throw new Error('installRunHelpers() did not install search().');
97 + }
98 +
99 + await expect(installedGlobals.search('test')).resolves.toMatchObject({
100 + successful: true,
101 + data: {
102 + sentinel: 'forwarded',
103 + perfDebug: '0',
104 + toolDebug: '0',
105 + acpOnly: '0',
106 + bunBeBun: '',
107 + },
108 + });
109 + });
110 });
ts/packages/cli/test/src/services/run-subagent-acp.test.ts
+60
@@ -1,3 +1,6 @@
1 +import * as fs from 'node:fs';
2 +import * as os from 'node:os';
3 +import * as path from 'node:path';
4 import { Readable } from 'node:stream';
5 import { BunContext } from '@effect/platform-bun';
6 import { Effect } from 'effect';
@@ -5,10 +8,12 @@ import { afterEach, describe, expect, it, vi } from '@effect/vitest';
8 import {
9 BufferedChunkLogger,
10 createStructuredOutputMcpContext,
11 + MissingAcpAdapterAssetsError,
12 readableStreamFromNode,
13 resolveAcpAdapterCommand,
14 selectPermissionOutcome,
15 } from 'src/services/run-subagent-acp';
16 +import { RUN_COMPANION_MODULE_FILENAMES } from 'src/services/run-companion-modules';
17 import { AcpInvokeError, isAcpInvokeError } from 'src/services/run-subagent-shared';
18
19 describe('run-subagent-acp', () => {
@@ -57,6 +62,61 @@ describe('run-subagent-acp', () => {
62 }).pipe(Effect.provide(BunContext.layer))
63 );
64
65 + it.effect(
66 + '[Given] a packaged install shipping the adapter [Then] it runs the shipped asset',
67 + () =>
68 + Effect.gen(function* () {
69 + const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-acp-shipped-'));
70 + const execPath = path.join(installDirectory, 'composio');
71 + for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
72 + fs.writeFileSync(path.join(installDirectory, fileName), '', 'utf8');
73 + }
74 + const adapterPath = path.join(installDirectory, 'acp-adapters', 'claude-code-acp.mjs');
75 + fs.mkdirSync(path.dirname(adapterPath), { recursive: true });
76 + fs.writeFileSync(adapterPath, '', 'utf8');
77 +
78 + return yield* Effect.gen(function* () {
79 + const result = yield* resolveAcpAdapterCommand('claude', { execPath });
80 + expect(result.source).toBe('shipped');
81 + expect(result.cmd).toEqual([execPath, adapterPath]);
82 + }).pipe(
83 + Effect.ensuring(
84 + Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
85 + )
86 + );
87 + }).pipe(Effect.provide(BunContext.layer))
88 + );
89 +
90 + it.effect(
91 + '[Given] a packaged install missing the ACP adapters [Then] it names the repair instead of falling back',
92 + () =>
93 + Effect.gen(function* () {
94 + const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-acp-missing-'));
95 + const execPath = path.join(installDirectory, 'composio');
96 + for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
97 + fs.writeFileSync(path.join(installDirectory, fileName), '', 'utf8');
98 + }
99 +
100 + return yield* Effect.gen(function* () {
101 + const error = yield* Effect.flip(resolveAcpAdapterCommand('claude', { execPath }));
102 +
103 + expect(error).toBeInstanceOf(MissingAcpAdapterAssetsError);
104 + expect(error.missingRelativePaths).toContain('acp-adapters/claude-code-acp.mjs');
105 + expect(error.message).toContain(
106 + `This Composio install cannot run a claude sub-agent: the ACP adapter files are missing from ${installDirectory}.`
107 + );
108 + expect(error.message).toContain("Run 'composio upgrade' to restore them");
109 + // Not an AcpInvokeError, so the helper runtime surfaces it to the user
110 + // instead of silently retrying through the legacy sub-agent.
111 + expect(isAcpInvokeError(error)).toBe(false);
112 + }).pipe(
113 + Effect.ensuring(
114 + Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
115 + )
116 + );
117 + }).pipe(Effect.provide(BunContext.layer))
118 + );
119 +
120 it('[Given] an ACP invoke error [Then] it is classified for fallback', () => {
121 const error = new AcpInvokeError('initialize_failed', 'boom');
122 expect(isAcpInvokeError(error)).toBe(true);
ts/packages/cli/test/src/services/runtime-debug-logger.test.ts
+48 -8
@@ -1,31 +1,42 @@
1 import { afterEach, describe, expect, layer, vi } from '@effect/vitest';
2 -import { Effect } from 'effect';
2 +import { ConfigProvider, Effect } from 'effect';
3 import { logToolDebug, makePerfDebugLogger } from 'src/services/runtime-debug-logger';
4 -import { resetRuntimeDebugFlags, setRuntimeDebugFlags } from 'src/services/runtime-debug-flags';
4 +import {
5 + cliDebugFlagsLayer,
6 + NO_CLI_DEBUG_FLAG_OVERRIDES,
7 + type CliDebugFlagOverrides,
8 +} from 'src/services/runtime-flags';
9 +import { extendConfigProvider } from 'src/services/config';
10 import { MockConsole, TestLive } from 'test/__utils__';
11
12 +const configuredDebugFlags = ConfigProvider.fromMap(
13 + new Map([
14 + ['COMPOSIO_PERF_DEBUG', '1'],
15 + ['COMPOSIO_TOOL_DEBUG', '1'],
16 + ])
17 +).pipe(extendConfigProvider);
18 +
19 +const withDebugFlags = (overrides: Partial<CliDebugFlagOverrides>) =>
20 + Effect.provide(cliDebugFlagsLayer({ ...NO_CLI_DEBUG_FLAG_OVERRIDES, ...overrides }));
21 +
22 describe('runtime debug logger', () => {
23 afterEach(() => {
9 - resetRuntimeDebugFlags();
24 vi.restoreAllMocks();
25 });
26
27 layer(TestLive())(it => {
28 it.scoped('writes tool diagnostics as the existing JSON line format', () =>
29 Effect.gen(function* () {
16 - setRuntimeDebugFlags({ toolDebug: true });
17 -
30 yield* logToolDebug('resolved', { slug: 'GITHUB_GET_REPO' });
31
32 expect(yield* MockConsole.getLines()).toContain(
33 '[tool-debug] {"label":"resolved","slug":"GITHUB_GET_REPO"}'
34 );
23 - })
35 + }).pipe(withDebugFlags({ toolDebug: true }))
36 );
37
38 it.scoped('writes performance diagnostics with elapsed time', () =>
39 Effect.gen(function* () {
28 - setRuntimeDebugFlags({ perfDebug: true });
40 vi.spyOn(Date, 'now').mockReturnValue(125);
41 const logPerfDebug = makePerfDebugLogger(100);
42
@@ -34,7 +45,36 @@ describe('runtime debug logger', () => {
45 expect(yield* MockConsole.getLines()).toContain(
46 '[perf] {"phase":"event","label":"started","elapsedMs":25,"slug":"GITHUB_GET_REPO"}'
47 );
37 - })
48 + }).pipe(withDebugFlags({ perfDebug: true }))
49 + );
50 +
51 + it.scoped('writes diagnostics enabled through app config', () =>
52 + Effect.gen(function* () {
53 + vi.spyOn(Date, 'now').mockReturnValue(125);
54 +
55 + yield* logToolDebug('configured-tool');
56 + yield* makePerfDebugLogger(100)('configured-perf');
57 +
58 + const lines = yield* MockConsole.getLines();
59 + expect(lines).toContain('[tool-debug] {"label":"configured-tool"}');
60 + expect(lines).toContain(
61 + '[perf] {"phase":"event","label":"configured-perf","elapsedMs":25}'
62 + );
63 + }).pipe(withDebugFlags({}), Effect.withConfigProvider(configuredDebugFlags))
64 + );
65 +
66 + it.scoped('lets explicit false flags override enabled app config', () =>
67 + Effect.gen(function* () {
68 + const existingLineCount = (yield* MockConsole.getLines()).length;
69 +
70 + yield* logToolDebug('configured-tool');
71 + yield* makePerfDebugLogger(100)('configured-perf');
72 +
73 + expect((yield* MockConsole.getLines()).slice(existingLineCount)).toEqual([]);
74 + }).pipe(
75 + withDebugFlags({ perfDebug: false, toolDebug: false }),
76 + Effect.withConfigProvider(configuredDebugFlags)
77 + )
78 );
79 });
80 });
ts/packages/cli/test/src/services/runtime-flags.test.ts new
+141
@@ -0,0 +1,141 @@
1 +import { afterEach, vi } from 'vitest';
2 +import { describe, expect, it, layer } from '@effect/vitest';
3 +import { ConfigProvider, Effect } from 'effect';
4 +import {
5 + cliDebugFlagsLayer,
6 + debugFlagsToChildEnv,
7 + isAcpOnlyEnabled,
8 + isPerfDebugEnabled,
9 + isTelemetryDebugEnabled,
10 + isToolDebugEnabled,
11 + NO_CLI_DEBUG_FLAG_OVERRIDES,
12 + stripTelemetryDebugFlag,
13 + telemetryDebugModeLayer,
14 + TELEMETRY_DEBUG_FLAG,
15 +} from 'src/services/runtime-flags';
16 +import { extendConfigProvider } from 'src/services/config';
17 +import { TestLive } from 'test/__utils__';
18 +
19 +describe('debugFlagsToChildEnv', () => {
20 + it('[Given] resolved debug flags [Then] every flag serializes into the child environment', () => {
21 + expect(
22 + debugFlagsToChildEnv({
23 + perfDebug: true,
24 + toolDebug: false,
25 + acpOnly: true,
26 + telemetryDebug: false,
27 + })
28 + ).toEqual({
29 + COMPOSIO_PERF_DEBUG: '1',
30 + COMPOSIO_TOOL_DEBUG: '0',
31 + COMPOSIO_RUN_ACP_ONLY: '1',
32 + COMPOSIO_CLI_TELEMETRY_DEBUG: '0',
33 + });
34 + });
35 +});
36 +
37 +describe('stripTelemetryDebugFlag', () => {
38 + it('[Given] the flag before the delimiter [Then] it is removed and reported', () => {
39 + expect(stripTelemetryDebugFlag(['bun', 'composio', TELEMETRY_DEBUG_FLAG, 'whoami'])).toEqual({
40 + argv: ['bun', 'composio', 'whoami'],
41 + telemetryDebug: true,
42 + });
43 + });
44 +
45 + it('[Given] the flag after a `--` delimiter [Then] it belongs to the child and survives', () => {
46 + const argv = ['bun', 'composio', 'run', 'my-agent', '--', TELEMETRY_DEBUG_FLAG];
47 +
48 + expect(stripTelemetryDebugFlag(argv)).toEqual({ argv, telemetryDebug: false });
49 + });
50 +
51 + it('[Given] the flag on both sides of `--` [Then] only the CLI-side one is consumed', () => {
52 + expect(
53 + stripTelemetryDebugFlag([
54 + 'bun',
55 + 'composio',
56 + TELEMETRY_DEBUG_FLAG,
57 + 'run',
58 + 'my-agent',
59 + '--',
60 + TELEMETRY_DEBUG_FLAG,
61 + ])
62 + ).toEqual({
63 + argv: ['bun', 'composio', 'run', 'my-agent', '--', TELEMETRY_DEBUG_FLAG],
64 + telemetryDebug: true,
65 + });
66 + });
67 +
68 + it('[Given] no flag [Then] argv is reported unchanged', () => {
69 + const argv = ['bun', 'composio', 'whoami'];
70 +
71 + expect(stripTelemetryDebugFlag(argv)).toEqual({ argv, telemetryDebug: false });
72 + });
73 +});
74 +
75 +const enabledDebugConfig = ConfigProvider.fromMap(
76 + new Map([
77 + ['COMPOSIO_PERF_DEBUG', '1'],
78 + ['COMPOSIO_TOOL_DEBUG', '1'],
79 + ['COMPOSIO_RUN_ACP_ONLY', '1'],
80 + ])
81 +).pipe(extendConfigProvider);
82 +
83 +const readAllDebugFlags = Effect.all({
84 + perfDebug: isPerfDebugEnabled,
85 + toolDebug: isToolDebugEnabled,
86 + acpOnly: isAcpOnlyEnabled,
87 +});
88 +
89 +describe('debug flag precedence', () => {
90 + layer(TestLive())(it => {
91 + it.effect('[Given] no flags [Then] the COMPOSIO_* config decides', () =>
92 + Effect.gen(function* () {
93 + expect(yield* readAllDebugFlags).toEqual({
94 + perfDebug: true,
95 + toolDebug: true,
96 + acpOnly: true,
97 + });
98 + }).pipe(
99 + Effect.provide(cliDebugFlagsLayer(NO_CLI_DEBUG_FLAG_OVERRIDES)),
100 + Effect.withConfigProvider(enabledDebugConfig)
101 + )
102 + );
103 +
104 + it.effect('[Given] explicit false flags [Then] they beat the enabled config', () =>
105 + Effect.gen(function* () {
106 + expect(yield* readAllDebugFlags).toEqual({
107 + perfDebug: false,
108 + toolDebug: false,
109 + acpOnly: false,
110 + });
111 + }).pipe(
112 + Effect.provide(cliDebugFlagsLayer({ perfDebug: false, toolDebug: false, acpOnly: false })),
113 + Effect.withConfigProvider(enabledDebugConfig)
114 + )
115 + );
116 + });
117 +});
118 +
119 +describe('telemetry debug mode', () => {
120 + afterEach(() => {
121 + vi.unstubAllEnvs();
122 + });
123 +
124 + it.effect('[Given] the bootstrap provided the flag [Then] it wins over the environment', () =>
125 + Effect.gen(function* () {
126 + vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DEBUG', '');
127 +
128 + expect(yield* isTelemetryDebugEnabled).toBe(true);
129 + }).pipe(Effect.provide(telemetryDebugModeLayer(true)))
130 + );
131 +
132 + it.effect('[Given] no bootstrap flag [Then] it falls back to COMPOSIO_CLI_TELEMETRY_DEBUG', () =>
133 + Effect.gen(function* () {
134 + vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DEBUG', 'true');
135 + expect(yield* isTelemetryDebugEnabled).toBe(true);
136 +
137 + vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DEBUG', '');
138 + expect(yield* isTelemetryDebugEnabled).toBe(false);
139 + })
140 + );
141 +});
ts/packages/cli/test/src/services/tool-file-uploads.test.ts
+3
@@ -154,6 +154,9 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
154 );
155
156 expect(createPresignedURL).toHaveBeenCalledTimes(1);
157 + expect(createPresignedURL).toHaveBeenCalledWith(
158 + expect.objectContaining({ md5: '5d41402abc4b2a76b9719d911017c592' })
159 + );
160 expect(result.attachment).toMatchObject({ s3key: 's3key-123', name: 'document.pdf' });
161 }).pipe(
162 Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)),
ts/packages/cli/test/src/services/tool-permissions.test.ts
+13 -4
@@ -10,6 +10,8 @@ import {
10 ToolPermissionDeniedError,
11 type ConsumerPermissionSnapshot,
12 } from 'src/services/tool-permissions';
13 +import { extendConfigProvider } from 'src/services/config';
14 +import { NodeOs } from 'src/services/node-os';
15
16 // Pinned wall clock for deterministic fixtures. The SUT reads the real
17 // `Date.now()` (snapshot TTL, allow-decision expiry), so every timestamp
@@ -17,6 +19,13 @@ import {
19 const PINNED_TIME = new Date('2026-01-01T00:00:00.000Z');
20 const PINNED_NOW = PINNED_TIME.getTime();
21
22 +const ToolPermissionsTest = Layer.mergeAll(
23 + BunFileSystem.layer,
24 + BunPath.layer,
25 + NodeOs.Default,
26 + Layer.setConfigProvider(extendConfigProvider(ConfigProvider.fromEnv()))
27 +);
28 +
29 const snapshotFixture = (
30 overrides: Partial<ConsumerPermissionSnapshot> = {}
31 ): ConsumerPermissionSnapshot => ({
@@ -133,7 +142,7 @@ describe('tool permissions', () => {
142 const result = yield* gateToolExecution({ toolSlug: 'GMAIL_SEND_EMAIL' });
143
144 expect(result).toBeUndefined();
136 - }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
145 + }).pipe(Effect.provide(ToolPermissionsTest))
146 );
147
148 it.effect('preserves permission-policy denial identity', () =>
@@ -161,7 +170,7 @@ describe('tool permissions', () => {
170 expect(failure.deniedBy).toBe('permissions');
171 expect(failure.toolSlug).toBe('GMAIL_SEND_EMAIL');
172 }
164 - }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
173 + }).pipe(Effect.provide(ToolPermissionsTest))
174 );
175
176 it.effect('fails closed when interactive approval is needed but permission UI is disabled', () =>
@@ -178,7 +187,7 @@ describe('tool permissions', () => {
187 expect(failure.deniedBy).toBe('permissions');
188 expect(failure.message).toContain('permission prompts are disabled');
189 }
181 - }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
190 + }).pipe(Effect.provide(ToolPermissionsTest))
191 );
192
193 it.effect('honors cached allow decisions even when permission UI is disabled', () =>
@@ -209,6 +218,6 @@ describe('tool permissions', () => {
218 });
219
220 expect(result).toStrictEqual({ approvalStatus: 'cached_approved' });
212 - }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
221 + }).pipe(Effect.provide(ToolPermissionsTest))
222 );
223 });