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.

feat(cli): reconcile managed PATH blocks and defer final messaging to installer

jkomynob7c17458abbb
diff --git a/ts/packages/cli/src/commands/install.cmd.ts b/ts/packages/cli/src/commands/install.cmd.ts
index 6c59a3a6e..3682c5c8e 100644
--- a/ts/packages/cli/src/commands/install.cmd.ts
+++ b/ts/packages/cli/src/commands/install.cmd.ts
@@ -189,6 +189,217 @@ const buildShellConfig = (
const fileContains = (contents: string, marker: string): boolean =>
contents.split('\n').some(line => line.trim() === marker.trim());
+/** Outcome of reconciling a startup file's managed PATH block against the resolved bin dir. */
+type ManagedPathBlockState =
+ | { readonly state: 'absent' }
+ | { readonly state: 'current' }
+ | { readonly state: 'stale'; readonly reconciled: string };
+
+const isAnyMarkerLine = (line: string): boolean => {
+ const trimmed = line.trim();
+ return trimmed === MARKER || trimmed === COMPLETIONS_MARKER;
+};
+
+/**
+ * Reconcile the managed PATH block — the `MARKER` line plus the PATH
+ * assignment right below it — with the currently resolved bin directory.
+ * A block recording a stale bin dir is replaced in place, duplicate managed
+ * PATH blocks collapse into a single current block, and unmanaged content
+ * (including the completions block) is left byte-for-byte untouched.
+ */
+const reconcileManagedPathBlock = (contents: string, pathBlock: string): ManagedPathBlockState => {
+ const lines = contents.split('\n');
+ const markerIndexes = lines.flatMap((line, index) => (line.trim() === MARKER ? [index] : []));
+ const firstMarkerIndex = markerIndexes[0];
+ if (firstMarkerIndex === undefined) return { state: 'absent' };
+
+ const expectedAssignment = (pathBlock.split('\n')[1] ?? '').trim();
+ if (
+ markerIndexes.length === 1 &&
+ (lines[firstMarkerIndex + 1] ?? '').trim() === expectedAssignment
+ ) {
+ return { state: 'current' };
+ }
+
+ // Managed lines: each marker line and its assignment line, unless that next
+ // line is itself a marker (never consume the completions block).
+ const managedLineIndexes = new Set<number>(
+ markerIndexes.flatMap(markerIndex => {
+ const assignment = lines[markerIndex + 1];
+ return assignment !== undefined && !isAnyMarkerLine(assignment)
+ ? [markerIndex, markerIndex + 1]
+ : [markerIndex];
+ })
+ );
+
+ const reconciledLines = lines.flatMap((line, index) => {
+ if (index === firstMarkerIndex) return pathBlock.split('\n');
+ return managedLineIndexes.has(index) ? [] : [line];
+ });
+ return { state: 'stale', reconciled: reconciledLines.join('\n') };
+};
+
+interface ManagedBlockReplacement {
+ readonly contents: string;
+ readonly displayPath: string;
+}
+
+interface PathBlockWritePlan {
+ readonly appendPathFiles: readonly string[];
+ readonly replacementsByTarget: ReadonlyMap<string, ManagedBlockReplacement>;
+ readonly loginOverrideWritten: boolean;
+}
+
+/**
+ * Decide, per configured PATH file, whether the managed block must be appended
+ * (absent), replaced in place (stale bin dir), or left alone (already
+ * current). Both appends and replacements are deduplicated by physical write
+ * target so two logical paths aliasing the same file (a dotfiles symlink
+ * setup) keep exactly one managed block.
+ */
+const planPathBlockWrites = (params: {
+ readonly pathFiles: readonly string[];
+ readonly existingByFile: ReadonlyMap<string, string>;
+ readonly pathFileTargets: ReadonlyMap<string, string>;
+ readonly pathBlock: string;
+ readonly bashLoginOverride: string | undefined;
+ readonly skipPathWriteForReachability: boolean;
+}): PathBlockWritePlan => {
+ const appendPathFiles: string[] = [];
+ const replacementsByTarget = new Map<string, ManagedBlockReplacement>();
+ const queuedPathTargets = new Set<string>();
+ let loginOverrideWritten = false;
+ for (const filePath of params.pathFiles) {
+ const existing = params.existingByFile.get(filePath) ?? '';
+ const target = params.pathFileTargets.get(filePath)!;
+ const reconciliation = reconcileManagedPathBlock(existing, params.pathBlock);
+ if (reconciliation.state === 'stale') {
+ if (!replacementsByTarget.has(target)) {
+ replacementsByTarget.set(target, {
+ contents: reconciliation.reconciled,
+ displayPath: filePath,
+ });
+ if (filePath === params.bashLoginOverride) loginOverrideWritten = true;
+ }
+ continue;
+ }
+ if (
+ reconciliation.state === 'current' ||
+ params.skipPathWriteForReachability ||
+ queuedPathTargets.has(target)
+ ) {
+ continue;
+ }
+ appendPathFiles.push(filePath);
+ queuedPathTargets.add(target);
+ if (filePath === params.bashLoginOverride) loginOverrideWritten = true;
+ }
+ return { appendPathFiles, replacementsByTarget, loginOverrideWritten };
+};
+
+/** Atomically rewrite each reconciled physical target, preserving its file mode. */
+const writeReconciledTargets = (params: {
+ readonly replacementsByTarget: ReadonlyMap<string, ManagedBlockReplacement>;
+ readonly fs: FileSystem.FileSystem;
+ readonly homedir: string;
+ readonly report: (message: string) => Effect.Effect<void>;
+}): Effect.Effect<void, PlatformError> =>
+ Effect.gen(function* () {
+ for (const [writeTarget, replacement] of params.replacementsByTarget.entries()) {
+ const existingTargetInfo = yield* params.fs.stat(writeTarget).pipe(Effect.option);
+ const tmpPath = `${writeTarget}.composio-tmp`;
+
+ yield* params.fs.writeFileString(tmpPath, replacement.contents);
+ if (Option.isSome(existingTargetInfo)) {
+ yield* params.fs.chmod(tmpPath, existingTargetInfo.value.mode & 0o7777);
+ }
+ yield* params.fs.rename(tmpPath, writeTarget);
+
+ yield* params.report(`Updated ${tildify(replacement.displayPath, params.homedir)}`);
+ }
+ });
+
+/** Completion status line, plus whether the completion block still needs appending. */
+const planCompletionWrite = (params: {
+ readonly shell: Shell;
+ readonly completionsRequested: boolean;
+ readonly completionBlock: string | undefined;
+ readonly completionFile: string;
+ readonly existingCompletionFile: string;
+ readonly homedir: string;
+}): { readonly statusLine: string; readonly append: boolean } => {
+ if (params.shell === 'zsh') {
+ return { statusLine: 'Completions: skipped for zsh', append: false };
+ }
+ if (!params.completionsRequested) {
+ return {
+ statusLine: 'Completions: skipped by default (pass --completions to enable)',
+ append: false,
+ };
+ }
+ if (!params.completionBlock) {
+ return { statusLine: 'Completions: not available for this shell', append: false };
+ }
+ if (fileContains(params.existingCompletionFile, COMPLETIONS_MARKER)) {
+ return { statusLine: 'Completions: already configured', append: false };
+ }
+ return {
+ statusLine:
+ params.shell === 'fish'
+ ? `Completions: will install fish completions to ${tildify(params.completionFile, params.homedir)}`
+ : 'Completions: will install shell completions',
+ append: true,
+ };
+};
+
+/** Status lines summarizing the planned PATH work, in print order. */
+const pathStatusLines = (params: {
+ readonly pathWritten: boolean;
+ readonly pathReplaced: boolean;
+ readonly skipPathWriteForReachability: boolean;
+ readonly renderedBinDir: string;
+}): readonly string[] => {
+ const lines: string[] = [];
+ if (params.pathWritten) lines.push(`PATH: will add ${params.renderedBinDir} to $PATH`);
+ if (params.pathReplaced) {
+ lines.push(`PATH: will update the managed block to ${params.renderedBinDir}`);
+ }
+ if (lines.length === 0) {
+ lines.push(
+ params.skipPathWriteForReachability
+ ? 'PATH: already on $PATH — nothing to do.'
+ : 'PATH: already configured'
+ );
+ }
+ return lines;
+};
+
+/** Shell-specific body of the restart hint printed after a change. */
+const restartHintBody = (params: {
+ readonly shell: Shell;
+ readonly zshPathFile: string;
+ readonly bashrc: string;
+ readonly bashLoginOverride: string | undefined;
+ readonly loginOverrideWritten: boolean;
+ readonly homedir: string;
+}): string => {
+ switch (params.shell) {
+ case 'fish':
+ return 'exec fish';
+ case 'zsh':
+ return `source ${tildify(params.zshPathFile, params.homedir)}`;
+ case 'bash': {
+ const hintLines = [`source ${tildify(params.bashrc, params.homedir)}`];
+ if (params.loginOverrideWritten && params.bashLoginOverride) {
+ hintLines.push(
+ `${tildify(params.bashLoginOverride, params.homedir)} was also updated — that entry applies to new login shells too.`
+ );
+ }
+ return hintLines.join('\n');
+ }
+ }
+};
+
const tildify = (p: string, homedir: string): string =>
p.startsWith(homedir + '/') ? `~/${p.slice(homedir.length + 1)}` : p;
@@ -276,6 +487,13 @@ export const installShellIntegration = (params: {
return;
}
+ // KD7 (final-block contract): when install.sh delegates to this command it
+ // passes COMPOSIO_CLI_INVOCATION_ORIGIN=installer and owns the final action
+ // block itself. Keep the concise per-file status lines but suppress the
+ // boxed restart hint so the CLI never prints a competing instruction.
+ const invocationOrigin = yield* readOptionalEnv('COMPOSIO_CLI_INVOCATION_ORIGIN');
+ const installerOwnsFinalMessaging = invocationOrigin === 'installer';
+
const isExplicitShell = params.shell !== undefined;
const shellEnv = yield* readEnvWithDefault('SHELL', '');
const shell = params.shell ?? detectShellFromEnv(path, shellEnv);
@@ -358,52 +576,51 @@ export const installShellIntegration = (params: {
);
const skipPathWriteForReachability =
!isExplicitShell && binDirOnPath && !anyPathFileAlreadyMarked;
- let pathWritten = false;
- let loginOverrideWritten = false;
- const queuedPathTargets = new Set<string>();
- for (const filePath of config.pathFiles) {
- const existing = existingByFile.get(filePath) ?? '';
- const target = pathFileTargets.get(filePath)!;
- if (
- fileContains(existing, MARKER) ||
- skipPathWriteForReachability ||
- queuedPathTargets.has(target)
- ) {
- continue;
- }
+ const writePlan = planPathBlockWrites({
+ pathFiles: config.pathFiles,
+ existingByFile,
+ pathFileTargets,
+ pathBlock: config.pathBlock,
+ bashLoginOverride,
+ skipPathWriteForReachability,
+ });
+ const { replacementsByTarget, loginOverrideWritten } = writePlan;
+ for (const filePath of writePlan.appendPathFiles) {
pushBlock(filePath, config.pathBlock);
- queuedPathTargets.add(target);
- pathWritten = true;
- if (filePath === bashLoginOverride) loginOverrideWritten = true;
}
+ const pathWritten = writePlan.appendPathFiles.length > 0;
+
+ yield* Effect.forEach(
+ pathStatusLines({
+ pathWritten,
+ pathReplaced: replacementsByTarget.size > 0,
+ skipPathWriteForReachability,
+ renderedBinDir: tildify(binDir, os.homedir),
+ }),
+ step
+ );
- if (pathWritten) {
- yield* step(`PATH: will add ${tildify(binDir, os.homedir)} to $PATH`);
- } else if (skipPathWriteForReachability) {
- yield* step('PATH: already on $PATH — nothing to do.');
- } else {
- yield* step('PATH: already configured');
+ const completionWrite = planCompletionWrite({
+ shell,
+ completionsRequested: params.completions,
+ completionBlock: config.completionBlock,
+ completionFile: config.completionFile,
+ existingCompletionFile: existingByFile.get(config.completionFile) ?? '',
+ homedir: os.homedir,
+ });
+ if (completionWrite.append && config.completionBlock) {
+ pushBlock(config.completionFile, config.completionBlock);
}
+ yield* step(completionWrite.statusLine);
- if (shell === 'zsh') {
- yield* step('Completions: skipped for zsh');
- } else if (!params.completions) {
- yield* step('Completions: skipped by default (pass --completions to enable)');
- } else if (!config.completionBlock) {
- yield* step('Completions: not available for this shell');
- } else {
- const existingCompletionFile = existingByFile.get(config.completionFile) ?? '';
- if (!fileContains(existingCompletionFile, COMPLETIONS_MARKER)) {
- pushBlock(config.completionFile, config.completionBlock);
- yield* step(
- config.shell === 'fish'
- ? `Completions: will install fish completions to ${tildify(config.completionFile, os.homedir)}`
- : 'Completions: will install shell completions'
- );
- } else {
- yield* step('Completions: already configured');
- }
- }
+ // Reconcile stale managed blocks first so any completion append below
+ // (which re-reads from disk) lands on top of the replaced contents.
+ yield* writeReconciledTargets({
+ replacementsByTarget,
+ fs,
+ homedir: os.homedir,
+ report: success,
+ });
if (blocksByFile.size > 0) {
for (const [filePath, blocks] of blocksByFile.entries()) {
@@ -435,28 +652,25 @@ export const installShellIntegration = (params: {
yield* success(`Updated ${tildify(filePath, os.homedir)}`);
}
- } else {
+ }
+
+ const changesWritten = blocksByFile.size > 0 || replacementsByTarget.size > 0;
+ if (!changesWritten) {
yield* success('Shell integration already configured — nothing to do.');
}
- if (blocksByFile.size > 0) {
- if (shell === 'fish') {
- yield* note('exec fish', 'Restart your shell to apply changes');
- } else if (shell === 'zsh') {
- yield* note(
- `source ${tildify(config.pathFiles[0]!, os.homedir)}`,
- 'Restart your shell to apply changes'
- );
- } else {
- const bashrc = path.join(os.homedir, '.bashrc');
- const hintLines = [`source ${tildify(bashrc, os.homedir)}`];
- if (loginOverrideWritten && bashLoginOverride) {
- hintLines.push(
- `${tildify(bashLoginOverride, os.homedir)} was also updated — that entry applies to new login shells too.`
- );
- }
- yield* note(hintLines.join('\n'), 'Restart your shell to apply changes');
- }
+ if (changesWritten && !installerOwnsFinalMessaging) {
+ yield* note(
+ restartHintBody({
+ shell,
+ zshPathFile: config.pathFiles[0]!,
+ bashrc: path.join(os.homedir, '.bashrc'),
+ bashLoginOverride,
+ loginOverrideWritten,
+ homedir: os.homedir,
+ }),
+ 'Restart your shell to apply changes'
+ );
}
yield* ui.outro('Done');
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 a8c825ff2..09fb61911 100644
--- a/ts/packages/cli/test/src/commands/install.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/install.cmd.test.ts
@@ -74,6 +74,8 @@ describe('CLI: composio install', () => {
Effect.gen(function* () {
const os = yield* NodeOs;
vi.stubEnv('SHELL', '/bin/zsh');
+ // A direct invocation (no installer origin) keeps the restart hint.
+ vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', '');
const expectedBinDir = expectedRuntimeBinDir();
yield* install();
@@ -93,6 +95,7 @@ describe('CLI: composio install', () => {
expect(output).toContain('PATH: will add');
expect(output).toContain('Completions: skipped for zsh');
expect(output).toContain('Updated');
+ expect(output).toContain('Restart your shell to apply changes');
expect(output).toContain('source ~/.zshrc');
})
);
@@ -500,20 +503,19 @@ describe('CLI: composio install', () => {
});
});
- describe('[When] .zshrc already has the marker', () => {
+ describe('[When] .zshrc already has a managed block recording the current bin dir', () => {
layer(InstallTestLive())(it => {
- it.scoped('[Then] reports already configured', () =>
+ it.scoped('[Then] reports already configured and leaves the file byte-identical', () =>
Effect.gen(function* () {
const os = yield* NodeOs;
const fs = yield* FileSystem.FileSystem;
vi.stubEnv('SHELL', '/bin/zsh');
+ const expectedBinDir = expectedRuntimeBinDir();
- // Pre-populate .zshrc with existing config
+ // Pre-populate .zshrc with a managed block that is already current.
const rcPath = path.join(os.homedir, '.zshrc');
- yield* fs.writeFileString(
- rcPath,
- '# existing config\n# Composio CLI\nexport PATH="$HOME/.local/bin:$PATH"\n# Composio CLI completions\n_composio() {}\n'
- );
+ const original = `# existing config\n# Composio CLI\nexport PATH="${expectedBinDir}:$PATH"\n# Composio CLI completions\n_composio() {}\n`;
+ yield* fs.writeFileString(rcPath, original);
yield* install({ completions: true });
@@ -522,11 +524,169 @@ describe('CLI: composio install', () => {
expect(output).toContain('PATH: already configured');
expect(output).toContain('Completions: skipped for zsh');
expect(output).toContain('Shell integration already configured');
+ expect(output).not.toContain('Updated');
+
+ // File must not be rewritten at all.
+ const contents = yield* fs.readFileString(rcPath);
+ expect(contents).toBe(original);
+ })
+ );
+ });
+ });
+
+ describe('[When] the managed PATH block records a stale bin dir', () => {
+ layer(InstallTestLive())(it => {
+ it.scoped('[Then] replaces only the managed block and keeps unmanaged content', () =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const fs = yield* FileSystem.FileSystem;
+ vi.stubEnv('SHELL', '/bin/zsh');
+ const expectedBinDir = expectedRuntimeBinDir();
+
+ const rcPath = path.join(os.homedir, '.zshrc');
+ yield* fs.writeFileString(
+ rcPath,
+ '# user prologue\n# Composio CLI\nexport PATH="/stale/bin:$PATH"\n# user epilogue\nalias ll="ls -la"\n'
+ );
+
+ yield* install();
+
+ const contents = yield* fs.readFileString(rcPath);
+ expect(contents).toContain(`export PATH="${expectedBinDir}:$PATH"`);
+ expect(contents).not.toContain('/stale/bin');
+ expect(contents).toContain('# user prologue');
+ expect(contents).toContain('# user epilogue');
+ expect(contents).toContain('alias ll="ls -la"');
+ expect(contents.match(/^# Composio CLI$/gm)?.length ?? 0).toBe(1);
+
+ const output = (yield* MockConsole.getLines()).join('\n');
+ expect(output).toContain('Updated ~/.zshrc');
+ })
+ );
+ });
+ });
+
+ describe('[When] duplicate managed PATH blocks exist in one file', () => {
+ layer(InstallTestLive())(it => {
+ it.scoped('[Then] they collapse into a single current block', () =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const fs = yield* FileSystem.FileSystem;
+ vi.stubEnv('SHELL', '/bin/zsh');
+ const expectedBinDir = expectedRuntimeBinDir();
+
+ const rcPath = path.join(os.homedir, '.zshrc');
+ yield* fs.writeFileString(
+ rcPath,
+ `# Composio CLI\nexport PATH="/stale/bin:$PATH"\n# unmanaged line\n# Composio CLI\nexport PATH="${expectedBinDir}:$PATH"\n`
+ );
+
+ yield* install();
- // File should not have grown
const contents = yield* fs.readFileString(rcPath);
- const markerCount = contents.split('# Composio CLI').length - 1;
- expect(markerCount).toBe(2);
+ expect(contents.match(/^# Composio CLI$/gm)?.length ?? 0).toBe(1);
+ expect(contents).toContain(`export PATH="${expectedBinDir}:$PATH"`);
+ expect(contents).not.toContain('/stale/bin');
+ expect(contents).toContain('# unmanaged line');
+ })
+ );
+ });
+ });
+
+ describe('[When] .bashrc and .bash_profile alias one physical file with a stale managed block', () => {
+ layer(InstallTestLive())(it => {
+ it.scoped('[Then] the physical file ends with exactly one current block', () =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const fs = yield* FileSystem.FileSystem;
+ vi.stubEnv('SHELL', '/bin/bash');
+ const expectedBinDir = expectedRuntimeBinDir();
+
+ const bashrcPath = path.join(os.homedir, '.bashrc');
+ const bashProfilePath = path.join(os.homedir, '.bash_profile');
+ const managedPath = path.join(os.homedir, '.managed-bashrc');
+ yield* fs.remove(bashrcPath, { force: true });
+ yield* fs.writeFileString(
+ managedPath,
+ '# managed prologue\n# Composio CLI\nexport PATH="/stale/bin:$PATH"\n'
+ );
+ yield* fs.symlink(managedPath, bashrcPath);
+ yield* fs.symlink(managedPath, bashProfilePath);
+
+ yield* install();
+
+ const contents = yield* fs.readFileString(managedPath);
+ expect(contents.match(/^# Composio CLI$/gm)?.length ?? 0).toBe(1);
+ expect(contents).toContain(`export PATH="${expectedBinDir}:$PATH"`);
+ expect(contents).not.toContain('/stale/bin');
+ expect(contents).toContain('# managed prologue');
+
+ // 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);
+ })
+ );
+ });
+ });
+
+ describe('[When] COMPOSIO_CLI_INVOCATION_ORIGIN=installer delegates shell setup', () => {
+ layer(InstallTestLive())(it => {
+ it.scoped('[Then] keeps the Updated status line but suppresses the restart hint', () =>
+ Effect.gen(function* () {
+ vi.stubEnv('SHELL', '/bin/zsh');
+ vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'installer');
+
+ yield* install();
+
+ const output = (yield* MockConsole.getLines()).join('\n');
+ expect(output).toContain('Updated ~/.zshrc');
+ expect(output).not.toContain('Restart your shell');
+ expect(output).not.toContain('source ~/.zshrc');
+ })
+ );
+ });
+ });
+
+ describe('[When] COMPOSIO_CLI_INVOCATION_ORIGIN=installer and integration is already current', () => {
+ layer(InstallTestLive())(it => {
+ it.scoped('[Then] keeps the already-current status line', () =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const fs = yield* FileSystem.FileSystem;
+ vi.stubEnv('SHELL', '/bin/zsh');
+ vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'installer');
+ const expectedBinDir = expectedRuntimeBinDir();
+
+ const rcPath = path.join(os.homedir, '.zshrc');
+ yield* fs.writeFileString(
+ rcPath,
+ `# Composio CLI\nexport PATH="${expectedBinDir}:$PATH"\n`
+ );
+
+ yield* install();
+
+ const output = (yield* MockConsole.getLines()).join('\n');
+ expect(output).toContain('Shell integration already configured');
+ expect(output).not.toContain('Restart your shell');
+ })
+ );
+ });
+ });
+
+ describe('[When] COMPOSIO_CLI_INVOCATION_ORIGIN has a non-installer value', () => {
+ layer(InstallTestLive())(it => {
+ it.scoped('[Then] the restart hint still prints', () =>
+ Effect.gen(function* () {
+ vi.stubEnv('SHELL', '/bin/zsh');
+ vi.stubEnv('COMPOSIO_CLI_INVOCATION_ORIGIN', 'agent');
+
+ yield* install();
+
+ const output = (yield* MockConsole.getLines()).join('\n');
+ expect(output).toContain('Updated ~/.zshrc');
+ expect(output).toContain('Restart your shell to apply changes');
+ expect(output).toContain('source ~/.zshrc');
})
);
});