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.

refactor(cli): share one atomic tmp-write helper with per-process tmp names

jkomyno8b7ebadef90a
diff --git a/ts/packages/cli/src/analytics/dispatch.ts b/ts/packages/cli/src/analytics/dispatch.ts
index 8a92c066d..b56a8c49c 100644
--- a/ts/packages/cli/src/analytics/dispatch.ts
+++ b/ts/packages/cli/src/analytics/dispatch.ts
@@ -14,6 +14,7 @@ import {
} from 'effect';
import * as constants from 'src/constants';
import { getDetachedWorkerSpawnArgs, spawnDetached } from 'src/services/detached-process';
+import { atomicWriteFileString } from 'src/utils/atomic-write';
import { sha256Hex } from 'src/utils/checksums';
import { djb2Hash } from 'src/utils/djb2';
import { NodeOs } from 'src/services/node-os';
@@ -291,11 +292,7 @@ const writeAnalyticsStateFile = (contents: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const paths = yield* getAnalyticsPaths;
- const temporaryPath = `${paths.analyticsStatePath}.${crypto.randomUUID().slice(0, 8)}.tmp`;
- yield* fs.writeFileString(temporaryPath, contents);
- yield* fs
- .rename(temporaryPath, paths.analyticsStatePath)
- .pipe(Effect.tapError(() => fs.remove(temporaryPath).pipe(Effect.ignore)));
+ yield* atomicWriteFileString({ fs, target: paths.analyticsStatePath, contents });
});
const getOrCreateInstallIdUnlocked = Effect.gen(function* () {
diff --git a/ts/packages/cli/src/commands/install.cmd.ts b/ts/packages/cli/src/commands/install.cmd.ts
index 9b45d0e96..81c0ecbbb 100644
--- a/ts/packages/cli/src/commands/install.cmd.ts
+++ b/ts/packages/cli/src/commands/install.cmd.ts
@@ -7,6 +7,7 @@ import { NodeOs } from 'src/services/node-os';
import { NodeProcess } from 'src/services/node-process';
import { TerminalUI } from 'src/services/terminal-ui';
import { getCompletionScript } from 'src/effects/shell-completions';
+import { atomicWriteFileString } from 'src/utils/atomic-write';
// ---------------------------------------------------------------------------
// Options
@@ -384,27 +385,50 @@ const planPathBlockWrites = (params: {
return { appendPathFiles, replacementsByTarget, loginOverrideWritten };
};
-/** Atomically replace a physical target file's contents, preserving its file mode. */
-const atomicWriteWithMode = (
+/**
+ * Replace an rc file's contents via the shared atomic-write helper, preserving
+ * the existing file's mode so a private rc stays private across the rewrite.
+ */
+const replaceFilePreservingMode = (
fs: FileSystem.FileSystem,
- writeTarget: string,
+ target: string,
contents: string
): Effect.Effect<void, PlatformError> =>
+ atomicWriteFileString({ fs, target, contents, preserveMode: true });
+
+/** Append each file's queued blocks in one atomic, mode-preserving rewrite per file. */
+const appendQueuedBlocks = (params: {
+ readonly blocksByFile: ReadonlyMap<string, ReadonlyArray<string>>;
+ readonly pathFileTargets: ReadonlyMap<string, string>;
+ readonly fs: FileSystem.FileSystem;
+ readonly path: Path.Path;
+ readonly homedir: string;
+ readonly report: (message: string) => Effect.Effect<void>;
+}): Effect.Effect<void, PlatformError> =>
Effect.gen(function* () {
- const existingTargetInfo = yield* fs.stat(writeTarget).pipe(Effect.option);
- const tmpPath = `${writeTarget}.composio-tmp`;
-
- yield* fs.writeFileString(tmpPath, contents);
- // Mirror install.sh's write_path_block: when the chmod or rename step
- // fails, remove the temp file before propagating the error so no
- // `.composio-tmp` litter is left next to the target.
- const promoteTmp = Effect.gen(function* () {
- if (Option.isSome(existingTargetInfo)) {
- yield* fs.chmod(tmpPath, existingTargetInfo.value.mode & 0o7777);
- }
- yield* fs.rename(tmpPath, writeTarget);
- });
- yield* promoteTmp.pipe(Effect.onError(() => fs.remove(tmpPath).pipe(Effect.ignore)));
+ const { fs, path } = params;
+ for (const [filePath, blocks] of params.blocksByFile.entries()) {
+ // Re-read instead of reusing the pre-check snapshot: two configured paths
+ // can alias the same physical file through symlinks, and this write must
+ // not discard a previous iteration's append.
+ const existingContents = yield* readMaybeMissingFile(filePath, fs);
+ // PATH files were already resolved by the caller; only the completion
+ // file needs a fresh resolve.
+ const writeTarget =
+ params.pathFileTargets.get(filePath) ?? (yield* resolveWriteTarget(filePath, fs));
+
+ yield* fs
+ .makeDirectory(path.dirname(writeTarget), { recursive: true })
+ .pipe(
+ Effect.catchAll(e =>
+ Effect.logDebug('Could not create parent directory (may already exist):', e)
+ )
+ );
+
+ const appendContent = '\n' + blocks.join('\n\n') + '\n';
+ yield* replaceFilePreservingMode(fs, writeTarget, existingContents + appendContent);
+ yield* params.report(`Updated ${tildify(filePath, params.homedir)}`);
+ }
});
/** Atomically rewrite each reconciled physical target, preserving its file mode. */
@@ -416,7 +440,7 @@ const writeReconciledTargets = (params: {
}): Effect.Effect<void, PlatformError> =>
Effect.gen(function* () {
for (const [writeTarget, replacement] of params.replacementsByTarget.entries()) {
- yield* atomicWriteWithMode(params.fs, writeTarget, replacement.contents);
+ yield* replaceFilePreservingMode(params.fs, writeTarget, replacement.contents);
yield* params.report(`Updated ${tildify(replacement.displayPath, params.homedir)}`);
}
});
@@ -527,38 +551,6 @@ const resolveWriteTarget = (
Effect.catchAll(() => Effect.succeed(filePath))
);
-/**
- * Atomically replace `writeTarget` via a same-directory tmp file. The tmp copy
- * is created with the target's mode from the start so a private rc's contents
- * never sit in a default-mode, world-readable tmp file. open(2) masks the
- * requested mode with the process umask (only ever clearing bits), so a chmod
- * still follows to pin the exact mode.
- */
-const replaceFilePreservingMode = (
- writeTarget: string,
- contents: string,
- fs: FileSystem.FileSystem
-): Effect.Effect<void, PlatformError> =>
- Effect.gen(function* () {
- const existingTargetInfo = yield* fs.stat(writeTarget).pipe(Effect.option);
- const preservedMode = Option.map(existingTargetInfo, info => info.mode & 0o7777);
- const tmpPath = `${writeTarget}.composio-tmp`;
- yield* Option.match(preservedMode, {
- onNone: () => fs.writeFileString(tmpPath, contents),
- onSome: mode => fs.writeFileString(tmpPath, contents, { mode }),
- });
- // Mirror install.sh's write_path_block: when the chmod or rename step
- // fails, remove the temp file before propagating the error so no
- // `.composio-tmp` litter is left next to the target.
- const promoteTmp = Effect.gen(function* () {
- if (Option.isSome(preservedMode)) {
- yield* fs.chmod(tmpPath, preservedMode.value);
- }
- yield* fs.rename(tmpPath, writeTarget);
- });
- yield* promoteTmp.pipe(Effect.onError(() => fs.remove(tmpPath).pipe(Effect.ignore)));
- });
-
// ---------------------------------------------------------------------------
// Exported logic (reusable from install.sh post-install delegation)
// ---------------------------------------------------------------------------
@@ -771,30 +763,14 @@ export const installShellIntegration = (params: {
report: success,
});
- if (blocksByFile.size > 0) {
- for (const [filePath, blocks] of blocksByFile.entries()) {
- // Re-read instead of reusing the pre-check snapshot: two configured paths
- // can alias the same physical file through symlinks, and this write must
- // not discard a previous iteration's append.
- const existingContents = yield* readMaybeMissingFile(filePath, fs);
- // PATH files were already resolved above; only the completion file needs a fresh resolve.
- const writeTarget =
- pathFileTargets.get(filePath) ?? (yield* resolveWriteTarget(filePath, fs));
-
- yield* fs
- .makeDirectory(path.dirname(writeTarget), { recursive: true })
- .pipe(
- Effect.catchAll(e =>
- Effect.logDebug('Could not create parent directory (may already exist):', e)
- )
- );
-
- const appendContent = '\n' + blocks.join('\n\n') + '\n';
- yield* replaceFilePreservingMode(writeTarget, existingContents + appendContent, fs);
-
- yield* success(`Updated ${tildify(filePath, os.homedir)}`);
- }
- }
+ yield* appendQueuedBlocks({
+ blocksByFile,
+ pathFileTargets,
+ fs,
+ path,
+ homedir: os.homedir,
+ report: success,
+ });
const changesWritten = blocksByFile.size > 0 || replacementsByTarget.size > 0;
if (!changesWritten) {
diff --git a/ts/packages/cli/src/services/tool-permissions.ts b/ts/packages/cli/src/services/tool-permissions.ts
index c3d8c9ebe..ad5d8b1bd 100644
--- a/ts/packages/cli/src/services/tool-permissions.ts
+++ b/ts/packages/cli/src/services/tool-permissions.ts
@@ -5,6 +5,7 @@ import { detectCliPlatform } from '@composio/cli-local-tools';
import { Data, Effect, Option, Record as EffectRecord, Schema } from 'effect';
import { JsonRecordSchema } from 'src/effects/json';
import { resolveCliConfigDirectorySync } from 'src/services/cli-user-config';
+import { atomicWriteFileString } from 'src/utils/atomic-write';
import { collectDecodedEntries } from 'src/utils/collect-decoded-entries';
import {
detectNativeUiCallerAgent,
@@ -205,25 +206,20 @@ const writeCacheFile = (fs: FileSystem.FileSystem, path: Path.Path, cache: Cache
const targetPath = cachePath(path);
yield* fs.makeDirectory(path.dirname(targetPath), { recursive: true });
- const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${crypto.randomUUID()}.tmp`;
// Atomic write: on failure the temp file is dropped (best effort) and the
// original error is surfaced.
- yield* fs
- .writeFileString(
- tempPath,
- `${JSON.stringify(
- {
- entries: cache.entries,
- allowEntries: pruneAllowEntries(cache.allowEntries),
- } satisfies CacheFile,
- null,
- 2
- )}\n`
- )
- .pipe(
- Effect.andThen(fs.rename(tempPath, targetPath)),
- Effect.onError(() => fs.remove(tempPath, { force: true }).pipe(Effect.ignore))
- );
+ yield* atomicWriteFileString({
+ fs,
+ target: targetPath,
+ contents: `${JSON.stringify(
+ {
+ entries: cache.entries,
+ allowEntries: pruneAllowEntries(cache.allowEntries),
+ } satisfies CacheFile,
+ null,
+ 2
+ )}\n`,
+ });
});
// Serializes the read-modify-write cycles on the cache file so concurrent
diff --git a/ts/packages/cli/src/utils/atomic-write.ts b/ts/packages/cli/src/utils/atomic-write.ts
new file mode 100644
index 000000000..18aab0050
--- /dev/null
+++ b/ts/packages/cli/src/utils/atomic-write.ts
@@ -0,0 +1,56 @@
+/**
+ * Atomic file replacement shared by every tmp-write→rename site in the CLI
+ * (shell rc rewrites, the tool-permissions cache, analytics state).
+ *
+ * The tmp file lives next to the target so the final rename(2) stays on one
+ * filesystem and is atomic: readers observe either the old or the new
+ * contents, never a partial write. The tmp name embeds the pid so concurrent
+ * CLI processes writing the same target never share (and clobber) one tmp
+ * file. On any failure — including a failure of the initial write itself,
+ * e.g. ENOSPC mid-write — the tmp file is removed best-effort before the
+ * original error propagates, so no tmp litter is left next to the target.
+ */
+
+import type { FileSystem } from '@effect/platform';
+import type { PlatformError } from '@effect/platform/Error';
+import { Effect, Option } from 'effect';
+
+export const atomicTmpPath = (target: string): string => `${target}.composio-tmp.${process.pid}`;
+
+export const atomicWriteFileString = (params: {
+ readonly fs: FileSystem.FileSystem;
+ readonly target: string;
+ readonly contents: string;
+ /**
+ * Preserve an existing target's file mode across the replacement: the tmp
+ * copy is created with the target's mode from the start so private contents
+ * never sit in a default-mode, world-readable tmp file. open(2) masks the
+ * requested mode with the process umask (only ever clearing bits), so a
+ * chmod still follows to pin the exact mode. When the target does not
+ * exist (or `preserveMode` is false) the tmp is created with default mode.
+ */
+ readonly preserveMode?: boolean;
+}): Effect.Effect<void, PlatformError> =>
+ Effect.gen(function* () {
+ const { fs, target, contents } = params;
+ const preservedMode = params.preserveMode
+ ? Option.map(yield* fs.stat(target).pipe(Effect.option), info => info.mode & 0o7777)
+ : Option.none<number>();
+ const tmpPath = atomicTmpPath(target);
+
+ const writeAndPromote = Effect.gen(function* () {
+ yield* Option.match(preservedMode, {
+ onNone: () => fs.writeFileString(tmpPath, contents),
+ onSome: mode => fs.writeFileString(tmpPath, contents, { mode }),
+ });
+ yield* Option.match(preservedMode, {
+ onNone: () => Effect.void,
+ onSome: mode => fs.chmod(tmpPath, mode),
+ });
+ yield* fs.rename(tmpPath, target);
+ });
+
+ yield* writeAndPromote.pipe(
+ Effect.onError(() => fs.remove(tmpPath, { force: true }).pipe(Effect.ignore))
+ );
+ });
diff --git a/ts/packages/cli/test/src/commands/install.cmd.test.ts b/ts/packages/cli/test/src/commands/install.cmd.test.ts
index 1ace64538..7a739b081 100644
--- a/ts/packages/cli/test/src/commands/install.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/install.cmd.test.ts
@@ -52,6 +52,14 @@ const install = (
shell: params.shell,
});
+// The atomic-write tmp name embeds the pid, so litter checks scan the target's
+// directory for any `.composio-tmp` remnant instead of probing one fixed name.
+const expectNoTmpLitter = (fs: FileSystem.FileSystem, targetPath: string) =>
+ Effect.gen(function* () {
+ const entries = yield* fs.readDirectory(path.dirname(targetPath));
+ expect(entries.filter(name => name.includes('.composio-tmp'))).toEqual([]);
+ });
+
// NOTE: `@effect/vitest`'s `layer(...)` builds one shared TestLive instance
// (home dir, MockConsole buffer, etc.) for every `it.scoped` nested inside a
// single call. Sharing is only safe when a later test doesn't read state a
@@ -121,7 +129,7 @@ describe('CLI: composio install', () => {
expect(yield* fs.readLink(rcPath)).toBe(linkTarget);
expect(yield* fs.readFileString(managedPath)).toContain('# Composio CLI');
- expect(yield* fs.exists(`${rcPath}.composio-tmp`)).toBe(false);
+ yield* expectNoTmpLitter(fs, rcPath);
})
);
});
@@ -253,7 +261,7 @@ describe('CLI: composio install', () => {
const info = yield* fs.stat(bashProfilePath);
expect(info.mode & 0o777).toBe(0o600);
- expect(yield* fs.exists(`${bashProfilePath}.composio-tmp`)).toBe(false);
+ yield* expectNoTmpLitter(fs, bashProfilePath);
})
);
});
@@ -734,7 +742,7 @@ describe('CLI: composio install', () => {
// Both aliases must survive as symlinks to the same physical file.
expect(yield* fs.readLink(bashrcPath)).toBe(managedPath);
expect(yield* fs.readLink(bashProfilePath)).toBe(managedPath);
- expect(yield* fs.exists(`${managedPath}.composio-tmp`)).toBe(false);
+ yield* expectNoTmpLitter(fs, managedPath);
})
);
});
@@ -757,7 +765,7 @@ describe('CLI: composio install', () => {
const exit = yield* install().pipe(Effect.exit);
expect(Exit.isFailure(exit)).toBe(true);
- expect(yield* fs.exists(`${rcPath}.composio-tmp`)).toBe(false);
+ yield* expectNoTmpLitter(fs, rcPath);
})
);
});