Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
refactor(cli): eliminate raw environment access (#4134)
Alberto Schiabel09f76b1c9fb2
diff --git a/.oxlintrc.json b/.oxlintrc.jsonindex 598f53f5d..a7f3e3379 100644--- a/.oxlintrc.json+++ b/.oxlintrc.json@@ -274,17 +274,6 @@}]}- ],- "eslint-js/no-restricted-syntax": [- "error",- {- "selector": "MemberExpression[object.name='process'][property.name='stdout']",- "message": "Write output and read terminal capabilities through TerminalUI."- },- {- "selector": "MemberExpression[object.name='process'][property.name='stderr']",- "message": "Write errors and read terminal capabilities through TerminalUI."- }]}},@@ -329,6 +318,42 @@],"eslint-js/no-restricted-syntax": ["error",+ {+ "selector": "TryStatement",+ "message": "Use Effect.try, Effect.tryPromise, or typed Effect error recovery instead of try/catch."+ },+ {+ "selector": "MemberExpression[object.name='process'][computed=false][property.name='env']",+ "message": "Read environment variables through effect/Config instead of process.env."+ },+ {+ "selector": "MemberExpression[object.name='process'][computed=true][property.value='env']",+ "message": "Read environment variables through effect/Config instead of process.env."+ },+ {+ "selector": "VariableDeclarator[init.name='process'] > ObjectPattern > Property[key.name='env']",+ "message": "Read environment variables through effect/Config instead of process.env."+ },+ {+ "selector": "VariableDeclarator[init.name='process'] > ObjectPattern > Property[key.value='env']",+ "message": "Read environment variables through effect/Config instead of process.env."+ },+ {+ "selector": "AssignmentExpression[right.name='process'] > ObjectPattern > Property[key.name='env']",+ "message": "Read environment variables through effect/Config instead of process.env."+ },+ {+ "selector": "AssignmentExpression[right.name='process'] > ObjectPattern > Property[key.value='env']",+ "message": "Read environment variables through effect/Config instead of process.env."+ },+ {+ "selector": "AssignmentPattern[right.name='process'] > ObjectPattern > Property[key.name='env']",+ "message": "Read environment variables through effect/Config instead of process.env."+ },+ {+ "selector": "AssignmentPattern[right.name='process'] > ObjectPattern > Property[key.value='env']",+ "message": "Read environment variables through effect/Config instead of process.env."+ },{"selector": "MemberExpression[object.name='process'][property.name='stdout']","message": "Write output and read terminal capabilities through TerminalUI."diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2b201ad87..0c370546a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -228,6 +228,12 @@ importers:specifier: 'catalog:'version: 1.3.14+ ts/e2e-tests/cli/run:+ devDependencies:+ '@e2e-tests/utils':+ specifier: workspace:*+ version: link:../../_utils+ts/e2e-tests/cli/setup-plugins:devDependencies:'@e2e-tests/utils':diff --git a/ts/e2e-tests/_utils/Dockerfile.cli b/ts/e2e-tests/_utils/Dockerfile.cliindex f79fdd598..6fe83e3c7 100644--- a/ts/e2e-tests/_utils/Dockerfile.cli+++ b/ts/e2e-tests/_utils/Dockerfile.cli@@ -61,6 +61,20 @@ RUN bun build ./src/bin.ts \--production \--outfile /out/composio+# Build the `composio run` companion modules next to the binary. Without the+# run-*.mjs wrappers every `composio run` treats the install as broken and+# enters the GitHub self-repair path. `--host-only` restricts the bundled+# codex-acp binary to this image's own platform; shipping all four costs ~870MB+# and ~2min of build time for binaries this image can never execute.+#+# The acp-adapters are dropped afterwards: they are only needed when a script+# invokes an ACP sub-agent, which is checked lazily at the invocation site, and+# no CLI e2e test does. Keeping them would add ~224MB to the image. The build+# script still produces them (it asserts on its own output), so the removal+# happens in the same layer to keep it out of the image entirely.+RUN bun scripts/build-companion-modules.ts /out --host-only && \+ rm -rf /out/acp-adapters+# Copy CLI e2e tests last (changes frequently)WORKDIR /appCOPY ts/e2e-tests/cli/ /app/ts/e2e-tests/cli/@@ -75,8 +89,9 @@ ENV HOME="/tmp"WORKDIR /app-# CLI binary-COPY --from=builder /out/composio /usr/local/bin/composio+# CLI binary plus the `composio run` companion modules, which must stay siblings+# of the executable (they are resolved from dirname(process.execPath)).+COPY --from=builder /out/ /usr/local/bin/# CLI e2e testsCOPY --from=builder /app/ts/e2e-tests/cli/ /app/ts/e2e-tests/cli/diff --git a/ts/e2e-tests/cli/run/README.md b/ts/e2e-tests/cli/run/README.mdnew file mode 100644index 000000000..e2c545ec8--- /dev/null+++ b/ts/e2e-tests/cli/run/README.md@@ -0,0 +1,39 @@+# CLI `composio run` Test++Verifies that `composio run` forwards the child script's exit status to the caller and that+the run log it advertises survives the process.++## Why This Exists++`composio run` never exits by itself: the handler sets `process.exitCode` and returns a+successful Effect, and the CLI teardown hands that code to `runMain`, which force-exits only+when the code is non-zero. Unit tests run in-process and can only observe `process.exitCode`,+so they cannot tell whether the code ever reached the OS. An Effect upgrade or a teardown+change could turn every failing script into exit 0 without failing a single unit test.++The `RUN_LOG_FILE=` path printed on stderr has the same problem: it is only useful if the file+outlives the process that printed it, which regressed once when the log lived inside a scoped+temp directory.++## What It Tests++| Test | Description |+| ------------------ | ---------------------------------------------------------------------- |+| Exit forwarding | `composio run 'process.exit(7)'` exits 7 |+| Successful run | An inline script exits 0 and its stdout reaches the caller |+| Missing script | `composio run` with no code and no `--file` exits non-zero and says so |+| Run log durability | The announced `RUN_LOG_FILE` path still exists after the process exits |++## Requirements++None. This suite does not require any environment variables or network access.++## Isolation Tool++**Docker** with the CLI built from the current monorepo source.++## Running++```bash+pnpm test:e2e:cli+```diff --git a/ts/e2e-tests/cli/run/e2e.test.ts b/ts/e2e-tests/cli/run/e2e.test.tsnew file mode 100644index 000000000..69fe38aad--- /dev/null+++ b/ts/e2e-tests/cli/run/e2e.test.ts@@ -0,0 +1,99 @@+/**+ * CLI run command e2e test+ *+ * `composio run` spawns the user's script as a child process and forwards its exit+ * status to the caller. The forwarding path is process-level: the command handler sets+ * `process.exitCode` and returns a *successful* Effect, and the CLI teardown hands that+ * code to `runMain`, which force-exits only for a non-zero code. Nothing in-process can+ * observe whether that hand-off actually reached the OS, so a `wait`/`$?` assertion+ * against the real binary is the only guard against a failing script silently becoming+ * exit 0.+ *+ * The same applies to the `RUN_LOG_FILE=` path announced on stderr: it is only useful if+ * the file outlives the process that printed it, which cannot be checked from inside the+ * run.+ */++import { e2e, sanitizeOutput, type E2ETestResult } from '@e2e-tests/utils';+import { TIMEOUTS } from '@e2e-tests/utils/const';+import { describe, it, expect, beforeAll } from 'bun:test';++/** Marker printed by the successful inline script, unique enough to grep for. */+const STDOUT_MARKER = 'composio-run-e2e-stdout-marker';++/**+ * Runs a successful script, then — after the CLI process has exited — reports whether the+ * `RUN_LOG_FILE=` path it advertised on stderr still exists. Probe results go to stdout as+ * `KEY=value` lines; the CLI's own stderr is parked in a file so it cannot mix in.+ */+const runLogProbeCommand = [+ `composio run 'console.log("run-log-probe")' 2> run-stderr.txt`,+ 'run_status=$?',+ `run_log_path=$(grep '^RUN_LOG_FILE=' run-stderr.txt | head -n 1 | cut -d= -f2-)`,+ 'echo "RUN_STATUS=$run_status"',+ 'if [ -n "$run_log_path" ]; then echo "RUN_LOG_ANNOUNCED=yes"; else echo "RUN_LOG_ANNOUNCED=no"; fi',+ 'if [ -f "$run_log_path" ]; then echo "RUN_LOG_EXISTS=yes"; else echo "RUN_LOG_EXISTS=no"; fi',+].join('; ');++e2e(import.meta.url, {+ versions: {+ cli: ['current'],+ },+ defineTests: ({ runCmd }) => {+ let failingScriptResult: E2ETestResult;+ let successfulScriptResult: E2ETestResult;+ let missingScriptResult: E2ETestResult;+ let runLogResult: E2ETestResult;++ beforeAll(async () => {+ failingScriptResult = await runCmd(`composio run 'process.exit(7)'`);+ successfulScriptResult = await runCmd(`composio run 'console.log("${STDOUT_MARKER}")'`);+ missingScriptResult = await runCmd('composio run');+ runLogResult = await runCmd(runLogProbeCommand);+ }, TIMEOUTS.FIXTURE);++ describe('composio run with a failing script', () => {+ it('forwards the script exit status to the caller', () => {+ expect(failingScriptResult.exitCode).toBe(7);+ });+ });++ describe('composio run with a successful script', () => {+ it('exits successfully', () => {+ expect(successfulScriptResult.exitCode).toBe(0);+ });++ it('forwards script stdout to the caller', () => {+ expect(sanitizeOutput(successfulScriptResult.stdout)).toContain(STDOUT_MARKER);+ });+ });++ describe('composio run without inline code or --file', () => {+ it('exits non-zero', () => {+ expect(missingScriptResult.exitCode).not.toBe(0);+ });++ it('explains what is missing on stderr', () => {+ expect(sanitizeOutput(missingScriptResult.stderr)).toContain(+ 'Provide inline code or use --file to run a script file.'+ );+ });++ it('writes no data to stdout', () => {+ expect(sanitizeOutput(missingScriptResult.stdout)).toBe('');+ });+ });++ describe('the RUN_LOG_FILE path announced on stderr', () => {+ it('is announced', () => {+ expect(runLogResult.exitCode).toBe(0);+ expect(sanitizeOutput(runLogResult.stdout)).toContain('RUN_STATUS=0');+ expect(sanitizeOutput(runLogResult.stdout)).toContain('RUN_LOG_ANNOUNCED=yes');+ });++ it('still exists after the CLI process exits', () => {+ expect(sanitizeOutput(runLogResult.stdout)).toContain('RUN_LOG_EXISTS=yes');+ });+ });+ },+});diff --git a/ts/e2e-tests/cli/run/package.json b/ts/e2e-tests/cli/run/package.jsonnew file mode 100644index 000000000..27db35ab2--- /dev/null+++ b/ts/e2e-tests/cli/run/package.json@@ -0,0 +1,14 @@+{+ "name": "@e2e-tests/cli-run",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "scripts": {+ "typecheck": "tsc --noEmit",+ "test:e2e": "bun test e2e.test.ts",+ "test:e2e:cli": "bun test e2e.test.ts"+ },+ "devDependencies": {+ "@e2e-tests/utils": "workspace:*"+ }+}diff --git a/ts/e2e-tests/cli/upgrade/e2e.test.ts b/ts/e2e-tests/cli/upgrade/e2e.test.tsindex f396638db..776ecac4d 100644--- a/ts/e2e-tests/cli/upgrade/e2e.test.ts+++ b/ts/e2e-tests/cli/upgrade/e2e.test.ts@@ -15,7 +15,7 @@ const companionRelativePaths = ['run-subagent-acp.mjs','run-subagent-legacy.mjs','run-subagent-output-mcp.mjs',- // RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS+ // RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS'acp-adapters/claude-code-acp.mjs','acp-adapters/cli.js','acp-adapters/codex/darwin-arm64/codex-acp',diff --git a/ts/packages/cli/README.md b/ts/packages/cli/README.mdindex 1141d09c3..64aa532f2 100644--- a/ts/packages/cli/README.md+++ b/ts/packages/cli/README.md@@ -50,22 +50,39 @@ composio [--log-level all|trace|debug|info|warning|error|fatal|none]## Configuration-The Composio CLI supports configuration via environment variables.-Additionally, for storing and retrieving user session context, a `user_data.json` JSON configuration file is used.--By default, this file is stored in `~/.composio`, but you can specify a custom location using the `COMPOSIO_CACHE_DIR` environment variable.--| Environment Variable | User JSON config | Description | Default |-| ---------------------- | ---------------- | ------------------------------------------------------------------ | -------------------------------- |-| COMPOSIO_API_KEY | `api_key` | Composio backend API key | None |-| COMPOSIO_BASE_URL | `base_url` | The base URL of the Composio backend API | https://backend.composio.dev |-| COMPOSIO_WEB_URL | `web_url` | The base URL of the Composio web app | https://dashboard.composio.dev/ |-| COMPOSIO_CACHE_DIR | - | The directory where the Composio CLI stores cache files | ~/.composio |-| COMPOSIO_BIN_DIR | - | The directory `composio install` adds to `PATH` (see below) | Resolved from the running binary |-| COMPOSIO_LOG_LEVEL | - | The log level for the Composio CLI | None |-| DEBUG_OVERRIDE_VERSION | - | The version to use when upgrading the Composio CLI (for debugging) | None |-| FORCE_USE_CACHE | - | Whether to force the use of previously cached HTTP responses | None |-| NO_COLOR | - | If set, disables color output in the CLI (https://no-color.org/) | None |+The Composio CLI supports configuration via environment variables. It stores authenticated user context in `user_data.json` and general CLI settings in `config.json`.++By default, both files are stored in `~/.composio`, but you can specify a custom location using the `COMPOSIO_CACHE_DIR` environment variable.++| Environment Variable | JSON config | Description | Default |+| ---------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------ |+| COMPOSIO_USER_API_KEY | `user_data.json`: `api_key` | Composio user API key | None |+| COMPOSIO_ENVIRONMENT | - | Selects the production or staging URL defaults | production |+| COMPOSIO_BASE_URL | `user_data.json`: `base_url` | The base URL of the Composio backend API | https://backend.composio.dev |+| COMPOSIO_WEB_URL | `user_data.json`: `web_url` | The base URL of the Composio web app | https://dashboard.composio.dev/ |+| COMPOSIO_CACHE_DIR | - | The directory where the Composio CLI stores cache files | ~/.composio |+| COMPOSIO_SESSION_DIR | `config.json`: `artifact_directory` | The root directory for CLI session artifacts | `COMPOSIO_CACHE_DIR`, then `artifact_directory`, then `$TMPDIR/composio` |+| COMPOSIO_BIN_DIR | - | The directory `composio install` adds to `PATH` (see below) | Resolved from the running binary |+| COMPOSIO_LOG_LEVEL | - | The log level for the Composio CLI | None |+| COMPOSIO_ORG_ID | - | The organization ID used for project-scoped commands | Active project |+| COMPOSIO_PROJECT_ID | - | The project ID used for project-scoped commands | Active project |+| COMPOSIO_AGENTS_BASE_URL | - | The base URL of the Composio agents service | https://agents.composio.dev |+| COMPOSIO_WEBHOOK_SECRET | - | The signing secret for events forwarded by `composio dev triggers listen` | Generated for the current session |+| COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE | - | Disables the connected-account cache | true |+| COMPOSIO_PERF_DEBUG | - | Set to `1` to write performance diagnostics | 0 |+| COMPOSIO_TOOL_DEBUG | - | Set to `1` to write tool diagnostics | 0 |+| DEBUG_OVERRIDE_VERSION | - | The version to use when upgrading the Composio CLI (for debugging) | None |+| FORCE_USE_CACHE | - | Whether to force the use of previously cached HTTP responses | None |+| NO_COLOR | - | If set, disables color output in the CLI (https://no-color.org/) | None |++The CLI and its installer use these variables to coordinate nested commands. They aren't intended for manual configuration.++| Environment Variable | Description | Default |+| ------------------------------ | -------------------------------------------------------------------------- | ------- |+| COMPOSIO_CLI_INVOCATION_ORIGIN | Identifies whether another CLI surface, such as `composio run`, invoked it | cli |+| COMPOSIO_CLI_PARENT_RUN_ID | Reuses the parent run ID for nested command telemetry | None |+| COMPOSIO_RUN_ACP_ONLY | Set to `1` to disable the legacy sub-agent fallback | 0 |+| COMPOSIO_RUN_OUTPUT_DIR | Shares one artifact directory across nested `composio run` commands | None |Additionally, `composio upgrade` supports the following environment variables:diff --git a/ts/packages/cli/lint-boundaries.json b/ts/packages/cli/lint-boundaries.jsonindex 027ed510b..9a3d0de33 100644--- a/ts/packages/cli/lint-boundaries.json+++ b/ts/packages/cli/lint-boundaries.json@@ -1,149 +1,4 @@{- "src/analytics/events.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "spawn-time env handoff from parent run",- "target": "(process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID())"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "spawn-time env handoff read outside Effect",- "target": "const getInvocationOrigin = (): string => process.env.COMPOSIO_CLI_INVOCATION_ORIGIN ?? 'cli';"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "spawn-time env handoff read outside Effect",- "target": "const getParentRunId = (): string | undefined => process.env.COMPOSIO_CLI_PARENT_RUN_ID;"- }- ],- "src/bin.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "pre-runtime env write during bootstrap",- "target": "process.env[CLI_TELEMETRY_DEBUG_ENV_VAR] = 'true';"- }- ],- "src/cli-main.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "env write propagates run id to children",- "target": "process.env.COMPOSIO_CLI_PARENT_RUN_ID = commandTelemetryContext.runId;"- }- ],- "src/commands/index.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "env delete clears a stale hidden-flag value",- "target": "delete process.env.COMPOSIO_RUN_ACP_ONLY;"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "env write hands the stripped flag to run.cmd",- "target": "process.env.COMPOSIO_RUN_ACP_ONLY = acpOnly ? '1' : '0';"- }- ],- "src/commands/run.cmd.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "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",- "target": "process.env.COMPOSIO_CACHE_DIR?.trim() || process.env.CACHE_DIR?.trim() || defaultComposioDir;"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "reads the COMPOSIO_RUN_ACP_ONLY flag a parent process sets to force the ACP-only subagent path in the child run",- "target": "const acpOnly = process.env.COMPOSIO_RUN_ACP_ONLY === '1';"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "reuses the run ID a parent `composio run` process passed via env so nested runs share one run identity",- "target": "const runId = process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID();"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "spreads the caller's full environment into the spawned script so user-provided variables reach the child process",- "target": "...process.env,"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "try/finally removes the temp preload and wrapper files around the imperative Bun.spawn block, whose success path ends in process.exit",- "target": "try {"- },- {- "rule": "no-restricted-imports",- "reason": "os.tmpdir and os.homedir locate the preload scratch directory and ~/.composio in the same synchronous helpers",- "target": "import * as os from 'node:os';"- },- {- "rule": "no-restricted-imports",- "reason": "synchronous fs (mkdtempSync/writeFileSync/rmSync/existsSync) builds and tears down the run preload files in plain helpers that execute outside the Effect runtime",- "target": "import * as fs from 'node:fs';"- }- ],- "src/commands/tools/commands/tools.execute.cmd.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "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",- "target": "const shouldStoreLargeExecuteOutput = () => process.env.COMPOSIO_CLI_INVOCATION_ORIGIN !== 'run';"- },- {- "rule": "eslint-js/no-restricted-syntax",- "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",- "target": "process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim() ||"- },- {- "rule": "eslint-js/no-restricted-syntax",- "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",- "target": "directoryPath: sharedDirectory?.trim() || process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim(),"- },- {- "rule": "eslint-js/no-restricted-syntax",- "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",- "target": "executeOutputDir: process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim() || undefined,"- }- ],- "src/commands/triggers/commands/triggers.listen.cmd.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "re-checks the same raw env var to tell the user whether they supplied a secret or this session generated one",- "target": "if (process.env.COMPOSIO_WEBHOOK_SECRET) {"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "the forward signing secret is an optional raw passthrough from the user's shell; its literal presence/absence selects the generated-secret fallback",- "target": "const webhookSecret = process.env.COMPOSIO_WEBHOOK_SECRET ?? generatedWebhookSecret;"- }- ],- "src/services/agents.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "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",- "target": "(process.env.COMPOSIO_AGENTS_BASE_URL ?? DEFAULT_AGENTS_BASE_URL).replace(/\\/+$/, '');"- }- ],- "src/services/cli-session-artifacts.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "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",- "target": "process.env.COMPOSIO_CACHE_DIR?.trim() ||"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "read inline so a blank/whitespace-only COMPOSIO_SESSION_DIR falls through the || precedence chain (session dir > cache dir > user config > tmpdir)",- "target": "process.env.COMPOSIO_SESSION_DIR?.trim() ||"- }- ],- "src/services/cli-user-config.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "this resolver is called from synchronous non-Effect code, so the COMPOSIO_CACHE_DIR override cannot come from effect/Config here",- "target": "process.env.COMPOSIO_CACHE_DIR?.trim() ||"- },- {- "rule": "no-restricted-imports",- "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",- "target": "import os from 'node:os';"- }- ],"src/services/detached-process.ts": [{"rule": "no-restricted-imports",@@ -151,20 +6,6 @@"target": "import { spawn } from 'node:child_process';"}],- "src/services/master-detector.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "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",- "target": "export const detectMaster = (env: Record<string, string | undefined> = process.env): MasterKind => {"- }- ],- "src/services/native-ui-sidecar.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "Sole raw-env boundary of this module: prefix scanning needs the full environment map, which effect/Config cannot enumerate.",- "target": "const rawProcessEnv: NodeJS.ProcessEnv = process.env;"- }- ],"src/services/node-os.ts": [{"rule": "no-restricted-imports",@@ -172,100 +13,18 @@"target": "import os from 'node:os';"}],- "src/services/project-environment-detector.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "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",- "target": "const userAgent = parseUserAgent(process.env.npm_config_user_agent);"- }- ],"src/services/run-helpers-runtime.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "JSON.stringify throws on circular user values in this sync formatter injected into user code; String() is the entire fallback",- "target": "try {"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "async fallback chain in the user's child process: ACP invoke errors route to the legacy sub-agent path, everything else rethrows",- "target": "try {"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "debug flag reaches the child process via inherited environment; the CLI's Config provider is not available here",- "target": "helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === '1';"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "debug flag reaches the child process via inherited environment; the CLI's Config provider is not available here",- "target": "helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === '1';"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "sync config read at the child-process boundary; a missing or malformed CLI config file just means the 'auto' target",- "target": "try {"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "the spawned CLI child must inherit the caller's full environment before Composio-specific overrides are layered on top",- "target": "...process.env,"- },- {- "rule": "no-restricted-imports",- "reason": "os.tmpdir() locates the fallback run-files directory in the child process, outside the Effect runtime",- "target": "import * as os from 'node:os';"- },{"rule": "no-restricted-imports","reason": "sync fs for run-log appends, run-file writes, and CLI config reads in the child process, outside the Effect runtime","target": "import * as fs from 'node:fs';"}],- "src/services/run-subagent-output-mcp.ts": [- {- "rule": "no-restricted-imports",- "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",- "target": "import * as fs from 'node:fs';"- }- ],- "src/services/runtime-debug-flags.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "called from sync non-Effect helper code in spawned child processes, where the flag arrives via inherited environment rather than a Config provider",- "target": "runtimeDebugFlags.perfDebug || process.env.COMPOSIO_PERF_DEBUG === '1';"- },- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "called from sync non-Effect helper code in spawned child processes, where the flag arrives via inherited environment rather than a Config provider",- "target": "runtimeDebugFlags.toolDebug || process.env.COMPOSIO_TOOL_DEBUG === '1';"- }- ],"src/services/tool-file-uploads.ts": [{"rule": "no-restricted-imports","reason": "MD5 for the presigned-upload checksum is not available in Web Crypto","target": "const { createHash } = await import('node:crypto');"}- ],- "src/services/tool-permissions.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "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",- "target": "try {"- }- ],- "src/ui/colors.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "palette is created eagerly at import time, before any Effect runtime; honors the NO_COLOR convention",- "target": "} = color.createColors(!Boolean(process.env.NO_COLOR));"- }- ],- "src/ui/redact.ts": [- {- "rule": "eslint-js/no-restricted-syntax",- "reason": "plain sync string helper called from formatting code; CI flag toggles redaction in recorded CLI output",- "target": "if (process.env.CI !== 'true') return value as `${Prefix}${string}`;"- }]}diff --git a/ts/packages/cli/package.json b/ts/packages/cli/package.jsonindex 0adf7b7f1..b056a4a66 100644--- a/ts/packages/cli/package.json+++ b/ts/packages/cli/package.json@@ -22,6 +22,7 @@"clean": "git clean -xdf node_modules","cli": "bun run src/bin.ts","build:binary": "bun run ./scripts/build-binary.ts",+ "build:companions": "bun run ./scripts/build-companion-modules.ts","build:binary:cross": "bun run ./scripts/build-binary-cross.ts","build:binary:all": "bun run ./scripts/build-all-binaries.ts","build:binary:package": "bun run ./scripts/package-binaries.ts",diff --git a/ts/packages/cli/scripts/_acp-adapters.ts b/ts/packages/cli/scripts/_acp-adapters.tsindex 4dee25f02..2310e2da8 100644--- a/ts/packages/cli/scripts/_acp-adapters.ts+++ b/ts/packages/cli/scripts/_acp-adapters.ts@@ -2,7 +2,10 @@ import { chmod, copyFile, mkdir, mkdtemp, readFile, rename, rm, writeFile } fromimport { createRequire } from 'node:module';import * as path from 'node:path';import { extract as extractTarball } from 'tar';-import { RUN_CODEX_ACP_BINARY_TARGETS } from '../src/services/run-companion-modules';+import {+ RUN_CODEX_ACP_BINARY_TARGETS,+ type RunCodexAcpBinaryTarget,+} from '../src/services/run-companion-modules';const GENERATED_ROOT_DIR = path.resolve('./.generated');const ACP_ADAPTERS_CACHE_DIR = path.join(GENERATED_ROOT_DIR, 'acp-adapters');@@ -82,12 +85,14 @@ const resolveClaudeAgentSdkPackageJsonPath = (): string => {return nestedRequire.resolve('@anthropic-ai/claude-agent-sdk/package.json');};-const buildCacheManifest = async (): Promise<AcpAdaptersManifest> => {+const buildCacheManifest = async (+ codexBinaryTargets: ReadonlyArray<RunCodexAcpBinaryTarget>+): Promise<AcpAdaptersManifest> => {const claudePackage = await readInstalledPackageJson('@zed-industries/claude-code-acp');const agentSdkPackage = await readJsonFile<PackageJson>(resolveClaudeAgentSdkPackageJsonPath());const codexLauncherPackage = await readInstalledPackageJson('@zed-industries/codex-acp');- const codexTargets = RUN_CODEX_ACP_BINARY_TARGETS.map(target => {+ const codexTargets = codexBinaryTargets.map(target => {const version = codexLauncherPackage.optionalDependencies?.[target.packageName];if (!version) {throw new Error(@@ -296,8 +301,18 @@ const materializeCodexAdapters = async ();};-export const materializeAcpAdaptersCache = async (): Promise<string> => {- const manifest = await buildCacheManifest();+/**+ * Materializes the ACP adapter cache.+ *+ * `codexBinaryTargets` narrows which codex-acp binaries are downloaded; release+ * builds keep the default (every supported platform), while a build that only+ * has to run on the building machine — e.g. the CLI e2e image — passes just its+ * own target to avoid downloading ~200MB per foreign platform.+ */+export const materializeAcpAdaptersCache = async (+ codexBinaryTargets: ReadonlyArray<RunCodexAcpBinaryTarget> = RUN_CODEX_ACP_BINARY_TARGETS+): Promise<string> => {+ const manifest = await buildCacheManifest(codexBinaryTargets);const existingManifest = await readExistingManifest();if (diff --git a/ts/packages/cli/scripts/_release-artifacts.ts b/ts/packages/cli/scripts/_release-artifacts.tsnew file mode 100644index 000000000..9716d80ce--- /dev/null+++ b/ts/packages/cli/scripts/_release-artifacts.ts@@ -0,0 +1,87 @@+/**+ * Release artifact identity: which platform/arch each published archive targets,+ * and which companion assets belong inside it.+ *+ * Deliberately free of Bun-only imports so the packaging rules stay unit-testable+ * under Node.+ */++import { Data, Either } from 'effect';+import {+ RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,+ runCompanionStaticAssetRelativePathsFor,+} from '../src/services/run-companion-modules';++export type ReleaseArtifactTarget = {+ readonly artifactName: string;+ readonly platform: NodeJS.Platform;+ readonly arch: string;+};++/**+ * Every published binary artifact, mapped to the Node `platform`/`arch` pair its+ * archive runs on. Artifact names use the `aarch64` spelling; Node calls the same+ * architecture `arm64`.+ */+export const RELEASE_ARTIFACT_TARGETS: ReadonlyArray<ReleaseArtifactTarget> = [+ { artifactName: 'composio-darwin-aarch64', platform: 'darwin', arch: 'arm64' },+ { artifactName: 'composio-darwin-x64', platform: 'darwin', arch: 'x64' },+ { artifactName: 'composio-linux-x64', platform: 'linux', arch: 'x64' },+ { artifactName: 'composio-linux-aarch64', platform: 'linux', arch: 'arm64' },+];++/**+ * Known binary artifact names (without extension).+ */+export const ARTIFACT_NAMES: ReadonlyArray<string> = RELEASE_ARTIFACT_TARGETS.map(+ target => target.artifactName+);++export class UnknownReleaseArtifactError extends Data.TaggedError(+ 'scripts/UnknownReleaseArtifactError'+)<{+ readonly artifactName: string;+}> {+ get message(): string {+ return `Unknown release artifact ${this.artifactName}. Expected one of: ${ARTIFACT_NAMES.join(', ')}.`;+ }+}++/**+ * Resolve an artifact name to its platform/arch. The mapping is total over+ * {@link RELEASE_ARTIFACT_TARGETS}; anything else fails instead of silently+ * producing an archive with no platform-specific assets.+ */+export const releaseArtifactTargetFor = (+ artifactName: string+): Either.Either<ReleaseArtifactTarget, UnknownReleaseArtifactError> =>+ Either.fromNullable(+ RELEASE_ARTIFACT_TARGETS.find(target => target.artifactName === artifactName),+ () => new UnknownReleaseArtifactError({ artifactName })+ );++/**+ * Narrow the full multi-platform companion asset list down to the assets one+ * archive should ship: the portable ones plus the single codex-acp binary that+ * archive's platform can execute.+ *+ * An archive already carries a platform-specific `composio` binary, so a+ * darwin-arm64 archive is unusable on linux-x64 no matter which codex-acp+ * binaries travel with it. Shipping foreign ones only inflates the download.+ */+export const archiveCompanionRelativePaths = ({+ allRelativePaths,+ target,+}: {+ readonly allRelativePaths: ReadonlyArray<string>;+ readonly target: ReleaseArtifactTarget;+}): ReadonlyArray<string> => {+ const included = new Set(runCompanionStaticAssetRelativePathsFor(target));+ const excluded = new Set(+ RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS.filter(+ relativePath => !included.has(relativePath)+ )+ );++ return allRelativePaths.filter(relativePath => !excluded.has(relativePath));+};diff --git a/ts/packages/cli/scripts/_shared.ts b/ts/packages/cli/scripts/_shared.tsindex b2bd19db4..4204f077a 100644--- a/ts/packages/cli/scripts/_shared.ts+++ b/ts/packages/cli/scripts/_shared.ts@@ -3,7 +3,12 @@ import { chmod, copyFile, mkdir, readdir, rm, stat, writeFile } from 'node:fs/primport * as path from 'node:path';import process from 'node:process';import { Effect } from 'effect';-import { RUN_COMPANION_MODULE_BASENAMES } from '../src/services/run-companion-modules';+import {+ codexAcpBinaryTargetFor,+ RUN_CODEX_ACP_BINARY_TARGETS,+ RUN_COMPANION_MODULE_BASENAMES,+ type RunCodexAcpBinaryTarget,+} from '../src/services/run-companion-modules';import { materializeAcpAdaptersCache } from './_acp-adapters';export { teardown } from './_teardown';@@ -43,13 +48,26 @@ const copyDirectoryRecursive = async (sourceDir: string, targetDir: string): Pro}};-const copyBundledAcpAdapters = async (outputDir: string): Promise<void> => {- const acpAdaptersCacheDir = await materializeAcpAdaptersCache();+const copyBundledAcpAdapters = async (+ outputDir: string,+ codexBinaryTargets: ReadonlyArray<RunCodexAcpBinaryTarget>+): Promise<void> => {+ const acpAdaptersCacheDir = await materializeAcpAdaptersCache(codexBinaryTargets);const acpOutputDir = path.join(outputDir, 'acp-adapters');await rm(acpOutputDir, { force: true, recursive: true });await copyDirectoryRecursive(acpAdaptersCacheDir, acpOutputDir);};+// The codex-acp binary the building machine can actually execute. Unsupported+// hosts get an empty list, matching the host requirement set the CLI checks.+export const hostCodexAcpBinaryTargets = (): ReadonlyArray<RunCodexAcpBinaryTarget> => {+ const hostTarget = codexAcpBinaryTargetFor({+ platform: process.platform,+ arch: process.arch,+ });+ return hostTarget ? [hostTarget] : [];+};+export const LOCAL_TOOLS_BINARY_ASSET_DIRNAME = 'local-tools-binaries';// 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> =>}};-export const buildCompanionModules = (outputDir: string) =>+export const buildCompanionModules = (+ outputDir: string,+ options: {+ readonly codexBinaryTargets?: ReadonlyArray<RunCodexAcpBinaryTarget>;+ } = {}+) =>Effect.gen(function* () {yield* Effect.tryPromise(() => mkdir(outputDir, { recursive: true }));@@ -314,6 +337,8 @@ export const buildCompanionModules = (outputDir: string) =>yield* Effect.tryPromise(() => writeFile(wrapperPath, wrapperSource, 'utf8'));}- yield* Effect.tryPromise(() => copyBundledAcpAdapters(outputDir));+ yield* Effect.tryPromise(() =>+ copyBundledAcpAdapters(outputDir, options.codexBinaryTargets ?? RUN_CODEX_ACP_BINARY_TARGETS)+ );yield* Effect.tryPromise(() => assertBundledRuntimeFiles(outputDir));});diff --git a/ts/packages/cli/scripts/build-companion-modules.ts b/ts/packages/cli/scripts/build-companion-modules.tsnew file mode 100644index 000000000..3549e3815--- /dev/null+++ b/ts/packages/cli/scripts/build-companion-modules.ts@@ -0,0 +1,67 @@+#!/usr/bin/env bun++/**+ * Build the `composio run` companion modules next to an already-compiled binary.+ *+ * `scripts/build-binary.ts` does this as part of a full release build, shipping+ * every platform's codex-acp binary. This entry point exists for builds whose+ * output only ever runs on the building machine — the CLI e2e image — where+ * downloading three foreign codex-acp binaries costs ~600MB and minutes of build+ * time for files that machine can never execute.+ *+ * Usage: `bun scripts/build-companion-modules.ts <OUTPUT_DIR> [--host-only]`+ */++import process from 'node:process';+import { Config, ConfigProvider, Console, Effect, Logger, Layer, LogLevel } from 'effect';+import { BunContext, BunRuntime } from '@effect/platform-bun';+import { buildCompanionModules, hostCodexAcpBinaryTargets, teardown } from './_shared';+import { BinaryBuildError } from './build-error';++export function buildCompanionModulesCommand() {+ return Effect.gen(function* () {+ const args = process.argv.slice(2);+ const outputDir = args.find(arg => !arg.startsWith('--'));++ if (!outputDir) {+ return yield* new BinaryBuildError({+ message: 'Missing <OUTPUT_DIR> argument',+ exitCode: 1,+ });+ }++ const hostOnly = args.includes('--host-only');+ const codexBinaryTargets = hostOnly ? hostCodexAcpBinaryTargets() : undefined;++ yield* buildCompanionModules(outputDir, { codexBinaryTargets });++ yield* Console.log(+ `Companion modules built in ${outputDir}${+ hostOnly+ ? ` (codex-acp: ${codexBinaryTargets?.map(target => target.relativePath).join(', ') || 'none for this host'})`+ : ''+ }`+ );+ });+}++const ConfigLive = Effect.gen(function* () {+ const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(+ Config.withDefault(LogLevel.Info)+ );++ return Logger.minimumLogLevel(logLevel);+}).pipe(Layer.unwrapEffect, Layer.merge(Layer.setConfigProvider(ConfigProvider.fromEnv())));++if (require.main === module) {+ buildCompanionModulesCommand().pipe(+ Effect.provide(ConfigLive),+ Effect.provide(Logger.pretty),+ Effect.provide(BunContext.layer),+ Effect.scoped,+ Effect.map(() => ({ message: 'Process completed successfully.' })),+ BunRuntime.runMain({+ teardown,+ })+ );+}diff --git a/ts/packages/cli/scripts/package-binaries.ts b/ts/packages/cli/scripts/package-binaries.tsindex 3261d7559..ef6fdbaab 100644--- a/ts/packages/cli/scripts/package-binaries.ts+++ b/ts/packages/cli/scripts/package-binaries.ts@@ -21,23 +21,21 @@ import { LOCAL_TOOLS_BINARY_ASSET_DIRNAME, teardown } from './_shared';import { $ } from 'bun';import { readdir, stat, writeFile } from 'node:fs/promises';import path from 'node:path';-import { collectExpectedRunCompanionAssetRelativePaths } from '../src/services/run-companion-modules';+import {+ collectExpectedRunCompanionAssetRelativePaths,+ RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,+} from '../src/services/run-companion-modules';+import {+ archiveCompanionRelativePaths,+ ARTIFACT_NAMES,+ releaseArtifactTargetFor,+} from './_release-artifacts';const BINARIES_DIR = './dist/binaries';const COMPANIONS_DIR = path.join(BINARIES_DIR, 'companions');const LOCAL_TOOLS_BINARY_ASSETS_DIR = path.join(BINARIES_DIR, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);const RELEASE_TAG = process.env.RELEASE_TAG?.trim();-/**- * Known binary artifact names (without extension).- */-const ARTIFACT_NAMES = [- 'composio-darwin-aarch64',- 'composio-darwin-x64',- 'composio-linux-x64',- 'composio-linux-aarch64',-];-export function packageBinaries() {return Effect.gen(function* () {const entries = yield* Effect.tryPromise(() => readdir(BINARIES_DIR));@@ -50,9 +48,14 @@ export function packageBinaries() {return;}- const companionRelativePaths =- yield* collectExpectedRunCompanionAssetRelativePaths(COMPANIONS_DIR);- for (const relativePath of companionRelativePaths) {+ // One packaging host produces all four archives, so `COMPANIONS_DIR` must hold+ // every platform's codex-acp binary before packaging starts. Validate that full+ // set up front; each archive then receives only the slice it can execute.+ const allCompanionRelativePaths = yield* collectExpectedRunCompanionAssetRelativePaths(+ COMPANIONS_DIR,+ { staticAssetRelativePaths: RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS }+ );+ for (const relativePath of allCompanionRelativePaths) {const companionPath = path.join(COMPANIONS_DIR, relativePath);const exists = yield* Effect.tryPromise(() => Bun.file(companionPath).exists());if (!exists) {@@ -67,6 +70,14 @@ export function packageBinaries() {yield* Console.log(`Packaging ${binaries.length} binaries...`);for (const binary of binaries) {+ // An archive's `composio` binary is already platform-specific, so a foreign+ // codex-acp binary inside it could never run. Ship only this platform's.+ const target = yield* releaseArtifactTargetFor(binary);+ const companionRelativePaths = archiveCompanionRelativePaths({+ allRelativePaths: allCompanionRelativePaths,+ target,+ });+const binaryPath = path.join(BINARIES_DIR, binary);const zipPath = path.join(BINARIES_DIR, `${binary}.zip`);const absoluteZipPath = path.resolve(zipPath);diff --git a/ts/packages/cli/src/analytics/dispatch.ts b/ts/packages/cli/src/analytics/dispatch.tsindex b56a8c49c..2273ccb06 100644--- a/ts/packages/cli/src/analytics/dispatch.ts+++ b/ts/packages/cli/src/analytics/dispatch.ts@@ -13,12 +13,16 @@ import {Schema,} from 'effect';import * as constants from 'src/constants';+import { APP_CONFIG } from 'src/effects/app-config';import { getDetachedWorkerSpawnArgs, spawnDetached } from 'src/services/detached-process';+import { extendConfigProvider } from 'src/services/config';import { atomicWriteFileString } from 'src/utils/atomic-write';import { sha256Hex } from 'src/utils/checksums';import { djb2Hash } from 'src/utils/djb2';import { NodeOs } from 'src/services/node-os';import { TerminalUI } from 'src/services/terminal-ui';+import { isTelemetryDebugEnabled, TELEMETRY_DEBUG_FLAG } from 'src/services/runtime-flags';+import { CliRunId } from 'src/services/runtime-cli-context';import type { AnalyticsEnvelope, TrackEvent } from './types';const INTERNAL_ANALYTICS_WORKER_FLAG = '__analytics-worker';@@ -79,10 +83,6 @@ const configuredString = (value: Option.Option<string>): string | undefined =>Option.getOrUndefined);-const telemetryDebugEnabled = environmentProvider.load(- booleanWithDefault('COMPOSIO_CLI_TELEMETRY_DEBUG')-);-const analyticsDisabled = environmentProvider.load(Config.all({cliTelemetryDisabled: booleanWithDefault('COMPOSIO_CLI_TELEMETRY_DISABLED'),@@ -140,7 +140,7 @@ const encodePrettyJson = Schema.encode(prettyJsonFromString);const telemetryDebugLog = (label: string, payload: Record<string, unknown>) =>Effect.gen(function* () {- if (!(yield* telemetryDebugEnabled)) {+ if (!(yield* isTelemetryDebugEnabled)) {return;}@@ -523,8 +523,9 @@ const getCliCodactFailuresEndpoint = Effect.map(readApiBaseUrl, baseUrl =>// Delivery is best effort: a failed spawn is swallowed, never surfaced.const spawnWorker = (command: string, args: ReadonlyArray<string>) =>Effect.gen(function* () {- const debugEnabled = yield* telemetryDebugEnabled;- return yield* spawnDetached(command, args, { inheritStderr: debugEnabled }).pipe(+ const debugEnabled = yield* isTelemetryDebugEnabled;+ const workerArgs = debugEnabled ? [...args, TELEMETRY_DEBUG_FLAG] : args;+ return yield* spawnDetached(command, workerArgs, { inheritStderr: debugEnabled }).pipe(Effect.as(true),Effect.catchTag('services/DetachedProcessSpawnError', () => Effect.succeed(false)));@@ -563,7 +564,7 @@ const captureToPostHog = (envelope: AnalyticsEnvelope) =>);const response = yield* httpClient.execute(request);const responseOk = response.status >= 200 && response.status < 300;- const debugEnabled = yield* telemetryDebugEnabled;+ const debugEnabled = yield* isTelemetryDebugEnabled;const responseBody = !responseOk && debugEnabled ? yield* response.text : undefined;yield* telemetryDebugLog(@@ -592,19 +593,22 @@ type CliInvocationContext = {readonly parentRunId?: string;};-const getCliInvocationContext = environmentProvider- .load(+// The COMPOSIO_CLI_PARENT_RUN_ID handshake only exists in processes `composio run` spawned. The+// root run process holds its freshly minted id in the CliRunId service instead, so failures it+// reports carry the same run id its children stamp from the environment.+const getCliInvocationContext = Effect.gen(function* () {+ const environment = yield* environmentProvider.pipe(extendConfigProvider).load(Config.all({- origin: optionalString('COMPOSIO_CLI_INVOCATION_ORIGIN'),- parentRunId: optionalString('COMPOSIO_CLI_PARENT_RUN_ID'),+ origin: APP_CONFIG.CLI_INVOCATION_ORIGIN,+ parentRunId: APP_CONFIG.CLI_PARENT_RUN_ID,})- )- .pipe(- Effect.map(({ origin, parentRunId }) => ({- origin: configuredString(origin),- parentRunId: configuredString(parentRunId),- })));+ const mintedRunId = Option.flatten(yield* Effect.serviceOption(CliRunId));+ return {+ origin: environment.origin,+ parentRunId: environment.parentRunId ?? Option.getOrUndefined(mintedRunId),+ };+});export const createCliCodactFailureBody = (failure: CliCodactFailure,@@ -658,7 +662,7 @@ const captureToComposioCodactFailures = (failure: CliCodactFailure) =>);const response = yield* httpClient.execute(request);const responseOk = response.status >= 200 && response.status < 300;- const debugEnabled = yield* telemetryDebugEnabled;+ const debugEnabled = yield* isTelemetryDebugEnabled;const responseBody = !responseOk && debugEnabled ? yield* response.text : undefined;yield* telemetryDebugLog(responseOk ? 'codact_delivery_succeeded' : 'codact_delivery_failed', {diff --git a/ts/packages/cli/src/analytics/events.ts b/ts/packages/cli/src/analytics/events.tsindex 22564b19e..4671f111b 100644--- a/ts/packages/cli/src/analytics/events.ts+++ b/ts/packages/cli/src/analytics/events.ts@@ -1,6 +1,7 @@import type { CliCommandTelemetryContext, TrackEvent } from './types';import { APP_VERSION } from 'src/constants';import { inferSkillReleaseChannel } from 'src/effects/install-skill';+import type { CliInvocationContext } from 'src/services/runtime-cli-context';import { ToolInputValidationError } from 'src/services/tool-input-validation';import { guessToolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';@@ -179,13 +180,6 @@ const TOOL_VALIDATION_CODES: ReadonlySet<number> = new Set([1607, // Upstream_ValidationError3702, // ComposioTools_ValidationError]);-// A parent `composio run` process hands these values to child CLI invocations through the-// environment at spawn time; the event builders below are plain synchronous functions that-// run outside any Effect context, so effect/Config is not available here.-// eslint-disable-next-line eslint-js/no-restricted-syntax -- spawn-time env handoff read outside Effect-const getInvocationOrigin = (): string => process.env.COMPOSIO_CLI_INVOCATION_ORIGIN ?? 'cli';-// eslint-disable-next-line eslint-js/no-restricted-syntax -- spawn-time env handoff read outside Effect-const getParentRunId = (): string | undefined => process.env.COMPOSIO_CLI_PARENT_RUN_ID;const extractCommandPath = (argv: ReadonlyArray<string>): string => {const commandTokens: string[] = [];@@ -306,9 +300,9 @@ const getExecuteCommandProperties = (context: CliCommandTelemetryContext) => {const slug = getTrailingPositionals(context)[0];return {source: 'cli',- invocation_origin: getInvocationOrigin(),- parent_run_id: getParentRunId(),- parent_command: getParentRunId() ? 'run' : undefined,+ invocation_origin: context.invocationOrigin,+ parent_run_id: context.parentRunId,+ parent_command: context.parentRunId ? 'run' : undefined,cli_version: context.cliVersion,command_path: context.commandPath,duration_ms: Date.now() - context.startedAt,@@ -332,9 +326,9 @@ const getSearchCommandProperties = (context: CliCommandTelemetryContext) => {const query = getTrailingPositionals(context)[0] ?? '';return {source: 'cli',- invocation_origin: getInvocationOrigin(),- parent_run_id: getParentRunId(),- parent_command: getParentRunId() ? 'run' : undefined,+ invocation_origin: context.invocationOrigin,+ parent_run_id: context.parentRunId,+ parent_command: context.parentRunId ? 'run' : undefined,cli_version: context.cliVersion,command_path: context.commandPath,duration_ms: Date.now() - context.startedAt,@@ -349,9 +343,9 @@ const getLinkCommandProperties = (context: CliCommandTelemetryContext) => {const firstPositional = getTrailingPositionals(context)[0];return {source: 'cli',- invocation_origin: getInvocationOrigin(),- parent_run_id: getParentRunId(),- parent_command: getParentRunId() ? 'run' : undefined,+ invocation_origin: context.invocationOrigin,+ parent_run_id: context.parentRunId,+ parent_command: context.parentRunId ? 'run' : undefined,cli_version: context.cliVersion,command_path: context.commandPath,duration_ms: Date.now() - context.startedAt,@@ -364,7 +358,7 @@ const getLinkCommandProperties = (context: CliCommandTelemetryContext) => {const getRunCommandProperties = (context: CliCommandTelemetryContext) => ({source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: context.invocationOrigin,run_id: context.runId,cli_version: context.cliVersion,command_path: context.commandPath,@@ -380,7 +374,7 @@ const getRunCommandProperties = (context: CliCommandTelemetryContext) => ({const getInstallCommandProperties = (context: CliCommandTelemetryContext) => ({source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: context.invocationOrigin,cli_version: context.cliVersion,command_path: context.commandPath,duration_ms: Date.now() - context.startedAt,@@ -390,7 +384,7 @@ const getInstallCommandProperties = (context: CliCommandTelemetryContext) => ({const getSetupCommandProperties = (context: CliCommandTelemetryContext) => ({source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: context.invocationOrigin,cli_version: context.cliVersion,command_path: context.commandPath,duration_ms: Date.now() - context.startedAt,@@ -403,7 +397,7 @@ const getSetupCommandProperties = (context: CliCommandTelemetryContext) => ({const getLoginCommandProperties = (context: CliCommandTelemetryContext) => ({source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: context.invocationOrigin,cli_version: context.cliVersion,command_path: context.commandPath,duration_ms: Date.now() - context.startedAt,@@ -415,7 +409,7 @@ const getLoginCommandProperties = (context: CliCommandTelemetryContext) => ({const getLogoutCommandProperties = (context: CliCommandTelemetryContext) => ({source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: context.invocationOrigin,cli_version: context.cliVersion,command_path: context.commandPath,duration_ms: Date.now() - context.startedAt,@@ -423,7 +417,7 @@ const getLogoutCommandProperties = (context: CliCommandTelemetryContext) => ({const getProxyCommandProperties = (context: CliCommandTelemetryContext) => ({source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: context.invocationOrigin,cli_version: context.cliVersion,command_path: context.commandPath,duration_ms: Date.now() - context.startedAt,@@ -470,13 +464,22 @@ export const getExecuteCommandToolSlug = (): string | undefined =>isExecuteCommand(context.commandPath) ? getTrailingPositionals(context)[0] : undefined;+/**+ * Builds the telemetry context of the running command.+ *+ * `invocation` is read from config by the caller and stamped here so every synchronous event+ * builder below takes the origin as an input rather than consulting process-wide state.+ */export const createCliCommandTelemetryContext = (argv: ReadonlyArray<string>,cliVersion: string,- terminal: { readonly stdoutIsTTY: boolean; readonly stderrIsTTY: boolean }+ terminal: { readonly stdoutIsTTY: boolean; readonly stderrIsTTY: boolean },+ invocation: CliInvocationContext): CliCommandTelemetryContext => ({argv,cliVersion,+ invocationOrigin: invocation.invocationOrigin,+ parentRunId: invocation.parentRunId,commandPath: extractCommandPath(argv),flagNames: extractFlagNames(argv),stdoutIsTTY: terminal.stdoutIsTTY,@@ -484,15 +487,14 @@ export const createCliCommandTelemetryContext = (startedAt: Date.now(),runId:extractCommandPath(argv) === 'run'- ? // eslint-disable-next-line eslint-js/no-restricted-syntax -- spawn-time env handoff from parent run- (process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID())+ ? (invocation.parentRunId ?? crypto.randomUUID()): undefined,});const getCliCommandInvokedEvent = (context: CliCommandTelemetryContext): TrackEvent =>buildEvent(CLI_ANALYTICS_EVENTS.CLI_COMMAND_INVOKED, {source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: context.invocationOrigin,cli_version: context.cliVersion,command_path: context.commandPath,flag_names: context.flagNames,@@ -504,7 +506,7 @@ const getCliCommandInvokedEvent = (context: CliCommandTelemetryContext): TrackEvconst getCliCommandSucceededEvent = (context: CliCommandTelemetryContext): TrackEvent =>buildEvent(CLI_ANALYTICS_EVENTS.CLI_COMMAND_SUCCEEDED, {source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: context.invocationOrigin,cli_version: context.cliVersion,command_path: context.commandPath,duration_ms: Date.now() - context.startedAt,@@ -517,7 +519,7 @@ const getCliCommandFailedEvent = (): TrackEvent =>buildEvent(CLI_ANALYTICS_EVENTS.CLI_COMMAND_FAILED, {source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: context.invocationOrigin,cli_version: context.cliVersion,command_path: context.commandPath,duration_ms: Date.now() - context.startedAt,@@ -640,6 +642,7 @@ export const getPluginLifecycleSucceededEvent = (params: {readonly operation: 'setup' | 'uninstall';readonly target: 'claude' | 'codex';readonly action: 'installed' | 'enabled' | 'configured' | 'uninstalled';+ readonly invocationOrigin: string;readonly cliVersion: string;}): TrackEvent =>buildEvent(@@ -648,7 +651,7 @@ export const getPluginLifecycleSucceededEvent = (params: {: CLI_ANALYTICS_EVENTS.CLI_PLUGIN_SETUP_SUCCEEDED,{source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: params.invocationOrigin,cli_version: params.cliVersion,command_path: 'setup',operation: params.operation,@@ -662,11 +665,12 @@ export const getPluginLifecycleFailedEvent = (params: {readonly target: 'claude' | 'codex';readonly phase: 'install' | 'uninstall';readonly error: unknown;+ readonly invocationOrigin: string;readonly cliVersion: string;}): TrackEvent =>buildEvent(CLI_ANALYTICS_EVENTS.CLI_PLUGIN_SETUP_FAILED, {source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: params.invocationOrigin,cli_version: params.cliVersion,command_path: 'setup',operation: params.operation,@@ -684,11 +688,12 @@ export const getSetupHostDetectedEvent = (params: {readonly hostVersion?: string;readonly unsupportedReasonCode?:'codex_too_old' | 'no_json_inspection' | 'host_command_failed' | 'unknown';+ readonly invocationOrigin: string;readonly cliVersion: string;}): TrackEvent =>buildEvent(CLI_ANALYTICS_EVENTS.CLI_SETUP_HOST_DETECTED, {source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: params.invocationOrigin,cli_version: params.cliVersion,command_path: 'setup',operation: params.operation,@@ -703,11 +708,12 @@ export const getSetupHostDetectedEvent = (params: {export const getSetupCancelledEvent = (params: {readonly operation: 'setup' | 'uninstall';readonly requestedTarget: 'auto' | 'claude' | 'codex' | 'all';+ readonly invocationOrigin: string;readonly cliVersion: string;}): TrackEvent =>buildEvent(CLI_ANALYTICS_EVENTS.CLI_SETUP_CANCELLED, {source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: params.invocationOrigin,cli_version: params.cliVersion,command_path: 'setup',operation: params.operation,@@ -718,11 +724,12 @@ export const getSetupCancelledEvent = (params: {export const getSetupSkippedEvent = (params: {readonly operation: 'setup' | 'uninstall';readonly requestedTarget: 'auto' | 'claude' | 'codex' | 'all';+ readonly invocationOrigin: string;readonly cliVersion: string;}): TrackEvent =>buildEvent(CLI_ANALYTICS_EVENTS.CLI_SETUP_SKIPPED, {source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: params.invocationOrigin,cli_version: params.cliVersion,command_path: 'setup',operation: params.operation,@@ -735,6 +742,7 @@ export const getToolExecuteValidationFailedEvent = (params: {readonly toolkitSlug?: string;readonly args: Record<string, unknown>;readonly error: ToolInputValidationError;+ readonly invocationOrigin: string;readonly surface: 'root' | 'dev';readonly projectMode: 'consumer' | 'developer';readonly stage: 'dry_run' | 'validation' | 'execution';@@ -743,7 +751,7 @@ export const getToolExecuteValidationFailedEvent = (params: {}): TrackEvent =>buildEvent(CLI_ANALYTICS_EVENTS.CLI_TOOL_INVOCATION_VALIDATION_FAILED, {source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: params.invocationOrigin,tool_slug: params.toolSlug,toolkit_slug: params.toolkitSlug ?? guessToolkitFromToolSlug(params.toolSlug),surface: params.surface,@@ -785,6 +793,7 @@ export const getToolExecuteToolNotFoundEvent = (params: {readonly toolSlug: string;readonly toolkitSlug?: string;readonly args: Record<string, unknown>;+ readonly invocationOrigin: string;readonly surface: 'root' | 'dev';readonly projectMode: 'consumer' | 'developer';readonly stage: 'schema_fetch' | 'dry_run' | 'execution';@@ -797,7 +806,7 @@ export const getToolExecuteToolNotFoundEvent = (params: {}): TrackEvent =>buildEvent(CLI_ANALYTICS_EVENTS.CLI_TOOL_INVOCATION_TOOL_NOT_FOUND, {source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: params.invocationOrigin,tool_slug: params.toolSlug,toolkit_slug: params.toolkitSlug ?? guessToolkitFromToolSlug(params.toolSlug),surface: params.surface,@@ -815,6 +824,7 @@ export const getToolExecuteFailedEvent = (params: {readonly toolSlug: string;readonly toolkitSlug?: string;readonly args: Record<string, unknown>;+ readonly invocationOrigin: string;readonly surface: 'root' | 'dev';readonly projectMode: 'consumer' | 'developer';readonly stage: 'schema_fetch' | 'dry_run' | 'execution';@@ -829,7 +839,7 @@ export const getToolExecuteFailedEvent = (params: {}): TrackEvent =>buildEvent(CLI_ANALYTICS_EVENTS.CLI_TOOL_INVOCATION_FAILED, {source: 'cli',- invocation_origin: getInvocationOrigin(),+ invocation_origin: params.invocationOrigin,tool_slug: params.toolSlug,toolkit_slug: params.toolkitSlug ?? guessToolkitFromToolSlug(params.toolSlug),surface: params.surface,diff --git a/ts/packages/cli/src/analytics/types.ts b/ts/packages/cli/src/analytics/types.tsindex a92dc73e1..e7bda9f50 100644--- a/ts/packages/cli/src/analytics/types.ts+++ b/ts/packages/cli/src/analytics/types.ts@@ -15,6 +15,10 @@ export type AnalyticsEnvelope = {export type CliCommandTelemetryContext = {readonly argv: ReadonlyArray<string>;readonly cliVersion: string;+ /** Who invoked this CLI process (`cli`, `run`, `installer`, …). */+ readonly invocationOrigin: string;+ /** Run id of the `composio run` that spawned this process, when there is one. */+ readonly parentRunId: string | undefined;readonly commandPath: string;readonly flagNames: ReadonlyArray<string>;readonly stdoutIsTTY: boolean;diff --git a/ts/packages/cli/src/bin.ts b/ts/packages/cli/src/bin.tsindex 1b3a0645a..ceaa3cae5 100644--- a/ts/packages/cli/src/bin.ts+++ b/ts/packages/cli/src/bin.ts@@ -5,35 +5,25 @@ import { BunFileSystem, BunPath, BunRuntime } from '@effect/platform-bun';import { isBackgroundWorkerInvocation, runBackgroundWorkerFromArgv } from 'src/analytics/dispatch';import { NodeOs } from 'src/services/node-os';import { TerminalUILive } from 'src/services/terminal-ui';+import { stripTelemetryDebugFlag, telemetryDebugModeLayer } from 'src/services/runtime-flags';-const TELEMETRY_DEBUG_FLAG = '--telemetry-debug';-const CLI_TELEMETRY_DEBUG_ENV_VAR = 'COMPOSIO_CLI_TELEMETRY_DEBUG';+const bootstrap = stripTelemetryDebugFlag(process.argv);+process.argv = [...bootstrap.argv];-const stripTelemetryDebugFlag = (argv: ReadonlyArray<string>): string[] => {- const normalizedArgv = [...argv];- const flagIndex = normalizedArgv.indexOf(TELEMETRY_DEBUG_FLAG);- if (flagIndex < 0) {- return normalizedArgv;- }+const workerLayers = Layer.mergeAll(+ BunFileSystem.layer,+ BunPath.layer,+ FetchHttpClient.layer,+ NodeOs.Default,+ TerminalUILive+);- normalizedArgv.splice(flagIndex, 1);- // Bootstrap runs before the Effect runtime and ConfigProvider exist; the stripped flag is- // persisted as an env var so later effect/Config reads and child processes observe it.- // eslint-disable-next-line eslint-js/no-restricted-syntax -- pre-runtime env write during bootstrap- process.env[CLI_TELEMETRY_DEBUG_ENV_VAR] = 'true';- return normalizedArgv;-};--if (isBackgroundWorkerInvocation(process.argv)) {- runBackgroundWorkerFromArgv(process.argv).pipe(+if (isBackgroundWorkerInvocation(bootstrap.argv)) {+ runBackgroundWorkerFromArgv(bootstrap.argv).pipe(Effect.provide(- Layer.mergeAll(- BunFileSystem.layer,- BunPath.layer,- FetchHttpClient.layer,- NodeOs.Default,- TerminalUILive- )+ bootstrap.telemetryDebug+ ? Layer.merge(workerLayers, telemetryDebugModeLayer(true))+ : workerLayers),effect =>BunRuntime.runMain(effect, {@@ -42,6 +32,7 @@ if (isBackgroundWorkerInvocation(process.argv)) {}));} else {- process.argv = stripTelemetryDebugFlag(process.argv);- void import('./cli-main');+ void import('./cli-main').then(({ runCli }) =>+ runCli({ telemetryDebug: bootstrap.telemetryDebug })+ );}diff --git a/ts/packages/cli/src/cli-main.ts b/ts/packages/cli/src/cli-main.tsindex 2b655af48..d830251a4 100644--- a/ts/packages/cli/src/cli-main.ts+++ b/ts/packages/cli/src/cli-main.ts@@ -5,7 +5,7 @@ import { CliConfig, HelpDoc, ValidationError } from '@effect/cli';import { FetchHttpClient } from '@effect/platform';import { BunContext, BunRuntime, BunFileSystem, BunPath } from '@effect/platform-bun';import type { Teardown } from '@effect/platform/Runtime';-import { buildRootCommand, runWithConfig } from 'src/commands';+import { buildRootCommand, runWithConfig, type RootCommandBootstrap } from 'src/commands';import { collectValueOptionNames } from 'src/commands/command-introspection';import { matchCommandFromArgv, getCommandHelpText } from 'src/commands/root-help';import * as constants from 'src/constants';@@ -48,6 +48,9 @@ import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overriimport { SetupSkillInstaller } from 'src/services/setup-skill-installer';import { SetupCommandError } from 'src/services/setup';import { ShellSetupAbortError } from 'src/commands/install.cmd';+import { MissingRunSourceError } from 'src/commands/run.cmd';+import { cliInvocationContext } from 'src/services/runtime-cli-context';+import { telemetryDebugModeLayer } from 'src/services/runtime-flags';// Layer is contravariant in ROut and covariant in E, so `never`/`unknown` accept any// produced context and error type while still pinning the requirements (RIn) to `never`.@@ -146,15 +149,19 @@ const layers = Layer.mergeAll(export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: number) => void) => {const shouldFail = Exit.isFailure(exit) && !Cause.isInterruptedOnly(exit.cause);- const errorCode = Number(process.exitCode ?? 1);- onExit(shouldFail ? errorCode : 0);+ // A command that proxies another process (`composio run`) reports its status by assigning+ // `process.exitCode`, so honor that on every path. It matters most on interrupt: the runtime+ // force-exits with whatever code teardown yields once a signal has been received, which would+ // otherwise turn a cancelled run into a success.+ onExit(Number(process.exitCode ?? (shouldFail ? 1 : 0)));};-const runWithArgs = Effect.flatMap(runWithConfig, run => run(process.argv)) satisfies Effect.Effect<- void,- unknown,- unknown->;+const runWithArgs = (bootstrap: RootCommandBootstrap) =>+ Effect.flatMap(runWithConfig, run => run(process.argv, bootstrap)) satisfies Effect.Effect<+ void,+ unknown,+ unknown+ >;const runWithTelemetry = Effect.gen(function* () {const ui = yield* TerminalUI;@@ -162,21 +169,25 @@ const runWithTelemetry = Effect.gen(function* () {const version = yield* getVersion;configureCliAnalyticsReleaseVersion(version);- const baseTelemetryContext = createCliCommandTelemetryContext(process.argv, version, terminal);+ const baseTelemetryContext = createCliCommandTelemetryContext(+ process.argv,+ version,+ terminal,+ yield* cliInvocationContext+ );const executeToolSlug = getExecuteCommandToolSlug(baseTelemetryContext);const commandTelemetryContext =executeToolSlug === undefined? baseTelemetryContext: { ...baseTelemetryContext, toolkitSlug: yield* toolkitFromToolSlug(executeToolSlug) };- if (commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId) {- // effect/Config is read-only; the run id must be written into the environment so the run- // command and the child processes it spawns observe the same telemetry run id.- // eslint-disable-next-line eslint-js/no-restricted-syntax -- env write propagates run id to children- process.env.COMPOSIO_CLI_PARENT_RUN_ID = commandTelemetryContext.runId;- }-+ // `composio run` mints its run id here so the lifecycle events and the id the spawned script+ // inherits are the same value; every other command leaves it unset.+ const bootstrap: RootCommandBootstrap =+ commandTelemetryContext.commandPath === 'run' && commandTelemetryContext.runId+ ? { runId: commandTelemetryContext.runId }+ : {};return yield* trackCliEventEffect(getPrimaryLifecycleInvokedEvent(commandTelemetryContext)).pipe(- Effect.andThen(runWithArgs),+ Effect.andThen(runWithArgs(bootstrap)),Effect.scoped,Effect.mapError(error =>ValidationError.isValidationError(error) ? error : mapOnlyComposioOverrideError({ error })@@ -192,7 +203,15 @@ const runWithTelemetry = Effect.gen(function* () {);});-showUpdateNotice.pipe(+/**+ * Values `src/bin.ts` resolved before the Effect runtime existed and hands to it here.+ */+export type CliBootstrapOptions = {+ /** `--telemetry-debug` was on the command line, and was stripped from argv before parsing. */+ readonly telemetryDebug: boolean;+};++const cliProgram = showUpdateNotice.pipe(Effect.andThen(showPluginAcquisitionHint(process.argv)),Effect.andThen(runWithTelemetry),Effect.catchIf(ValidationError.isValidationError, error => {@@ -242,6 +261,17 @@ showUpdateNotice.pipe(process.exitCode = 1;})),+ // A bare `composio run` is a usage mistake, not a broken invariant: print the one-line fix and+ // exit non-zero instead of routing it through the defect reporter below.+ Effect.catchIf(+ (error): error is MissingRunSourceError => error instanceof MissingRunSourceError,+ error =>+ Effect.gen(function* () {+ const ui = yield* TerminalUI;+ yield* ui.error(error.message);+ process.exitCode = 1;+ })+ ),Effect.catchIf((error): error is ShellSetupAbortError => error instanceof ShellSetupAbortError,// `composio install` already printed the abort reason; the typed failure@@ -296,6 +326,15 @@ showUpdateNotice.pipe(})),Effect.provide(layers),- Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive)),- BunRuntime.runMain({ teardown })+ Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive)));++export const runCli = (options: CliBootstrapOptions): void => {+ cliProgram.pipe(+ // Only provided when the flag was actually present: without it telemetry debugging falls back+ // to `COMPOSIO_CLI_TELEMETRY_DEBUG`.+ effect =>+ options.telemetryDebug ? Effect.provide(effect, telemetryDebugModeLayer(true)) : effect,+ BunRuntime.runMain({ teardown })+ );+};diff --git a/ts/packages/cli/src/commands/index.ts b/ts/packages/cli/src/commands/index.tsindex 10ec3d9df..198802ba4 100644--- a/ts/packages/cli/src/commands/index.ts+++ b/ts/packages/cli/src/commands/index.ts@@ -1,5 +1,4 @@-import process from 'node:process';-import { Array as Arr, Data, Effect, HashSet, Option } from 'effect';+import { Array as Arr, Data, Effect, HashSet, Layer, Option } from 'effect';import { Command, HelpDoc, ValidationError } from '@effect/cli';import {hasCommandName,@@ -45,11 +44,12 @@ import { configCmd } from './config/config.cmd';import { rootConnectionsCmd } from './connections/connections.cmd';import { agentCmd } from './agent/agent.cmd';import { renderCommandHintGraph } from 'src/services/command-hints';-import { resetRuntimeDebugFlags, setRuntimeDebugFlags } from 'src/services/runtime-debug-flags';+import { cliDebugFlagsLayer, type CliDebugFlagOverrides } from 'src/services/runtime-flags';+import { cliRunIdLayer } from 'src/services/runtime-cli-context';import { ComposioCliUserConfig } from 'src/services/cli-user-config';import { ComposioUserContext } from 'src/services/user-context';import { TerminalUI } from 'src/services/terminal-ui';-import { detectMaster } from 'src/services/master-detector';+import { detectMasterFromHost } from 'src/services/master-detector';import {formatResolveCommandProjectError,resolveCommandProject,@@ -285,7 +285,16 @@ const parseBooleanFlag = (argument: string, name: string): Option.Option<booleanreturn argument === `${name}=false` ? Option.some(false) : Option.none();};-const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {+/**+ * Splits the hidden debug flags off argv and returns their parsed values.+ *+ * The values are inputs to the command that follows — `src/commands/index.ts` provides them as+ * `CliDebugFlags` — rather than process-wide state, so an explicit `--perf-debug=false` on one+ * invocation cannot leak into the next.+ */+const normalizeHiddenDebugFlags = (+ argv: ReadonlyArray<string>+): { readonly argv: ReadonlyArray<string>; readonly overrides: CliDebugFlagOverrides } => {const retainedArgs: Array<string> = [];let perfDebug: boolean | undefined;let toolDebug: boolean | undefined;@@ -310,22 +319,10 @@ const normalizeHiddenDebugFlags = (argv: ReadonlyArray<string>): ReadonlyArray<sretainedArgs.push(argument);}- resetRuntimeDebugFlags();- setRuntimeDebugFlags({- ...(perfDebug === undefined ? {} : { perfDebug }),- ...(toolDebug === undefined ? {} : { toolDebug }),- });- // The hidden --acp-only flag is stripped from argv before @effect/cli parses it, so its value- // travels to run.cmd.ts through the environment; effect/Config cannot write or delete env vars.- if (acpOnly === undefined) {- // eslint-disable-next-line eslint-js/no-restricted-syntax -- env delete clears a stale hidden-flag value- delete process.env.COMPOSIO_RUN_ACP_ONLY;- } else {- // eslint-disable-next-line eslint-js/no-restricted-syntax -- env write hands the stripped flag to run.cmd- process.env.COMPOSIO_RUN_ACP_ONLY = acpOnly ? '1' : '0';- }-- return Arr.appendAll(Arr.take(argv, 2), retainedArgs);+ return {+ argv: Arr.appendAll(Arr.take(argv, 2), retainedArgs),+ overrides: { perfDebug, toolDebug, acpOnly },+ };};const isRootHelp = (argv: ReadonlyArray<string>): boolean => {@@ -435,11 +432,11 @@ const printDebugApiInfo = Effect.gen(function* () {);});-const printDetectedMaster = Effect.suspend(() =>- Effect.flatMap(TerminalUI, ui =>- ui.output(JSON.stringify({ master: detectMaster() }, null, 2), { force: true })- )-);+const printDetectedMaster = Effect.gen(function* () {+ const ui = yield* TerminalUI;+ const master = yield* detectMasterFromHost;+ yield* ui.output(JSON.stringify({ master }, null, 2), { force: true });+});const printDevModeDisabled = Effect.gen(function* () {const ui = yield* TerminalUI;@@ -447,6 +444,16 @@ const printDevModeDisabled = Effect.gen(function* () {yield* ui.log.step('Run `composio dev --mode on` in an interactive terminal to enable it.');});+/**+ * Values the CLI bootstrap resolved before the root command runs and that the command tree needs+ * as an input. Empty for callers that drive the root command on their own (tests, `--install-skill`+ * style entry points), which is why every field is optional.+ */+export type RootCommandBootstrap = {+ /** Run id minted for a `composio run` invocation, shared with its telemetry events. */+ readonly runId?: string;+};+export const runWithConfig = Effect.gen(function* () {const cliUserConfig = yield* ComposioCliUserConfig;const visibility: CommandVisibility = {@@ -521,10 +528,10 @@ export const runWithConfig = Effect.gen(function* () {);};- return (argv: ReadonlyArray<string>) => {+ return (argv: ReadonlyArray<string>, bootstrap: RootCommandBootstrap = {}) => {const { argv: argvWithoutDangerouslyAllow, dangerouslyAllow } =normalizeDangerouslyAllowFlag(argv);- const normalizedArgv = normalizeHiddenDebugFlags(+ const { argv: normalizedArgv, overrides } = normalizeHiddenDebugFlags(normalizeListenStreamFlag(normalizeVersionShortFlag(argvWithoutDangerouslyAllow)));@@ -534,7 +541,8 @@ export const runWithConfig = Effect.gen(function* () {onNone: () => routeRootCommand(normalizedArgv, dangerouslyAllow),onSome: installSkill,})- )+ ),+ Effect.provide(Layer.merge(cliDebugFlagsLayer(overrides), cliRunIdLayer(bootstrap.runId))));};});diff --git a/ts/packages/cli/src/commands/install.cmd.ts b/ts/packages/cli/src/commands/install.cmd.tsindex e5f4f2949..d3f84c392 100644--- a/ts/packages/cli/src/commands/install.cmd.ts+++ b/ts/packages/cli/src/commands/install.cmd.ts@@ -2,6 +2,7 @@ import { Command, Options } from '@effect/cli';import { FileSystem, Path } from '@effect/platform';import type { PlatformError } from '@effect/platform/Error';import { Array as Arr, Config, ConfigProvider, Data, Effect, Option } from 'effect';+import { APP_CONFIG } from 'src/effects/app-config';import { ComposioCliUserConfig } from 'src/services/cli-user-config';import { NodeOs } from 'src/services/node-os';import { NodeProcess } from 'src/services/node-process';@@ -83,21 +84,10 @@ const COMPLETIONS_MARKER = '# Composio CLI completions';const UNSAFE_PATH_CHARS = /[`$"\\\n\r:]/;const isUnsafePath = (p: string): boolean => UNSAFE_PATH_CHARS.test(p);-// SHELL, PATH, and COMPOSIO_BIN_DIR are read from the literal environment: SHELL-// and PATH are POSIX-standard (no app prefix applies to them), and COMPOSIO_BIN_DIR-// is already the full env var name, not a suffix the app's `COMPOSIO_`-prefixing-// ambient config provider should prefix again. Read them from a raw provider-// instead (precedent: `src/analytics/dispatch.ts`'s `environmentProvider`).+// SHELL and PATH are POSIX-standard host variables, so the CLI's COMPOSIO_+// prefix does not apply to them.const environmentProvider = ConfigProvider.fromEnv();-/** Read an optional env var from the raw environment; provider errors die rather than fail the command. */-const readOptionalEnv = (name: string): Effect.Effect<string | undefined> =>- Effect.orDie(- environmentProvider.load(- Config.option(Config.string(name)).pipe(Config.map(Option.getOrUndefined))- )- );-/** Read an env var from the raw environment, falling back when unset. */const readEnvWithDefault = (name: string, fallback: string): Effect.Effect<string> =>Effect.orDie(environmentProvider.load(Config.string(name).pipe(Config.withDefault(fallback))));@@ -658,7 +648,7 @@ export const installShellIntegration = (params: {// Resolve the entry-point bin dir: explicit env, then a ~/.local/bin/composio// that is this executable, then the runtime executable's own directory.- const envBinDir = yield* readOptionalEnv('COMPOSIO_BIN_DIR');+ const envBinDir = yield* APP_CONFIG.BIN_DIR.pipe(Effect.orDie);const localBinDir = path.join(os.homedir, '.local', 'bin');const execPath = nodeProcess.execPath;const localBinComposioIsCurrentExecutable = yield* resolvesToCurrentExecutable(@@ -696,7 +686,7 @@ export const installShellIntegration = (params: {// prints the final action block itself. Keep the concise per-file status// lines but suppress the boxed restart hint so the CLI never prints a// competing instruction.- const invocationOrigin = yield* readOptionalEnv('COMPOSIO_CLI_INVOCATION_ORIGIN');+ const invocationOrigin = yield* APP_CONFIG.CLI_INVOCATION_ORIGIN.pipe(Effect.orDie);const installerOwnsFinalMessaging = invocationOrigin === 'installer';const shellEnv = yield* readEnvWithDefault('SHELL', '');diff --git a/ts/packages/cli/src/commands/run.cmd.ts b/ts/packages/cli/src/commands/run.cmd.tsindex 8ba12abf1..7b17f5e02 100644--- a/ts/packages/cli/src/commands/run.cmd.ts+++ b/ts/packages/cli/src/commands/run.cmd.ts@@ -1,20 +1,23 @@-// 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-import * as fs from 'node:fs';-// eslint-disable-next-line no-restricted-imports -- os.tmpdir and os.homedir locate the preload scratch directory and ~/.composio in the same synchronous helpers-import * as os from 'node:os';import process from 'node:process';-import { pathToFileURL } from 'node:url';import { Args, Command, Options } from '@effect/cli';-import { FileSystem, Path } from '@effect/platform';-import { Effect, Option } from 'effect';+import { Command as PlatformCommand, CommandExecutor, FileSystem, Path } from '@effect/platform';+import { Data, Deferred, Duration, Effect, Either, MutableRef, Option } from 'effect';import { ts } from 'ts-morph';import { APP_VERSION } from 'src/constants';+import { APP_CONFIG, UNPREFIXED_CONFIG } from 'src/effects/app-config';import { resolveCommandProject } from 'src/services/command-project';import { type RunHelperContext } from 'src/services/run-helpers-runtime';import { warmToolInputDefinitions } from 'src/services/tool-input-validation';import { ComposioUserContext } from 'src/services/user-context';-import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';-import { detectMaster } from 'src/services/master-detector';+import {+ debugFlagsToChildEnv,+ isAcpOnlyEnabled,+ isPerfDebugEnabled,+ isTelemetryDebugEnabled,+ isToolDebugEnabled,+} from 'src/services/runtime-flags';+import { detectMasterFromHost } from 'src/services/master-detector';+import { cliInvocationContext, CliRunId } from 'src/services/runtime-cli-context';import {repairMissingInstalledRunCompanionModules,resolveRunCompanionModulePath,@@ -25,6 +28,9 @@ import {} from 'src/services/cli-session-artifacts';import { USER_COMPOSIO_DIR } from 'src/constants';import { TerminalUI } from 'src/services/terminal-ui';+import { loadHostConfig } from 'src/services/config';+import { resolveCliConfigPath } from 'src/services/cli-user-config';+import { NodeOs } from 'src/services/node-os';const file = Options.text('file').pipe(Options.withAlias('f'),@@ -152,24 +158,26 @@ export const wrapFileSourceForRun = (source: string): string => {export const inferCliInvocationPrefix = (path: Path.Path,argv: ReadonlyArray<string> = process.argv-): ReadonlyArray<string> => {- const entrypoint = argv[1];- if (!entrypoint) {- return [process.execPath];- }+) =>+ Effect.gen(function* () {+ const entrypoint = argv[1];+ if (!entrypoint) {+ return [process.execPath];+ }- // Compiled Bun binaries report an internal $bunfs entrypoint which cannot be- // re-executed as a real filesystem path. In that case the binary itself is- // the CLI entrypoint.- if (entrypoint.startsWith('/$bunfs/')) {- return [process.execPath];- }+ // Compiled Bun binaries report an internal $bunfs entrypoint which cannot be+ // re-executed as a real filesystem path. In that case the binary itself is+ // the CLI entrypoint.+ if (entrypoint.startsWith('/$bunfs/')) {+ return [process.execPath];+ }- const resolvedEntrypoint = path.resolve(entrypoint);- return fs.existsSync(resolvedEntrypoint)- ? [process.execPath, resolvedEntrypoint]- : [process.execPath];-};+ const fs = yield* FileSystem.FileSystem;+ const resolvedEntrypoint = path.resolve(entrypoint);+ return (yield* fs.exists(resolvedEntrypoint))+ ? [process.execPath, resolvedEntrypoint]+ : [process.execPath];+ });type RunHelperModuleUrls = {readonly helpersRuntimeModuleUrl: string;@@ -179,14 +187,16 @@ const resolveRunHelperModuleUrls: Effect.Effect<RunHelperModuleUrls,never,FileSystem.FileSystem | Path.Path-> = Effect.map(- resolveRunCompanionModulePath({+> = Effect.gen(function* () {+ const path = yield* Path.Path;+ const modulePath = yield* resolveRunCompanionModulePath({callerImportMetaUrl: import.meta.url,execPath: process.execPath,relativeNoExtensionFromCaller: '../services/run-helpers-runtime',- }),- modulePath => ({ helpersRuntimeModuleUrl: pathToFileURL(modulePath).href })-);+ });+ const moduleUrl = yield* Effect.orDie(path.toFileUrl(modulePath));+ return { helpersRuntimeModuleUrl: moduleUrl.href };+});export const buildRunHelpersSource = (cliPrefix: ReadonlyArray<string>,context: RunHelperContext = {},@@ -203,40 +213,64 @@ const createRunHelpersPreloadFile = (cliPrefix: ReadonlyArray<string>,context: RunHelperContext,moduleUrls: RunHelperModuleUrls-) => {- const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-'));- const preloadPath = path.join(directory, 'globals.mjs');- const runOutputDir =- typeof context.runOutputDir === 'string' && context.runOutputDir.length > 0- ? context.runOutputDir- : path.join(directory, 'artifacts');- const runLogFilePath = path.join(runOutputDir, 'run.log');- const readAccessRoots = [- ...new Set(- [- ...(Array.isArray(context.readAccessRoots) ? context.readAccessRoots : []),- runOutputDir,- ].map(value => path.resolve(value))- ),- ];- fs.mkdirSync(runOutputDir, { recursive: true });- fs.writeFileSync(runLogFilePath, '', 'utf8');- fs.writeFileSync(- preloadPath,- buildRunHelpersSource(- cliPrefix,- {- ...context,- runOutputDir,- runLogFilePath,- readAccessRoots,- },- moduleUrls- ),- 'utf8'- );- return { directory, preloadPath, runOutputDir, runLogFilePath };-};+) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const os = yield* NodeOs;+ const directory = yield* fs.makeTempDirectoryScoped({+ directory: os.tmpdir,+ prefix: 'composio-run-',+ });+ const preloadPath = path.join(directory, 'globals.mjs');+ // The preload directory is scoped and removed when the run ends, but the run log and any+ // large tool outputs are advertised to the caller on stderr (`RUN_LOG_FILE=`) and must+ // outlive the process that printed them, so they get their own unscoped directory.+ const runOutputDir =+ typeof context.runOutputDir === 'string' && context.runOutputDir.length > 0+ ? context.runOutputDir+ : yield* fs.makeTempDirectory({ directory: os.tmpdir, prefix: 'composio-run-artifacts-' });+ const runLogFilePath = path.join(runOutputDir, 'run.log');+ const readAccessRoots = [+ ...new Set(+ [+ ...(Array.isArray(context.readAccessRoots) ? context.readAccessRoots : []),+ runOutputDir,+ ].map(value => path.resolve(value))+ ),+ ];+ yield* fs.makeDirectory(runOutputDir, { recursive: true });+ yield* fs.writeFileString(runLogFilePath, '');+ yield* fs.writeFileString(+ preloadPath,+ buildRunHelpersSource(+ cliPrefix,+ {+ ...context,+ runOutputDir,+ runLogFilePath,+ readAccessRoots,+ },+ moduleUrls+ )+ );+ return { directory, preloadPath, runOutputDir, runLogFilePath };+ });++/**+ * `composio run` was given neither inline code nor `--file`.+ *+ * An ordinary usage mistake rather than a broken invariant, so it is a typed failure with a+ * one-line message instead of a defect: the caller sees the fix, not a stack trace.+ */+export class MissingRunSourceError extends Data.TaggedError('commands/MissingRunSourceError')<{+ readonly message: string;+}> {}++const MISSING_RUN_SOURCE_MESSAGE = [+ 'Provide inline code or use --file to run a script file.',+ ` composio run 'console.log(1)'`,+ ' composio run --file ./script.ts',+].join('\n');export const buildRunCommand = ({path,@@ -250,59 +284,64 @@ export const buildRunCommand = ({args: ReadonlyArray<string>;preloadPath: string;preloadDirectory: string;-}) => {- // Use process.execPath directly — the child is spawned with BUN_BE_BUN=1- // which makes compiled Bun binaries act as a plain Bun runtime.- // Avoid the `run` subcommand entirely since Bun intercepts it as its own- // built-in; `bun --preload <file> <script>` works without it.- const base = [process.execPath, '--preload', preloadPath];- if (Option.isSome(file)) {- const filePath = path.resolve(file.value);- const wrapperFilePath = path.join(- path.dirname(filePath),- `.composio-run-${path.basename(preloadDirectory)}${path.extname(filePath) || '.ts'}`- );- fs.writeFileSync(- wrapperFilePath,- wrapFileSourceForRun(fs.readFileSync(filePath, 'utf8')),- 'utf8'- );- return {- cmd: [...base, wrapperFilePath, ...withArgDelimiter(args)],- cleanupPaths: [wrapperFilePath],- };- }+}) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ // Use process.execPath directly — the child is spawned with BUN_BE_BUN=1+ // which makes compiled Bun binaries act as a plain Bun runtime.+ // Avoid the `run` subcommand entirely since Bun intercepts it as its own+ // built-in; `bun --preload <file> <script>` works without it.+ const base = [process.execPath, '--preload', preloadPath];+ if (Option.isSome(file)) {+ const filePath = path.resolve(file.value);+ const wrapperFilePath = path.join(+ path.dirname(filePath),+ `.composio-run-${path.basename(preloadDirectory)}${path.extname(filePath) || '.ts'}`+ );+ yield* fs.writeFileString(+ wrapperFilePath,+ wrapFileSourceForRun(yield* fs.readFileString(filePath, 'utf8'))+ );+ return {+ cmd: [...base, wrapperFilePath, ...withArgDelimiter(args)],+ cleanupPaths: [wrapperFilePath],+ };+ }- const [inlineCode, ...scriptArgs] = args;- if (inlineCode) {- const wrappedInlineCode = [- '(async () => {',- wrapInlineCodeForRun(inlineCode),- '})().then((__composioResult) => {',- ' if (__composioResult !== undefined) {',- ' console.log(__composioResult);',- ' }',- '});',- ].join('\n');- return {- cmd: [...base, '--eval', wrappedInlineCode, ...withArgDelimiter(scriptArgs)],- cleanupPaths: [],- };- }+ const [inlineCode, ...scriptArgs] = args;+ if (inlineCode) {+ const wrappedInlineCode = [+ '(async () => {',+ wrapInlineCodeForRun(inlineCode),+ '})().then((__composioResult) => {',+ ' if (__composioResult !== undefined) {',+ ' console.log(__composioResult);',+ ' }',+ '});',+ ].join('\n');+ return {+ cmd: [...base, '--eval', wrappedInlineCode, ...withArgDelimiter(scriptArgs)],+ cleanupPaths: [],+ };+ }- throw new Error('Provide inline code or use --file to run a script file.');-};+ return yield* Effect.fail(new MissingRunSourceError({ message: MISSING_RUN_SOURCE_MESSAGE }));+ });const resolveRunHelperContext = () =>Effect.gen(function* () {const path = yield* Path.Path;+ const os = yield* NodeOs;const userContext = yield* ComposioUserContext;const apiKey = Option.getOrUndefined(userContext.data.apiKey);const orgId = Option.getOrUndefined(userContext.data.orgId);- const defaultComposioDir = path.join(os.homedir(), USER_COMPOSIO_DIR);- const configuredCacheDir =- // 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- process.env.COMPOSIO_CACHE_DIR?.trim() || process.env.CACHE_DIR?.trim() || defaultComposioDir;+ const defaultComposioDir = path.join(os.homedir, USER_COMPOSIO_DIR);+ // Honors the same COMPOSIO_CACHE_DIR-then-CACHE_DIR precedence the spawned+ // run-helpers child applies when locating its cache, so the sandbox read+ // roots below always include the directory the child actually uses.+ const composioCacheDir = yield* APP_CONFIG.CACHE_DIR;+ const hostCacheDir = yield* loadHostConfig(UNPREFIXED_CONFIG.CACHE_DIR);+ const configuredCacheDir = composioCacheDir || hostCacheDir || defaultComposioDir;const baseReadAccessRoots = [...new Set([defaultComposioDir, configuredCacheDir].map(value => path.resolve(value))),];@@ -312,6 +351,7 @@ const resolveRunHelperContext = () =>baseURL: userContext.data.baseURL,webURL: userContext.data.webURL,orgId,+ cliConfigPath: yield* resolveCliConfigPath,readAccessRoots: baseReadAccessRoots,} satisfies RunHelperContext;@@ -324,28 +364,22 @@ const resolveRunHelperContext = () =>return baseContext;}+ const sessionArtifactsDir = Option.getOrUndefined(+ yield* resolveCliSessionArtifacts({+ orgId,+ consumerUserId: consumerProject.value.consumerUserId,+ }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))+ );+return {...baseContext,consumerUserId: consumerProject.value.consumerUserId,consumerProjectId: consumerProject.value.projectId,consumerProjectName: consumerProject.value.projectName,- runOutputDir: Option.getOrUndefined(- yield* resolveCliSessionArtifacts({- orgId,- consumerUserId: consumerProject.value.consumerUserId,- }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))- ),+ runOutputDir: sessionArtifactsDir,readAccessRoots: [...new Set(- [- ...baseReadAccessRoots,- Option.getOrUndefined(- yield* resolveCliSessionArtifacts({- orgId,- consumerUserId: consumerProject.value.consumerUserId,- }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))- ),- ]+ [...baseReadAccessRoots, sessionArtifactsDir].filter((value): value is string => typeof value === 'string' && value.length > 0).map(value => path.resolve(value))),@@ -353,6 +387,102 @@ const resolveRunHelperContext = () =>} satisfies RunHelperContext;});+/**+ * Signals the CLI forwards to the script it runs. Anything else (SIGHUP, SIGQUIT, …) keeps the+ * platform default: the executor's finalizer still tears the child's process group down.+ */+const FORWARDED_SIGNALS = ['SIGINT', 'SIGTERM'] as const;++type ForwardedSignal = (typeof FORWARDED_SIGNALS)[number];++/**+ * How long the CLI waits for the script to finish its own signal handling before the platform+ * executor's finalizer sends SIGTERM to the process group.+ */+const CHILD_SIGNAL_GRACE_PERIOD = Duration.seconds(2);++class ChildSignalError extends Data.TaggedError('ChildSignalError')<{+ readonly pid: number;+ readonly signal: ForwardedSignal;+ readonly cause: unknown;+}> {}++/**+ * Sends `signal` to the child's process group and reports whether it was delivered.+ *+ * The @effect/platform executor spawns with `detached: true` on POSIX, so the script leads its+ * own process group and a negative pid is what reaches it (and anything it spawned). Delivery+ * fails with ESRCH when the group is already gone, which is a normal race, not a run failure.+ */+const signalChildProcessGroup = (pid: number, signal: ForwardedSignal): boolean =>+ Either.try({+ try: () => process.kill(-pid, signal),+ catch: cause => new ChildSignalError({ pid, signal, cause }),+ }).pipe(Either.getOrElse(() => false));++/**+ * Waits for the script to exit, giving up after `duration`.+ *+ * `Effect.timeout` cannot express this here: the wait runs in a release, while the fiber is+ * already interrupted, and the timer `Effect.timeout` forks as a child of that fiber is+ * interrupted along with it — leaving the wait hanging until the script exits on its own.+ * Daemon fibers are detached from the interrupted fiber, so their deadline still fires.+ */+const awaitChildExitWithin = (child: CommandExecutor.Process, duration: Duration.Duration) =>+ Effect.gen(function* () {+ const settled = yield* Deferred.make<void>();+ const complete = Deferred.succeed(settled, undefined);+ yield* Effect.forkDaemon(Effect.zipRight(Effect.ignore(child.exitCode), complete));+ yield* Effect.forkDaemon(Effect.zipRight(Effect.sleep(duration), complete));+ yield* Deferred.await(settled);+ });++/**+ * Forwards terminal signals to the running script for as long as it is alive.+ *+ * A terminal Ctrl-C only reaches the CLI's process group, so without this the script never+ * observes SIGINT and its `process.on('SIGINT')` cleanup never runs — it is reached later and+ * only as the executor's SIGTERM. Handlers are registered and removed with the scope so they+ * never leak into a later run.+ */+const forwardSignalsToChild = (child: CommandExecutor.Process) =>+ Effect.gen(function* () {+ const os = yield* NodeOs;+ // Windows has no process groups and the executor does not detach there.+ if (os.platform === 'win32') {+ return;+ }++ const pid = Number(child.pid);+ const forwarded = MutableRef.make(false);++ yield* Effect.acquireRelease(+ Effect.sync(() =>+ FORWARDED_SIGNALS.map(signal => {+ const listener = () => {+ if (signalChildProcessGroup(pid, signal)) {+ MutableRef.set(forwarded, true);+ }+ };+ process.on(signal, listener);+ return { signal, listener } as const;+ })+ ),+ listeners =>+ Effect.sync(() => {+ for (const { signal, listener } of listeners) {+ process.removeListener(signal, listener);+ }+ }).pipe(+ Effect.zipRight(+ MutableRef.get(forwarded)+ ? awaitChildExitWithin(child, CHILD_SIGNAL_GRACE_PERIOD)+ : Effect.void+ )+ )+ );+ });+export const runCmd = Command.make('run', {file,dryRun,@@ -429,13 +559,25 @@ export const runCmd = Command.make('run', {args,}) =>Effect.gen(function* () {+ // Checked before any setup work so a bare `composio run` neither creates a run-artifacts+ // directory nor advertises a log file for a script that will never start.+ if (Option.isNone(file) && !args[0]) {+ return yield* Effect.fail(+ new MissingRunSourceError({ message: MISSING_RUN_SOURCE_MESSAGE })+ );+ }++ const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;- // 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- const runId = process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID();- const perfDebug = isPerfDebugEnabled();- const toolDebug = isToolDebugEnabled();- // 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- const acpOnly = process.env.COMPOSIO_RUN_ACP_ONLY === '1';+ const invocation = yield* cliInvocationContext;+ const runId = Option.getOrElse(+ yield* CliRunId,+ () => invocation.parentRunId ?? crypto.randomUUID()+ );+ const perfDebug = yield* isPerfDebugEnabled;+ const toolDebug = yield* isToolDebugEnabled;+ const acpOnly = yield* isAcpOnlyEnabled;+ const telemetryDebug = yield* isTelemetryDebugEnabled;if (Option.isNone(file)) {const [inlineCode] = args;const preloadSlugs = extractInlineExecuteToolSlugs(inlineCode ?? '');@@ -450,9 +592,10 @@ export const runCmd = Command.make('run', {const helperContext: RunHelperContext = {...(yield* resolveRunHelperContext()),runId,- master: detectMaster(),+ master: yield* detectMasterFromHost,perfDebug,toolDebug,+ telemetryDebug,debug,logsOff,acpOnly,@@ -469,57 +612,74 @@ export const runCmd = Command.make('run', {Effect.mapError(error => new Error(error.message)),Effect.andThen(resolveRunHelperModuleUrls));- const preload = createRunHelpersPreloadFile(+ const cliPrefix = yield* inferCliInvocationPrefix(path);+ const preload = yield* createRunHelpersPreloadFile(path,- inferCliInvocationPrefix(path),+ cliPrefix,helperContext,runHelperModuleUrls);const ui = yield* TerminalUI;- let cleanupPaths: ReadonlyArray<string> = [];- // 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- try {- yield* appendCliSessionHistory({- orgId: helperContext.orgId,- consumerUserId: helperContext.consumerUserId,- entry: {- command: 'run',- status: 'start',- file: Option.getOrUndefined(file),- args,- debug,- },- }).pipe(Effect.catchAll(() => Effect.void));- yield* ui.error(`RUN_LOG_FILE=${preload.runLogFilePath}`);- const runCommand = buildRunCommand({- path,- file,+ yield* appendCliSessionHistory({+ orgId: helperContext.orgId,+ consumerUserId: helperContext.consumerUserId,+ entry: {+ command: 'run',+ status: 'start',+ file: Option.getOrUndefined(file),args,- preloadPath: preload.preloadPath,- preloadDirectory: preload.directory,- });- cleanupPaths = runCommand.cleanupPaths;- const child = Bun.spawn({- cmd: runCommand.cmd,- env: {- // 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- ...process.env,+ debug,+ },+ }).pipe(Effect.catchAll(() => Effect.void));+ yield* ui.error(`RUN_LOG_FILE=${preload.runLogFilePath}`);+ const runCommand = yield* buildRunCommand({+ path,+ file,+ args,+ preloadPath: preload.preloadPath,+ preloadDirectory: preload.directory,+ });+ const exitCode = yield* Effect.gen(function* () {+ const [executable, ...commandArgs] = runCommand.cmd;+ const command = PlatformCommand.make(executable, ...commandArgs).pipe(+ PlatformCommand.env({BUN_BE_BUN: '1',COMPOSIO_CLI_PARENT_RUN_ID: runId,- ...(perfDebug ? { COMPOSIO_PERF_DEBUG: '1' } : {}),- ...(toolDebug ? { COMPOSIO_TOOL_DEBUG: '1' } : {}),- },- stdio: ['inherit', 'inherit', 'inherit'],- });-- const exitCode = yield* Effect.promise(() => child.exited);- process.exit(exitCode);- } finally {- for (const cleanupPath of cleanupPaths) {- fs.rmSync(cleanupPath, { force: true });- }- fs.rmSync(preload.directory, { recursive: true, force: true });- }- })+ ...debugFlagsToChildEnv({ perfDebug, toolDebug, acpOnly, telemetryDebug }),+ }),+ PlatformCommand.stdin('inherit'),+ PlatformCommand.stdout('inherit'),+ PlatformCommand.stderr('inherit')+ );+ // Start the process instead of running it to completion: only a started process+ // exposes the pid the signal forwarding below needs.+ const child = yield* PlatformCommand.start(command);+ yield* forwardSignalsToChild(child);+ return Number(yield* child.exitCode);+ }).pipe(+ Effect.scoped,+ Effect.ensuring(+ Effect.forEach(+ runCommand.cleanupPaths,+ cleanupPath => fs.remove(cleanupPath, { force: true }),+ { discard: true }+ ).pipe(+ // The wrapper file sits next to the user's script, so removal can fail on a+ // read-only or locked directory. That must not turn an already-successful run+ // into a failure, which is what the previous `Effect.orDie` did.+ Effect.ignore+ )+ ),+ // Interruption (Ctrl-C) skips the assignment below, and the default teardown reports+ // an interrupt-only exit as success. Report the conventional 128+SIGINT instead so+ // wrappers and `set -e` scripts do not read a cancelled run as a passing one.+ Effect.onInterrupt(() =>+ Effect.sync(() => {+ process.exitCode = 130;+ })+ )+ );+ process.exitCode = exitCode;+ }).pipe(Effect.scoped)));diff --git a/ts/packages/cli/src/commands/setup.cmd.ts b/ts/packages/cli/src/commands/setup.cmd.tsindex e0ebae285..67524fff7 100644--- a/ts/packages/cli/src/commands/setup.cmd.ts+++ b/ts/packages/cli/src/commands/setup.cmd.ts@@ -21,6 +21,7 @@ import {} from 'src/services/setup';import { TerminalUI } from 'src/services/terminal-ui';import { SetupSkillInstaller } from 'src/services/setup-skill-installer';+import { cliInvocationContext } from 'src/services/runtime-cli-context';const target = Options.choice('target', SETUP_TARGETS).pipe(Options.withDefault('auto'),@@ -63,6 +64,7 @@ const setupBaseCmd = Command.make(Effect.gen(function* () {const ui = yield* TerminalUI;const terminal = yield* ui.capabilities;+ const { invocationOrigin } = yield* cliInvocationContext;const operation = uninstall ? 'uninstall' : 'setup';yield* ui.intro(uninstall ? 'composio setup --uninstall' : 'composio setup');@@ -80,6 +82,7 @@ const setupBaseCmd = Command.make(detection.available && !detection.supported? (detection.unsupportedReasonCode ?? 'unknown'): undefined,+ invocationOrigin,cliVersion: APP_VERSION,}))@@ -117,7 +120,12 @@ const setupBaseCmd = Command.make(if (supported.length === 0) {if (ifPresent) {yield* trackCliEventEffect(- getSetupSkippedEvent({ operation, requestedTarget: target, cliVersion: APP_VERSION })+ getSetupSkippedEvent({+ operation,+ requestedTarget: target,+ invocationOrigin,+ cliVersion: APP_VERSION,+ }));yield* ui.outro(`No supported agent host detected; plugin ${uninstall ? 'uninstall' : 'setup'} skipped.`@@ -141,7 +149,12 @@ const setupBaseCmd = Command.make();}yield* trackCliEventEffect(- getSetupSkippedEvent({ operation, requestedTarget: target, cliVersion: APP_VERSION })+ getSetupSkippedEvent({+ operation,+ requestedTarget: target,+ invocationOrigin,+ cliVersion: APP_VERSION,+ }));yield* ui.outro(`No supported agent host detected; plugin ${uninstall ? 'uninstall' : 'setup'} skipped.`@@ -191,6 +204,7 @@ const setupBaseCmd = Command.make(getSetupCancelledEvent({operation,requestedTarget: target,+ invocationOrigin,cliVersion: APP_VERSION,}));@@ -241,6 +255,7 @@ const setupBaseCmd = Command.make(getSetupCancelledEvent({operation,requestedTarget: target,+ invocationOrigin,cliVersion: APP_VERSION,}));diff --git a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.tsindex e20f31efa..28802ff4f 100644--- a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts+++ b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts@@ -29,6 +29,7 @@ import { ComposioToolkitsRepository } from 'src/services/composio-clients';import { ComposioUserContext } from 'src/services/user-context';import { ProjectContext } from 'src/services/project-context';import { trackCliCodactFailureEffect, trackCliEventEffect } from 'src/analytics/dispatch';+import { cliInvocationContext } from 'src/services/runtime-cli-context';import {getToolExecuteFailedEvent,getToolExecuteToolNotFoundEvent,@@ -63,6 +64,7 @@ import {import * as constants from 'src/constants';import { ComposioCliUserConfig } from 'src/services/cli-user-config';import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';+import { APP_CONFIG } from 'src/effects/app-config';const slug = Args.text({ name: 'slug' }).pipe(Args.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')@@ -315,8 +317,10 @@ const getExecuteOutputEncoder = () => {return executeOutputEncoder;};-// 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-const shouldStoreLargeExecuteOutput = () => process.env.COMPOSIO_CLI_INVOCATION_ORIGIN !== 'run';+const shouldStoreLargeExecuteOutput = APP_CONFIG.CLI_INVOCATION_ORIGIN.pipe(+ Effect.orDie,+ Effect.map(origin => origin !== 'run')+);type StoredExecuteOutputSummary = {readonly successful: true;@@ -362,12 +366,12 @@ const executionSuccessSuffix = (result: {const persistLargeExecuteOutput = (toolSlug: string, json: string, sharedDirectory?: string) =>Effect.gen(function* () {+ const runOutputDirectory = yield* APP_CONFIG.RUN_OUTPUT_DIR;const outputFilePath = yield* storeCliSessionArtifact({contents: json,name: `${toolSlug}_OUTPUT`,extension: 'json',- // 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- directoryPath: sharedDirectory?.trim() || process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim(),+ directoryPath: sharedDirectory?.trim() || runOutputDirectory,});return {@@ -390,7 +394,10 @@ const prepareExecuteOutput = (Effect.gen(function* () {const json = serializeExecuteOutput(result);const tokenCount = getExecuteOutputEncoder().encode(json).length;- if (tokenCount <= EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD || !shouldStoreLargeExecuteOutput()) {+ if (+ tokenCount <= EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD ||+ !(yield* shouldStoreLargeExecuteOutput)+ ) {return {kind: 'inline',json,@@ -418,6 +425,7 @@ const emitExecuteFailureTelemetry = (params: {}) =>Effect.gen(function* () {const toolkitSlug = yield* toolkitFromToolSlug(params.toolSlug);+ const { invocationOrigin } = yield* cliInvocationContext;const normalized = params.mappedError?.normalized ?? normalizeCliError(params.error);const failureOrigin: 'fast_fail' | 'main_endpoint' =normalized instanceof ToolInputValidationError || params.stage !== 'execution'@@ -431,6 +439,7 @@ const emitExecuteFailureTelemetry = (params: {toolkitSlug,args: params.args,error: normalized,+ invocationOrigin,surface: params.surface,projectMode: params.projectMode,stage: params.stage === 'dry_run' ? 'dry_run' : 'validation',@@ -489,6 +498,7 @@ const emitExecuteFailureTelemetry = (params: {schemaPath: 'server',issues: [message],}),+ invocationOrigin,surface: params.surface,projectMode: params.projectMode,stage:@@ -510,6 +520,7 @@ const emitExecuteFailureTelemetry = (params: {toolSlug: params.toolSlug,toolkitSlug,args: params.args,+ invocationOrigin,surface: params.surface,projectMode: params.projectMode,stage: params.stage === 'validation' ? 'execution' : params.stage,@@ -524,6 +535,7 @@ const emitExecuteFailureTelemetry = (params: {toolSlug: params.toolSlug,toolkitSlug,args: params.args,+ invocationOrigin,surface: params.surface,projectMode: params.projectMode,stage: params.stage === 'validation' ? 'execution' : params.stage,@@ -978,6 +990,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>const input = (yield* resolveInput(params.data)) ?? '{}';const parsedArgs = yield* parseArguments(input);const cliConfig = yield* ComposioCliUserConfig;+ const runOutputDirectory = yield* APP_CONFIG.RUN_OUTPUT_DIR;if (isLocalToolSlug(params.slug) &&@@ -1009,8 +1022,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>args: parsedArgs,resolvedUserId: 'local',selectedConnectedAccountId: undefined,- // 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- executeOutputDir: process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim() || undefined,+ executeOutputDir: runOutputDirectory,executeParams: {userId: 'local',arguments: parsedArgs,@@ -1079,8 +1091,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>): parsedArgs;const executeOutputDir =- // 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- process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim() ||+ runOutputDirectory ||Option.getOrUndefined(yield* resolveCliSessionArtifacts({orgId: resolvedProject.projectType === 'CONSUMER' ? resolvedProject.orgId : undefined,diff --git a/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts b/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.tsindex ee94cf7e0..276136e56 100644--- a/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts+++ b/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts@@ -1,6 +1,7 @@import { Command, Options } from '@effect/cli';import { FileSystem, Path } from '@effect/platform';import { Deferred, Effect, Option, Runtime } from 'effect';+import { APP_CONFIG } from 'src/effects/app-config';import { requireAuth } from 'src/effects/require-auth';import { TerminalUI } from 'src/services/terminal-ui';import { TriggersRealtime } from 'src/services/triggers-realtime';@@ -184,8 +185,8 @@ export const triggersCmd$Listen = Command.make(const runtime = yield* Effect.runtime<never>();const forwardUrl = Option.getOrUndefined(forward);const generatedWebhookSecret = `composio-forward-secret-${randomUUID()}`;- // 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- const webhookSecret = process.env.COMPOSIO_WEBHOOK_SECRET ?? generatedWebhookSecret;+ const configuredWebhookSecret = yield* APP_CONFIG.WEBHOOK_SECRET;+ const webhookSecret = configuredWebhookSecret ?? generatedWebhookSecret;const outputFilePathOption = Option.getOrUndefined(out);const outputFilePath = outputFilePathOption ? path.resolve(outputFilePathOption) : undefined;@@ -211,8 +212,7 @@ export const triggersCmd$Listen = Command.make(yield* ui.intro('composio dev triggers listen');if (forwardUrl) {- // 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- if (process.env.COMPOSIO_WEBHOOK_SECRET) {+ if (configuredWebhookSecret) {yield* ui.note(`Forward URL: ${forwardUrl}\nSigning secret: ${webhookSecret}`,'Forwarding'diff --git a/ts/packages/cli/src/effects/app-config.ts b/ts/packages/cli/src/effects/app-config.tsindex 8b0a7589e..906f050c1 100644--- a/ts/packages/cli/src/effects/app-config.ts+++ b/ts/packages/cli/src/effects/app-config.ts@@ -1,4 +1,4 @@-import { Config, LogLevel, Option } from 'effect';+import { Config, HashMap, LogLevel, Option } from 'effect';import * as constants from 'src/constants';type APP_CONFIG = Config.Config.Wrap<{@@ -6,13 +6,95 @@ type APP_CONFIG = Config.Config.Wrap<{ENVIRONMENT: Option.Option<string>;BASE_URL: string;WEB_URL: string;- CACHE_DIR: Option.Option<string>;+ CACHE_DIR: string | undefined;+ SESSION_DIR: string | undefined;+ BIN_DIR: string | undefined;LOG_LEVEL: Option.Option<LogLevel.LogLevel>;ORG_ID: Option.Option<string>;PROJECT_ID: Option.Option<string>;+ AGENTS_BASE_URL: string | undefined;+ WEBHOOK_SECRET: string | undefined;+ CLI_INVOCATION_ORIGIN: string | undefined;+ CLI_PARENT_RUN_ID: string | undefined;+ RUN_ACP_ONLY: boolean;+ RUN_OUTPUT_DIR: string | undefined;+ PERF_DEBUG: boolean;+ TOOL_DEBUG: boolean;DISABLE_CONNECTED_ACCOUNT_CACHE: boolean;}>;+type UNPREFIXED_CONFIG = Config.Config.Wrap<{+ CACHE_DIR: string | undefined;+ NPM_CONFIG_USER_AGENT: string | undefined;+ CI_REDACTION_ENABLED: boolean;+ INTERACTIVE_PERMISSION_UI_DISABLED: boolean;+ NO_COLOR: boolean;+ TELEMETRY_DEBUG: boolean;+ MASTER_SIGNALS: {+ readonly codex: boolean;+ readonly claude: boolean;+ };+ CALLER_AGENT_SIGNALS: {+ readonly explicit: string | undefined;+ readonly openclaw: boolean;+ readonly claude: boolean;+ readonly codex: boolean;+ };+}>;++const optionalString = (name: string): Config.Config<string | undefined> =>+ Config.option(Config.string(name)).pipe(Config.map(Option.getOrUndefined));++const optionalTrimmedString = (name: string): Config.Config<string | undefined> =>+ optionalString(name).pipe(+ Config.map(value => {+ if (value === undefined) return undefined;+ const trimmed = value.trim();+ return trimmed.length > 0 ? trimmed : undefined;+ })+ );++const ENV_FLAG_OFF_SPELLINGS = new Set(['0', 'false', 'no', 'off']);++// A flag that is set counts as enabled unless it spells out one of the usual+// "off" values, compared case-insensitively (`OFF` disables like `off`).+const isEnvFlagEnabled = (value: string): boolean =>+ !ENV_FLAG_OFF_SPELLINGS.has(value.toLowerCase());++/**+ * Tri-state read of a boolean environment flag:+ *+ * unset, or set to blank (`COMPOSIO_X=`) → `undefined` — absent, caller picks the default+ * `0` / `false` / `no` / `off`, any casing → `false`+ * anything else (`1`, `true`, even a typo) → `true`+ */+const optionalEnvironmentFlag = (name: string): Config.Config<boolean | undefined> =>+ optionalTrimmedString(name).pipe(+ Config.map(value => (value === undefined ? undefined : isEnvFlagEnabled(value)))+ );++// Deliberately tolerant rather than `Config.boolean`: these flags arrive from the ambient+// environment, where a blank (`COMPOSIO_PERF_DEBUG=`) or unexpected value is routine.+// `Config.boolean` rejects both with `InvalidData`, and `Config.withDefault` only recovers+// `MissingData`, so a stray value would surface as an unrecoverable defect instead of `false`.+const booleanFlag = (name: string, defaultValue = false): Config.Config<boolean> =>+ optionalEnvironmentFlag(name).pipe(Config.map(value => value ?? defaultValue));++// `Config.hashMap` enumerates the provider's root keys instead of reading one+// named variable, so it depends on how `ConfigProvider.fromEnv` derives them:+// every `process.env` key is uppercased and split on `_`, and the first segment+// becomes a root. `CODEX_HOME`, `codex_home`, and a bare `CODEX` therefore all+// surface as the root `CODEX`. Matching is consequently case-insensitive and no+// longer requires a trailing underscore, unlike the+// `Object.keys(env).some(key => key.startsWith('CODEX_'))` scan it replaced.+const agentPrefixSignals = Config.hashMap(Config.succeed(true)).pipe(+ Config.map(environmentRoots => ({+ codex: HashMap.has(environmentRoots, 'CODEX'),+ claude: HashMap.has(environmentRoots, 'CLAUDE'),+ openclaw: HashMap.has(environmentRoots, 'OPENCLAW'),+ }))+);+/*** Derives a URL default based on the `COMPOSIO_ENVIRONMENT` config key.* Returns `stagingDefault` when ENVIRONMENT is `"staging"`, otherwise `prodDefault`.@@ -56,7 +138,13 @@ export const APP_CONFIG = {),// The cache directory for the Composio CLI- CACHE_DIR: Config.option(Config.string('CACHE_DIR')),+ CACHE_DIR: optionalTrimmedString('CACHE_DIR'),++ // Override the root directory for CLI session artifacts+ SESSION_DIR: optionalTrimmedString('SESSION_DIR'),++ // Override the directory added to PATH by `composio install`+ BIN_DIR: optionalTrimmedString('BIN_DIR'),// The log level for the Composio CLILOG_LEVEL: Config.option(Config.logLevel('LOG_LEVEL')),@@ -67,8 +155,64 @@ export const APP_CONFIG = {// The project ID for multi-project auth (overrides file-based config)PROJECT_ID: Config.option(Config.string('PROJECT_ID')),+ // Override the Composio agents service URL+ AGENTS_BASE_URL: optionalString('AGENTS_BASE_URL'),++ // Sign forwarded trigger payloads with this secret+ WEBHOOK_SECRET: optionalString('WEBHOOK_SECRET'),++ // Internal context propagated between CLI processes+ CLI_INVOCATION_ORIGIN: optionalTrimmedString('CLI_INVOCATION_ORIGIN'),+ CLI_PARENT_RUN_ID: optionalTrimmedString('CLI_PARENT_RUN_ID'),+ RUN_ACP_ONLY: booleanFlag('RUN_ACP_ONLY'),+ RUN_OUTPUT_DIR: optionalTrimmedString('RUN_OUTPUT_DIR'),++ // Runtime debug flags+ PERF_DEBUG: booleanFlag('PERF_DEBUG'),+ TOOL_DEBUG: booleanFlag('TOOL_DEBUG'),+// Disable connected account cache (defaults to true — cache is off by default)- DISABLE_CONNECTED_ACCOUNT_CACHE: Config.boolean('DISABLE_CONNECTED_ACCOUNT_CACHE').pipe(- Config.withDefault(true)- ),+ DISABLE_CONNECTED_ACCOUNT_CACHE: booleanFlag('DISABLE_CONNECTED_ACCOUNT_CACHE', true),} satisfies APP_CONFIG;++/**+ * Configuration whose keys are spelled out in full and are therefore loaded+ * through the raw `ConfigProvider.fromEnv()` provider (`loadHostConfig` in+ * `src/services/config.ts`) rather than the `COMPOSIO_`-prefixing provider that+ * serves `APP_CONFIG`. Several keys do carry the `COMPOSIO_` prefix; what unites+ * them is that the prefix is written here instead of being applied by the+ * provider. Keep their string-to-domain normalization here so consumers never+ * inspect raw environment strings.+ */+export const UNPREFIXED_CONFIG = {+ // The cache directory of the host tool driving the CLI (not `COMPOSIO_CACHE_DIR`)+ CACHE_DIR: optionalTrimmedString('CACHE_DIR'),++ // The package manager that invoked the CLI, as reported by npm-compatible clients+ NPM_CONFIG_USER_AGENT: optionalString('npm_config_user_agent'),++ // Stricter than the `booleanFlag` family on purpose: output redaction is for+ // recorded CI sessions and keys off the exact `CI=true` convention. A looser+ // parse would also start redacting under `CI=1`-style environments, changing+ // long-standing behavior. `INTERACTIVE_PERMISSION_UI_DISABLED` below reads+ // the same variable tolerantly because failing closed there is the safe+ // reading of any non-falsy `CI` value.+ CI_REDACTION_ENABLED: optionalTrimmedString('CI').pipe(+ Config.map(value => value?.toLowerCase() === 'true')+ ),+ INTERACTIVE_PERMISSION_UI_DISABLED: Config.all({+ explicit: optionalEnvironmentFlag('COMPOSIO_DISABLE_PERMISSION_UI'),+ ci: optionalEnvironmentFlag('CI'),+ vitest: optionalEnvironmentFlag('VITEST'),+ }).pipe(Config.map(({ explicit, ci, vitest }) => explicit ?? (ci === true || vitest === true))),+ NO_COLOR: optionalString('NO_COLOR').pipe(Config.map(Boolean)),+ TELEMETRY_DEBUG: booleanFlag('COMPOSIO_CLI_TELEMETRY_DEBUG'),+ MASTER_SIGNALS: agentPrefixSignals.pipe(Config.map(({ codex, claude }) => ({ codex, claude }))),+ CALLER_AGENT_SIGNALS: Config.all({+ explicit: Config.all({+ callerAgent: optionalTrimmedString('COMPOSIO_CALLER_AGENT'),+ legacyAgent: optionalTrimmedString('COMPOSIO_AGENT'),+ }).pipe(Config.map(({ callerAgent, legacyAgent }) => callerAgent ?? legacyAgent)),+ prefixes: agentPrefixSignals,+ }).pipe(Config.map(({ explicit, prefixes }) => ({ explicit, ...prefixes }))),+} satisfies UNPREFIXED_CONFIG;diff --git a/ts/packages/cli/src/effects/setup-cache-dir.ts b/ts/packages/cli/src/effects/setup-cache-dir.tsindex b0de31993..4e622f52f 100644--- a/ts/packages/cli/src/effects/setup-cache-dir.ts+++ b/ts/packages/cli/src/effects/setup-cache-dir.ts@@ -1,4 +1,4 @@-import { Effect, pipe, Option } from 'effect';+import { Effect } from 'effect';import { FileSystem, Path } from '@effect/platform';import * as constants from 'src/constants';import { APP_CONFIG } from 'src/effects/app-config';@@ -10,10 +10,8 @@ export const setupCacheDir = Effect.gen(function* () {const path = yield* Path.Path;const os = yield* NodeOs;- const cacheDir = yield* pipe(- APP_CONFIG.CACHE_DIR,- Effect.map(Option.getOrElse(() => path.join(os.homedir, constants.USER_COMPOSIO_DIR)))- );+ const cacheDir =+ (yield* APP_CONFIG.CACHE_DIR) ?? path.join(os.homedir, constants.USER_COMPOSIO_DIR);// Ensure cache directory existsyield* fs.makeDirectory(cacheDir, { recursive: true }).pipe(Effect.catchAll(() => Effect.void));diff --git a/ts/packages/cli/src/services/agents.ts b/ts/packages/cli/src/services/agents.tsindex e4cc76518..37ee77c82 100644--- a/ts/packages/cli/src/services/agents.ts+++ b/ts/packages/cli/src/services/agents.ts@@ -1,5 +1,6 @@import { FileSystem, Path } from '@effect/platform';import { Data, Effect, Either, Option, Predicate, Schema } from 'effect';+import { APP_CONFIG } from 'src/effects/app-config';import { JsonRecordSchema } from 'src/effects/json';import { setupCacheDir } from 'src/effects/setup-cache-dir';import { ComposioUserContext } from 'src/services/user-context';@@ -81,9 +82,10 @@ export class AgentResponseDecodeError extends Data.TaggedError(readonly cause: unknown;}> {}-const agentsBaseURL = (): string =>- // 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- (process.env.COMPOSIO_AGENTS_BASE_URL ?? DEFAULT_AGENTS_BASE_URL).replace(/\/+$/, '');+const agentsBaseURL = APP_CONFIG.AGENTS_BASE_URL.pipe(+ Effect.orDie,+ Effect.map(value => (value ?? DEFAULT_AGENTS_BASE_URL).replace(/\/+$/, ''))+);const decodeAgentResponse =<A, I>(pathname: string, schema: Schema.Schema<A, I>) =>@@ -197,9 +199,10 @@ export const removeStoredAgentIdentity = Effect.gen(function* () {const fetchAgentJson = (pathname: string, init: RequestInit = {}) =>Effect.gen(function* () {+ const baseURL = yield* agentsBaseURL;const response = yield* Effect.tryPromise({try: () =>- fetch(`${agentsBaseURL()}${pathname}`, {+ fetch(`${baseURL}${pathname}`, {redirect: 'error',...init,headers: {diff --git a/ts/packages/cli/src/services/cli-session-artifacts.ts b/ts/packages/cli/src/services/cli-session-artifacts.tsindex ea35b2841..519236b89 100644--- a/ts/packages/cli/src/services/cli-session-artifacts.ts+++ b/ts/packages/cli/src/services/cli-session-artifacts.ts@@ -1,5 +1,6 @@import { FileSystem, Path } from '@effect/platform';import { Effect, Option } from 'effect';+import { APP_CONFIG } from 'src/effects/app-config';import { getOrCreateProbablyMyCliSessionIdForCurrentCwd } from 'src/services/consumer-short-term-cache';import { ComposioCliUserConfig } from 'src/services/cli-user-config';import { NodeOs } from 'src/services/node-os';@@ -8,12 +9,12 @@ export const resolveArtifactsRoot = Effect.gen(function* () {const path = yield* Path.Path;const os = yield* NodeOs;const cliUserConfig = yield* ComposioCliUserConfig;+ const sessionDirectory = yield* APP_CONFIG.SESSION_DIR;+ const cacheDirectory = yield* APP_CONFIG.CACHE_DIR;return (- // 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)- process.env.COMPOSIO_SESSION_DIR?.trim() ||- // 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- process.env.COMPOSIO_CACHE_DIR?.trim() ||+ sessionDirectory ||+ cacheDirectory ||cliUserConfig.data.artifactDirectory?.trim() ||path.join(os.tmpdir, 'composio'));diff --git a/ts/packages/cli/src/services/cli-user-config.ts b/ts/packages/cli/src/services/cli-user-config.tsindex 45a391750..f8c24dbcf 100644--- a/ts/packages/cli/src/services/cli-user-config.ts+++ b/ts/packages/cli/src/services/cli-user-config.ts@@ -2,8 +2,6 @@ import { FileSystem, Path } from '@effect/platform';import type { PlatformError } from '@effect/platform/Error';import { Context, Effect, Layer, Option, Predicate, Schema } from 'effect';import type { ParseError } from 'effect/ParseResult';-// 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-import os from 'node:os';import { JsonRecordSchema } from 'src/effects/json';import { setupCacheDir } from 'src/effects/setup-cache-dir';import { getVersion } from 'src/effects/version';@@ -48,24 +46,6 @@ const DEFAULT_CLI_USER_CONFIG = CliUserConfig.make({const decodeConfigJson = Schema.decodeUnknown(Schema.parseJson(JsonRecordSchema));-// The sync resolvers below run from non-Effect call sites (the-// run-helpers-runtime child process), so the Path service is materialized once-// from its pure default layer instead of being yielded from context.-const syncPath = Effect.runSync(Path.Path.pipe(Effect.provide(Path.layer)));--export const resolveCliConfigDirectorySync = (): string =>- // 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- process.env.COMPOSIO_CACHE_DIR?.trim() ||- syncPath.join(os.homedir(), constants.USER_COMPOSIO_DIR);--export const resolveCliConfigPathSync = (): string =>- syncPath.join(resolveCliConfigDirectorySync(), constants.CLI_CONFIG_FILE_NAME);--/**- * Effect-based resolver for the CLI config file path. Prefer this over- * `resolveCliConfigPathSync` inside Effect-hosted code: it honors the- * COMPOSIO_CACHE_DIR override via `effect/Config` and the NodeOs service.- */export const resolveCliConfigPath = Effect.gen(function* () {const path = yield* Path.Path;const configDir = yield* setupCacheDir;diff --git a/ts/packages/cli/src/services/command-runner.ts b/ts/packages/cli/src/services/command-runner.tsindex eb3e8a229..c6ccfd193 100644--- a/ts/packages/cli/src/services/command-runner.ts+++ b/ts/packages/cli/src/services/command-runner.ts@@ -7,7 +7,8 @@ export interface CommandResult {readonly stderr: string;}-const collectText = (stream: Stream.Stream<Uint8Array, unknown>) =>+/** Drains a child-process output stream into one string; shared with the run-helpers runtime. */+export const collectText = (stream: Stream.Stream<Uint8Array, unknown>) =>stream.pipe(Stream.decodeText(), Stream.runFold(String.empty, String.concat));export class CommandRunner extends Effect.Service<CommandRunner>()('services/CommandRunner', {diff --git a/ts/packages/cli/src/services/config.ts b/ts/packages/cli/src/services/config.tsindex 1ded7bed2..3c0adbcfd 100644--- a/ts/packages/cli/src/services/config.ts+++ b/ts/packages/cli/src/services/config.ts@@ -1,4 +1,4 @@-import { Option, Effect, ConfigProvider, Layer, Logger } from 'effect';+import { Config, Option, Effect, ConfigProvider, Layer, Logger } from 'effect';import * as constants from 'src/constants';import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';import { APP_CONFIG } from 'src/effects/app-config';@@ -23,6 +23,13 @@ import { APP_CONFIG } from 'src/effects/app-config';export const BaseConfigProviderLive = ConfigProvider.fromEnv();+/**+ * Load a config whose keys are spelled out in full, through the raw provider+ * that applies no `COMPOSIO_` prefix mapping. Pair it with `UNPREFIXED_CONFIG`.+ */+export const loadHostConfig = <A>(config: Config.Config<A>): Effect.Effect<A> =>+ BaseConfigProviderLive.load(config).pipe(Effect.orDie);+export function extendConfigProvider(baseConfigProvider: ConfigProvider.ConfigProvider) {return baseConfigProvider.pipe(ConfigProvider.mapInputPath(key => {diff --git a/ts/packages/cli/src/services/master-detector.ts b/ts/packages/cli/src/services/master-detector.tsindex 7a86c71b3..811675120 100644--- a/ts/packages/cli/src/services/master-detector.ts+++ b/ts/packages/cli/src/services/master-detector.ts@@ -1,15 +1,24 @@+import { Effect } from 'effect';+import { UNPREFIXED_CONFIG } from 'src/effects/app-config';+import { loadHostConfig } from 'src/services/config';+export type MasterKind = 'claude' | 'codex' | 'user';-export const hasEnvPrefix = (env: Record<string, string | undefined>, prefix: string): boolean =>- Object.keys(env).some(key => key.startsWith(prefix));+export type MasterSignals = {+ readonly codex: boolean;+ readonly claude: boolean;+};-// 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-export const detectMaster = (env: Record<string, string | undefined> = process.env): MasterKind => {- if (hasEnvPrefix(env, 'CODEX_')) {+export const detectMaster = (signals: MasterSignals): MasterKind => {+ if (signals.codex) {return 'codex';}- if (hasEnvPrefix(env, 'CLAUDE_')) {+ if (signals.claude) {return 'claude';}return 'user';};++export const detectMasterFromHost: Effect.Effect<MasterKind> = loadHostConfig(+ UNPREFIXED_CONFIG.MASTER_SIGNALS+).pipe(Effect.map(detectMaster));diff --git a/ts/packages/cli/src/services/native-ui-sidecar.ts b/ts/packages/cli/src/services/native-ui-sidecar.tsindex aab02fe74..489977940 100644--- a/ts/packages/cli/src/services/native-ui-sidecar.ts+++ b/ts/packages/cli/src/services/native-ui-sidecar.ts@@ -3,7 +3,6 @@ import { BunContext } from '@effect/platform-bun';import {Cause,Config,- ConfigProvider,Data,Duration,Effect,@@ -18,7 +17,8 @@ import {ensureBundledBinaryExecutable,getLocalToolsBundleRootCandidates,} from '@composio/cli-local-tools';-import { hasEnvPrefix } from 'src/services/master-detector';+import { UNPREFIXED_CONFIG } from 'src/effects/app-config';+import { loadHostConfig } from 'src/services/config';const NATIVE_UI_BINARY_NAME = 'composio-native-ui';@@ -61,64 +61,18 @@ export class NativeUiDecisionMissingError extends Data.TaggedError(}}-// Caller-agent detection scans the whole environment for agent-specific-// prefixes (OPENCLAW_*, CLAUDE_*, CODEX_*). effect/Config can only read named-// keys, so this module keeps a single raw-env boundary, mirroring the-// node-os.ts precedent.-// 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.-const rawProcessEnv: NodeJS.ProcessEnv = process.env;--const FALSY_ENV_FLAG_VALUES: ReadonlyArray<string> = ['0', 'false', 'no', 'off'];--// Any other non-empty value counts as set (`CI=woohoo` still disables the UI)-// rather than failing config decoding the way `Config.boolean` would.-const EnvFlagFromString = Schema.transform(- Schema.compose(Schema.Trim, Schema.Lowercase),- Schema.Boolean,- {- decode: value => !FALSY_ENV_FLAG_VALUES.includes(value),- encode: enabled => (enabled ? '1' : '0'),- strict: true,- }-);-const decodeEnvFlag = Schema.decodeOption(EnvFlagFromString);--// None when the variable is unset or blank, so callers can distinguish-// "not configured" from an explicit true/false.-const envFlag = (name: string): Config.Config<Option.Option<boolean>> =>- Config.string(name).pipe(- Config.map(value => value.trim()),- Config.option,- Config.map(Option.filter(value => value.length > 0)),- Config.map(Option.flatMap(decodeEnvFlag))- );-/*** Interactive permission UI (the native sidecar dialog and the browser* approval page) must never spawn from automated environments. The explicit* COMPOSIO_DISABLE_PERMISSION_UI knob wins in both directions; without it,* CI and Vitest runs disable the UI.*/-export const interactivePermissionUiDisabledConfig: Config.Config<boolean> = Config.all({- explicit: envFlag('COMPOSIO_DISABLE_PERMISSION_UI'),- ci: envFlag('CI'),- vitest: envFlag('VITEST'),-}).pipe(- Config.map(({ explicit, ci, vitest }) =>- Option.getOrElse(- explicit,- () => Option.getOrElse(ci, () => false) || Option.getOrElse(vitest, () => false)- )- )-);--// CI / VITEST / COMPOSIO_DISABLE_PERMISSION_UI are read verbatim, so load them-// through a raw env provider rather than the CLI's COMPOSIO_-prefixed one.-const environmentProvider = ConfigProvider.fromEnv();+export const interactivePermissionUiDisabledConfig =+ UNPREFIXED_CONFIG.INTERACTIVE_PERMISSION_UI_DISABLED;-export const isInteractivePermissionUiDisabled: Effect.Effect<boolean> = environmentProvider- .load(interactivePermissionUiDisabledConfig)- .pipe(Effect.orDie);+export const isInteractivePermissionUiDisabled: Effect.Effect<boolean> = loadHostConfig(+ interactivePermissionUiDisabledConfig+);const normalizeCallerAgent = (value?: string): NativeUiCallerAgent | undefined => {const normalized = value?.toLowerCase().replace(/[^a-z]/g, '');@@ -170,31 +124,37 @@ const detectCallerAgentFromProcessTree: Effect.Effect<return undefined;});-const detectCallerAgentFromEnv = (env: NodeJS.ProcessEnv): NativeUiCallerAgent | undefined => {- const explicit = normalizeCallerAgent(env.COMPOSIO_CALLER_AGENT ?? env.COMPOSIO_AGENT);+export type NativeUiCallerAgentSignals = Config.Config.Success<+ typeof UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS+>;++const detectCallerAgentFromSignals = (+ signals: NativeUiCallerAgentSignals+): NativeUiCallerAgent | undefined => {+ const explicit = normalizeCallerAgent(signals.explicit);if (explicit) return explicit;- if (hasEnvPrefix(env, 'OPENCLAW_')) return 'openclaw';- if (hasEnvPrefix(env, 'CLAUDE_')) return 'claude';- if (hasEnvPrefix(env, 'CODEX_')) return 'codex';+ if (signals.openclaw) return 'openclaw';+ if (signals.claude) return 'claude';+ if (signals.codex) return 'codex';return undefined;};export const detectNativeUiCallerAgentEffect = (- env: NodeJS.ProcessEnv = rawProcessEnv+ providedSignals?: NativeUiCallerAgentSignals): Effect.Effect<NativeUiCallerAgent, never, CommandExecutor.CommandExecutor> =>Effect.gen(function* () {- const fromEnv = detectCallerAgentFromEnv(env);+ const signals =+ providedSignals ?? (yield* loadHostConfig(UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS));+ const fromEnv = detectCallerAgentFromSignals(signals);if (fromEnv !== undefined) return fromEnv;return (yield* detectCallerAgentFromProcessTree) ?? 'composio';});-export const detectNativeUiCallerAgent = (- env: NodeJS.ProcessEnv = rawProcessEnv-): Promise<NativeUiCallerAgent> =>- Effect.runPromise(Effect.provide(detectNativeUiCallerAgentEffect(env), BunContext.layer));+export const detectNativeUiCallerAgent = (): Promise<NativeUiCallerAgent> =>+ Effect.runPromise(Effect.provide(detectNativeUiCallerAgentEffect(), BunContext.layer));export const resolveNativeUiBinary: Effect.Effect<NativeUiBinaryResolution,diff --git a/ts/packages/cli/src/services/plugin-hint.ts b/ts/packages/cli/src/services/plugin-hint.tsindex e3b3e77d7..e491e7057 100644--- a/ts/packages/cli/src/services/plugin-hint.ts+++ b/ts/packages/cli/src/services/plugin-hint.ts@@ -1,6 +1,7 @@import { FileSystem, Path } from '@effect/platform';import { BunFileSystem } from '@effect/platform-bun';import { Config, ConfigProvider, Effect, Layer, Option, Schema } from 'effect';+import { APP_CONFIG } from 'src/effects/app-config';import { setupCacheDir } from 'src/effects/setup-cache-dir';import { AGENT_HOST_LABELS, COMPOSIO_AGENT_PLUGIN_ID, type AgentHost } from './agent-host';import { NodeOs } from './node-os';@@ -153,18 +154,16 @@ export function findRootCommandName(argv: ReadonlyArray<string>): string | undef// Host-owned variables must bypass the CLI ConfigProvider, which prefixes// application keys with COMPOSIO_.-const rawEnvironment = Effect.gen(function* () {+const rawHostEnvironment = Effect.gen(function* () {const claudeCode = yield* readOptionalEnv('CLAUDECODE');const codexThreadId = yield* readOptionalEnv('CODEX_THREAD_ID');const codexSandbox = yield* readOptionalEnv('CODEX_SANDBOX');- const invocationOrigin = yield* readOptionalEnv('COMPOSIO_CLI_INVOCATION_ORIGIN');const claudeConfigDir = nonBlankOrUndefined(yield* readOptionalEnv('CLAUDE_CONFIG_DIR'));const codexHome = nonBlankOrUndefined(yield* readOptionalEnv('CODEX_HOME'));return {claudeCode,codexThreadId,codexSandbox,- invocationOrigin,claudeConfigDir,codexHome,};@@ -175,11 +174,12 @@ export const resolvePluginHintConfig = (argv: ReadonlyArray<string>) =>const path = yield* Path.Path;const os = yield* NodeOs;const cacheDir = yield* setupCacheDir;- const env = yield* rawEnvironment;+ const invocationOrigin = yield* APP_CONFIG.CLI_INVOCATION_ORIGIN;+ const env = yield* rawHostEnvironment;return {stateDirectory: path.join(cacheDir, 'plugin-hints'),host: detectPluginHost(env),- invocationOrigin: env.invocationOrigin,+ invocationOrigin,commandName: findRootCommandName(argv),claudeInstalledPluginsFile: path.join(env.claudeConfigDir ?? path.join(os.homedir, '.claude'),diff --git a/ts/packages/cli/src/services/project-environment-detector.ts b/ts/packages/cli/src/services/project-environment-detector.tsindex 43ce9882a..56fcdf480 100644--- a/ts/packages/cli/src/services/project-environment-detector.ts+++ b/ts/packages/cli/src/services/project-environment-detector.ts@@ -1,8 +1,9 @@import { BunFileSystem } from '@effect/platform-bun';import { FileSystem, Path } from '@effect/platform';import { Data, Effect, Match } from 'effect';-import process from 'node:process';import { getAncestors } from 'src/utils/get-ancestors';+import { UNPREFIXED_CONFIG } from 'src/effects/app-config';+import { loadHostConfig } from 'src/services/config';const toError = (e: unknown): Error => (e instanceof Error ? e : new Error(String(e)));@@ -498,8 +499,9 @@ const detectJsPackageManager = (fs: FileSystem.FileSystem, cwd: string) =>if (fileSet.has('pnpm-workspace.yaml')) return 'pnpm' as const;}- // 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- const userAgent = parseUserAgent(process.env.npm_config_user_agent);+ const userAgent = parseUserAgent(+ yield* loadHostConfig(UNPREFIXED_CONFIG.NPM_CONFIG_USER_AGENT)+ );if (userAgent) return userAgent;return 'npm' as const;diff --git a/ts/packages/cli/src/services/run-companion-modules.ts b/ts/packages/cli/src/services/run-companion-modules.tsindex c1ce5f798..065a5b784 100644--- a/ts/packages/cli/src/services/run-companion-modules.ts+++ b/ts/packages/cli/src/services/run-companion-modules.ts@@ -2,7 +2,6 @@// the bundled `composio run` companion modules, and the binary build scripts. Every// helper is an Effect over the @effect/platform FileSystem/Path services; consumers// outside the CLI runtime (companion runtimes, scripts) provide their own platform layers.-import { fileURLToPath } from 'node:url';import { FileSystem, Path } from '@effect/platform';import type { PlatformError } from '@effect/platform/Error';import { Config, ConfigProvider, Data, Effect, Option, Schema } from 'effect';@@ -10,6 +9,7 @@ import extractZip from 'extract-zip';import { IS_RELEASE_BUILD } from 'src/constants';import { GitHubRelease } from 'src/effects/resolve-cli-release';import { BaseConfigProviderLive, extendConfigProvider } from 'src/services/config';+import { NodeOs } from 'src/services/node-os';import { atomicReplaceFile } from 'src/utils/atomic-replace';import { parseChecksumsText, sha256Hex } from 'src/utils/checksums';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);export const RUN_COMPANION_RELEASE_TAG_FILENAME = 'release-tag.txt';-type RunCodexAcpBinaryTarget = {+export type RunCodexAcpBinaryTarget = {readonly platform: NodeJS.Platform;readonly arch: string;readonly packageName: string;@@ -65,14 +65,62 @@ export const RUN_CODEX_ACP_BINARY_TARGETS: ReadonlyArray<RunCodexAcpBinaryTargetrelativePath: 'acp-adapters/codex/linux-x64/codex-acp',},];-export const RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS: ReadonlyArray<string> = [+export const codexAcpBinaryTargetFor = ({+ platform,+ arch,+}: {+ readonly platform: string;+ readonly arch: string;+}): RunCodexAcpBinaryTarget | undefined =>+ RUN_CODEX_ACP_BINARY_TARGETS.find(target => target.platform === platform && target.arch === arch);++// Portable ACP assets: any install that invokes an ACP sub-agent needs these+// regardless of platform/arch. They belong to the lazy tier — see+// `listMissingInstalledRunCompanionModules` for the two-tier split.+export const RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS: ReadonlyArray<string> = ['acp-adapters/claude-code-acp.mjs',// cli.js from @anthropic-ai/claude-agent-sdk must live next to claude-code-acp.mjs.// The bundled adapter uses import.meta.url to locate it at runtime.'acp-adapters/cli.js',+];++// Every asset a release archive ships, across all supported platforms. Only the+// packaging step cares about this: a single machine can execute exactly one of+// the codex-acp binaries.+export const RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS: ReadonlyArray<string> = [+ ...RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,...RUN_CODEX_ACP_BINARY_TARGETS.map(target => target.relativePath),];+/**+ * ACP assets an install must contain to be complete on the given platform/arch:+ * the portable ones plus at most the single codex-acp binary this host can run.+ * Unsupported platform/arch pairs simply have no codex-acp requirement.+ *+ * These are the *lazy* tier: `composio run` only needs them when the script it+ * runs actually invokes an ACP sub-agent, so startup never demands them.+ */+export const runCompanionStaticAssetRelativePathsFor = ({+ platform,+ arch,+}: {+ readonly platform: string;+ readonly arch: string;+}): ReadonlyArray<string> => {+ const hostTarget = codexAcpBinaryTargetFor({ platform, arch });++ return hostTarget+ ? [...RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS, hostTarget.relativePath]+ : RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS;+};++// NodeOs is the sanctioned platform/arch boundary; self-provided so callers keep+// their existing FileSystem/Path-only requirements.+export const hostRunCompanionStaticAssetRelativePaths: Effect.Effect<ReadonlyArray<string>> =+ Effect.map(NodeOs, os =>+ runCompanionStaticAssetRelativePathsFor({ platform: os.platform, arch: os.arch })+ ).pipe(Effect.provide(NodeOs.Default));+export class RunCompanionRepairError extends Data.TaggedError('services/RunCompanionRepairError')<{readonly message: string;readonly cause?: unknown;@@ -86,6 +134,9 @@ const isImportGraphFile = (relativePath: string) => /\.(?:m?js|ts)$/.test(relaticonst fileExists = (fs: FileSystem.FileSystem, filePath: string) =>fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));+const filePathFromUrl = (path: Path.Path, url: string): Effect.Effect<string> =>+ Schema.decodeUnknown(Schema.URL)(url).pipe(Effect.flatMap(path.fromFileUrl), Effect.orDie);+const collectRelativeImportPaths = ({fs,path,@@ -174,7 +225,7 @@ export const collectRunCompanionAssetRelativePaths = (}}- for (const relativePath of RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS) {+ for (const relativePath of yield* hostRunCompanionStaticAssetRelativePaths) {yield* collectRelativeImportPaths({fs,path,@@ -199,7 +250,7 @@ export const resolveRunCompanionAssetPath = ({Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;- const currentFilePath = fileURLToPath(callerImportMetaUrl);+ const currentFilePath = yield* filePathFromUrl(path, callerImportMetaUrl);const currentDirectory = path.dirname(currentFilePath);const executableDirectory = path.dirname(execPath);@@ -213,13 +264,24 @@ export const resolveRunCompanionAssetPath = ({return Option.getOrNull(found);});+/**+ * Relative paths an install rooted at `rootDir` is expected to contain.+ *+ * `staticAssetRelativePaths` defaults to the host's requirement set, so a+ * missing codex-acp binary for a foreign platform never counts as a broken+ * install. Release packaging passes `RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS`+ * because one packaging host builds archives for every platform.+ */export const collectExpectedRunCompanionAssetRelativePaths = (- rootDir: string+ rootDir: string,+ options: { readonly staticAssetRelativePaths?: ReadonlyArray<string> } = {}): Effect.Effect<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;const collected = new Set<string>();+ const staticAssetRelativePaths =+ options.staticAssetRelativePaths ?? (yield* hostRunCompanionStaticAssetRelativePaths);for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {yield* collectRelativeImportPaths({@@ -232,7 +294,7 @@ export const collectExpectedRunCompanionAssetRelativePaths = (});}- for (const relativePath of RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS) {+ for (const relativePath of staticAssetRelativePaths) {yield* collectRelativeImportPaths({fs,path,@@ -358,6 +420,16 @@ export const writeInstalledReleaseTag = ();});+/**+ * Startup tier: the `run-*.mjs` companion wrappers and their import graph.+ *+ * Every `composio run` preloads these into the spawned child, so a missing one+ * really is a broken install and justifies the self-repair download. The ACP+ * adapter assets are deliberately excluded — a script like+ * `composio run 'console.log(1)'` never invokes a sub-agent, and requiring+ * ~224MB of adapters for it turned a working install into a hard failure.+ * `run-subagent-acp` checks the ACP tier lazily at the invocation site instead.+ */export const listMissingInstalledRunCompanionModules = (execPath: string): Effect.Effect<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> =>@@ -365,13 +437,37 @@ export const listMissingInstalledRunCompanionModules = (const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;const installDirectory = path.dirname(execPath);- const expectedRelativePaths =- yield* collectExpectedRunCompanionAssetRelativePaths(installDirectory);+ const expectedRelativePaths = yield* collectExpectedRunCompanionAssetRelativePaths(+ installDirectory,+ { staticAssetRelativePaths: [] }+ );return yield* Effect.filter(expectedRelativePaths, relativePath =>Effect.map(fileExists(fs, path.join(installDirectory, relativePath)), exists => !exists));});+/**+ * Whether the companion wrappers sit next to the executable, which is how+ * packaged installs ship them.+ *+ * This distinguishes an install whose shipped assets went missing (report the+ * fix: reinstall / `composio upgrade`) from a source checkout that never had+ * them, where the CLI runs through `bun` and the npx/PATH adapter fallbacks are+ * the intended route.+ */+export const hasInstalledRunCompanionModules = (+ execPath: string+): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const installDirectory = path.dirname(execPath);+ const missing = yield* Effect.findFirst(RUN_COMPANION_MODULE_FILENAMES, fileName =>+ Effect.map(fileExists(fs, path.join(installDirectory, fileName)), exists => !exists)+ );+ return Option.isNone(missing);+ });+const fetchGitHubJson = async <A, I>(schema: Schema.Schema<A, I>,{@@ -493,6 +589,14 @@ const githubRepairConfig = Effect.orDie(})).pipe(Effect.withConfigProvider(repairConfigProvider));+/**+ * Restores a packaged install whose companion wrappers went missing.+ *+ * Triggered by the startup tier only (`listMissingInstalledRunCompanionModules`),+ * so a plain `composio run` never downloads a release just because the ACP+ * adapters are absent. Once it does run it restores the host's full asset set,+ * ACP adapters included, so a repaired install is a complete one.+ */export const repairMissingInstalledRunCompanionModules = ({callerImportMetaUrl,execPath,@@ -510,7 +614,7 @@ export const repairMissingInstalledRunCompanionModules = ({const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;- const currentFilePath = fileURLToPath(callerImportMetaUrl);+ const currentFilePath = yield* filePathFromUrl(path, callerImportMetaUrl);if (!currentFilePath.startsWith('/$bunfs/')) {return { repaired: false as const };}@@ -666,7 +770,7 @@ export const resolveRunCompanionModulePath = ({Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;- const currentFilePath = fileURLToPath(callerImportMetaUrl);+ const currentFilePath = yield* filePathFromUrl(path, callerImportMetaUrl);const currentDirectory = path.dirname(currentFilePath);const executableDirectory = path.dirname(execPath);const baseName = path.basename(relativeNoExtensionFromCaller);diff --git a/ts/packages/cli/src/services/run-helpers-runtime.ts b/ts/packages/cli/src/services/run-helpers-runtime.tsindex 586d8ea7e..2d668c486 100644--- a/ts/packages/cli/src/services/run-helpers-runtime.ts+++ b/ts/packages/cli/src/services/run-helpers-runtime.ts@@ -2,15 +2,12 @@// runtime or @effect/platform layers are provided, so it uses sync Node builtins.// 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 runtimeimport * as fs from 'node:fs';-// eslint-disable-next-line no-restricted-imports -- os.tmpdir() locates the fallback run-files directory in the child process, outside the Effect runtime-import * as os from 'node:os';-import process from 'node:process';-import { Path } from '@effect/platform';-import { Effect, Predicate, Schema } from 'effect';+import { Command, Path } from '@effect/platform';+import { BunContext } from '@effect/platform-bun';+import { Effect, Either, ManagedRuntime, Predicate, Schema } from 'effect';import { z } from 'zod';import { JsonRecordSchema } from 'src/effects/json';-import { resolveCliConfigPathSync } from 'src/services/cli-user-config';-import { detectMaster, type MasterKind } from 'src/services/master-detector';+import type { MasterKind } from 'src/services/master-detector';import {isAcpInvokeError,parseJson,@@ -20,6 +17,14 @@ import {import { invokeAcpSubAgent } from 'src/services/run-subagent-acp';import { invokeLegacySubAgent } from 'src/services/run-subagent-legacy';import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';+import { NodeOs } from 'src/services/node-os';+import { collectText } from 'src/services/command-runner';+import { debugFlagsToChildEnv } from 'src/services/runtime-flags';++// One Bun platform runtime shared by every CLI child process this module spawns. ManagedRuntime+// builds the layer lazily on first use, so importers that never spawn a child pay nothing, and a+// run script that spawns many does not rebuild the platform services per call.+const bunCommandRuntime = ManagedRuntime.make(BunContext.layer);export type RunHelperContext = {readonly apiKey?: string;@@ -32,6 +37,7 @@ export type RunHelperContext = {readonly consumerProjectName?: string;readonly perfDebug?: boolean;readonly toolDebug?: boolean;+ readonly telemetryDebug?: boolean;readonly dryRun?: boolean;readonly skipConnectionCheck?: boolean;readonly skipToolParamsCheck?: boolean;@@ -43,6 +49,7 @@ export type RunHelperContext = {readonly runOutputDir?: string;readonly runLogFilePath?: string;readonly readAccessRoots?: ReadonlyArray<string>;+ readonly cliConfigPath?: string;};type RunHelpersInstallParams = {@@ -262,12 +269,10 @@ const stringifyForPrompt = (value: unknown): string => {if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {return String(value);}- // 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- try {- return JSON.stringify(value, null, 2);- } catch {- return String(value);- }+ return Either.getOrElse(+ Either.try(() => JSON.stringify(value, null, 2)),+ () => String(value)+ );};const attachPromptMethod = <T>(value: T): T => {@@ -318,16 +323,20 @@ const summarizeCliResultPreview = (result: RunCliResult): unknown => {return result;};-const readConfiguredExperimentalSubagentTarget = (): 'auto' | 'claude' | 'codex' => {- // 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- try {- const raw = fs.readFileSync(resolveCliConfigPathSync(), 'utf8');- const parsed = decodeExperimentalSubagentConfig(raw);- const target = parsed.experimental_subagent?.target;- return target === 'claude' || target === 'codex' || target === 'auto' ? target : 'auto';- } catch {- return 'auto';- }+const readConfiguredExperimentalSubagentTarget = (+ cliConfigPath: string | undefined+): 'auto' | 'claude' | 'codex' => {+ if (!cliConfigPath) return 'auto';++ return Either.getOrElse(+ Either.try(() => {+ const raw = fs.readFileSync(cliConfigPath, 'utf8');+ const parsed = decodeExperimentalSubagentConfig(raw);+ const target = parsed.experimental_subagent?.target;+ return target === 'claude' || target === 'codex' || target === 'auto' ? target : 'auto';+ }),+ () => 'auto' as const+ );};const normalizeInvokeAgentOptions = (@@ -506,12 +515,13 @@ const createRunHelperLoggers = (params: {const createExecutePayloadMaterializer = (params: {readonly path: Path.Path;+ readonly tmpdir: string;readonly sharedRunOutputDir: string | null;}): ((value: unknown) => Promise<unknown>) => {- const { path, sharedRunOutputDir } = params;+ const { path, tmpdir, sharedRunOutputDir } = params;const writeTempExecuteFile = async (value: unknown): Promise<unknown> => {- const outputDir = sharedRunOutputDir || path.join(os.tmpdir(), 'composio-run-files');+ const outputDir = sharedRunOutputDir || path.join(tmpdir, 'composio-run-files');fs.mkdirSync(outputDir, { recursive: true });if (typeof File !== 'undefined' && value instanceof File) {const safeName =@@ -612,32 +622,59 @@ const createCliRunner = (params: {});};+ // Invariant for the life of the run session, so built once rather than per+ // spawned CLI call.+ const env: Record<string, string> = {+ // The platform command inherits the ambient environment by default. An+ // empty BUN_BE_BUN masks the parent run process's Bun compatibility flag+ // without copying or enumerating unrelated values.+ BUN_BE_BUN: '',+ ...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),+ ...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),+ ...(helperContext.webURL ? { COMPOSIO_WEB_URL: helperContext.webURL } : {}),+ COMPOSIO_CLI_INVOCATION_ORIGIN: 'run',+ ...(helperContext.runId ? { COMPOSIO_CLI_PARENT_RUN_ID: helperContext.runId } : {}),+ ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}),+ ...debugFlagsToChildEnv({+ perfDebug: perfDebugEnabled,+ toolDebug: toolDebugEnabled,+ acpOnly: helperContext.acpOnly === true,+ telemetryDebug: helperContext.telemetryDebug === true,+ }),+ };+const runCliJson = async (args: ReadonlyArray<string>): Promise<RunCliResult> => {const requestId = `${args[0] ?? 'cli'}#${++perfDebugSeq}`;helperDebugLog('cli.start', { requestId, args });- const env: Record<string, string | undefined> = {- // 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- ...process.env,- ...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),- ...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),- ...(helperContext.webURL ? { COMPOSIO_WEB_URL: helperContext.webURL } : {}),- COMPOSIO_CLI_INVOCATION_ORIGIN: 'run',- ...(helperContext.runId ? { COMPOSIO_CLI_PARENT_RUN_ID: helperContext.runId } : {}),- ...(sharedRunOutputDir ? { COMPOSIO_RUN_OUTPUT_DIR: sharedRunOutputDir } : {}),- ...(perfDebugEnabled ? { COMPOSIO_PERF_DEBUG: '1' } : {}),- ...(toolDebugEnabled ? { COMPOSIO_TOOL_DEBUG: '1' } : {}),- };- delete env.BUN_BE_BUN;perfDebugLog('start', requestId, { cmd: args });- const child = Bun.spawn({- cmd: [...cliPrefix, ...args],- env,- stdio: ['inherit', 'pipe', perfDebugEnabled || toolDebugEnabled ? 'inherit' : 'pipe'],- });- const stdout = child.stdout ? await new Response(child.stdout).text() : '';- const stderr = child.stderr ? await new Response(child.stderr).text() : '';+ const [executable, ...commandArgs] = [...cliPrefix, ...args];+ const inheritStderr = perfDebugEnabled || toolDebugEnabled;+ const { exitCode, stderr, stdout } = await bunCommandRuntime.runPromise(+ Effect.scoped(+ Effect.gen(function* () {+ const command = Command.make(executable, ...commandArgs).pipe(+ Command.env(env),+ Command.stdin('inherit'),+ Command.stderr(inheritStderr ? 'inherit' : 'pipe')+ );+ const child = yield* Command.start(command);+ const [childExitCode, childStdout, childStderr] = yield* Effect.all(+ [+ child.exitCode,+ collectText(child.stdout),+ inheritStderr ? Effect.succeed('') : collectText(child.stderr),+ ],+ { concurrency: 'unbounded' }+ );+ return {+ exitCode: Number(childExitCode),+ stdout: childStdout,+ stderr: childStderr,+ };+ })+ )+ );const result = maybeLoadStoredCliResult(parseJson(stdout));- const exitCode = await child.exited;if (exitCode !== 0) {perfDebugLog('error', requestId, { exitCode, stderr: stderr.trim() || undefined });helperDebugLog('cli.error', {@@ -762,6 +799,10 @@ const createExperimentalSubAgent = (params: {}) => {const { helperContext, helperDebugLog } = params;+ // The parent CLI resolves the master via `detectMasterFromHost` and serializes+ // it into `helperContext` (see run.cmd.ts), so a missing or unrecognized value+ // deliberately falls back to 'user' instead of re-detecting from this child+ // process's environment.const detectInvokeAgentMaster = (): MasterKind | 'user' => {if (helperContext.master === 'claude' ||@@ -770,12 +811,12 @@ const createExperimentalSubAgent = (params: {) {return helperContext.master;}- return detectMaster();+ return 'user';};const resolveInvokeAgentTarget = (requestedTarget?: string): 'claude' | 'codex' => {if (requestedTarget === 'claude' || requestedTarget === 'codex') return requestedTarget;- const configuredTarget = readConfiguredExperimentalSubagentTarget();+ const configuredTarget = readConfiguredExperimentalSubagentTarget(helperContext.cliConfigPath);if (configuredTarget === 'claude' || configuredTarget === 'codex') return configuredTarget;const detected = requestedTarget === 'user' ? 'user' : detectInvokeAgentMaster();if (detected === 'codex' || detected === 'claude') return detected;@@ -805,20 +846,20 @@ const createExperimentalSubAgent = (params: {resolvedTarget: target,master,});- // 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- try {- const response = await invokeAcpSubAgent({- prompt: prompt.trim(),- options: normalizedOptions,- master,- target,- allowedReadRoots: Array.isArray(helperContext.readAccessRoots)- ? helperContext.readAccessRoots- : [],- helperDebugLog,- });- return logFilePath ? { ...response, logFilePath } : response;- } catch (error) {+ const response = await invokeAcpSubAgent({+ prompt: prompt.trim(),+ options: normalizedOptions,+ master,+ target,+ allowedReadRoots: Array.isArray(helperContext.readAccessRoots)+ ? helperContext.readAccessRoots+ : [],+ helperDebugLog,+ }).catch(error => {+ // Only ACP protocol failures fall back to the legacy sub-agent. A damaged+ // install (MissingAcpAdapterAssetsError) is not one of them: its message+ // names the repair, and swapping in a different sub-agent implementation+ // would hide the fact that the install needs fixing.if (!isAcpInvokeError(error)) throw error;if (helperContext.acpOnly === true) throw error;helperDebugLog('subAgent.acp.fallback', {@@ -826,15 +867,15 @@ const createExperimentalSubAgent = (params: {code: error.code,message: error.message,});- const response = await invokeLegacySubAgent({+ return invokeLegacySubAgent({prompt: prompt.trim(),options: normalizedOptions,master,target,helperDebugLog,});- return logFilePath ? { ...response, logFilePath } : response;- }+ });+ return logFilePath ? { ...response, logFilePath } : response;};Object.defineProperty(experimentalSubAgentImpl, 'schema', { value: experimentalSubAgentSchema });@@ -965,17 +1006,14 @@ export const installRunHelpers = async ({// Resolve the live services once at that boundary and keep all writes centralized.const terminal = Effect.runSync(TerminalUI.pipe(Effect.provide(TerminalUILive)));const path = Effect.runSync(Path.Path.pipe(Effect.provide(Path.layer)));+ const nodeOs = Effect.runSync(NodeOs.pipe(Effect.provide(NodeOs.Default)));const writeError = (line: string) => Effect.runSync(terminal.error(line));Reflect.set(globalThis, 'z', z);Reflect.set(globalThis, 'zod', z);- const perfDebugEnabled =- // 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- helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === '1';- const toolDebugEnabled =- // 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- helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === '1';+ const perfDebugEnabled = helperContext.perfDebug === true;+ const toolDebugEnabled = helperContext.toolDebug === true;const perfDebugStart = Date.now();const composioBaseURL = (helperContext.baseURL || 'https://backend.composio.dev').replace(/\/$/,@@ -1001,6 +1039,7 @@ export const installRunHelpers = async ({const materializeExecutePayload = createExecutePayloadMaterializer({path,+ tmpdir: nodeOs.tmpdir,sharedRunOutputDir,});const runCliJson = createCliRunner({diff --git a/ts/packages/cli/src/services/run-subagent-acp.ts b/ts/packages/cli/src/services/run-subagent-acp.tsindex c0686c8aa..b6ca8bab2 100644--- a/ts/packages/cli/src/services/run-subagent-acp.ts+++ b/ts/packages/cli/src/services/run-subagent-acp.ts@@ -3,13 +3,15 @@ import type { Readable } from 'node:stream';import * as acp from '@agentclientprotocol/sdk';import { Command, FileSystem, Path } from '@effect/platform';import { BunContext } from '@effect/platform-bun';-import { Cause, Config, Effect, Exit, Layer, Option, Predicate, Queue, Stream } from 'effect';+import { Cause, Config, Data, Effect, Exit, Layer, Option, Predicate, Queue, Stream } from 'effect';import type { MasterKind } from 'src/services/master-detector';import { NodeOs } from 'src/services/node-os';import {+ codexAcpBinaryTargetFor,+ hasInstalledRunCompanionModules,resolveRunCompanionAssetPath,resolveRunCompanionModulePath,- RUN_CODEX_ACP_BINARY_TARGETS,+ RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,} from 'src/services/run-companion-modules';import {ACP_STRUCTURED_OUTPUT_TOOL_NAME,@@ -105,30 +107,95 @@ const writableStreamFromQueue = (queue: Queue.Queue<Uint8Array>): WritableStreamabort: () => Effect.runPromise(Queue.shutdown(queue)),});-const resolveShippedAdapterAsset = (- target: InvokeAgentTarget-): Effect.Effect<string | null, never, FileSystem.FileSystem | Path.Path> => {- if (target === 'claude') {- return resolveRunCompanionAssetPath({- callerImportMetaUrl: import.meta.url,- execPath: process.execPath,- relativePathFromRoot: 'acp-adapters/claude-code-acp.mjs',+/**+ * The ACP adapter assets are the lazy tier of the companion install: `composio+ * run` no longer requires them at startup, so this is the first place that can+ * observe them missing. When a packaged install has lost them, say so with the+ * fix instead of silently falling through to an npx download or a 404 from the+ * startup repair path.+ */+export class MissingAcpAdapterAssetsError extends Data.TaggedError(+ 'services/MissingAcpAdapterAssetsError'+)<{+ readonly message: string;+ readonly target: InvokeAgentTarget;+ readonly missingRelativePaths: ReadonlyArray<string>;+ readonly installDirectory: string;+}> {+ // The error crosses into the user's script as a rejection, so it reports its+ // own name rather than the internal `services/`-prefixed tag.+ override readonly name = 'MissingAcpAdapterAssetsError';+}++type ShippedAdapterAsset = {+ /** Absolute path to the adapter shipped with this install, when present. */+ readonly resolvedPath: string | null;+ /**+ * Asset paths a complete install ships for this target on this host, relative+ * to the install root. Empty when this platform has no shipped adapter at all+ * (no codex-acp binary is built for it), which is not a broken install.+ */+ readonly expectedRelativePaths: ReadonlyArray<string>;+};++const resolveShippedAdapterAsset = ({+ target,+ execPath,+}: {+ target: InvokeAgentTarget;+ execPath: string;+}): Effect.Effect<ShippedAdapterAsset, never, FileSystem.FileSystem | Path.Path> =>+ Effect.gen(function* () {+ if (target === 'claude') {+ return {+ resolvedPath: yield* resolveRunCompanionAssetPath({+ callerImportMetaUrl: import.meta.url,+ execPath,+ relativePathFromRoot: 'acp-adapters/claude-code-acp.mjs',+ }),+ // cli.js has no separate resolution step: the bundled adapter finds it+ // through import.meta.url, so name it as part of the requirement.+ expectedRelativePaths: RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,+ };+ }++ const binaryTarget = codexAcpBinaryTargetFor({+ platform: process.platform,+ arch: process.arch,});- }+ if (!binaryTarget) {+ return { resolvedPath: null, expectedRelativePaths: [] };+ }- const binaryTarget = RUN_CODEX_ACP_BINARY_TARGETS.find(- candidate => candidate.platform === process.platform && candidate.arch === process.arch- );- if (!binaryTarget) {- return Effect.succeed(null);- }+ return {+ resolvedPath: yield* resolveRunCompanionAssetPath({+ callerImportMetaUrl: import.meta.url,+ execPath,+ relativePathFromRoot: binaryTarget.relativePath,+ }),+ expectedRelativePaths: [binaryTarget.relativePath],+ };+ });- return resolveRunCompanionAssetPath({- callerImportMetaUrl: import.meta.url,- execPath: process.execPath,- relativePathFromRoot: binaryTarget.relativePath,+const missingAcpAdapterAssetsError = ({+ target,+ installDirectory,+ missingRelativePaths,+}: {+ target: InvokeAgentTarget;+ installDirectory: string;+ missingRelativePaths: ReadonlyArray<string>;+}) =>+ new MissingAcpAdapterAssetsError({+ target,+ installDirectory,+ missingRelativePaths,+ message: [+ `This Composio install cannot run a ${target} sub-agent: the ACP adapter files are missing from ${installDirectory}.`,+ ...missingRelativePaths.map(relativePath => ` - ${relativePath}`),+ `Run 'composio upgrade' to restore them, or reinstall the CLI.`,+ ].join('\n'),});-};const resolveInstalledAdapter = (target: InvokeAgentTarget): string | null => {const specifier =@@ -140,25 +207,31 @@ const resolveInstalledAdapter = (target: InvokeAgentTarget): string | null => {};export const resolveAcpAdapterCommand = (- target: InvokeAgentTarget-): Effect.Effect<AcpAdapterCommand, never, FileSystem.FileSystem | Path.Path> =>+ target: InvokeAgentTarget,+ { execPath = process.execPath }: { readonly execPath?: string } = {}+): Effect.Effect<+ AcpAdapterCommand,+ MissingAcpAdapterAssetsError,+ FileSystem.FileSystem | Path.Path+> =>Effect.gen(function* () {+ const path = yield* Path.Path;const binary = target === 'claude' ? 'claude-code-acp' : 'codex-acp';const packageName =target === 'claude' ? '@zed-industries/claude-code-acp' : '@zed-industries/codex-acp';// 1. Prefer shipped companion assets next to the CLI binary / dist bundle.- const shipped = yield* resolveShippedAdapterAsset(target);- if (shipped) {+ const shipped = yield* resolveShippedAdapterAsset({ target, execPath });+ if (shipped.resolvedPath) {if (target === 'codex') {return {- cmd: [shipped],+ cmd: [shipped.resolvedPath],source: 'shipped',} satisfies AcpAdapterCommand;}return {- cmd: [process.execPath, shipped],+ cmd: [execPath, shipped.resolvedPath],env: {BUN_BE_BUN: '1',},@@ -166,11 +239,26 @@ export const resolveAcpAdapterCommand = (} satisfies AcpAdapterCommand;}+ // A packaged install ships both the companion wrappers and the adapters. If+ // the wrappers are there and the adapters are not, the install is damaged —+ // report the repair instead of quietly downloading an adapter through npx.+ // A source checkout has no wrappers next to `bun`, so it keeps falling back.+ if (+ shipped.expectedRelativePaths.length > 0 &&+ (yield* hasInstalledRunCompanionModules(execPath))+ ) {+ return yield* missingAcpAdapterAssetsError({+ target,+ installDirectory: path.dirname(execPath),+ missingRelativePaths: shipped.expectedRelativePaths,+ });+ }+// 2. Try the installed dependency bundle next (no npx overhead).const bundled = resolveInstalledAdapter(target);if (bundled) {return {- cmd: [process.execPath, bundled],+ cmd: [execPath, bundled],env: {BUN_BE_BUN: '1',},@@ -741,10 +829,9 @@ const invokeAcpSubAgentEffect = ({args: resolved.cmd.slice(1),});- // The Claude Code CLI refuses to start when it inherits CLAUDECODE=1 (its- // nested-session guard checks `process.env.CLAUDECODE === "1"`). The- // platform Command executor always spreads process.env into the child, so- // the variable cannot be dropped; mask it with an empty string instead —+ // The Claude Code CLI refuses to start when it inherits CLAUDECODE=1. The+ // platform Command executor inherits the parent environment, so the+ // variable cannot be dropped; mask it with an empty string instead —// falsy and distinct from the guarded "1" — only when the parent has it set.const claudeCode = yield* Config.option(Config.string('CLAUDECODE'));const childEnv: Record<string, string> = {diff --git a/ts/packages/cli/src/services/run-subagent-output-mcp.ts b/ts/packages/cli/src/services/run-subagent-output-mcp.tsindex 498958344..79076f32b 100644--- a/ts/packages/cli/src/services/run-subagent-output-mcp.ts+++ b/ts/packages/cli/src/services/run-subagent-output-mcp.ts@@ -1,7 +1,7 @@-// 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-import * as fs from 'node:fs';import process from 'node:process';import { jsonSchemaToZod } from '@composio/json-schema-to-zod';+import { FileSystem } from '@effect/platform';+import { BunFileSystem } from '@effect/platform-bun';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';import { Effect } from 'effect';@@ -22,9 +22,10 @@ const readFlag = (name: string): string => {};const main = async (): Promise<void> => {+ const fs = Effect.runSync(FileSystem.FileSystem.pipe(Effect.provide(BunFileSystem.layer)));const schemaFilePath = readFlag('--schema-file');const resultFilePath = readFlag('--result-file');- const schemaText = fs.readFileSync(schemaFilePath, 'utf8');+ const schemaText = await Effect.runPromise(fs.readFileString(schemaFilePath));const structuredSchema = decodeStructuredSchemaJson(schemaText);const toolInputSchema = jsonSchemaToZod(buildStructuredOutputToolSchema(structuredSchema));@@ -42,7 +43,7 @@ const main = async (): Promise<void> => {inputSchema: toolInputSchema,},async (payload: unknown) => {- fs.writeFileSync(resultFilePath, JSON.stringify(payload), 'utf8');+ await Effect.runPromise(fs.writeFileString(resultFilePath, JSON.stringify(payload)));return {content: [{diff --git a/ts/packages/cli/src/services/runtime-cli-context.ts b/ts/packages/cli/src/services/runtime-cli-context.tsnew file mode 100644index 000000000..7fec03e05--- /dev/null+++ b/ts/packages/cli/src/services/runtime-cli-context.ts@@ -0,0 +1,40 @@+import { Context, Effect, Layer, Option } from 'effect';+import { APP_CONFIG } from 'src/effects/app-config';++export const DEFAULT_CLI_INVOCATION_ORIGIN = 'cli';++export type CliInvocationContext = {+ readonly invocationOrigin: string;+ readonly parentRunId: string | undefined;+};++/**+ * Who invoked this CLI process, and under which parent run.+ *+ * Both values arrive as the `COMPOSIO_CLI_INVOCATION_ORIGIN` / `COMPOSIO_CLI_PARENT_RUN_ID`+ * handshake `composio run` and `install.sh` set on the processes they spawn, so `effect/Config`+ * already is their injection point: a test overrides them with a config provider.+ */+export const cliInvocationContext: Effect.Effect<CliInvocationContext> = Effect.all({+ invocationOrigin: APP_CONFIG.CLI_INVOCATION_ORIGIN,+ parentRunId: APP_CONFIG.CLI_PARENT_RUN_ID,+}).pipe(+ Effect.orDie,+ Effect.map(({ invocationOrigin, parentRunId }) => ({+ invocationOrigin: invocationOrigin ?? DEFAULT_CLI_INVOCATION_ORIGIN,+ parentRunId,+ }))+);++/**+ * Run id the bootstrap resolved for a `composio run` invocation.+ *+ * `cli-main.ts` mints it while building the run's telemetry context and hands it to the command,+ * so the `CLI_RUN_*` events and the `COMPOSIO_CLI_PARENT_RUN_ID` the script's child process+ * inherits carry the same id. `None` for every other command, and for callers that drive the root+ * command directly.+ */+export class CliRunId extends Context.Tag('services/CliRunId')<CliRunId, Option.Option<string>>() {}++export const cliRunIdLayer = (runId: string | undefined): Layer.Layer<CliRunId> =>+ Layer.succeed(CliRunId, Option.fromNullable(runId));diff --git a/ts/packages/cli/src/services/runtime-debug-flags.ts b/ts/packages/cli/src/services/runtime-debug-flags.tsdeleted file mode 100644index b9357eeab..000000000--- a/ts/packages/cli/src/services/runtime-debug-flags.ts+++ /dev/null@@ -1,31 +0,0 @@-type RuntimeDebugFlags = {- readonly perfDebug: boolean;- readonly toolDebug: boolean;-};--let runtimeDebugFlags: RuntimeDebugFlags = {- perfDebug: false,- toolDebug: false,-};--export const setRuntimeDebugFlags = (flags: Partial<RuntimeDebugFlags>) => {- runtimeDebugFlags = {- perfDebug: flags.perfDebug ?? runtimeDebugFlags.perfDebug,- toolDebug: flags.toolDebug ?? runtimeDebugFlags.toolDebug,- };-};--export const resetRuntimeDebugFlags = () => {- runtimeDebugFlags = {- perfDebug: false,- toolDebug: false,- };-};--export const isPerfDebugEnabled = () =>- // 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- runtimeDebugFlags.perfDebug || process.env.COMPOSIO_PERF_DEBUG === '1';--export const isToolDebugEnabled = () =>- // 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- runtimeDebugFlags.toolDebug || process.env.COMPOSIO_TOOL_DEBUG === '1';diff --git a/ts/packages/cli/src/services/runtime-debug-logger.ts b/ts/packages/cli/src/services/runtime-debug-logger.tsindex 2fbeeffe3..75cc9be64 100644--- a/ts/packages/cli/src/services/runtime-debug-logger.ts+++ b/ts/packages/cli/src/services/runtime-debug-logger.ts@@ -1,5 +1,5 @@import { Effect } from 'effect';-import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';+import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-flags';import { TerminalUI } from 'src/services/terminal-ui';const writeJsonDebugLine = (channel: string, payload: Record<string, unknown>) =>@@ -9,15 +9,15 @@ const writeJsonDebugLine = (channel: string, payload: Record<string, unknown>) =});export const logToolDebug = (label: string, details: Record<string, unknown> = {}) =>- Effect.suspend(() =>- isToolDebugEnabled() ? writeJsonDebugLine('tool-debug', { label, ...details }) : Effect.void+ Effect.flatMap(isToolDebugEnabled, enabled =>+ enabled ? writeJsonDebugLine('tool-debug', { label, ...details }) : Effect.void);export const makePerfDebugLogger =(startedAt: number = Date.now()) =>(label: string, details: Record<string, unknown> = {}) =>- Effect.suspend(() =>- isPerfDebugEnabled()+ Effect.flatMap(isPerfDebugEnabled, enabled =>+ enabled? writeJsonDebugLine('perf', {phase: 'event',label,diff --git a/ts/packages/cli/src/services/runtime-flags.ts b/ts/packages/cli/src/services/runtime-flags.tsnew file mode 100644index 000000000..c1ea32a2b--- /dev/null+++ b/ts/packages/cli/src/services/runtime-flags.ts@@ -0,0 +1,142 @@+import { Context, Effect, Layer, Option } from 'effect';+import { APP_CONFIG, UNPREFIXED_CONFIG } from 'src/effects/app-config';+import { loadHostConfig } from 'src/services/config';++export const TELEMETRY_DEBUG_FLAG = '--telemetry-debug';++export type StrippedTelemetryDebugArgv = {+ readonly argv: ReadonlyArray<string>;+ readonly telemetryDebug: boolean;+};++/**+ * Removes `--telemetry-debug` from the CLI's own arguments and reports whether it was there.+ *+ * Only arguments before the first `--` are considered: everything after the delimiter belongs to+ * the process `composio run` spawns, so `composio run -- my-agent --telemetry-debug` has to reach+ * `my-agent` untouched.+ *+ * `src/bin.ts` runs this before the Effect runtime exists, which is why the answer travels into+ * the runtime as the `TelemetryDebugMode` service instead of module state.+ */+export const stripTelemetryDebugFlag = (+ argv: ReadonlyArray<string>+): StrippedTelemetryDebugArgv => {+ const delimiterIndex = argv.indexOf('--');+ const searchEnd = delimiterIndex < 0 ? argv.length : delimiterIndex;+ const flagIndex = argv.findIndex(+ (token, index) => index < searchEnd && token === TELEMETRY_DEBUG_FLAG+ );+ if (flagIndex < 0) {+ return { argv, telemetryDebug: false };+ }++ return {+ argv: [...argv.slice(0, flagIndex), ...argv.slice(flagIndex + 1)],+ telemetryDebug: true,+ };+};++/**+ * Values parsed from the hidden `--perf-debug` / `--tool-debug` / `--acp-only` flags.+ *+ * `undefined` means "the flag was absent", which is what lets the corresponding `COMPOSIO_*`+ * config value through; an explicit `true`/`false` always wins over it.+ */+export type CliDebugFlagOverrides = {+ readonly perfDebug: boolean | undefined;+ readonly toolDebug: boolean | undefined;+ readonly acpOnly: boolean | undefined;+};++export const NO_CLI_DEBUG_FLAG_OVERRIDES: CliDebugFlagOverrides = {+ perfDebug: undefined,+ toolDebug: undefined,+ acpOnly: undefined,+};++/**+ * Hidden debug flags of the current invocation.+ *+ * `src/commands/index.ts` parses them out of argv in one place and provides this service for the+ * command it then routes to, so every reader takes the values as an input instead of reaching for+ * process-wide state.+ */+export class CliDebugFlags extends Context.Tag('services/CliDebugFlags')<+ CliDebugFlags,+ CliDebugFlagOverrides+>() {}++export const cliDebugFlagsLayer = (+ overrides: CliDebugFlagOverrides = NO_CLI_DEBUG_FLAG_OVERRIDES+): Layer.Layer<CliDebugFlags> => Layer.succeed(CliDebugFlags, overrides);++const debugFlagOr = (+ select: (overrides: CliDebugFlagOverrides) => boolean | undefined,+ configured: Effect.Effect<boolean, never, never>+): Effect.Effect<boolean, never, CliDebugFlags> =>+ Effect.map(+ Effect.all([CliDebugFlags, configured]),+ ([overrides, configuredValue]) => select(overrides) ?? configuredValue+ );++export const isPerfDebugEnabled = debugFlagOr(+ overrides => overrides.perfDebug,+ Effect.orDie(APP_CONFIG.PERF_DEBUG)+);++export const isToolDebugEnabled = debugFlagOr(+ overrides => overrides.toolDebug,+ Effect.orDie(APP_CONFIG.TOOL_DEBUG)+);++export const isAcpOnlyEnabled = debugFlagOr(+ overrides => overrides.acpOnly,+ Effect.orDie(APP_CONFIG.RUN_ACP_ONLY)+);++/**+ * Debug state a parent CLI process resolved for the processes it spawns.+ *+ * Flags reach the parent as hidden CLI options or `COMPOSIO_*` variables, but a child only sees+ * the environment, so every spawn site has to serialize the resolved values back into it. Keeping+ * the mapping here means a flag added to this file cannot be forwarded from one spawn site and+ * forgotten at another.+ */+export type ChildProcessDebugFlags = {+ readonly perfDebug: boolean;+ readonly toolDebug: boolean;+ readonly acpOnly: boolean;+ readonly telemetryDebug: boolean;+};++export const debugFlagsToChildEnv = (flags: ChildProcessDebugFlags): Record<string, string> => ({+ COMPOSIO_PERF_DEBUG: flags.perfDebug ? '1' : '0',+ COMPOSIO_TOOL_DEBUG: flags.toolDebug ? '1' : '0',+ COMPOSIO_RUN_ACP_ONLY: flags.acpOnly ? '1' : '0',+ COMPOSIO_CLI_TELEMETRY_DEBUG: flags.telemetryDebug ? '1' : '0',+});++/**+ * Set when `--telemetry-debug` was found on the command line.+ *+ * The flag is stripped in `src/bin.ts` before the Effect runtime exists, so its value is handed to+ * the runtime as this service. Telemetry dispatch runs from service constructors and from the+ * detached worker process, where a hard requirement could not be satisfied, so readers resolve it+ * with `Effect.serviceOption` and fall back to `COMPOSIO_CLI_TELEMETRY_DEBUG`.+ */+export class TelemetryDebugMode extends Context.Tag('services/TelemetryDebugMode')<+ TelemetryDebugMode,+ boolean+>() {}++export const telemetryDebugModeLayer = (enabled: boolean): Layer.Layer<TelemetryDebugMode> =>+ Layer.succeed(TelemetryDebugMode, enabled);++export const isTelemetryDebugEnabled: Effect.Effect<boolean> = Effect.flatMap(+ Effect.serviceOption(TelemetryDebugMode),+ Option.match({+ onNone: () => loadHostConfig(UNPREFIXED_CONFIG.TELEMETRY_DEBUG),+ onSome: Effect.succeed,+ })+);diff --git a/ts/packages/cli/src/services/setup.ts b/ts/packages/cli/src/services/setup.tsindex 6a76567c7..10d457343 100644--- a/ts/packages/cli/src/services/setup.ts+++ b/ts/packages/cli/src/services/setup.ts@@ -15,6 +15,7 @@ import {} from './agent-host';import { CommandRunner, type CommandResult } from './command-runner';import { SetupSkillInstaller } from './setup-skill-installer';+import { cliInvocationContext } from './runtime-cli-context';export const SETUP_TARGETS = ['auto', ...AGENT_HOSTS, 'all'] as const;export type SetupTarget = (typeof SETUP_TARGETS)[number];@@ -829,6 +830,7 @@ const runSetupTargets = <E, R>(Effect.gen(function* () {const operation = verb === 'Uninstall' ? 'uninstall' : 'setup';const phase = verb === 'Uninstall' ? 'uninstall' : 'install';+ const { invocationOrigin } = yield* cliInvocationContext;const completed: SetupTargetResult[] = [];for (const status of inspected) {const result = yield* runAdapter(ADAPTERS[status.target], status).pipe(@@ -839,6 +841,7 @@ const runSetupTargets = <E, R>(target: status.target,phase,error,+ invocationOrigin,cliVersion: APP_VERSION,}))@@ -868,6 +871,7 @@ const runSetupTargets = <E, R>(operation,target: result.target,action,+ invocationOrigin,cliVersion: APP_VERSION,}));diff --git a/ts/packages/cli/src/services/tool-permissions.ts b/ts/packages/cli/src/services/tool-permissions.tsindex ad5d8b1bd..88adddf03 100644--- a/ts/packages/cli/src/services/tool-permissions.ts+++ b/ts/packages/cli/src/services/tool-permissions.ts@@ -4,7 +4,7 @@ import open from 'open';import { detectCliPlatform } from '@composio/cli-local-tools';import { Data, Effect, Option, Record as EffectRecord, Schema } from 'effect';import { JsonRecordSchema } from 'src/effects/json';-import { resolveCliConfigDirectorySync } from 'src/services/cli-user-config';+import { setupCacheDir } from 'src/effects/setup-cache-dir';import { atomicWriteFileString } from 'src/utils/atomic-write';import { collectDecodedEntries } from 'src/utils/collect-decoded-entries';import {@@ -170,7 +170,8 @@ interface GateParams {const allowDecisionMemoryCache = new Map<string, number>();-const cachePath = (path: Path.Path) => path.join(resolveCliConfigDirectorySync(), CACHE_FILE_NAME);+const cachePath = (path: Path.Path, cacheDirectory: string) =>+ path.join(cacheDirectory, CACHE_FILE_NAME);const cacheKey = (params: { orgId: string; projectId: string; consumerUserId: string }) =>[params.orgId, params.projectId, params.consumerUserId].join(':');const normalizeBaseUrl = (baseURL: string) => baseURL.replace(/\/$/, '');@@ -189,8 +190,12 @@ const pruneAllowEntries = ();// A missing or unreadable cache file degrades to an empty cache.-const readCacheFile = (fs: FileSystem.FileSystem, path: Path.Path): Effect.Effect<CacheFile> =>- fs.readFileString(cachePath(path)).pipe(+const readCacheFile = (+ fs: FileSystem.FileSystem,+ path: Path.Path,+ cacheDirectory: string+): Effect.Effect<CacheFile> =>+ fs.readFileString(cachePath(path, cacheDirectory)).pipe(Effect.map((raw): CacheFile => {const parsed = decodeCacheFileTolerant(raw);return {@@ -201,9 +206,14 @@ const readCacheFile = (fs: FileSystem.FileSystem, path: Path.Path): Effect.EffecEffect.orElseSucceed((): CacheFile => ({ entries: {} })));-const writeCacheFile = (fs: FileSystem.FileSystem, path: Path.Path, cache: CacheFile) =>+const writeCacheFile = (+ fs: FileSystem.FileSystem,+ path: Path.Path,+ cacheDirectory: string,+ cache: CacheFile+) =>Effect.gen(function* () {- const targetPath = cachePath(path);+ const targetPath = cachePath(path, cacheDirectory);yield* fs.makeDirectory(path.dirname(targetPath), { recursive: true });// Atomic write: on failure the temp file is dropped (best effort) and the@@ -230,20 +240,22 @@ const cacheWriteSemaphore = Effect.unsafeMakeSemaphore(1);const updateCacheFile = (fs: FileSystem.FileSystem,path: Path.Path,+ cacheDirectory: string,update: (current: CacheFile) => CacheFile) =>cacheWriteSemaphore.withPermits(1)(- readCacheFile(fs, path).pipe(- Effect.flatMap(current => writeCacheFile(fs, path, update(current)))+ readCacheFile(fs, path, cacheDirectory).pipe(+ Effect.flatMap(current => writeCacheFile(fs, path, cacheDirectory, update(current)))));const writeCacheEntry = (fs: FileSystem.FileSystem,path: Path.Path,+ cacheDirectory: string,entry: ConsumerPermissionSnapshot) =>- updateCacheFile(fs, path, current => ({+ updateCacheFile(fs, path, cacheDirectory, current => ({entries: {...current.entries,[cacheKey(entry)]: entry,@@ -254,13 +266,16 @@ const writeCacheEntry = (const readCachedEntry = (fs: FileSystem.FileSystem,path: Path.Path,+ cacheDirectory: string,params: {orgId: string;projectId: string;consumerUserId: string;}): Effect.Effect<ConsumerPermissionSnapshot | undefined> =>- readCacheFile(fs, path).pipe(Effect.map(cache => cache.entries[cacheKey(params)]));+ readCacheFile(fs, path, cacheDirectory).pipe(+ Effect.map(cache => cache.entries[cacheKey(params)])+ );const isFreshForAccounts = (entry: ConsumerPermissionSnapshot | undefined,@@ -324,6 +339,7 @@ export const refreshConsumerPermissionSnapshot = (params: {Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;+ const cacheDirectory = yield* setupCacheDir;const userContext = yield* ComposioUserContext;const apiKey = Option.getOrUndefined(userContext.data.apiKey);if (!apiKey) return undefined;@@ -410,7 +426,7 @@ export const refreshConsumerPermissionSnapshot = (params: {// A fail-closed snapshot is not persisted, so a healthy fetch replaces it// on the next command instead of pinning ask_every_call for the TTL.if (!resolved.resolveFailed) {- yield* writeCacheEntry(fs, path, snapshot).pipe(+ yield* writeCacheEntry(fs, path, cacheDirectory, snapshot).pipe(Effect.catchAll(cause =>Effect.logDebug('Failed to write the tool permissions cache',@@ -442,10 +458,11 @@ export const getConsumerPermissionSnapshot = (params: {Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;+ const cacheDirectory = yield* setupCacheDir;const connectedAccountIds = uniq(params.connectedAccountIds ?? []);// Read failures are absorbed inside readCacheFile (empty cache), so an// unreadable cache file behaves exactly like a cache miss here.- const cached = yield* readCachedEntry(fs, path, params);+ const cached = yield* readCachedEntry(fs, path, cacheDirectory, params);if (isFreshForAccounts(cached, connectedAccountIds)) {yield* refreshConsumerPermissionSnapshot({ ...params, connectedAccountIds }).pipe(@@ -554,13 +571,14 @@ const isAllowCachedInMemory = (cacheKey: string, now = Date.now()): boolean => {const isAllowCached = (fs: FileSystem.FileSystem,path: Path.Path,+ cacheDirectory: string,cacheKey: string,now = Date.now()): Effect.Effect<boolean> =>Effect.suspend(() => {if (isAllowCachedInMemory(cacheKey, now)) return Effect.succeed(true);- return readCacheFile(fs, path).pipe(+ return readCacheFile(fs, path, cacheDirectory).pipe(Effect.map(cache => {const expiresAt = cache.allowEntries?.[cacheKey]?.expiresAt;if (expiresAt === undefined || expiresAt <= now) return false;@@ -574,6 +592,7 @@ const isAllowCached = (const cacheAllowDecision = (fs: FileSystem.FileSystem,path: Path.Path,+ cacheDirectory: string,cacheKey: string,now = Date.now()) =>@@ -581,7 +600,7 @@ const cacheAllowDecision = (const expiresAt = now + ALLOW_FOR_DURATION_MS;allowDecisionMemoryCache.set(cacheKey, expiresAt);- return updateCacheFile(fs, path, current => ({+ return updateCacheFile(fs, path, cacheDirectory, current => ({entries: current.entries,allowEntries: {...current.allowEntries,@@ -1002,19 +1021,21 @@ const requestPermissionInBrowser = (params: {clearTimeout(timeout);reject(error);});- server.listen(0, '127.0.0.1', async () => {- // 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- try {- const address = server.address();- const port = typeof address === 'object' && address ? address.port : undefined;- if (!port) throw new Error('Unable to allocate permission callback port.');- await open(`http://127.0.0.1:${port}/?token=${encodeURIComponent(token)}`, {- wait: false,- });- } catch (error) {+ server.listen(0, '127.0.0.1', () => {+ const address = server.address();+ const port = typeof address === 'object' && address ? address.port : undefined;+ if (!port) {server.close();- reject(error);+ reject(new Error('Unable to allocate permission callback port.'));+ return;}++ void open(`http://127.0.0.1:${port}/?token=${encodeURIComponent(token)}`, {+ wait: false,+ }).catch(error => {+ server.close();+ reject(error);+ });});});@@ -1055,10 +1076,11 @@ export const gateToolExecution = (params: GateParams) =>const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;+ const cacheDirectory = yield* setupCacheDir;const cacheKey = allowCacheKey(params);// Read failures are absorbed inside readCacheFile (empty cache), so an// unreadable allow cache behaves exactly like "no cached allow decision".- const hasCachedAllow = yield* isAllowCached(fs, path, cacheKey);+ const hasCachedAllow = yield* isAllowCached(fs, path, cacheDirectory, cacheKey);if (hasCachedAllow) {return { approvalStatus: 'cached_approved' } satisfies PermissionGateResult;}@@ -1096,7 +1118,7 @@ export const gateToolExecution = (params: GateParams) =>}const cachesAllowOnce = state === 'ask_once' || state === 'ask_once_per_session';if (decision === 'allow_session' || (cachesAllowOnce && decision === 'allow_once')) {- yield* cacheAllowDecision(fs, path, cacheKey).pipe(+ yield* cacheAllowDecision(fs, path, cacheDirectory, cacheKey).pipe(Effect.catchAll(cause =>Effect.logDebug('Failed to cache tool permission allow decision',diff --git a/ts/packages/cli/src/services/tools-executor.ts b/ts/packages/cli/src/services/tools-executor.tsindex 0a04a7c8e..56464a479 100644--- a/ts/packages/cli/src/services/tools-executor.ts+++ b/ts/packages/cli/src/services/tools-executor.ts@@ -14,6 +14,7 @@ import {mapComposioError,} from 'src/services/composio-error-overrides';import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';+import type { CliDebugFlags } from 'src/services/runtime-flags';import { ToolFileUploadError, uploadToolInputFiles } from 'src/services/tool-file-uploads';import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';import { ToolkitSlugCatalog } from 'src/services/toolkit-slug-catalog';@@ -67,6 +68,8 @@ export interface ToolsExecutor {| ComposioToolkitsRepository| ComposioCliUserConfig| TerminalUI+ // Tool-schema resolution emits `--tool-debug` diagnostics, whose flag values the caller owns.+ | CliDebugFlags>;}diff --git a/ts/packages/cli/src/ui/colors.ts b/ts/packages/cli/src/ui/colors.tsindex 26d660fb1..ff4fb29a4 100644--- a/ts/packages/cli/src/ui/colors.ts+++ b/ts/packages/cli/src/ui/colors.ts@@ -1,4 +1,9 @@import color from 'picocolors';+import { Effect } from 'effect';+import { UNPREFIXED_CONFIG } from 'src/effects/app-config';+import { loadHostConfig } from 'src/services/config';++const colorsEnabled = !Effect.runSync(loadHostConfig(UNPREFIXED_CONFIG.NO_COLOR));export const {bold,@@ -14,5 +19,4 @@ export const {white,blue,cyanBright,- // 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-} = color.createColors(!Boolean(process.env.NO_COLOR));+} = color.createColors(colorsEnabled);diff --git a/ts/packages/cli/src/ui/redact.ts b/ts/packages/cli/src/ui/redact.tsindex 9ad42b67e..f26185ff1 100644--- a/ts/packages/cli/src/ui/redact.ts+++ b/ts/packages/cli/src/ui/redact.ts@@ -1,4 +1,11 @@-import process from 'node:process';+import { Effect } from 'effect';+import { UNPREFIXED_CONFIG } from 'src/effects/app-config';+import { loadHostConfig } from 'src/services/config';++// Read once at import time, like `ui/colors.ts`: `redact` runs per formatted+// value, and spinning up a fiber per call to read a single environment+// variable is pure overhead.+const ciRedactionEnabled = Effect.runSync(loadHostConfig(UNPREFIXED_CONFIG.CI_REDACTION_ENABLED));/*** Redact a value when running in CI (e.g., CLI recordings).@@ -12,7 +19,6 @@ export function redact<const Prefix extends string = string>({value: string;prefix?: Prefix;}): `${Prefix}${string}` {- // 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- if (process.env.CI !== 'true') return value as `${Prefix}${string}`;+ if (!ciRedactionEnabled) return value as `${Prefix}${string}`;return `${prefix ?? ''}<REDACTED>` as `${Prefix}${string}`;}diff --git a/ts/packages/cli/test/__utils__/cli.ts b/ts/packages/cli/test/__utils__/cli.tsindex 7bbfd9911..000c439ea 100644--- a/ts/packages/cli/test/__utils__/cli.ts+++ b/ts/packages/cli/test/__utils__/cli.ts@@ -1,6 +1,7 @@import { Effect } from 'effect';import * as Cli from 'src/commands';-// Run CLI in test environment-export const cli = (args: ReadonlyArray<string>) =>- Effect.flatMap(Cli.runWithConfig, run => run(['node', '<CMD>', ...args]));+// Run CLI in test environment. `bootstrap` stands in for the values `cli-main.ts` resolves before+// routing the root command (currently the `composio run` id).+export const cli = (args: ReadonlyArray<string>, bootstrap?: Cli.RootCommandBootstrap) =>+ Effect.flatMap(Cli.runWithConfig, run => run(['node', '<CMD>', ...args], bootstrap));diff --git a/ts/packages/cli/test/__utils__/services/test-layer.ts b/ts/packages/cli/test/__utils__/services/test-layer.tsindex ed1dcfcd6..0d98583e7 100644--- a/ts/packages/cli/test/__utils__/services/test-layer.ts+++ b/ts/packages/cli/test/__utils__/services/test-layer.ts@@ -23,6 +23,7 @@ import * as MockTerminal from './mock-terminal';import { TerminalUITest } from './terminal-ui-test';import type { Toolkits, ToolkitDetailed } from 'src/models/toolkits';import { NodeProcess } from 'src/services/node-process';+import { cliDebugFlagsLayer } from 'src/services/runtime-flags';import {ComposioClientSingleton,ComposioSessionRepository,@@ -99,15 +100,15 @@ export interface TestLiveInput {execPath?: string;/**- * Mock toolkit-related data to use in test.- */-toolkitsData?: {- toolkits?: Toolkits;- detailedToolkits?: ToolkitDetailed[];- tools?: Tools;- triggerTypesAsEnums?: TriggerTypesAsEnums;- triggerTypes?: TriggerTypes;-};+ * Mock toolkit-related data to use in test.+ */+ toolkitsData?: {+ toolkits?: Toolkits;+ detailedToolkits?: ToolkitDetailed[];+ tools?: Tools;+ triggerTypesAsEnums?: TriggerTypesAsEnums;+ triggerTypes?: TriggerTypes;+ };/*** Mock auth-config data to use in test.@@ -1315,6 +1316,9 @@ export const TestLayer = (input?: TestLiveInput) =>ConsumerProjectResolveFetchMock,StdinTest,TerminalUILayer,+ // `src/commands/index.ts` provides these for real invocations; direct-effect tests that+ // never route through the root command still need the "no CLI flag override" default.+ cliDebugFlagsLayer(),Layer.provide(ProjectContext.Default,Layer.mergeAll(BunFileSystem.layer, NodeOsTest, NodeProcessTest)diff --git a/ts/packages/cli/test/src/analytics.dispatch.test.ts b/ts/packages/cli/test/src/analytics.dispatch.test.tsindex 649ce330c..abc986cc9 100644--- a/ts/packages/cli/test/src/analytics.dispatch.test.ts+++ b/ts/packages/cli/test/src/analytics.dispatch.test.ts@@ -17,6 +17,7 @@ import {trackCliEventEffect,} from 'src/analytics/dispatch';import { CLI_ANALYTICS_EVENTS } from 'src/analytics/events';+import { cliRunIdLayer } from 'src/services/runtime-cli-context';import { APP_VERSION, USER_CONFIG_FILE_NAME } from 'src/constants';import { defaultNodeOs, NodeOs } from 'src/services/node-os';import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';@@ -305,6 +306,30 @@ describe('CLI analytics dispatch', () => {}).pipe(Effect.provide(makePlatformLayer(home)));});+ it.effect('propagates telemetry debug to the detached worker without an env write', () => {+ const home = tempy.temporaryDirectory();+ const scriptPath = `${home}/composio.ts`;+ enableTelemetry();+ vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DEBUG', 'true');+ process.argv[1] = scriptPath;++ return Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ yield* fs.writeFileString(scriptPath, '');+ yield* trackCliEventEffect({ name: 'producer_event' });++ const [, args, options] = childProcessMocks.spawn.mock.calls[0] as unknown as [+ string,+ string[],+ { detached: boolean; stdio: unknown },+ ];+ expect(args).toHaveLength(4);+ expect(args.at(-1)).toBe('--telemetry-debug');+ expect(options.stdio).toEqual(['ignore', 'ignore', 'inherit']);+ expect(options).not.toHaveProperty('env');+ }).pipe(Effect.provide(makePlatformLayer(home)));+ });+it.effect('spawns a detached codact worker with a decodable failure body', () => {const home = tempy.temporaryDirectory();const scriptPath = `${home}/composio.ts`;@@ -360,6 +385,34 @@ describe('CLI analytics dispatch', () => {}).pipe(Effect.provide(makePlatformLayer(home)));});+ it.effect(+ 'stamps codact failures with the minted CliRunId when no parent run id is inherited',+ () => {+ const home = tempy.temporaryDirectory();+ const scriptPath = `${home}/composio.ts`;+ enableTelemetry();+ process.argv[1] = scriptPath;++ return Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ yield* fs.writeFileString(scriptPath, '');+ yield* trackCliCodactFailureEffect({+ failureType: 'wrong_tool_slug',+ ctx: { slug: 'MISSING_TOOL' },+ });++ expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);+ const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];+ expect(decodeWorkerPayload(args[2]!)).toMatchObject({+ failure_type: 'wrong_tool_slug',+ session: {+ parent_run_id: 'run_minted',+ },+ });+ }).pipe(Effect.provide(cliRunIdLayer('run_minted')), Effect.provide(makePlatformLayer(home)));+ }+ );+it.effect('keeps both producer effects non-fatal when spawn throws', () => {const home = tempy.temporaryDirectory();enableTelemetry();diff --git a/ts/packages/cli/test/src/analytics.events.test.ts b/ts/packages/cli/test/src/analytics.events.test.tsindex b3834afd6..814c22222 100644--- a/ts/packages/cli/test/src/analytics.events.test.ts+++ b/ts/packages/cli/test/src/analytics.events.test.ts@@ -29,15 +29,26 @@ import {import { APP_VERSION } from 'src/constants';import { inferSkillReleaseChannel } from 'src/effects/install-skill';import { CLI_RELEASE_CHANNELS } from 'src/experimental-features';+import {+ DEFAULT_CLI_INVOCATION_ORIGIN,+ type CliInvocationContext,+} from 'src/services/runtime-cli-context';import { ToolInputValidationError } from 'src/services/tool-input-validation';import { resolveInstalledCliVersion } from 'src/services/run-companion-modules';+const CLI_INVOCATION = {+ invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,+ parentRunId: undefined,+} as const;+describe('CLI analytics execute failure events', () => {it('records terminal capabilities supplied by the terminal service', () => {- const context = createCliCommandTelemetryContext(['bun', 'composio'], '0.3.0', {- stdoutIsTTY: true,- stderrIsTTY: false,- });+ const context = createCliCommandTelemetryContext(+ ['bun', 'composio'],+ '0.3.0',+ { stdoutIsTTY: true, stderrIsTTY: false },+ CLI_INVOCATION+ );const event = getPrimaryLifecycleInvokedEvent(context);@@ -58,6 +69,7 @@ describe('CLI analytics execute failure events', () => {toolSlug: 'GMAIL_SEND_EMAIL',args: { recipient: '[email protected]' },error,+ invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,surface: 'root',projectMode: 'consumer',stage: 'validation',@@ -73,6 +85,7 @@ describe('CLI analytics execute failure events', () => {const event = getToolExecuteToolNotFoundEvent({toolSlug: 'FAKE_TOOL',args: {},+ invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,surface: 'root',projectMode: 'consumer',stage: 'execution',@@ -91,6 +104,7 @@ describe('CLI analytics execute failure events', () => {const event = getToolExecuteFailedEvent({toolSlug: 'GMAIL_SEND_EMAIL',args: { to: '[email protected]' },+ invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,surface: 'root',projectMode: 'consumer',stage: 'execution',@@ -172,7 +186,8 @@ describe('CLI analytics setup and install lifecycle events', () => {const context = createCliCommandTelemetryContext(['bun', 'composio', 'setup', '--target', 'codex', '--uninstall', '--yes'],APP_VERSION,- { stdoutIsTTY: false, stderrIsTTY: false }+ { stdoutIsTTY: false, stderrIsTTY: false },+ CLI_INVOCATION);const invoked = getPrimaryLifecycleInvokedEvent(context);@@ -196,7 +211,8 @@ describe('CLI analytics setup and install lifecycle events', () => {const context = createCliCommandTelemetryContext(['bun', 'composio', 'install', '--completions'],APP_VERSION,- { stdoutIsTTY: false, stderrIsTTY: false }+ { stdoutIsTTY: false, stderrIsTTY: false },+ CLI_INVOCATION);expect(getPrimaryLifecycleInvokedEvent(context)).toMatchObject({@@ -215,14 +231,16 @@ describe('CLI analytics setup and install lifecycle events', () => {createCliCommandTelemetryContext(['bun', 'composio', 'search', '[email protected] secret'],APP_VERSION,- terminal+ terminal,+ CLI_INVOCATION));const proxy = getPrimaryLifecycleInvokedEvent(createCliCommandTelemetryContext(['bun', 'composio', 'proxy', 'https://user:[email protected]/private?token=small'],APP_VERSION,- terminal+ terminal,+ CLI_INVOCATION));@@ -242,6 +260,7 @@ describe('CLI analytics setup and install lifecycle events', () => {operation: 'setup',target: 'claude',action: 'installed',+ invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,cliVersion: APP_VERSION,})).toMatchObject({@@ -266,6 +285,7 @@ describe('CLI analytics setup runtime-context events', () => {available: true,supported: true,hostVersion: '2.1.0',+ invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,cliVersion: APP_VERSION,})).toMatchObject({@@ -294,6 +314,7 @@ describe('CLI analytics setup runtime-context events', () => {supported: false,hostVersion: 'codex-cli 0.137.0',unsupportedReasonCode: 'codex_too_old',+ invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,cliVersion: APP_VERSION,})).toMatchObject({@@ -315,6 +336,7 @@ describe('CLI analytics setup runtime-context events', () => {target: 'claude',phase: 'install',error,+ invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,cliVersion: APP_VERSION,});@@ -336,6 +358,7 @@ describe('CLI analytics setup runtime-context events', () => {getSetupCancelledEvent({operation: 'setup',requestedTarget: 'claude',+ invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,cliVersion: APP_VERSION,})).toMatchObject({@@ -352,6 +375,7 @@ describe('CLI analytics setup runtime-context events', () => {getSetupSkippedEvent({operation: 'uninstall',requestedTarget: 'auto',+ invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,cliVersion: APP_VERSION,})).toMatchObject({@@ -372,11 +396,16 @@ describe('CLI analytics journey taxonomy', () => {vi.unstubAllEnvs();});- const contextFor = (argv: ReadonlyArray<string>) =>- createCliCommandTelemetryContext(['bun', 'composio', ...argv], APP_VERSION, {- stdoutIsTTY: false,- stderrIsTTY: false,- });+ const contextFor = (+ argv: ReadonlyArray<string>,+ invocation: CliInvocationContext = CLI_INVOCATION+ ) =>+ createCliCommandTelemetryContext(+ ['bun', 'composio', ...argv],+ APP_VERSION,+ { stdoutIsTTY: false, stderrIsTTY: false },+ invocation+ );const lifecycleCases: ReadonlyArray<[ReadonlyArray<string>, string]> = [[['execute', 'GMAIL_SEND_EMAIL'], 'execute'],@@ -413,6 +442,7 @@ describe('CLI analytics journey taxonomy', () => {operation: 'setup',target: 'claude',action: 'installed',+ invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,cliVersion: APP_VERSION,})?.properties?.journey_stage).toBe('setup');@@ -421,6 +451,7 @@ describe('CLI analytics journey taxonomy', () => {getSetupSkippedEvent({operation: 'setup',requestedTarget: 'auto',+ invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,cliVersion: APP_VERSION,})?.properties?.journey_stage).toBe('setup');@@ -429,6 +460,7 @@ describe('CLI analytics journey taxonomy', () => {getToolExecuteFailedEvent({toolSlug: 'GMAIL_SEND_EMAIL',args: {},+ invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,surface: 'root',projectMode: 'consumer',stage: 'execution',@@ -457,13 +489,15 @@ describe('CLI analytics journey taxonomy', () => {const context = createCliCommandTelemetryContext(['bun', 'composio', 'login'],resolvedVersion,- { stdoutIsTTY: false, stderrIsTTY: false }+ { stdoutIsTTY: false, stderrIsTTY: false },+ CLI_INVOCATION);const properties = getPrimaryLifecycleInvokedEvent(context)?.properties;const pluginProperties = getPluginLifecycleSucceededEvent({operation: 'setup',target: 'codex',action: 'installed',+ invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN,cliVersion: APP_VERSION,})?.properties;expect(inferSkillReleaseChannel(APP_VERSION)).toBe('stable');@@ -472,15 +506,29 @@ describe('CLI analytics journey taxonomy', () => {}).pipe(Effect.provide(Layer.merge(BunFileSystem.layer, BunPath.layer)));});- it('propagates the installer invocation origin from the environment', () => {- vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'installer');+ it('propagates the configured installer invocation origin', () => {+ const installerInvocation = { invocationOrigin: 'installer', parentRunId: undefined };- expect(getPrimaryLifecycleInvokedEvent(contextFor(['install']))?.properties).toMatchObject({+ expect(+ getPrimaryLifecycleInvokedEvent(contextFor(['install'], installerInvocation))?.properties+ ).toMatchObject({invocation_origin: 'installer',journey_stage: 'install',});});+ it('uses the configured parent run id for nested run telemetry', () => {+ const context = contextFor(['run', 'console.log("hi")'], {+ invocationOrigin: 'run',+ parentRunId: 'run_parent',+ });+ expect(context.runId).toBe('run_parent');+ expect(getPrimaryLifecycleInvokedEvent(context)?.properties).toMatchObject({+ invocation_origin: 'run',+ run_id: 'run_parent',+ });+ });+it('keeps the base installer install-only and marks shell-setup delegation as installer-origin', () => {const installScript = readFileSync(new URL('../../../../../install.sh', import.meta.url),diff --git a/ts/packages/cli/test/src/cli-main.test.ts b/ts/packages/cli/test/src/cli-main.test.tsindex 4f260fdf9..b57d4ae84 100644--- a/ts/packages/cli/test/src/cli-main.test.ts+++ b/ts/packages/cli/test/src/cli-main.test.ts@@ -51,4 +51,59 @@ describe('CLI process error handling', () => {'--file is not supported for local tools yet.');});++ it('reports a bare `composio run` as a usage error without a defect dump', () => {+ const configDirectory = tempy.temporaryDirectory();++ const result = spawnSync('bun', ['run', 'src/bin.ts', 'run'], {+ cwd: process.cwd(),+ encoding: 'utf8',+ env: {+ ...process.env,+ CI: '1',+ NO_COLOR: '1',+ COMPOSIO_CACHE_DIR: configDirectory,+ },+ });++ const output = `${result.stdout}\n${result.stderr}`;+ expect(result.status).toBe(1);+ expect(output).toContain('Provide inline code or use --file to run a script file.');+ // No defect banner, no source-mapped stack, and no run artifacts for a script that never ran.+ expect(output).not.toContain('MissingRunSourceError');+ expect(output).not.toContain('Sources');+ expect(output).not.toContain('RUN_LOG_FILE=');+ });++ it('normalizes telemetry debug before dispatching a background worker', () => {+ const configDirectory = tempy.temporaryDirectory();+ const encodedPayload = Buffer.from(+ JSON.stringify({+ event: 'worker_bootstrap_test',+ sentAt: '2026-08-14T00:00:00.000Z',+ source: 'cli',+ distinctId: 'install_test',+ installId: 'install_test',+ })+ ).toString('base64url');++ const result = spawnSync(+ 'bun',+ ['run', 'src/bin.ts', '__analytics-worker', encodedPayload, '--telemetry-debug'],+ {+ cwd: process.cwd(),+ encoding: 'utf8',+ env: {+ ...process.env,+ CI: 'true',+ NO_COLOR: '1',+ COMPOSIO_CACHE_DIR: configDirectory,+ },+ }+ );++ expect(result.status).toBe(0);+ expect(`${result.stdout}\n${result.stderr}`).toContain('[telemetry-debug]');+ expect(`${result.stdout}\n${result.stderr}`).toContain('posthog_delivery_skipped');+ });});diff --git a/ts/packages/cli/test/src/commands/install.cmd.test.ts b/ts/packages/cli/test/src/commands/install.cmd.test.tsindex 4ec066089..6b4552fd9 100644--- a/ts/packages/cli/test/src/commands/install.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/install.cmd.test.ts@@ -2,7 +2,7 @@ import path from 'node:path';import { Writable } from 'node:stream';import { beforeEach, vi } from 'vitest';import { describe, expect, layer } from '@effect/vitest';-import { Effect, Exit } from 'effect';+import { ConfigProvider, Effect, Exit } from 'effect';import { FileSystem } from '@effect/platform';import { NodeOs } from 'src/services/node-os';import {@@ -11,6 +11,7 @@ import {type Shell,} from 'src/commands/install.cmd';import { makeTerminalUI } from 'src/services/terminal-ui';+import { extendConfigProvider } from 'src/services/config';import { cli, TestLive, MockConsole } from 'test/__utils__';const makeSink = (isTTY: boolean) => {@@ -40,7 +41,11 @@ const SAFE_PATH = '/usr/bin:/bin';const TEST_EXEC_PATH = '/usr/local/bin/composio';const expectedRuntimeBinDir = (): string => path.dirname(TEST_EXEC_PATH);const InstallTestLive = (input: Parameters<typeof TestLive>[0] = {}) =>- TestLive({ execPath: TEST_EXEC_PATH, ...input });+ TestLive({+ baseConfigProvider: ConfigProvider.fromEnv().pipe(extendConfigProvider),+ execPath: TEST_EXEC_PATH,+ ...input,+ });const install = (params: {readonly completions?: boolean;@@ -76,6 +81,7 @@ describe('CLI: composio install', () => {// below is automatically reverted after each test — no manual save/restore.vi.stubEnv('PATH', SAFE_PATH);vi.stubEnv('COMPOSIO_BIN_DIR', '');+ vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', undefined);capturedStdout.chunks.length = 0;capturedStderr.chunks.length = 0;});@@ -1335,7 +1341,7 @@ describe('CLI: composio install', () => {});describe('[When] COMPOSIO_BIN_DIR is set and ~/.local/bin/composio is also the running executable', () => {- layer(TestLive({ execPath: '.local/bin/composio' }))(it => {+ layer(InstallTestLive({ execPath: '.local/bin/composio' }))(it => {it.scoped('[Then] the env var wins over the ~/.local/bin fallback', () =>Effect.gen(function* () {const os = yield* NodeOs;diff --git a/ts/packages/cli/test/src/commands/run.cmd.test.ts b/ts/packages/cli/test/src/commands/run.cmd.test.tsindex 96958abe6..bbac80bde 100644--- a/ts/packages/cli/test/src/commands/run.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/run.cmd.test.ts@@ -3,19 +3,33 @@ import * as os from 'node:os';import * as path from 'node:path';import { pathToFileURL } from 'node:url';import { describe, expect, layer } from '@effect/vitest';-import { Path } from '@effect/platform';+import { Command as PlatformCommand, CommandExecutor, Path } from '@effect/platform';import { BunContext } from '@effect/platform-bun';-import { Effect, Exit } from 'effect';+import {+ Cause,+ ConfigProvider,+ Effect,+ Exit,+ HashMap,+ Inspectable,+ Layer,+ Option,+ Sink,+ Stream,+} from 'effect';import { afterEach, it, vi } from 'vitest';+import { createCliCommandTelemetryContext } from 'src/analytics/events';import {buildRunHelpersSource,extractInlineExecuteToolSlugs,inferCliInvocationPrefix,+ MissingRunSourceError,wrapInlineCodeForRun,} from 'src/commands/run.cmd';import {RUN_COMPANION_MODULE_FILENAMES,- RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS,+ hasInstalledRunCompanionModules,+ hostRunCompanionStaticAssetRelativePaths,listMissingInstalledRunCompanionModules,readInstalledReleaseTag,resolveRunCompanionModulePath,@@ -29,32 +43,171 @@ import {buildStructuredToolPrompt,finalizeInvokeAgentText,} from 'src/services/run-subagent-shared';+import { extendConfigProvider } from 'src/services/config';+import { telemetryDebugModeLayer } from 'src/services/runtime-flags';+import { DEFAULT_CLI_INVOCATION_ORIGIN } from 'src/services/runtime-cli-context';import { cli, MockConsole, TestLive } from 'test/__utils__';+import { CommandRunner } from 'src/services/command-runner';++const acpOnlyConfigProvider = ConfigProvider.fromMap(+ new Map([['COMPOSIO_RUN_ACP_ONLY', '1']])+).pipe(extendConfigProvider);++const enabledRuntimeFlagsConfigProvider = ConfigProvider.fromMap(+ new Map([+ ['COMPOSIO_RUN_ACP_ONLY', '1'],+ ['COMPOSIO_PERF_DEBUG', '1'],+ ['COMPOSIO_TOOL_DEBUG', '1'],+ ])+).pipe(extendConfigProvider);++const readRunPreloadSource = (command: ReadonlyArray<string>): string => {+ const preloadPath = command[2];+ if (preloadPath === undefined) {+ throw new Error('Expected the run command to include a preload file.');+ }+ return fs.readFileSync(preloadPath, 'utf8');+};++const commandRuns = vi.fn((_: PlatformCommand.Command) =>+ Effect.succeed(CommandExecutor.ExitCode(0))+);++// `composio run` starts the child through the platform `CommandExecutor` so it owns the pid it+// forwards signals to, so the stub has to replace the executor rather than `CommandRunner`.+// `exitCode` stays suspended: the command only awaits it after the signal handlers are+// registered, which is what makes the forwarding observable below.+const STUB_CHILD_PID = 987_654;++const stubProcess = (command: PlatformCommand.Command): CommandExecutor.Process => ({+ [CommandExecutor.ProcessTypeId]: CommandExecutor.ProcessTypeId,+ pid: CommandExecutor.ProcessId(STUB_CHILD_PID),+ exitCode: Effect.suspend(() => commandRuns(command)),+ isRunning: Effect.succeed(false),+ kill: () => Effect.void,+ stdin: Sink.drain,+ stdout: Stream.empty,+ stderr: Stream.empty,+ toJSON: () => ({ _id: 'StubProcess' }),+ toString: () => 'StubProcess',+ [Inspectable.NodeInspectSymbol]: () => ({ _id: 'StubProcess' }),+});++const StubCommandExecutor = Layer.succeed(+ CommandExecutor.CommandExecutor,+ CommandExecutor.makeExecutor(command => Effect.succeed(stubProcess(command)))+);++const RunTestLive = (input: Parameters<typeof TestLive>[0] = {}) =>+ Layer.merge(+ TestLive({+ ...input,+ commandRunner: new CommandRunner({+ run: command => commandRuns(command),+ capture: () => Effect.succeed({ exitCode: 0, stdout: '', stderr: '' }),+ }),+ }),+ StubCommandExecutor+ );++const inspectRunCommand = (command: PlatformCommand.Command) => {+ const [standard] = PlatformCommand.flatten(command);+ return {+ cmd: [standard.command, ...standard.args],+ env: Object.fromEntries(HashMap.entries(standard.env)),+ extendEnv: standard.extendEnv,+ stdio: [standard.stdin, standard.stdout, standard.stderr],+ };+};describe('CLI: composio run', () => {afterEach(() => {+ process.exitCode = undefined;+ commandRuns.mockReset().mockImplementation(() => Effect.succeed(CommandExecutor.ExitCode(0)));vi.unstubAllGlobals();vi.restoreAllMocks();});- layer(TestLive())(it => {+ layer(RunTestLive())(it => {+ it.scoped('[Given] a root run telemetry id [Then] the child receives the same run id', () =>+ Effect.gen(function* () {+ const telemetryContext = createCliCommandTelemetryContext(+ ['bun', 'composio', 'run', 'console.log("hi")'],+ '0.0.0-test',+ { stdoutIsTTY: false, stderrIsTTY: false },+ { invocationOrigin: DEFAULT_CLI_INVOCATION_ORIGIN, parentRunId: undefined }+ );+ const runId = telemetryContext.runId;+ expect(runId).toBeDefined();+ if (runId === undefined) return;++ commandRuns.mockImplementation(command => {+ expect(inspectRunCommand(command).env.COMPOSIO_CLI_PARENT_RUN_ID).toBe(runId);+ return Effect.succeed(CommandExecutor.ExitCode(0));+ });++ // The bootstrap hands the run id it minted for telemetry to the command, the way+ // `cli-main.ts` does, instead of publishing it through process-wide state.+ yield* cli(['run', 'console.log("hi")'], { runId });++ expect(commandRuns).toHaveBeenCalledTimes(1);+ })+ );+ });++ layer(RunTestLive())(it => {+ it.scoped(+ '[Given] a terminal interrupt [Then] it forwards the signal to the child process group and unregisters its handlers',+ () =>+ Effect.gen(function* () {+ const signalled: Array<readonly [number, string]> = [];+ vi.spyOn(process, 'kill').mockImplementation((pid, signal) => {+ signalled.push([Number(pid), String(signal)]);+ return true;+ });++ const sigintBaseline = process.listenerCount('SIGINT');+ const sigtermBaseline = process.listenerCount('SIGTERM');+ const registeredWhileRunning: Array<{ sigint: number; sigterm: number }> = [];++ commandRuns.mockImplementation(() =>+ Effect.sync(() => {+ registeredWhileRunning.push({+ sigint: process.listenerCount('SIGINT') - sigintBaseline,+ sigterm: process.listenerCount('SIGTERM') - sigtermBaseline,+ });+ // Stand in for the terminal delivering Ctrl-C to the CLI only: the child is+ // detached into its own process group and never sees it directly.+ for (const listener of process.listeners('SIGINT').slice(sigintBaseline)) {+ listener('SIGINT');+ }+ return CommandExecutor.ExitCode(0);+ })+ );++ yield* cli(['run', 'console.log("hi")']);++ expect(registeredWhileRunning[0]).toEqual({ sigint: 1, sigterm: 1 });+ // Negative pid: the detached child leads its own process group.+ expect(signalled).toEqual([[-STUB_CHILD_PID, 'SIGINT']]);+ expect(process.listenerCount('SIGINT')).toBe(sigintBaseline);+ expect(process.listenerCount('SIGTERM')).toBe(sigtermBaseline);+ })+ );+ });++ layer(RunTestLive())(it => {it.scoped('[Given] inline code and args [Then] it forwards them to the embedded Bun runtime',() =>Effect.gen(function* () {- const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(7) }));- const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);- vi.stubGlobal('Bun', { spawn });+ commandRuns.mockImplementation(() => Effect.succeed(CommandExecutor.ExitCode(7)));yield* cli(['run', 'console.log("hi")', '--flag', 'value']);const output = yield* MockConsole.getLines();- expect(spawn).toHaveBeenCalledTimes(1);- const spawnConfig = spawn.mock.calls[0][0] as {- cmd: string[];- env: unknown;- stdio: string[];- };+ expect(commandRuns).toHaveBeenCalledTimes(1);+ const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);expect(spawnConfig.cmd[0]).toBe(process.execPath);expect(spawnConfig.cmd[1]).toBe('--preload');expect(spawnConfig.cmd[2]).toMatch(/globals\.mjs$/);@@ -63,62 +216,161 @@ describe('CLI: composio run', () => {expect(spawnConfig.cmd[4]).toContain('return (console.log("hi"));');expect(spawnConfig.cmd[4]).toContain('if (__composioResult !== undefined) {');expect(spawnConfig.cmd.slice(5)).toEqual(['--', '--flag', 'value']);- expect(spawnConfig.env).toEqual(- expect.objectContaining({- ...process.env,- BUN_BE_BUN: '1',- })- );+ expect(spawnConfig.env).toEqual(expect.objectContaining({ BUN_BE_BUN: '1' }));+ expect(spawnConfig.extendEnv).toBe(true);expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);expect(output).toContainEqual(expect.stringMatching(/^RUN_LOG_FILE=.*run\.log$/));- expect(exit).toHaveBeenCalledWith(7);+ // The preload file lives in a scoped directory and is removed with it, ...+ expect(fs.existsSync(spawnConfig.cmd[2]!)).toBe(false);+ // ... but the run log is advertised to the caller on stderr, so it has to outlive+ // the run that printed it.+ const runLogPath = output+ .find(line => line.startsWith('RUN_LOG_FILE='))+ ?.slice('RUN_LOG_FILE='.length);+ expect(runLogPath).toBeDefined();+ expect(fs.existsSync(runLogPath!)).toBe(true);+ fs.rmSync(path.dirname(runLogPath!), { recursive: true, force: true });+ expect(process.exitCode).toBe(7);+ })+ );+ });++ layer(RunTestLive({ baseConfigProvider: acpOnlyConfigProvider }))(it => {+ it.scoped(+ '[Given] COMPOSIO_RUN_ACP_ONLY=1 [Then] run enables ACP-only execution without a flag',+ () =>+ Effect.gen(function* () {+ commandRuns.mockImplementation(command => {+ expect(readRunPreloadSource(inspectRunCommand(command).cmd)).toContain(+ '"acpOnly":true'+ );+ return Effect.succeed(CommandExecutor.ExitCode(0));+ });++ yield* cli(['run', 'console.log("hi")']);++ expect(commandRuns).toHaveBeenCalledTimes(1);+ })+ );++ it.scoped('[Given] --acp-only=false and configured ACP-only mode [Then] the flag wins', () =>+ Effect.gen(function* () {+ commandRuns.mockImplementation(command => {+ expect(readRunPreloadSource(inspectRunCommand(command).cmd)).toContain('"acpOnly":false');+ return Effect.succeed(CommandExecutor.ExitCode(0));+ });++ yield* cli(['run', '--acp-only=false', 'console.log("hi")']);++ expect(commandRuns).toHaveBeenCalledTimes(1);+ })+ );+ });++ layer(RunTestLive({ baseConfigProvider: enabledRuntimeFlagsConfigProvider }))(it => {+ it.scoped('[Given] explicit false flags [Then] inherited true values are cleared', () =>+ Effect.gen(function* () {+ let preloadSource = '';+ commandRuns.mockImplementation(command => {+ preloadSource = readRunPreloadSource(inspectRunCommand(command).cmd);+ return Effect.succeed(CommandExecutor.ExitCode(0));+ });++ yield* cli([+ 'run',+ '--perf-debug=false',+ '--tool-debug=false',+ '--acp-only=false',+ 'console.log("hi")',+ ]);++ const command = inspectRunCommand(commandRuns.mock.calls[0]![0]);+ expect(command.env).toMatchObject({+ COMPOSIO_PERF_DEBUG: '0',+ COMPOSIO_TOOL_DEBUG: '0',+ COMPOSIO_RUN_ACP_ONLY: '0',+ COMPOSIO_CLI_TELEMETRY_DEBUG: '0',+ });+ expect(preloadSource).toContain('"acpOnly":false');+ })+ );+ });++ layer(Layer.merge(RunTestLive(), telemetryDebugModeLayer(true)))(it => {+ it.scoped(+ '[Given] --telemetry-debug [Then] the spawned script and its children observe it',+ () =>+ Effect.gen(function* () {+ let preloadSource = '';+ commandRuns.mockImplementation(command => {+ preloadSource = readRunPreloadSource(inspectRunCommand(command).cmd);+ return Effect.succeed(CommandExecutor.ExitCode(0));+ });++ yield* cli(['run', 'console.log("hi")']);++ const command = inspectRunCommand(commandRuns.mock.calls[0]![0]);+ expect(command.env.COMPOSIO_CLI_TELEMETRY_DEBUG).toBe('1');+ expect(preloadSource).toContain('"telemetryDebug":true');}));});- layer(TestLive())(it => {+ layer(RunTestLive())(it => {it.scoped('[Given] --acp-only [Then] run accepts the flag and forwards execution normally',() =>Effect.gen(function* () {- const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));- const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);- vi.stubGlobal('Bun', { spawn });+ commandRuns.mockImplementation(command => {+ expect(readRunPreloadSource(inspectRunCommand(command).cmd)).toContain(+ '"acpOnly":true'+ );+ return Effect.succeed(CommandExecutor.ExitCode(0));+ });yield* cli(['run', '--acp-only', 'console.log("hi")']);- expect(spawn).toHaveBeenCalledTimes(1);- const spawnConfig = spawn.mock.calls[0][0] as {- cmd: string[];- };+ expect(commandRuns).toHaveBeenCalledTimes(1);+ const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);expect(spawnConfig.cmd[3]).toBe('--eval');- expect(exit).toHaveBeenCalledWith(0);+ expect(process.exitCode).toBe(0);}));++ it.scoped('[Given] repeated invocations [Then] hidden flags do not leak', () =>+ Effect.gen(function* () {+ const preloadSources: string[] = [];+ commandRuns.mockImplementation(command => {+ preloadSources.push(readRunPreloadSource(inspectRunCommand(command).cmd));+ return Effect.succeed(CommandExecutor.ExitCode(0));+ });++ yield* cli(['run', '--acp-only', 'console.log("first")']);+ yield* cli(['run', 'console.log("second")']);++ expect(preloadSources).toHaveLength(2);+ expect(preloadSources[0]).toContain('"acpOnly":true');+ expect(preloadSources[1]).toContain('"acpOnly":false');+ })+ );});- layer(TestLive())(it => {+ layer(RunTestLive())(it => {it.scoped('[Given] --logs-off [Then] run accepts the flag and forwards execution normally',() =>Effect.gen(function* () {- const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));- const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);- vi.stubGlobal('Bun', { spawn });-yield* cli(['run', '--logs-off', 'console.log("hi")']);- expect(spawn).toHaveBeenCalledTimes(1);- const spawnConfig = spawn.mock.calls[0][0] as {- cmd: string[];- };+ expect(commandRuns).toHaveBeenCalledTimes(1);+ const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);expect(spawnConfig.cmd[3]).toBe('--eval');- expect(exit).toHaveBeenCalledWith(0);+ expect(process.exitCode).toBe(0);}));});- layer(TestLive())(it => {+ layer(RunTestLive())(it => {it.scoped('[Given] a multiline structured experimental_subAgent script [Then] run preserves the inline TypeScript source',() =>@@ -140,16 +392,10 @@ describe('CLI: composio run', () => {console.log(JSON.stringify(brief));console.log(JSON.stringify(brief.structuredOutput));`;- const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));- const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);- vi.stubGlobal('Bun', { spawn });-yield* cli(['run', '--logs-off', script]);- expect(spawn).toHaveBeenCalledTimes(1);- const spawnConfig = spawn.mock.calls[0][0] as {- cmd: string[];- };+ expect(commandRuns).toHaveBeenCalledTimes(1);+ const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);expect(spawnConfig.cmd[3]).toBe('--eval');expect(spawnConfig.cmd[4]).toContain('const brief = await experimental_subAgent(');expect(spawnConfig.cmd[4]).toContain('"Do not run terminal commands."');@@ -160,44 +406,34 @@ describe('CLI: composio run', () => {'return (console.log(JSON.stringify(brief.structuredOutput)));');expect(spawnConfig.cmd[4]).not.toContain('"Do not run terminal\n');- expect(exit).toHaveBeenCalledWith(0);+ expect(process.exitCode).toBe(0);}));});- layer(TestLive())(it => {+ layer(RunTestLive())(it => {it.scoped('[Given] --file [Then] it forwards file execution to the embedded Bun runtime', () =>Effect.gen(function* () {const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-test-'));const scriptPath = path.join(tempDir, 'script.ts');fs.writeFileSync(scriptPath, 'const value = 1 + 1;\nvalue * 2;\n', 'utf8');- const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));- const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);- vi.stubGlobal('Bun', { spawn });-try {yield* cli(['run', '--file', scriptPath, '--', 'hello']);- expect(spawn).toHaveBeenCalledTimes(1);- const spawnConfig = spawn.mock.calls[0][0] as {- cmd: string[];- env: unknown;- stdio: string[];- };+ expect(commandRuns).toHaveBeenCalledTimes(1);+ const spawnConfig = inspectRunCommand(commandRuns.mock.calls[0]![0]);expect(spawnConfig.cmd[0]).toBe(process.execPath);expect(spawnConfig.cmd[1]).toBe('--preload');expect(spawnConfig.cmd[2]).toMatch(/globals\.mjs$/);expect(spawnConfig.cmd[3]).toMatch(/\.composio-run-.*\.ts$/);expect(spawnConfig.cmd[4]).toBe('--');expect(spawnConfig.cmd[5]).toBe('hello');- expect(spawnConfig.env).toEqual(- expect.objectContaining({- ...process.env,- BUN_BE_BUN: '1',- })- );+ expect(spawnConfig.env).toEqual(expect.objectContaining({ BUN_BE_BUN: '1' }));+ expect(spawnConfig.extendEnv).toBe(true);expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);- expect(exit).toHaveBeenCalledWith(0);+ expect(fs.existsSync(spawnConfig.cmd[2]!)).toBe(false);+ expect(fs.existsSync(spawnConfig.cmd[3]!)).toBe(false);+ expect(process.exitCode).toBe(0);} finally {fs.rmSync(tempDir, { recursive: true, force: true });}@@ -205,16 +441,28 @@ describe('CLI: composio run', () => {);});- layer(TestLive())(it => {- it.scoped('[Given] no inline code and no --file [Then] it fails with a clear error', () =>- Effect.gen(function* () {- const exit = yield* cli(['run']).pipe(Effect.exit);- expect(Exit.isFailure(exit)).toBe(true);- })+ layer(RunTestLive())(it => {+ it.scoped(+ '[Given] no inline code and no --file [Then] it fails with a typed usage error, not a defect',+ () =>+ Effect.gen(function* () {+ const exit = yield* cli(['run']).pipe(Effect.exit);+ expect(Exit.isFailure(exit)).toBe(true);+ if (!Exit.isFailure(exit)) return;++ const failure = Cause.failureOption(exit.cause);+ expect(Option.isSome(failure)).toBe(true);+ expect(failure.pipe(Option.getOrThrow)).toBeInstanceOf(MissingRunSourceError);+ expect(+ String((failure.pipe(Option.getOrThrow) as MissingRunSourceError).message)+ ).toContain('Provide inline code or use --file to run a script file.');+ // Nothing was set up before the check, so no child process was started.+ expect(commandRuns).not.toHaveBeenCalled();+ }));});- layer(TestLive())(it => {+ layer(RunTestLive())(it => {it.scoped('[Given] run help [Then] it documents injected execute, search, proxy, experimental_subAgent, and z helpers',() =>@@ -386,15 +634,15 @@ describe('run-subagent-shared', () => {});describe('inferCliInvocationPrefix', () => {- layer(Path.layer)(it => {+ layer(BunContext.layer)(it => {it.effect('[Given] a compiled bunfs entrypoint [Then] it falls back to the binary path only',() =>Effect.gen(function* () {const pathService = yield* Path.Path;- expect(inferCliInvocationPrefix(pathService, ['node', '/$bunfs/root/composio'])).toEqual([- process.execPath,- ]);+ expect(+ yield* inferCliInvocationPrefix(pathService, ['node', '/$bunfs/root/composio'])+ ).toEqual([process.execPath]);}));});@@ -469,16 +717,44 @@ describe('run companion install metadata', () => {fs.writeFileSync(path.join(tempDir, RUN_COMPANION_MODULE_FILENAMES[0]!), '', 'utf8');expect(yield* listMissingInstalledRunCompanionModules(execPath)).toEqual(- [- ...RUN_COMPANION_MODULE_FILENAMES.slice(1),- ...RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS,- ]- .slice()- .sort()+ RUN_COMPANION_MODULE_FILENAMES.slice(1).slice().sort());}));+ it.effect(+ '[Given] an install without ACP adapters [Then] the startup tier reports nothing missing',+ () =>+ Effect.gen(function* () {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-no-acp-'));+ const execPath = path.join(tempDir, 'composio');+ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {+ fs.writeFileSync(path.join(tempDir, fileName), '', 'utf8');+ }++ // The ACP adapters are the lazy tier: a plain `composio run` must not+ // treat an install without them as broken.+ const hostStaticAssets = yield* hostRunCompanionStaticAssetRelativePaths;+ expect(hostStaticAssets.length).toBeGreaterThan(0);+ for (const relativePath of hostStaticAssets) {+ expect(fs.existsSync(path.join(tempDir, relativePath))).toBe(false);+ }++ expect(yield* listMissingInstalledRunCompanionModules(execPath)).toEqual([]);+ expect(yield* hasInstalledRunCompanionModules(execPath)).toBe(true);+ })+ );++ it.effect(+ '[Given] a source checkout [Then] the executable has no companion modules next to it',+ () =>+ Effect.gen(function* () {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-no-install-'));++ expect(yield* hasInstalledRunCompanionModules(path.join(tempDir, 'bun'))).toBe(false);+ })+ );+it.effect('[Given] a nested companion dependency is missing [Then] it reports the missing helper asset',() =>diff --git a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.tsindex 67b60655f..a4667847f 100644--- a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts@@ -22,10 +22,40 @@ import { ComposioCliUserConfig } from 'src/services/cli-user-config';import type { ToolkitDetailed } from 'src/models/toolkits';import { makeToolkitFixture } from 'test/__utils__/models/toolkits';+// Disable CI redaction so tests see raw values. `src/ui/redact` reads `CI` once+// at import time, so the variable has to be gone before the imports above run —+// `vi.hoisted` executes ahead of them. The explicit CI-redaction test overrides+// via `vi.spyOn` and is unaffected.+vi.hoisted(() => {+ delete process.env.CI;+});+const testConfigProvider = ConfigProvider.fromMap(new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])).pipe(extendConfigProvider);+const runInvocationConfigProvider = ConfigProvider.fromMap(+ new Map([+ ['COMPOSIO_USER_API_KEY', 'test_api_key'],+ ['COMPOSIO_CLI_INVOCATION_ORIGIN', 'run'],+ ])+).pipe(extendConfigProvider);++// Reuse the suite-managed cache directory for artifacts without exposing the+// empty test cache as the CLI's authenticated config directory.+const testArtifactConfigProvider = ConfigProvider.fromEnv().pipe(+ ConfigProvider.mapInputPath(key =>+ key === 'COMPOSIO_SESSION_DIR' ? 'COMPOSIO_CACHE_DIR' : `UNSET_${key}`+ )+);++const largeOutputConfigProvider = ConfigProvider.fromMap(+ new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])+).pipe(+ ConfigProvider.orElse(() => testArtifactConfigProvider),+ extendConfigProvider+);+const expectInvalidValueMessage = (failure: unknown, message: string) => {expect(ValidationError.isValidationError(failure)).toBe(true);if (!ValidationError.isValidationError(failure)) return;@@ -68,12 +98,7 @@ describe('CLI: composio execute', () => {}));- // Disable CI redaction so tests see raw values.- // The explicit CI-redaction test overrides via vi.spyOn and is unaffected.- let savedCI: string | undefined;beforeEach(() => {- savedCI = process.env.CI;- delete process.env.CI;vi.spyOn(composioClients, 'getLatestToolVersion').mockImplementation(() =>Effect.fail(new composioClients.HttpServerError({})));@@ -86,7 +111,6 @@ describe('CLI: composio execute', () => {});afterEach(() => {vi.restoreAllMocks();- if (savedCI !== undefined) process.env.CI = savedCI;});let recordedSessionCreateParams: Array<Record<string, unknown>> = [];@@ -191,7 +215,7 @@ describe('CLI: composio execute', () => {layer(TestLive({- baseConfigProvider: testConfigProvider,+ baseConfigProvider: runInvocationConfigProvider,fixture: 'global-test-user-id',stdin: { isTTY: true, data: '' },toolsExecutor: {@@ -210,8 +234,6 @@ describe('CLI: composio execute', () => {it => {it.scoped('returns the full JSON payload when invocation origin is run', () =>Effect.gen(function* () {- vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'run');-yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = parseLastJson(lines) as unknown as {@@ -1076,7 +1098,7 @@ describe('CLI: composio execute', () => {layer(TestLive({- baseConfigProvider: testConfigProvider,+ baseConfigProvider: largeOutputConfigProvider,fixture: 'global-test-user-id',stdin: { isTTY: true, data: '' },toolsExecutor: {diff --git a/ts/packages/cli/test/src/scripts/release-artifacts.test.ts b/ts/packages/cli/test/src/scripts/release-artifacts.test.tsnew file mode 100644index 000000000..f84bcf5df--- /dev/null+++ b/ts/packages/cli/test/src/scripts/release-artifacts.test.ts@@ -0,0 +1,140 @@+import { Either, Option } from 'effect';+import { describe, expect, it } from 'vitest';++import {+ RUN_CODEX_ACP_BINARY_TARGETS,+ RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,+ RUN_COMPANION_MODULE_FILENAMES,+ RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,+} from '../../../src/services/run-companion-modules';+import {+ archiveCompanionRelativePaths,+ ARTIFACT_NAMES,+ RELEASE_ARTIFACT_TARGETS,+ releaseArtifactTargetFor,+ UnknownReleaseArtifactError,+} from '../../../scripts/_release-artifacts';++/**+ * Everything `collectExpectedRunCompanionAssetRelativePaths` yields for a fully+ * populated companions directory: the wrappers, their bundled services, and the+ * multi-platform static asset set.+ */+const ALL_COMPANION_RELATIVE_PATHS: ReadonlyArray<string> = [+ ...RUN_COMPANION_MODULE_FILENAMES,+ ...RUN_COMPANION_MODULE_FILENAMES.map(fileName => `services/${fileName}`),+ ...RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,+].sort();++const codexAcpRelativePathsIn = (relativePaths: ReadonlyArray<string>): ReadonlyArray<string> =>+ relativePaths.filter(relativePath => relativePath.endsWith('/codex-acp'));++describe('releaseArtifactTargetFor', () => {+ it('maps every published artifact name to a Node platform/arch pair', () => {+ expect(+ RELEASE_ARTIFACT_TARGETS.map(({ artifactName, platform, arch }) => [+ artifactName,+ `${platform}-${arch}`,+ ])+ ).toEqual([+ ['composio-darwin-aarch64', 'darwin-arm64'],+ ['composio-darwin-x64', 'darwin-x64'],+ ['composio-linux-x64', 'linux-x64'],+ ['composio-linux-aarch64', 'linux-arm64'],+ ]);+ });++ it.each(ARTIFACT_NAMES)('resolves %s', artifactName => {+ const target = releaseArtifactTargetFor(artifactName);++ expect(Either.isRight(target)).toBe(true);+ });++ it('covers every codex-acp binary target exactly once', () => {+ const artifactTargets = RELEASE_ARTIFACT_TARGETS.map(+ ({ platform, arch }) => `${platform}-${arch}`+ ).sort();+ const codexTargets = RUN_CODEX_ACP_BINARY_TARGETS.map(+ ({ platform, arch }) => `${platform}-${arch}`+ ).sort();++ expect(artifactTargets).toEqual(codexTargets);+ });++ it.each(['composio-linux-arm64', 'composio-windows-x64', 'composio', ''])(+ 'rejects the unknown artifact name %o',+ artifactName => {+ const target = releaseArtifactTargetFor(artifactName);++ const error = Option.getOrUndefined(Either.getLeft(target));++ expect(error).toBeInstanceOf(UnknownReleaseArtifactError);+ expect(error?.message).toContain('Unknown release artifact');+ }+ );+});++describe('archiveCompanionRelativePaths', () => {+ it.each(RELEASE_ARTIFACT_TARGETS)(+ 'ships only $platform-$arch codex-acp in $artifactName',+ target => {+ const selected = archiveCompanionRelativePaths({+ allRelativePaths: ALL_COMPANION_RELATIVE_PATHS,+ target,+ });++ expect(codexAcpRelativePathsIn(selected)).toEqual([+ `acp-adapters/codex/${target.platform}-${target.arch}/codex-acp`,+ ]);+ }+ );++ it.each(RELEASE_ARTIFACT_TARGETS)('keeps portable assets in $artifactName', target => {+ const selected = archiveCompanionRelativePaths({+ allRelativePaths: ALL_COMPANION_RELATIVE_PATHS,+ target,+ });++ expect(selected).toEqual(+ expect.arrayContaining([+ ...RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,+ ...RUN_COMPANION_MODULE_FILENAMES,+ ...RUN_COMPANION_MODULE_FILENAMES.map(fileName => `services/${fileName}`),+ ])+ );+ });++ it.each(RELEASE_ARTIFACT_TARGETS)(+ 'drops exactly the foreign codex-acp binaries from $artifactName',+ target => {+ const selected = archiveCompanionRelativePaths({+ allRelativePaths: ALL_COMPANION_RELATIVE_PATHS,+ target,+ });++ const dropped = ALL_COMPANION_RELATIVE_PATHS.filter(+ relativePath => !selected.includes(relativePath)+ );++ expect(dropped).toEqual(+ RUN_CODEX_ACP_BINARY_TARGETS.filter(+ codexTarget =>+ codexTarget.platform !== target.platform || codexTarget.arch !== target.arch+ )+ .map(codexTarget => codexTarget.relativePath)+ .sort()+ );+ expect(dropped).toHaveLength(RUN_CODEX_ACP_BINARY_TARGETS.length - 1);+ }+ );++ it('leaves an already-narrowed list untouched', () => {+ const target = RELEASE_ARTIFACT_TARGETS[0]!;+ const selected = archiveCompanionRelativePaths({+ allRelativePaths: ALL_COMPANION_RELATIVE_PATHS,+ target,+ });++ expect(archiveCompanionRelativePaths({ allRelativePaths: selected, target })).toEqual(selected);+ });+});diff --git a/ts/packages/cli/test/src/services/cli-session-artifacts.test.ts b/ts/packages/cli/test/src/services/cli-session-artifacts.test.tsindex 0a92c050d..4c86ca008 100644--- a/ts/packages/cli/test/src/services/cli-session-artifacts.test.ts+++ b/ts/packages/cli/test/src/services/cli-session-artifacts.test.ts@@ -1,6 +1,6 @@import { FileSystem, Path } from '@effect/platform';import { describe, expect, layer } from '@effect/vitest';-import { afterEach, vi } from 'vitest';+import { afterEach, beforeEach, vi } from 'vitest';import { ConfigProvider, Effect, Option } from 'effect';import * as tempy from 'tempy';import {@@ -16,14 +16,24 @@ import { TestLive } from 'test/__utils__';const cacheEnabledTestConfigProvider = ConfigProvider.fromMap(new Map([['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false']])-).pipe(extendConfigProvider);+).pipe(+ ConfigProvider.orElse(() => ConfigProvider.fromEnv()),+ extendConfigProvider+);++const environmentTestConfigProvider = ConfigProvider.fromEnv().pipe(extendConfigProvider);describe('CLI session artifacts', () => {+ beforeEach(() => {+ vi.stubEnv('COMPOSIO_SESSION_DIR', undefined);+ vi.stubEnv('COMPOSIO_CACHE_DIR', undefined);+ });+afterEach(() => {vi.unstubAllEnvs();});- layer(TestLive())(it => {+ layer(TestLive({ baseConfigProvider: environmentTestConfigProvider }))(it => {it.scoped('resolves artifact roots in documented precedence order', () =>Effect.gen(function* () {const path = yield* Path.Path;diff --git a/ts/packages/cli/test/src/services/cli-user-config.test.ts b/ts/packages/cli/test/src/services/cli-user-config.test.tsindex 45908de34..e1abd448b 100644--- a/ts/packages/cli/test/src/services/cli-user-config.test.ts+++ b/ts/packages/cli/test/src/services/cli-user-config.test.ts@@ -8,11 +8,7 @@ import { BunFileSystem, BunPath } from '@effect/platform-bun';import { ConfigProvider, Effect, Layer } from 'effect';import { extendConfigProvider } from 'src/services/config';import { defaultNodeOs, NodeOs } from 'src/services/node-os';-import {- ComposioCliUserConfig,- ComposioCliUserConfigLive,- resolveCliConfigPathSync,-} from 'src/services/cli-user-config';+import { ComposioCliUserConfig, ComposioCliUserConfigLive } from 'src/services/cli-user-config';describe('ComposioCliUserConfig', () => {const withMapConfigProvider = (map: Map<string, string>) =>@@ -224,17 +220,4 @@ describe('ComposioCliUserConfig', () => {assertEquals(Array.isArray(JSON.parse(persisted)), false);}).pipe(Effect.provide(CliUserConfigTest));});-- it.effect('resolves sync config path from COMPOSIO_CACHE_DIR when provided', () => {- const cacheDir = tempy.temporaryDirectory();- process.env.COMPOSIO_CACHE_DIR = cacheDir;-- return Effect.sync(() => {- try {- assertEquals(resolveCliConfigPathSync(), path.join(cacheDir, 'config.json'));- } finally {- delete process.env.COMPOSIO_CACHE_DIR;- }- });- });});diff --git a/ts/packages/cli/test/src/services/config.test.ts b/ts/packages/cli/test/src/services/config.test.tsindex 195f72a91..15b97311a 100644--- a/ts/packages/cli/test/src/services/config.test.ts+++ b/ts/packages/cli/test/src/services/config.test.ts@@ -1,12 +1,26 @@-import { beforeEach, describe, it, vi } from '@effect/vitest';+import { beforeEach, describe, expect, it, vi } from '@effect/vitest';import { assertEquals } from '@effect/vitest/utils';import { Config, ConfigProvider, Effect, Option, Data, LogLevel } from 'effect';-import { APP_CONFIG } from 'src/effects/app-config';+import { APP_CONFIG, UNPREFIXED_CONFIG } from 'src/effects/app-config';import { extendConfigProvider } from 'src/services/config';import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';import * as constants from 'src/constants';+const NORMALIZED_APP_CONFIG_DEFAULTS = {+ CACHE_DIR: undefined,+ SESSION_DIR: undefined,+ BIN_DIR: undefined,+ AGENTS_BASE_URL: undefined,+ WEBHOOK_SECRET: undefined,+ CLI_INVOCATION_ORIGIN: undefined,+ CLI_PARENT_RUN_ID: undefined,+ RUN_ACP_ONLY: false,+ RUN_OUTPUT_DIR: undefined,+ PERF_DEBUG: false,+ TOOL_DEBUG: false,+};+describe('Config', () => {describe('[When] using `ConfigProvider.fromMap`', () => {const withMapConfigProvider = (map: Map<string, string>) =>@@ -25,9 +39,9 @@ describe('Config', () => {actual,Data.struct({USER_API_KEY: Option.none(),+ ...NORMALIZED_APP_CONFIG_DEFAULTS,ENVIRONMENT: Option.none(),BASE_URL: 'https://backend.composio.dev',- CACHE_DIR: Option.none(),LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),@@ -55,9 +69,9 @@ describe('Config', () => {actual,Data.struct({USER_API_KEY: Option.none(),+ ...NORMALIZED_APP_CONFIG_DEFAULTS,ENVIRONMENT: Option.none(),BASE_URL: 'https://backend.composio.dev',- CACHE_DIR: Option.none(),LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),@@ -75,7 +89,17 @@ describe('Config', () => {['COMPOSIO_BASE_URL', 'https://test.localhost'],['COMPOSIO_WEB_URL', 'https://test.localhost'],['COMPOSIO_CACHE_DIR', '~/.composio'],+ ['COMPOSIO_SESSION_DIR', '/tmp/composio-sessions'],+ ['COMPOSIO_BIN_DIR', '/usr/local/bin'],['COMPOSIO_LOG_LEVEL', 'info'],+ ['COMPOSIO_AGENTS_BASE_URL', 'https://agents.test.localhost'],+ ['COMPOSIO_WEBHOOK_SECRET', 'secret'],+ ['COMPOSIO_CLI_INVOCATION_ORIGIN', 'run'],+ ['COMPOSIO_CLI_PARENT_RUN_ID', 'run_parent'],+ ['COMPOSIO_RUN_ACP_ONLY', '1'],+ ['COMPOSIO_RUN_OUTPUT_DIR', '/tmp/composio-output'],+ ['COMPOSIO_PERF_DEBUG', '1'],+ ['COMPOSIO_TOOL_DEBUG', '1'],]) satisfies Map<string, string>;const actual = yield* withMapConfigProvider(map)(@@ -89,16 +113,112 @@ describe('Config', () => {ENVIRONMENT: Option.none(),BASE_URL: 'https://test.localhost',WEB_URL: 'https://test.localhost',- CACHE_DIR: Option.some('~/.composio'),+ CACHE_DIR: '~/.composio',+ SESSION_DIR: '/tmp/composio-sessions',+ BIN_DIR: '/usr/local/bin',LOG_LEVEL: Option.some(LogLevel.Info),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ AGENTS_BASE_URL: 'https://agents.test.localhost',+ WEBHOOK_SECRET: 'secret',+ CLI_INVOCATION_ORIGIN: 'run',+ CLI_PARENT_RUN_ID: 'run_parent',+ RUN_ACP_ONLY: true,+ RUN_OUTPUT_DIR: '/tmp/composio-output',+ PERF_DEBUG: true,+ TOOL_DEBUG: true,DISABLE_CONNECTED_ACCOUNT_CACHE: true,}));}));+ it.effect('[When] optional directory values contain whitespace', () =>+ Effect.gen(function* () {+ const map = new Map([+ ['COMPOSIO_CACHE_DIR', ' /tmp/composio-cache '],+ ['COMPOSIO_SESSION_DIR', ' '],+ ['COMPOSIO_BIN_DIR', ' /usr/local/bin '],+ ['COMPOSIO_RUN_OUTPUT_DIR', '\t/tmp/composio-output\n'],+ ]) satisfies Map<string, string>;++ const actual = yield* withMapConfigProvider(map)(+ Config.all({+ cacheDirectory: APP_CONFIG.CACHE_DIR,+ sessionDirectory: APP_CONFIG.SESSION_DIR,+ binDirectory: APP_CONFIG.BIN_DIR,+ runOutputDirectory: APP_CONFIG.RUN_OUTPUT_DIR,+ }).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ cacheDirectory: '/tmp/composio-cache',+ sessionDirectory: undefined,+ binDirectory: '/usr/local/bin',+ runOutputDirectory: '/tmp/composio-output',+ })+ );+ })+ );++ it.effect('[When] boolean flags carry blank or unrecognized values', () =>+ Effect.gen(function* () {+ // These arrive from the ambient environment, where `COMPOSIO_PERF_DEBUG=` and+ // stray values are routine. They must resolve to a boolean rather than failing+ // config decoding, which would surface as an unrecoverable defect at the call site.+ const map = new Map([+ ['COMPOSIO_PERF_DEBUG', ''],+ ['COMPOSIO_TOOL_DEBUG', ' '],+ ['COMPOSIO_RUN_ACP_ONLY', 'maybe'],+ ['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', ''],+ ]) satisfies Map<string, string>;++ const actual = yield* withMapConfigProvider(map)(+ Config.all({+ perfDebug: APP_CONFIG.PERF_DEBUG,+ toolDebug: APP_CONFIG.TOOL_DEBUG,+ acpOnly: APP_CONFIG.RUN_ACP_ONLY,+ disableConnectedAccountCache: APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE,+ }).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(+ actual,+ Data.struct({+ // Blank falls back to the flag's own default, ...+ perfDebug: false,+ toolDebug: false,+ // ... which must hold for a default-true flag too, ...+ disableConnectedAccountCache: true,+ // ... while any other non-falsy value counts as set.+ acpOnly: true,+ })+ );+ })+ );++ it.effect('[When] boolean flags carry explicit falsy words', () =>+ Effect.gen(function* () {+ const map = new Map([+ ['COMPOSIO_PERF_DEBUG', '0'],+ ['COMPOSIO_TOOL_DEBUG', 'false'],+ ['COMPOSIO_RUN_ACP_ONLY', 'OFF'],+ ]) satisfies Map<string, string>;++ const actual = yield* withMapConfigProvider(map)(+ Config.all({+ perfDebug: APP_CONFIG.PERF_DEBUG,+ toolDebug: APP_CONFIG.TOOL_DEBUG,+ acpOnly: APP_CONFIG.RUN_ACP_ONLY,+ }).pipe(Effect.andThen(Data.struct))+ );++ assertEquals(actual, Data.struct({ perfDebug: false, toolDebug: false, acpOnly: false }));+ })+ );+it.effect('[When] COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE is "false"', () =>Effect.gen(function* () {const map = new Map([@@ -113,10 +233,10 @@ describe('Config', () => {actual,Data.struct({USER_API_KEY: Option.none(),+ ...NORMALIZED_APP_CONFIG_DEFAULTS,ENVIRONMENT: Option.none(),BASE_URL: 'https://backend.composio.dev',WEB_URL: 'https://dashboard.composio.dev/',- CACHE_DIR: Option.none(),LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),@@ -141,10 +261,10 @@ describe('Config', () => {actual,Data.struct({USER_API_KEY: Option.none(),+ ...NORMALIZED_APP_CONFIG_DEFAULTS,ENVIRONMENT: Option.some('production'),BASE_URL: constants.DEFAULT_BASE_URL,WEB_URL: constants.DEFAULT_WEB_URL,- CACHE_DIR: Option.none(),LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),@@ -166,10 +286,10 @@ describe('Config', () => {actual,Data.struct({USER_API_KEY: Option.none(),+ ...NORMALIZED_APP_CONFIG_DEFAULTS,ENVIRONMENT: Option.some('staging'),BASE_URL: constants.STAGING_BASE_URL,WEB_URL: 'https://staging-dashboard.composio.dev/',- CACHE_DIR: Option.none(),LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),@@ -196,10 +316,10 @@ describe('Config', () => {actual,Data.struct({USER_API_KEY: Option.none(),+ ...NORMALIZED_APP_CONFIG_DEFAULTS,ENVIRONMENT: Option.some('staging'),BASE_URL: 'https://custom-backend.localhost',WEB_URL: constants.STAGING_WEB_URL,- CACHE_DIR: Option.none(),LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),@@ -226,10 +346,10 @@ describe('Config', () => {actual,Data.struct({USER_API_KEY: Option.none(),+ ...NORMALIZED_APP_CONFIG_DEFAULTS,ENVIRONMENT: Option.some('staging'),BASE_URL: constants.STAGING_BASE_URL,WEB_URL: 'https://custom-web.localhost',- CACHE_DIR: Option.none(),LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),@@ -251,10 +371,10 @@ describe('Config', () => {actual,Data.struct({USER_API_KEY: Option.none(),+ ...NORMALIZED_APP_CONFIG_DEFAULTS,ENVIRONMENT: Option.some('unknown'),BASE_URL: constants.DEFAULT_BASE_URL,WEB_URL: constants.DEFAULT_WEB_URL,- CACHE_DIR: Option.none(),LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),@@ -348,6 +468,63 @@ describe('Config', () => {}));});++ describe('UNPREFIXED_CONFIG', () => {+ it.effect('[Then] it normalizes unprefixed host values into runtime facts', () =>+ Effect.gen(function* () {+ const provider = ConfigProvider.fromMap(+ new Map([+ ['CACHE_DIR', ' /host/cache '],+ ['npm_config_user_agent', 'pnpm/9.0.0 npm/? node/v22.0.0 darwin arm64'],+ ['CI', ' TRUE '],+ ['NO_COLOR', '1'],+ ['COMPOSIO_CLI_TELEMETRY_DEBUG', 'true'],+ ['CODEX_FUTURE_MARKER', 'thread_test'],+ ['CLAUDE_FUTURE_MARKER', 'cli'],+ ['COMPOSIO_CALLER_AGENT', 'Open-Claw'],+ ['VITEST', 'off'],+ ]),+ { pathDelim: '_' }+ );++ const actual = yield* provider.load(Config.all(UNPREFIXED_CONFIG));++ expect(actual).toEqual({+ CACHE_DIR: '/host/cache',+ NPM_CONFIG_USER_AGENT: 'pnpm/9.0.0 npm/? node/v22.0.0 darwin arm64',+ CI_REDACTION_ENABLED: true,+ INTERACTIVE_PERMISSION_UI_DISABLED: true,+ NO_COLOR: true,+ TELEMETRY_DEBUG: true,+ MASTER_SIGNALS: { codex: true, claude: true },+ CALLER_AGENT_SIGNALS: {+ explicit: 'Open-Claw',+ openclaw: false,+ claude: true,+ codex: true,+ },+ });+ })+ );++ it.effect('[Then] an explicit permission UI value overrides CI detection', () =>+ Effect.gen(function* () {+ const provider = ConfigProvider.fromMap(+ new Map([+ ['COMPOSIO_DISABLE_PERMISSION_UI', 'false'],+ ['CI', 'true'],+ ['VITEST', 'true'],+ ]),+ { pathDelim: '_' }+ );++ assertEquals(+ yield* provider.load(UNPREFIXED_CONFIG.INTERACTIVE_PERMISSION_UI_DISABLED),+ false+ );+ })+ );+ });});describe('[When] using `ConfigProvider.env`', () => {@@ -364,9 +541,19 @@ describe('Config', () => {vi.stubEnv('COMPOSIO_BASE_URL', undefined);vi.stubEnv('COMPOSIO_WEB_URL', undefined);vi.stubEnv('COMPOSIO_CACHE_DIR', undefined);+ vi.stubEnv('COMPOSIO_SESSION_DIR', undefined);+ vi.stubEnv('COMPOSIO_BIN_DIR', undefined);vi.stubEnv('COMPOSIO_LOG_LEVEL', undefined);vi.stubEnv('COMPOSIO_ORG_ID', undefined);vi.stubEnv('COMPOSIO_PROJECT_ID', undefined);+ vi.stubEnv('COMPOSIO_AGENTS_BASE_URL', undefined);+ vi.stubEnv('COMPOSIO_WEBHOOK_SECRET', undefined);+ vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', undefined);+ vi.stubEnv('COMPOSIO_CLI_PARENT_RUN_ID', undefined);+ vi.stubEnv('COMPOSIO_RUN_ACP_ONLY', undefined);+ vi.stubEnv('COMPOSIO_RUN_OUTPUT_DIR', undefined);+ vi.stubEnv('COMPOSIO_PERF_DEBUG', undefined);+ vi.stubEnv('COMPOSIO_TOOL_DEBUG', undefined);vi.stubEnv('COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', undefined);});@@ -381,10 +568,10 @@ describe('Config', () => {actual,Data.struct({USER_API_KEY: Option.none(),+ ...NORMALIZED_APP_CONFIG_DEFAULTS,ENVIRONMENT: Option.none(),BASE_URL: 'https://backend.composio.dev',WEB_URL: 'https://dashboard.composio.dev/',- CACHE_DIR: Option.none(),LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),@@ -409,10 +596,10 @@ describe('Config', () => {actual,Data.struct({USER_API_KEY: Option.none(),+ ...NORMALIZED_APP_CONFIG_DEFAULTS,ENVIRONMENT: Option.none(),BASE_URL: 'https://backend.composio.dev',WEB_URL: 'https://dashboard.composio.dev/',- CACHE_DIR: Option.none(),LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),@@ -428,7 +615,17 @@ describe('Config', () => {vi.stubEnv('COMPOSIO_BASE_URL', 'https://test.localhost');vi.stubEnv('COMPOSIO_WEB_URL', 'https://test.localhost');vi.stubEnv('COMPOSIO_CACHE_DIR', '~/.composio');+ vi.stubEnv('COMPOSIO_SESSION_DIR', '/tmp/composio-sessions');+ vi.stubEnv('COMPOSIO_BIN_DIR', '/usr/local/bin');vi.stubEnv('COMPOSIO_LOG_LEVEL', 'info');+ vi.stubEnv('COMPOSIO_AGENTS_BASE_URL', 'https://agents.test.localhost');+ vi.stubEnv('COMPOSIO_WEBHOOK_SECRET', 'secret');+ vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'run');+ vi.stubEnv('COMPOSIO_CLI_PARENT_RUN_ID', 'run_parent');+ vi.stubEnv('COMPOSIO_RUN_ACP_ONLY', '1');+ vi.stubEnv('COMPOSIO_RUN_OUTPUT_DIR', '/tmp/composio-output');+ vi.stubEnv('COMPOSIO_PERF_DEBUG', '1');+ vi.stubEnv('COMPOSIO_TOOL_DEBUG', '1');const actual = yield* withEnvConfigProvider(Config.all(APP_CONFIG).pipe(Effect.andThen(Data.struct))@@ -441,10 +638,20 @@ describe('Config', () => {ENVIRONMENT: Option.none(),BASE_URL: 'https://test.localhost',WEB_URL: 'https://test.localhost',- CACHE_DIR: Option.some('~/.composio'),+ CACHE_DIR: '~/.composio',+ SESSION_DIR: '/tmp/composio-sessions',+ BIN_DIR: '/usr/local/bin',LOG_LEVEL: Option.some(LogLevel.Info),ORG_ID: Option.none(),PROJECT_ID: Option.none(),+ AGENTS_BASE_URL: 'https://agents.test.localhost',+ WEBHOOK_SECRET: 'secret',+ CLI_INVOCATION_ORIGIN: 'run',+ CLI_PARENT_RUN_ID: 'run_parent',+ RUN_ACP_ONLY: true,+ RUN_OUTPUT_DIR: '/tmp/composio-output',+ PERF_DEBUG: true,+ TOOL_DEBUG: true,DISABLE_CONNECTED_ACCOUNT_CACHE: true,}));@@ -463,10 +670,10 @@ describe('Config', () => {actual,Data.struct({USER_API_KEY: Option.none(),+ ...NORMALIZED_APP_CONFIG_DEFAULTS,ENVIRONMENT: Option.none(),BASE_URL: 'https://backend.composio.dev',WEB_URL: 'https://dashboard.composio.dev/',- CACHE_DIR: Option.none(),LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),@@ -488,10 +695,10 @@ describe('Config', () => {actual,Data.struct({USER_API_KEY: Option.none(),+ ...NORMALIZED_APP_CONFIG_DEFAULTS,ENVIRONMENT: Option.some('staging'),BASE_URL: constants.STAGING_BASE_URL,WEB_URL: 'https://staging-dashboard.composio.dev/',- CACHE_DIR: Option.none(),LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),@@ -515,10 +722,10 @@ describe('Config', () => {actual,Data.struct({USER_API_KEY: Option.none(),+ ...NORMALIZED_APP_CONFIG_DEFAULTS,ENVIRONMENT: Option.some('staging'),BASE_URL: 'https://custom.localhost',WEB_URL: 'https://custom-web.localhost',- CACHE_DIR: Option.none(),LOG_LEVEL: Option.none(),ORG_ID: Option.none(),PROJECT_ID: Option.none(),diff --git a/ts/packages/cli/test/src/services/master-detector.test.ts b/ts/packages/cli/test/src/services/master-detector.test.tsindex 993389f03..634396b90 100644--- a/ts/packages/cli/test/src/services/master-detector.test.ts+++ b/ts/packages/cli/test/src/services/master-detector.test.ts@@ -6,7 +6,8 @@ describe('master-detector', () => {it('detects codex when codex env markers are present', () => {expect(detectMaster({- CODEX_THREAD_ID: 'thread_123',+ codex: true,+ claude: false,})).toBe('codex');});@@ -14,7 +15,8 @@ describe('master-detector', () => {it('detects claude when claude env markers are present without codex markers', () => {expect(detectMaster({- CLAUDE_CODE_ENTRYPOINT: 'sdk-ts',+ codex: false,+ claude: true,})).toBe('claude');});@@ -22,13 +24,13 @@ describe('master-detector', () => {it('prefers codex when both codex and claude markers are present', () => {expect(detectMaster({- CLAUDE_CODE_ENTRYPOINT: 'sdk-ts',- CODEX_THREAD_ID: 'thread_123',+ codex: true,+ claude: true,})).toBe('codex');});it('falls back to user when no known agent markers are present', () => {- expect(detectMaster({})).toBe('user');+ expect(detectMaster({ codex: false, claude: false })).toBe('user');});});diff --git a/ts/packages/cli/test/src/services/native-ui-sidecar.test.ts b/ts/packages/cli/test/src/services/native-ui-sidecar.test.tsindex f9d75c0a1..2312509d1 100644--- a/ts/packages/cli/test/src/services/native-ui-sidecar.test.ts+++ b/ts/packages/cli/test/src/services/native-ui-sidecar.test.ts@@ -5,6 +5,7 @@ import {detectNativeUiCallerAgentEffect,interactivePermissionUiDisabledConfig,} from 'src/services/native-ui-sidecar';+import { UNPREFIXED_CONFIG } from 'src/effects/app-config';const loadFlag = (entries: Record<string, string>) =>ConfigProvider.fromMap(new Map(Object.entries(entries))).load(@@ -29,7 +30,13 @@ const processTreeUnavailable = executorLayer(() =>const detectAgent = (env: Record<string, string>,layer: Layer.Layer<CommandExecutor.CommandExecutor>-) => detectNativeUiCallerAgentEffect(env).pipe(Effect.provide(layer));+) =>+ Effect.gen(function* () {+ const signals = yield* ConfigProvider.fromMap(new Map(Object.entries(env)), {+ pathDelim: '_',+ }).load(UNPREFIXED_CONFIG.CALLER_AGENT_SIGNALS);+ return yield* detectNativeUiCallerAgentEffect(signals);+ }).pipe(Effect.provide(layer));describe('native UI sidecar', () => {it.effect('disables interactive permission UI in CI and Vitest environments', () =>@@ -76,11 +83,13 @@ describe('native UI sidecar', () => {it.effect('detects the caller agent from environment prefixes', () =>Effect.gen(function* () {- expect(yield* detectAgent({ OPENCLAW_GATEWAY: '1' }, processTreeMustNotRun)).toBe('openclaw');- expect(yield* detectAgent({ CLAUDE_CODE_ENTRYPOINT: 'cli' }, processTreeMustNotRun)).toBe(+ expect(yield* detectAgent({ OPENCLAW_FUTURE_MARKER: '1' }, processTreeMustNotRun)).toBe(+ 'openclaw'+ );+ expect(yield* detectAgent({ CLAUDE_FUTURE_MARKER: 'cli' }, processTreeMustNotRun)).toBe('claude');- expect(yield* detectAgent({ CODEX_HOME: '/tmp/codex' }, processTreeMustNotRun)).toBe('codex');+ expect(yield* detectAgent({ CODEX_FUTURE_MARKER: '1' }, processTreeMustNotRun)).toBe('codex');}));diff --git a/ts/packages/cli/test/src/services/run-companion-modules.test.ts b/ts/packages/cli/test/src/services/run-companion-modules.test.tsindex 2dce9ff34..48021589b 100644--- a/ts/packages/cli/test/src/services/run-companion-modules.test.ts+++ b/ts/packages/cli/test/src/services/run-companion-modules.test.ts@@ -2,14 +2,19 @@ import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import { BunContext } from '@effect/platform-bun';-import { afterEach, describe, expect, layer } from '@effect/vitest';+import { afterEach, describe, expect, it, layer } from '@effect/vitest';import { Effect } from 'effect';import { vi } from 'vitest';import {+ hostRunCompanionStaticAssetRelativePaths,+ listMissingInstalledRunCompanionModules,repairMissingInstalledRunCompanionModules,+ RUN_CODEX_ACP_BINARY_TARGETS,+ RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,RUN_COMPANION_MODULE_FILENAMES,RUN_COMPANION_RELEASE_TAG_FILENAME,- RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS,+ RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS,+ runCompanionStaticAssetRelativePathsFor,} from 'src/services/run-companion-modules';import { BaseConfigProviderLive, extendConfigProvider } from 'src/services/config';@@ -23,9 +28,10 @@ const TEST_BINARY_ASSET_NAMES = ['composio-linux-aarch64.zip','composio-linux-x64.zip',];+// A release archive ships every platform's codex-acp binary.const TEST_COMPANION_RELATIVE_PATHS = [...RUN_COMPANION_MODULE_FILENAMES,- ...RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS,+ ...RUN_COMPANION_ALL_STATIC_ASSET_RELATIVE_PATHS,].sort();const stubRepairFetch = () => {@@ -71,7 +77,126 @@ describe('run-companion-modules', () => {vi.unstubAllEnvs();});+ describe('runCompanionStaticAssetRelativePathsFor', () => {+ it('[Given] a supported host [Then] it requires only that host codex-acp binary', () => {+ for (const target of RUN_CODEX_ACP_BINARY_TARGETS) {+ expect(+ runCompanionStaticAssetRelativePathsFor({+ platform: target.platform,+ arch: target.arch,+ })+ ).toEqual([...RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS, target.relativePath]);+ }+ });++ it('[Given] an unsupported host [Then] it requires only the portable assets', () => {+ expect(runCompanionStaticAssetRelativePathsFor({ platform: 'win32', arch: 'x64' })).toEqual(+ RUN_COMPANION_SHARED_STATIC_ASSET_RELATIVE_PATHS+ );+ });+ });+layer(BunContext.layer)(it => {+ it.effect(+ "[Given] an install lacking another platform's codex-acp binary [Then] nothing needs repair",+ () =>+ Effect.gen(function* () {+ const hostStaticAssets = yield* hostRunCompanionStaticAssetRelativePaths;+ const foreignRelativePaths = RUN_CODEX_ACP_BINARY_TARGETS.map(+ target => target.relativePath+ ).filter(relativePath => !hostStaticAssets.includes(relativePath));++ expect(foreignRelativePaths.length).toBe(RUN_CODEX_ACP_BINARY_TARGETS.length - 1);++ const installDirectory = fs.mkdtempSync(+ path.join(os.tmpdir(), 'composio-run-host-scope-')+ );+ const execPath = path.join(installDirectory, 'composio');+ for (const relativePath of [...RUN_COMPANION_MODULE_FILENAMES, ...hostStaticAssets]) {+ const filePath = path.join(installDirectory, relativePath);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, `installed:${relativePath}`);+ }+ const fetchMock = stubRepairFetch();++ return yield* Effect.gen(function* () {+ expect(yield* listMissingInstalledRunCompanionModules(execPath)).toEqual([]);+ expect(+ yield* repairMissingInstalledRunCompanionModules({+ callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',+ execPath,+ appVersion: '0.0.0-test',+ })+ ).toEqual({ repaired: false });+ expect(fetchMock).not.toHaveBeenCalled();+ }).pipe(+ Effect.ensuring(+ Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))+ )+ );+ })+ );++ it.effect(+ '[Given] an install without ACP adapters [Then] a plain run neither reports nor repairs anything',+ () =>+ Effect.gen(function* () {+ const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-no-acp-'));+ const execPath = path.join(installDirectory, 'composio');+ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {+ fs.writeFileSync(path.join(installDirectory, fileName), '', 'utf8');+ }+ const fetchMock = stubRepairFetch();++ return yield* Effect.gen(function* () {+ expect(yield* listMissingInstalledRunCompanionModules(execPath)).toEqual([]);+ expect(+ yield* repairMissingInstalledRunCompanionModules({+ callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',+ execPath,+ appVersion: '0.0.0-test',+ })+ ).toEqual({ repaired: false });+ // The self-repair download is what 404s on a dev build; the ACP tier+ // must never reach it.+ expect(fetchMock).not.toHaveBeenCalled();+ }).pipe(+ Effect.ensuring(+ Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))+ )+ );+ })+ );++ it.effect(+ '[Given] a missing companion wrapper [Then] repair still restores the ACP tier too',+ () => {+ const installDirectory = fs.mkdtempSync(+ path.join(os.tmpdir(), 'composio-run-tier-repair-')+ );+ const execPath = path.join(installDirectory, 'composio');+ stubRepairFetch();+ mockArchiveContents();++ return Effect.gen(function* () {+ const result = yield* repairMissingInstalledRunCompanionModules({+ callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',+ execPath,+ appVersion: '0.0.0-test',+ });++ expect(result).toEqual({ repaired: true, releaseTag: TEST_RELEASE_TAG });+ for (const relativePath of yield* hostRunCompanionStaticAssetRelativePaths) {+ expect(fs.existsSync(path.join(installDirectory, relativePath))).toBe(true);+ }+ }).pipe(+ Effect.ensuring(+ Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))+ )+ );+ }+ );+it.effect('[Given] a complete archive [Then] repair atomically replaces companions', () => {const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-repair-test-'));const execPath = path.join(installDirectory, 'composio');diff --git a/ts/packages/cli/test/src/services/run-helpers-runtime.test.ts b/ts/packages/cli/test/src/services/run-helpers-runtime.test.tsindex ac0b72d6a..da636c8b7 100644--- a/ts/packages/cli/test/src/services/run-helpers-runtime.test.ts+++ b/ts/packages/cli/test/src/services/run-helpers-runtime.test.ts@@ -61,4 +61,50 @@ describe('run-helpers-runtime', () => {await expect(installedGlobals.proxy('github')).rejects.toThrow(/session_id/);expect(fetchMock).toHaveBeenCalledOnce();});++ it('[Given] normalized false flags [Then] nested CLI children receive false explicitly', async () => {+ vi.stubEnv('COMPOSIO_RUN_ENV_SENTINEL', 'forwarded');+ vi.stubEnv('COMPOSIO_PERF_DEBUG', '1');+ vi.stubEnv('COMPOSIO_TOOL_DEBUG', '1');+ vi.stubEnv('COMPOSIO_RUN_ACP_ONLY', '1');+ vi.stubEnv('BUN_BE_BUN', '1');++ const childScript = [+ 'console.log(JSON.stringify({',+ ' successful: true,',+ ' data: {',+ ' sentinel: process.env.COMPOSIO_RUN_ENV_SENTINEL,',+ ' perfDebug: process.env.COMPOSIO_PERF_DEBUG,',+ ' toolDebug: process.env.COMPOSIO_TOOL_DEBUG,',+ ' acpOnly: process.env.COMPOSIO_RUN_ACP_ONLY,',+ ' bunBeBun: process.env.BUN_BE_BUN,',+ ' },',+ '}));',+ ].join('\n');++ await installRunHelpers({+ cliPrefix: [process.execPath, '-e', childScript],+ helperContext: { perfDebug: false, toolDebug: false, acpOnly: false },+ });++ const installedGlobals: unknown = globalThis;+ expect(Predicate.hasProperty(installedGlobals, 'search')).toBe(true);+ if (+ !Predicate.hasProperty(installedGlobals, 'search') ||+ typeof installedGlobals.search !== 'function'+ ) {+ throw new Error('installRunHelpers() did not install search().');+ }++ await expect(installedGlobals.search('test')).resolves.toMatchObject({+ successful: true,+ data: {+ sentinel: 'forwarded',+ perfDebug: '0',+ toolDebug: '0',+ acpOnly: '0',+ bunBeBun: '',+ },+ });+ });});diff --git a/ts/packages/cli/test/src/services/run-subagent-acp.test.ts b/ts/packages/cli/test/src/services/run-subagent-acp.test.tsindex 77bf0ce2d..b92e86d67 100644--- a/ts/packages/cli/test/src/services/run-subagent-acp.test.ts+++ b/ts/packages/cli/test/src/services/run-subagent-acp.test.ts@@ -1,3 +1,6 @@+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';import { Readable } from 'node:stream';import { BunContext } from '@effect/platform-bun';import { Effect } from 'effect';@@ -5,10 +8,12 @@ import { afterEach, describe, expect, it, vi } from '@effect/vitest';import {BufferedChunkLogger,createStructuredOutputMcpContext,+ MissingAcpAdapterAssetsError,readableStreamFromNode,resolveAcpAdapterCommand,selectPermissionOutcome,} from 'src/services/run-subagent-acp';+import { RUN_COMPANION_MODULE_FILENAMES } from 'src/services/run-companion-modules';import { AcpInvokeError, isAcpInvokeError } from 'src/services/run-subagent-shared';describe('run-subagent-acp', () => {@@ -57,6 +62,61 @@ describe('run-subagent-acp', () => {}).pipe(Effect.provide(BunContext.layer)));+ it.effect(+ '[Given] a packaged install shipping the adapter [Then] it runs the shipped asset',+ () =>+ Effect.gen(function* () {+ const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-acp-shipped-'));+ const execPath = path.join(installDirectory, 'composio');+ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {+ fs.writeFileSync(path.join(installDirectory, fileName), '', 'utf8');+ }+ const adapterPath = path.join(installDirectory, 'acp-adapters', 'claude-code-acp.mjs');+ fs.mkdirSync(path.dirname(adapterPath), { recursive: true });+ fs.writeFileSync(adapterPath, '', 'utf8');++ return yield* Effect.gen(function* () {+ const result = yield* resolveAcpAdapterCommand('claude', { execPath });+ expect(result.source).toBe('shipped');+ expect(result.cmd).toEqual([execPath, adapterPath]);+ }).pipe(+ Effect.ensuring(+ Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))+ )+ );+ }).pipe(Effect.provide(BunContext.layer))+ );++ it.effect(+ '[Given] a packaged install missing the ACP adapters [Then] it names the repair instead of falling back',+ () =>+ Effect.gen(function* () {+ const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-acp-missing-'));+ const execPath = path.join(installDirectory, 'composio');+ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {+ fs.writeFileSync(path.join(installDirectory, fileName), '', 'utf8');+ }++ return yield* Effect.gen(function* () {+ const error = yield* Effect.flip(resolveAcpAdapterCommand('claude', { execPath }));++ expect(error).toBeInstanceOf(MissingAcpAdapterAssetsError);+ expect(error.missingRelativePaths).toContain('acp-adapters/claude-code-acp.mjs');+ expect(error.message).toContain(+ `This Composio install cannot run a claude sub-agent: the ACP adapter files are missing from ${installDirectory}.`+ );+ expect(error.message).toContain("Run 'composio upgrade' to restore them");+ // Not an AcpInvokeError, so the helper runtime surfaces it to the user+ // instead of silently retrying through the legacy sub-agent.+ expect(isAcpInvokeError(error)).toBe(false);+ }).pipe(+ Effect.ensuring(+ Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))+ )+ );+ }).pipe(Effect.provide(BunContext.layer))+ );+it('[Given] an ACP invoke error [Then] it is classified for fallback', () => {const error = new AcpInvokeError('initialize_failed', 'boom');expect(isAcpInvokeError(error)).toBe(true);diff --git a/ts/packages/cli/test/src/services/runtime-debug-logger.test.ts b/ts/packages/cli/test/src/services/runtime-debug-logger.test.tsindex f30a5c484..4f51041c8 100644--- a/ts/packages/cli/test/src/services/runtime-debug-logger.test.ts+++ b/ts/packages/cli/test/src/services/runtime-debug-logger.test.ts@@ -1,31 +1,42 @@import { afterEach, describe, expect, layer, vi } from '@effect/vitest';-import { Effect } from 'effect';+import { ConfigProvider, Effect } from 'effect';import { logToolDebug, makePerfDebugLogger } from 'src/services/runtime-debug-logger';-import { resetRuntimeDebugFlags, setRuntimeDebugFlags } from 'src/services/runtime-debug-flags';+import {+ cliDebugFlagsLayer,+ NO_CLI_DEBUG_FLAG_OVERRIDES,+ type CliDebugFlagOverrides,+} from 'src/services/runtime-flags';+import { extendConfigProvider } from 'src/services/config';import { MockConsole, TestLive } from 'test/__utils__';+const configuredDebugFlags = ConfigProvider.fromMap(+ new Map([+ ['COMPOSIO_PERF_DEBUG', '1'],+ ['COMPOSIO_TOOL_DEBUG', '1'],+ ])+).pipe(extendConfigProvider);++const withDebugFlags = (overrides: Partial<CliDebugFlagOverrides>) =>+ Effect.provide(cliDebugFlagsLayer({ ...NO_CLI_DEBUG_FLAG_OVERRIDES, ...overrides }));+describe('runtime debug logger', () => {afterEach(() => {- resetRuntimeDebugFlags();vi.restoreAllMocks();});layer(TestLive())(it => {it.scoped('writes tool diagnostics as the existing JSON line format', () =>Effect.gen(function* () {- setRuntimeDebugFlags({ toolDebug: true });-yield* logToolDebug('resolved', { slug: 'GITHUB_GET_REPO' });expect(yield* MockConsole.getLines()).toContain('[tool-debug] {"label":"resolved","slug":"GITHUB_GET_REPO"}');- })+ }).pipe(withDebugFlags({ toolDebug: true })));it.scoped('writes performance diagnostics with elapsed time', () =>Effect.gen(function* () {- setRuntimeDebugFlags({ perfDebug: true });vi.spyOn(Date, 'now').mockReturnValue(125);const logPerfDebug = makePerfDebugLogger(100);@@ -34,7 +45,36 @@ describe('runtime debug logger', () => {expect(yield* MockConsole.getLines()).toContain('[perf] {"phase":"event","label":"started","elapsedMs":25,"slug":"GITHUB_GET_REPO"}');- })+ }).pipe(withDebugFlags({ perfDebug: true }))+ );++ it.scoped('writes diagnostics enabled through app config', () =>+ Effect.gen(function* () {+ vi.spyOn(Date, 'now').mockReturnValue(125);++ yield* logToolDebug('configured-tool');+ yield* makePerfDebugLogger(100)('configured-perf');++ const lines = yield* MockConsole.getLines();+ expect(lines).toContain('[tool-debug] {"label":"configured-tool"}');+ expect(lines).toContain(+ '[perf] {"phase":"event","label":"configured-perf","elapsedMs":25}'+ );+ }).pipe(withDebugFlags({}), Effect.withConfigProvider(configuredDebugFlags))+ );++ it.scoped('lets explicit false flags override enabled app config', () =>+ Effect.gen(function* () {+ const existingLineCount = (yield* MockConsole.getLines()).length;++ yield* logToolDebug('configured-tool');+ yield* makePerfDebugLogger(100)('configured-perf');++ expect((yield* MockConsole.getLines()).slice(existingLineCount)).toEqual([]);+ }).pipe(+ withDebugFlags({ perfDebug: false, toolDebug: false }),+ Effect.withConfigProvider(configuredDebugFlags)+ ));});});diff --git a/ts/packages/cli/test/src/services/runtime-flags.test.ts b/ts/packages/cli/test/src/services/runtime-flags.test.tsnew file mode 100644index 000000000..d7c2c7fb6--- /dev/null+++ b/ts/packages/cli/test/src/services/runtime-flags.test.ts@@ -0,0 +1,141 @@+import { afterEach, vi } from 'vitest';+import { describe, expect, it, layer } from '@effect/vitest';+import { ConfigProvider, Effect } from 'effect';+import {+ cliDebugFlagsLayer,+ debugFlagsToChildEnv,+ isAcpOnlyEnabled,+ isPerfDebugEnabled,+ isTelemetryDebugEnabled,+ isToolDebugEnabled,+ NO_CLI_DEBUG_FLAG_OVERRIDES,+ stripTelemetryDebugFlag,+ telemetryDebugModeLayer,+ TELEMETRY_DEBUG_FLAG,+} from 'src/services/runtime-flags';+import { extendConfigProvider } from 'src/services/config';+import { TestLive } from 'test/__utils__';++describe('debugFlagsToChildEnv', () => {+ it('[Given] resolved debug flags [Then] every flag serializes into the child environment', () => {+ expect(+ debugFlagsToChildEnv({+ perfDebug: true,+ toolDebug: false,+ acpOnly: true,+ telemetryDebug: false,+ })+ ).toEqual({+ COMPOSIO_PERF_DEBUG: '1',+ COMPOSIO_TOOL_DEBUG: '0',+ COMPOSIO_RUN_ACP_ONLY: '1',+ COMPOSIO_CLI_TELEMETRY_DEBUG: '0',+ });+ });+});++describe('stripTelemetryDebugFlag', () => {+ it('[Given] the flag before the delimiter [Then] it is removed and reported', () => {+ expect(stripTelemetryDebugFlag(['bun', 'composio', TELEMETRY_DEBUG_FLAG, 'whoami'])).toEqual({+ argv: ['bun', 'composio', 'whoami'],+ telemetryDebug: true,+ });+ });++ it('[Given] the flag after a `--` delimiter [Then] it belongs to the child and survives', () => {+ const argv = ['bun', 'composio', 'run', 'my-agent', '--', TELEMETRY_DEBUG_FLAG];++ expect(stripTelemetryDebugFlag(argv)).toEqual({ argv, telemetryDebug: false });+ });++ it('[Given] the flag on both sides of `--` [Then] only the CLI-side one is consumed', () => {+ expect(+ stripTelemetryDebugFlag([+ 'bun',+ 'composio',+ TELEMETRY_DEBUG_FLAG,+ 'run',+ 'my-agent',+ '--',+ TELEMETRY_DEBUG_FLAG,+ ])+ ).toEqual({+ argv: ['bun', 'composio', 'run', 'my-agent', '--', TELEMETRY_DEBUG_FLAG],+ telemetryDebug: true,+ });+ });++ it('[Given] no flag [Then] argv is reported unchanged', () => {+ const argv = ['bun', 'composio', 'whoami'];++ expect(stripTelemetryDebugFlag(argv)).toEqual({ argv, telemetryDebug: false });+ });+});++const enabledDebugConfig = ConfigProvider.fromMap(+ new Map([+ ['COMPOSIO_PERF_DEBUG', '1'],+ ['COMPOSIO_TOOL_DEBUG', '1'],+ ['COMPOSIO_RUN_ACP_ONLY', '1'],+ ])+).pipe(extendConfigProvider);++const readAllDebugFlags = Effect.all({+ perfDebug: isPerfDebugEnabled,+ toolDebug: isToolDebugEnabled,+ acpOnly: isAcpOnlyEnabled,+});++describe('debug flag precedence', () => {+ layer(TestLive())(it => {+ it.effect('[Given] no flags [Then] the COMPOSIO_* config decides', () =>+ Effect.gen(function* () {+ expect(yield* readAllDebugFlags).toEqual({+ perfDebug: true,+ toolDebug: true,+ acpOnly: true,+ });+ }).pipe(+ Effect.provide(cliDebugFlagsLayer(NO_CLI_DEBUG_FLAG_OVERRIDES)),+ Effect.withConfigProvider(enabledDebugConfig)+ )+ );++ it.effect('[Given] explicit false flags [Then] they beat the enabled config', () =>+ Effect.gen(function* () {+ expect(yield* readAllDebugFlags).toEqual({+ perfDebug: false,+ toolDebug: false,+ acpOnly: false,+ });+ }).pipe(+ Effect.provide(cliDebugFlagsLayer({ perfDebug: false, toolDebug: false, acpOnly: false })),+ Effect.withConfigProvider(enabledDebugConfig)+ )+ );+ });+});++describe('telemetry debug mode', () => {+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it.effect('[Given] the bootstrap provided the flag [Then] it wins over the environment', () =>+ Effect.gen(function* () {+ vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DEBUG', '');++ expect(yield* isTelemetryDebugEnabled).toBe(true);+ }).pipe(Effect.provide(telemetryDebugModeLayer(true)))+ );++ it.effect('[Given] no bootstrap flag [Then] it falls back to COMPOSIO_CLI_TELEMETRY_DEBUG', () =>+ Effect.gen(function* () {+ vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DEBUG', 'true');+ expect(yield* isTelemetryDebugEnabled).toBe(true);++ vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DEBUG', '');+ expect(yield* isTelemetryDebugEnabled).toBe(false);+ })+ );+});diff --git a/ts/packages/cli/test/src/services/tool-file-uploads.test.ts b/ts/packages/cli/test/src/services/tool-file-uploads.test.tsindex 832d04614..c8eebe1a2 100644--- a/ts/packages/cli/test/src/services/tool-file-uploads.test.ts+++ b/ts/packages/cli/test/src/services/tool-file-uploads.test.ts@@ -154,6 +154,9 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {);expect(createPresignedURL).toHaveBeenCalledTimes(1);+ expect(createPresignedURL).toHaveBeenCalledWith(+ expect.objectContaining({ md5: '5d41402abc4b2a76b9719d911017c592' })+ );expect(result.attachment).toMatchObject({ s3key: 's3key-123', name: 'document.pdf' });}).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)),diff --git a/ts/packages/cli/test/src/services/tool-permissions.test.ts b/ts/packages/cli/test/src/services/tool-permissions.test.tsindex 252444b8e..904309dca 100644--- a/ts/packages/cli/test/src/services/tool-permissions.test.ts+++ b/ts/packages/cli/test/src/services/tool-permissions.test.ts@@ -10,6 +10,8 @@ import {ToolPermissionDeniedError,type ConsumerPermissionSnapshot,} from 'src/services/tool-permissions';+import { extendConfigProvider } from 'src/services/config';+import { NodeOs } from 'src/services/node-os';// Pinned wall clock for deterministic fixtures. The SUT reads the real// `Date.now()` (snapshot TTL, allow-decision expiry), so every timestamp@@ -17,6 +19,13 @@ import {const PINNED_TIME = new Date('2026-01-01T00:00:00.000Z');const PINNED_NOW = PINNED_TIME.getTime();+const ToolPermissionsTest = Layer.mergeAll(+ BunFileSystem.layer,+ BunPath.layer,+ NodeOs.Default,+ Layer.setConfigProvider(extendConfigProvider(ConfigProvider.fromEnv()))+);+const snapshotFixture = (overrides: Partial<ConsumerPermissionSnapshot> = {}): ConsumerPermissionSnapshot => ({@@ -133,7 +142,7 @@ describe('tool permissions', () => {const result = yield* gateToolExecution({ toolSlug: 'GMAIL_SEND_EMAIL' });expect(result).toBeUndefined();- }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))+ }).pipe(Effect.provide(ToolPermissionsTest)));it.effect('preserves permission-policy denial identity', () =>@@ -161,7 +170,7 @@ describe('tool permissions', () => {expect(failure.deniedBy).toBe('permissions');expect(failure.toolSlug).toBe('GMAIL_SEND_EMAIL');}- }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))+ }).pipe(Effect.provide(ToolPermissionsTest)));it.effect('fails closed when interactive approval is needed but permission UI is disabled', () =>@@ -178,7 +187,7 @@ describe('tool permissions', () => {expect(failure.deniedBy).toBe('permissions');expect(failure.message).toContain('permission prompts are disabled');}- }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))+ }).pipe(Effect.provide(ToolPermissionsTest)));it.effect('honors cached allow decisions even when permission UI is disabled', () =>@@ -209,6 +218,6 @@ describe('tool permissions', () => {});expect(result).toStrictEqual({ approvalStatus: 'cached_approved' });- }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))+ }).pipe(Effect.provide(ToolPermissionsTest)));});