Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 22, 02:00 UTC
feat: fix bundling for run (#3040)
run bundling was not working for some shared scripts in certain envs --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Rahul Tarak committed
Mar 27, 2026 at 03:21 UTC
9538903fc6897161344ceb8f7aacd5f9d3df50ca
17 files changed
+363
-240
.github/workflows/cli.test-installation.yml
+14
-19
@@ -224,39 +224,34 @@ jobs:
224
echo "=== Current PATH before sourcing ==="
225
echo "$PATH"
226
227
- # Source the appropriate shell config
227
if [[ "${{ matrix.shell }}" == "zsh" ]]; then
228
if [[ -f ~/.zshrc ]]; then
230
- echo "Sourcing ~/.zshrc..."
231
- source ~/.zshrc
232
- echo "PATH after sourcing .zshrc: $PATH"
229
+ echo "Testing interactive zsh startup..."
230
+ if zsh -ic 'echo "PATH after startup: $PATH"; command -v composio; composio --version; composio --help | head -5'; then
231
+ echo "✅ composio found in PATH via zsh"
232
+ else
233
+ echo "❌ composio not found in PATH via zsh"
234
+ exit 1
235
+ fi
236
else
237
echo "❌ ~/.zshrc not found - install script failed to create it"
238
exit 1
239
fi
240
else
241
if [[ -f ~/.bashrc ]]; then
239
- echo "Sourcing ~/.bashrc..."
240
- source ~/.bashrc
241
- echo "PATH after sourcing .bashrc: $PATH"
242
+ echo "Testing interactive bash startup..."
243
+ if bash -ic 'echo "PATH after startup: $PATH"; command -v composio; composio --version; composio --help | head -5'; then
244
+ echo "✅ composio found in PATH via bash"
245
+ else
246
+ echo "❌ composio not found in PATH via bash"
247
+ exit 1
248
+ fi
249
else
250
echo "❌ ~/.bashrc not found - install script failed to create it"
251
exit 1
252
fi
253
fi
254
248
- # Test if composio is in PATH
249
- if command -v composio &> /dev/null; then
250
- echo "✅ composio found in PATH"
251
- which composio
252
- composio --version
253
- composio --help | head -5
254
- else
255
- echo "❌ composio not found in PATH"
256
- echo "Final PATH: $PATH"
257
- exit 1
258
- fi
259
-
255
- name: Test shell config updates
256
run: |
257
echo "Checking shell configuration updates..."
install.sh
+25
-10
@@ -170,21 +170,36 @@ companion_modules=(
170
"run-subagent-legacy.mjs"
171
)
172
173
-# Handle nested directory structure (composio-<target>/composio)
174
-if [[ -f "$tmpdir/composio-$target/composio" ]]; then
175
- mv "$tmpdir/composio-$target/composio" "$exe"
173
+install_companion_modules() {
174
+ local source_dir="$1"
175
+ local installed_count=0
176
+ local missing=()
177
+
178
for module in "${companion_modules[@]}"; do
177
- if [[ -f "$tmpdir/composio-$target/$module" ]]; then
178
- mv "$tmpdir/composio-$target/$module" "$COMPOSIO_INSTALL_DIR/$module"
179
+ if [[ -f "$source_dir/$module" ]]; then
180
+ mv "$source_dir/$module" "$COMPOSIO_INSTALL_DIR/$module"
181
+ installed_count=$((installed_count + 1))
182
+ else
183
+ missing+=("$module")
184
fi
185
done
186
+
187
+ if (( installed_count > 0 && installed_count < ${#companion_modules[@]} )); then
188
+ error "Downloaded archive is incomplete; missing companion modules: ${missing[*]}"
189
+ fi
190
+
191
+ if (( installed_count == 0 )); then
192
+ warn "This release archive does not include the companion modules required by 'composio run'. That command may be unavailable in this version."
193
+ fi
194
+}
195
+
196
+# Handle nested directory structure (composio-<target>/composio)
197
+if [[ -f "$tmpdir/composio-$target/composio" ]]; then
198
+ mv "$tmpdir/composio-$target/composio" "$exe"
199
+ install_companion_modules "$tmpdir/composio-$target"
200
elif [[ -f "$tmpdir/composio" ]]; then
201
mv "$tmpdir/composio" "$exe"
183
- for module in "${companion_modules[@]}"; do
184
- if [[ -f "$tmpdir/$module" ]]; then
185
- mv "$tmpdir/$module" "$COMPOSIO_INSTALL_DIR/$module"
186
- fi
187
- done
202
+ install_companion_modules "$tmpdir"
203
else
204
error 'Binary not found in extracted archive'
205
fi
ts/packages/cli/scripts/_shared.ts
+54
-1
@@ -1,6 +1,9 @@
1
+import { mkdir } from 'node:fs/promises';
2
import process from 'node:process';
2
-import { Cause, Exit } from 'effect';
3
+import { Command } from '@effect/platform';
4
+import { Cause, Console, Effect, Exit, Stream } from 'effect';
5
import type { Teardown } from '@effect/platform/Runtime';
6
+import { RUN_COMPANION_MODULE_BASENAMES } from '../src/services/run-companion-modules';
7
8
/**
9
* Shared teardown for all CLI scripts.
@@ -13,3 +16,53 @@ export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: n
16
const errorCode = Number(process.exitCode ?? 1);
17
onExit(shouldFail ? errorCode : 0);
18
};
19
+
20
+type LoggedCommandArgs = readonly [string, ...string[]];
21
+
22
+const runLoggedCommand = (args: LoggedCommandArgs) =>
23
+ Command.make(...args).pipe(
24
+ Command.start,
25
+ Effect.flatMap(process =>
26
+ Effect.all(
27
+ {
28
+ exitCode: process.exitCode,
29
+ output: Stream.merge(
30
+ Stream.decodeText(process.stdout, 'utf-8'),
31
+ Stream.decodeText(process.stderr, 'utf-8'),
32
+ { haltStrategy: 'left' }
33
+ ).pipe(
34
+ Stream.tap(chunk => Console.log(chunk)),
35
+ Stream.runDrain
36
+ ),
37
+ },
38
+ {
39
+ concurrency: 'unbounded',
40
+ }
41
+ )
42
+ ),
43
+ Effect.map(({ exitCode }) => exitCode)
44
+ );
45
+
46
+export const buildCompanionModules = (outputDir: string) =>
47
+ Effect.gen(function* () {
48
+ yield* Effect.tryPromise(() => mkdir(outputDir, { recursive: true }));
49
+
50
+ for (const name of RUN_COMPANION_MODULE_BASENAMES) {
51
+ const args = [
52
+ 'bun',
53
+ 'build',
54
+ `./src/services/${name}.ts`,
55
+ '--outfile',
56
+ `${outputDir}/${name}.mjs`,
57
+ '--format',
58
+ 'esm',
59
+ '--target',
60
+ 'bun',
61
+ ] as const satisfies LoggedCommandArgs;
62
+
63
+ const exitCode = yield* runLoggedCommand(args);
64
+ if (exitCode !== 0) {
65
+ return yield* Effect.fail(new Error(`Failed to build companion module: ${name}`));
66
+ }
67
+ }
68
+ });
ts/packages/cli/scripts/build-all-binaries.ts
+5
-1
@@ -16,7 +16,7 @@ import process from 'node:process';
16
import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLevel } from 'effect';
17
import { Command } from '@effect/platform';
18
import { BunContext, BunRuntime } from '@effect/platform-bun';
19
-import { teardown } from './_shared';
19
+import { buildCompanionModules, teardown } from './_shared';
20
21
/**
22
* All cross-compilation targets and their artifact names.
@@ -85,6 +85,10 @@ export function buildAllBinaries() {
85
yield* Console.log(`Built: ${outfile}`);
86
}
87
88
+ const companionOutputDir = './dist/binaries/companions';
89
+ yield* Console.log(`\nBuilding run companion modules in ${companionOutputDir}...`);
90
+ yield* buildCompanionModules(companionOutputDir);
91
+
92
yield* Console.log(`\nAll ${TARGETS.length} binaries built successfully.`);
93
});
94
}
ts/packages/cli/scripts/build-binary-cross.ts
+2
-50
@@ -14,12 +14,11 @@
14
* Output: `dist/binaries/<artifact-name>`
15
*/
16
17
-import { mkdir } from 'node:fs/promises';
17
import process from 'node:process';
18
import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLevel } from 'effect';
19
import { Command } from '@effect/platform';
20
import { BunContext, BunRuntime } from '@effect/platform-bun';
22
-import { teardown } from './_shared';
21
+import { buildCompanionModules, teardown } from './_shared';
22
23
/**
24
* Maps Bun cross-compilation targets to Composio artifact names.
@@ -33,12 +32,6 @@ const TARGET_MAP: Record<string, string> = {
32
33
const VALID_TARGETS = Object.keys(TARGET_MAP);
34
36
-const RUN_COMPANION_MODULE_BASENAMES = [
37
- 'run-subagent-shared',
38
- 'run-subagent-acp',
39
- 'run-subagent-legacy',
40
-] as const;
41
-
35
function parseTarget(): { target: string; artifact: string } {
36
const targetIdx = process.argv.indexOf('--target');
37
if (targetIdx === -1 || !process.argv[targetIdx + 1]) {
@@ -114,48 +107,7 @@ export function buildBinaryCross() {
107
}
108
109
const companionOutputDir = './dist/binaries/companions';
117
- yield* Effect.tryPromise(() => mkdir(companionOutputDir, { recursive: true }));
118
-
119
- for (const name of RUN_COMPANION_MODULE_BASENAMES) {
120
- const companionArgs = [
121
- 'bun',
122
- 'build',
123
- `./src/services/${name}.ts`,
124
- '--outfile',
125
- `${companionOutputDir}/${name}.mjs`,
126
- '--format',
127
- 'esm',
128
- '--target',
129
- 'bun',
130
- ] as const satisfies ReadonlyArray<string>;
131
-
132
- const companionCmd = Command.make(...companionArgs);
133
- const { exitCode: companionExitCode } = yield* companionCmd.pipe(
134
- Command.start,
135
- Effect.flatMap(process =>
136
- Effect.all(
137
- {
138
- exitCode: process.exitCode,
139
- output: Stream.merge(
140
- Stream.decodeText(process.stdout, 'utf-8'),
141
- Stream.decodeText(process.stderr, 'utf-8'),
142
- { haltStrategy: 'left' }
143
- ).pipe(
144
- Stream.tap(chunk => Console.log(chunk)),
145
- Stream.runDrain
146
- ),
147
- },
148
- {
149
- concurrency: 'unbounded',
150
- }
151
- )
152
- )
153
- );
154
-
155
- if (companionExitCode !== 0) {
156
- return yield* Effect.fail(new Error(`Failed to build companion module: ${name}`));
157
- }
158
- }
110
+ yield* buildCompanionModules(companionOutputDir);
111
112
yield* Console.log(`Binary cross-compiled: ${outfile}`);
113
});
ts/packages/cli/scripts/build-binary.ts
+2
-48
@@ -2,7 +2,7 @@ import process from 'node:process';
2
import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLevel } from 'effect';
3
import { Command } from '@effect/platform';
4
import { BunContext, BunRuntime } from '@effect/platform-bun';
5
-import { teardown } from './_shared';
5
+import { buildCompanionModules, teardown } from './_shared';
6
7
/**
8
* Usage: `bun scripts/build-binary.ts`
@@ -76,53 +76,7 @@ export function buildBinary() {
76
// Build companion modules that `composio run` imports in the child process.
77
// These cannot live inside the compiled binary because they run in a separate
78
// Bun process via the --preload globals file.
79
- const companionModules = [
80
- 'src/services/run-subagent-shared.ts',
81
- 'src/services/run-subagent-acp.ts',
82
- 'src/services/run-subagent-legacy.ts',
83
- ] as const;
84
-
85
- for (const entry of companionModules) {
86
- const name = entry.replace(/^.*\//, '').replace(/\.ts$/, '');
87
- const companionArgs = [
88
- 'bun',
89
- 'build',
90
- `./${entry}`,
91
- '--outfile',
92
- `./dist/${name}.mjs`,
93
- '--format',
94
- 'esm',
95
- '--target',
96
- 'bun',
97
- ] as const satisfies ReadonlyArray<string>;
98
-
99
- yield* Effect.logDebug(`Building companion module: ${name}`);
100
-
101
- const companionCmd = Command.make(...companionArgs);
102
- const { exitCode: companionExitCode } = yield* companionCmd.pipe(
103
- Command.start,
104
- Effect.flatMap(p =>
105
- Effect.all(
106
- {
107
- exitCode: p.exitCode,
108
- output: Stream.merge(
109
- Stream.decodeText(p.stdout, 'utf-8'),
110
- Stream.decodeText(p.stderr, 'utf-8'),
111
- { haltStrategy: 'left' }
112
- ).pipe(
113
- Stream.tap(chunk => Console.log(chunk)),
114
- Stream.runDrain
115
- ),
116
- },
117
- { concurrency: 'unbounded' }
118
- )
119
- )
120
- );
121
-
122
- if (companionExitCode !== 0) {
123
- return yield* Effect.fail(new Error(`Failed to build companion module: ${name}`));
124
- }
125
- }
79
+ yield* buildCompanionModules('./dist');
80
81
yield* Effect.logDebug('', 'Companion modules built successfully');
82
});
ts/packages/cli/scripts/install-binary.ts
+14
@@ -4,7 +4,9 @@ import { BunContext, BunRuntime } from '@effect/platform-bun';
4
import { teardown } from './_shared';
5
import path from 'node:path';
6
import os from 'node:os';
7
+import { mkdir } from 'node:fs/promises';
8
import { $ } from 'bun';
9
+import { RUN_COMPANION_MODULE_FILENAMES } from '../src/services/run-companion-modules';
10
11
/**
12
* Usage: `COMPOSIO_INSTALL_DIR=<INSTALL_DIR> bun scripts/build-binary.ts <BINARY_PATH>`
@@ -24,8 +26,20 @@ export function installBinary() {
26
27
yield* Effect.logDebug(`Installing binary in ${installDir}`);
28
29
+ yield* Effect.tryPromise(() => mkdir(installDir, { recursive: true }));
30
yield* Effect.tryPromise(() => $`cp ${binaryPath} ${installDir}/composio`.quiet());
31
32
+ const sourceDirectory = path.dirname(path.resolve(binaryPath));
33
+ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
34
+ const sourcePath = path.join(sourceDirectory, fileName);
35
+ yield* Effect.tryPromise(async () => {
36
+ if (!(await Bun.file(sourcePath).exists())) {
37
+ throw new Error(`Missing companion module: ${sourcePath}`);
38
+ }
39
+ await $`cp ${sourcePath} ${installDir}/${fileName}`.quiet();
40
+ });
41
+ }
42
+
43
yield* Console.log('Binary successfully installed in', installDir);
44
});
45
}
ts/packages/cli/scripts/package-binaries.ts
+25
-1
@@ -21,8 +21,10 @@ import { teardown } from './_shared';
21
import { $ } from 'bun';
22
import { readdir, stat } from 'node:fs/promises';
23
import path from 'node:path';
24
+import { RUN_COMPANION_MODULE_FILENAMES } from '../src/services/run-companion-modules';
25
26
const BINARIES_DIR = './dist/binaries';
27
+const COMPANIONS_DIR = path.join(BINARIES_DIR, 'companions');
28
29
/**
30
* Known binary artifact names (without extension).
@@ -46,11 +48,24 @@ export function packageBinaries() {
48
return;
49
}
50
51
+ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
52
+ const companionPath = path.join(COMPANIONS_DIR, fileName);
53
+ const exists = yield* Effect.tryPromise(() => Bun.file(companionPath).exists());
54
+ if (!exists) {
55
+ yield* Console.error(
56
+ `Missing companion module ${companionPath}. Run build:binary:all before packaging.`
57
+ );
58
+ process.exitCode = 1;
59
+ return;
60
+ }
61
+ }
62
+
63
yield* Console.log(`Packaging ${binaries.length} binaries...`);
64
65
for (const binary of binaries) {
66
const binaryPath = path.join(BINARIES_DIR, binary);
67
const zipPath = path.join(BINARIES_DIR, `${binary}.zip`);
68
+ const absoluteZipPath = path.resolve(zipPath);
69
70
// Create nested directory structure: <artifact>/<binary-name>
71
const tempDir = path.join(BINARIES_DIR, `_pkg_${binary}`);
@@ -59,7 +74,16 @@ export function packageBinaries() {
74
yield* Effect.tryPromise(async () => {
75
await $`mkdir -p ${nestedDir}`.quiet();
76
await $`cp ${binaryPath} ${nestedDir}/composio`.quiet();
62
- await $`cd ${tempDir} && zip -r ${path.resolve(zipPath)} ${binary}`.quiet();
77
+ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
78
+ await $`cp ${path.join(COMPANIONS_DIR, fileName)} ${nestedDir}/${fileName}`.quiet();
79
+ }
80
+ const previousCwd = process.cwd();
81
+ process.chdir(tempDir);
82
+ try {
83
+ await $`zip -r ${absoluteZipPath} ${binary}`.quiet();
84
+ } finally {
85
+ process.chdir(previousCwd);
86
+ }
87
await $`rm -rf ${tempDir}`.quiet();
88
});
89
ts/packages/cli/skills/composio-cli/SKILL.md
+53
-49
@@ -5,29 +5,14 @@ description: Help users operate the published Composio CLI to find the right too
5
6
# Composio CLI
7
8
-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`.
9
-
10
-## Use The Default Workflow
8
+## Default Workflow
9
10
1. Start with `composio execute <slug>` whenever the slug is known.
13
-2. Let `execute` do the work. It already validates inputs and checks connection state.
14
-3. If `execute` says the toolkit is not connected, run `composio link <toolkit>` and retry.
15
-4. If the arguments are unclear, run `composio execute <slug> --get-schema` or `--dry-run` before guessing.
16
-5. Reach for `composio search "<task>"` only when the slug is unknown.
17
-
18
-## Treat Auth As A Footnote
11
+2. If `execute` says the toolkit is not connected, run `composio link <toolkit>` and retry.
12
+3. If the arguments are unclear, run `composio execute <slug> --get-schema` or `--dry-run` before guessing.
13
+4. Reach for `composio search "<task>"` only when the slug is unknown.
14
20
-Use auth checks as quick preflight, not as the main workflow.
21
-
22
-```bash
23
-composio whoami
24
-```
25
-
26
-If `composio whoami` fails, run `composio login` and then move straight back to `execute`.
27
-
28
-## Use `execute` First
29
-
30
-Run a known slug:
15
+## `execute` — Run A Tool
16
17
```bash
18
composio execute GITHUB_GET_THE_AUTHENTICATED_USER -d '{}'
@@ -48,68 +33,87 @@ composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{
33
Pass data from a file or stdin:
34
35
```bash
51
-composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d @issue.json
52
-cat issue.json | composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d -
36
+composio execute GITHUB_CREATE_AN_ISSUE -d @issue.json
37
+cat issue.json | composio execute GITHUB_CREATE_AN_ISSUE -d -
38
```
39
55
-Recover from missing connections:
40
+## `search` — Find The Slug
41
42
```bash
58
-composio execute GMAIL_FETCH_EMAILS -d '{ max_results: 1 }'
59
-composio link gmail --no-browser
43
+composio search "create a github issue"
44
+composio search "send an email" --toolkits gmail
45
```
46
62
-After the auth flow completes, rerun the original `execute` command.
63
-
64
-Prefer `composio tools info` and `composio tools list` only when `search`, `--get-schema`, or the error message still leave the user stuck.
47
+Read the returned slugs, choose the best match, and move back to `execute`.
48
66
-## Use `search` To Find The Slug
49
+## `link` — Connect An Account
50
68
-When the user knows the task but not the tool name, search first and then execute the best match.
51
+Use `link` when `execute` reports the toolkit is not connected, or the user wants to authorize an account.
52
53
```bash
71
-composio search "create a github issue"
72
-composio search "send an email" --toolkits gmail
54
+composio link gmail
55
+composio link googlecalendar --no-browser
56
```
57
75
-Read the returned slugs, choose the best match, and immediately move back to `execute`.
58
+After linking, retry the original `execute` command.
59
77
-## Use `link` Only To Unblock `execute`
60
+## `proxy` — Raw API Access
61
79
-Use `link` when `execute` reports that the toolkit is not connected, or when the user explicitly wants to authorize an account.
62
+Use `composio proxy` when the toolkit supports a raw API operation that is easier than finding a dedicated tool.
63
64
```bash
82
-composio link gmail
83
-composio link googlecalendar --no-browser
65
+composio proxy https://api.github.com/user --toolkit github --method GET </dev/null
66
```
67
86
-After linking, retry the original `execute` command instead of changing strategies.
68
+## `run` — Scripting, LLMs, and Programmatic Workflows
69
+
70
+> **For programmatic calls, LLM workflows, or anything beyond a single tool call — use `composio run`.**
71
+
72
+`composio run` executes an inline JavaScript snippet with authenticated `execute()`, `search()`, `proxy()`, and `subAgent()` helpers pre-injected. No SDK setup required.
73
+
74
+Chain multiple tools:
75
88
-## Use Power Tools Deliberately
76
+```bash
77
+composio run '
78
+ const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");
79
+ const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 1 });
80
+ console.log({ login: me.data.login, fetchedEmails: !!emails.data });
81
+'
82
+```
83
90
-Use `composio run` when one tool call is not enough and the user needs chaining, batching, lightweight automation, or sub-agent orchestration.
84
+Fan out with `Promise.all`:
85
86
```bash
87
composio run '
88
const [me, emails] = await Promise.all([
89
execute("GITHUB_GET_THE_AUTHENTICATED_USER"),
96
- execute("GMAIL_FETCH_EMAILS", { max_results: 1 }),
90
+ execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),
91
]);
98
-
99
- console.log({
100
- login: me.data.login,
101
- fetchedEmails: !!emails.data,
102
- });
92
+ console.log({ login: me.data.login, emailCount: emails.data.messages?.length });
93
'
94
```
95
106
-Use `composio proxy` when the toolkit supports a raw API operation that is easier than finding a dedicated tool.
96
+Feed tool output into an LLM and get structured JSON back:
97
98
```bash
109
-composio proxy https://api.github.com/user --toolkit github --method GET </dev/null
99
+composio run --logs-off '
100
+ const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 5 });
101
+ const brief = await subAgent(
102
+ `Summarize these emails and count them.\n\n${emails.prompt()}`,
103
+ { schema: z.object({ summary: z.string(), count: z.number() }) }
104
+ );
105
+ console.log(brief.structuredOutput);
106
+'
107
```
108
112
-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).
109
+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).
110
+
111
+## Auth
112
+
113
+```bash
114
+composio whoami # check current session
115
+composio login # authenticate if whoami fails
116
+```
117
118
## Escalate Only When Needed
119
ts/packages/cli/src/commands/login.cmd.ts
+6
-6
@@ -119,8 +119,8 @@ const storeCredentials = (params: {
119
const email = sessionInfo?.org_member.email || fallbackEmail || undefined;
120
yield* ui.log.success(email ? `Logged in as ${email}` : 'Logged in successfully');
121
if (!skipHints) {
122
- yield* ui.log.info(commandHintStep('Set up developer project context', 'dev.init'));
123
- yield* ui.log.info(commandHintStep('Switch your default org later', 'dev.orgs.switch'));
122
+ yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
123
+ yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));
124
}
125
126
// Emit structured JSON for piped/scripted consumption (agent-native)
@@ -251,8 +251,8 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPick
251
org_name: finalOrgName,
252
})
253
);
254
- yield* ui.log.info(commandHintStep('Set up developer project context', 'dev.init'));
255
- yield* ui.log.info(commandHintStep('Switch your default org later', 'dev.orgs.switch'));
254
+ yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
255
+ yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));
256
yield* ui.outro("You're all set!");
257
}
258
});
@@ -411,8 +411,8 @@ export const browserLogin = (params: {
411
org_name: finalOrgName,
412
})
413
);
414
- yield* ui.log.info(commandHintStep('Set up developer project context', 'dev.init'));
415
- yield* ui.log.info(commandHintStep('Switch your default org later', 'dev.orgs.switch'));
414
+ yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
415
+ yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));
416
yield* ui.outro("You're all set!");
417
}
418
});
ts/packages/cli/src/commands/run.cmd.ts
+17
-36
@@ -2,7 +2,7 @@ import * as fs from 'node:fs';
2
import * as os from 'node:os';
3
import * as path from 'node:path';
4
import process from 'node:process';
5
-import { fileURLToPath, pathToFileURL } from 'node:url';
5
+import { pathToFileURL } from 'node:url';
6
import { Args, Command, Options } from '@effect/cli';
7
import { Effect, Option } from 'effect';
8
import { ts } from 'ts-morph';
@@ -11,6 +11,7 @@ import { warmToolInputDefinitions } from 'src/services/tool-input-validation';
11
import { ComposioUserContext } from 'src/services/user-context';
12
import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';
13
import { detectMaster, type MasterKind } from 'src/services/master-detector';
14
+import { resolveRunCompanionModulePath } from 'src/services/run-companion-modules';
15
import {
16
appendCliSessionHistory,
17
resolveCliSessionArtifacts,
@@ -160,46 +161,26 @@ export const inferCliInvocationPrefix = (
161
: [process.execPath];
162
};
163
163
-const resolveSiblingModulePath = (relativeNoExtensionFromRunCmd: string): string => {
164
- const currentFilePath = fileURLToPath(import.meta.url);
165
- const currentDirectory = path.dirname(currentFilePath);
166
-
167
- // Source (.ts) — running from `bun src/bin.ts`
168
- const tsPath = path.resolve(currentDirectory, `${relativeNoExtensionFromRunCmd}.ts`);
169
- if (fs.existsSync(tsPath)) {
170
- return tsPath;
171
- }
172
-
173
- // Built (.js) — running from `bun dist/bin.mjs`
174
- const jsPath = path.resolve(currentDirectory, `${relativeNoExtensionFromRunCmd}.js`);
175
- if (fs.existsSync(jsPath)) {
176
- return jsPath;
177
- }
178
-
179
- // Compiled binary — import.meta.url points to /$bunfs/, files live next to the executable
180
- const baseName = path.basename(relativeNoExtensionFromRunCmd);
181
- const exeDir = path.dirname(process.execPath);
182
- const mjsPath = path.resolve(exeDir, `${baseName}.mjs`);
183
- if (fs.existsSync(mjsPath)) {
184
- return mjsPath;
185
- }
186
- const exeJsPath = path.resolve(exeDir, `${baseName}.js`);
187
- if (fs.existsSync(exeJsPath)) {
188
- return exeJsPath;
189
- }
190
-
191
- // Fallback — return the .js path (will error at runtime with a clear module-not-found)
192
- return jsPath;
193
-};
194
-
164
const subAgentSharedModuleUrl = pathToFileURL(
196
- resolveSiblingModulePath('../services/run-subagent-shared')
165
+ resolveRunCompanionModulePath({
166
+ callerImportMetaUrl: import.meta.url,
167
+ execPath: process.execPath,
168
+ relativeNoExtensionFromCaller: '../services/run-subagent-shared',
169
+ })
170
).href;
171
const subAgentAcpModuleUrl = pathToFileURL(
199
- resolveSiblingModulePath('../services/run-subagent-acp')
172
+ resolveRunCompanionModulePath({
173
+ callerImportMetaUrl: import.meta.url,
174
+ execPath: process.execPath,
175
+ relativeNoExtensionFromCaller: '../services/run-subagent-acp',
176
+ })
177
).href;
178
const subAgentLegacyModuleUrl = pathToFileURL(
202
- resolveSiblingModulePath('../services/run-subagent-legacy')
179
+ resolveRunCompanionModulePath({
180
+ callerImportMetaUrl: import.meta.url,
181
+ execPath: process.execPath,
182
+ relativeNoExtensionFromCaller: '../services/run-subagent-legacy',
183
+ })
184
).href;
185
186
type RunHelperContext = {
ts/packages/cli/src/commands/whoami.cmd.ts
+1
-1
@@ -37,7 +37,7 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
37
);
38
yield* ui.log.step(
39
[
40
- commandHintStep('To switch orgs', 'dev.orgs.switch'),
40
+ commandHintStep('To switch orgs', 'root.orgs.switch'),
41
commandHintStep('To set up developer project context', 'dev.init'),
42
].join('\n\n')
43
);
ts/packages/cli/src/services/command-hints.ts
+9
-9
@@ -10,6 +10,7 @@ export type CommandHintId =
10
| 'root.execute'
11
| 'root.execute.getSchema'
12
| 'root.link'
13
+ | 'root.orgs.switch'
14
| 'dev.init'
15
| 'dev.playgroundExecute'
16
| 'dev.playgroundExecute.getSchema'
@@ -52,6 +53,10 @@ export const COMMAND_HINTS: Record<CommandHintId, CommandHintNode> = {
53
example: params => `composio link ${getParam(params, 'toolkit', '<toolkit>')}`,
54
links: ['root.execute'],
55
},
56
+ 'root.orgs.switch': {
57
+ example: () => 'composio orgs switch',
58
+ links: ['root.execute'],
59
+ },
60
'dev.init': {
61
example: () => 'composio dev init',
62
links: ['dev.playgroundExecute', 'dev.logs.tools', 'dev.logs.triggers'],
@@ -67,12 +72,10 @@ export const COMMAND_HINTS: Record<CommandHintId, CommandHintNode> = {
72
links: ['dev.playgroundExecute'],
73
},
74
'dev.logs.tools': {
70
- example: params =>
71
- `composio dev logs tools "${getParam(params, 'logId', '<log_id>')}"`,
75
+ example: params => `composio dev logs tools "${getParam(params, 'logId', '<log_id>')}"`,
76
},
77
'dev.logs.triggers': {
74
- example: params =>
75
- `composio dev logs triggers "${getParam(params, 'logId', '<log_id>')}"`,
78
+ example: params => `composio dev logs triggers "${getParam(params, 'logId', '<log_id>')}"`,
79
},
80
'dev.orgs.switch': {
81
example: () => 'composio dev orgs switch',
@@ -100,11 +103,8 @@ export const COMMAND_HINTS: Record<CommandHintId, CommandHintNode> = {
103
export const commandHintExample = (id: CommandHintId, params?: HintParams): string =>
104
COMMAND_HINTS[id].example(params);
105
103
-export const commandHintStep = (
104
- label: string,
105
- id: CommandHintId,
106
- params?: HintParams
107
-): string => `${label}:\n> ${commandHintExample(id, params)}`;
106
+export const commandHintStep = (label: string, id: CommandHintId, params?: HintParams): string =>
107
+ `${label}:\n> ${commandHintExample(id, params)}`;
108
109
export const commandHintLinks = (id: CommandHintId): ReadonlyArray<CommandHintId> =>
110
COMMAND_HINTS[id].links ?? [];
ts/packages/cli/src/services/run-companion-modules.ts
new
+49
@@ -0,0 +1,49 @@
1
+import * as fs from 'node:fs';
2
+import * as path from 'node:path';
3
+import { fileURLToPath } from 'node:url';
4
+
5
+export const RUN_COMPANION_MODULE_BASENAMES = [
6
+ 'run-subagent-shared',
7
+ 'run-subagent-acp',
8
+ 'run-subagent-legacy',
9
+] as const;
10
+
11
+export const RUN_COMPANION_MODULE_FILENAMES = RUN_COMPANION_MODULE_BASENAMES.map(
12
+ name => `${name}.mjs`
13
+);
14
+
15
+export const resolveRunCompanionModulePath = ({
16
+ callerImportMetaUrl,
17
+ execPath,
18
+ relativeNoExtensionFromCaller,
19
+}: {
20
+ callerImportMetaUrl: string;
21
+ execPath: string;
22
+ relativeNoExtensionFromCaller: string;
23
+}): string => {
24
+ const currentFilePath = fileURLToPath(callerImportMetaUrl);
25
+ const currentDirectory = path.dirname(currentFilePath);
26
+ const executableDirectory = path.dirname(execPath);
27
+ const baseName = path.basename(relativeNoExtensionFromCaller);
28
+
29
+ const candidates = [
30
+ path.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.ts`),
31
+ path.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.js`),
32
+ path.resolve(currentDirectory, 'services', `${baseName}.mjs`),
33
+ path.resolve(currentDirectory, 'services', `${baseName}.js`),
34
+ path.resolve(currentDirectory, `${baseName}.mjs`),
35
+ path.resolve(currentDirectory, `${baseName}.js`),
36
+ path.resolve(executableDirectory, `${baseName}.mjs`),
37
+ path.resolve(executableDirectory, `${baseName}.js`),
38
+ ];
39
+
40
+ for (const candidate of candidates) {
41
+ if (fs.existsSync(candidate)) {
42
+ return candidate;
43
+ }
44
+ }
45
+
46
+ return currentFilePath.startsWith('/$bunfs/')
47
+ ? path.resolve(executableDirectory, `${baseName}.mjs`)
48
+ : path.resolve(currentDirectory, `${baseName}.mjs`);
49
+};
ts/packages/cli/src/services/upgrade-binary.ts
+44
-5
@@ -12,6 +12,7 @@ import decompress from 'decompress';
12
import type { Predicate } from 'effect/Predicate';
13
import { renderPrettyError } from './utils/pretty-error';
14
import { TerminalUI } from './terminal-ui';
15
+import { RUN_COMPANION_MODULE_FILENAMES } from './run-companion-modules';
16
17
export class UpgradeBinaryError extends Data.TaggedError('services/UpgradeBinaryError')<{
18
readonly cause?: unknown;
@@ -345,11 +346,12 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg
346
const extractBinary = (
347
{ name, data }: { name: string; data: Uint8Array },
348
tempDir: string
348
- ): Effect.Effect<string, UpgradeBinaryError, never> =>
349
+ ): Effect.Effect<{ binaryPath: string; packageDir: string }, UpgradeBinaryError, never> =>
350
Effect.gen(function* () {
351
const zipPath = path.join(tempDir, name);
352
const extractDir = path.join(tempDir, 'extract');
352
- const binaryPath = path.join(extractDir, path.parse(name).name, CLI_BINARY_NAME);
353
+ const packageDir = path.join(extractDir, path.parse(name).name);
354
+ const binaryPath = path.join(packageDir, CLI_BINARY_NAME);
355
356
yield* Effect.logDebug(`Download zip to ${extractDir}`);
357
@@ -414,7 +416,10 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg
416
)
417
);
418
417
- return binaryPath;
419
+ return {
420
+ binaryPath,
421
+ packageDir,
422
+ };
423
});
424
425
/**
@@ -463,6 +468,40 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg
468
)
469
)
470
);
471
+
472
+ const sourceDirectory = path.dirname(sourcePath);
473
+ const targetDirectory = path.dirname(targetPath);
474
+
475
+ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
476
+ const sourceCompanion = path.join(sourceDirectory, fileName);
477
+ const sourceExists = yield* fs
478
+ .exists(sourceCompanion)
479
+ .pipe(Effect.catchAll(() => Effect.succeed(false)));
480
+
481
+ if (!sourceExists) {
482
+ return yield* Effect.fail(
483
+ new UpgradeBinaryError({
484
+ cause: new Error(`Missing companion module: ${sourceCompanion}`),
485
+ message: 'Downloaded binary package is incomplete',
486
+ })
487
+ );
488
+ }
489
+
490
+ yield* fs
491
+ .copy(sourceCompanion, path.join(targetDirectory, fileName), {
492
+ overwrite: true,
493
+ })
494
+ .pipe(
495
+ Effect.catchAll(error =>
496
+ Effect.fail(
497
+ new UpgradeBinaryError({
498
+ cause: error as Error,
499
+ message: `Failed to replace companion module: ${fileName}`,
500
+ })
501
+ )
502
+ )
503
+ );
504
+ }
505
});
506
507
/**
@@ -531,8 +570,8 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg
570
)
571
);
572
534
- const extractedBinaryPath = yield* extractBinary({ name, data }, tmpDir);
535
- yield* replaceBinary(extractedBinaryPath, currentPath);
573
+ const extractedBinary = yield* extractBinary({ name, data }, tmpDir);
574
+ yield* replaceBinary(extractedBinary.binaryPath, currentPath);
575
576
yield* spinner.stop('Upgrade completed!');
577
return release.tag_name;
ts/packages/cli/test/src/commands/run.cmd.test.ts
+37
@@ -1,6 +1,7 @@
1
import * as fs from 'node:fs';
2
import * as os from 'node:os';
3
import * as path from 'node:path';
4
+import { pathToFileURL } from 'node:url';
5
import { describe, expect, layer } from '@effect/vitest';
6
import { Effect } from 'effect';
7
import { afterEach, it, vi } from 'vitest';
@@ -10,6 +11,7 @@ import {
11
inferCliInvocationPrefix,
12
wrapInlineCodeForRun,
13
} from 'src/commands/run.cmd';
14
+import { resolveRunCompanionModulePath } from 'src/services/run-companion-modules';
15
import { buildStructuredPrompt, finalizeInvokeAgentText } from 'src/services/run-subagent-shared';
16
import { cli, MockConsole, TestLive } from 'test/__utils__';
17
@@ -311,6 +313,41 @@ describe('inferCliInvocationPrefix', () => {
313
});
314
});
315
316
+describe('resolveRunCompanionModulePath', () => {
317
+ it('[Given] a bundled dist chunk [Then] it resolves sibling companion modules in dist', () => {
318
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-companion-dist-'));
319
+ const callerPath = path.join(tempDir, 'commands-abc.mjs');
320
+ const servicesDir = path.join(tempDir, 'services');
321
+ const companionPath = path.join(servicesDir, 'run-subagent-shared.mjs');
322
+ fs.writeFileSync(callerPath, '', 'utf8');
323
+ fs.mkdirSync(servicesDir);
324
+ fs.writeFileSync(companionPath, '', 'utf8');
325
+
326
+ expect(
327
+ resolveRunCompanionModulePath({
328
+ callerImportMetaUrl: pathToFileURL(callerPath).href,
329
+ execPath: '/tmp/composio',
330
+ relativeNoExtensionFromCaller: '../services/run-subagent-shared',
331
+ })
332
+ ).toBe(companionPath);
333
+ });
334
+
335
+ it('[Given] a compiled bunfs caller [Then] it falls back to modules next to the binary', () => {
336
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-companion-bin-'));
337
+ const execPath = path.join(tempDir, 'composio');
338
+ const companionPath = path.join(tempDir, 'run-subagent-shared.mjs');
339
+ fs.writeFileSync(companionPath, '', 'utf8');
340
+
341
+ expect(
342
+ resolveRunCompanionModulePath({
343
+ callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
344
+ execPath,
345
+ relativeNoExtensionFromCaller: '../services/run-subagent-shared',
346
+ })
347
+ ).toBe(companionPath);
348
+ });
349
+});
350
+
351
describe('extractInlineExecuteToolSlugs', () => {
352
it('[Given] inline run source [Then] it finds static execute slugs from the AST', () => {
353
expect(
ts/packages/cli/tsdown.config.ts
+6
-4
@@ -3,12 +3,14 @@ import { baseConfig } from '../../../tsdown.config.base';
3
4
export default defineConfig({
5
...baseConfig,
6
- entry: ['src/bin.ts'],
6
+ entry: [
7
+ 'src/bin.ts',
8
+ 'src/services/run-subagent-shared.ts',
9
+ 'src/services/run-subagent-acp.ts',
10
+ 'src/services/run-subagent-legacy.ts',
11
+ ],
12
format: ['esm'],
13
tsconfig: './tsconfig.src.json',
9
- banner: {
10
- js: '#!/usr/bin/env bun',
11
- },
14
external: undefined,
15
publint: undefined,
16
attw: undefined,