@devries-cameron20 / composio-1 / commits / 2eee65d09
Fork 0

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

[codex] Repair missing run companion modules (#3042)

## Summary This changes `composio run` so an installed binary can recover missing `run-subagent-*.mjs` companion modules at runtime instead of failing immediately. ## What changed - add run-time companion repair in `composio run` - persist the installed release tag so `run` can fetch the matching release asset when repair is needed - update binary upgrade flow to keep that release metadata current - add CLI coverage for companion install metadata and missing companion detection - include a patch changeset for `@composio/cli` ## Root cause `composio run` launches a child Bun process that imports helper modules from disk. If the installed binary was missing the companion `.mjs` files, the command failed with `Cannot find module ... run-subagent-shared.mjs` before any user code ran. ## Impact - future CLI binaries with this change can self-heal missing companion modules during `composio run` - install and upgrade flows now record the release tag needed for deterministic repair - already-shipped older binaries still need one reinstall to get this repair logic ## Validation - `pnpm --filter @composio/cli test -- run.cmd.test.ts` - `pnpm --filter @composio/cli run build:binary` - verified a binary-only temp install containing just `composio` plus `release-tag.txt`; `composio run 'console.log("healed")'` restored the three companion modules and executed successfully

Rahul Tarak committed Mar 27, 2026 at 03:43 UTC 2eee65d09168aa2584c95271c4e6abf6a12b6f4d
6 files changed +392 -33
.changeset/cli-patch.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +"@composio/cli": patch
3 +---
4 +
5 +patch
install.sh
+4
@@ -169,6 +169,7 @@ companion_modules=(
169 "run-subagent-acp.mjs"
170 "run-subagent-legacy.mjs"
171 )
172 +release_tag_file="$COMPOSIO_INSTALL_DIR/release-tag.txt"
173
174 install_companion_modules() {
175 local source_dir="$1"
@@ -207,6 +208,9 @@ fi
208 chmod +x "$exe" ||
209 error 'Failed to set permissions on executable'
210
211 +printf '%s\n' "$version" > "$release_tag_file" ||
212 + error "Failed to write install metadata to \"$release_tag_file\""
213 +
214 success "Composio CLI was installed successfully to $Bold_Green$(tildify "$exe")"
215
216 # --- Shell integration (PATH + completions) ---
ts/packages/cli/src/commands/run.cmd.ts
+64 -29
@@ -6,12 +6,16 @@ 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';
9 +import { APP_VERSION } from 'src/constants';
10 import { resolveCommandProject } from 'src/services/command-project';
11 import { warmToolInputDefinitions } from 'src/services/tool-input-validation';
12 import { ComposioUserContext } from 'src/services/user-context';
13 import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';
14 import { detectMaster, type MasterKind } from 'src/services/master-detector';
14 -import { resolveRunCompanionModulePath } from 'src/services/run-companion-modules';
15 +import {
16 + repairMissingInstalledRunCompanionModules,
17 + resolveRunCompanionModulePath,
18 +} from 'src/services/run-companion-modules';
19 import {
20 appendCliSessionHistory,
21 resolveCliSessionArtifacts,
@@ -161,27 +165,35 @@ export const inferCliInvocationPrefix = (
165 : [process.execPath];
166 };
167
164 -const subAgentSharedModuleUrl = pathToFileURL(
165 - resolveRunCompanionModulePath({
166 - callerImportMetaUrl: import.meta.url,
167 - execPath: process.execPath,
168 - relativeNoExtensionFromCaller: '../services/run-subagent-shared',
169 - })
170 -).href;
171 -const subAgentAcpModuleUrl = pathToFileURL(
172 - resolveRunCompanionModulePath({
173 - callerImportMetaUrl: import.meta.url,
174 - execPath: process.execPath,
175 - relativeNoExtensionFromCaller: '../services/run-subagent-acp',
176 - })
177 -).href;
178 -const subAgentLegacyModuleUrl = pathToFileURL(
179 - resolveRunCompanionModulePath({
180 - callerImportMetaUrl: import.meta.url,
181 - execPath: process.execPath,
182 - relativeNoExtensionFromCaller: '../services/run-subagent-legacy',
183 - })
184 -).href;
168 +type RunHelperModuleUrls = {
169 + readonly subAgentSharedModuleUrl: string;
170 + readonly subAgentAcpModuleUrl: string;
171 + readonly subAgentLegacyModuleUrl: string;
172 +};
173 +
174 +const resolveRunHelperModuleUrls = (): RunHelperModuleUrls => ({
175 + subAgentSharedModuleUrl: pathToFileURL(
176 + resolveRunCompanionModulePath({
177 + callerImportMetaUrl: import.meta.url,
178 + execPath: process.execPath,
179 + relativeNoExtensionFromCaller: '../services/run-subagent-shared',
180 + })
181 + ).href,
182 + subAgentAcpModuleUrl: pathToFileURL(
183 + resolveRunCompanionModulePath({
184 + callerImportMetaUrl: import.meta.url,
185 + execPath: process.execPath,
186 + relativeNoExtensionFromCaller: '../services/run-subagent-acp',
187 + })
188 + ).href,
189 + subAgentLegacyModuleUrl: pathToFileURL(
190 + resolveRunCompanionModulePath({
191 + callerImportMetaUrl: import.meta.url,
192 + execPath: process.execPath,
193 + relativeNoExtensionFromCaller: '../services/run-subagent-legacy',
194 + })
195 + ).href,
196 +});
197
198 type RunHelperContext = {
199 readonly apiKey?: string;
@@ -791,13 +803,14 @@ const buildRunProxyHelpersSource = (): ReadonlyArray<string> => [
803
804 export const buildRunHelpersSource = (
805 cliPrefix: ReadonlyArray<string>,
794 - context: RunHelperContext = {}
806 + context: RunHelperContext = {},
807 + moduleUrls: RunHelperModuleUrls = resolveRunHelperModuleUrls()
808 ): string =>
809 [
810 'import { z } from "zod";',
798 - `import { isAcpInvokeError } from ${JSON.stringify(subAgentSharedModuleUrl)};`,
799 - `import { invokeAcpSubAgent } from ${JSON.stringify(subAgentAcpModuleUrl)};`,
800 - `import { invokeLegacySubAgent } from ${JSON.stringify(subAgentLegacyModuleUrl)};`,
811 + `import { isAcpInvokeError } from ${JSON.stringify(moduleUrls.subAgentSharedModuleUrl)};`,
812 + `import { invokeAcpSubAgent } from ${JSON.stringify(moduleUrls.subAgentAcpModuleUrl)};`,
813 + `import { invokeLegacySubAgent } from ${JSON.stringify(moduleUrls.subAgentLegacyModuleUrl)};`,
814 '',
815 `const cliPrefix = ${JSON.stringify(cliPrefix)};`,
816 `const helperContext = ${JSON.stringify(context)};`,
@@ -809,7 +822,8 @@ export const buildRunHelpersSource = (
822
823 const createRunHelpersPreloadFile = (
824 cliPrefix: ReadonlyArray<string>,
812 - context: RunHelperContext
825 + context: RunHelperContext,
826 + moduleUrls: RunHelperModuleUrls
827 ) => {
828 const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-'));
829 const preloadPath = path.join(directory, 'globals.mjs');
@@ -820,7 +834,7 @@ const createRunHelpersPreloadFile = (
834 fs.mkdirSync(runOutputDir, { recursive: true });
835 fs.writeFileSync(
836 preloadPath,
823 - buildRunHelpersSource(cliPrefix, { ...context, runOutputDir }),
837 + buildRunHelpersSource(cliPrefix, { ...context, runOutputDir }, moduleUrls),
838 'utf8'
839 );
840 return { directory, preloadPath, runOutputDir };
@@ -1019,7 +1033,28 @@ export const runCmd = Command.make('run', {
1033 skipToolParamsCheck,
1034 skipChecks,
1035 };
1022 - const preload = createRunHelpersPreloadFile(inferCliInvocationPrefix(), helperContext);
1036 + const runHelperModuleUrls = yield* Effect.tryPromise({
1037 + try: async () => {
1038 + await repairMissingInstalledRunCompanionModules({
1039 + callerImportMetaUrl: import.meta.url,
1040 + execPath: process.execPath,
1041 + appVersion: APP_VERSION,
1042 + });
1043 +
1044 + return resolveRunHelperModuleUrls();
1045 + },
1046 + catch: error =>
1047 + new Error(
1048 + error instanceof Error
1049 + ? error.message
1050 + : `Failed to prepare the modules required by 'composio run': ${String(error)}`
1051 + ),
1052 + });
1053 + const preload = createRunHelpersPreloadFile(
1054 + inferCliInvocationPrefix(),
1055 + helperContext,
1056 + runHelperModuleUrls
1057 + );
1058 let cleanupPaths: ReadonlyArray<string> = [];
1059 try {
1060 yield* appendCliSessionHistory({
ts/packages/cli/src/services/run-companion-modules.ts
+272
@@ -1,6 +1,8 @@
1 import * as fs from 'node:fs';
2 +import * as os from 'node:os';
3 import * as path from 'node:path';
4 import { fileURLToPath } from 'node:url';
5 +import decompress from 'decompress';
6
7 export const RUN_COMPANION_MODULE_BASENAMES = [
8 'run-subagent-shared',
@@ -12,6 +14,276 @@ export const RUN_COMPANION_MODULE_FILENAMES = RUN_COMPANION_MODULE_BASENAMES.map
14 name => `${name}.mjs`
15 );
16
17 +export const RUN_COMPANION_RELEASE_TAG_FILENAME = 'release-tag.txt';
18 +
19 +type GitHubReleaseAsset = {
20 + name: string;
21 + browser_download_url: string;
22 +};
23 +
24 +type GitHubRelease = {
25 + tag_name: string;
26 + assets: GitHubReleaseAsset[];
27 +};
28 +
29 +const DEFAULT_GITHUB_CONFIG = {
30 + apiBaseUrl: 'https://api.github.com',
31 + owner: 'ComposioHQ',
32 + repo: 'composio',
33 +} as const;
34 +
35 +const resolveCompanionInstallDirectory = (execPath: string) => path.dirname(execPath);
36 +
37 +const resolveBinaryAssetName = ({
38 + platform = process.platform,
39 + arch = process.arch,
40 +}: {
41 + platform?: NodeJS.Platform;
42 + arch?: string;
43 +}) => {
44 + switch (`${platform}-${arch}`) {
45 + case 'darwin-arm64':
46 + return 'composio-darwin-aarch64.zip';
47 + case 'darwin-x64':
48 + return 'composio-darwin-x64.zip';
49 + case 'linux-x64':
50 + return 'composio-linux-x64.zip';
51 + case 'linux-arm64':
52 + return 'composio-linux-aarch64.zip';
53 + default:
54 + throw new Error(`Unsupported platform for run companion repair: ${platform}-${arch}`);
55 + }
56 +};
57 +
58 +const readTextFileIfPresent = (filePath: string) => {
59 + if (!fs.existsSync(filePath)) {
60 + return undefined;
61 + }
62 +
63 + const value = fs.readFileSync(filePath, 'utf8').trim();
64 + return value.length > 0 ? value : undefined;
65 +};
66 +
67 +export const readInstalledReleaseTag = (execPath: string) =>
68 + readTextFileIfPresent(
69 + path.join(resolveCompanionInstallDirectory(execPath), RUN_COMPANION_RELEASE_TAG_FILENAME)
70 + );
71 +
72 +export const writeInstalledReleaseTag = (installDir: string, releaseTag: string) => {
73 + fs.writeFileSync(
74 + path.join(installDir, RUN_COMPANION_RELEASE_TAG_FILENAME),
75 + `${releaseTag}\n`,
76 + 'utf8'
77 + );
78 +};
79 +
80 +export const listMissingInstalledRunCompanionModules = (execPath: string) => {
81 + const installDirectory = resolveCompanionInstallDirectory(execPath);
82 + return RUN_COMPANION_MODULE_FILENAMES.filter(
83 + fileName => !fs.existsSync(path.join(installDirectory, fileName))
84 + );
85 +};
86 +
87 +const fetchGitHubJson = async <T>({
88 + url,
89 + accessToken,
90 + fetchErrorMessage,
91 +}: {
92 + url: string;
93 + accessToken?: string;
94 + fetchErrorMessage: string;
95 +}): Promise<T> => {
96 + const response = await fetch(url, {
97 + headers: {
98 + Accept: 'application/vnd.github+json',
99 + 'User-Agent': 'composio-cli-run-repair',
100 + ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
101 + },
102 + });
103 +
104 + if (!response.ok) {
105 + const body = await response.text().catch(() => '');
106 + throw new Error(`${fetchErrorMessage} (HTTP ${response.status}${body ? `: ${body}` : ''})`);
107 + }
108 +
109 + return (await response.json()) as T;
110 +};
111 +
112 +const fetchChecksums = async ({
113 + release,
114 + accessToken,
115 +}: {
116 + release: GitHubRelease;
117 + accessToken?: string;
118 +}) => {
119 + const checksumsAsset = release.assets.find(asset => asset.name === 'checksums.txt');
120 + if (!checksumsAsset) {
121 + return undefined;
122 + }
123 +
124 + const response = await fetch(checksumsAsset.browser_download_url, {
125 + headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined,
126 + });
127 +
128 + if (!response.ok) {
129 + return undefined;
130 + }
131 +
132 + const text = await response.text();
133 + const checksums = new Map<string, string>();
134 + for (const line of text.split('\n')) {
135 + const trimmed = line.trim();
136 + if (!trimmed) {
137 + continue;
138 + }
139 +
140 + const parts = trimmed.split(/\s+/);
141 + if (parts.length >= 2) {
142 + checksums.set(parts[1]!, parts[0]!);
143 + }
144 + }
145 +
146 + return checksums;
147 +};
148 +
149 +const verifyChecksum = async ({
150 + data,
151 + expectedHash,
152 + fileName,
153 +}: {
154 + data: Uint8Array;
155 + expectedHash: string;
156 + fileName: string;
157 +}) => {
158 + const digest = await crypto.subtle.digest('SHA-256', data.slice().buffer);
159 + const actualHash = Array.from(new Uint8Array(digest))
160 + .map(byte => byte.toString(16).padStart(2, '0'))
161 + .join('');
162 +
163 + if (actualHash !== expectedHash) {
164 + throw new Error(
165 + `Checksum mismatch while repairing ${fileName}\n Expected: ${expectedHash}\n Actual: ${actualHash}`
166 + );
167 + }
168 +};
169 +
170 +const resolveRepairReleaseTag = ({
171 + execPath,
172 + appVersion,
173 +}: {
174 + execPath: string;
175 + appVersion: string;
176 +}) =>
177 + process.env.GITHUB_TAG?.trim() ||
178 + readInstalledReleaseTag(execPath) ||
179 + `@composio/cli@${appVersion}`;
180 +
181 +export const repairMissingInstalledRunCompanionModules = async ({
182 + callerImportMetaUrl,
183 + execPath,
184 + appVersion,
185 +}: {
186 + callerImportMetaUrl: string;
187 + execPath: string;
188 + appVersion: string;
189 +}) => {
190 + const currentFilePath = fileURLToPath(callerImportMetaUrl);
191 + if (!currentFilePath.startsWith('/$bunfs/')) {
192 + return { repaired: false as const };
193 + }
194 +
195 + const missingModules = listMissingInstalledRunCompanionModules(execPath);
196 + if (missingModules.length === 0) {
197 + return { repaired: false as const };
198 + }
199 +
200 + const releaseTag = resolveRepairReleaseTag({ execPath, appVersion });
201 + const githubConfig = {
202 + apiBaseUrl: process.env.GITHUB_API_BASE_URL || DEFAULT_GITHUB_CONFIG.apiBaseUrl,
203 + owner: process.env.GITHUB_OWNER || DEFAULT_GITHUB_CONFIG.owner,
204 + repo: process.env.GITHUB_REPO || DEFAULT_GITHUB_CONFIG.repo,
205 + accessToken: process.env.GITHUB_ACCESS_TOKEN,
206 + };
207 +
208 + const encodedTag = encodeURIComponent(releaseTag);
209 + const release = await fetchGitHubJson<GitHubRelease>({
210 + url: `${githubConfig.apiBaseUrl}/repos/${githubConfig.owner}/${githubConfig.repo}/releases/tags/${encodedTag}`,
211 + accessToken: githubConfig.accessToken,
212 + fetchErrorMessage: `Failed to fetch release metadata for ${releaseTag} while repairing run companion modules`,
213 + }).catch(error => {
214 + throw new Error(
215 + [
216 + `Unable to restore the files required by 'composio run' for ${releaseTag}.`,
217 + error instanceof Error ? error.message : String(error),
218 + `Reinstall the CLI, or set GITHUB_TAG to the exact release tag for this build and try again.`,
219 + ].join('\n')
220 + );
221 + });
222 +
223 + const assetName = resolveBinaryAssetName({});
224 + const asset = release.assets.find(candidate => candidate.name === assetName);
225 + if (!asset) {
226 + throw new Error(
227 + `Release ${release.tag_name} does not contain ${assetName}; cannot restore run companion modules.`
228 + );
229 + }
230 +
231 + const archiveResponse = await fetch(asset.browser_download_url, {
232 + headers: githubConfig.accessToken
233 + ? { Authorization: `Bearer ${githubConfig.accessToken}` }
234 + : undefined,
235 + });
236 + if (!archiveResponse.ok) {
237 + throw new Error(
238 + `Failed to download ${asset.name} from ${release.tag_name} while repairing run companion modules (HTTP ${archiveResponse.status}).`
239 + );
240 + }
241 +
242 + const archiveData = new Uint8Array(await archiveResponse.arrayBuffer());
243 + const checksums = await fetchChecksums({
244 + release,
245 + accessToken: githubConfig.accessToken,
246 + });
247 + const expectedChecksum = checksums?.get(asset.name);
248 + if (expectedChecksum) {
249 + await verifyChecksum({
250 + data: archiveData,
251 + expectedHash: expectedChecksum,
252 + fileName: asset.name,
253 + });
254 + }
255 +
256 + const tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-repair-'));
257 + try {
258 + const archivePath = path.join(tempDirectory, asset.name);
259 + const extractDirectory = path.join(tempDirectory, 'extract');
260 + const packageDirectory = path.join(extractDirectory, path.parse(asset.name).name);
261 + fs.writeFileSync(archivePath, archiveData);
262 + fs.mkdirSync(extractDirectory, { recursive: true });
263 + await decompress(archivePath, extractDirectory);
264 +
265 + const installDirectory = resolveCompanionInstallDirectory(execPath);
266 + for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
267 + const sourcePath = path.join(packageDirectory, fileName);
268 + if (!fs.existsSync(sourcePath)) {
269 + throw new Error(
270 + `Release ${release.tag_name} is missing ${fileName}; cannot restore the files required by 'composio run'.`
271 + );
272 + }
273 +
274 + fs.copyFileSync(sourcePath, path.join(installDirectory, fileName));
275 + }
276 +
277 + writeInstalledReleaseTag(installDirectory, release.tag_name);
278 + return {
279 + repaired: true as const,
280 + releaseTag: release.tag_name,
281 + };
282 + } finally {
283 + fs.rmSync(tempDirectory, { recursive: true, force: true });
284 + }
285 +};
286 +
287 export const resolveRunCompanionModulePath = ({
288 callerImportMetaUrl,
289 execPath,
ts/packages/cli/src/services/upgrade-binary.ts
+19 -3
@@ -12,7 +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';
15 +import { RUN_COMPANION_MODULE_FILENAMES, writeInstalledReleaseTag } from './run-companion-modules';
16
17 export class UpgradeBinaryError extends Data.TaggedError('services/UpgradeBinaryError')<{
18 readonly cause?: unknown;
@@ -449,7 +449,10 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg
449 */
450 const replaceBinary = (
451 sourcePath: string,
452 - targetPath: string
452 + targetPath: string,
453 + options: {
454 + releaseTag?: string;
455 + } = {}
456 ): Effect.Effect<void, UpgradeBinaryError> =>
457 Effect.gen(function* () {
458 yield* Effect.logDebug(`Replacing binary: ${sourcePath} -> ${targetPath}`);
@@ -502,6 +505,17 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg
505 )
506 );
507 }
508 +
509 + if (options.releaseTag) {
510 + yield* Effect.try({
511 + try: () => writeInstalledReleaseTag(targetDirectory, options.releaseTag!),
512 + catch: error =>
513 + new UpgradeBinaryError({
514 + cause: error as Error,
515 + message: 'Failed to update installed release metadata',
516 + }),
517 + });
518 + }
519 });
520
521 /**
@@ -571,7 +585,9 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg
585 );
586
587 const extractedBinary = yield* extractBinary({ name, data }, tmpDir);
574 - yield* replaceBinary(extractedBinary.binaryPath, currentPath);
588 + yield* replaceBinary(extractedBinary.binaryPath, currentPath, {
589 + releaseTag: release.tag_name,
590 + });
591
592 yield* spinner.stop('Upgrade completed!');
593 return release.tag_name;
ts/packages/cli/test/src/commands/run.cmd.test.ts
+28 -1
@@ -11,7 +11,13 @@ import {
11 inferCliInvocationPrefix,
12 wrapInlineCodeForRun,
13 } from 'src/commands/run.cmd';
14 -import { resolveRunCompanionModulePath } from 'src/services/run-companion-modules';
14 +import {
15 + RUN_COMPANION_MODULE_FILENAMES,
16 + listMissingInstalledRunCompanionModules,
17 + readInstalledReleaseTag,
18 + resolveRunCompanionModulePath,
19 + writeInstalledReleaseTag,
20 +} from 'src/services/run-companion-modules';
21 import { buildStructuredPrompt, finalizeInvokeAgentText } from 'src/services/run-subagent-shared';
22 import { cli, MockConsole, TestLive } from 'test/__utils__';
23
@@ -348,6 +354,27 @@ describe('resolveRunCompanionModulePath', () => {
354 });
355 });
356
357 +describe('run companion install metadata', () => {
358 + it('[Given] an installed release tag file [Then] run helpers can read it back from the install dir', () => {
359 + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-release-tag-'));
360 + const execPath = path.join(tempDir, 'composio');
361 +
362 + writeInstalledReleaseTag(tempDir, '@composio/cli@0.2.12');
363 +
364 + expect(readInstalledReleaseTag(execPath)).toBe('@composio/cli@0.2.12');
365 + });
366 +
367 + it('[Given] a partial companion install [Then] it reports only the missing companion files', () => {
368 + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-'));
369 + const execPath = path.join(tempDir, 'composio');
370 + fs.writeFileSync(path.join(tempDir, RUN_COMPANION_MODULE_FILENAMES[0]!), '', 'utf8');
371 +
372 + expect(listMissingInstalledRunCompanionModules(execPath)).toEqual(
373 + RUN_COMPANION_MODULE_FILENAMES.slice(1)
374 + );
375 + });
376 +});
377 +
378 describe('extractInlineExecuteToolSlugs', () => {
379 it('[Given] inline run source [Then] it finds static execute slugs from the AST', () => {
380 expect(