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
fix(cli): bundle mcp server into subagent helper (#3049)
Rahul Tarak456ee40e5822
diff --git a/.github/workflows/build-cli-binaries.yml b/.github/workflows/build-cli-binaries.ymlindex 218227411..7640abe0b 100644--- a/.github/workflows/build-cli-binaries.yml+++ b/.github/workflows/build-cli-binaries.yml@@ -72,17 +72,8 @@ jobs:./dist/binaries/${{ matrix.artifact }} --help | head -5- name: Create archive- working-directory: ts/packages/cli/dist/binaries- run: |- # Create subdirectory structure expected by install script- # Use a temp directory name to avoid name collision with the binary file- temp_dir="archive-${{ matrix.artifact }}"- rm -rf "$temp_dir"- mkdir -p "$temp_dir/${{ matrix.artifact }}"- cp "${{ matrix.artifact }}" "$temp_dir/${{ matrix.artifact }}/composio"- cp companions/run-subagent-*.mjs "$temp_dir/${{ matrix.artifact }}/"- cd "$temp_dir" && zip -r "../${{ matrix.artifact }}.zip" "${{ matrix.artifact }}"- cd .. && rm -r "$temp_dir"+ working-directory: ts/packages/cli+ run: pnpm build:binary:package- name: Upload artifactuses: actions/upload-artifact@v6diff --git a/.github/workflows/cli.test-installation.yml b/.github/workflows/cli.test-installation.ymlindex ef8fd69af..4fbfa023d 100644--- a/.github/workflows/cli.test-installation.yml+++ b/.github/workflows/cli.test-installation.yml@@ -252,6 +252,65 @@ jobs:fifi+ - name: Test bundled support files+ shell: bash+ run: |+ echo "Checking bundled support files..."++ install_dir="${COMPOSIO_INSTALL_DIR:-$HOME/.composio}"+ release_tag=$(cat "$install_dir/release-tag.txt")++ platform=$(uname -ms)+ case $platform in+ 'Darwin x86_64') target=darwin-x64 ;;+ 'Darwin arm64') target=darwin-aarch64 ;;+ 'Linux aarch64' | 'Linux arm64')+ target=linux-aarch64 ;;+ 'Linux x86_64') target=linux-x64 ;;+ *) echo "❌ Unsupported platform: $platform"; exit 1 ;;+ esac++ if [[ $target = darwin-x64 ]]; then+ if [[ $(sysctl -n sysctl.proc_translated 2>/dev/null) = 1 ]]; then+ target=darwin-aarch64+ fi+ fi++ archive_name="composio-$target.zip"+ archive_url="https://github.com/ComposioHQ/composio/releases/download/$release_tag/$archive_name"+ tmpdir="$(mktemp -d)"+ trap 'rm -rf "$tmpdir"' EXIT++ curl --fail --silent --location --output "$tmpdir/$archive_name" "$archive_url"++ mapfile -t expected_paths < <(+ unzip -Z1 "$tmpdir/$archive_name" \+ | grep -v '/$' \+ | sed "s#^composio-$target/##" \+ | grep -v '^composio$' \+ | sort+ )++ if [[ ${#expected_paths[@]} -eq 0 ]]; then+ echo "❌ No bundled support files found in $archive_name"+ exit 1+ fi++ missing_paths=()+ for relative_path in "${expected_paths[@]}"; do+ if [[ -f "$install_dir/$relative_path" ]]; then+ echo "✅ Found $relative_path"+ else+ missing_paths+=("$relative_path")+ fi+ done++ if [[ ${#missing_paths[@]} -gt 0 ]]; then+ printf '❌ Missing bundled support files after install:\n' >&2+ printf ' %s\n' "${missing_paths[@]}" >&2+ exit 1+ fi+- name: Test shell config updatesrun: |echo "Checking shell configuration updates..."@@ -264,7 +323,7 @@ jobs:exit 1fi- if grep -q 'PATH="\\$COMPOSIO_INSTALL_DIR:\\$PATH"' ~/.zshrc; then+ if grep -q 'export PATH="\\$COMPOSIO_INSTALL_DIR:\\$PATH"' ~/.zshrc; thenecho "✅ .zshrc updated with PATH"elseecho "❌ .zshrc PATH not updated"@@ -278,7 +337,7 @@ jobs:exit 1fi- if grep -q 'PATH="\\$COMPOSIO_INSTALL_DIR:\\$PATH"' ~/.bashrc; then+ if grep -q 'export PATH="\\$COMPOSIO_INSTALL_DIR:\\$PATH"' ~/.bashrc; thenecho "✅ .bashrc updated with PATH"elseecho "❌ .bashrc PATH not updated"diff --git a/.gitignore b/.gitignoreindex aa18b0b28..ae784519b 100644--- a/.gitignore+++ b/.gitignore@@ -35,6 +35,7 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json# turbo.turbo+ts/packages/cli/.generated# lernalerna-debug.log*@@ -60,4 +61,4 @@ test/e2e/*/node_modules# Agent memory-.agent_cache\ No newline at end of file+.agent_cachediff --git a/eslint.config.mjs b/eslint.config.mjsindex ddebc0850..0368ed555 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -6,6 +6,8 @@ export default [{ignores: ['ts/packages/**/dist/**',+ 'ts/packages/**/.generated/**',+ 'ts/packages/**/acp-adapters/**','ts/packages/**/node_modules/**','node_modules/**','examples/',diff --git a/install.sh b/install.shindex 27dab2958..0d24bd0e5 100755--- a/install.sh+++ b/install.sh@@ -164,43 +164,37 @@ mkdir -p "$COMPOSIO_INSTALL_DIR" ||error "Failed to create install directory \"$COMPOSIO_INSTALL_DIR\""exe="$COMPOSIO_INSTALL_DIR/composio"-companion_modules=(- "run-subagent-shared.mjs"- "run-subagent-acp.mjs"- "run-subagent-legacy.mjs"-)release_tag_file="$COMPOSIO_INSTALL_DIR/release-tag.txt"-install_companion_modules() {+install_bundle_support_files() {local source_dir="$1"local installed_count=0- local missing=()- for module in "${companion_modules[@]}"; do- if [[ -f "$source_dir/$module" ]]; then- mv "$source_dir/$module" "$COMPOSIO_INSTALL_DIR/$module"- installed_count=$((installed_count + 1))- else- missing+=("$module")- fi- done+ while IFS= read -r -d '' source_path; do+ local relative_path=${source_path#"$source_dir"/}+ local target_path="$COMPOSIO_INSTALL_DIR/$relative_path"- if (( installed_count > 0 && installed_count < ${#companion_modules[@]} )); then- error "Downloaded archive is incomplete; missing companion modules: ${missing[*]}"- fi+ mkdir -p "$(dirname "$target_path")" ||+ error "Failed to create support file directory \"$(dirname "$target_path")\""++ mv "$source_path" "$target_path" ||+ error "Failed to install support file \"$relative_path\""++ installed_count=$((installed_count + 1))+ done < <(find "$source_dir" -mindepth 1 -type f ! -path "$source_dir/composio" -print0)if (( installed_count == 0 )); then- warn "This release archive does not include the companion modules required by 'composio run'. That command may be unavailable in this version."+ warn "This release archive does not include any bundled support files beyond the main binary. Some CLI features may be unavailable in this version."fi}# Handle nested directory structure (composio-<target>/composio)if [[ -f "$tmpdir/composio-$target/composio" ]]; thenmv "$tmpdir/composio-$target/composio" "$exe"- install_companion_modules "$tmpdir/composio-$target"+ install_bundle_support_files "$tmpdir/composio-$target"elif [[ -f "$tmpdir/composio" ]]; thenmv "$tmpdir/composio" "$exe"- install_companion_modules "$tmpdir"+ install_bundle_support_files "$tmpdir"elseerror 'Binary not found in extracted archive'fidiff --git a/ts/e2e-tests/_utils/Dockerfile.cli b/ts/e2e-tests/_utils/Dockerfile.cliindex 1b16cbad1..4f007bf7b 100644--- a/ts/e2e-tests/_utils/Dockerfile.cli+++ b/ts/e2e-tests/_utils/Dockerfile.cli@@ -1,4 +1,3 @@-# syntax=docker/dockerfile:1# Reusable Dockerfile for CLI e2e tests (debian runtime)# Usage: docker build -f Dockerfile.cli --build-arg CLI_VERSION=0.1.24 -t test-name .diff --git a/ts/e2e-tests/_utils/Dockerfile.deno b/ts/e2e-tests/_utils/Dockerfile.denoindex 3c1096123..5afa77f04 100644--- a/ts/e2e-tests/_utils/Dockerfile.deno+++ b/ts/e2e-tests/_utils/Dockerfile.deno@@ -1,4 +1,3 @@-# syntax=docker/dockerfile:1# Reusable Dockerfile for Deno e2e tests# Usage: docker build -f Dockerfile.deno --build-arg DENO_VERSION=2.6.7 -t test-name .#@@ -18,10 +17,8 @@ USER rootWORKDIR /app-# Install system dependencies with cache mounts-RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \- --mount=type=cache,target=/var/lib/apt,sharing=locked \- apt-get update && \+# Install system dependencies+RUN apt-get update && \apt-get install -y --no-install-recommends ca-certificates curl unzip && \rm -rf /var/lib/apt/lists/*@@ -30,9 +27,8 @@ RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \apt-get install -y nodejs && \rm -rf /var/lib/apt/lists/*-# Install corepack (for pnpm) with npm cache mount-RUN --mount=type=cache,target=/root/.npm \- npm i -g corepack@latest && \+# Install corepack (for pnpm)+RUN npm i -g corepack@latest && \corepack enable# Install bun (version from .bun-version)diff --git a/ts/e2e-tests/_utils/Dockerfile.node b/ts/e2e-tests/_utils/Dockerfile.nodeindex 8c8bba1c9..3efac09cf 100644--- a/ts/e2e-tests/_utils/Dockerfile.node+++ b/ts/e2e-tests/_utils/Dockerfile.node@@ -1,4 +1,3 @@-# syntax=docker/dockerfile:1# Reusable Dockerfile for Node.js e2e tests# Usage: docker build -f Dockerfile.node --build-arg NODE_VERSION=20.19.0 -t test-name .#@@ -15,16 +14,13 @@ ENV PATH="$BUN_INSTALL/bin:$PNPM_HOME:$PATH"WORKDIR /app-# Install system dependencies with cache mounts-RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \- --mount=type=cache,target=/var/lib/apt,sharing=locked \- apt-get update && \+# Install system dependencies+RUN apt-get update && \apt-get install -y --no-install-recommends ca-certificates curl unzip && \rm -rf /var/lib/apt/lists/*-# Install corepack (for pnpm) with npm cache mount-RUN --mount=type=cache,target=/root/.npm \- npm i -g corepack@latest && \+# Install corepack (for pnpm)+RUN npm i -g corepack@latest && \corepack enable# Install bun (version from .bun-version)diff --git a/ts/packages/cli/scripts/_acp-adapters.ts b/ts/packages/cli/scripts/_acp-adapters.tsnew file mode 100644index 000000000..b7a87ceeb--- /dev/null+++ b/ts/packages/cli/scripts/_acp-adapters.ts@@ -0,0 +1,297 @@+import { chmod, copyFile, mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises';+import { createRequire } from 'node:module';+import * as path from 'node:path';+import process from 'node:process';+import decompress from 'decompress';+import { $ } from 'bun';+import { RUN_CODEX_ACP_BINARY_TARGETS } 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');+const ACP_ADAPTERS_MANIFEST_PATH = path.join(GENERATED_ROOT_DIR, 'acp-adapters.manifest.json');+const REGISTRY_BASE_URL = 'https://registry.npmjs.org';+const USER_AGENT = 'composio-cli-acp-vendor/1';+const ACP_ADAPTERS_PREFIX = 'acp-adapters/';++type PackageJson = {+ readonly bin?: Readonly<Record<string, string>>;+ readonly optionalDependencies?: Readonly<Record<string, string>>;+ readonly version?: string;+};++type RegistryVersionManifest = {+ readonly dist?: {+ readonly tarball?: string;+ };+};++type AcpAdaptersManifest = {+ readonly claude: {+ readonly packageName: '@zed-industries/claude-code-acp';+ readonly version: string;+ readonly agentSdkVersion: string;+ };+ readonly codex: ReadonlyArray<{+ readonly packageName: string;+ readonly relativePath: string;+ readonly version: string;+ }>;+};++const require = createRequire(import.meta.url);++const fileExists = async (filePath: string): Promise<boolean> => Bun.file(filePath).exists();++const readJsonFile = async <T>(filePath: string): Promise<T> =>+ JSON.parse(await readFile(filePath, 'utf8')) as T;++const resolvePackageJsonPath = (specifier: string): string =>+ require.resolve(`${specifier}/package.json`);++const stripAcpAdaptersPrefix = (relativePath: string): string =>+ relativePath.startsWith(ACP_ADAPTERS_PREFIX)+ ? relativePath.slice(ACP_ADAPTERS_PREFIX.length)+ : relativePath;++const readInstalledPackageJson = async (specifier: string): Promise<PackageJson> =>+ readJsonFile<PackageJson>(resolvePackageJsonPath(specifier));++const resolveClaudeAdapterEntryPath = async (): Promise<string> => {+ const manifest = await readInstalledPackageJson('@zed-industries/claude-code-acp');+ const entryPath = manifest.bin?.['claude-code-acp'];+ if (!entryPath) {+ throw new Error('Missing claude-code-acp bin entry in installed package metadata.');+ }++ return path.join(+ path.dirname(resolvePackageJsonPath('@zed-industries/claude-code-acp')),+ entryPath+ );+};++const resolveClaudeAgentSdkCliPath = (): string => {+ const claudeCodeAcpPkg = require.resolve('@zed-industries/claude-code-acp/package.json');+ const nestedRequire = createRequire(claudeCodeAcpPkg);+ const agentSdkPkg = nestedRequire.resolve('@anthropic-ai/claude-agent-sdk/package.json');+ return path.join(path.dirname(agentSdkPkg), 'cli.js');+};++const resolveClaudeAgentSdkPackageJsonPath = (): string => {+ const claudeCodeAcpPkg = require.resolve('@zed-industries/claude-code-acp/package.json');+ const nestedRequire = createRequire(claudeCodeAcpPkg);+ return nestedRequire.resolve('@anthropic-ai/claude-agent-sdk/package.json');+};++const buildCacheManifest = async (): 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 version = codexLauncherPackage.optionalDependencies?.[target.packageName];+ if (!version) {+ throw new Error(+ `Missing pinned optional dependency version for ${target.packageName} in @zed-industries/codex-acp.`+ );+ }++ return {+ packageName: target.packageName,+ relativePath: target.relativePath,+ version,+ };+ });++ if (!claudePackage.version || !agentSdkPackage.version) {+ throw new Error('Missing installed claude ACP package versions.');+ }++ return {+ claude: {+ packageName: '@zed-industries/claude-code-acp',+ version: claudePackage.version,+ agentSdkVersion: agentSdkPackage.version,+ },+ codex: codexTargets,+ };+};++const readExistingManifest = async (): Promise<AcpAdaptersManifest | null> => {+ if (!(await fileExists(ACP_ADAPTERS_MANIFEST_PATH))) {+ return null;+ }++ return readJsonFile<AcpAdaptersManifest>(ACP_ADAPTERS_MANIFEST_PATH).catch(() => null);+};++const manifestPathsExist = async (manifest: AcpAdaptersManifest): Promise<boolean> => {+ const requiredPaths = [+ path.join(ACP_ADAPTERS_CACHE_DIR, 'claude-code-acp.mjs'),+ path.join(ACP_ADAPTERS_CACHE_DIR, 'cli.js'),+ ...manifest.codex.map(target =>+ path.join(ACP_ADAPTERS_CACHE_DIR, stripAcpAdaptersPrefix(target.relativePath))+ ),+ ];++ for (const requiredPath of requiredPaths) {+ if (!(await fileExists(requiredPath))) {+ return false;+ }+ }++ return true;+};++const fetchRegistryJson = async (+ packageName: string,+ version: string+): Promise<RegistryVersionManifest> => {+ const url = `${REGISTRY_BASE_URL}/${encodeURIComponent(packageName)}/${version}`;+ const response = await fetch(url, {+ headers: {+ accept: 'application/json',+ 'user-agent': USER_AGENT,+ },+ });++ if (!response.ok) {+ throw new Error(+ `Failed to fetch registry metadata for ${packageName}@${version}: ${response.status}`+ );+ }++ return (await response.json()) as RegistryVersionManifest;+};++const downloadTarball = async (url: string, targetPath: string): Promise<void> => {+ const response = await fetch(url, {+ headers: {+ 'user-agent': USER_AGENT,+ },+ });++ if (!response.ok) {+ throw new Error(`Failed to download ${url}: ${response.status}`);+ }++ await writeFile(targetPath, new Uint8Array(await response.arrayBuffer()));+};++const buildClaudeAdapterBundle = async (cacheDir: string): Promise<void> => {+ const outputPath = path.join(cacheDir, 'claude-code-acp.mjs');+ const entryPath = await resolveClaudeAdapterEntryPath();+ const result =+ await $`${process.execPath} build ${entryPath} --target node --outfile ${outputPath}`.quiet();+ if (result.exitCode !== 0) {+ throw new Error('Failed to bundle claude-code-acp.mjs.');+ }++ await chmod(outputPath, 0o755);++ const cliOutputPath = path.join(cacheDir, 'cli.js');+ await copyFile(resolveClaudeAgentSdkCliPath(), cliOutputPath);+ await chmod(cliOutputPath, 0o755);+};++const extractCodexBinaryFromTarball = async ({+ binaryFileName,+ packageName,+ relativePath,+ stageCacheDir,+ stageRootDir,+ version,+}: {+ readonly binaryFileName: string;+ readonly packageName: string;+ readonly relativePath: string;+ readonly stageCacheDir: string;+ readonly stageRootDir: string;+ readonly version: string;+}): Promise<void> => {+ const metadata = await fetchRegistryJson(packageName, version);+ const tarballUrl = metadata.dist?.tarball;+ if (!tarballUrl) {+ throw new Error(+ `Registry metadata for ${packageName}@${version} did not include a tarball URL.`+ );+ }++ const tempArchivePath = path.join(+ stageRootDir,+ `${packageName.split('/')[1]?.replaceAll('/', '-') ?? 'package'}-${version}.tgz`+ );+ const tempExtractDir = path.join(+ stageRootDir,+ `${path.basename(tempArchivePath, '.tgz')}-extract`+ );++ await downloadTarball(tarballUrl, tempArchivePath);+ await mkdir(tempExtractDir, { recursive: true });+ await decompress(tempArchivePath, tempExtractDir);++ const extractedBinaryPath = path.join(tempExtractDir, 'package', 'bin', binaryFileName);+ if (!(await fileExists(extractedBinaryPath))) {+ throw new Error(+ `Codex ACP tarball for ${packageName}@${version} did not contain ${binaryFileName}.`+ );+ }++ const outputPath = path.join(stageCacheDir, stripAcpAdaptersPrefix(relativePath));+ await mkdir(path.dirname(outputPath), { recursive: true });+ await copyFile(extractedBinaryPath, outputPath);+ await chmod(outputPath, 0o755);+};++const materializeCodexAdapters = async (+ manifest: AcpAdaptersManifest,+ stageRootDir: string,+ stageCacheDir: string+): Promise<void> => {+ await Promise.all(+ manifest.codex.map(target =>+ extractCodexBinaryFromTarball({+ binaryFileName:+ RUN_CODEX_ACP_BINARY_TARGETS.find(+ candidate => candidate.packageName === target.packageName+ )?.binaryFileName ?? 'codex-acp',+ packageName: target.packageName,+ relativePath: target.relativePath,+ stageCacheDir,+ stageRootDir,+ version: target.version,+ })+ )+ );+};++export const materializeAcpAdaptersCache = async (): Promise<string> => {+ const manifest = await buildCacheManifest();+ const existingManifest = await readExistingManifest();++ if (+ existingManifest &&+ JSON.stringify(existingManifest) === JSON.stringify(manifest) &&+ (await manifestPathsExist(manifest))+ ) {+ return ACP_ADAPTERS_CACHE_DIR;+ }++ await mkdir(GENERATED_ROOT_DIR, { recursive: true });++ const stageRootDir = await mkdtemp(path.join(GENERATED_ROOT_DIR, '.acp-adapters-'));+ const stageCacheDir = path.join(stageRootDir, 'acp-adapters');++ try {+ await mkdir(stageCacheDir, { recursive: true });+ await buildClaudeAdapterBundle(stageCacheDir);+ await materializeCodexAdapters(manifest, stageRootDir, stageCacheDir);++ await rm(ACP_ADAPTERS_CACHE_DIR, { force: true, recursive: true });+ await rename(stageCacheDir, ACP_ADAPTERS_CACHE_DIR);+ await writeFile(ACP_ADAPTERS_MANIFEST_PATH, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');+ } finally {+ await rm(stageRootDir, { force: true, recursive: true });+ }++ return ACP_ADAPTERS_CACHE_DIR;+};diff --git a/ts/packages/cli/scripts/_shared.ts b/ts/packages/cli/scripts/_shared.tsindex 196367327..7614c0415 100644--- a/ts/packages/cli/scripts/_shared.ts+++ b/ts/packages/cli/scripts/_shared.ts@@ -1,9 +1,37 @@-import { mkdir } from 'node:fs/promises';+import { chmod, copyFile, mkdir, readdir, stat, writeFile } from 'node:fs/promises';+import * as path from 'node:path';import process from 'node:process';-import { Command } from '@effect/platform';-import { Cause, Console, Effect, Exit, Stream } from 'effect';+import { Cause, Effect, Exit } from 'effect';import type { Teardown } from '@effect/platform/Runtime';-import { RUN_COMPANION_MODULE_BASENAMES } from '../src/services/run-companion-modules';+import {+ collectRunCompanionAssetRelativePaths,+ RUN_COMPANION_MODULE_BASENAMES,+} from '../src/services/run-companion-modules';+import { materializeAcpAdaptersCache } from './_acp-adapters';++const copyDirectoryRecursive = async (sourceDir: string, targetDir: string): Promise<void> => {+ await mkdir(targetDir, { recursive: true });++ for (const entry of await readdir(sourceDir, { withFileTypes: true })) {+ const sourcePath = path.join(sourceDir, entry.name);+ const targetPath = path.join(targetDir, entry.name);++ if (entry.isDirectory()) {+ await copyDirectoryRecursive(sourcePath, targetPath);+ continue;+ }++ await copyFile(sourcePath, targetPath);+ const mode = (await stat(sourcePath)).mode & 0o777;+ await chmod(targetPath, mode || 0o755);+ }+};++const copyBundledAcpAdapters = async (outputDir: string): Promise<void> => {+ const acpAdaptersCacheDir = await materializeAcpAdaptersCache();+ const acpOutputDir = path.join(outputDir, 'acp-adapters');+ await copyDirectoryRecursive(acpAdaptersCacheDir, acpOutputDir);+};/*** Shared teardown for all CLI scripts.@@ -17,52 +45,40 @@ export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: nonExit(shouldFail ? errorCode : 0);};-type LoggedCommandArgs = readonly [string, ...string[]];--const runLoggedCommand = (args: LoggedCommandArgs) =>- Command.make(...args).pipe(- Command.start,- Effect.flatMap(process =>- Effect.all(- {- exitCode: process.exitCode,- output: Stream.merge(- Stream.decodeText(process.stdout, 'utf-8'),- Stream.decodeText(process.stderr, 'utf-8'),- { haltStrategy: 'left' }- ).pipe(- Stream.tap(chunk => Console.log(chunk)),- Stream.runDrain- ),- },- {- concurrency: 'unbounded',- }- )- ),- Effect.map(({ exitCode }) => exitCode)- );-export const buildCompanionModules = (outputDir: string) =>Effect.gen(function* () {yield* Effect.tryPromise(() => mkdir(outputDir, { recursive: true }));- for (const name of RUN_COMPANION_MODULE_BASENAMES) {- const args = [- 'bun',- 'build',- `./src/services/${name}.ts`,- '--outfile',- `${outputDir}/${name}.mjs`,- '--format',- 'esm',- '--target',- 'bun',- ] as const satisfies LoggedCommandArgs;+ const compiledRootDir = path.resolve('./dist');+ const companionRelativePaths = collectRunCompanionAssetRelativePaths(compiledRootDir);+ if (companionRelativePaths.length === 0) {+ return yield* Effect.fail(+ new Error('Missing compiled run companion modules. Run `pnpm build:packages` first.')+ );+ }++ for (const relativePath of companionRelativePaths) {+ const sourcePath = path.join(compiledRootDir, relativePath);+ const targetPath = path.join(outputDir, relativePath);++ yield* Effect.tryPromise(async () => {+ if (!(await Bun.file(sourcePath).exists())) {+ throw new Error(`Missing companion module: ${sourcePath}`);+ }+ if (path.resolve(sourcePath) === path.resolve(targetPath)) {+ return;+ }- const exitCode = yield* runLoggedCommand(args);- if (exitCode !== 0) {- return yield* Effect.fail(new Error(`Failed to build companion module: ${name}`));- }+ await mkdir(path.dirname(targetPath), { recursive: true });+ await copyFile(sourcePath, targetPath);+ });}++ for (const name of RUN_COMPANION_MODULE_BASENAMES) {+ const wrapperPath = path.join(outputDir, `${name}.mjs`);+ const wrapperSource = `export * from "./services/${name}.mjs";\n`;+ yield* Effect.tryPromise(() => writeFile(wrapperPath, wrapperSource, 'utf8'));+ }++ yield* Effect.tryPromise(() => copyBundledAcpAdapters(outputDir));});diff --git a/ts/packages/cli/scripts/install-binary.ts b/ts/packages/cli/scripts/install-binary.tsindex 365229994..05b3f4999 100644--- a/ts/packages/cli/scripts/install-binary.ts+++ b/ts/packages/cli/scripts/install-binary.ts@@ -6,7 +6,7 @@ import path from 'node:path';import os from 'node:os';import { mkdir } from 'node:fs/promises';import { $ } from 'bun';-import { RUN_COMPANION_MODULE_FILENAMES } from '../src/services/run-companion-modules';+import { collectExpectedRunCompanionAssetRelativePaths } from '../src/services/run-companion-modules';/*** Usage: `COMPOSIO_INSTALL_DIR=<INSTALL_DIR> bun scripts/build-binary.ts <BINARY_PATH>`@@ -30,13 +30,17 @@ export function installBinary() {yield* Effect.tryPromise(() => $`cp ${binaryPath} ${installDir}/composio`.quiet());const sourceDirectory = path.dirname(path.resolve(binaryPath));- for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {- const sourcePath = path.join(sourceDirectory, fileName);+ const companionRelativePaths = collectExpectedRunCompanionAssetRelativePaths(sourceDirectory);++ for (const relativePath of companionRelativePaths) {+ const sourcePath = path.join(sourceDirectory, relativePath);+ const targetPath = path.join(installDir, relativePath);yield* Effect.tryPromise(async () => {if (!(await Bun.file(sourcePath).exists())) {throw new Error(`Missing companion module: ${sourcePath}`);}- await $`cp ${sourcePath} ${installDir}/${fileName}`.quiet();+ await $`mkdir -p ${path.dirname(targetPath)}`.quiet();+ await $`cp ${sourcePath} ${targetPath}`.quiet();});}diff --git a/ts/packages/cli/scripts/package-binaries.ts b/ts/packages/cli/scripts/package-binaries.tsindex 97163661e..0216fca0d 100644--- a/ts/packages/cli/scripts/package-binaries.ts+++ b/ts/packages/cli/scripts/package-binaries.ts@@ -21,7 +21,7 @@ import { teardown } from './_shared';import { $ } from 'bun';import { readdir, stat } from 'node:fs/promises';import path from 'node:path';-import { RUN_COMPANION_MODULE_FILENAMES } from '../src/services/run-companion-modules';+import { collectExpectedRunCompanionAssetRelativePaths } from '../src/services/run-companion-modules';const BINARIES_DIR = './dist/binaries';const COMPANIONS_DIR = path.join(BINARIES_DIR, 'companions');@@ -48,8 +48,9 @@ export function packageBinaries() {return;}- for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {- const companionPath = path.join(COMPANIONS_DIR, fileName);+ const companionRelativePaths = collectExpectedRunCompanionAssetRelativePaths(COMPANIONS_DIR);+ for (const relativePath of companionRelativePaths) {+ const companionPath = path.join(COMPANIONS_DIR, relativePath);const exists = yield* Effect.tryPromise(() => Bun.file(companionPath).exists());if (!exists) {yield* Console.error(@@ -74,8 +75,10 @@ export function packageBinaries() {yield* Effect.tryPromise(async () => {await $`mkdir -p ${nestedDir}`.quiet();await $`cp ${binaryPath} ${nestedDir}/composio`.quiet();- for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {- await $`cp ${path.join(COMPANIONS_DIR, fileName)} ${nestedDir}/${fileName}`.quiet();+ for (const relativePath of companionRelativePaths) {+ const targetDirectory = path.dirname(path.join(nestedDir, relativePath));+ await $`mkdir -p ${targetDirectory}`.quiet();+ await $`cp ${path.join(COMPANIONS_DIR, relativePath)} ${path.join(nestedDir, relativePath)}`.quiet();}const previousCwd = process.cwd();process.chdir(tempDir);diff --git a/ts/packages/cli/skills/composio-cli/references/troubleshooting.md b/ts/packages/cli/skills/composio-cli/references/troubleshooting.mdindex 7d97fed87..101e2f853 100644--- a/ts/packages/cli/skills/composio-cli/references/troubleshooting.md+++ b/ts/packages/cli/skills/composio-cli/references/troubleshooting.md@@ -102,7 +102,7 @@ composio execute --parallel \GITHUB_CREATE_AN_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'```-Escalate to `composio run` only when the user needs control flow, loops, `Promise.all`, `search()` inside a script, `proxy()`, or `subAgent()`.+Escalate to `composio run` only when the user needs control flow, loops, `Promise.all`, `search()` inside a script, `proxy()`, or `experimental_subAgent()`.## `tools info` And `tools list` Are Fallbacksdiff --git a/ts/packages/cli/src/services/run-companion-modules.ts b/ts/packages/cli/src/services/run-companion-modules.tsindex 17fa17d0a..000ee5fb2 100644--- a/ts/packages/cli/src/services/run-companion-modules.ts+++ b/ts/packages/cli/src/services/run-companion-modules.ts@@ -16,6 +16,185 @@ export const RUN_COMPANION_MODULE_FILENAMES = RUN_COMPANION_MODULE_BASENAMES.map);export const RUN_COMPANION_RELEASE_TAG_FILENAME = 'release-tag.txt';+export const RUN_CODEX_ACP_BINARY_TARGETS = [+ {+ platform: 'darwin',+ arch: 'arm64',+ packageName: '@zed-industries/codex-acp-darwin-arm64',+ binaryFileName: 'codex-acp',+ relativePath: 'acp-adapters/codex/darwin-arm64/codex-acp',+ },+ {+ platform: 'darwin',+ arch: 'x64',+ packageName: '@zed-industries/codex-acp-darwin-x64',+ binaryFileName: 'codex-acp',+ relativePath: 'acp-adapters/codex/darwin-x64/codex-acp',+ },+ {+ platform: 'linux',+ arch: 'arm64',+ packageName: '@zed-industries/codex-acp-linux-arm64',+ binaryFileName: 'codex-acp',+ relativePath: 'acp-adapters/codex/linux-arm64/codex-acp',+ },+ {+ platform: 'linux',+ arch: 'x64',+ packageName: '@zed-industries/codex-acp-linux-x64',+ binaryFileName: 'codex-acp',+ relativePath: 'acp-adapters/codex/linux-x64/codex-acp',+ },+] as const;+export const RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS = [+ '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',+ ...RUN_CODEX_ACP_BINARY_TARGETS.map(target => target.relativePath),+] as const;++const relativeImportPattern =+ /(?:import\s+(?:[^'"]+?\s+from\s+)?|export\s+(?:\*\s+from\s+|\{[^}]+\}\s+from\s+)|import\s*\()\s*["'](\.{1,2}\/[^"']+?\.mjs)["']/g;++const isImportGraphFile = (relativePath: string) => /\.(?:m?js|ts)$/.test(relativePath);++const collectRelativeImportPaths = ({+ rootDir,+ relativePath,+ collected,+ recordMissingPaths = false,+}: {+ rootDir: string;+ relativePath: string;+ collected: Set<string>;+ recordMissingPaths?: boolean;+}): void => {+ const normalizedRelativePath = relativePath.replaceAll(path.sep, '/');+ if (collected.has(normalizedRelativePath)) {+ return;+ }++ const absolutePath = path.join(rootDir, normalizedRelativePath);+ const exists = fs.existsSync(absolutePath);+ if (!exists && !recordMissingPaths) {+ return;+ }++ collected.add(normalizedRelativePath);+ if (!exists) {+ return;+ }++ if (!isImportGraphFile(normalizedRelativePath)) {+ return;+ }++ const source = fs.readFileSync(absolutePath, 'utf8');+ for (const match of source.matchAll(relativeImportPattern)) {+ const specifier = match[1];+ if (!specifier) {+ continue;+ }++ const dependencyRelativePath = path+ .relative(rootDir, path.resolve(path.dirname(absolutePath), specifier))+ .replaceAll(path.sep, '/');++ collectRelativeImportPaths({+ rootDir,+ relativePath: dependencyRelativePath,+ collected,+ recordMissingPaths,+ });+ }+};++export const collectRunCompanionAssetRelativePaths = (rootDir: string): ReadonlyArray<string> => {+ const collected = new Set<string>();++ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {+ collectRelativeImportPaths({+ rootDir,+ relativePath: fileName,+ collected,+ });+ }++ if (collected.size === 0) {+ for (const baseName of RUN_COMPANION_MODULE_BASENAMES) {+ collectRelativeImportPaths({+ rootDir,+ relativePath: path.posix.join('services', `${baseName}.mjs`),+ collected,+ });+ }+ }++ for (const relativePath of RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS) {+ collectRelativeImportPaths({+ rootDir,+ relativePath,+ collected,+ });+ }++ return [...collected].sort();+};++export const resolveRunCompanionAssetPath = ({+ callerImportMetaUrl,+ execPath,+ relativePathFromRoot,+}: {+ callerImportMetaUrl: string;+ execPath: string;+ relativePathFromRoot: string;+}): string | null => {+ const currentFilePath = fileURLToPath(callerImportMetaUrl);+ const currentDirectory = path.dirname(currentFilePath);+ const executableDirectory = path.dirname(execPath);++ const candidates = [+ path.resolve(currentDirectory, relativePathFromRoot),+ path.resolve(currentDirectory, '..', relativePathFromRoot),+ path.resolve(executableDirectory, relativePathFromRoot),+ ];++ for (const candidate of candidates) {+ if (fs.existsSync(candidate)) {+ return candidate;+ }+ }++ return null;+};++export const collectExpectedRunCompanionAssetRelativePaths = (+ rootDir: string+): ReadonlyArray<string> => {+ const collected = new Set<string>();++ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {+ collectRelativeImportPaths({+ rootDir,+ relativePath: fileName,+ collected,+ recordMissingPaths: true,+ });+ }++ for (const relativePath of RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS) {+ collectRelativeImportPaths({+ rootDir,+ relativePath,+ collected,+ recordMissingPaths: true,+ });+ }++ return [...collected].sort();+};type GitHubReleaseAsset = {name: string;@@ -80,8 +259,8 @@ export const writeInstalledReleaseTag = (installDir: string, releaseTag: string)export const listMissingInstalledRunCompanionModules = (execPath: string) => {const installDirectory = resolveCompanionInstallDirectory(execPath);- return RUN_COMPANION_MODULE_FILENAMES.filter(- fileName => !fs.existsSync(path.join(installDirectory, fileName))+ return collectExpectedRunCompanionAssetRelativePaths(installDirectory).filter(+ relativePath => !fs.existsSync(path.join(installDirectory, relativePath)));};@@ -264,15 +443,19 @@ export const repairMissingInstalledRunCompanionModules = async ({await decompress(archivePath, extractDirectory);const installDirectory = resolveCompanionInstallDirectory(execPath);- for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {- const sourcePath = path.join(packageDirectory, fileName);+ const companionRelativePaths = collectExpectedRunCompanionAssetRelativePaths(packageDirectory);++ for (const relativePath of companionRelativePaths) {+ const sourcePath = path.join(packageDirectory, relativePath);if (!fs.existsSync(sourcePath)) {throw new Error(- `Release ${release.tag_name} is missing ${fileName}; cannot restore the files required by 'composio run'.`+ `Release ${release.tag_name} is missing ${relativePath}; cannot restore the files required by 'composio run'.`);}- fs.copyFileSync(sourcePath, path.join(installDirectory, fileName));+ const targetPath = path.join(installDirectory, relativePath);+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });+ fs.copyFileSync(sourcePath, targetPath);}writeInstalledReleaseTag(installDirectory, release.tag_name);diff --git a/ts/packages/cli/src/services/run-subagent-acp.ts b/ts/packages/cli/src/services/run-subagent-acp.tsindex 26a435f62..c9b7eb1eb 100644--- a/ts/packages/cli/src/services/run-subagent-acp.ts+++ b/ts/packages/cli/src/services/run-subagent-acp.ts@@ -6,7 +6,11 @@ import path from 'node:path';import { Readable, Writable } from 'node:stream';import * as acp from '@agentclientprotocol/sdk';import type { MasterKind } from 'src/services/master-detector';-import { resolveRunCompanionModulePath } from 'src/services/run-companion-modules';+import {+ resolveRunCompanionAssetPath,+ resolveRunCompanionModulePath,+ RUN_CODEX_ACP_BINARY_TARGETS,+} from 'src/services/run-companion-modules';import {ACP_STRUCTURED_OUTPUT_TOOL_NAME,AcpInvokeError,@@ -23,7 +27,30 @@ import {type InvokeAgentTarget,} from 'src/services/run-subagent-shared';-const resolveBundledAdapter = (target: InvokeAgentTarget): string | null => {+const resolveShippedAdapterAsset = (target: InvokeAgentTarget): string | null => {+ if (target === 'claude') {+ return resolveRunCompanionAssetPath({+ callerImportMetaUrl: import.meta.url,+ execPath: process.execPath,+ relativePathFromRoot: 'acp-adapters/claude-code-acp.mjs',+ });+ }++ const binaryTarget = RUN_CODEX_ACP_BINARY_TARGETS.find(+ candidate => candidate.platform === process.platform && candidate.arch === process.arch+ );+ if (!binaryTarget) {+ return null;+ }++ return resolveRunCompanionAssetPath({+ callerImportMetaUrl: import.meta.url,+ execPath: process.execPath,+ relativePathFromRoot: binaryTarget.relativePath,+ });+};++const resolveInstalledAdapter = (target: InvokeAgentTarget): string | null => {const specifier =target === 'claude'? '@zed-industries/claude-code-acp/dist/index.js'@@ -40,22 +67,45 @@ export const resolveAcpAdapterCommand = (target: InvokeAgentTarget): {readonly cmd: ReadonlyArray<string>;- readonly source: 'bundled' | 'which' | 'npx';+ readonly env?: Readonly<Record<string, string>>;+ readonly source: 'shipped' | 'bundled' | 'which' | 'npx';} => {const binary = target === 'claude' ? 'claude-code-acp' : 'codex-acp';const packageName =target === 'claude' ? '@zed-industries/claude-code-acp' : '@zed-industries/codex-acp';- // 1. Try the bundled dependency first (no npx overhead)- const bundled = resolveBundledAdapter(target);+ // 1. Prefer shipped companion assets next to the CLI binary / dist bundle.+ const shipped = resolveShippedAdapterAsset(target);+ if (shipped) {+ if (target === 'codex') {+ return {+ cmd: [shipped],+ source: 'shipped',+ };+ }++ return {+ cmd: [process.execPath, shipped],+ env: {+ BUN_BE_BUN: '1',+ },+ source: 'shipped',+ };+ }++ // 2. Try the installed dependency bundle next (no npx overhead).+ const bundled = resolveInstalledAdapter(target);if (bundled) {return {cmd: [process.execPath, bundled],+ env: {+ BUN_BE_BUN: '1',+ },source: 'bundled',};}- // 2. Check if the binary is on PATH+ // 3. Check if the binary is on PATH.if (typeof Bun !== 'undefined' && typeof Bun.which === 'function') {const resolved = Bun.which(binary);if (resolved) {@@ -66,7 +116,7 @@ export const resolveAcpAdapterCommand = (}}- // 3. Fall back to npx+ // 4. Fall back to npx.return {cmd: [process.platform === 'win32' ? 'npx.cmd' : 'npx', '-y', packageName],source: 'npx',@@ -175,7 +225,7 @@ export const selectPermissionOutcome = (params.options.find(option => option.kind === 'reject_once') ??params.options.find(option => option.kind === 'reject_always');- // Intentionally permissive for `composio run` subAgent sessions. The user is+ // Intentionally permissive for `composio run` experimental_subAgent sessions. The user is// explicitly opting into local tool access, so prefer broad ACP approval over// heuristic rejections that strand the agent mid-task.if (allowOnce) {@@ -479,7 +529,12 @@ export const invokeAcpSubAgent = async ({const { CLAUDECODE: _, ...childEnv } = process.env;const child = spawn(resolved.cmd[0]!, resolved.cmd.slice(1), {cwd: process.cwd(),- env: childEnv,+ env: resolved.env+ ? {+ ...childEnv,+ ...resolved.env,+ }+ : childEnv,stdio: ['pipe', 'pipe', 'pipe'],});diff --git a/ts/packages/cli/src/services/run-subagent-output-mcp.ts b/ts/packages/cli/src/services/run-subagent-output-mcp.tsindex 929019cc0..777fac3bd 100644--- a/ts/packages/cli/src/services/run-subagent-output-mcp.ts+++ b/ts/packages/cli/src/services/run-subagent-output-mcp.ts@@ -1,9 +1,8 @@-import path from 'node:path';import * as fs from 'node:fs';-import { createRequire } from 'node:module';import process from 'node:process';-import { pathToFileURL } from 'node:url';import { jsonSchemaToZodSchema } from '@composio/core';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';import {ACP_STRUCTURED_OUTPUT_TOOL_NAME,buildStructuredOutputToolSchema,@@ -18,51 +17,7 @@ const readFlag = (name: string): string => {return value;};-type McpServerInstance = {- registerTool: (- name: string,- config: {- title?: string;- description?: string;- inputSchema?: unknown;- },- cb: (payload: unknown) => Promise<{- content: Array<{- type: string;- text: string;- }>;- }>- ) => void;- connect: (transport: unknown) => Promise<void>;-};--type McpServerConstructor = new (serverInfo: {- name: string;- version: string;-}) => McpServerInstance;--type StdioServerTransportConstructor = new () => unknown;--const loadMcpSdk = async (): Promise<{- McpServer: McpServerConstructor;- StdioServerTransport: StdioServerTransportConstructor;-}> => {- const require = createRequire(import.meta.url);- const sdkPackageJsonPath = require.resolve('@modelcontextprotocol/sdk/package.json');- const sdkDirectory = path.dirname(sdkPackageJsonPath);- const [mcpModule, stdioModule] = await Promise.all([- import(pathToFileURL(path.join(sdkDirectory, 'dist/esm/server/mcp.js')).href),- import(pathToFileURL(path.join(sdkDirectory, 'dist/esm/server/stdio.js')).href),- ]);-- return {- McpServer: mcpModule.McpServer as McpServerConstructor,- StdioServerTransport: stdioModule.StdioServerTransport as StdioServerTransportConstructor,- };-};-const main = async (): Promise<void> => {- const { McpServer, StdioServerTransport } = await loadMcpSdk();const schemaFilePath = readFlag('--schema-file');const resultFilePath = readFlag('--result-file');const schemaText = fs.readFileSync(schemaFilePath, 'utf8');diff --git a/ts/packages/cli/src/services/upgrade-binary.ts b/ts/packages/cli/src/services/upgrade-binary.tsindex 4c9071050..8df395099 100644--- a/ts/packages/cli/src/services/upgrade-binary.ts+++ b/ts/packages/cli/src/services/upgrade-binary.ts@@ -12,7 +12,10 @@ import decompress from 'decompress';import type { Predicate } from 'effect/Predicate';import { renderPrettyError } from './utils/pretty-error';import { TerminalUI } from './terminal-ui';-import { RUN_COMPANION_MODULE_FILENAMES, writeInstalledReleaseTag } from './run-companion-modules';+import {+ collectExpectedRunCompanionAssetRelativePaths,+ writeInstalledReleaseTag,+} from './run-companion-modules';export class UpgradeBinaryError extends Data.TaggedError('services/UpgradeBinaryError')<{readonly cause?: unknown;@@ -36,10 +39,10 @@ type GitHubRelease = {const CLI_RELEASE_TAG_PATTERN = /^@composio\/cli@\d+\.\d+\.\d+.*$/;-const getBinaryAssetName = (platformArch: PlatformArch): string =>+const getBinaryAssetName = (platformArch: PlatformArch) =>`${CLI_BINARY_NAME}-${platformArch.platform}-${platformArch.arch}.zip`;-const hasBinaryAsset = (release: GitHubRelease, platformArch: PlatformArch): boolean =>+const hasPlatformBinaryAsset = (release: GitHubRelease, platformArch: PlatformArch) =>release.assets.some(asset => asset.name === getBinaryAssetName(platformArch));// Service to manage CLI binary upgrades@@ -106,7 +109,7 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upgconst fetchLatestRelease = (platformArch: PlatformArch- ): Effect.Effect<Option.Option<GitHubRelease>, UpgradeBinaryError, never> =>+ ): Effect.Effect<GitHubRelease, UpgradeBinaryError, never> =>Effect.gen(function* () {const release = yield* githubConfig.TAG.pipe(Option.match({@@ -151,19 +154,24 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg);}- const releasesWithBinary = cliReleases.filter(release =>- hasBinaryAsset(release, platformArch)+ const cliReleasesWithBinary = cliReleases.filter(release =>+ hasPlatformBinaryAsset(release, platformArch));- if (releasesWithBinary.length === 0) {- yield* Effect.logDebug(- `No published CLI releases currently contain ${getBinaryAssetName(platformArch)}`+ if (cliReleasesWithBinary.length === 0) {+ return yield* Effect.fail(+ new UpgradeBinaryError({+ cause: new Error(+ `No package-scoped CLI releases found with ${getBinaryAssetName(platformArch)}`+ ),+ message:+ 'Failed to determine latest CLI release from @composio/cli tags on GitHub',+ }));- return Option.none();}- let latest = releasesWithBinary[0];- for (const release of releasesWithBinary.slice(1)) {+ let latest = cliReleasesWithBinary[0];+ for (const release of cliReleasesWithBinary.slice(1)) {const comparison = yield* semverComparator(latest.tag_name, release.tag_name).pipe(Effect.mapError(error =>@@ -180,7 +188,7 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg}yield* Effect.logDebug(`Resolved latest CLI release tag: ${latest.tag_name}`);- return Option.some(latest);+ return latest;}),onSome: Effect.fn(function* (tag) {yield* Effect.logDebug(`Using tag: ${tag}`);@@ -192,14 +200,7 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/UpgparseErrorMessage: 'Failed to parse GitHub release JSON response',});- if (!hasBinaryAsset(release, platformArch)) {- yield* Effect.logDebug(- `Release ${tag} does not yet contain ${getBinaryAssetName(platformArch)}`- );- return Option.none();- }-- return Option.some(release as GitHubRelease);+ return release as GitHubRelease;}),}));@@ -500,9 +501,10 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upgconst sourceDirectory = path.dirname(sourcePath);const targetDirectory = path.dirname(targetPath);-- for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {- const sourceCompanion = path.join(sourceDirectory, fileName);+ const companionRelativePaths =+ collectExpectedRunCompanionAssetRelativePaths(sourceDirectory);+ for (const relativePath of companionRelativePaths) {+ const sourceCompanion = path.join(sourceDirectory, relativePath);const sourceExists = yield* fs.exists(sourceCompanion).pipe(Effect.catchAll(() => Effect.succeed(false)));@@ -516,8 +518,20 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg);}+ const targetCompanion = path.join(targetDirectory, relativePath);+ yield* fs.makeDirectory(path.dirname(targetCompanion), { recursive: true }).pipe(+ Effect.catchAll(error =>+ Effect.fail(+ new UpgradeBinaryError({+ cause: error as Error,+ message: `Failed to create companion module directory: ${relativePath}`,+ })+ )+ )+ );+yield* fs- .copy(sourceCompanion, path.join(targetDirectory, fileName), {+ .copy(sourceCompanion, targetCompanion, {overwrite: true,}).pipe(@@ -525,7 +539,7 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/UpgEffect.fail(new UpgradeBinaryError({cause: error as Error,- message: `Failed to replace companion module: ${fileName}`,+ message: `Failed to replace companion module: ${relativePath}`,})))@@ -567,13 +581,7 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upgconst didUpgrade = yield* ui.useMakeSpinner('Checking for updates...', spinner =>Effect.gen(function* () {const platformArch = yield* detectPlatform;- const releaseOption = yield* fetchLatestRelease(platformArch);- if (Option.isNone(releaseOption)) {- yield* spinner.stop('You are already running the latest version!');- return false;- }-- const release = releaseOption.value;+ const release = yield* fetchLatestRelease(platformArch);const updateAvailable = yield* isUpdateAvailable(release);if (!updateAvailable) {yield* spinner.stop('You are already running the latest version!');diff --git a/ts/packages/cli/test/src/commands/run.cmd.test.ts b/ts/packages/cli/test/src/commands/run.cmd.test.tsindex a4a593aea..541c4c649 100644--- a/ts/packages/cli/test/src/commands/run.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/run.cmd.test.ts@@ -13,6 +13,7 @@ import {} from 'src/commands/run.cmd';import {RUN_COMPANION_MODULE_FILENAMES,+ RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS,listMissingInstalledRunCompanionModules,readInstalledReleaseTag,resolveRunCompanionModulePath,@@ -119,6 +120,53 @@ describe('CLI: composio run', () => {);});+ layer(TestLive())(it => {+ it.scoped(+ '[Given] a multiline structured experimental_subAgent script [Then] run preserves the inline TypeScript source',+ () =>+ Effect.gen(function* () {+ const script = `+ const brief = await experimental_subAgent(+ [+ "Do not read files.",+ "Do not run terminal commands.",+ "Do not inspect the workspace.",+ "Return exactly this structured value:",+ "{\\"summary\\":\\"ok\\",\\"urgent\\":[\\"a\\",\\"b\\"]}",+ ].join("\\n"),+ {+ target: "codex",+ schema: z.object({ summary: z.string(), urgent: z.array(z.string()) }),+ }+ );+ console.log(JSON.stringify(brief));+ console.log(JSON.stringify(brief.structuredOutput));+ `;+ const spawn = vi.fn(() => ({ 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 as any).mock.calls[0][0] as {+ cmd: string[];+ };+ 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."');+ expect(spawnConfig.cmd[4]).toContain('].join("\\n"),');+ expect(spawnConfig.cmd[4]).toContain('target: "codex"');+ expect(spawnConfig.cmd[4]).toContain('console.log(JSON.stringify(brief));');+ expect(spawnConfig.cmd[4]).toContain(+ 'return (console.log(JSON.stringify(brief.structuredOutput)));'+ );+ expect(spawnConfig.cmd[4]).not.toContain('"Do not run terminal\n');+ expect(exit).toHaveBeenCalledWith(0);+ })+ );+ });+layer(TestLive())(it => {it.scoped('[Given] --file [Then] it forwards file execution to the embedded Bun runtime', () =>Effect.gen(function* () {@@ -471,7 +519,115 @@ describe('run companion install metadata', () => {fs.writeFileSync(path.join(tempDir, RUN_COMPANION_MODULE_FILENAMES[0]!), '', 'utf8');expect(listMissingInstalledRunCompanionModules(execPath)).toEqual(- RUN_COMPANION_MODULE_FILENAMES.slice(1)+ [...RUN_COMPANION_MODULE_FILENAMES.slice(1), ...RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS]+ .slice()+ .sort()+ );+ });++ it('[Given] a nested companion dependency is missing [Then] it reports the missing helper asset', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-nested-'));+ const execPath = path.join(tempDir, 'composio');+ const servicesDir = path.join(tempDir, 'services');+ fs.mkdirSync(servicesDir, { recursive: true });++ fs.writeFileSync(+ path.join(tempDir, 'run-subagent-shared.mjs'),+ 'export * from "./services/run-subagent-shared.mjs";\n',+ 'utf8'+ );+ fs.writeFileSync(+ path.join(tempDir, 'run-subagent-acp.mjs'),+ 'export * from "./services/run-subagent-acp.mjs";\n',+ 'utf8'+ );+ fs.writeFileSync(+ path.join(tempDir, 'run-subagent-legacy.mjs'),+ 'export * from "./services/run-subagent-legacy.mjs";\n',+ 'utf8'+ );+ fs.writeFileSync(+ path.join(tempDir, 'run-subagent-output-mcp.mjs'),+ 'export * from "./services/run-subagent-output-mcp.mjs";\n',+ 'utf8'+ );++ fs.writeFileSync(+ path.join(servicesDir, 'run-subagent-shared.mjs'),+ 'export const x = 1;\n',+ 'utf8'+ );+ fs.writeFileSync(+ path.join(servicesDir, 'run-subagent-acp.mjs'),+ 'export * from "../run-companion-modules-abc123.mjs";\n',+ 'utf8'+ );+ fs.writeFileSync(+ path.join(servicesDir, 'run-subagent-legacy.mjs'),+ 'export const y = 1;\n',+ 'utf8'+ );+ fs.writeFileSync(+ path.join(servicesDir, 'run-subagent-output-mcp.mjs'),+ 'export const z = 1;\n',+ 'utf8'+ );++ expect(listMissingInstalledRunCompanionModules(execPath)).toContain(+ 'run-companion-modules-abc123.mjs'+ );+ });++ it('[Given] a named re-export dependency is missing [Then] it reports the missing helper asset', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-reexport-'));+ const execPath = path.join(tempDir, 'composio');+ const servicesDir = path.join(tempDir, 'services');+ fs.mkdirSync(servicesDir, { recursive: true });++ fs.writeFileSync(+ path.join(tempDir, 'run-subagent-shared.mjs'),+ 'export * from "./services/run-subagent-shared.mjs";\n',+ 'utf8'+ );+ fs.writeFileSync(+ path.join(tempDir, 'run-subagent-acp.mjs'),+ 'export * from "./services/run-subagent-acp.mjs";\n',+ 'utf8'+ );+ fs.writeFileSync(+ path.join(tempDir, 'run-subagent-legacy.mjs'),+ 'export * from "./services/run-subagent-legacy.mjs";\n',+ 'utf8'+ );+ fs.writeFileSync(+ path.join(tempDir, 'run-subagent-output-mcp.mjs'),+ 'export * from "./services/run-subagent-output-mcp.mjs";\n',+ 'utf8'+ );++ fs.writeFileSync(+ path.join(servicesDir, 'run-subagent-shared.mjs'),+ 'export const sharedValue = 1;\n',+ 'utf8'+ );+ fs.writeFileSync(+ path.join(servicesDir, 'run-subagent-acp.mjs'),+ 'export { helperValue } from "../run-companion-modules-def456.mjs";\n',+ 'utf8'+ );+ fs.writeFileSync(+ path.join(servicesDir, 'run-subagent-legacy.mjs'),+ 'export const legacyValue = 1;\n',+ 'utf8'+ );+ fs.writeFileSync(+ path.join(servicesDir, 'run-subagent-output-mcp.mjs'),+ 'export const outputValue = 1;\n',+ 'utf8'+ );++ expect(listMissingInstalledRunCompanionModules(execPath)).toContain(+ 'run-companion-modules-def456.mjs');});});diff --git a/ts/packages/cli/test/src/services/run-subagent-output-mcp.test.ts b/ts/packages/cli/test/src/services/run-subagent-output-mcp.test.tsnew file mode 100644index 000000000..690ae2439--- /dev/null+++ b/ts/packages/cli/test/src/services/run-subagent-output-mcp.test.ts@@ -0,0 +1,17 @@+import * as fs from 'node:fs';+import { fileURLToPath } from 'node:url';+import { describe, expect, it } from 'vitest';++describe('run-subagent-output-mcp source', () => {+ it('[Given] the structured output helper source [Then] it statically imports the MCP SDK', () => {+ const sourcePath = fileURLToPath(+ new URL('../../../src/services/run-subagent-output-mcp.ts', import.meta.url)+ );+ const source = fs.readFileSync(sourcePath, 'utf8');++ expect(source).toContain("from '@modelcontextprotocol/sdk/server/mcp.js'");+ expect(source).toContain("from '@modelcontextprotocol/sdk/server/stdio.js'");+ expect(source).not.toContain('@modelcontextprotocol/sdk/package.json');+ expect(source).not.toContain('createRequire(import.meta.url)');+ });+});diff --git a/ts/packages/cli/test/src/services/upgrade-binary.test.ts b/ts/packages/cli/test/src/services/upgrade-binary.test.tsindex 7ff85138e..80b6d5a6b 100644--- a/ts/packages/cli/test/src/services/upgrade-binary.test.ts+++ b/ts/packages/cli/test/src/services/upgrade-binary.test.ts@@ -43,10 +43,10 @@ const NodeOsTest = Layer.succeed(}));-const runUpgrade = (configEntries: ReadonlyArray<[string, string]>) =>+const makeUpgradeEffect = (configEntries: ReadonlyArray<[string, string]>) =>Effect.gen(function* () {const service = yield* UpgradeBinary;- return yield* Effect.flip(service.upgrade());+ return yield* service.upgrade();}).pipe(Effect.provide(UpgradeBinary.Default),Effect.provide(FetchHttpClient.layer),@@ -54,24 +54,14 @@ const runUpgrade = (configEntries: ReadonlyArray<[string, string]>) =>Effect.provide(TerminalUINoop),Effect.provide(NodeOsTest),Effect.withConfigProvider(ConfigProvider.fromMap(new Map(configEntries))),- Effect.scoped,- Effect.runPromise+ Effect.scoped);+const runUpgrade = (configEntries: ReadonlyArray<[string, string]>) =>+ makeUpgradeEffect(configEntries).pipe(Effect.flip, Effect.runPromise);+const runUpgradeSuccess = (configEntries: ReadonlyArray<[string, string]>) =>- Effect.gen(function* () {- const service = yield* UpgradeBinary;- return yield* service.upgrade();- }).pipe(- Effect.provide(UpgradeBinary.Default),- Effect.provide(FetchHttpClient.layer),- Effect.provide(BunFileSystem.layer),- Effect.provide(TerminalUINoop),- Effect.provide(NodeOsTest),- Effect.withConfigProvider(ConfigProvider.fromMap(new Map(configEntries))),- Effect.scoped,- Effect.runPromise- );+ makeUpgradeEffect(configEntries).pipe(Effect.runPromise);describe('UpgradeBinary', () => {it('wraps non-2xx releases fetch failures with fetch context (no tag branch)', async () => {@@ -169,83 +159,45 @@ describe('UpgradeBinary', () => {}});- it('skips newer releases that do not yet contain a binary for the current platform', async () => {+ it('skips newer releases that do not contain a binary for the current platform', async () => {vi.stubGlobal('Bun', { which: vi.fn(() => null) });try {await withHttpServer(- (req, res) => {- if (req.url === '/repos/test-owner/test-repo/releases?per_page=100') {- res.writeHead(200, { 'content-type': 'application/json' });- res.end(- JSON.stringify([- {- tag_name: '@composio/[email protected]',- prerelease: false,- draft: false,- assets: [],- },- {- tag_name: '@composio/[email protected]',- prerelease: false,- draft: false,- assets: [],- },- ])- );- return;- }-- res.writeHead(404, { 'content-type': 'application/json' });- res.end(JSON.stringify({ message: 'not found' }));- },- async apiBaseUrl => {- const result = await runUpgradeSuccess([- ['GITHUB_API_BASE_URL', apiBaseUrl],- ['GITHUB_OWNER', 'test-owner'],- ['GITHUB_REPO', 'test-repo'],- ]);-- expect(result).toBeUndefined();- }- );- } finally {- vi.unstubAllGlobals();- vi.restoreAllMocks();- }- });-- it('treats an explicitly requested release without binaries as no upgrade', async () => {- vi.stubGlobal('Bun', { which: vi.fn(() => null) });-- try {- await withHttpServer(- (req, res) => {- if (- req.url ===- `/repos/test-owner/test-repo/releases/tags/${encodeURIComponent('@composio/[email protected]')}`- ) {- res.writeHead(200, { 'content-type': 'application/json' });- res.end(- JSON.stringify({- tag_name: '@composio/[email protected]',+ (_req, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(+ JSON.stringify([+ {+ tag_name: '@composio/[email protected]',+ draft: false,prerelease: false,+ assets: [+ {+ name: 'composio-linux-x64.zip',+ browser_download_url: 'http://127.0.0.1/unused-linux.zip',+ },+ ],+ },+ {+ tag_name: '@composio/[email protected]',draft: false,- assets: [],- })- );- return;- }-- res.writeHead(404, { 'content-type': 'application/json' });- res.end(JSON.stringify({ message: 'not found' }));+ prerelease: false,+ assets: [+ {+ name: 'composio-darwin-aarch64.zip',+ browser_download_url: 'http://127.0.0.1/current-darwin.zip',+ },+ ],+ },+ ])+ );},async apiBaseUrl => {const result = await runUpgradeSuccess([['GITHUB_API_BASE_URL', apiBaseUrl],['GITHUB_OWNER', 'test-owner'],['GITHUB_REPO', 'test-repo'],- ['GITHUB_TAG', '@composio/[email protected]'],]);expect(result).toBeUndefined();diff --git a/ts/packages/cli/tsdown.config.ts b/ts/packages/cli/tsdown.config.tsindex 4daf2d5f0..b3114cc2d 100644--- a/ts/packages/cli/tsdown.config.ts+++ b/ts/packages/cli/tsdown.config.ts@@ -13,6 +13,12 @@ export default defineConfig({format: ['esm'],tsconfig: './tsconfig.src.json',external: undefined,+ noExternal: [+ '@composio/core',+ /^zod(?:\/.*)?$/,+ /^@agentclientprotocol\/sdk(?:\/.*)?$/,+ /^@modelcontextprotocol\/sdk(?:\/.*)?$/,+ ],publint: undefined,attw: undefined,});