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.

fix(cli): replace upgraded binaries atomically

jkomyno96b199c3268e
diff --git a/ts/packages/cli/src/services/upgrade-binary.ts b/ts/packages/cli/src/services/upgrade-binary.ts
index 885537522..8645628da 100644
--- a/ts/packages/cli/src/services/upgrade-binary.ts
+++ b/ts/packages/cli/src/services/upgrade-binary.ts
@@ -1,4 +1,13 @@
-import { Data, Effect, Config, Match, Option, Predicate, Record as EffectRecord } from 'effect';
+import {
+ Data,
+ Effect,
+ Config,
+ Match,
+ Option,
+ Predicate,
+ Record as EffectRecord,
+ Scope,
+} from 'effect';
import { HttpClient, HttpClientResponse, FileSystem, Path } from '@effect/platform';
import { APP_VERSION } from '../constants';
import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
@@ -7,6 +16,11 @@ import { detectPlatform, type PlatformArch } from 'src/effects/detect-platform';
import { CompareSemverError, semverComparator } from 'src/effects/compare-semver';
import { fetchLatestCliRelease, GitHubRelease } from 'src/effects/resolve-cli-release';
import { parseChecksumsText, sha256Hex } from 'src/utils/checksums';
+import {
+ atomicReplaceDirectory,
+ atomicReplaceFile,
+ type AtomicReplaceError,
+} from 'src/utils/atomic-replace';
// Note: `node:zlib` does not support Github's zip files
import extractZip from 'extract-zip';
@@ -14,6 +28,7 @@ import { renderPrettyError } from './utils/pretty-error';
import { TerminalUI } from './terminal-ui';
import {
collectExpectedRunCompanionAssetRelativePaths,
+ RUN_COMPANION_RELEASE_TAG_FILENAME,
resolveRunningCliReleaseTag,
writeInstalledReleaseTag,
} from './run-companion-modules';
@@ -160,9 +175,9 @@ const fetchLatestRelease = (
return release;
});
-const provideFsAndPath = <A, E>(
- { fs, path }: UpgradeBinaryContext,
- effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>
+const provideFsAndPath = <A, E, R>(
+ { fs, path }: Pick<UpgradeBinaryContext, 'fs' | 'path'>,
+ effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path | R>
) =>
effect.pipe(
Effect.provideService(FileSystem.FileSystem, fs),
@@ -414,31 +429,23 @@ const getCurrentExecutablePath = Effect.fn(function* () {
/**
* Replace current executable binary with the new target one.
*/
+const mapAtomicReplaceError = (message: string) => (error: AtomicReplaceError) =>
+ new UpgradeBinaryError({
+ cause: error.cause,
+ message,
+ });
+
const replaceBinary = (
- ctx: UpgradeBinaryContext,
+ ctx: Pick<UpgradeBinaryContext, 'fs' | 'path'>,
sourcePath: string,
targetPath: string,
options: {
releaseTag?: string;
} = {}
-): Effect.Effect<void, UpgradeBinaryError> =>
+): Effect.Effect<void, UpgradeBinaryError, Scope.Scope> =>
Effect.gen(function* () {
const { fs, path } = ctx;
yield* Effect.logDebug(`Replacing binary: ${sourcePath} -> ${targetPath}`);
- yield* fs
- .copy(sourcePath, targetPath, {
- // Note: without `overwrite: true`, the copy operation will silently bail out
- overwrite: true,
- })
- .pipe(
- Effect.mapError(
- cause =>
- new UpgradeBinaryError({
- cause,
- message: 'Failed to replace binary',
- })
- )
- );
const sourceDirectory = path.dirname(sourcePath);
const targetDirectory = path.dirname(targetPath);
@@ -446,6 +453,12 @@ const replaceBinary = (
ctx,
collectExpectedRunCompanionAssetRelativePaths(sourceDirectory)
);
+ const companionReplacements: Array<{
+ readonly relativePath: string;
+ readonly sourcePath: string;
+ readonly targetPath: string;
+ }> = [];
+
for (const relativePath of companionRelativePaths) {
const sourceCompanion = path.join(sourceDirectory, relativePath);
const sourceExists = yield* fs
@@ -461,64 +474,82 @@ const replaceBinary = (
);
}
- const targetCompanion = path.join(targetDirectory, relativePath);
- yield* fs.makeDirectory(path.dirname(targetCompanion), { recursive: true }).pipe(
- Effect.mapError(
- cause =>
- new UpgradeBinaryError({
- cause,
- message: `Failed to create companion module directory: ${relativePath}`,
- })
- )
- );
-
- yield* fs
- .copy(sourceCompanion, targetCompanion, {
- overwrite: true,
- })
- .pipe(
- Effect.mapError(
- cause =>
- new UpgradeBinaryError({
- cause,
- message: `Failed to replace companion module: ${relativePath}`,
- })
- )
- );
+ companionReplacements.push({
+ relativePath,
+ sourcePath: sourceCompanion,
+ targetPath: path.join(targetDirectory, relativePath),
+ });
}
const localToolsAssetSource = path.join(sourceDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
const localToolsAssetExists = yield* fs
.exists(localToolsAssetSource)
.pipe(Effect.catchAll(() => Effect.succeed(false)));
- if (localToolsAssetExists) {
- const localToolsAssetTarget = path.join(targetDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
- // Replace the whole asset directory: drop the previous tree, then copy
- // the new one (fs.copy is recursive for directories).
- yield* fs.remove(localToolsAssetTarget, { recursive: true, force: true }).pipe(
- Effect.andThen(fs.copy(localToolsAssetSource, localToolsAssetTarget, { overwrite: true })),
+ const localToolsAssetTarget = path.join(targetDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
+
+ const releaseTag = options.releaseTag;
+ const stagedReleaseTagPath = path.join(sourceDirectory, RUN_COMPANION_RELEASE_TAG_FILENAME);
+ if (releaseTag) {
+ yield* provideFsAndPath(ctx, writeInstalledReleaseTag(sourceDirectory, releaseTag)).pipe(
Effect.mapError(
error =>
new UpgradeBinaryError({
cause: error,
- message: 'Failed to replace local-tool binary assets',
+ message: 'Failed to update installed release metadata',
})
)
);
}
- const releaseTag = options.releaseTag;
- if (releaseTag) {
- yield* provideFsAndPath(ctx, writeInstalledReleaseTag(targetDirectory, releaseTag)).pipe(
+ for (const replacement of companionReplacements) {
+ const {
+ relativePath,
+ sourcePath: sourceCompanion,
+ targetPath: targetCompanion,
+ } = replacement;
+ yield* fs.makeDirectory(path.dirname(targetCompanion), { recursive: true }).pipe(
Effect.mapError(
- error =>
+ cause =>
new UpgradeBinaryError({
- cause: error,
- message: 'Failed to update installed release metadata',
+ cause,
+ message: `Failed to create companion module directory: ${relativePath}`,
})
)
);
+
+ yield* provideFsAndPath(
+ ctx,
+ atomicReplaceFile({ sourcePath: sourceCompanion, targetPath: targetCompanion })
+ ).pipe(
+ Effect.mapError(
+ mapAtomicReplaceError(`Failed to replace companion module: ${relativePath}`)
+ )
+ );
+ }
+
+ if (localToolsAssetExists) {
+ yield* provideFsAndPath(
+ ctx,
+ atomicReplaceDirectory({
+ sourcePath: localToolsAssetSource,
+ targetPath: localToolsAssetTarget,
+ })
+ ).pipe(Effect.mapError(mapAtomicReplaceError('Failed to replace local-tool binary assets')));
}
+
+ if (releaseTag) {
+ yield* provideFsAndPath(
+ ctx,
+ atomicReplaceFile({
+ sourcePath: stagedReleaseTagPath,
+ targetPath: path.join(targetDirectory, RUN_COMPANION_RELEASE_TAG_FILENAME),
+ })
+ ).pipe(Effect.mapError(mapAtomicReplaceError('Failed to update installed release metadata')));
+ }
+
+ yield* provideFsAndPath(ctx, atomicReplaceFile({ sourcePath, targetPath, mode: 0o755 })).pipe(
+ Effect.mapError(mapAtomicReplaceError('Failed to replace binary'))
+ );
});
/**
@@ -546,7 +577,9 @@ const upgrade = (
// If local binary path is provided (for testing), use it directly
if (Option.isSome(upgradeTargetOpt)) {
yield* ui.log.info(`New local version available (current: ${currentReleaseIdentifier})`);
- yield* replaceBinary(ctx, upgradeTargetOpt.value, currentPath);
+ yield* replaceBinary(ctx, upgradeTargetOpt.value, currentPath, {
+ releaseTag: explicitTag,
+ });
yield* ui.outro('Upgrade completed');
return undefined;
}
diff --git a/ts/packages/cli/test/src/services/upgrade-binary.test.ts b/ts/packages/cli/test/src/services/upgrade-binary.test.ts
index 09b920535..ce31cea73 100644
--- a/ts/packages/cli/test/src/services/upgrade-binary.test.ts
+++ b/ts/packages/cli/test/src/services/upgrade-binary.test.ts
@@ -1,12 +1,16 @@
import { describe, expect, it, vi } from '@effect/vitest';
-import { ConfigProvider, Effect, Layer } from 'effect';
+import { ConfigProvider, Effect, Layer, Option } from 'effect';
import { FetchHttpClient, FileSystem, Path } from '@effect/platform';
+import * as PlatformError from '@effect/platform/Error';
import { BunFileSystem, BunPath } from '@effect/platform-bun';
import { withHttpServer } from 'test/__utils__/http-server';
import { getTerminalCapabilities, TerminalUI } from 'src/services/terminal-ui';
import { UpgradeBinary, UpgradeBinaryError } from 'src/services/upgrade-binary';
import { NodeOs } from 'src/services/node-os';
-import { collectExpectedRunCompanionAssetRelativePaths } from 'src/services/run-companion-modules';
+import {
+ collectExpectedRunCompanionAssetRelativePaths,
+ RUN_COMPANION_RELEASE_TAG_FILENAME,
+} from 'src/services/run-companion-modules';
const TerminalUINoop = Layer.succeed(
TerminalUI,
@@ -55,11 +59,15 @@ const NodeOsTest = Layer.succeed(
const TestPlatform = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);
+type UpgradeOptions = {
+ readonly prerelease?: boolean;
+ readonly tag?: string;
+};
+
const makeUpgradeEffect = (
configEntries: ReadonlyArray<[string, string]>,
- options?: {
- prerelease?: boolean;
- }
+ options?: UpgradeOptions,
+ fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = BunFileSystem.layer
) =>
Effect.gen(function* () {
const service = yield* UpgradeBinary;
@@ -67,7 +75,7 @@ const makeUpgradeEffect = (
}).pipe(
Effect.provide(UpgradeBinary.Default),
Effect.provide(FetchHttpClient.layer),
- Effect.provide(BunFileSystem.layer),
+ Effect.provide(fileSystemLayer),
Effect.provide(TerminalUINoop),
Effect.provide(NodeOsTest),
Effect.withConfigProvider(ConfigProvider.fromMap(new Map(configEntries))),
@@ -76,17 +84,43 @@ const makeUpgradeEffect = (
const runUpgrade = (
configEntries: ReadonlyArray<[string, string]>,
- options?: {
- prerelease?: boolean;
- }
-) => makeUpgradeEffect(configEntries, options).pipe(Effect.flip);
+ options?: UpgradeOptions,
+ fileSystemLayer?: Layer.Layer<FileSystem.FileSystem>
+) => makeUpgradeEffect(configEntries, options, fileSystemLayer).pipe(Effect.flip);
const runUpgradeSuccess = (
configEntries: ReadonlyArray<[string, string]>,
- options?: {
- prerelease?: boolean;
- }
-) => makeUpgradeEffect(configEntries, options);
+ options?: UpgradeOptions,
+ fileSystemLayer?: Layer.Layer<FileSystem.FileSystem>
+) => makeUpgradeEffect(configEntries, options, fileSystemLayer);
+
+const failRenameTo = (failedTargetPath: string) =>
+ Layer.effect(
+ FileSystem.FileSystem,
+ Effect.map(
+ FileSystem.FileSystem,
+ fs =>
+ new Proxy(fs, {
+ get(target, property, receiver) {
+ if (property !== 'rename') {
+ return Reflect.get(target, property, receiver);
+ }
+
+ return (oldPath: string, newPath: string) =>
+ newPath === failedTargetPath
+ ? Effect.fail(
+ new PlatformError.SystemError({
+ reason: 'Busy',
+ module: 'FileSystem',
+ method: 'rename',
+ pathOrDescriptor: newPath,
+ })
+ )
+ : target.rename(oldPath, newPath);
+ },
+ })
+ )
+ ).pipe(Layer.provide(BunFileSystem.layer));
/**
* Bridge the promise-based `withHttpServer` harness into a scoped Effect:
@@ -434,11 +468,16 @@ describe('UpgradeBinary', () => {
'darwin-arm64',
'imessage-cli'
);
+ const staleLocalToolPath = path.join(installDir, 'local-tools-binaries', 'stale-tool');
yield* fs.writeFileString(fakeExecPath, 'old-binary');
yield* fs.writeFileString(sourceBinaryPath, 'new-binary');
yield* fs.makeDirectory(path.dirname(sourceLocalToolPath), { recursive: true });
yield* fs.writeFileString(sourceLocalToolPath, 'imessage-sidecar');
+ yield* fs.makeDirectory(path.dirname(installedLocalToolPath), { recursive: true });
+ yield* fs.writeFileString(installedLocalToolPath, 'old-imessage-sidecar');
+ yield* fs.writeFileString(staleLocalToolPath, 'stale');
+ const originalBinaryInfo = yield* fs.stat(fakeExecPath);
vi.spyOn(process, 'execPath', 'get').mockReturnValue(fakeExecPath);
@@ -456,8 +495,127 @@ describe('UpgradeBinary', () => {
expect(result).toBeUndefined();
expect(yield* fs.readFileString(fakeExecPath)).toBe('new-binary');
+ const replacedBinaryInfo = yield* fs.stat(fakeExecPath);
+ expect(replacedBinaryInfo.dev).toBe(originalBinaryInfo.dev);
+ expect(Option.getOrThrow(replacedBinaryInfo.ino)).not.toBe(
+ Option.getOrThrow(originalBinaryInfo.ino)
+ );
+ expect(replacedBinaryInfo.mode & 0o777).toBe(0o755);
expect(yield* fs.exists(installedLocalToolPath)).toBe(true);
expect(yield* fs.readFileString(installedLocalToolPath)).toBe('imessage-sidecar');
+ expect(yield* fs.exists(staleLocalToolPath)).toBe(false);
+ }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
+ });
+
+ it.scoped('commits companions and release metadata before replacing the binary', () => {
+ vi.stubGlobal('Bun', { which: vi.fn(() => null) });
+
+ return Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const installDir = yield* fs.makeTempDirectoryScoped({
+ prefix: 'composio-ordered-upgrade-target-',
+ });
+ const sourceDir = yield* fs.makeTempDirectoryScoped({
+ prefix: 'composio-ordered-upgrade-source-',
+ });
+ const fakeExecPath = path.join(installDir, 'composio');
+ const sourceBinaryPath = path.join(sourceDir, 'composio');
+ const releaseTagPath = path.join(installDir, RUN_COMPANION_RELEASE_TAG_FILENAME);
+ const newReleaseTag = '@composio/[email protected]';
+ yield* fs.writeFileString(fakeExecPath, 'old-binary');
+ yield* fs.writeFileString(sourceBinaryPath, 'new-binary');
+ yield* fs.writeFileString(releaseTagPath, '@composio/[email protected]\n');
+ const originalReleaseTagInfo = yield* fs.stat(releaseTagPath);
+
+ const companionRelativePaths =
+ yield* collectExpectedRunCompanionAssetRelativePaths(sourceDir);
+ for (const relativePath of companionRelativePaths) {
+ const companionPath = path.join(sourceDir, relativePath);
+ yield* fs.makeDirectory(path.dirname(companionPath), { recursive: true });
+ yield* fs.writeFileString(companionPath, 'new-support-file');
+ }
+ const observedCompanionPath = path.join(installDir, companionRelativePaths[0]!);
+ yield* fs.makeDirectory(path.dirname(observedCompanionPath), { recursive: true });
+ yield* fs.writeFileString(observedCompanionPath, 'old-support-file');
+ vi.spyOn(process, 'execPath', 'get').mockReturnValue(fakeExecPath);
+
+ const error = yield* runUpgrade(
+ [['DEBUG_OVERRIDE_UPGRADE_TARGET', sourceBinaryPath]],
+ { tag: newReleaseTag },
+ failRenameTo(fakeExecPath)
+ );
+
+ expect(error).toBeInstanceOf(UpgradeBinaryError);
+ if (!(error instanceof UpgradeBinaryError)) {
+ throw error;
+ }
+ expect(error.message).toBe('Failed to replace binary');
+ expect(error.cause).toBeInstanceOf(PlatformError.SystemError);
+ expect(yield* fs.readFileString(fakeExecPath)).toBe('old-binary');
+ expect(yield* fs.readFileString(observedCompanionPath)).toBe('new-support-file');
+ expect(yield* fs.readFileString(releaseTagPath)).toBe(`${newReleaseTag}\n`);
+ const replacedReleaseTagInfo = yield* fs.stat(releaseTagPath);
+ expect(Option.getOrThrow(replacedReleaseTagInfo.ino)).not.toBe(
+ Option.getOrThrow(originalReleaseTagInfo.ino)
+ );
+ }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
+ });
+
+ it.scoped('preflights every companion before changing installed files', () => {
+ vi.stubGlobal('Bun', { which: vi.fn(() => null) });
+
+ return Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const installDir = yield* fs.makeTempDirectoryScoped({
+ prefix: 'composio-incomplete-upgrade-target-',
+ });
+ const sourceDir = yield* fs.makeTempDirectoryScoped({
+ prefix: 'composio-incomplete-upgrade-source-',
+ });
+ const fakeExecPath = path.join(installDir, 'composio');
+ const sourceBinaryPath = path.join(sourceDir, 'composio');
+ const releaseTagPath = path.join(installDir, RUN_COMPANION_RELEASE_TAG_FILENAME);
+ yield* fs.writeFileString(fakeExecPath, 'old-binary');
+ yield* fs.writeFileString(sourceBinaryPath, 'new-binary');
+ yield* fs.writeFileString(releaseTagPath, '@composio/[email protected]\n');
+
+ const companionRelativePaths =
+ yield* collectExpectedRunCompanionAssetRelativePaths(sourceDir);
+ const missingRelativePath = companionRelativePaths.at(-1)!;
+ for (const relativePath of companionRelativePaths) {
+ if (relativePath === missingRelativePath) continue;
+ const companionPath = path.join(sourceDir, relativePath);
+ yield* fs.makeDirectory(path.dirname(companionPath), { recursive: true });
+ yield* fs.writeFileString(companionPath, 'new-support-file');
+ }
+ const observedCompanionPath = path.join(installDir, companionRelativePaths[0]!);
+ yield* fs.makeDirectory(path.dirname(observedCompanionPath), { recursive: true });
+ yield* fs.writeFileString(observedCompanionPath, 'old-support-file');
+
+ const sourceLocalToolPath = path.join(sourceDir, 'local-tools-binaries', 'test-tool');
+ const installedLocalToolPath = path.join(installDir, 'local-tools-binaries', 'test-tool');
+ yield* fs.makeDirectory(path.dirname(sourceLocalToolPath), { recursive: true });
+ yield* fs.writeFileString(sourceLocalToolPath, 'new-local-tool');
+ yield* fs.makeDirectory(path.dirname(installedLocalToolPath), { recursive: true });
+ yield* fs.writeFileString(installedLocalToolPath, 'old-local-tool');
+ vi.spyOn(process, 'execPath', 'get').mockReturnValue(fakeExecPath);
+
+ const error = yield* runUpgrade([['DEBUG_OVERRIDE_UPGRADE_TARGET', sourceBinaryPath]], {
+ tag: '@composio/[email protected]',
+ });
+
+ expect(error).toBeInstanceOf(UpgradeBinaryError);
+ if (!(error instanceof UpgradeBinaryError)) {
+ throw error;
+ }
+ expect(error.message).toBe('Downloaded binary package is incomplete');
+ expect(String(error.cause)).toContain(missingRelativePath);
+ expect(yield* fs.readFileString(fakeExecPath)).toBe('old-binary');
+ expect(yield* fs.readFileString(observedCompanionPath)).toBe('old-support-file');
+ expect(yield* fs.readFileString(installedLocalToolPath)).toBe('old-local-tool');
+ expect(yield* fs.readFileString(releaseTagPath)).toBe('@composio/[email protected]\n');
}).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
});