Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(cli): replace repaired companions atomically
jkomynoa32712ffd97d
diff --git a/ts/packages/cli/src/services/run-companion-modules.ts b/ts/packages/cli/src/services/run-companion-modules.tsindex 7e8edebb0..3b570e76c 100644--- a/ts/packages/cli/src/services/run-companion-modules.ts+++ b/ts/packages/cli/src/services/run-companion-modules.ts@@ -10,6 +10,7 @@ import extractZip from 'extract-zip';import { IS_RELEASE_BUILD } from 'src/constants';import { GitHubRelease } from 'src/effects/resolve-cli-release';import { BaseConfigProviderLive, extendConfigProvider } from 'src/services/config';+import { atomicReplaceFile } from 'src/utils/atomic-replace';import { parseChecksumsText, sha256Hex } from 'src/utils/checksums';import { CLI_RELEASE_TAG_PREFIX } from 'src/utils/cli-release-version';@@ -628,7 +629,19 @@ export const repairMissingInstalledRunCompanionModules = ({const targetPath = path.join(installDirectory, relativePath);yield* fs.makeDirectory(path.dirname(targetPath), { recursive: true });- yield* fs.copyFile(sourcePath, targetPath);+ yield* atomicReplaceFile({ sourcePath, targetPath }).pipe(+ Effect.mapError(+ error =>+ new RunCompanionRepairError({+ message: [+ `Unable to restore the files required by 'composio run' for ${releaseTag}.`,+ error.message,+ `Reinstall the CLI, or set GITHUB_TAG to the exact release tag for this build and try again.`,+ ].join('\n'),+ cause: error.cause,+ })+ )+ );}yield* writeInstalledReleaseTag(installDirectory, release.tag_name);diff --git a/ts/packages/cli/test/src/services/run-companion-modules.test.ts b/ts/packages/cli/test/src/services/run-companion-modules.test.tsindex 4bf111c0c..2dce9ff34 100644--- a/ts/packages/cli/test/src/services/run-companion-modules.test.ts+++ b/ts/packages/cli/test/src/services/run-companion-modules.test.ts@@ -2,18 +2,138 @@ import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import { BunContext } from '@effect/platform-bun';-import { afterEach, describe, expect, layer, vi } from '@effect/vitest';+import { afterEach, describe, expect, layer } from '@effect/vitest';import { Effect } from 'effect';-import { repairMissingInstalledRunCompanionModules } from 'src/services/run-companion-modules';+import { vi } from 'vitest';+import {+ repairMissingInstalledRunCompanionModules,+ RUN_COMPANION_MODULE_FILENAMES,+ RUN_COMPANION_RELEASE_TAG_FILENAME,+ RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS,+} from 'src/services/run-companion-modules';import { BaseConfigProviderLive, extendConfigProvider } from 'src/services/config';+const extractZipMock = vi.hoisted(() => vi.fn());+vi.mock('extract-zip', () => ({ default: extractZipMock }));++const TEST_RELEASE_TAG = '@composio/[email protected]';+const TEST_BINARY_ASSET_NAMES = [+ 'composio-darwin-aarch64.zip',+ 'composio-darwin-x64.zip',+ 'composio-linux-aarch64.zip',+ 'composio-linux-x64.zip',+];+const TEST_COMPANION_RELATIVE_PATHS = [+ ...RUN_COMPANION_MODULE_FILENAMES,+ ...RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS,+].sort();++const stubRepairFetch = () => {+ const fetchMock = vi.fn((url: string) =>+ Promise.resolve(+ url.includes('/releases/tags/')+ ? new Response(+ JSON.stringify({+ tag_name: TEST_RELEASE_TAG,+ assets: TEST_BINARY_ASSET_NAMES.map(name => ({+ name,+ browser_download_url: `https://download.test/${name}`,+ })),+ }),+ { status: 200, headers: { 'content-type': 'application/json' } }+ )+ : new Response(new Uint8Array([1]), { status: 200 })+ )+ );+ vi.stubGlobal('fetch', fetchMock);+ vi.stubEnv('GITHUB_TAG', TEST_RELEASE_TAG);+ return fetchMock;+};++const mockArchiveContents = (missingRelativePath?: string) => {+ extractZipMock.mockImplementation(+ async (archivePath: string, options: { readonly dir: string }) => {+ const packageDirectory = path.join(options.dir, path.parse(archivePath).name);+ for (const relativePath of TEST_COMPANION_RELATIVE_PATHS) {+ if (relativePath === missingRelativePath) continue;+ const filePath = path.join(packageDirectory, relativePath);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, `new:${relativePath}`);+ }+ }+ );+};+describe('run-companion-modules', () => {afterEach(() => {+ extractZipMock.mockReset();vi.unstubAllGlobals();vi.unstubAllEnvs();});layer(BunContext.layer)(it => {+ it.effect('[Given] a complete archive [Then] repair atomically replaces companions', () => {+ const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-repair-test-'));+ const execPath = path.join(installDirectory, 'composio');+ const companionRelativePath = TEST_COMPANION_RELATIVE_PATHS[0]!;+ const companionPath = path.join(installDirectory, companionRelativePath);+ const releaseTagPath = path.join(installDirectory, RUN_COMPANION_RELEASE_TAG_FILENAME);+ fs.mkdirSync(path.dirname(companionPath), { recursive: true });+ fs.writeFileSync(companionPath, 'old-companion');+ fs.writeFileSync(releaseTagPath, '@composio/[email protected]\n');+ const originalCompanion = fs.statSync(companionPath);+ const fetchMock = stubRepairFetch();+ mockArchiveContents();++ return Effect.gen(function* () {+ const result = yield* repairMissingInstalledRunCompanionModules({+ callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',+ execPath,+ appVersion: '0.0.0-test',+ });++ expect(result).toEqual({ repaired: true, releaseTag: TEST_RELEASE_TAG });+ expect(fs.readFileSync(companionPath, 'utf8')).toBe(`new:${companionRelativePath}`);+ const replacedCompanion = fs.statSync(companionPath);+ expect(replacedCompanion.dev).toBe(originalCompanion.dev);+ expect(replacedCompanion.ino).not.toBe(originalCompanion.ino);+ expect(fs.readFileSync(releaseTagPath, 'utf8')).toBe(`${TEST_RELEASE_TAG}\n`);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ }).pipe(+ Effect.ensuring(+ Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))+ )+ );+ });++ it.effect('[Given] an incomplete archive [Then] repair preserves release metadata', () => {+ const installDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-repair-test-'));+ const execPath = path.join(installDirectory, 'composio');+ const releaseTagPath = path.join(installDirectory, RUN_COMPANION_RELEASE_TAG_FILENAME);+ const previousReleaseTag = '@composio/[email protected]\n';+ const missingRelativePath = TEST_COMPANION_RELATIVE_PATHS.at(-1)!;+ fs.writeFileSync(releaseTagPath, previousReleaseTag);+ stubRepairFetch();+ mockArchiveContents(missingRelativePath);++ return Effect.gen(function* () {+ const error = yield* repairMissingInstalledRunCompanionModules({+ callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',+ execPath,+ appVersion: '0.0.0-test',+ }).pipe(Effect.flip);++ expect(error.message).toContain(+ `missing ${missingRelativePath}; cannot restore the files required by 'composio run'`+ );+ expect(fs.readFileSync(releaseTagPath, 'utf8')).toBe(previousReleaseTag);+ }).pipe(+ Effect.ensuring(+ Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))+ )+ );+ });+it.effect('[Given] malformed release metadata [Then] repair rejects it before using release assets',() => {