Skip to content

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

feat: fix bundling for run (#3040)

Rahul Tarak9538903fc689
diff --git a/.github/workflows/cli.test-installation.yml b/.github/workflows/cli.test-installation.yml
index 8fc0dba54..ef8fd69af 100644
--- a/.github/workflows/cli.test-installation.yml
+++ b/.github/workflows/cli.test-installation.yml
@@ -224,39 +224,34 @@ jobs:
echo "=== Current PATH before sourcing ==="
echo "$PATH"
- # Source the appropriate shell config
if [[ "${{ matrix.shell }}" == "zsh" ]]; then
if [[ -f ~/.zshrc ]]; then
- echo "Sourcing ~/.zshrc..."
- source ~/.zshrc
- echo "PATH after sourcing .zshrc: $PATH"
+ echo "Testing interactive zsh startup..."
+ if zsh -ic 'echo "PATH after startup: $PATH"; command -v composio; composio --version; composio --help | head -5'; then
+ echo "✅ composio found in PATH via zsh"
+ else
+ echo "❌ composio not found in PATH via zsh"
+ exit 1
+ fi
else
echo "❌ ~/.zshrc not found - install script failed to create it"
exit 1
fi
else
if [[ -f ~/.bashrc ]]; then
- echo "Sourcing ~/.bashrc..."
- source ~/.bashrc
- echo "PATH after sourcing .bashrc: $PATH"
+ echo "Testing interactive bash startup..."
+ if bash -ic 'echo "PATH after startup: $PATH"; command -v composio; composio --version; composio --help | head -5'; then
+ echo "✅ composio found in PATH via bash"
+ else
+ echo "❌ composio not found in PATH via bash"
+ exit 1
+ fi
else
echo "❌ ~/.bashrc not found - install script failed to create it"
exit 1
fi
fi
- # Test if composio is in PATH
- if command -v composio &> /dev/null; then
- echo "✅ composio found in PATH"
- which composio
- composio --version
- composio --help | head -5
- else
- echo "❌ composio not found in PATH"
- echo "Final PATH: $PATH"
- exit 1
- fi
-
- name: Test shell config updates
run: |
echo "Checking shell configuration updates..."
diff --git a/install.sh b/install.sh
index d622b7460..dbf155e5f 100755
--- a/install.sh
+++ b/install.sh
@@ -170,21 +170,36 @@ companion_modules=(
"run-subagent-legacy.mjs"
)
-# Handle nested directory structure (composio-<target>/composio)
-if [[ -f "$tmpdir/composio-$target/composio" ]]; then
- mv "$tmpdir/composio-$target/composio" "$exe"
+install_companion_modules() {
+ local source_dir="$1"
+ local installed_count=0
+ local missing=()
+
for module in "${companion_modules[@]}"; do
- if [[ -f "$tmpdir/composio-$target/$module" ]]; then
- mv "$tmpdir/composio-$target/$module" "$COMPOSIO_INSTALL_DIR/$module"
+ if [[ -f "$source_dir/$module" ]]; then
+ mv "$source_dir/$module" "$COMPOSIO_INSTALL_DIR/$module"
+ installed_count=$((installed_count + 1))
+ else
+ missing+=("$module")
fi
done
+
+ if (( installed_count > 0 && installed_count < ${#companion_modules[@]} )); then
+ error "Downloaded archive is incomplete; missing companion modules: ${missing[*]}"
+ fi
+
+ 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."
+ fi
+}
+
+# Handle nested directory structure (composio-<target>/composio)
+if [[ -f "$tmpdir/composio-$target/composio" ]]; then
+ mv "$tmpdir/composio-$target/composio" "$exe"
+ install_companion_modules "$tmpdir/composio-$target"
elif [[ -f "$tmpdir/composio" ]]; then
mv "$tmpdir/composio" "$exe"
- for module in "${companion_modules[@]}"; do
- if [[ -f "$tmpdir/$module" ]]; then
- mv "$tmpdir/$module" "$COMPOSIO_INSTALL_DIR/$module"
- fi
- done
+ install_companion_modules "$tmpdir"
else
error 'Binary not found in extracted archive'
fi
diff --git a/ts/packages/cli/scripts/_shared.ts b/ts/packages/cli/scripts/_shared.ts
index 28c4aa64c..196367327 100644
--- a/ts/packages/cli/scripts/_shared.ts
+++ b/ts/packages/cli/scripts/_shared.ts
@@ -1,6 +1,9 @@
+import { mkdir } from 'node:fs/promises';
import process from 'node:process';
-import { Cause, Exit } from 'effect';
+import { Command } from '@effect/platform';
+import { Cause, Console, Effect, Exit, Stream } from 'effect';
import type { Teardown } from '@effect/platform/Runtime';
+import { RUN_COMPANION_MODULE_BASENAMES } from '../src/services/run-companion-modules';
/**
* Shared teardown for all CLI scripts.
@@ -13,3 +16,53 @@ export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: n
const errorCode = Number(process.exitCode ?? 1);
onExit(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 exitCode = yield* runLoggedCommand(args);
+ if (exitCode !== 0) {
+ return yield* Effect.fail(new Error(`Failed to build companion module: ${name}`));
+ }
+ }
+ });
diff --git a/ts/packages/cli/scripts/build-all-binaries.ts b/ts/packages/cli/scripts/build-all-binaries.ts
index 57ac5109a..c073e610c 100644
--- a/ts/packages/cli/scripts/build-all-binaries.ts
+++ b/ts/packages/cli/scripts/build-all-binaries.ts
@@ -16,7 +16,7 @@ import process from 'node:process';
import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLevel } from 'effect';
import { Command } from '@effect/platform';
import { BunContext, BunRuntime } from '@effect/platform-bun';
-import { teardown } from './_shared';
+import { buildCompanionModules, teardown } from './_shared';
/**
* All cross-compilation targets and their artifact names.
@@ -85,6 +85,10 @@ export function buildAllBinaries() {
yield* Console.log(`Built: ${outfile}`);
}
+ const companionOutputDir = './dist/binaries/companions';
+ yield* Console.log(`\nBuilding run companion modules in ${companionOutputDir}...`);
+ yield* buildCompanionModules(companionOutputDir);
+
yield* Console.log(`\nAll ${TARGETS.length} binaries built successfully.`);
});
}
diff --git a/ts/packages/cli/scripts/build-binary-cross.ts b/ts/packages/cli/scripts/build-binary-cross.ts
index c962025d5..9404099da 100644
--- a/ts/packages/cli/scripts/build-binary-cross.ts
+++ b/ts/packages/cli/scripts/build-binary-cross.ts
@@ -14,12 +14,11 @@
* Output: `dist/binaries/<artifact-name>`
*/
-import { mkdir } from 'node:fs/promises';
import process from 'node:process';
import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLevel } from 'effect';
import { Command } from '@effect/platform';
import { BunContext, BunRuntime } from '@effect/platform-bun';
-import { teardown } from './_shared';
+import { buildCompanionModules, teardown } from './_shared';
/**
* Maps Bun cross-compilation targets to Composio artifact names.
@@ -33,12 +32,6 @@ const TARGET_MAP: Record<string, string> = {
const VALID_TARGETS = Object.keys(TARGET_MAP);
-const RUN_COMPANION_MODULE_BASENAMES = [
- 'run-subagent-shared',
- 'run-subagent-acp',
- 'run-subagent-legacy',
-] as const;
-
function parseTarget(): { target: string; artifact: string } {
const targetIdx = process.argv.indexOf('--target');
if (targetIdx === -1 || !process.argv[targetIdx + 1]) {
@@ -114,48 +107,7 @@ export function buildBinaryCross() {
}
const companionOutputDir = './dist/binaries/companions';
- yield* Effect.tryPromise(() => mkdir(companionOutputDir, { recursive: true }));
-
- for (const name of RUN_COMPANION_MODULE_BASENAMES) {
- const companionArgs = [
- 'bun',
- 'build',
- `./src/services/${name}.ts`,
- '--outfile',
- `${companionOutputDir}/${name}.mjs`,
- '--format',
- 'esm',
- '--target',
- 'bun',
- ] as const satisfies ReadonlyArray<string>;
-
- const companionCmd = Command.make(...companionArgs);
- const { exitCode: companionExitCode } = yield* companionCmd.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',
- }
- )
- )
- );
-
- if (companionExitCode !== 0) {
- return yield* Effect.fail(new Error(`Failed to build companion module: ${name}`));
- }
- }
+ yield* buildCompanionModules(companionOutputDir);
yield* Console.log(`Binary cross-compiled: ${outfile}`);
});
diff --git a/ts/packages/cli/scripts/build-binary.ts b/ts/packages/cli/scripts/build-binary.ts
index 4e5c91091..b6398217d 100644
--- a/ts/packages/cli/scripts/build-binary.ts
+++ b/ts/packages/cli/scripts/build-binary.ts
@@ -2,7 +2,7 @@ import process from 'node:process';
import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLevel } from 'effect';
import { Command } from '@effect/platform';
import { BunContext, BunRuntime } from '@effect/platform-bun';
-import { teardown } from './_shared';
+import { buildCompanionModules, teardown } from './_shared';
/**
* Usage: `bun scripts/build-binary.ts`
@@ -76,53 +76,7 @@ export function buildBinary() {
// Build companion modules that `composio run` imports in the child process.
// These cannot live inside the compiled binary because they run in a separate
// Bun process via the --preload globals file.
- const companionModules = [
- 'src/services/run-subagent-shared.ts',
- 'src/services/run-subagent-acp.ts',
- 'src/services/run-subagent-legacy.ts',
- ] as const;
-
- for (const entry of companionModules) {
- const name = entry.replace(/^.*\//, '').replace(/\.ts$/, '');
- const companionArgs = [
- 'bun',
- 'build',
- `./${entry}`,
- '--outfile',
- `./dist/${name}.mjs`,
- '--format',
- 'esm',
- '--target',
- 'bun',
- ] as const satisfies ReadonlyArray<string>;
-
- yield* Effect.logDebug(`Building companion module: ${name}`);
-
- const companionCmd = Command.make(...companionArgs);
- const { exitCode: companionExitCode } = yield* companionCmd.pipe(
- Command.start,
- Effect.flatMap(p =>
- Effect.all(
- {
- exitCode: p.exitCode,
- output: Stream.merge(
- Stream.decodeText(p.stdout, 'utf-8'),
- Stream.decodeText(p.stderr, 'utf-8'),
- { haltStrategy: 'left' }
- ).pipe(
- Stream.tap(chunk => Console.log(chunk)),
- Stream.runDrain
- ),
- },
- { concurrency: 'unbounded' }
- )
- )
- );
-
- if (companionExitCode !== 0) {
- return yield* Effect.fail(new Error(`Failed to build companion module: ${name}`));
- }
- }
+ yield* buildCompanionModules('./dist');
yield* Effect.logDebug('', 'Companion modules built successfully');
});
diff --git a/ts/packages/cli/scripts/install-binary.ts b/ts/packages/cli/scripts/install-binary.ts
index 98f39ceba..365229994 100644
--- a/ts/packages/cli/scripts/install-binary.ts
+++ b/ts/packages/cli/scripts/install-binary.ts
@@ -4,7 +4,9 @@ import { BunContext, BunRuntime } from '@effect/platform-bun';
import { teardown } from './_shared';
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';
/**
* Usage: `COMPOSIO_INSTALL_DIR=<INSTALL_DIR> bun scripts/build-binary.ts <BINARY_PATH>`
@@ -24,8 +26,20 @@ export function installBinary() {
yield* Effect.logDebug(`Installing binary in ${installDir}`);
+ yield* Effect.tryPromise(() => mkdir(installDir, { recursive: true }));
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);
+ yield* Effect.tryPromise(async () => {
+ if (!(await Bun.file(sourcePath).exists())) {
+ throw new Error(`Missing companion module: ${sourcePath}`);
+ }
+ await $`cp ${sourcePath} ${installDir}/${fileName}`.quiet();
+ });
+ }
+
yield* Console.log('Binary successfully installed in', installDir);
});
}
diff --git a/ts/packages/cli/scripts/package-binaries.ts b/ts/packages/cli/scripts/package-binaries.ts
index 29d498efc..97163661e 100644
--- a/ts/packages/cli/scripts/package-binaries.ts
+++ b/ts/packages/cli/scripts/package-binaries.ts
@@ -21,8 +21,10 @@ 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';
const BINARIES_DIR = './dist/binaries';
+const COMPANIONS_DIR = path.join(BINARIES_DIR, 'companions');
/**
* Known binary artifact names (without extension).
@@ -46,11 +48,24 @@ export function packageBinaries() {
return;
}
+ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
+ const companionPath = path.join(COMPANIONS_DIR, fileName);
+ const exists = yield* Effect.tryPromise(() => Bun.file(companionPath).exists());
+ if (!exists) {
+ yield* Console.error(
+ `Missing companion module ${companionPath}. Run build:binary:all before packaging.`
+ );
+ process.exitCode = 1;
+ return;
+ }
+ }
+
yield* Console.log(`Packaging ${binaries.length} binaries...`);
for (const binary of binaries) {
const binaryPath = path.join(BINARIES_DIR, binary);
const zipPath = path.join(BINARIES_DIR, `${binary}.zip`);
+ const absoluteZipPath = path.resolve(zipPath);
// Create nested directory structure: <artifact>/<binary-name>
const tempDir = path.join(BINARIES_DIR, `_pkg_${binary}`);
@@ -59,7 +74,16 @@ export function packageBinaries() {
yield* Effect.tryPromise(async () => {
await $`mkdir -p ${nestedDir}`.quiet();
await $`cp ${binaryPath} ${nestedDir}/composio`.quiet();
- await $`cd ${tempDir} && zip -r ${path.resolve(zipPath)} ${binary}`.quiet();
+ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
+ await $`cp ${path.join(COMPANIONS_DIR, fileName)} ${nestedDir}/${fileName}`.quiet();
+ }
+ const previousCwd = process.cwd();
+ process.chdir(tempDir);
+ try {
+ await $`zip -r ${absoluteZipPath} ${binary}`.quiet();
+ } finally {
+ process.chdir(previousCwd);
+ }
await $`rm -rf ${tempDir}`.quiet();
});
diff --git a/ts/packages/cli/skills/composio-cli/SKILL.md b/ts/packages/cli/skills/composio-cli/SKILL.md
index 92101e40a..76ea8f013 100644
--- a/ts/packages/cli/skills/composio-cli/SKILL.md
+++ b/ts/packages/cli/skills/composio-cli/SKILL.md
@@ -5,29 +5,14 @@ description: Help users operate the published Composio CLI to find the right too
# Composio CLI
-Use the shortest loop that gets the job done: `execute` first, `search` when the slug is unknown, `link` when a connection is missing, then retry `execute`.
-
-## Use The Default Workflow
+## Default Workflow
1. Start with `composio execute <slug>` whenever the slug is known.
-2. Let `execute` do the work. It already validates inputs and checks connection state.
-3. If `execute` says the toolkit is not connected, run `composio link <toolkit>` and retry.
-4. If the arguments are unclear, run `composio execute <slug> --get-schema` or `--dry-run` before guessing.
-5. Reach for `composio search "<task>"` only when the slug is unknown.
-
-## Treat Auth As A Footnote
+2. If `execute` says the toolkit is not connected, run `composio link <toolkit>` and retry.
+3. If the arguments are unclear, run `composio execute <slug> --get-schema` or `--dry-run` before guessing.
+4. Reach for `composio search "<task>"` only when the slug is unknown.
-Use auth checks as quick preflight, not as the main workflow.
-
-```bash
-composio whoami
-```
-
-If `composio whoami` fails, run `composio login` and then move straight back to `execute`.
-
-## Use `execute` First
-
-Run a known slug:
+## `execute` — Run A Tool
```bash
composio execute GITHUB_GET_THE_AUTHENTICATED_USER -d '{}'
@@ -48,68 +33,87 @@ composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{
Pass data from a file or stdin:
```bash
-composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d @issue.json
-cat issue.json | composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d -
+composio execute GITHUB_CREATE_AN_ISSUE -d @issue.json
+cat issue.json | composio execute GITHUB_CREATE_AN_ISSUE -d -
```
-Recover from missing connections:
+## `search` — Find The Slug
```bash
-composio execute GMAIL_FETCH_EMAILS -d '{ max_results: 1 }'
-composio link gmail --no-browser
+composio search "create a github issue"
+composio search "send an email" --toolkits gmail
```
-After the auth flow completes, rerun the original `execute` command.
-
-Prefer `composio tools info` and `composio tools list` only when `search`, `--get-schema`, or the error message still leave the user stuck.
+Read the returned slugs, choose the best match, and move back to `execute`.
-## Use `search` To Find The Slug
+## `link` — Connect An Account
-When the user knows the task but not the tool name, search first and then execute the best match.
+Use `link` when `execute` reports the toolkit is not connected, or the user wants to authorize an account.
```bash
-composio search "create a github issue"
-composio search "send an email" --toolkits gmail
+composio link gmail
+composio link googlecalendar --no-browser
```
-Read the returned slugs, choose the best match, and immediately move back to `execute`.
+After linking, retry the original `execute` command.
-## Use `link` Only To Unblock `execute`
+## `proxy` — Raw API Access
-Use `link` when `execute` reports that the toolkit is not connected, or when the user explicitly wants to authorize an account.
+Use `composio proxy` when the toolkit supports a raw API operation that is easier than finding a dedicated tool.
```bash
-composio link gmail
-composio link googlecalendar --no-browser
+composio proxy https://api.github.com/user --toolkit github --method GET </dev/null
```
-After linking, retry the original `execute` command instead of changing strategies.
+## `run` — Scripting, LLMs, and Programmatic Workflows
+
+> **For programmatic calls, LLM workflows, or anything beyond a single tool call — use `composio run`.**
+
+`composio run` executes an inline JavaScript snippet with authenticated `execute()`, `search()`, `proxy()`, and `subAgent()` helpers pre-injected. No SDK setup required.
+
+Chain multiple tools:
-## Use Power Tools Deliberately
+```bash
+composio run '
+ const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");
+ const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 1 });
+ console.log({ login: me.data.login, fetchedEmails: !!emails.data });
+'
+```
-Use `composio run` when one tool call is not enough and the user needs chaining, batching, lightweight automation, or sub-agent orchestration.
+Fan out with `Promise.all`:
```bash
composio run '
const [me, emails] = await Promise.all([
execute("GITHUB_GET_THE_AUTHENTICATED_USER"),
- execute("GMAIL_FETCH_EMAILS", { max_results: 1 }),
+ execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),
]);
-
- console.log({
- login: me.data.login,
- fetchedEmails: !!emails.data,
- });
+ console.log({ login: me.data.login, emailCount: emails.data.messages?.length });
'
```
-Use `composio proxy` when the toolkit supports a raw API operation that is easier than finding a dedicated tool.
+Feed tool output into an LLM and get structured JSON back:
```bash
-composio proxy https://api.github.com/user --toolkit github --method GET </dev/null
+composio run --logs-off '
+ const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 5 });
+ const brief = await subAgent(
+ `Summarize these emails and count them.\n\n${emails.prompt()}`,
+ { schema: z.object({ summary: z.string(), count: z.number() }) }
+ );
+ console.log(brief.structuredOutput);
+'
```
-For richer `run`, `subAgent()`, `result.prompt()`, `Promise.all`, and mixed `execute()` plus `proxy()` patterns, load [references/power-user-examples.md](references/power-user-examples.md).
+For more patterns — `proxy()` inside scripts, `search()` inside scripts, mixed `execute()` + `proxy()`, and `--dry-run`/`--debug` flags — load [references/power-user-examples.md](references/power-user-examples.md).
+
+## Auth
+
+```bash
+composio whoami # check current session
+composio login # authenticate if whoami fails
+```
## Escalate Only When Needed
diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.ts
index 6d2382208..6bf851a7e 100644
--- a/ts/packages/cli/src/commands/login.cmd.ts
+++ b/ts/packages/cli/src/commands/login.cmd.ts
@@ -119,8 +119,8 @@ const storeCredentials = (params: {
const email = sessionInfo?.org_member.email || fallbackEmail || undefined;
yield* ui.log.success(email ? `Logged in as ${email}` : 'Logged in successfully');
if (!skipHints) {
- yield* ui.log.info(commandHintStep('Set up developer project context', 'dev.init'));
- yield* ui.log.info(commandHintStep('Switch your default org later', 'dev.orgs.switch'));
+ yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
+ yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));
}
// Emit structured JSON for piped/scripted consumption (agent-native)
@@ -251,8 +251,8 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPick
org_name: finalOrgName,
})
);
- yield* ui.log.info(commandHintStep('Set up developer project context', 'dev.init'));
- yield* ui.log.info(commandHintStep('Switch your default org later', 'dev.orgs.switch'));
+ yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
+ yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));
yield* ui.outro("You're all set!");
}
});
@@ -411,8 +411,8 @@ export const browserLogin = (params: {
org_name: finalOrgName,
})
);
- yield* ui.log.info(commandHintStep('Set up developer project context', 'dev.init'));
- yield* ui.log.info(commandHintStep('Switch your default org later', 'dev.orgs.switch'));
+ yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
+ yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));
yield* ui.outro("You're all set!");
}
});
diff --git a/ts/packages/cli/src/commands/run.cmd.ts b/ts/packages/cli/src/commands/run.cmd.ts
index e2fc3be45..0240f10bf 100644
--- a/ts/packages/cli/src/commands/run.cmd.ts
+++ b/ts/packages/cli/src/commands/run.cmd.ts
@@ -2,7 +2,7 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import process from 'node:process';
-import { fileURLToPath, pathToFileURL } from 'node:url';
+import { pathToFileURL } from 'node:url';
import { Args, Command, Options } from '@effect/cli';
import { Effect, Option } from 'effect';
import { ts } from 'ts-morph';
@@ -11,6 +11,7 @@ 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, type MasterKind } from 'src/services/master-detector';
+import { resolveRunCompanionModulePath } from 'src/services/run-companion-modules';
import {
appendCliSessionHistory,
resolveCliSessionArtifacts,
@@ -160,46 +161,26 @@ export const inferCliInvocationPrefix = (
: [process.execPath];
};
-const resolveSiblingModulePath = (relativeNoExtensionFromRunCmd: string): string => {
- const currentFilePath = fileURLToPath(import.meta.url);
- const currentDirectory = path.dirname(currentFilePath);
-
- // Source (.ts) — running from `bun src/bin.ts`
- const tsPath = path.resolve(currentDirectory, `${relativeNoExtensionFromRunCmd}.ts`);
- if (fs.existsSync(tsPath)) {
- return tsPath;
- }
-
- // Built (.js) — running from `bun dist/bin.mjs`
- const jsPath = path.resolve(currentDirectory, `${relativeNoExtensionFromRunCmd}.js`);
- if (fs.existsSync(jsPath)) {
- return jsPath;
- }
-
- // Compiled binary — import.meta.url points to /$bunfs/, files live next to the executable
- const baseName = path.basename(relativeNoExtensionFromRunCmd);
- const exeDir = path.dirname(process.execPath);
- const mjsPath = path.resolve(exeDir, `${baseName}.mjs`);
- if (fs.existsSync(mjsPath)) {
- return mjsPath;
- }
- const exeJsPath = path.resolve(exeDir, `${baseName}.js`);
- if (fs.existsSync(exeJsPath)) {
- return exeJsPath;
- }
-
- // Fallback — return the .js path (will error at runtime with a clear module-not-found)
- return jsPath;
-};
-
const subAgentSharedModuleUrl = pathToFileURL(
- resolveSiblingModulePath('../services/run-subagent-shared')
+ resolveRunCompanionModulePath({
+ callerImportMetaUrl: import.meta.url,
+ execPath: process.execPath,
+ relativeNoExtensionFromCaller: '../services/run-subagent-shared',
+ })
).href;
const subAgentAcpModuleUrl = pathToFileURL(
- resolveSiblingModulePath('../services/run-subagent-acp')
+ resolveRunCompanionModulePath({
+ callerImportMetaUrl: import.meta.url,
+ execPath: process.execPath,
+ relativeNoExtensionFromCaller: '../services/run-subagent-acp',
+ })
).href;
const subAgentLegacyModuleUrl = pathToFileURL(
- resolveSiblingModulePath('../services/run-subagent-legacy')
+ resolveRunCompanionModulePath({
+ callerImportMetaUrl: import.meta.url,
+ execPath: process.execPath,
+ relativeNoExtensionFromCaller: '../services/run-subagent-legacy',
+ })
).href;
type RunHelperContext = {
diff --git a/ts/packages/cli/src/commands/whoami.cmd.ts b/ts/packages/cli/src/commands/whoami.cmd.ts
index ab31f202e..237cc2e6c 100644
--- a/ts/packages/cli/src/commands/whoami.cmd.ts
+++ b/ts/packages/cli/src/commands/whoami.cmd.ts
@@ -37,7 +37,7 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
);
yield* ui.log.step(
[
- commandHintStep('To switch orgs', 'dev.orgs.switch'),
+ commandHintStep('To switch orgs', 'root.orgs.switch'),
commandHintStep('To set up developer project context', 'dev.init'),
].join('\n\n')
);
diff --git a/ts/packages/cli/src/services/command-hints.ts b/ts/packages/cli/src/services/command-hints.ts
index 2b7042d95..fa9ad1c97 100644
--- a/ts/packages/cli/src/services/command-hints.ts
+++ b/ts/packages/cli/src/services/command-hints.ts
@@ -10,6 +10,7 @@ export type CommandHintId =
| 'root.execute'
| 'root.execute.getSchema'
| 'root.link'
+ | 'root.orgs.switch'
| 'dev.init'
| 'dev.playgroundExecute'
| 'dev.playgroundExecute.getSchema'
@@ -52,6 +53,10 @@ export const COMMAND_HINTS: Record<CommandHintId, CommandHintNode> = {
example: params => `composio link ${getParam(params, 'toolkit', '<toolkit>')}`,
links: ['root.execute'],
},
+ 'root.orgs.switch': {
+ example: () => 'composio orgs switch',
+ links: ['root.execute'],
+ },
'dev.init': {
example: () => 'composio dev init',
links: ['dev.playgroundExecute', 'dev.logs.tools', 'dev.logs.triggers'],
@@ -67,12 +72,10 @@ export const COMMAND_HINTS: Record<CommandHintId, CommandHintNode> = {
links: ['dev.playgroundExecute'],
},
'dev.logs.tools': {
- example: params =>
- `composio dev logs tools "${getParam(params, 'logId', '<log_id>')}"`,
+ example: params => `composio dev logs tools "${getParam(params, 'logId', '<log_id>')}"`,
},
'dev.logs.triggers': {
- example: params =>
- `composio dev logs triggers "${getParam(params, 'logId', '<log_id>')}"`,
+ example: params => `composio dev logs triggers "${getParam(params, 'logId', '<log_id>')}"`,
},
'dev.orgs.switch': {
example: () => 'composio dev orgs switch',
@@ -100,11 +103,8 @@ export const COMMAND_HINTS: Record<CommandHintId, CommandHintNode> = {
export const commandHintExample = (id: CommandHintId, params?: HintParams): string =>
COMMAND_HINTS[id].example(params);
-export const commandHintStep = (
- label: string,
- id: CommandHintId,
- params?: HintParams
-): string => `${label}:\n> ${commandHintExample(id, params)}`;
+export const commandHintStep = (label: string, id: CommandHintId, params?: HintParams): string =>
+ `${label}:\n> ${commandHintExample(id, params)}`;
export const commandHintLinks = (id: CommandHintId): ReadonlyArray<CommandHintId> =>
COMMAND_HINTS[id].links ?? [];
diff --git a/ts/packages/cli/src/services/run-companion-modules.ts b/ts/packages/cli/src/services/run-companion-modules.ts
new file mode 100644
index 000000000..38598f259
--- /dev/null
+++ b/ts/packages/cli/src/services/run-companion-modules.ts
@@ -0,0 +1,49 @@
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+export const RUN_COMPANION_MODULE_BASENAMES = [
+ 'run-subagent-shared',
+ 'run-subagent-acp',
+ 'run-subagent-legacy',
+] as const;
+
+export const RUN_COMPANION_MODULE_FILENAMES = RUN_COMPANION_MODULE_BASENAMES.map(
+ name => `${name}.mjs`
+);
+
+export const resolveRunCompanionModulePath = ({
+ callerImportMetaUrl,
+ execPath,
+ relativeNoExtensionFromCaller,
+}: {
+ callerImportMetaUrl: string;
+ execPath: string;
+ relativeNoExtensionFromCaller: string;
+}): string => {
+ const currentFilePath = fileURLToPath(callerImportMetaUrl);
+ const currentDirectory = path.dirname(currentFilePath);
+ const executableDirectory = path.dirname(execPath);
+ const baseName = path.basename(relativeNoExtensionFromCaller);
+
+ const candidates = [
+ path.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.ts`),
+ path.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.js`),
+ path.resolve(currentDirectory, 'services', `${baseName}.mjs`),
+ path.resolve(currentDirectory, 'services', `${baseName}.js`),
+ path.resolve(currentDirectory, `${baseName}.mjs`),
+ path.resolve(currentDirectory, `${baseName}.js`),
+ path.resolve(executableDirectory, `${baseName}.mjs`),
+ path.resolve(executableDirectory, `${baseName}.js`),
+ ];
+
+ for (const candidate of candidates) {
+ if (fs.existsSync(candidate)) {
+ return candidate;
+ }
+ }
+
+ return currentFilePath.startsWith('/$bunfs/')
+ ? path.resolve(executableDirectory, `${baseName}.mjs`)
+ : path.resolve(currentDirectory, `${baseName}.mjs`);
+};
diff --git a/ts/packages/cli/src/services/upgrade-binary.ts b/ts/packages/cli/src/services/upgrade-binary.ts
index 2f6abc88a..071f9dbb4 100644
--- a/ts/packages/cli/src/services/upgrade-binary.ts
+++ b/ts/packages/cli/src/services/upgrade-binary.ts
@@ -12,6 +12,7 @@ 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 } from './run-companion-modules';
export class UpgradeBinaryError extends Data.TaggedError('services/UpgradeBinaryError')<{
readonly cause?: unknown;
@@ -345,11 +346,12 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg
const extractBinary = (
{ name, data }: { name: string; data: Uint8Array },
tempDir: string
- ): Effect.Effect<string, UpgradeBinaryError, never> =>
+ ): Effect.Effect<{ binaryPath: string; packageDir: string }, UpgradeBinaryError, never> =>
Effect.gen(function* () {
const zipPath = path.join(tempDir, name);
const extractDir = path.join(tempDir, 'extract');
- const binaryPath = path.join(extractDir, path.parse(name).name, CLI_BINARY_NAME);
+ const packageDir = path.join(extractDir, path.parse(name).name);
+ const binaryPath = path.join(packageDir, CLI_BINARY_NAME);
yield* Effect.logDebug(`Download zip to ${extractDir}`);
@@ -414,7 +416,10 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg
)
);
- return binaryPath;
+ return {
+ binaryPath,
+ packageDir,
+ };
});
/**
@@ -463,6 +468,40 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg
)
)
);
+
+ const sourceDirectory = path.dirname(sourcePath);
+ const targetDirectory = path.dirname(targetPath);
+
+ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
+ const sourceCompanion = path.join(sourceDirectory, fileName);
+ const sourceExists = yield* fs
+ .exists(sourceCompanion)
+ .pipe(Effect.catchAll(() => Effect.succeed(false)));
+
+ if (!sourceExists) {
+ return yield* Effect.fail(
+ new UpgradeBinaryError({
+ cause: new Error(`Missing companion module: ${sourceCompanion}`),
+ message: 'Downloaded binary package is incomplete',
+ })
+ );
+ }
+
+ yield* fs
+ .copy(sourceCompanion, path.join(targetDirectory, fileName), {
+ overwrite: true,
+ })
+ .pipe(
+ Effect.catchAll(error =>
+ Effect.fail(
+ new UpgradeBinaryError({
+ cause: error as Error,
+ message: `Failed to replace companion module: ${fileName}`,
+ })
+ )
+ )
+ );
+ }
});
/**
@@ -531,8 +570,8 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg
)
);
- const extractedBinaryPath = yield* extractBinary({ name, data }, tmpDir);
- yield* replaceBinary(extractedBinaryPath, currentPath);
+ const extractedBinary = yield* extractBinary({ name, data }, tmpDir);
+ yield* replaceBinary(extractedBinary.binaryPath, currentPath);
yield* spinner.stop('Upgrade completed!');
return release.tag_name;
diff --git a/ts/packages/cli/test/src/commands/run.cmd.test.ts b/ts/packages/cli/test/src/commands/run.cmd.test.ts
index faa353a20..4a20b1476 100644
--- a/ts/packages/cli/test/src/commands/run.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/run.cmd.test.ts
@@ -1,6 +1,7 @@
import * as fs from 'node:fs';
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 { Effect } from 'effect';
import { afterEach, it, vi } from 'vitest';
@@ -10,6 +11,7 @@ import {
inferCliInvocationPrefix,
wrapInlineCodeForRun,
} from 'src/commands/run.cmd';
+import { resolveRunCompanionModulePath } from 'src/services/run-companion-modules';
import { buildStructuredPrompt, finalizeInvokeAgentText } from 'src/services/run-subagent-shared';
import { cli, MockConsole, TestLive } from 'test/__utils__';
@@ -311,6 +313,41 @@ describe('inferCliInvocationPrefix', () => {
});
});
+describe('resolveRunCompanionModulePath', () => {
+ it('[Given] a bundled dist chunk [Then] it resolves sibling companion modules in dist', () => {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-companion-dist-'));
+ const callerPath = path.join(tempDir, 'commands-abc.mjs');
+ const servicesDir = path.join(tempDir, 'services');
+ const companionPath = path.join(servicesDir, 'run-subagent-shared.mjs');
+ fs.writeFileSync(callerPath, '', 'utf8');
+ fs.mkdirSync(servicesDir);
+ fs.writeFileSync(companionPath, '', 'utf8');
+
+ expect(
+ resolveRunCompanionModulePath({
+ callerImportMetaUrl: pathToFileURL(callerPath).href,
+ execPath: '/tmp/composio',
+ relativeNoExtensionFromCaller: '../services/run-subagent-shared',
+ })
+ ).toBe(companionPath);
+ });
+
+ it('[Given] a compiled bunfs caller [Then] it falls back to modules next to the binary', () => {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-companion-bin-'));
+ const execPath = path.join(tempDir, 'composio');
+ const companionPath = path.join(tempDir, 'run-subagent-shared.mjs');
+ fs.writeFileSync(companionPath, '', 'utf8');
+
+ expect(
+ resolveRunCompanionModulePath({
+ callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
+ execPath,
+ relativeNoExtensionFromCaller: '../services/run-subagent-shared',
+ })
+ ).toBe(companionPath);
+ });
+});
+
describe('extractInlineExecuteToolSlugs', () => {
it('[Given] inline run source [Then] it finds static execute slugs from the AST', () => {
expect(
diff --git a/ts/packages/cli/tsdown.config.ts b/ts/packages/cli/tsdown.config.ts
index 03f9673f3..4b55b45b5 100644
--- a/ts/packages/cli/tsdown.config.ts
+++ b/ts/packages/cli/tsdown.config.ts
@@ -3,12 +3,14 @@ import { baseConfig } from '../../../tsdown.config.base';
export default defineConfig({
...baseConfig,
- entry: ['src/bin.ts'],
+ entry: [
+ 'src/bin.ts',
+ 'src/services/run-subagent-shared.ts',
+ 'src/services/run-subagent-acp.ts',
+ 'src/services/run-subagent-legacy.ts',
+ ],
format: ['esm'],
tsconfig: './tsconfig.src.json',
- banner: {
- js: '#!/usr/bin/env bun',
- },
external: undefined,
publint: undefined,
attw: undefined,