@devries-cameron20 / composio-1 / commits / 73f710b5c
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.

fix(cli): repair a companion's own files before importing it

Bun keeps a failed or already-loaded import in its module registry, so importing a companion again after a repair can still see the missing dependency or the old module. Repair now runs before the single import, and only when the requested companion's wrapper or its import graph is missing, so unrelated missing companions still cannot block it. Claude-Session: https://claude.ai/code/session_01MTb47vexN35pLGsSZwBmrJ

jkomyno committed Sep 14, 2026 at 19:59 UTC 73f710b5cf43219b9528a017a0ae7bd41e2d4ba3
2 files changed +142 -46
ts/packages/cli/src/services/run-companion-modules.ts
+76 -46
@@ -475,6 +475,32 @@ export const listMissingInstalledRunCompanionModules = (
475 );
476 });
477
478 +/**
479 + * The files one companion needs next to the executable: its wrapper and every
480 + * relative import reachable from it, listed when missing.
481 + */
482 +const listMissingInstalledCompanionModuleFiles = (
483 + execPath: string,
484 + baseName: string
485 +): Effect.Effect<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> =>
486 + Effect.gen(function* () {
487 + const fs = yield* FileSystem.FileSystem;
488 + const path = yield* Path.Path;
489 + const installDirectory = path.dirname(execPath);
490 + const collected = new Set<string>();
491 + yield* collectRelativeImportPaths({
492 + fs,
493 + path,
494 + rootDir: installDirectory,
495 + relativePath: `${baseName}.mjs`,
496 + collected,
497 + recordMissingPaths: true,
498 + });
499 + return yield* Effect.filter([...collected], relativePath =>
500 + Effect.map(fileExists(fs, path.join(installDirectory, relativePath)), exists => !exists)
501 + );
502 + });
503 +
504 /**
505 * Whether the companion wrappers sit next to the executable, which is how
506 * packaged installs ship them.
@@ -646,10 +672,16 @@ export const repairMissingInstalledRunCompanionModules = ({
672 callerImportMetaUrl,
673 execPath,
674 appVersion,
675 + companionBaseName,
676 }: {
677 callerImportMetaUrl: string;
678 execPath: string;
679 appVersion: string;
680 + /**
681 + * Repair only when this companion's own files are missing, rather than when
682 + * any startup-tier file is. The repair still restores the full set.
683 + */
684 + companionBaseName?: string;
685 }): Effect.Effect<
686 { readonly repaired: false } | { readonly repaired: true; readonly releaseTag: string },
687 RunCompanionRepairError | PlatformError.PlatformError,
@@ -664,7 +696,10 @@ export const repairMissingInstalledRunCompanionModules = ({
696 return { repaired: false as const };
697 }
698
667 - const missingModules = yield* listMissingInstalledRunCompanionModules(execPath);
699 + const missingModules =
700 + companionBaseName === undefined
701 + ? yield* listMissingInstalledRunCompanionModules(execPath)
702 + : yield* listMissingInstalledCompanionModuleFiles(execPath, companionBaseName);
703 if (missingModules.length === 0) {
704 return { repaired: false as const };
705 }
@@ -847,13 +882,15 @@ export const resolveRunCompanionModulePath = ({
882 * this file when running from a checkout (tests, `bun run src/bin.ts`), the
883 * `.mjs` bundle next to the executable in a packaged install.
884 *
850 - * The module is imported before anything else is checked, so a companion that
851 - * loads is used even when an unrelated one is missing and the repair download
852 - * would fail offline. Only a module that fails to load, or that lacks one of
853 - * `requiredExports` (a file left behind by a different release), sends a
854 - * packaged install through the release-archive repair `composio run` uses. If
855 - * that repair restored missing files the module is imported once more;
856 - * otherwise the load error stands.
885 + * A packaged install missing this module's own files goes through the
886 + * release-archive repair `composio run` uses before the import. Files of other
887 + * companions do not trigger it, so an offline repair failure cannot block a
888 + * module that is already in place. The repair has to come first: Bun keeps a
889 + * failed or already-loaded import in its module registry, so importing again
890 + * after a repair can still see the old result.
891 + *
892 + * A module that loads but lacks one of `requiredExports` is a file left behind
893 + * by a different release; it fails with a typed error asking for a reinstall.
894 *
895 * The specifier is computed at runtime on purpose: a literal `import('./x')`
896 * would make the bundler fold the module back into the executable, which is the
@@ -875,45 +912,38 @@ export const loadInstalledCompanionModule = <M>(
912 const callerImportMetaUrl = import.meta.url;
913 const execPath = process.execPath;
914
878 - const importModule = Effect.gen(function* () {
879 - const modulePath = yield* resolveRunCompanionModulePath({
880 - callerImportMetaUrl,
881 - execPath,
882 - relativeNoExtensionFromCaller: `./${baseName}`,
883 - });
884 - const fileName = path.basename(modulePath);
885 - const moduleUrl = yield* Effect.orDie(path.toFileUrl(modulePath));
886 -
887 - // A rejected import means the file resolved above is missing or unloadable:
888 - // a broken install. It stays a typed failure so callers can report it, or
889 - // fall back, instead of crashing with a stack trace.
890 - const exports = yield* Effect.tryPromise({
891 - try: () => import(moduleUrl.href) as Promise<Record<string, unknown>>,
892 - catch: cause =>
893 - new RunCompanionRepairError({
894 - message: `Unable to load the CLI's bundled support file ${fileName}. Reinstall the CLI and try again.`,
895 - cause,
896 - }),
897 - });
915 + yield* repairMissingInstalledRunCompanionModules({
916 + callerImportMetaUrl,
917 + execPath,
918 + appVersion: APP_VERSION,
919 + companionBaseName: baseName,
920 + });
921
899 - const missingExports = requiredExports.filter(name => !(name in exports));
900 - if (missingExports.length > 0) {
901 - return yield* new RunCompanionRepairError({
902 - message: `The CLI's bundled support file ${fileName} does not match this CLI (missing ${missingExports.join(', ')}). Reinstall the CLI and try again.`,
903 - });
904 - }
905 - return exports as M;
922 + const modulePath = yield* resolveRunCompanionModulePath({
923 + callerImportMetaUrl,
924 + execPath,
925 + relativeNoExtensionFromCaller: `./${baseName}`,
926 + });
927 + const fileName = path.basename(modulePath);
928 + const moduleUrl = yield* Effect.orDie(path.toFileUrl(modulePath));
929 +
930 + // A rejected import means the file resolved above is missing or unloadable:
931 + // a broken install. It stays a typed failure so callers can report it, or
932 + // fall back, instead of crashing with a stack trace.
933 + const exports = yield* Effect.tryPromise({
934 + try: () => import(moduleUrl.href) as Promise<Record<string, unknown>>,
935 + catch: cause =>
936 + new RunCompanionRepairError({
937 + message: `Unable to load the CLI's bundled support file ${fileName}. Reinstall the CLI and try again.`,
938 + cause,
939 + }),
940 });
941
908 - return yield* importModule.pipe(
909 - Effect.catchTag('services/RunCompanionRepairError', loadError =>
910 - repairMissingInstalledRunCompanionModules({
911 - callerImportMetaUrl,
912 - execPath,
913 - appVersion: APP_VERSION,
914 - }).pipe(
915 - Effect.flatMap(({ repaired }) => (repaired ? importModule : Effect.fail(loadError)))
916 - )
917 - )
918 - );
942 + const missingExports = requiredExports.filter(name => !(name in exports));
943 + if (missingExports.length > 0) {
944 + return yield* new RunCompanionRepairError({
945 + message: `The CLI's bundled support file ${fileName} does not match this CLI (missing ${missingExports.join(', ')}). Reinstall the CLI and try again.`,
946 + });
947 + }
948 + return exports as M;
949 });
ts/packages/cli/test/src/services/run-companion-modules.test.ts
+66
@@ -200,6 +200,72 @@ describe('run-companion-modules', () => {
200 }
201 );
202
203 + it.effect(
204 + '[Given] only an unrelated companion is missing [Then] a scoped repair does nothing',
205 + () => {
206 + const installDirectory = fs.mkdtempSync(
207 + path.join(os.tmpdir(), 'composio-run-scoped-repair-')
208 + );
209 + const execPath = path.join(installDirectory, 'composio');
210 + fs.mkdirSync(path.join(installDirectory, 'services'));
211 + fs.writeFileSync(
212 + path.join(installDirectory, 'generation-runtime.mjs'),
213 + 'export * from "./services/generation-runtime.mjs";\n'
214 + );
215 + fs.writeFileSync(path.join(installDirectory, 'services', 'generation-runtime.mjs'), '');
216 + const fetchMock = stubRepairFetch();
217 +
218 + return Effect.gen(function* () {
219 + expect(yield* listMissingInstalledRunCompanionModules(execPath)).not.toEqual([]);
220 + expect(
221 + yield* repairMissingInstalledRunCompanionModules({
222 + callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
223 + execPath,
224 + appVersion: '0.0.0-test',
225 + companionBaseName: 'generation-runtime',
226 + })
227 + ).toEqual({ repaired: false });
228 + expect(fetchMock).not.toHaveBeenCalled();
229 + }).pipe(
230 + Effect.ensuring(
231 + Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
232 + )
233 + );
234 + }
235 + );
236 +
237 + it.effect(
238 + '[Given] a companion wrapper whose bundle is missing [Then] a scoped repair restores it',
239 + () => {
240 + const installDirectory = fs.mkdtempSync(
241 + path.join(os.tmpdir(), 'composio-run-scoped-repair-')
242 + );
243 + const execPath = path.join(installDirectory, 'composio');
244 + fs.writeFileSync(
245 + path.join(installDirectory, 'generation-runtime.mjs'),
246 + 'export * from "./services/generation-runtime.mjs";\n'
247 + );
248 + stubRepairFetch();
249 + mockArchiveContents();
250 +
251 + return Effect.gen(function* () {
252 + const result = yield* repairMissingInstalledRunCompanionModules({
253 + callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
254 + execPath,
255 + appVersion: '0.0.0-test',
256 + companionBaseName: 'generation-runtime',
257 + });
258 +
259 + expect(result).toEqual({ repaired: true, releaseTag: TEST_RELEASE_TAG });
260 + expect(fs.existsSync(path.join(installDirectory, 'generation-runtime.mjs'))).toBe(true);
261 + }).pipe(
262 + Effect.ensuring(
263 + Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
264 + )
265 + );
266 + }
267 + );
268 +
269 it.effect('[Given] a complete archive [Then] repair atomically replaces companions', () => {
270 const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-repair-test-'));
271 const execPath = path.join(installDirectory, 'composio');