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

refactor(cli): migrate platform access to @effect/platform services (#3880)

This PR: - activates the platform-imports rule group: `node:fs`, `node:path`, `node:os`, and `child_process` are now ESLint-banned in CLI source - migrates ~36 files to `FileSystem`/`Path`/`Command` from `@effect/platform`, introducing the `NodeOs` and `DetachedProcess` service boundaries and Effect-native run-companion module resolution - keeps the sanctioned permanent boundaries (`node-os.ts`, `detached-process.ts`, `run-subagent-output-mcp.ts`, `cli-user-config.ts`, the child-process companion runtime) on inline `-- reason` disables - files whose compliant rewrite belongs to a later slice carry temporary inline disables naming the owning PR; a small sync bridge in `run-companion-modules.ts` keeps the not-yet-migrated Promise-based callers working until the typed-error slice removes it - adds A-theme coverage: `NodeOs` platform info through Effect, session artifacts via `FileSystem` with symlink and HOME-less handling, skill-root discovery, and safe-output-path traversal guards --- **Stack** (re-slice of https://github.com/ComposioHQ/composio/pull/3859; each PR targets its parent and auto-retargets to `next` as parents merge): 1. https://github.com/ComposioHQ/composio/pull/3877 — guidelines + inert rule groups 2. https://github.com/ComposioHQ/composio/pull/3878 — `new Function()` eval security fix 3. https://github.com/ComposioHQ/composio/pull/3879 — behavioral fix pack 4. https://github.com/ComposioHQ/composio/pull/3880 — platform-imports rule + migration ← **this PR** 5. https://github.com/ComposioHQ/composio/pull/3881 — terminal-streams rule + TerminalUI boundary 6. https://github.com/ComposioHQ/composio/pull/3882 — descriptor seam + zod→Schema 7. https://github.com/ComposioHQ/composio/pull/3883 — test-tree lint + deterministic suites 8. https://github.com/ComposioHQ/composio/pull/3884 — typed error boundaries + v4 seams 9. https://github.com/ComposioHQ/composio/pull/3885 — try/catch+env ban + boundary ratchet On stacked bases CI runs lint/build and the CLI Docker e2e job; unit tests and typecheck are verified locally per PR and re-verified by full CI when each PR is retargeted to `next`. ## Review follow-up - `DetachedProcess` now waits for Node’s `spawn` or `error` event, so ENOENT/EACCES become typed failures instead of false success; focused tests cover failure and success. - the platform-import rule now rejects bare `fs`, `fs/*`, `os`, and `path` specifiers as well as their `node:` forms; the two exposed path imports now use Effect `Path`. - run-companion self-repair again honors unprefixed `GITHUB_*` values first, with `COMPOSIO_GITHUB_*` fallback and regression coverage for both contracts. Verification: CLI tests (95 files, 834 passed, 1 skipped), workspace TypeScript typecheck, scoped ESLint (0 errors), CLI build, Prettier, and `git diff --check`.

Alberto Schiabel committed Jul 21, 2026 at 11:19 UTC 4e26d36fd4b817c7691320654df1f9631c3e11af
78 files changed +3053 -1900
eslint.config.mjs
+28 -10
@@ -53,14 +53,26 @@ const cliRestrictedImportPaths = [
53 name: 'node:child_process',
54 message: 'Use Command from @effect/platform instead.',
55 },
56 + {
57 + name: 'fs',
58 + message: 'Use FileSystem from @effect/platform instead.',
59 + },
60 {
61 name: 'node:fs',
62 message: 'Use FileSystem from @effect/platform instead.',
63 },
64 + {
65 + name: 'os',
66 + message: 'Use an Effect service instead of importing node:os directly.',
67 + },
68 {
69 name: 'node:os',
70 message: 'Use an Effect service instead of importing node:os directly.',
71 },
72 + {
73 + name: 'path',
74 + message: 'Use Path from @effect/platform instead.',
75 + },
76 {
77 name: 'node:path',
78 message: 'Use Path from @effect/platform instead.',
@@ -69,7 +81,7 @@ const cliRestrictedImportPaths = [
81
82 const cliRestrictedImportPatterns = [
83 {
72 - group: ['node:fs/*'],
84 + group: ['fs/*', 'node:fs/*'],
85 message: 'Use FileSystem from @effect/platform instead.',
86 },
87 ];
@@ -174,15 +186,21 @@ export default [
186 {
187 files: ['ts/packages/cli/src/**/*.{ts,tsx}'],
188 rules: {
177 - // uncommented by the platform-imports PR of this stack (the
178 - // CommandDescriptor/Usage seam entries by the seam-rules PR).
179 - // 'no-restricted-imports': [
180 - // 'error',
181 - // {
182 - // paths: [...cliRestrictedImportPaths, ...cliDescriptorSeamRestrictedImportPaths],
183 - // patterns: [...cliRestrictedImportPatterns, ...cliDescriptorSeamRestrictedImportPatterns],
184 - // },
185 - // ],
189 + 'no-restricted-imports': [
190 + 'error',
191 + {
192 + paths: [
193 + ...cliRestrictedImportPaths,
194 + // uncommented by the seam-rules PR of this stack
195 + // ...cliDescriptorSeamRestrictedImportPaths,
196 + ],
197 + patterns: [
198 + ...cliRestrictedImportPatterns,
199 + // uncommented by the seam-rules PR of this stack
200 + // ...cliDescriptorSeamRestrictedImportPatterns,
201 + ],
202 + },
203 + ],
204 // uncommented by the terminal-streams PR of this stack (the try/catch and
205 // process.env entries by the boundary-ratchet PR).
206 // 'no-restricted-syntax': ['error', ...cliRestrictedSyntax, ...cliProcessStreamRestrictions],
ts/packages/cli/scripts/install-binary.ts
+2 -1
@@ -30,7 +30,8 @@ export function installBinary() {
30 yield* Effect.tryPromise(() => $`cp ${binaryPath} ${installDir}/composio`.quiet());
31
32 const sourceDirectory = path.dirname(path.resolve(binaryPath));
33 - const companionRelativePaths = collectExpectedRunCompanionAssetRelativePaths(sourceDirectory);
33 + const companionRelativePaths =
34 + yield* collectExpectedRunCompanionAssetRelativePaths(sourceDirectory);
35
36 for (const relativePath of companionRelativePaths) {
37 const sourcePath = path.join(sourceDirectory, relativePath);
ts/packages/cli/scripts/package-binaries.ts
+2 -1
@@ -50,7 +50,8 @@ export function packageBinaries() {
50 return;
51 }
52
53 - const companionRelativePaths = collectExpectedRunCompanionAssetRelativePaths(COMPANIONS_DIR);
53 + const companionRelativePaths =
54 + yield* collectExpectedRunCompanionAssetRelativePaths(COMPANIONS_DIR);
55 for (const relativePath of companionRelativePaths) {
56 const companionPath = path.join(COMPANIONS_DIR, relativePath);
57 const exists = yield* Effect.tryPromise(() => Bun.file(companionPath).exists());
ts/packages/cli/src/analytics/dispatch.ts
+4
@@ -1,7 +1,11 @@
1 +// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
2 import fs from 'node:fs';
3 +// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
4 import os from 'node:os';
5 +// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
6 import path from 'node:path';
7 import process from 'node:process';
8 +// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
9 import { spawn } from 'node:child_process';
10 import { Effect } from 'effect';
11 import type { AnalyticsEnvelope, TrackEvent } from './types';
ts/packages/cli/src/cli-main.ts
+9 -8
@@ -49,22 +49,22 @@ export const CliConfigLive = CliConfig.layer(ComposioCliConfig) satisfies Requir
49
50 export const ComposioUserContextLive = Layer.provide(
51 _ComposioUserContextLive,
52 - Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
52 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
53 ) satisfies RequiredLayer;
54
55 export const ComposioCliUserConfigLayer = Layer.provide(
56 ComposioCliUserConfigLive,
57 - Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
57 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
58 );
59
60 export const ComposioSessionRepositoryLive = Layer.provide(
61 ComposioSessionRepository.Default,
62 - Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
62 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
63 ) satisfies RequiredLayer;
64
65 export const ComposioToolkitsRepositoryLive = Layer.provide(
66 ComposioToolkitsRepository.Default,
67 - Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, ConfigLive)
67 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, ConfigLive)
68 ) satisfies RequiredLayer;
69
70 export const ComposioToolkitsRepositoryCachedLive = Layer.provide(
@@ -74,17 +74,17 @@ export const ComposioToolkitsRepositoryCachedLive = Layer.provide(
74
75 export const UpgradeBinaryLive = Layer.provide(
76 UpgradeBinary.Default,
77 - Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer)
77 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, FetchHttpClient.layer)
78 ) satisfies RequiredLayer;
79
80 export const TriggersRealtimeLive = Layer.provide(
81 TriggersRealtime.Default,
82 - Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
82 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
83 ) satisfies RequiredLayer;
84
85 export const ComposioClientSingletonLive = Layer.provide(
86 ComposioClientSingleton.Default,
87 - Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, ConfigLive)
87 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, ConfigLive)
88 ) satisfies RequiredLayer;
89
90 export const ToolsExecutorLive = Layer.provide(
@@ -94,7 +94,7 @@ export const ToolsExecutorLive = Layer.provide(
94
95 export const ProjectContextLive = Layer.provide(
96 ProjectContext.Default,
97 - Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, NodeProcess.Default)
97 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, NodeProcess.Default)
98 ) satisfies RequiredLayer;
99
100 export const SetupSkillInstallerLive = Layer.provide(
@@ -121,6 +121,7 @@ const layers = Layer.mergeAll(
121 ProjectContextLive,
122 BunContext.layer,
123 BunFileSystem.layer,
124 + BunPath.layer,
125 FetchHttpClient.layer,
126 StdinLive,
127 TerminalUILive,
ts/packages/cli/src/commands/artifacts.cmd.ts
+3 -4
@@ -11,10 +11,9 @@ const cwdCmd = Command.make('cwd').pipe(
11 Command.withHandler(() =>
12 Effect.gen(function* () {
13 const artifacts = yield* resolveCliSessionArtifacts();
14 - const directoryPath = Option.match(artifacts, {
15 - onNone: () => resolveArtifactsRoot(),
16 - onSome: value => value.directoryPath,
17 - });
14 + const directoryPath = Option.isSome(artifacts)
15 + ? artifacts.value.directoryPath
16 + : yield* resolveArtifactsRoot;
17 process.stdout.write(`${directoryPath}\n`);
18 })
19 )
ts/packages/cli/src/commands/config/config.experimental.cmd.ts
+23 -68
@@ -1,15 +1,14 @@
1 -import * as fs from 'node:fs';
2 -import * as path from 'node:path';
3 -import { Command, Args } from '@effect/cli';
1 +import { Args, Command, HelpDoc, ValidationError } from '@effect/cli';
2 import { Effect, Option } from 'effect';
3 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { NodeOs } from 'src/services/node-os';
6 import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
7 +import { discoverSkillRoots } from 'src/effects/discover-skill-roots';
8 import { buildComposioCliSkill } from '../../../skills-src/composio-cli/index';
9 import type { SkillFeatureFlag } from '../../../skills-src/composio-cli/reference-schema';
10
12 -const knownFeatures: readonly string[] = Object.values(CLI_EXPERIMENTAL_FEATURES);
11 +const knownFeatures: ReadonlyArray<SkillFeatureFlag> = Object.values(CLI_EXPERIMENTAL_FEATURES);
12
13 const featureArg = Args.text({ name: 'feature' }).pipe(
14 Args.withDescription(`Experimental feature name. Known features: ${knownFeatures.join(', ')}`),
@@ -21,55 +20,6 @@ const stateArg = Args.text({ name: 'state' }).pipe(
20 Args.optional
21 );
22
24 -const SKILL_NAME = 'composio-cli';
25 -
26 -/**
27 - * Find every directory where the composio-cli skill is currently installed.
28 - * Known locations:
29 - * ~/.agents/skills/composio-cli (canonical install target)
30 - * ~/.claude/skills/composio-cli (Claude Code — may be a symlink or a real dir)
31 - *
32 - * We resolve symlinks so we don't rebuild the same physical directory twice,
33 - * but we also rebuild any real (non-symlink) copies so everything stays in sync.
34 - */
35 -const discoverSkillRoots = (home: string): string[] => {
36 - const candidates = [path.join(home, '.agents', 'skills'), path.join(home, '.claude', 'skills')];
37 -
38 - const seen = new Set<string>();
39 - const roots: string[] = [];
40 -
41 - for (const parent of candidates) {
42 - const skillDir = path.join(parent, SKILL_NAME);
43 - try {
44 - const stat = fs.lstatSync(skillDir);
45 - if (stat.isSymbolicLink()) {
46 - // Resolve the symlink target — we'll rebuild the real directory it points to
47 - const realDir = fs.realpathSync(skillDir);
48 - const realParent = path.dirname(realDir);
49 - if (!seen.has(realParent)) {
50 - seen.add(realParent);
51 - roots.push(realParent);
52 - }
53 - } else if (stat.isDirectory()) {
54 - if (!seen.has(parent)) {
55 - seen.add(parent);
56 - roots.push(parent);
57 - }
58 - }
59 - } catch {
60 - // Directory doesn't exist — skip
61 - }
62 - }
63 -
64 - // Always include ~/.agents/skills as a fallback so there's at least one target
65 - const agentSkillsRoot = path.join(home, '.agents', 'skills');
66 - if (!seen.has(agentSkillsRoot)) {
67 - roots.push(agentSkillsRoot);
68 - }
69 -
70 - return roots;
71 -};
72 -
23 const rebuildSkill = Effect.gen(function* () {
24 const ui = yield* TerminalUI;
25 const os = yield* NodeOs;
@@ -79,16 +29,18 @@ const rebuildSkill = Effect.gen(function* () {
29 // Build the feature overrides from the current config
30 const featureOverrides: Partial<Record<SkillFeatureFlag, boolean>> = {};
31 for (const name of knownFeatures) {
82 - featureOverrides[name as SkillFeatureFlag] = cliConfig.isExperimentalFeatureEnabled(name);
32 + featureOverrides[name] = cliConfig.isExperimentalFeatureEnabled(name);
33 }
34
85 - const roots = discoverSkillRoots(home);
35 + const roots = yield* discoverSkillRoots(home);
36 for (const root of roots) {
87 - buildComposioCliSkill({
88 - channel: cliConfig.channel,
89 - outputRoot: root,
90 - featureOverrides,
91 - });
37 + yield* Effect.try(() =>
38 + buildComposioCliSkill({
39 + channel: cliConfig.channel,
40 + outputRoot: root,
41 + featureOverrides,
42 + })
43 + );
44 }
45
46 yield* ui.log.step(
@@ -119,7 +71,7 @@ export const configExperimentalCmd = Command.make(
71
72 // Show any custom features not in the known list
73 for (const [name, value] of Object.entries(features)) {
122 - if (!knownFeatures.includes(name)) {
74 + if (!knownFeatures.some(feature => feature === name)) {
75 lines.push(` ${name}: ${value ? 'on' : 'off'}`);
76 }
77 }
@@ -146,7 +98,9 @@ export const configExperimentalCmd = Command.make(
98 const stateValue = state.value.toLowerCase();
99 if (stateValue !== 'on' && stateValue !== 'off') {
100 yield* ui.log.error(`Invalid state "${state.value}". Use "on" or "off".`);
149 - return yield* Effect.fail(new Error(`Invalid state: ${state.value}`));
101 + return yield* Effect.fail(
102 + ValidationError.invalidValue(HelpDoc.p(`Invalid state: ${state.value}`))
103 + );
104 }
105
106 const enabled = stateValue === 'on';
@@ -161,12 +115,13 @@ export const configExperimentalCmd = Command.make(
115
116 // Rebuild the skill so Claude Code picks up the new feature flags
117 yield* rebuildSkill.pipe(
164 - Effect.catchAll(error =>
165 - Effect.gen(function* () {
166 - yield* Effect.logDebug('Skill rebuild failed:', error);
167 - yield* ui.log.warn('Could not rebuild skill (non-fatal)');
168 - })
169 - )
118 + Effect.tapError(error =>
119 + Effect.all([
120 + Effect.logDebug('Skill rebuild failed:', error),
121 + ui.log.warn('Could not rebuild skill (non-fatal)'),
122 + ])
123 + ),
124 + Effect.ignore
125 );
126
127 yield* ui.output(stateValue);
ts/packages/cli/src/commands/dev/dev.native-ui.cmd.ts
+22 -13
@@ -1,10 +1,15 @@
1 import { Command, Options } from '@effect/cli';
2 -import { Effect, Option } from 'effect';
3 -import { spawn } from 'node:child_process';
2 +import { Data, Effect, Option, Predicate } from 'effect';
3 import { ensureBundledBinaryExecutable } from '@composio/cli-local-tools';
4 +import { spawnDetached } from 'src/services/detached-process';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 import { resolveNativeUiBinary } from 'src/services/native-ui-sidecar';
7
8 +class NativeUiSetupError extends Data.TaggedError('commands/NativeUiSetupError')<{
9 + readonly message: string;
10 + readonly cause: unknown;
11 +}> {}
12 +
13 const title = Options.text('title').pipe(
14 Options.withDefault('Composio'),
15 Options.withDescription('Title for the native sidecar window.')
@@ -29,16 +34,16 @@ export const devNativeUiCmd = Command.make('native-ui', { title, message, detail
34 Command.withHandler(({ title, message, detail, timeout }) =>
35 Effect.gen(function* () {
36 const ui = yield* TerminalUI;
32 - const resolved = resolveNativeUiBinary();
37 + const resolved = yield* resolveNativeUiBinary;
38
34 - if (resolved._tag === 'unsupported') {
39 + if (Predicate.isTagged(resolved, 'unsupported')) {
40 yield* ui.log.error(
41 `The native UI sidecar is currently only available on macOS (detected ${resolved.platform}).`
42 );
43 return;
44 }
45
41 - if (resolved._tag === 'missing') {
46 + if (Predicate.isTagged(resolved, 'missing')) {
47 yield* ui.log.error('The native UI sidecar binary was not found.');
48 yield* ui.log.step(
49 `Build it with: pnpm --filter @composio/cli-local-tools build:composio-native-ui -- --target ${resolved.platform}`
@@ -47,7 +52,14 @@ export const devNativeUiCmd = Command.make('native-ui', { title, message, detail
52 return;
53 }
54
50 - yield* Effect.tryPromise(() => ensureBundledBinaryExecutable(resolved.binaryPath));
55 + yield* Effect.tryPromise({
56 + try: () => ensureBundledBinaryExecutable(resolved.binaryPath),
57 + catch: cause =>
58 + new NativeUiSetupError({
59 + message: `Failed to make the native UI sidecar binary executable: ${resolved.binaryPath}`,
60 + cause,
61 + }),
62 + });
63
64 const args = ['--title', title, '--message', message, '--detail', detail];
65 const timeoutValue = Option.getOrUndefined(timeout)?.trim();
@@ -55,13 +67,10 @@ export const devNativeUiCmd = Command.make('native-ui', { title, message, detail
67 args.push('--timeout', timeoutValue);
68 }
69
58 - yield* Effect.sync(() => {
59 - const child = spawn(resolved.binaryPath, args, {
60 - detached: true,
61 - stdio: 'ignore',
62 - });
63 - child.unref();
64 - });
70 + // The sidecar window must outlive the CLI process, so it goes through
71 + // the sanctioned detached-spawn boundary instead of @effect/platform
72 + // Command (whose processes are killed when their scope closes).
73 + yield* spawnDetached(resolved.binaryPath, args);
74
75 yield* ui.log.success('Opened native UI sidecar.');
76 })
ts/packages/cli/src/commands/init.cmd.ts
+5 -2
@@ -1,7 +1,6 @@
1 -import path from 'node:path';
1 import { Command as CliCommand, Options } from '@effect/cli';
2 import { Effect, Option } from 'effect';
4 -import { FileSystem } from '@effect/platform';
3 +import { FileSystem, Path } from '@effect/platform';
4 import { ComposioUserContext } from 'src/services/user-context';
5 import { NodeProcess } from 'src/services/node-process';
6 import { projectKeysToJSON, type ProjectKeys } from 'src/models/project-keys';
@@ -43,6 +42,7 @@ const yesOpt = Options.boolean('yes').pipe(
42 const writeProjectConfig = (composioDir: string, selected: ProjectKeys) =>
43 Effect.gen(function* () {
44 const fs = yield* FileSystem.FileSystem;
45 + const path = yield* Path.Path;
46
47 yield* fs
48 .makeDirectory(composioDir, { recursive: true })
@@ -76,6 +76,7 @@ const makeOutputJson = (selected: ProjectKeys, composioDir: string) =>
76 const getGlobalUserApiKey = () =>
77 Effect.gen(function* () {
78 const fs = yield* FileSystem.FileSystem;
79 + const path = yield* Path.Path;
80 const cacheDir = yield* setupCacheDir;
81 const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
82 const exists = yield* fs.exists(userConfigPath);
@@ -103,6 +104,7 @@ const ensureProjectApiKeyInEnv = (params: { cwd: string; selected: ProjectKeys }
104 const { cwd, selected } = params;
105 const ui = yield* TerminalUI;
106 const fs = yield* FileSystem.FileSystem;
107 + const path = yield* Path.Path;
108 const ctx = yield* ComposioUserContext;
109
110 const envPath = path.join(cwd, '.env.local');
@@ -229,6 +231,7 @@ export const initCmd = CliCommand.make(
231 Effect.gen(function* () {
232 const ui = yield* TerminalUI;
233 const proc = yield* NodeProcess;
234 + const path = yield* Path.Path;
235
236 yield* ui.intro('composio dev init');
237
ts/packages/cli/src/commands/install.cmd.ts
+9 -8
@@ -1,7 +1,6 @@
1 -import path from 'node:path';
1 import process from 'node:process';
2 import { Command, Options } from '@effect/cli';
4 -import { FileSystem } from '@effect/platform';
3 +import { FileSystem, Path } from '@effect/platform';
4 import type { PlatformError } from '@effect/platform/Error';
5 import { Array as Arr, Effect } from 'effect';
6 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
@@ -48,7 +47,7 @@ const COMPLETIONS_MARKER = '# Composio CLI completions';
47 const UNSAFE_PATH_CHARS = /[;`$|&"'()\n\r\\]/;
48 const isUnsafePath = (p: string): boolean => UNSAFE_PATH_CHARS.test(p);
49
51 -const detectShell = (): Shell | undefined => {
50 +const detectShell = (path: Path.Path): Shell | undefined => {
51 const shellEnv = process.env.SHELL ?? '';
52 const base = path.basename(shellEnv);
53 if (base === 'zsh') return 'zsh';
@@ -61,7 +60,7 @@ const detectShell = (): Shell | undefined => {
60 * Return candidate rc file paths for a shell, ordered by preference.
61 * For bash this mirrors the install.sh fallback: .bashrc then .bash_profile.
62 */
64 -const rcFileCandidates = (shell: Shell, homedir: string): string[] => {
63 +const rcFileCandidates = (path: Path.Path, shell: Shell, homedir: string): string[] => {
64 switch (shell) {
65 case 'zsh':
66 return [path.join(homedir, '.zshrc')];
@@ -106,6 +105,7 @@ const pathBlockForShell = (shell: Shell, installDir: string): string => {
105 };
106
107 const buildShellConfig = (
108 + path: Path.Path,
109 shell: Shell,
110 rcFile: string,
111 installDir: string,
@@ -150,12 +150,13 @@ export const installShellIntegration = (params: {
150 }): Effect.Effect<
151 void,
152 PlatformError,
153 - TerminalUI | NodeOs | FileSystem.FileSystem | ComposioCliUserConfig
153 + TerminalUI | NodeOs | FileSystem.FileSystem | Path.Path | ComposioCliUserConfig
154 > =>
155 Effect.gen(function* () {
156 const ui = yield* TerminalUI;
157 const os = yield* NodeOs;
158 const fs = yield* FileSystem.FileSystem;
159 + const path = yield* Path.Path;
160
161 yield* ui.intro('composio install');
162
@@ -171,7 +172,7 @@ export const installShellIntegration = (params: {
172 }
173
174 // Detect user shell
174 - const shell = detectShell();
175 + const shell = detectShell(path);
176 if (!shell) {
177 yield* ui.log.warn(
178 'Could not detect your shell. Manually add the following to your shell config:'
@@ -204,8 +205,8 @@ export const installShellIntegration = (params: {
205 completionScript = lines.length > 0 ? Arr.join(lines, '\n') : undefined;
206 }
207
207 - const rcFile = yield* resolveRcFile(rcFileCandidates(shell, os.homedir), fs);
208 - const config = buildShellConfig(shell, rcFile, installDir, completionScript, os.homedir);
208 + const rcFile = yield* resolveRcFile(rcFileCandidates(path, shell, os.homedir), fs);
209 + const config = buildShellConfig(path, shell, rcFile, installDir, completionScript, os.homedir);
210
211 const uniqueTargetFiles = [...new Set([config.pathFile, config.completionFile])];
212 const existingByFile = new Map<string, string>();
ts/packages/cli/src/commands/listen.cmd.ts
+5 -8
@@ -1,8 +1,7 @@
1 import { Args, Command, Options } from '@effect/cli';
2 -import { FileSystem } from '@effect/platform';
2 +import { FileSystem, Path } from '@effect/platform';
3 import type { Composio as RawComposioClient } from '@composio/client';
4 import { Deferred, Effect, Either, Option, Runtime } from 'effect';
5 -import path from 'node:path';
5 import { requireAuth } from 'src/effects/require-auth';
6 import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
7 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -181,8 +180,6 @@ const extractEventFileId = (eventData: Record<string, unknown>): string => {
180 return `${Date.now()}-${crypto.randomUUID().slice(0, 8)}`;
181 };
182
184 -const resolveFallbackArtifactsDir = () => resolveArtifactsRoot();
185 -
183 const parseStreamPath = (expression: string): ReadonlyArray<string | number> => {
184 const trimmed = expression.trim();
185 if (!trimmed.startsWith('.')) {
@@ -379,6 +376,7 @@ export const listenCmd = Command.make(
376
377 const ui = yield* TerminalUI;
378 const fs = yield* FileSystem.FileSystem;
379 + const path = yield* Path.Path;
380 const runtime = yield* Effect.runtime<never>();
381 const clientSingleton = yield* ComposioClientSingleton;
382 const realtime = yield* TriggersRealtime;
@@ -420,10 +418,9 @@ export const listenCmd = Command.make(
418 orgId: resolvedProject.orgId,
419 consumerUserId,
420 });
423 - const artifactsRoot = Option.match(artifactsOption, {
424 - onNone: () => resolveFallbackArtifactsDir(),
425 - onSome: value => value.directoryPath,
426 - });
421 + const artifactsRoot = Option.isSome(artifactsOption)
422 + ? artifactsOption.value.directoryPath
423 + : yield* resolveArtifactsRoot;
424 const triggerDir = path.join(
425 artifactsRoot,
426 listeningToProjectEvent ? 'events' : 'triggers',
ts/packages/cli/src/commands/login.cmd.ts
+1
@@ -1,3 +1,4 @@
1 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
2 import path from 'node:path';
3 import { Command, Options } from '@effect/cli';
4 import { FileSystem } from '@effect/platform';
ts/packages/cli/src/commands/py/commands/py.generate.cmd.ts
+1
@@ -1,3 +1,4 @@
1 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
2 import path from 'node:path';
3 import { Command, Options } from '@effect/cli';
4 import { pipe, Effect, Option, Array } from 'effect';
ts/packages/cli/src/commands/run.cmd.ts
+33 -29
@@ -1,9 +1,11 @@
1 +// eslint-disable-next-line no-restricted-imports -- synchronous fs (mkdtempSync/writeFileSync/rmSync/existsSync) builds and tears down the run preload files in plain helpers that execute outside the Effect runtime
2 import * as fs from 'node:fs';
3 +// eslint-disable-next-line no-restricted-imports -- os.tmpdir and os.homedir locate the preload scratch directory and ~/.composio in the same synchronous helpers
4 import * as os from 'node:os';
3 -import * as path from 'node:path';
5 import process from 'node:process';
6 import { pathToFileURL } from 'node:url';
7 import { Args, Command, Options } from '@effect/cli';
8 +import { FileSystem, Path } from '@effect/platform';
9 import { Effect, Option } from 'effect';
10 import { ts } from 'ts-morph';
11 import { APP_VERSION } from 'src/constants';
@@ -147,6 +149,7 @@ export const wrapFileSourceForRun = (source: string): string => {
149 };
150
151 export const inferCliInvocationPrefix = (
152 + path: Path.Path,
153 argv: ReadonlyArray<string> = process.argv
154 ): ReadonlyArray<string> => {
155 const entrypoint = argv[1];
@@ -171,19 +174,22 @@ type RunHelperModuleUrls = {
174 readonly helpersRuntimeModuleUrl: string;
175 };
176
174 -const resolveRunHelperModuleUrls = (): RunHelperModuleUrls => ({
175 - helpersRuntimeModuleUrl: pathToFileURL(
176 - resolveRunCompanionModulePath({
177 - callerImportMetaUrl: import.meta.url,
178 - execPath: process.execPath,
179 - relativeNoExtensionFromCaller: '../services/run-helpers-runtime',
180 - })
181 - ).href,
182 -});
177 +const resolveRunHelperModuleUrls: Effect.Effect<
178 + RunHelperModuleUrls,
179 + never,
180 + FileSystem.FileSystem | Path.Path
181 +> = Effect.map(
182 + resolveRunCompanionModulePath({
183 + callerImportMetaUrl: import.meta.url,
184 + execPath: process.execPath,
185 + relativeNoExtensionFromCaller: '../services/run-helpers-runtime',
186 + }),
187 + modulePath => ({ helpersRuntimeModuleUrl: pathToFileURL(modulePath).href })
188 +);
189 export const buildRunHelpersSource = (
190 cliPrefix: ReadonlyArray<string>,
191 context: RunHelperContext = {},
186 - moduleUrls: RunHelperModuleUrls = resolveRunHelperModuleUrls()
192 + moduleUrls: RunHelperModuleUrls
193 ): string =>
194 [
195 `import { installRunHelpers } from ${JSON.stringify(moduleUrls.helpersRuntimeModuleUrl)};`,
@@ -192,6 +198,7 @@ export const buildRunHelpersSource = (
198 ].join('\n');
199
200 const createRunHelpersPreloadFile = (
201 + path: Path.Path,
202 cliPrefix: ReadonlyArray<string>,
203 context: RunHelperContext,
204 moduleUrls: RunHelperModuleUrls
@@ -231,11 +238,13 @@ const createRunHelpersPreloadFile = (
238 };
239
240 export const buildRunCommand = ({
241 + path,
242 file,
243 args,
244 preloadPath,
245 preloadDirectory,
246 }: {
247 + path: Path.Path;
248 file: Option.Option<string>;
249 args: ReadonlyArray<string>;
250 preloadPath: string;
@@ -285,6 +294,7 @@ export const buildRunCommand = ({
294
295 const resolveRunHelperContext = () =>
296 Effect.gen(function* () {
297 + const path = yield* Path.Path;
298 const userContext = yield* ComposioUserContext;
299 const apiKey = Option.getOrUndefined(userContext.data.apiKey);
300 const orgId = Option.getOrUndefined(userContext.data.orgId);
@@ -417,6 +427,7 @@ export const runCmd = Command.make('run', {
427 args,
428 }) =>
429 Effect.gen(function* () {
430 + const path = yield* Path.Path;
431 const runId = process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID();
432 const perfDebug = isPerfDebugEnabled();
433 const toolDebug = isToolDebugEnabled();
@@ -446,25 +457,17 @@ export const runCmd = Command.make('run', {
457 skipToolParamsCheck,
458 skipChecks,
459 };
449 - const runHelperModuleUrls = yield* Effect.tryPromise({
450 - try: async () => {
451 - await repairMissingInstalledRunCompanionModules({
452 - callerImportMetaUrl: import.meta.url,
453 - execPath: process.execPath,
454 - appVersion: APP_VERSION,
455 - });
456 -
457 - return resolveRunHelperModuleUrls();
458 - },
459 - catch: error =>
460 - new Error(
461 - error instanceof Error
462 - ? error.message
463 - : `Failed to prepare the modules required by 'composio run': ${String(error)}`
464 - ),
465 - });
460 + const runHelperModuleUrls = yield* repairMissingInstalledRunCompanionModules({
461 + callerImportMetaUrl: import.meta.url,
462 + execPath: process.execPath,
463 + appVersion: APP_VERSION,
464 + }).pipe(
465 + Effect.mapError(error => new Error(error.message)),
466 + Effect.andThen(resolveRunHelperModuleUrls)
467 + );
468 const preload = createRunHelpersPreloadFile(
467 - inferCliInvocationPrefix(),
469 + path,
470 + inferCliInvocationPrefix(path),
471 helperContext,
472 runHelperModuleUrls
473 );
@@ -483,6 +486,7 @@ export const runCmd = Command.make('run', {
486 }).pipe(Effect.catchAll(() => Effect.void));
487 process.stderr.write(`RUN_LOG_FILE=${preload.runLogFilePath}\n`);
488 const runCommand = buildRunCommand({
489 + path,
490 file,
491 args,
492 preloadPath: preload.preloadPath,
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+2 -2
@@ -1,7 +1,6 @@
1 import { Command, Options } from '@effect/cli';
2 -import { FileSystem } from '@effect/platform';
2 +import { FileSystem, Path } from '@effect/platform';
3 import { Deferred, Effect, Option, Runtime } from 'effect';
4 -import path from 'node:path';
4 import { requireAuth } from 'src/effects/require-auth';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 import { TriggersRealtime } from 'src/services/triggers-realtime';
@@ -180,6 +179,7 @@ export const triggersCmd$Listen = Command.make(
179 Effect.mapError(formatResolveCommandProjectError)
180 );
181 const fs = yield* FileSystem.FileSystem;
182 + const path = yield* Path.Path;
183 const realtime = yield* TriggersRealtime;
184 const runtime = yield* Effect.runtime<never>();
185 const forwardUrl = Option.getOrUndefined(forward);
ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts
+2 -2
@@ -15,6 +15,7 @@
15 * and stored along with the generated TypeScript files. CJS is not supported.
16 */
17
18 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
19 import path from 'node:path';
20 import { Command, Options } from '@effect/cli';
21 import { Effect, Option, pipe, Array } from 'effect';
@@ -96,8 +97,7 @@ type FetchResult = {
97 toolkits: ReadonlyArray<Toolkit>;
98 triggerTypes: ReadonlyArray<TriggerType>;
99 typeableTools:
99 - | { withTypes: true; tools: ReadonlyArray<Tool> }
100 - | { withTypes: false; tools: ToolsAsEnums };
100 + { withTypes: true; tools: ReadonlyArray<Tool> } | { withTypes: false; tools: ToolsAsEnums };
101 /** Map of lowercase toolkit slug to version (only includes non-'latest' versions) */
102 versionMap: ToolkitVersionOverrides;
103 };
ts/packages/cli/src/effect-errors/capture-errors.ts
+2 -1
@@ -1,5 +1,6 @@
1 import type { PlatformError } from '@effect/platform/Error';
2 import type { FileSystem } from '@effect/platform/FileSystem';
3 +import type { Path } from '@effect/platform/Path';
4 import { Effect } from 'effect';
5 import { type Cause, isInterruptedOnly } from 'effect/Cause';
6
@@ -36,7 +37,7 @@ export const captureErrors = <E>(
37 options: CaptureErrorsOptions = {
38 stripCwd: true,
39 }
39 -): Effect.Effect<CapturedErrors, PlatformError | JsonParsingError, FileSystem> =>
40 +): Effect.Effect<CapturedErrors, PlatformError | JsonParsingError, FileSystem | Path> =>
41 Effect.gen(function* () {
42 if (isInterruptedOnly(cause)) {
43 return {
ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts
+2 -1
@@ -1,5 +1,6 @@
1 import type { PlatformError } from '@effect/platform/Error';
2 import type { FileSystem } from '@effect/platform/FileSystem';
3 +import type { Path } from '@effect/platform/Path';
4 import { Effect } from 'effect';
5
6 import type { JsonParsingError } from 'effect-errors/dependencies/fs';
@@ -18,7 +19,7 @@ export const getErrorRelatedSources = (
19 ): Effect.Effect<
20 ErrorRelatedSources | RawErrorLocation | undefined,
21 PlatformError | JsonParsingError,
21 - FileSystem
22 + FileSystem | Path
23 > =>
24 Effect.gen(function* () {
25 const location = getErrorLocationFrom(sourceFile);
ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts
+3 -3
@@ -1,7 +1,6 @@
1 -import path from 'node:path';
2 -
1 import type { PlatformError } from '@effect/platform/Error';
2 import { FileSystem } from '@effect/platform/FileSystem';
3 +import { Path } from '@effect/platform/Path';
4 import { Effect, pipe } from 'effect';
5 import { type RawSourceMap, SourceMapConsumer } from 'source-map-js';
6
@@ -29,11 +28,12 @@ export const getSourcesFromMapFile = (
28 ): Effect.Effect<
29 ErrorRelatedSources | RawErrorLocation | undefined,
30 PlatformError | JsonParsingError,
32 - FileSystem
31 + FileSystem | Path
32 > =>
33 pipe(
34 Effect.gen(function* () {
35 const fs = yield* FileSystem;
36 + const path = yield* Path;
37 const fileExists = yield* fs.exists(`${location.filePath}.map`);
38 if (!fileExists) {
39 return {
ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts
+13 -10
@@ -1,10 +1,14 @@
1 -import { Effect, Option, pipe } from 'effect';
1 +import { Effect, Option, Predicate, pipe } from 'effect';
2 import type { AnySpan, Span } from 'effect/Tracer';
3
4 import { splitSpansAttributesByTypes } from 'effect-errors/logic/spans';
5
6 import type { ErrorRelatedSources, RawErrorLocation } from './get-sources-from-map-file';
7 -import { maybeMapSourcemaps } from './maybe-map-sourcemaps';
7 +import {
8 + isErrorRelatedSources,
9 + isRawErrorLocation,
10 + maybeMapSourcemaps,
11 +} from './maybe-map-sourcemaps';
12
13 export const getSourcesFromSpan = ({
14 span,
@@ -28,25 +32,24 @@ export const getSourcesFromSpan = ({
32 const spans = [];
33
34 let current: Span | AnySpan | undefined = span;
31 - while (current !== undefined && current._tag === 'Span') {
35 + while (current !== undefined && Predicate.isTagged(current, 'Span')) {
36 const { name, attributes: allAttributes, status } = current;
37
38 const { attributes, stacktrace } = splitSpansAttributesByTypes(allAttributes);
39
40 const sourcesOrLocation = yield* maybeMapSourcemaps(name, stacktrace);
37 - const duration =
38 - status._tag === 'Ended'
39 - ? +`${(status.endTime - status.startTime) / BigInt(1000000)}`
40 - : undefined;
41 + const duration = Predicate.isTagged(status, 'Ended')
42 + ? +`${(status.endTime - status.startTime) / BigInt(1000000)}`
43 + : undefined;
44
42 - sources.push(...sourcesOrLocation.filter(el => el._tag === 'sources'));
43 - location.push(...sourcesOrLocation.filter(el => el._tag === 'location'));
45 + sources.push(...sourcesOrLocation.filter(isErrorRelatedSources));
46 + location.push(...sourcesOrLocation.filter(isRawErrorLocation));
47 spans.push({
48 name,
49 attributes: Object.fromEntries(attributes),
50 durationInMilliseconds: duration,
51 startTime: status.startTime,
49 - endTime: status._tag === 'Ended' ? status.endTime : undefined,
52 + endTime: Predicate.isTagged(status, 'Ended') ? status.endTime : undefined,
53 });
54
55 current = Option.getOrUndefined(current.parent);
ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-stack.ts
+7 -3
@@ -2,7 +2,11 @@ import { Effect, pipe } from 'effect';
2
3 import { removeNodeModulesEntriesFromStack } from 'effect-errors/logic/spans';
4
5 -import { maybeMapSourcemaps } from './maybe-map-sourcemaps';
5 +import {
6 + isErrorRelatedSources,
7 + isRawErrorLocation,
8 + maybeMapSourcemaps,
9 +} from './maybe-map-sourcemaps';
10
11 export const getSourcesFromStack = (maybeStack: string | undefined) =>
12 pipe(
@@ -18,8 +22,8 @@ export const getSourcesFromStack = (maybeStack: string | undefined) =>
22 const sourcesOrLocation = yield* maybeMapSourcemaps('', relevantStackEntries);
23
24 return {
21 - sources: sourcesOrLocation.filter(el => el._tag === 'sources'),
22 - location: sourcesOrLocation.filter(el => el._tag === 'location'),
25 + sources: sourcesOrLocation.filter(isErrorRelatedSources),
26 + location: sourcesOrLocation.filter(isRawErrorLocation),
27 };
28 }),
29 Effect.withSpan('get-sources-from-stack')
ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts
+10 -3
@@ -1,6 +1,7 @@
1 import type { PlatformError } from '@effect/platform/Error';
2 import type { FileSystem } from '@effect/platform/FileSystem';
3 -import { Effect, pipe } from 'effect';
3 +import type { Path } from '@effect/platform/Path';
4 +import { Effect, Predicate, pipe } from 'effect';
5
6 import type { JsonParsingError } from 'effect-errors/dependencies/fs';
7 import { stackAtRegex } from 'effect-errors/logic/stack';
@@ -15,10 +16,16 @@ export type StackEntry = {
16
17 export type MaybeMappedSources = ErrorRelatedSources | RawErrorLocation | StackEntry;
18
19 +export const isErrorRelatedSources = (value: MaybeMappedSources): value is ErrorRelatedSources =>
20 + Predicate.isTagged(value, 'sources');
21 +
22 +export const isRawErrorLocation = (value: MaybeMappedSources): value is RawErrorLocation =>
23 + Predicate.isTagged(value, 'location');
24 +
25 export const maybeMapSourcemaps = (
26 name: string,
27 stacktrace: string[]
21 -): Effect.Effect<MaybeMappedSources[], PlatformError | JsonParsingError, FileSystem> =>
28 +): Effect.Effect<MaybeMappedSources[], PlatformError | JsonParsingError, FileSystem | Path> =>
29 pipe(
30 Effect.forEach(stacktrace, stackLine =>
31 Effect.gen(function* () {
@@ -33,7 +40,7 @@ export const maybeMapSourcemaps = (
40 runPath: stackLine.replaceAll(stackAtRegex, 'at '),
41 };
42 }
36 - if (details._tag === 'location') {
43 + if (isRawErrorLocation(details)) {
44 return details;
45 }
46
ts/packages/cli/src/effects/core-dependency.ts
+5 -5
@@ -1,5 +1,4 @@
1 -import path from 'node:path';
2 -import { Command, FileSystem } from '@effect/platform';
1 +import { Command, FileSystem, Path } from '@effect/platform';
2 import { Effect, Match } from 'effect';
3 import {
4 ProjectEnvironmentDetector,
@@ -71,7 +70,7 @@ export const detectCoreDependencyPlan = (cwd: string) =>
70 } satisfies CoreDependencyPlan;
71 });
72
74 -const readPackageJson = (fs: FileSystem.FileSystem, dir: string) =>
73 +const readPackageJson = (fs: FileSystem.FileSystem, path: Path.Path, dir: string) =>
74 fs.readFileString(path.join(dir, 'package.json')).pipe(
75 Effect.andThen(content =>
76 Effect.try({
@@ -96,7 +95,8 @@ const detectJsDependencyVersion = (
95 plan: Extract<CoreDependencyPlan, { kind: 'js' }>
96 ) =>
97 Effect.gen(function* () {
99 - const dirs = getAncestors(plan.rootDir);
98 + const path = yield* Path.Path;
99 + const dirs = yield* getAncestors(plan.rootDir);
100
101 for (const dir of dirs) {
102 const packageJsonPath = path.join(dir, 'node_modules', '@composio', 'core', 'package.json');
@@ -156,7 +156,7 @@ const detectJsDependencyVersion = (
156 }
157
158 for (const dir of dirs) {
159 - const pkg = yield* readPackageJson(fs, dir);
159 + const pkg = yield* readPackageJson(fs, path, dir);
160 if (!pkg) {
161 continue;
162 }
ts/packages/cli/src/effects/discover-skill-roots.ts new
+52
@@ -0,0 +1,52 @@
1 +import { FileSystem, Path } from '@effect/platform';
2 +import { Effect, Option } from 'effect';
3 +
4 +const SKILL_NAME = 'composio-cli';
5 +
6 +/**
7 + * Find every directory where the composio-cli skill is currently installed.
8 + * Known locations:
9 + * ~/.agents/skills/composio-cli (canonical install target)
10 + * ~/.claude/skills/composio-cli (Claude Code — may be a symlink or a real dir)
11 + *
12 + * We resolve symlinks so we don't rebuild the same physical directory twice,
13 + * but we also rebuild any real (non-symlink) copies so everything stays in sync.
14 + */
15 +export const discoverSkillRoots = (home: string) =>
16 + Effect.gen(function* () {
17 + const fs = yield* FileSystem.FileSystem;
18 + const path = yield* Path.Path;
19 + const candidates = [path.join(home, '.agents', 'skills'), path.join(home, '.claude', 'skills')];
20 + const seen = new Set<string>();
21 + const roots: string[] = [];
22 +
23 + for (const parent of candidates) {
24 + const skillDir = path.join(parent, SKILL_NAME);
25 + const link = yield* fs.readLink(skillDir).pipe(Effect.option);
26 + if (Option.isSome(link)) {
27 + const realDir = yield* fs.realPath(skillDir).pipe(Effect.option);
28 + if (Option.isNone(realDir)) continue;
29 +
30 + const realParent = path.dirname(realDir.value);
31 + if (!seen.has(realParent)) {
32 + seen.add(realParent);
33 + roots.push(realParent);
34 + }
35 + continue;
36 + }
37 +
38 + const stat = yield* fs.stat(skillDir).pipe(Effect.option);
39 + if (Option.isSome(stat) && stat.value.type === 'Directory' && !seen.has(parent)) {
40 + seen.add(parent);
41 + roots.push(parent);
42 + }
43 + }
44 +
45 + // Always include ~/.agents/skills as a fallback so there's at least one target
46 + const agentSkillsRoot = path.join(home, '.agents', 'skills');
47 + if (!seen.has(agentSkillsRoot)) {
48 + roots.push(agentSkillsRoot);
49 + }
50 +
51 + return roots;
52 + });
ts/packages/cli/src/effects/find-composio-core-generated.ts
+8 -4
@@ -1,5 +1,4 @@
1 -import path from 'node:path';
2 -import { Command, FileSystem } from '@effect/platform';
1 +import { Command, FileSystem, Path } from '@effect/platform';
2 import { Data, Effect, Match } from 'effect';
3 import {
4 JsPackageManagerDetector,
@@ -12,8 +11,12 @@ export class ComposioCorePkgNotFound extends Data.TaggedError('error/ComposioCor
11 readonly fix?: string;
12 }> {}
13
14 +const DEFAULT_PACKAGE_MANAGER: PackageManager = 'npm';
15 +
16 export function pyFindComposioCoreGenerated(cwd: string) {
17 return Effect.gen(function* () {
18 + const path = yield* Path.Path;
19 +
20 /**
21 * Returns a `ComposioCorePkgNotFound` error with the given message and cause.
22 * It lazily identifies the package manager used by the user to tell them how to install `@composio/core`.
@@ -25,7 +28,7 @@ export function pyFindComposioCoreGenerated(cwd: string) {
28 const pkgManager = yield* pkgManagerDetector.detectJsPackageManager(cwd).pipe(
29 Effect.andThen(pkgManager => pkgManager),
30 Effect.tapError(e => Effect.logError(e)),
28 - Effect.catchAll(() => Effect.succeed('npm' as PackageManager))
31 + Effect.catchAll(() => Effect.succeed(DEFAULT_PACKAGE_MANAGER))
32 );
33
34 yield* Effect.logDebug({ pkgManager });
@@ -101,12 +104,13 @@ export function jsFindComposioCoreGenerated(cwd: string) {
104 }) satisfies Effect.Effect<never, ComposioCorePkgNotFound, JsPackageManagerDetector>;
105
106 const fs = yield* FileSystem.FileSystem;
107 + const path = yield* Path.Path;
108
109 yield* Effect.logDebug('Detecting package manager...');
110 const pkgManagerDetector = yield* JsPackageManagerDetector;
111 const pkgManager = yield* pkgManagerDetector.detectJsPackageManager(cwd).pipe(
112 Effect.tapError(e => Effect.logError(e)),
109 - Effect.catchAll(() => Effect.succeed('npm' as PackageManager))
113 + Effect.catchAll(() => Effect.succeed(DEFAULT_PACKAGE_MANAGER))
114 );
115 yield* Effect.logDebug({ pkgManager });
116
ts/packages/cli/src/effects/json.ts
+12 -6
@@ -1,12 +1,18 @@
1 -import { Data, Effect } from 'effect';
1 +import { Data, Effect, Schema } from 'effect';
2
3 export class JSONParseError extends Data.TaggedError('effects/JSONParseError')<{
4 - readonly cause: Error;
4 + readonly cause: unknown;
5 readonly message: string;
6 }> {}
7
8 +/**
9 + * The canonical "JSON object" schema: a string-keyed record of unknown values.
10 + * Import this instead of re-declaring `Schema.Record({ key: Schema.String,
11 + * value: Schema.Unknown })` locally.
12 + */
13 +export const JsonRecordSchema = Schema.Record({ key: Schema.String, value: Schema.Unknown });
14 +
15 export const JSONParse = (s: string) =>
9 - Effect.try({
10 - try: () => JSON.parse(s) as Record<string, unknown>,
11 - catch: e => new JSONParseError({ cause: e as Error, message: 'Failed to parse JSON' }),
12 - });
16 + Schema.decodeUnknown(Schema.parseJson(JsonRecordSchema))(s).pipe(
17 + Effect.mapError(cause => new JSONParseError({ cause, message: 'Failed to parse JSON' }))
18 + );
ts/packages/cli/src/effects/setup-cache-dir.ts
+2 -2
@@ -1,6 +1,5 @@
1 -import path from 'node:path';
1 import { Effect, pipe, Option } from 'effect';
3 -import { FileSystem } from '@effect/platform';
2 +import { FileSystem, Path } from '@effect/platform';
3 import * as constants from 'src/constants';
4 import { APP_CONFIG } from 'src/effects/app-config';
5 import { NodeOs } from 'src/services/node-os';
@@ -8,6 +7,7 @@ import { NodeOs } from 'src/services/node-os';
7 // Helper to create cache directory
8 export const setupCacheDir = Effect.gen(function* () {
9 const fs = yield* FileSystem.FileSystem;
10 + const path = yield* Path.Path;
11 const os = yield* NodeOs;
12
13 const cacheDir = yield* pipe(
ts/packages/cli/src/effects/version.ts
+5 -2
@@ -3,7 +3,10 @@ import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
3 import * as constants from 'src/constants';
4 import { resolveInstalledCliVersion } from 'src/services/run-companion-modules';
5
6 -export const getVersion = Effect.map(
6 +export const getVersion = Effect.flatMap(
7 DEBUG_OVERRIDE_CONFIG.VERSION,
8 - Option.getOrElse(() => resolveInstalledCliVersion(process.execPath, constants.APP_VERSION))
8 + Option.match({
9 + onNone: () => resolveInstalledCliVersion(process.execPath, constants.APP_VERSION),
10 + onSome: version => Effect.succeed(version),
11 + })
12 );
ts/packages/cli/src/generation/create-toolkit-index.ts
+27 -22
@@ -84,37 +84,47 @@ export function createToolkitIndex(input: CreateToolkitIndexInput): Simplify<Too
84 );
85 }
86
87 -type TriggerTypeWithUppercaseSlug<T extends ToolkitName> = Omit<TriggerType, 'slug'> & {
88 - slug: `${Uppercase<T>}_${string}`;
87 +type ToolkitPrefixedSlug = `${ToolkitName}_${string}`;
88 +
89 +type TriggerTypeWithToolkitPrefix = Omit<TriggerType, 'slug'> & {
90 + slug: ToolkitPrefixedSlug;
91 };
92
91 -type GroupByToolkitOutput<T extends ToolkitName> = [
92 - Uppercase<T>,
93 +type GroupByToolkitOutput = [
94 + ToolkitName,
95 {
96 toolkit: Toolkit;
97 typeableTools:
96 - | { withTypes: false; tools: Array<`${Uppercase<T>}_${string}`> }
97 - | { withTypes: true; tools: Array<Tool & { slug: `${Uppercase<T>}_${string}` }> };
98 - triggerTypes: Array<TriggerTypeWithUppercaseSlug<T>>;
98 + | { withTypes: false; tools: Array<ToolkitPrefixedSlug> }
99 + | { withTypes: true; tools: Array<Tool & { slug: ToolkitPrefixedSlug }> };
100 + triggerTypes: Array<TriggerTypeWithToolkitPrefix>;
101 },
102 ];
103
104 +const hasToolkitSlugPrefix = <A extends { readonly slug: string }>(toolkitName: ToolkitName) => {
105 + const hasPrefix = startsWith(`${toolkitName}_`);
106 + return (value: A): value is A & { readonly slug: ToolkitPrefixedSlug } => hasPrefix(value.slug);
107 +};
108 +
109 const groupByToolkit =
103 - <const T extends string>(toolkit: Omit<Toolkit, 'name'> & { name: T }) =>
110 + (toolkit: Toolkit) =>
111 ({
112 typeableTools,
113 triggerTypes,
107 - }: Omit<CreateToolkitIndexInput, 'toolkits'>): GroupByToolkitOutput<T & ToolkitName> => {
108 - const toolkitName = pipe(toolkit.slug, String.toUpperCase, ToolkitName) as Uppercase<
109 - T & ToolkitName
110 - >;
114 + }: Omit<CreateToolkitIndexInput, 'toolkits'>): GroupByToolkitOutput => {
115 + const toolkitName = pipe(toolkit.slug, String.toUpperCase, ToolkitName);
116 + const hasMatchingSlug = hasToolkitSlugPrefix(toolkitName);
117 + const hasMatchingToolSlug = (
118 + tool: Tool
119 + ): tool is Tool & { readonly slug: ToolkitPrefixedSlug } => hasMatchingSlug(tool);
120 + const hasMatchingTriggerSlug = (
121 + triggerType: TriggerType
122 + ): triggerType is TriggerTypeWithToolkitPrefix => hasMatchingSlug(triggerType);
123
124 const filteredTypeableTools = Match.value(typeableTools).pipe(
125 Match.when({ withTypes: true }, ({ withTypes, tools }) => ({
126 withTypes,
115 - tools: tools.filter(tool => startsWith(`${toolkitName}_`)(tool.slug)) as Array<
116 - Tool & { slug: `${typeof toolkitName}_${string}` }
117 - >,
127 + tools: tools.filter(hasMatchingToolSlug),
128 })),
129 Match.when({ withTypes: false }, ({ withTypes, tools }) => ({
130 withTypes,
@@ -128,16 +138,11 @@ const groupByToolkit =
138 {
139 toolkit,
140 typeableTools: filteredTypeableTools,
131 - triggerTypes: triggerTypes.filter(triggerType =>
132 - startsWith(`${toolkitName}_`)(triggerType.slug)
133 - ) as Array<TriggerTypeWithUppercaseSlug<T & ToolkitName>>,
141 + triggerTypes: triggerTypes.filter(hasMatchingTriggerSlug),
142 },
143 ];
144 };
145
138 -function groupByToolkits({
139 - toolkits,
140 - ...rest
141 -}: CreateToolkitIndexInput): GroupByToolkitOutput<ToolkitName>[] {
146 +function groupByToolkits({ toolkits, ...rest }: CreateToolkitIndexInput): GroupByToolkitOutput[] {
147 return toolkits.map(toolkit => groupByToolkit(toolkit)(rest));
148 }
ts/packages/cli/src/generation/python/generate.ts
+4 -1
@@ -1,3 +1,4 @@
1 +import type { Path } from '@effect/platform';
2 import type { ToolkitIndex } from 'src/generation/create-toolkit-index';
3 import type { SourceFile } from 'src/generation/types';
4 import { Effect } from 'effect';
@@ -10,7 +11,9 @@ type GeneratePythonSourcesParams = {
11 };
12
13 export function generatePythonSources(params: GeneratePythonSourcesParams) {
13 - return (index: ToolkitIndex): Effect.Effect<Array<SourceFile>, SafeOutputPathError> => {
14 + return (
15 + index: ToolkitIndex
16 + ): Effect.Effect<Array<SourceFile>, SafeOutputPathError, Path.Path> => {
17 const toolkiteSources = generatePythonToolkitSources(params.banner)(index);
18
19 return Effect.all(
ts/packages/cli/src/generation/safe-output-path.ts
+22 -19
@@ -1,4 +1,4 @@
1 -import path from 'node:path';
1 +import { Path } from '@effect/platform';
2 import { Data, Effect } from 'effect';
3
4 export class SafeOutputPathError extends Data.TaggedError('generation/SafeOutputPathError')<{
@@ -22,24 +22,27 @@ export class SafeOutputPathError extends Data.TaggedError('generation/SafeOutput
22 export function safeOutputPath(
23 outputDir: string,
24 filename: string
25 -): Effect.Effect<string, SafeOutputPathError> {
26 - const resolvedDir = path.resolve(outputDir);
27 - const resolved = path.resolve(resolvedDir, filename);
28 - const relative = path.relative(resolvedDir, resolved);
29 - const isWithinOutputDir =
30 - relative === '' ||
31 - (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
25 +): Effect.Effect<string, SafeOutputPathError, Path.Path> {
26 + return Effect.gen(function* () {
27 + const path = yield* Path.Path;
28 + const resolvedDir = path.resolve(outputDir);
29 + const resolved = path.resolve(resolvedDir, filename);
30 + const relative = path.relative(resolvedDir, resolved);
31 + const isWithinOutputDir =
32 + relative === '' ||
33 + (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
34
33 - if (path.isAbsolute(filename) || !isWithinOutputDir) {
34 - return Effect.fail(
35 - new SafeOutputPathError({
36 - filename,
37 - outputDir,
38 - resolvedPath: resolved,
39 - message: `Refusing unsafe generated filename: ${filename} resolves to ${resolved}`,
40 - })
41 - );
42 - }
35 + if (path.isAbsolute(filename) || !isWithinOutputDir) {
36 + return yield* Effect.fail(
37 + new SafeOutputPathError({
38 + filename,
39 + outputDir,
40 + resolvedPath: resolved,
41 + message: `Refusing unsafe generated filename: ${filename} resolves to ${resolved}`,
42 + })
43 + );
44 + }
45
44 - return Effect.succeed(path.join(outputDir, filename));
46 + return path.join(outputDir, filename);
47 + });
48 }
ts/packages/cli/src/generation/typescript/generate-index-source.ts
+1 -1
@@ -64,7 +64,7 @@ export function generateTypeScriptIndexMapSource(params: GenerateTypeScriptIndex
64 return (index: ToolkitIndex): string => {
65 const indexMapEntries = pipe(
66 index,
67 - Record.map((_, key) => ts.propertyValue(key, ts.namedValue(key as string))),
67 + Record.map((_, key) => ts.propertyValue(key, ts.namedValue(key))),
68 Record.toEntries,
69 Arr.map(([_, value]) => value)
70 );
ts/packages/cli/src/generation/typescript/generate.ts
+3 -2
@@ -1,5 +1,5 @@
1 import * as ts from '@composio/ts-builders';
2 -import path from 'node:path';
2 +import { Path } from '@effect/platform';
3 import { safeOutputPath, type SafeOutputPathError } from 'src/generation/safe-output-path';
4 import type { ToolkitIndex } from 'src/generation/create-toolkit-index';
5 import type { SourceFile } from 'src/generation/types';
@@ -20,8 +20,9 @@ type GenerateTypeScriptSourcesParams = {
20 export function generateTypeScriptSources(params: GenerateTypeScriptSourcesParams) {
21 return (
22 index: ToolkitIndex
23 - ): Effect.Effect<Array<SourceFile>, GenerateTypeScriptSourcesError, never> =>
23 + ): Effect.Effect<Array<SourceFile>, GenerateTypeScriptSourcesError, Path.Path> =>
24 Effect.gen(function* () {
25 + const path = yield* Path.Path;
26 const toolkitSources = yield* generateTypeScriptToolkitSources(params.banner)(index);
27
28 const indexSource = generateIndexSource(params)(index);
ts/packages/cli/src/generation/typescript/transpile.ts
+4 -1
@@ -1,4 +1,5 @@
1 import ts from 'typescript';
2 +import { Path } from '@effect/platform';
3 import { Effect, Data } from 'effect';
4 import {
5 buildVirtualFileMap,
@@ -25,6 +26,8 @@ export function transpileTypeScriptSources({ sources, outputDir }: TranspileType
26 return yield* Effect.void;
27 }
28
29 + const path = yield* Path.Path;
30 +
31 const compilerOptions = {
32 target: ts.ScriptTarget.ES2022,
33 module: ts.ModuleKind.NodeNext,
@@ -42,7 +45,7 @@ export function transpileTypeScriptSources({ sources, outputDir }: TranspileType
45 const virtualFileNames = Array.from(virtualFileMap.keys());
46
47 const tsHost = ts.createCompilerHost(compilerOptions);
45 - patchCompilerHostWithVirtualFiles(tsHost, virtualFileMap, 'delegate');
48 + patchCompilerHostWithVirtualFiles(tsHost, virtualFileMap, path, 'delegate');
49
50 const program = ts.createProgram(virtualFileNames, compilerOptions, tsHost);
51 const emitResult = program.emit();
ts/packages/cli/src/generation/typescript/virtual-compiler-host.ts
+11 -3
@@ -1,4 +1,4 @@
1 -import path from 'node:path';
1 +import type { Path } from '@effect/platform';
2 import ts from 'typescript';
3
4 /**
@@ -23,6 +23,9 @@ export function buildVirtualFileMap(
23 * Overrides both `getSourceFile` and `fileExists` so that module resolution
24 * can discover virtual files that don't exist on the real file system.
25 *
26 + * @param path - `Path` service instance used for the synchronous
27 + * normalize/resolve/relative lookups; the `ts.CompilerHost`
28 + * callbacks are sync and cannot yield Effects.
29 * @param fallback - `'throw'` raises when a file cannot be resolved by the
30 * virtual file map, which keeps validation hosts isolated.
31 * `'delegate'` falls back to the real file system without
@@ -31,6 +34,7 @@ export function buildVirtualFileMap(
34 export function patchCompilerHostWithVirtualFiles(
35 tsHost: ts.CompilerHost,
36 virtualFileMap: Map<string, ts.SourceFile>,
37 + path: Path.Path,
38 fallback: 'throw' | 'delegate' = 'delegate'
39 ): void {
40 const currentDirectory = normalizeSlashes(tsHost.getCurrentDirectory());
@@ -40,7 +44,7 @@ export function patchCompilerHostWithVirtualFiles(
44
45 const virtualFileLookupMap = new Map<string, ts.SourceFile>();
46 for (const [filename, sourceFile] of virtualFileMap) {
43 - for (const lookupKey of getVirtualFileLookupKeys(filename, currentDirectory)) {
47 + for (const lookupKey of getVirtualFileLookupKeys(path, filename, currentDirectory)) {
48 virtualFileLookupMap.set(canonicalizePath(lookupKey), sourceFile);
49 }
50 }
@@ -81,7 +85,11 @@ export function patchCompilerHostWithVirtualFiles(
85 };
86 }
87
84 -function getVirtualFileLookupKeys(filename: string, currentDirectory: string): string[] {
88 +function getVirtualFileLookupKeys(
89 + path: Path.Path,
90 + filename: string,
91 + currentDirectory: string
92 +): string[] {
93 const normalizedFilename = normalizeSlashes(path.normalize(filename));
94
95 if (path.isAbsolute(normalizedFilename)) {
ts/packages/cli/src/services/agents.ts
+4 -3
@@ -1,6 +1,6 @@
1 -import { FileSystem } from '@effect/platform';
1 +import { FileSystem, Path } from '@effect/platform';
2 import { Data, Effect, Option, Predicate, Schema } from 'effect';
3 -import path from 'node:path';
3 +import { JsonRecordSchema } from 'src/effects/json';
4 import { setupCacheDir } from 'src/effects/setup-cache-dir';
5 import { ComposioUserContext } from 'src/services/user-context';
6 import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
@@ -10,7 +10,7 @@ export const DEFAULT_AGENTS_BASE_URL = 'https://agents.composio.dev';
10
11 export type AgentStatus = 'READY' | 'PENDING' | 'UNKNOWN';
12
13 -const UnknownFields = Schema.Record({ key: Schema.String, value: Schema.Unknown });
13 +const UnknownFields = JsonRecordSchema;
14
15 const AgentComposioCredentials = Schema.Struct({
16 member_id: Schema.optional(Schema.NullOr(Schema.String)),
@@ -157,6 +157,7 @@ export const safeAgentSummary = (identity: AgentIdentity): SafeAgentSummary => (
157 });
158
159 export const agentConfigPath = Effect.gen(function* () {
160 + const path = yield* Path.Path;
161 const cacheDir = yield* setupCacheDir;
162 return path.join(cacheDir, AGENT_CONFIG_FILE_NAME);
163 });
ts/packages/cli/src/services/cli-session-artifacts.ts
+49 -46
@@ -1,28 +1,21 @@
1 -import fs from 'node:fs';
2 -import os from 'node:os';
3 -import path from 'node:path';
1 +import { FileSystem, Path } from '@effect/platform';
2 import { Effect, Option } from 'effect';
3 import { getOrCreateProbablyMyCliSessionIdForCurrentCwd } from 'src/services/consumer-short-term-cache';
6 -import { resolveCliConfigPathSync } from 'src/services/cli-user-config';
4 +import { ComposioCliUserConfig } from 'src/services/cli-user-config';
5 +import { NodeOs } from 'src/services/node-os';
6
8 -const readConfiguredArtifactDirectory = (): string | undefined => {
9 - try {
10 - const raw = fs.readFileSync(resolveCliConfigPathSync(), 'utf8');
11 - const parsed = JSON.parse(raw) as { artifact_directory?: unknown };
12 - return typeof parsed.artifact_directory === 'string' &&
13 - parsed.artifact_directory.trim().length > 0
14 - ? parsed.artifact_directory.trim()
15 - : undefined;
16 - } catch {
17 - return undefined;
18 - }
19 -};
7 +export const resolveArtifactsRoot = Effect.gen(function* () {
8 + const path = yield* Path.Path;
9 + const os = yield* NodeOs;
10 + const cliUserConfig = yield* ComposioCliUserConfig;
11
21 -export const resolveArtifactsRoot = (): string =>
22 - process.env.COMPOSIO_SESSION_DIR?.trim() ||
23 - process.env.COMPOSIO_CACHE_DIR?.trim() ||
24 - readConfiguredArtifactDirectory() ||
25 - path.join(os.tmpdir(), 'composio');
12 + return (
13 + process.env.COMPOSIO_SESSION_DIR?.trim() ||
14 + process.env.COMPOSIO_CACHE_DIR?.trim() ||
15 + cliUserConfig.data.artifactDirectory?.trim() ||
16 + path.join(os.tmpdir, 'composio')
17 + );
18 +});
19
20 const SESSION_HISTORY_FILE = 'session-history.jsonl';
21
@@ -42,19 +35,24 @@ export const resolveCliSessionArtifacts = (params?: {
35 readonly consumerUserId?: string;
36 }) =>
37 Effect.gen(function* () {
38 + const fs = yield* FileSystem.FileSystem;
39 + const path = yield* Path.Path;
40 const sessionIdOption = yield* getOrCreateProbablyMyCliSessionIdForCurrentCwd(params).pipe(
46 - Effect.catchAll(() => Effect.succeed(Option.none<string>()))
41 + Effect.option,
42 + Effect.map(Option.flatten)
43 );
44 if (Option.isNone(sessionIdOption)) {
45 return Option.none<CliSessionArtifacts>();
46 }
47
52 - const directoryPath = path.join(resolveArtifactsRoot(), sessionIdOption.value);
53 - try {
54 - fs.mkdirSync(directoryPath, { recursive: true });
55 - } catch {
48 + const directoryPath = path.join(yield* resolveArtifactsRoot, sessionIdOption.value);
49 + const directoryCreated = yield* fs
50 + .makeDirectory(directoryPath, { recursive: true })
51 + .pipe(Effect.option, Effect.map(Option.isSome));
52 + if (!directoryCreated) {
53 return Option.none<CliSessionArtifacts>();
54 }
55 +
56 return Option.some({
57 sessionId: sessionIdOption.value,
58 directoryPath,
@@ -68,6 +66,7 @@ export const appendCliSessionHistory = (params: {
66 readonly consumerUserId?: string;
67 }) =>
68 Effect.gen(function* () {
69 + const fs = yield* FileSystem.FileSystem;
70 const artifactsOption = yield* resolveCliSessionArtifacts({
71 orgId: params.orgId,
72 consumerUserId: params.consumerUserId,
@@ -81,11 +80,9 @@ export const appendCliSessionHistory = (params: {
80 sessionId: artifactsOption.value.sessionId,
81 ...params.entry,
82 });
84 - try {
85 - fs.appendFileSync(artifactsOption.value.historyFilePath, `${line}\n`, 'utf8');
86 - } catch {
87 - // Best-effort — session history write is non-fatal.
88 - }
83 + yield* fs
84 + .writeFileString(artifactsOption.value.historyFilePath, `${line}\n`, { flag: 'a' })
85 + .pipe(Effect.ignore);
86 });
87
88 export const storeCliSessionArtifact = (params: {
@@ -97,26 +94,32 @@ export const storeCliSessionArtifact = (params: {
94 readonly consumerUserId?: string;
95 }) =>
96 Effect.gen(function* () {
100 - const directoryPath =
101 - params.directoryPath ||
102 - Option.getOrUndefined(
103 - yield* resolveCliSessionArtifacts({
104 - orgId: params.orgId,
105 - consumerUserId: params.consumerUserId,
106 - }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
107 - ) ||
108 - path.join(resolveArtifactsRoot(), `adhoc_${randomToken(12)}`);
97 + const fs = yield* FileSystem.FileSystem;
98 + const path = yield* Path.Path;
99 + const directoryPath = yield* Effect.gen(function* () {
100 + if (params.directoryPath) {
101 + return params.directoryPath;
102 + }
103 +
104 + const artifactsOption = yield* resolveCliSessionArtifacts({
105 + orgId: params.orgId,
106 + consumerUserId: params.consumerUserId,
107 + });
108 + if (Option.isSome(artifactsOption)) {
109 + return artifactsOption.value.directoryPath;
110 + }
111
110 - try {
111 - fs.mkdirSync(directoryPath, { recursive: true });
112 + return path.join(yield* resolveArtifactsRoot, `adhoc_${randomToken(12)}`);
113 + });
114 +
115 + return yield* Effect.gen(function* () {
116 + yield* fs.makeDirectory(directoryPath, { recursive: true });
117 const extension = (params.extension ?? 'json').replace(/^\.+/, '') || 'json';
118 const filePath = path.join(
119 directoryPath,
120 `${sanitizeArtifactName(params.name)}_${randomToken()}.${extension}`
121 );
117 - fs.writeFileSync(filePath, params.contents, 'utf8');
122 + yield* fs.writeFileString(filePath, params.contents);
123 return filePath;
119 - } catch {
120 - return undefined;
121 - }
124 + }).pipe(Effect.option, Effect.map(Option.getOrUndefined));
125 });
ts/packages/cli/src/services/cli-user-config.ts
+2
@@ -2,7 +2,9 @@ import { FileSystem } from '@effect/platform';
2 import type { PlatformError } from '@effect/platform/Error';
3 import { Context, Effect, Layer, Option } from 'effect';
4 import type { ParseError } from 'effect/ParseResult';
5 +// eslint-disable-next-line no-restricted-imports -- os.homedir feeds resolveCliConfigDirectorySync, which runs from synchronous non-Effect call sites (dev.cmd messages, run-helpers-runtime readFileSync) where the NodeOs service is unavailable
6 import os from 'node:os';
7 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
8 import path from 'node:path';
9 import { setupCacheDir } from 'src/effects/setup-cache-dir';
10 import { getVersion } from 'src/effects/version';
ts/packages/cli/src/services/composio-clients-cached.ts
+16 -15
@@ -1,6 +1,5 @@
1 -import path from 'node:path';
1 import { Effect, Option, ParseResult, Layer, Array as Arr } from 'effect';
3 -import { FileSystem } from '@effect/platform';
2 +import { FileSystem, Path } from '@effect/platform';
3 import { BunFileSystem } from '@effect/platform-bun';
4 import { setupCacheDir } from 'src/effects/setup-cache-dir';
5 import { FORCE_CONFIG } from 'src/effects/force-config';
@@ -35,6 +34,17 @@ export const CACHE_FILES = {
34 triggerTypes: 'trigger-types.json',
35 } as const;
36
37 +/**
38 + * Cache filter that keeps only items whose slug starts with one of the
39 + * requested toolkits' `<TOOLKIT>_` prefixes.
40 + */
41 +const filterBySlugPrefixes =
42 + (toolkitSlugs: ReadonlyArray<string>) =>
43 + <T extends { readonly slug: string }>(data: ReadonlyArray<T>) => {
44 + const prefixes = toolkitSlugs.map(s => `${s.toUpperCase()}_`);
45 + return Effect.succeed(data.filter(t => prefixes.some(p => t.slug.toUpperCase().startsWith(p))));
46 + };
47 +
48 /**
49 * Generic cache helper function that handles both cache read/write with graceful error handling.
50 */
@@ -48,6 +58,7 @@ function createCachedEffect<T, E, R>(
58 // First define the cache-handling function that will run with all required services
59 const cacheEffect = Effect.gen(function* () {
60 const fs = yield* FileSystem.FileSystem;
61 + const path = yield* Path.Path;
62 const cacheDir = yield* setupCacheDir;
63
64 const cacheFilePath = path.join(cacheDir, cacheFileName);
@@ -107,7 +118,7 @@ function createCachedEffect<T, E, R>(
118 // This ensures the returned effect has the same error type as the original computation
119 // by providing all the required cache services
120 return handledCacheEffect.pipe(
110 - Effect.provide(Layer.mergeAll(BunFileSystem.layer, NodeOs.Default))
121 + Effect.provide(Layer.mergeAll(BunFileSystem.layer, Path.layer, NodeOs.Default))
122 ) as Effect.Effect<T, E, R>;
123 }
124
@@ -186,12 +197,7 @@ export const ComposioToolkitsRepositoryCached = Layer.effect(
197 getTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) => {
198 const cacheFilter =
199 toolkitSlugs && toolkitSlugs.length > 0
189 - ? (data: TriggerTypes) => {
190 - const prefixes = toolkitSlugs.map(s => `${s.toUpperCase()}_`);
191 - return Effect.succeed(
192 - data.filter(t => prefixes.some(p => t.slug.toUpperCase().startsWith(p)))
193 - );
194 - }
200 + ? (data: TriggerTypes) => filterBySlugPrefixes(toolkitSlugs)(data)
201 : undefined;
202 return createCachedEffect(
203 CACHE_FILES.triggerTypes,
@@ -205,12 +211,7 @@ export const ComposioToolkitsRepositoryCached = Layer.effect(
211 getTools: (toolkitSlugs?: ReadonlyArray<string>) => {
212 const cacheFilter =
213 toolkitSlugs && toolkitSlugs.length > 0
208 - ? (data: Tools) => {
209 - const prefixes = toolkitSlugs.map(s => `${s.toUpperCase()}_`);
210 - return Effect.succeed(
211 - data.filter(t => prefixes.some(p => t.slug.toUpperCase().startsWith(p)))
212 - );
213 - }
214 + ? (data: Tools) => filterBySlugPrefixes(toolkitSlugs)(data)
215 : undefined;
216 return createCachedEffect(
217 CACHE_FILES.tools,
ts/packages/cli/src/services/consumer-short-term-cache.ts
+9 -8
@@ -1,5 +1,4 @@
1 -import path from 'node:path';
2 -import { FileSystem } from '@effect/platform';
1 +import { FileSystem, Path } from '@effect/platform';
2 import { Effect, Option, Record as EffectRecord, Schema } from 'effect';
3 import { APP_CONFIG } from 'src/effects/app-config';
4 import { setupCacheDir } from 'src/effects/setup-cache-dir';
@@ -76,7 +75,11 @@ export const decodeCacheStateTolerant = (raw: string): CacheState =>
75
76 const cacheKey = (orgId: string, consumerUserId: string) => `${orgId}:${consumerUserId}`;
77
79 -const cachePath = (cacheDir: string) => path.join(cacheDir, CACHE_FILE);
78 +const cachePath = Effect.gen(function* () {
79 + const path = yield* Path.Path;
80 + const cacheDir = yield* setupCacheDir;
81 + return path.join(cacheDir, CACHE_FILE);
82 +});
83
84 const cwdHash = (cwd: string): string => {
85 let hash = 5381;
@@ -131,8 +134,7 @@ const resolveSearchSessionMetadata = (params: {
134 const readCache = () =>
135 Effect.gen(function* () {
136 const fs = yield* FileSystem.FileSystem;
134 - const cacheDir = yield* setupCacheDir;
135 - const filePath = cachePath(cacheDir);
137 + const filePath = yield* cachePath;
138 if (!(yield* fs.exists(filePath))) {
139 return {} satisfies CacheState;
140 }
@@ -146,7 +148,7 @@ const writeCache = (state: CacheState) =>
148 const cacheDir = yield* setupCacheDir;
149 yield* fs.makeDirectory(cacheDir, { recursive: true }).pipe(Effect.catchAll(() => Effect.void));
150 yield* fs
149 - .writeFileString(cachePath(cacheDir), JSON.stringify(state, null, 2))
151 + .writeFileString(yield* cachePath, JSON.stringify(state, null, 2))
152 .pipe(Effect.catchAll(() => Effect.void));
153 });
154
@@ -393,8 +395,7 @@ export const getFreshConsumerToolRouterConnectedAccountsFromCache = (params: {
395 export const invalidateConsumerConnectedToolkitsCache = () =>
396 Effect.gen(function* () {
397 const fs = yield* FileSystem.FileSystem;
396 - const cacheDir = yield* setupCacheDir;
397 - const filePath = cachePath(cacheDir);
398 + const filePath = yield* cachePath;
399 if (yield* fs.exists(filePath)) {
400 yield* fs.remove(filePath);
401 }
ts/packages/cli/src/services/detached-process.ts new
+64
@@ -0,0 +1,64 @@
1 +// eslint-disable-next-line no-restricted-imports -- This Effect helper is the sole detached-spawn boundary for CLI source: @effect/platform Command processes are scope-bound and are killed when their scope closes, while these children must outlive the CLI process.
2 +import { spawn } from 'node:child_process';
3 +import { Data, Effect } from 'effect';
4 +
5 +export class DetachedProcessSpawnError extends Data.TaggedError(
6 + 'services/DetachedProcessSpawnError'
7 +)<{
8 + readonly command: string;
9 + readonly cause: unknown;
10 +}> {}
11 +
12 +/**
13 + * Spawns a process that outlives the CLI: detached from the CLI's process
14 + * group so terminal signals never reach it, and unref'd so the CLI event loop
15 + * never waits on it. All stdio is ignored unless stderr passthrough is
16 + * requested (telemetry debug output).
17 + */
18 +export const spawnDetached = (
19 + command: string,
20 + args: ReadonlyArray<string>,
21 + options?: { readonly inheritStderr?: boolean }
22 +): Effect.Effect<void, DetachedProcessSpawnError> =>
23 + Effect.try({
24 + try: () =>
25 + spawn(command, [...args], {
26 + detached: true,
27 + stdio: options?.inheritStderr === true ? ['ignore', 'ignore', 'inherit'] : 'ignore',
28 + // Leaving `env` unset makes the child inherit the complete parent environment.
29 + }),
30 + catch: cause => new DetachedProcessSpawnError({ command, cause }),
31 + }).pipe(
32 + Effect.flatMap(child =>
33 + Effect.async<void, DetachedProcessSpawnError>(resume => {
34 + let settled = false;
35 +
36 + const cleanup = () => {
37 + child.removeListener('spawn', onSpawn);
38 + child.removeListener('error', onError);
39 + };
40 +
41 + const settle = (result: Effect.Effect<void, DetachedProcessSpawnError>) => {
42 + if (settled) {
43 + return;
44 + }
45 +
46 + settled = true;
47 + cleanup();
48 + resume(result);
49 + };
50 +
51 + const onSpawn = () => {
52 + child.unref();
53 + settle(Effect.void);
54 + };
55 +
56 + const onError = (cause: Error) => {
57 + settle(Effect.fail(new DetachedProcessSpawnError({ command, cause })));
58 + };
59 +
60 + child.once('spawn', onSpawn);
61 + child.once('error', onError);
62 + })
63 + )
64 + );
ts/packages/cli/src/services/js-package-manager-detector.ts
+3 -3
@@ -1,7 +1,6 @@
1 import { BunFileSystem } from '@effect/platform-bun';
2 import { Data, Effect, Option, Schema, pipe } from 'effect';
3 -import { FileSystem } from '@effect/platform';
4 -import * as path from 'path';
3 +import { FileSystem, Path } from '@effect/platform';
4
5 const toError = (e: unknown): Error => (e instanceof Error ? e : new Error(String(e)));
6
@@ -36,6 +35,7 @@ export class JsPackageManagerDetector extends Effect.Service<JsPackageManagerDet
35 yield* Effect.logDebug('[JsPackageManagerDetector] Identifying JS package manager...');
36
37 const fs = yield* FileSystem.FileSystem;
38 + const path = yield* Path.Path;
39
40 const parsePackageManager = (pm: string): Option.Option<PackageManager> => {
41 if (pm.startsWith('pnpm@')) return Option.some('pnpm');
@@ -151,6 +151,6 @@ export class JsPackageManagerDetector extends Effect.Service<JsPackageManagerDet
151 detectJsPackageManager,
152 };
153 }),
154 - dependencies: [BunFileSystem.layer],
154 + dependencies: [BunFileSystem.layer, Path.layer],
155 }
156 ) {}
ts/packages/cli/src/services/master-detector.ts
+1 -1
@@ -1,6 +1,6 @@
1 export type MasterKind = 'claude' | 'codex' | 'user';
2
3 -const hasEnvPrefix = (env: Record<string, string | undefined>, prefix: string): boolean =>
3 +export const hasEnvPrefix = (env: Record<string, string | undefined>, prefix: string): boolean =>
4 Object.keys(env).some(key => key.startsWith(prefix));
5
6 export const detectMaster = (env: Record<string, string | undefined> = process.env): MasterKind => {
ts/packages/cli/src/services/native-ui-sidecar.ts
+229 -124
@@ -1,14 +1,24 @@
1 -import { execFileSync, spawn } from 'node:child_process';
2 -import fsSync from 'node:fs';
3 -import fs from 'node:fs/promises';
4 -import os from 'node:os';
5 -import path from 'node:path';
6 -import { Config, ConfigProvider, Effect, Option, Predicate, Schema } from 'effect';
1 +import { Command, CommandExecutor, FileSystem, Path } from '@effect/platform';
2 +import { BunContext } from '@effect/platform-bun';
3 +import {
4 + Cause,
5 + Config,
6 + ConfigProvider,
7 + Data,
8 + Duration,
9 + Effect,
10 + Exit,
11 + Option,
12 + Predicate,
13 + Schema,
14 + Stream,
15 +} from 'effect';
16 import {
17 detectCliPlatform,
18 ensureBundledBinaryExecutable,
19 getLocalToolsBundleRootCandidates,
20 } from '@composio/cli-local-tools';
21 +import { hasEnvPrefix } from 'src/services/master-detector';
22
23 const NATIVE_UI_BINARY_NAME = 'composio-native-ui';
24
@@ -30,12 +40,32 @@ export type NativeUiBinaryResolution =
40 readonly platform: string;
41 };
42
33 -interface NativeUiDecisionPayload {
34 - readonly decision?: NativeUiPermissionDecision;
43 +export class NativeUiBinarySetupError extends Data.TaggedError(
44 + 'services/NativeUiBinarySetupError'
45 +)<{
46 + readonly binaryPath: string;
47 + readonly cause: unknown;
48 +}> {
49 + override get message(): string {
50 + return `Failed to make the native UI sidecar binary executable: ${this.binaryPath}`;
51 + }
52 +}
53 +
54 +export class NativeUiDecisionMissingError extends Data.TaggedError(
55 + 'services/NativeUiDecisionMissingError'
56 +)<{
57 + readonly binaryPath: string;
58 +}> {
59 + override get message(): string {
60 + return 'Native permission prompt exited without a decision.';
61 + }
62 }
63
37 -const hasEnvPrefix = (env: NodeJS.ProcessEnv, prefix: string): boolean =>
38 - Object.keys(env).some(key => key.startsWith(prefix));
64 +// Caller-agent detection scans the whole environment for agent-specific
65 +// prefixes (OPENCLAW_*, CLAUDE_*, CODEX_*). effect/Config can only read named
66 +// keys, so this module keeps a single raw-env boundary, mirroring the
67 +// node-os.ts precedent.
68 +const rawProcessEnv: NodeJS.ProcessEnv = process.env;
69
70 const FALSY_ENV_FLAG_VALUES: ReadonlyArray<string> = ['0', 'false', 'no', 'off'];
71
@@ -97,38 +127,49 @@ const normalizeCallerAgent = (value?: string): NativeUiCallerAgent | undefined =
127 return undefined;
128 };
129
100 -const detectCallerAgentFromProcessTree = (): NativeUiCallerAgent | undefined => {
130 +const PS_TREE_MAX_DEPTH = 8;
131 +
132 +// Mirrors the former execFileSync('ps', ...) lookup: any spawn failure (or a
133 +// non-zero exit, which leaves stdout empty) resolves to undefined.
134 +const psParentEntry = (
135 + pid: number
136 +): Effect.Effect<string | undefined, never, CommandExecutor.CommandExecutor> =>
137 + Command.make('ps', '-o', 'ppid=', '-o', 'comm=', '-p', String(pid)).pipe(
138 + // The child never reads interactive input: hand it an immediately-closed
139 + // stdin pipe (EOF), matching the previous `stdio: ['ignore', ...]` spawn.
140 + Command.stdin(Stream.empty),
141 + Command.string,
142 + Effect.map(output => output.trim()),
143 + Effect.orElseSucceed(() => undefined)
144 + );
145 +
146 +const detectCallerAgentFromProcessTree: Effect.Effect<
147 + NativeUiCallerAgent | undefined,
148 + never,
149 + CommandExecutor.CommandExecutor
150 +> = Effect.gen(function* () {
151 if (process.platform === 'win32') return undefined;
152
153 let pid = process.ppid;
104 - for (let depth = 0; depth < 8 && pid > 1; depth += 1) {
105 - try {
106 - const output = execFileSync('ps', ['-o', 'ppid=', '-o', 'comm=', '-p', String(pid)], {
107 - encoding: 'utf8',
108 - stdio: ['ignore', 'pipe', 'ignore'],
109 - }).trim();
110 - if (!output) return undefined;
111 -
112 - const match = output.match(/^(\d+)\s+(.+)$/);
113 - if (!match) return undefined;
114 -
115 - const command = match[2]?.toLowerCase() ?? '';
116 - if (command.includes('openclaw') || command.includes('open-claw')) return 'openclaw';
117 - if (command.includes('claude')) return 'claude';
118 - if (command.includes('codex')) return 'codex';
119 -
120 - pid = Number(match[1]);
121 - } catch {
122 - return undefined;
123 - }
154 + for (let depth = 0; depth < PS_TREE_MAX_DEPTH && pid > 1; depth += 1) {
155 + const output = yield* psParentEntry(pid);
156 + if (output === undefined || output === '') return undefined;
157 +
158 + const match = output.match(/^(\d+)\s+(.+)$/);
159 + if (!match) return undefined;
160 +
161 + const command = match[2]?.toLowerCase() ?? '';
162 + if (command.includes('openclaw') || command.includes('open-claw')) return 'openclaw';
163 + if (command.includes('claude')) return 'claude';
164 + if (command.includes('codex')) return 'codex';
165 +
166 + pid = Number(match[1]);
167 }
168
169 return undefined;
127 -};
170 +});
171
129 -export const detectNativeUiCallerAgent = (
130 - env: NodeJS.ProcessEnv = process.env
131 -): NativeUiCallerAgent => {
172 +const detectCallerAgentFromEnv = (env: NodeJS.ProcessEnv): NativeUiCallerAgent | undefined => {
173 const explicit = normalizeCallerAgent(env.COMPOSIO_CALLER_AGENT ?? env.COMPOSIO_AGENT);
174 if (explicit) return explicit;
175
@@ -136,10 +177,29 @@ export const detectNativeUiCallerAgent = (
177 if (hasEnvPrefix(env, 'CLAUDE_')) return 'claude';
178 if (hasEnvPrefix(env, 'CODEX_')) return 'codex';
179
139 - return detectCallerAgentFromProcessTree() ?? 'composio';
180 + return undefined;
181 };
182
142 -export const resolveNativeUiBinary = (): NativeUiBinaryResolution => {
183 +export const detectNativeUiCallerAgentEffect = (
184 + env: NodeJS.ProcessEnv = rawProcessEnv
185 +): Effect.Effect<NativeUiCallerAgent, never, CommandExecutor.CommandExecutor> =>
186 + Effect.gen(function* () {
187 + const fromEnv = detectCallerAgentFromEnv(env);
188 + if (fromEnv !== undefined) return fromEnv;
189 +
190 + return (yield* detectCallerAgentFromProcessTree) ?? 'composio';
191 + });
192 +
193 +export const detectNativeUiCallerAgent = (
194 + env: NodeJS.ProcessEnv = rawProcessEnv
195 +): Promise<NativeUiCallerAgent> =>
196 + Effect.runPromise(Effect.provide(detectNativeUiCallerAgentEffect(env), BunContext.layer));
197 +
198 +export const resolveNativeUiBinary: Effect.Effect<
199 + NativeUiBinaryResolution,
200 + never,
201 + FileSystem.FileSystem | Path.Path
202 +> = Effect.gen(function* () {
203 const platform = detectCliPlatform();
204 if (!platform.startsWith('darwin-')) {
205 return {
@@ -148,26 +208,35 @@ export const resolveNativeUiBinary = (): NativeUiBinaryResolution => {
208 };
209 }
210
211 + const fs = yield* FileSystem.FileSystem;
212 + const path = yield* Path.Path;
213 +
214 const candidates = getLocalToolsBundleRootCandidates().map(root =>
215 path.join(root, NATIVE_UI_BINARY_NAME, platform, NATIVE_UI_BINARY_NAME)
216 );
154 - const binaryPath = candidates.find(candidate => fsSync.existsSync(candidate));
155 -
156 - return binaryPath
157 - ? {
158 - _tag: 'found',
159 - binaryPath,
160 - }
161 - : {
162 - _tag: 'missing',
163 - platform,
164 - candidates,
165 - };
166 -};
217 + const binaryPath = yield* Effect.findFirst(candidates, candidate =>
218 + fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))
219 + );
220 +
221 + return Option.match(binaryPath, {
222 + onNone: (): NativeUiBinaryResolution => ({
223 + _tag: 'missing',
224 + platform,
225 + candidates,
226 + }),
227 + onSome: (binaryPath): NativeUiBinaryResolution => ({
228 + _tag: 'found',
229 + binaryPath,
230 + }),
231 + });
232 +});
233 +
234 +const NativeUiDecisionPayloadSchema = Schema.parseJson(Schema.Struct({ decision: Schema.String }));
235
236 const parseDecisionPayload = (raw: string): NativeUiPermissionDecision | undefined => {
169 - const payload = JSON.parse(raw) as NativeUiDecisionPayload;
170 - const decision = payload.decision;
237 + const decision = Option.getOrUndefined(
238 + Schema.decodeUnknownOption(NativeUiDecisionPayloadSchema)(raw)
239 + )?.decision;
240 return decision === 'allow_once' ||
241 decision === 'allow_session' ||
242 decision === 'deny' ||
@@ -176,81 +245,117 @@ const parseDecisionPayload = (raw: string): NativeUiPermissionDecision | undefin
245 : undefined;
246 };
247
248 +type DialogExit =
249 + | {
250 + readonly _tag: 'exited';
251 + // undefined when the dialog was terminated by a signal, which the
252 + // previous 'exit' handler saw as `code === null` (treated as non-zero).
253 + readonly exitCode: number | undefined;
254 + }
255 + | {
256 + readonly _tag: 'timedOut';
257 + };
258 +
259 +const requestNativeUiPermissionDecisionEffect = (params: {
260 + readonly toolSlug: string;
261 + readonly accountLabel?: string;
262 + readonly timeoutSeconds?: number;
263 +}) =>
264 + Effect.gen(function* () {
265 + if (yield* isInteractivePermissionUiDisabled) return undefined;
266 +
267 + const resolved = yield* resolveNativeUiBinary;
268 + if (!Predicate.isTagged(resolved, 'found')) return undefined;
269 +
270 + yield* Effect.tryPromise({
271 + try: () => ensureBundledBinaryExecutable(resolved.binaryPath),
272 + catch: cause => new NativeUiBinarySetupError({ binaryPath: resolved.binaryPath, cause }),
273 + });
274 +
275 + const fs = yield* FileSystem.FileSystem;
276 + const path = yield* Path.Path;
277 +
278 + // Removed when the surrounding scope closes, replacing the try/finally rm.
279 + const tempDir = yield* fs.makeTempDirectoryScoped({
280 + prefix: 'composio-native-ui-decision-',
281 + });
282 + const callbackFile = path.join(tempDir, 'decision.json');
283 + const timeoutSeconds = params.timeoutSeconds ?? 30;
284 + const callerAgent = yield* detectNativeUiCallerAgentEffect();
285 +
286 + const args = [
287 + '--tool',
288 + params.toolSlug,
289 + '--account',
290 + params.accountLabel ?? 'default connection',
291 + '--caller-agent',
292 + callerAgent,
293 + '--subtitle',
294 + 'Approve once, allow for 1 hour, or deny.',
295 + '--allow-session-label',
296 + 'Allow for 1 hr',
297 + '--callback-file',
298 + callbackFile,
299 + '--timeout',
300 + String(timeoutSeconds),
301 + ];
302 +
303 + const child = yield* Command.start(
304 + // The dialog never reads interactive input: hand it an immediately-closed
305 + // stdin pipe (EOF), matching the previous `stdio: 'ignore'` spawn.
306 + Command.make(resolved.binaryPath, ...args).pipe(Command.stdin(Stream.empty))
307 + );
308 +
309 + // The previous spawn ignored the dialog's output entirely; drain the pipes
310 + // so the dialog can never block on a full pipe buffer.
311 + yield* Effect.fork(Effect.ignore(Stream.runDrain(child.stdout)));
312 + yield* Effect.fork(Effect.ignore(Stream.runDrain(child.stderr)));
313 +
314 + const dialogExit = yield* child.exitCode.pipe(
315 + Effect.map((exitCode): DialogExit => ({ _tag: 'exited', exitCode })),
316 + // exitCode fails when the dialog was terminated by a signal; fold it into
317 + // the signal-termination shape instead of surfacing a PlatformError.
318 + Effect.orElseSucceed((): DialogExit => ({ _tag: 'exited', exitCode: undefined })),
319 + Effect.timeoutTo({
320 + duration: Duration.seconds(timeoutSeconds + 5),
321 + onSuccess: (exit: DialogExit) => exit,
322 + onTimeout: (): DialogExit => ({ _tag: 'timedOut' }),
323 + })
324 + );
325 +
326 + // SIGKILL rather than leaving the scope finalizer's SIGTERM to clean up:
327 + // the finalizer awaits the child's exit, so a dialog that ignored SIGTERM
328 + // would stall this permission gate instead of resolving as dismissed.
329 + if (dialogExit._tag === 'timedOut') {
330 + yield* Effect.ignore(child.kill('SIGKILL'));
331 + return 'dismissed';
332 + }
333 +
334 + // If the sidecar exits without writing a callback file, treat a non-zero
335 + // exit as a dismissal. A zero exit without a callback is unexpected.
336 + const decision = yield* fs.readFileString(callbackFile).pipe(
337 + Effect.map(parseDecisionPayload),
338 + Effect.orElseSucceed(() => undefined)
339 + );
340 + if (decision !== undefined) return decision;
341 +
342 + if (dialogExit.exitCode === 0) {
343 + return yield* new NativeUiDecisionMissingError({ binaryPath: resolved.binaryPath });
344 + }
345 + return 'dismissed';
346 + }).pipe(Effect.scoped);
347 +
348 export const requestNativeUiPermissionDecision = async (params: {
349 readonly toolSlug: string;
350 readonly accountLabel?: string;
351 readonly timeoutSeconds?: number;
352 }): Promise<NativeUiPermissionDecision | undefined> => {
184 - if (await Effect.runPromise(isInteractivePermissionUiDisabled)) return undefined;
185 -
186 - const resolved = resolveNativeUiBinary();
187 - if (!Predicate.isTagged(resolved, 'found')) return undefined;
188 -
189 - await ensureBundledBinaryExecutable(resolved.binaryPath);
190 -
191 - const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'composio-native-ui-decision-'));
192 - const callbackFile = path.join(tempDir, 'decision.json');
193 - const timeoutSeconds = params.timeoutSeconds ?? 30;
194 -
195 - try {
196 - return await new Promise<NativeUiPermissionDecision>((resolve, reject) => {
197 - const args = [
198 - '--tool',
199 - params.toolSlug,
200 - '--account',
201 - params.accountLabel ?? 'default connection',
202 - '--caller-agent',
203 - detectNativeUiCallerAgent(),
204 - '--subtitle',
205 - 'Approve once, allow for 1 hour, or deny.',
206 - '--allow-session-label',
207 - 'Allow for 1 hr',
208 - '--callback-file',
209 - callbackFile,
210 - '--timeout',
211 - String(timeoutSeconds),
212 - ];
213 -
214 - const child = spawn(resolved.binaryPath, args, {
215 - detached: false,
216 - stdio: 'ignore',
217 - });
218 -
219 - const timeout = setTimeout(
220 - () => {
221 - child.kill();
222 - resolve('dismissed');
223 - },
224 - (timeoutSeconds + 5) * 1000
225 - );
226 -
227 - child.on('error', error => {
228 - clearTimeout(timeout);
229 - reject(error);
230 - });
231 -
232 - child.on('exit', async code => {
233 - clearTimeout(timeout);
234 - try {
235 - const raw = await fs.readFile(callbackFile, 'utf8');
236 - const decision = parseDecisionPayload(raw);
237 - if (decision) {
238 - resolve(decision);
239 - return;
240 - }
241 - } catch {
242 - // If the sidecar exits without writing a callback file, treat a non-zero
243 - // exit as a dismissal. A zero exit without a callback is unexpected.
244 - }
245 -
246 - if (code === 0) {
247 - reject(new Error('Native permission prompt exited without a decision.'));
248 - } else {
249 - resolve('dismissed');
250 - }
251 - });
252 - });
253 - } finally {
254 - await fs.rm(tempDir, { recursive: true, force: true });
255 - }
353 + const exit = await Effect.runPromiseExit(
354 + Effect.provide(requestNativeUiPermissionDecisionEffect(params), BunContext.layer)
355 + );
356 + if (Exit.isSuccess(exit)) return exit.value;
357 +
358 + // Surface the original error instance (callers recover from any rejection),
359 + // not a FiberFailure wrapper.
360 + throw Cause.squash(exit.cause);
361 };
ts/packages/cli/src/services/node-os.ts
+10 -3
@@ -1,15 +1,22 @@
1 +// eslint-disable-next-line no-restricted-imports -- This Effect service is the sole node:os boundary for CLI source.
2 import os from 'node:os';
3 import { Effect } from 'effect';
4
4 -// Service to that wraps `node:os`, for testing purposes.
5 +// Injectable operating-system details for testing purposes.
6 export class NodeOs extends Effect.Service<NodeOs>()('services/NodeOs', {
7 sync: () => ({
8 homedir: os.homedir(),
9 + tmpdir: os.tmpdir(),
10 platform: os.platform(),
11 arch: os.arch(),
12 }),
13 dependencies: [],
14 }) {}
15
14 -export const defaultNodeOs = ({ homedir }: { homedir: string }) =>
15 - new NodeOs({ homedir, platform: os.platform(), arch: os.arch() });
16 +export const defaultNodeOs = ({
17 + homedir,
18 + tmpdir = os.tmpdir(),
19 +}: {
20 + homedir: string;
21 + tmpdir?: string;
22 +}) => new NodeOs({ homedir, tmpdir, platform: os.platform(), arch: os.arch() });
ts/packages/cli/src/services/project-context.ts
+7 -10
@@ -1,13 +1,11 @@
1 -import path from 'node:path';
1 import { Effect, Option } from 'effect';
3 -import { FileSystem } from '@effect/platform';
2 +import { FileSystem, Path } from '@effect/platform';
3 import { NodeOs } from 'src/services/node-os';
4 import { NodeProcess } from 'src/services/node-process';
5 import { APP_CONFIG } from 'src/effects/app-config';
6 +import { getAncestors } from 'src/utils/get-ancestors';
7 import * as constants from 'src/constants';
8 import { type ProjectKeys, projectKeysFromJSON } from 'src/models/project-keys';
9 -import type { PlatformError } from '@effect/platform/Error';
10 -import type { ParseError } from 'effect/ParseResult';
9
10 /**
11 * Keys allowed in `.composio/.env` files.
@@ -55,6 +53,7 @@ const parseEnvFile = (content: string): Map<string, string> => {
53 export class ProjectContext extends Effect.Service<ProjectContext>()('services/ProjectContext', {
54 effect: Effect.gen(function* () {
55 const fs = yield* FileSystem.FileSystem;
56 + const path = yield* Path.Path;
57 const proc = yield* NodeProcess;
58 const os = yield* NodeOs;
59
@@ -80,10 +79,9 @@ export class ProjectContext extends Effect.Service<ProjectContext>()('services/P
79 }
80
81 // 2. Walk up from CWD, stop at homedir (not filesystem root)
83 - let dir = proc.cwd;
82 const stopAt = os.homedir;
83
86 - while (true) {
84 + for (const dir of yield* getAncestors(proc.cwd)) {
85 const composioDir = path.join(dir, constants.PROJECT_COMPOSIO_DIR);
86
87 // 2a. Check .composio/.env
@@ -141,15 +139,14 @@ export class ProjectContext extends Effect.Service<ProjectContext>()('services/P
139 }
140
141 // Stop at homedir to avoid reading from system directories
144 - if (dir === stopAt || dir === path.dirname(dir)) break;
145 - dir = path.dirname(dir);
142 + if (dir === stopAt) break;
143 }
144
145 // 3. Nothing found
146 yield* Effect.logDebug('ProjectContext: no context found');
147 return Option.none<ProjectKeys>();
151 - }),
148 + }).pipe(Effect.provideService(Path.Path, path)),
149 };
150 }),
154 - dependencies: [],
151 + dependencies: [Path.layer],
152 }) {}
ts/packages/cli/src/services/project-environment-detector.ts
+25 -19
@@ -1,7 +1,6 @@
1 import { BunFileSystem } from '@effect/platform-bun';
2 -import { FileSystem } from '@effect/platform';
2 +import { FileSystem, Path } from '@effect/platform';
3 import { Data, Effect, Match } from 'effect';
4 -import * as path from 'node:path';
4 import process from 'node:process';
5 import { getAncestors } from 'src/utils/get-ancestors';
6
@@ -99,7 +98,7 @@ const isTsConfig = (name: string) => {
98 return lower === 'tsconfig.json' || (lower.startsWith('tsconfig.') && lower.endsWith('.json'));
99 };
100
102 -const countExtensions = (files: string[]) => {
101 +const countExtensions = (path: Path.Path, files: string[]) => {
102 let ts = 0;
103 let js = 0;
104 let py = 0;
@@ -156,7 +155,7 @@ const SYSTEM_ROOTS = new Set([
155 ]);
156
157 /** Reject system roots (/, /tmp, /var, /private/tmp, etc.) as project roots. */
159 -const isSystemRoot = (dir: string): boolean => {
158 +const isSystemRoot = (path: Path.Path, dir: string): boolean => {
159 const resolved = path.resolve(dir);
160 if (SYSTEM_ROOTS.has(resolved)) return true;
161 const parent = path.dirname(resolved);
@@ -209,7 +208,7 @@ const makeReadDirectoryOptional = (fs: FileSystem.FileSystem) => (dir: string) =
208 const makeReadFileStringOptional = (fs: FileSystem.FileSystem) => (filePath: string) =>
209 fs.readFileString(filePath).pipe(Effect.catchAll(() => Effect.succeed<string | null>(null)));
210
212 -const makeReadPackageJson = (fs: FileSystem.FileSystem) => {
211 +const makeReadPackageJson = (fs: FileSystem.FileSystem, path: Path.Path) => {
212 const readFileStringOptional = makeReadFileStringOptional(fs);
213 return (dir: string) =>
214 Effect.gen(function* () {
@@ -228,6 +227,7 @@ const makeReadPackageJson = (fs: FileSystem.FileSystem) => {
227
228 const analyzeDirectory = (
229 fs: FileSystem.FileSystem,
230 + path: Path.Path,
231 dir: string
232 ): Effect.Effect<DirEvidence, ProjectEnvironmentDetectorError> =>
233 Effect.gen(function* () {
@@ -243,7 +243,7 @@ const analyzeDirectory = (
243 );
244 const readDirectoryOptional = makeReadDirectoryOptional(fs);
245 const readFileStringOptional = makeReadFileStringOptional(fs);
246 - const readPackageJson = makeReadPackageJson(fs);
246 + const readPackageJson = makeReadPackageJson(fs, path);
247
248 const lowerFiles = files.map(file => file.toLowerCase());
249 const fileSet = new Set(lowerFiles);
@@ -354,7 +354,7 @@ const analyzeDirectory = (
354 }
355
356 // Score from file extensions
357 - const extensionCounts = countExtensions(files);
357 + const extensionCounts = countExtensions(path, files);
358 if (extensionCounts.ts > 0) {
359 tsScore += Math.min(3, extensionCounts.ts);
360 jsHints.tsFiles = true;
@@ -372,7 +372,7 @@ const analyzeDirectory = (
372 if (!fileSet.has(subdir)) continue;
373 const actualSubdir = fileByLower.get(subdir) ?? subdir;
374 const subFiles = yield* readDirectoryOptional(path.join(dir, actualSubdir));
375 - const subCounts = countExtensions(subFiles);
375 + const subCounts = countExtensions(path, subFiles);
376 if (subCounts.ts > 0) {
377 tsScore += Math.min(2, subCounts.ts);
378 jsHints.tsFiles = true;
@@ -404,13 +404,14 @@ const analyzeDirectory = (
404
405 const detectLanguage = (fs: FileSystem.FileSystem, cwd: string) =>
406 Effect.gen(function* () {
407 - const dirs = getAncestors(cwd);
407 + const path = yield* Path.Path;
408 + const dirs = yield* getAncestors(cwd);
409 let bestWeak: ReturnType<typeof pickBestWeak> | null = null;
410 let ambiguous: { dir: string; details: string } | null = null;
411
412 for (const [depth, dir] of dirs.entries()) {
412 - const evidence = yield* analyzeDirectory(fs, dir);
413 - const systemRoot = isSystemRoot(dir);
413 + const evidence = yield* analyzeDirectory(fs, path, dir);
414 + const systemRoot = isSystemRoot(path, dir);
415
416 if (evidence.strongJs && evidence.strongPy) {
417 if (depth === 0 && !systemRoot) {
@@ -441,7 +442,7 @@ const detectLanguage = (fs: FileSystem.FileSystem, cwd: string) =>
442 bestWeak = weakCandidate;
443 }
444
444 - if (bestWeak && !isSystemRoot(bestWeak.dir))
445 + if (bestWeak && !isSystemRoot(path, bestWeak.dir))
446 return {
447 language: bestWeak.language,
448 rootDir: bestWeak.dir,
@@ -470,9 +471,10 @@ const detectLanguage = (fs: FileSystem.FileSystem, cwd: string) =>
471
472 const detectJsPackageManager = (fs: FileSystem.FileSystem, cwd: string) =>
473 Effect.gen(function* () {
474 + const path = yield* Path.Path;
475 const readDirectoryOptional = makeReadDirectoryOptional(fs);
474 - const readPackageJson = makeReadPackageJson(fs);
475 - const dirs = getAncestors(cwd);
476 + const readPackageJson = makeReadPackageJson(fs, path);
477 + const dirs = yield* getAncestors(cwd);
478
479 for (const dir of dirs) {
480 const files = yield* readDirectoryOptional(dir);
@@ -504,9 +506,10 @@ const detectJsPackageManager = (fs: FileSystem.FileSystem, cwd: string) =>
506
507 const detectPythonPackageManager = (fs: FileSystem.FileSystem, cwd: string) =>
508 Effect.gen(function* () {
509 + const path = yield* Path.Path;
510 const readDirectoryOptional = makeReadDirectoryOptional(fs);
511 const readFileStringOptional = makeReadFileStringOptional(fs);
509 - const dirs = getAncestors(cwd);
512 + const dirs = yield* getAncestors(cwd);
513 let fallback: PythonPackageManager | null = null;
514
515 for (const dir of dirs) {
@@ -550,6 +553,7 @@ export class ProjectEnvironmentDetector extends Effect.Service<ProjectEnvironmen
553 {
554 effect: Effect.gen(function* () {
555 const fs = yield* FileSystem.FileSystem;
556 + const path = yield* Path.Path;
557
558 const detectProjectEnvironment = (
559 cwd: string
@@ -576,14 +580,16 @@ export class ProjectEnvironmentDetector extends Effect.Service<ProjectEnvironmen
580 rootDir: detection.rootDir,
581 evidence: detection.evidence.evidence,
582 } satisfies ProjectEnvironment;
579 - });
583 + }).pipe(Effect.provideService(Path.Path, path));
584
585 return {
586 detectProjectEnvironment,
583 - detectJsPackageManager: (cwd: string) => detectJsPackageManager(fs, cwd),
584 - detectPythonPackageManager: (cwd: string) => detectPythonPackageManager(fs, cwd),
587 + detectJsPackageManager: (cwd: string) =>
588 + detectJsPackageManager(fs, cwd).pipe(Effect.provideService(Path.Path, path)),
589 + detectPythonPackageManager: (cwd: string) =>
590 + detectPythonPackageManager(fs, cwd).pipe(Effect.provideService(Path.Path, path)),
591 };
592 }),
587 - dependencies: [BunFileSystem.layer],
593 + dependencies: [BunFileSystem.layer, Path.layer],
594 }
595 ) {}
ts/packages/cli/src/services/run-companion-modules.ts
+501 -282
@@ -1,23 +1,38 @@
1 -import * as fs from 'node:fs';
2 -import * as os from 'node:os';
3 -import * as path from 'node:path';
1 +// Companion-module asset resolution and self-repair helpers shared by the CLI runtime,
2 +// the bundled `composio run` companion modules, and the binary build scripts. Every
3 +// helper is an Effect over the @effect/platform FileSystem/Path services; consumers
4 +// outside the CLI runtime (companion runtimes, scripts) provide their own platform layers.
5 import { fileURLToPath } from 'node:url';
6 +import { FileSystem, Path } from '@effect/platform';
7 +import type { PlatformError } from '@effect/platform/Error';
8 +import { Config, ConfigProvider, Data, Effect, Option, Schema } from 'effect';
9 import extractZip from 'extract-zip';
10 +import { GitHubRelease } from 'src/effects/resolve-cli-release';
11 +import { BaseConfigProviderLive, extendConfigProvider } from 'src/services/config';
12 +import { parseChecksumsText, sha256Hex } from 'src/utils/checksums';
13
7 -export const RUN_COMPANION_MODULE_BASENAMES = [
14 +export const RUN_COMPANION_MODULE_BASENAMES: ReadonlyArray<string> = [
15 'run-helpers-runtime',
16 'run-subagent-shared',
17 'run-subagent-acp',
18 'run-subagent-legacy',
19 'run-subagent-output-mcp',
13 -] as const;
20 +];
21
22 export const RUN_COMPANION_MODULE_FILENAMES = RUN_COMPANION_MODULE_BASENAMES.map(
23 name => `${name}.mjs`
24 );
25
26 export const RUN_COMPANION_RELEASE_TAG_FILENAME = 'release-tag.txt';
20 -export const RUN_CODEX_ACP_BINARY_TARGETS = [
27 +type RunCodexAcpBinaryTarget = {
28 + readonly platform: NodeJS.Platform;
29 + readonly arch: string;
30 + readonly packageName: string;
31 + readonly binaryFileName: string;
32 + readonly relativePath: string;
33 +};
34 +
35 +export const RUN_CODEX_ACP_BINARY_TARGETS: ReadonlyArray<RunCodexAcpBinaryTarget> = [
36 {
37 platform: 'darwin',
38 arch: 'arm64',
@@ -46,102 +61,128 @@ export const RUN_CODEX_ACP_BINARY_TARGETS = [
61 binaryFileName: 'codex-acp',
62 relativePath: 'acp-adapters/codex/linux-x64/codex-acp',
63 },
49 -] as const;
50 -export const RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS = [
64 +];
65 +export const RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS: ReadonlyArray<string> = [
66 'acp-adapters/claude-code-acp.mjs',
67 // cli.js from @anthropic-ai/claude-agent-sdk must live next to claude-code-acp.mjs.
68 // The bundled adapter uses import.meta.url to locate it at runtime.
69 'acp-adapters/cli.js',
70 ...RUN_CODEX_ACP_BINARY_TARGETS.map(target => target.relativePath),
56 -] as const;
71 +];
72 +
73 +export class RunCompanionRepairError extends Data.TaggedError('services/RunCompanionRepairError')<{
74 + readonly message: string;
75 + readonly cause?: unknown;
76 +}> {}
77
78 const relativeImportPattern =
79 /(?:import\s+(?:[^'"]+?\s+from\s+)?|export\s+(?:\*\s+from\s+|\{[^}]+\}\s+from\s+)|import\s*\()\s*["'](\.{1,2}\/[^"']+?\.mjs)["']/g;
80
81 const isImportGraphFile = (relativePath: string) => /\.(?:m?js|ts)$/.test(relativePath);
82
83 +const fileExists = (fs: FileSystem.FileSystem, filePath: string) =>
84 + fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
85 +
86 const collectRelativeImportPaths = ({
87 + fs,
88 + path,
89 rootDir,
90 relativePath,
91 collected,
92 recordMissingPaths = false,
93 }: {
94 + fs: FileSystem.FileSystem;
95 + path: Path.Path;
96 rootDir: string;
97 relativePath: string;
98 collected: Set<string>;
99 recordMissingPaths?: boolean;
73 -}): void => {
74 - const normalizedRelativePath = relativePath.replaceAll(path.sep, '/');
75 - if (collected.has(normalizedRelativePath)) {
76 - return;
77 - }
78 -
79 - const absolutePath = path.join(rootDir, normalizedRelativePath);
80 - const exists = fs.existsSync(absolutePath);
81 - if (!exists && !recordMissingPaths) {
82 - return;
83 - }
84 -
85 - collected.add(normalizedRelativePath);
86 - if (!exists) {
87 - return;
88 - }
100 +}): Effect.Effect<void> =>
101 + Effect.gen(function* () {
102 + const normalizedRelativePath = relativePath.replaceAll(path.sep, '/');
103 + if (collected.has(normalizedRelativePath)) {
104 + return;
105 + }
106
90 - if (!isImportGraphFile(normalizedRelativePath)) {
91 - return;
92 - }
107 + const absolutePath = path.join(rootDir, normalizedRelativePath);
108 + const exists = yield* fileExists(fs, absolutePath);
109 + if (!exists && !recordMissingPaths) {
110 + return;
111 + }
112
94 - const source = fs.readFileSync(absolutePath, 'utf8');
95 - for (const match of source.matchAll(relativeImportPattern)) {
96 - const specifier = match[1];
97 - if (!specifier) {
98 - continue;
113 + collected.add(normalizedRelativePath);
114 + if (!exists) {
115 + return;
116 }
117
101 - const dependencyRelativePath = path
102 - .relative(rootDir, path.resolve(path.dirname(absolutePath), specifier))
103 - .replaceAll(path.sep, '/');
118 + if (!isImportGraphFile(normalizedRelativePath)) {
119 + return;
120 + }
121
105 - collectRelativeImportPaths({
106 - rootDir,
107 - relativePath: dependencyRelativePath,
108 - collected,
109 - recordMissingPaths,
110 - });
111 - }
112 -};
122 + const source = yield* Effect.orDie(fs.readFileString(absolutePath, 'utf8'));
123 + for (const match of source.matchAll(relativeImportPattern)) {
124 + const specifier = match[1];
125 + if (!specifier) {
126 + continue;
127 + }
128
114 -export const collectRunCompanionAssetRelativePaths = (rootDir: string): ReadonlyArray<string> => {
115 - const collected = new Set<string>();
129 + const dependencyRelativePath = path
130 + .relative(rootDir, path.resolve(path.dirname(absolutePath), specifier))
131 + .replaceAll(path.sep, '/');
132
117 - for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
118 - collectRelativeImportPaths({
119 - rootDir,
120 - relativePath: fileName,
121 - collected,
122 - });
123 - }
133 + yield* collectRelativeImportPaths({
134 + fs,
135 + path,
136 + rootDir,
137 + relativePath: dependencyRelativePath,
138 + collected,
139 + recordMissingPaths,
140 + });
141 + }
142 + });
143
125 - if (collected.size === 0) {
126 - for (const baseName of RUN_COMPANION_MODULE_BASENAMES) {
127 - collectRelativeImportPaths({
144 +export const collectRunCompanionAssetRelativePaths = (
145 + rootDir: string
146 +): Effect.Effect<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> =>
147 + Effect.gen(function* () {
148 + const fs = yield* FileSystem.FileSystem;
149 + const path = yield* Path.Path;
150 + const collected = new Set<string>();
151 +
152 + for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
153 + yield* collectRelativeImportPaths({
154 + fs,
155 + path,
156 rootDir,
129 - relativePath: path.posix.join('services', `${baseName}.mjs`),
157 + relativePath: fileName,
158 collected,
159 });
160 }
133 - }
161
135 - for (const relativePath of RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS) {
136 - collectRelativeImportPaths({
137 - rootDir,
138 - relativePath,
139 - collected,
140 - });
141 - }
162 + if (collected.size === 0) {
163 + for (const baseName of RUN_COMPANION_MODULE_BASENAMES) {
164 + yield* collectRelativeImportPaths({
165 + fs,
166 + path,
167 + rootDir,
168 + relativePath: `services/${baseName}.mjs`,
169 + collected,
170 + });
171 + }
172 + }
173
143 - return [...collected].sort();
144 -};
174 + for (const relativePath of RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS) {
175 + yield* collectRelativeImportPaths({
176 + fs,
177 + path,
178 + rootDir,
179 + relativePath,
180 + collected,
181 + });
182 + }
183 +
184 + return [...collected].sort();
185 + });
186
187 export const resolveRunCompanionAssetPath = ({
188 callerImportMetaUrl,
@@ -151,69 +192,62 @@ export const resolveRunCompanionAssetPath = ({
192 callerImportMetaUrl: string;
193 execPath: string;
194 relativePathFromRoot: string;
154 -}): string | null => {
155 - const currentFilePath = fileURLToPath(callerImportMetaUrl);
156 - const currentDirectory = path.dirname(currentFilePath);
157 - const executableDirectory = path.dirname(execPath);
158 -
159 - const candidates = [
160 - path.resolve(currentDirectory, relativePathFromRoot),
161 - path.resolve(currentDirectory, '..', relativePathFromRoot),
162 - path.resolve(executableDirectory, relativePathFromRoot),
163 - ];
164 -
165 - for (const candidate of candidates) {
166 - if (fs.existsSync(candidate)) {
167 - return candidate;
168 - }
169 - }
170 -
171 - return null;
172 -};
195 +}): Effect.Effect<string | null, never, FileSystem.FileSystem | Path.Path> =>
196 + Effect.gen(function* () {
197 + const fs = yield* FileSystem.FileSystem;
198 + const path = yield* Path.Path;
199 + const currentFilePath = fileURLToPath(callerImportMetaUrl);
200 + const currentDirectory = path.dirname(currentFilePath);
201 + const executableDirectory = path.dirname(execPath);
202 +
203 + const candidates = [
204 + path.resolve(currentDirectory, relativePathFromRoot),
205 + path.resolve(currentDirectory, '..', relativePathFromRoot),
206 + path.resolve(executableDirectory, relativePathFromRoot),
207 + ];
208 +
209 + const found = yield* Effect.findFirst(candidates, candidate => fileExists(fs, candidate));
210 + return Option.getOrNull(found);
211 + });
212
213 export const collectExpectedRunCompanionAssetRelativePaths = (
214 rootDir: string
176 -): ReadonlyArray<string> => {
177 - const collected = new Set<string>();
178 -
179 - for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
180 - collectRelativeImportPaths({
181 - rootDir,
182 - relativePath: fileName,
183 - collected,
184 - recordMissingPaths: true,
185 - });
186 - }
187 -
188 - for (const relativePath of RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS) {
189 - collectRelativeImportPaths({
190 - rootDir,
191 - relativePath,
192 - collected,
193 - recordMissingPaths: true,
194 - });
195 - }
196 -
197 - return [...collected].sort();
198 -};
215 +): Effect.Effect<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> =>
216 + Effect.gen(function* () {
217 + const fs = yield* FileSystem.FileSystem;
218 + const path = yield* Path.Path;
219 + const collected = new Set<string>();
220 +
221 + for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
222 + yield* collectRelativeImportPaths({
223 + fs,
224 + path,
225 + rootDir,
226 + relativePath: fileName,
227 + collected,
228 + recordMissingPaths: true,
229 + });
230 + }
231
200 -type GitHubReleaseAsset = {
201 - name: string;
202 - browser_download_url: string;
203 -};
232 + for (const relativePath of RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS) {
233 + yield* collectRelativeImportPaths({
234 + fs,
235 + path,
236 + rootDir,
237 + relativePath,
238 + collected,
239 + recordMissingPaths: true,
240 + });
241 + }
242
205 -type GitHubRelease = {
206 - tag_name: string;
207 - assets: GitHubReleaseAsset[];
208 -};
243 + return [...collected].sort();
244 + });
245
246 const DEFAULT_GITHUB_CONFIG = {
247 apiBaseUrl: 'https://api.github.com',
248 owner: 'ComposioHQ',
249 repo: 'composio',
214 -} as const;
215 -
216 -const resolveCompanionInstallDirectory = (execPath: string) => path.dirname(execPath);
250 +};
251
252 const resolveBinaryAssetName = ({
253 platform = process.platform,
@@ -232,23 +266,32 @@ const resolveBinaryAssetName = ({
266 case 'linux-arm64':
267 return 'composio-linux-aarch64.zip';
268 default:
235 - throw new Error(`Unsupported platform for run companion repair: ${platform}-${arch}`);
269 + return undefined;
270 }
271 };
272
239 -const readTextFileIfPresent = (filePath: string) => {
240 - if (!fs.existsSync(filePath)) {
241 - return undefined;
242 - }
273 +const readTextFileIfPresent = (fs: FileSystem.FileSystem, filePath: string) =>
274 + Effect.gen(function* () {
275 + const exists = yield* fileExists(fs, filePath);
276 + if (!exists) {
277 + return undefined;
278 + }
279
244 - const value = fs.readFileSync(filePath, 'utf8').trim();
245 - return value.length > 0 ? value : undefined;
246 -};
280 + const value = (yield* Effect.orDie(fs.readFileString(filePath, 'utf8'))).trim();
281 + return value.length > 0 ? value : undefined;
282 + });
283
248 -export const readInstalledReleaseTag = (execPath: string) =>
249 - readTextFileIfPresent(
250 - path.join(resolveCompanionInstallDirectory(execPath), RUN_COMPANION_RELEASE_TAG_FILENAME)
251 - );
284 +export const readInstalledReleaseTag = (
285 + execPath: string
286 +): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>
287 + Effect.gen(function* () {
288 + const fs = yield* FileSystem.FileSystem;
289 + const path = yield* Path.Path;
290 + return yield* readTextFileIfPresent(
291 + fs,
292 + path.join(path.dirname(execPath), RUN_COMPANION_RELEASE_TAG_FILENAME)
293 + );
294 + });
295
296 export const normalizeCliReleaseVersion = (releaseIdentifier: string): string => {
297 const trimmed = releaseIdentifier.trim();
@@ -261,33 +304,53 @@ export const normalizeCliReleaseVersion = (releaseIdentifier: string): string =>
304 return trimmed;
305 };
306
264 -export const resolveInstalledCliVersion = (execPath: string, fallbackVersion: string): string =>
265 - normalizeCliReleaseVersion(readInstalledReleaseTag(execPath) ?? fallbackVersion);
266 -
267 -export const writeInstalledReleaseTag = (installDir: string, releaseTag: string) => {
268 - fs.writeFileSync(
269 - path.join(installDir, RUN_COMPANION_RELEASE_TAG_FILENAME),
270 - `${releaseTag}\n`,
271 - 'utf8'
307 +export const resolveInstalledCliVersion = (
308 + execPath: string,
309 + fallbackVersion: string
310 +): Effect.Effect<string, never, FileSystem.FileSystem | Path.Path> =>
311 + Effect.map(readInstalledReleaseTag(execPath), releaseTag =>
312 + normalizeCliReleaseVersion(releaseTag ?? fallbackVersion)
313 );
273 -};
314
275 -export const listMissingInstalledRunCompanionModules = (execPath: string) => {
276 - const installDirectory = resolveCompanionInstallDirectory(execPath);
277 - return collectExpectedRunCompanionAssetRelativePaths(installDirectory).filter(
278 - relativePath => !fs.existsSync(path.join(installDirectory, relativePath))
279 - );
280 -};
315 +export const writeInstalledReleaseTag = (
316 + installDir: string,
317 + releaseTag: string
318 +): Effect.Effect<void, PlatformError, FileSystem.FileSystem | Path.Path> =>
319 + Effect.gen(function* () {
320 + const fs = yield* FileSystem.FileSystem;
321 + const path = yield* Path.Path;
322 + yield* fs.writeFileString(
323 + path.join(installDir, RUN_COMPANION_RELEASE_TAG_FILENAME),
324 + `${releaseTag}\n`
325 + );
326 + });
327
282 -const fetchGitHubJson = async <T>({
283 - url,
284 - accessToken,
285 - fetchErrorMessage,
286 -}: {
287 - url: string;
288 - accessToken?: string;
289 - fetchErrorMessage: string;
290 -}): Promise<T> => {
328 +export const listMissingInstalledRunCompanionModules = (
329 + execPath: string
330 +): Effect.Effect<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> =>
331 + Effect.gen(function* () {
332 + const fs = yield* FileSystem.FileSystem;
333 + const path = yield* Path.Path;
334 + const installDirectory = path.dirname(execPath);
335 + const expectedRelativePaths =
336 + yield* collectExpectedRunCompanionAssetRelativePaths(installDirectory);
337 + return yield* Effect.filter(expectedRelativePaths, relativePath =>
338 + Effect.map(fileExists(fs, path.join(installDirectory, relativePath)), exists => !exists)
339 + );
340 + });
341 +
342 +const fetchGitHubJson = async <A, I>(
343 + schema: Schema.Schema<A, I>,
344 + {
345 + url,
346 + accessToken,
347 + fetchErrorMessage,
348 + }: {
349 + url: string;
350 + accessToken?: string;
351 + fetchErrorMessage: string;
352 + }
353 +): Promise<A> => {
354 const response = await fetch(url, {
355 headers: {
356 Accept: 'application/vnd.github+json',
@@ -301,7 +364,7 @@ const fetchGitHubJson = async <T>({
364 throw new Error(`${fetchErrorMessage} (HTTP ${response.status}${body ? `: ${body}` : ''})`);
365 }
366
304 - return (await response.json()) as T;
367 + return Schema.decodeUnknownPromise(schema)(await response.json());
368 };
369
370 const fetchChecksums = async ({
@@ -324,21 +387,7 @@ const fetchChecksums = async ({
387 return undefined;
388 }
389
327 - const text = await response.text();
328 - const checksums = new Map<string, string>();
329 - for (const line of text.split('\n')) {
330 - const trimmed = line.trim();
331 - if (!trimmed) {
332 - continue;
333 - }
334 -
335 - const parts = trimmed.split(/\s+/);
336 - if (parts.length >= 2) {
337 - checksums.set(parts[1]!, parts[0]!);
338 - }
339 - }
340 -
341 - return checksums;
390 + return parseChecksumsText(await response.text());
391 };
392
393 const verifyChecksum = async ({
@@ -350,10 +399,7 @@ const verifyChecksum = async ({
399 expectedHash: string;
400 fileName: string;
401 }) => {
353 - const digest = await crypto.subtle.digest('SHA-256', data.slice().buffer);
354 - const actualHash = Array.from(new Uint8Array(digest))
355 - .map(byte => byte.toString(16).padStart(2, '0'))
356 - .join('');
402 + const actualHash = await sha256Hex(data);
403
404 if (actualHash !== expectedHash) {
405 throw new Error(
@@ -362,6 +408,19 @@ const verifyChecksum = async ({
408 }
409 };
410
411 +const toRepairError = (error: unknown) =>
412 + new RunCompanionRepairError({
413 + message: error instanceof Error ? error.message : String(error),
414 + cause: error,
415 + });
416 +
417 +// Self-repair honors the unprefixed GITHUB_* contract (set by CI and the binary
418 +// build workflow, mirrored by cli-local-tools) first, then falls back to the
419 +// CLI-wide COMPOSIO_-prefixed spelling installed by cli-main's config provider.
420 +const repairConfigProvider = BaseConfigProviderLive.pipe(
421 + ConfigProvider.orElse(() => extendConfigProvider(BaseConfigProviderLive))
422 +);
423 +
424 const resolveRepairReleaseTag = ({
425 execPath,
426 appVersion,
@@ -369,11 +428,40 @@ const resolveRepairReleaseTag = ({
428 execPath: string;
429 appVersion: string;
430 }) =>
372 - process.env.GITHUB_TAG?.trim() ||
373 - readInstalledReleaseTag(execPath) ||
374 - `@composio/cli@${appVersion}`;
431 + Effect.gen(function* () {
432 + // GITHUB_TAG pins the release used for self-repair (set by the binary build workflow).
433 + const pinnedTag = yield* Effect.orDie(
434 + Config.option(Config.string('GITHUB_TAG')).pipe(
435 + Config.map(tag => Option.getOrUndefined(Option.map(tag, value => value.trim())))
436 + )
437 + ).pipe(Effect.withConfigProvider(repairConfigProvider));
438 + if (pinnedTag) {
439 + return pinnedTag;
440 + }
441
376 -export const repairMissingInstalledRunCompanionModules = async ({
442 + const installedTag = yield* readInstalledReleaseTag(execPath);
443 + return installedTag || `@composio/cli@${appVersion}`;
444 + });
445 +
446 +const nonEmptyConfigWithFallback = (name: string, fallback: string) =>
447 + Config.string(name).pipe(
448 + Config.map(value => value || fallback),
449 + Config.withDefault(fallback)
450 + );
451 +
452 +// The GITHUB_* overrides let CI and forks redirect the self-repair download.
453 +const githubRepairConfig = Effect.orDie(
454 + Effect.all({
455 + apiBaseUrl: nonEmptyConfigWithFallback('GITHUB_API_BASE_URL', DEFAULT_GITHUB_CONFIG.apiBaseUrl),
456 + owner: nonEmptyConfigWithFallback('GITHUB_OWNER', DEFAULT_GITHUB_CONFIG.owner),
457 + repo: nonEmptyConfigWithFallback('GITHUB_REPO', DEFAULT_GITHUB_CONFIG.repo),
458 + accessToken: Config.option(Config.string('GITHUB_ACCESS_TOKEN')).pipe(
459 + Config.map(Option.getOrUndefined)
460 + ),
461 + })
462 +).pipe(Effect.withConfigProvider(repairConfigProvider));
463 +
464 +export const repairMissingInstalledRunCompanionModules = ({
465 callerImportMetaUrl,
466 execPath,
467 appVersion,
@@ -381,109 +469,240 @@ export const repairMissingInstalledRunCompanionModules = async ({
469 callerImportMetaUrl: string;
470 execPath: string;
471 appVersion: string;
384 -}) => {
385 - const currentFilePath = fileURLToPath(callerImportMetaUrl);
386 - if (!currentFilePath.startsWith('/$bunfs/')) {
387 - return { repaired: false as const };
388 - }
472 +}): Effect.Effect<
473 + { readonly repaired: false } | { readonly repaired: true; readonly releaseTag: string },
474 + RunCompanionRepairError | PlatformError,
475 + FileSystem.FileSystem | Path.Path
476 +> =>
477 + Effect.gen(function* () {
478 + const fs = yield* FileSystem.FileSystem;
479 + const path = yield* Path.Path;
480 +
481 + const currentFilePath = fileURLToPath(callerImportMetaUrl);
482 + if (!currentFilePath.startsWith('/$bunfs/')) {
483 + return { repaired: false as const };
484 + }
485
390 - const missingModules = listMissingInstalledRunCompanionModules(execPath);
391 - if (missingModules.length === 0) {
392 - return { repaired: false as const };
393 - }
486 + const missingModules = yield* listMissingInstalledRunCompanionModules(execPath);
487 + if (missingModules.length === 0) {
488 + return { repaired: false as const };
489 + }
490
395 - const releaseTag = resolveRepairReleaseTag({ execPath, appVersion });
396 - const githubConfig = {
397 - apiBaseUrl: process.env.GITHUB_API_BASE_URL || DEFAULT_GITHUB_CONFIG.apiBaseUrl,
398 - owner: process.env.GITHUB_OWNER || DEFAULT_GITHUB_CONFIG.owner,
399 - repo: process.env.GITHUB_REPO || DEFAULT_GITHUB_CONFIG.repo,
400 - accessToken: process.env.GITHUB_ACCESS_TOKEN,
401 - };
402 -
403 - const encodedTag = encodeURIComponent(releaseTag);
404 - const release = await fetchGitHubJson<GitHubRelease>({
405 - url: `${githubConfig.apiBaseUrl}/repos/${githubConfig.owner}/${githubConfig.repo}/releases/tags/${encodedTag}`,
406 - accessToken: githubConfig.accessToken,
407 - fetchErrorMessage: `Failed to fetch release metadata for ${releaseTag} while repairing run companion modules`,
408 - }).catch(error => {
409 - throw new Error(
410 - [
411 - `Unable to restore the files required by 'composio run' for ${releaseTag}.`,
412 - error instanceof Error ? error.message : String(error),
413 - `Reinstall the CLI, or set GITHUB_TAG to the exact release tag for this build and try again.`,
414 - ].join('\n')
491 + const releaseTag = yield* resolveRepairReleaseTag({ execPath, appVersion });
492 + const githubConfig = yield* githubRepairConfig;
493 +
494 + const encodedTag = encodeURIComponent(releaseTag);
495 + const release = yield* Effect.tryPromise({
496 + try: () =>
497 + fetchGitHubJson(GitHubRelease, {
498 + url: `${githubConfig.apiBaseUrl}/repos/${githubConfig.owner}/${githubConfig.repo}/releases/tags/${encodedTag}`,
499 + accessToken: githubConfig.accessToken,
500 + fetchErrorMessage: `Failed to fetch release metadata for ${releaseTag} while repairing run companion modules`,
501 + }),
502 + catch: error =>
503 + new RunCompanionRepairError({
504 + message: [
505 + `Unable to restore the files required by 'composio run' for ${releaseTag}.`,
506 + error instanceof Error ? error.message : String(error),
507 + `Reinstall the CLI, or set GITHUB_TAG to the exact release tag for this build and try again.`,
508 + ].join('\n'),
509 + cause: error,
510 + }),
511 + });
512 +
513 + const assetName = resolveBinaryAssetName({});
514 + if (!assetName) {
515 + return yield* Effect.fail(
516 + new RunCompanionRepairError({
517 + message: `Unsupported platform for run companion repair: ${process.platform}-${process.arch}`,
518 + })
519 + );
520 + }
521 +
522 + const asset = release.assets.find(candidate => candidate.name === assetName);
523 + if (!asset) {
524 + return yield* Effect.fail(
525 + new RunCompanionRepairError({
526 + message: `Release ${release.tag_name} does not contain ${assetName}; cannot restore run companion modules.`,
527 + })
528 + );
529 + }
530 +
531 + const archiveData = yield* Effect.tryPromise({
532 + try: async () => {
533 + const archiveResponse = await fetch(asset.browser_download_url, {
534 + headers: githubConfig.accessToken
535 + ? { Authorization: `Bearer ${githubConfig.accessToken}` }
536 + : undefined,
537 + });
538 + if (!archiveResponse.ok) {
539 + throw new Error(
540 + `Failed to download ${asset.name} from ${release.tag_name} while repairing run companion modules (HTTP ${archiveResponse.status}).`
541 + );
542 + }
543 + return new Uint8Array(await archiveResponse.arrayBuffer());
544 + },
545 + catch: toRepairError,
546 + });
547 +
548 + const checksums = yield* Effect.tryPromise({
549 + try: () =>
550 + fetchChecksums({
551 + release,
552 + accessToken: githubConfig.accessToken,
553 + }),
554 + catch: toRepairError,
555 + });
556 + const expectedChecksum = checksums?.get(asset.name);
557 + if (expectedChecksum) {
558 + yield* Effect.tryPromise({
559 + try: () =>
560 + verifyChecksum({
561 + data: archiveData,
562 + expectedHash: expectedChecksum,
563 + fileName: asset.name,
564 + }),
565 + catch: toRepairError,
566 + });
567 + }
568 +
569 + return yield* Effect.scoped(
570 + Effect.gen(function* () {
571 + const tempDirectory = yield* fs.makeTempDirectoryScoped({
572 + prefix: 'composio-run-repair-',
573 + });
574 + const archivePath = path.join(tempDirectory, asset.name);
575 + const extractDirectory = path.join(tempDirectory, 'extract');
576 + const packageDirectory = path.join(extractDirectory, path.parse(asset.name).name);
577 + yield* fs.writeFile(archivePath, archiveData);
578 + yield* fs.makeDirectory(extractDirectory, { recursive: true });
579 + yield* Effect.tryPromise({
580 + try: () => extractZip(archivePath, { dir: extractDirectory }),
581 + catch: toRepairError,
582 + });
583 +
584 + const installDirectory = path.dirname(execPath);
585 + const companionRelativePaths =
586 + yield* collectExpectedRunCompanionAssetRelativePaths(packageDirectory);
587 +
588 + for (const relativePath of companionRelativePaths) {
589 + const sourcePath = path.join(packageDirectory, relativePath);
590 + const sourceExists = yield* fileExists(fs, sourcePath);
591 + if (!sourceExists) {
592 + return yield* Effect.fail(
593 + new RunCompanionRepairError({
594 + message: `Release ${release.tag_name} is missing ${relativePath}; cannot restore the files required by 'composio run'.`,
595 + })
596 + );
597 + }
598 +
599 + const targetPath = path.join(installDirectory, relativePath);
600 + yield* fs.makeDirectory(path.dirname(targetPath), { recursive: true });
601 + yield* fs.copyFile(sourcePath, targetPath);
602 + }
603 +
604 + yield* writeInstalledReleaseTag(installDirectory, release.tag_name);
605 + return {
606 + repaired: true as const,
607 + releaseTag: release.tag_name,
608 + };
609 + })
610 );
611 });
612
418 - const assetName = resolveBinaryAssetName({});
419 - const asset = release.assets.find(candidate => candidate.name === assetName);
420 - if (!asset) {
421 - throw new Error(
422 - `Release ${release.tag_name} does not contain ${assetName}; cannot restore run companion modules.`
613 +export const resolveRunCompanionModulePath = ({
614 + callerImportMetaUrl,
615 + execPath,
616 + relativeNoExtensionFromCaller,
617 +}: {
618 + callerImportMetaUrl: string;
619 + execPath: string;
620 + relativeNoExtensionFromCaller: string;
621 +}): Effect.Effect<string, never, FileSystem.FileSystem | Path.Path> =>
622 + Effect.gen(function* () {
623 + const fs = yield* FileSystem.FileSystem;
624 + const path = yield* Path.Path;
625 + const currentFilePath = fileURLToPath(callerImportMetaUrl);
626 + const currentDirectory = path.dirname(currentFilePath);
627 + const executableDirectory = path.dirname(execPath);
628 + const baseName = path.basename(relativeNoExtensionFromCaller);
629 +
630 + const candidates = [
631 + path.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.ts`),
632 + path.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.js`),
633 + path.resolve(currentDirectory, 'services', `${baseName}.mjs`),
634 + path.resolve(currentDirectory, 'services', `${baseName}.js`),
635 + path.resolve(currentDirectory, `${baseName}.mjs`),
636 + path.resolve(currentDirectory, `${baseName}.js`),
637 + path.resolve(executableDirectory, `${baseName}.mjs`),
638 + path.resolve(executableDirectory, `${baseName}.js`),
639 + ];
640 +
641 + const found = yield* Effect.findFirst(candidates, candidate => fileExists(fs, candidate));
642 + return Option.getOrElse(found, () =>
643 + currentFilePath.startsWith('/$bunfs/')
644 + ? path.resolve(executableDirectory, `${baseName}.mjs`)
645 + : path.resolve(currentDirectory, `${baseName}.mjs`)
646 );
424 - }
425 -
426 - const archiveResponse = await fetch(asset.browser_download_url, {
427 - headers: githubConfig.accessToken
428 - ? { Authorization: `Bearer ${githubConfig.accessToken}` }
429 - : undefined,
647 });
431 - if (!archiveResponse.ok) {
432 - throw new Error(
433 - `Failed to download ${asset.name} from ${release.tag_name} while repairing run companion modules (HTTP ${archiveResponse.status}).`
434 - );
435 - }
648
437 - const archiveData = new Uint8Array(await archiveResponse.arrayBuffer());
438 - const checksums = await fetchChecksums({
439 - release,
440 - accessToken: githubConfig.accessToken,
441 - });
442 - const expectedChecksum = checksums?.get(asset.name);
443 - if (expectedChecksum) {
444 - await verifyChecksum({
445 - data: archiveData,
446 - expectedHash: expectedChecksum,
447 - fileName: asset.name,
448 - });
649 +// ── Temporary sync bridges ──────────────────────────────────────────────
650 +//
651 +// The callers below still run outside the Effect runtime and are migrated
652 +// wholesale by the typed-error slice (PR 8 of this stack), which deletes this
653 +// whole section: update-check.ts and run-subagent-acp.ts. Do not add new
654 +// callers.
655 +
656 +// eslint-disable-next-line no-restricted-imports -- temporary sync bridge for pre-migration callers, removed with the typed-error slice (PR 8 of this stack)
657 +import * as fsSync from 'node:fs';
658 +// eslint-disable-next-line no-restricted-imports -- temporary sync bridge for pre-migration callers, removed with the typed-error slice (PR 8 of this stack)
659 +import * as pathSync from 'node:path';
660 +
661 +const readTextFileIfPresentSync = (filePath: string) => {
662 + if (!fsSync.existsSync(filePath)) {
663 + return undefined;
664 }
665
451 - const tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-repair-'));
452 - try {
453 - const archivePath = path.join(tempDirectory, asset.name);
454 - const extractDirectory = path.join(tempDirectory, 'extract');
455 - const packageDirectory = path.join(extractDirectory, path.parse(asset.name).name);
456 - fs.writeFileSync(archivePath, archiveData);
457 - fs.mkdirSync(extractDirectory, { recursive: true });
458 - await extractZip(archivePath, { dir: extractDirectory });
459 -
460 - const installDirectory = resolveCompanionInstallDirectory(execPath);
461 - const companionRelativePaths = collectExpectedRunCompanionAssetRelativePaths(packageDirectory);
462 -
463 - for (const relativePath of companionRelativePaths) {
464 - const sourcePath = path.join(packageDirectory, relativePath);
465 - if (!fs.existsSync(sourcePath)) {
466 - throw new Error(
467 - `Release ${release.tag_name} is missing ${relativePath}; cannot restore the files required by 'composio run'.`
468 - );
469 - }
666 + const value = fsSync.readFileSync(filePath, 'utf8').trim();
667 + return value.length > 0 ? value : undefined;
668 +};
669
471 - const targetPath = path.join(installDirectory, relativePath);
472 - fs.mkdirSync(path.dirname(targetPath), { recursive: true });
473 - fs.copyFileSync(sourcePath, targetPath);
474 - }
670 +export const resolveInstalledCliVersionSync = (execPath: string, fallbackVersion: string): string =>
671 + normalizeCliReleaseVersion(
672 + readTextFileIfPresentSync(
673 + pathSync.join(pathSync.dirname(execPath), RUN_COMPANION_RELEASE_TAG_FILENAME)
674 + ) ?? fallbackVersion
675 + );
676
476 - writeInstalledReleaseTag(installDirectory, release.tag_name);
477 - return {
478 - repaired: true as const,
479 - releaseTag: release.tag_name,
480 - };
481 - } finally {
482 - fs.rmSync(tempDirectory, { recursive: true, force: true });
677 +export const resolveRunCompanionAssetPathSync = ({
678 + callerImportMetaUrl,
679 + execPath,
680 + relativePathFromRoot,
681 +}: {
682 + callerImportMetaUrl: string;
683 + execPath: string;
684 + relativePathFromRoot: string;
685 +}): string | null => {
686 + const currentFilePath = fileURLToPath(callerImportMetaUrl);
687 + const currentDirectory = pathSync.dirname(currentFilePath);
688 + const executableDirectory = pathSync.dirname(execPath);
689 +
690 + const candidates = [
691 + pathSync.resolve(currentDirectory, relativePathFromRoot),
692 + pathSync.resolve(currentDirectory, '..', relativePathFromRoot),
693 + pathSync.resolve(executableDirectory, relativePathFromRoot),
694 + ];
695 +
696 + for (const candidate of candidates) {
697 + if (fsSync.existsSync(candidate)) {
698 + return candidate;
699 + }
700 }
701 +
702 + return null;
703 };
704
486 -export const resolveRunCompanionModulePath = ({
705 +export const resolveRunCompanionModulePathSync = ({
706 callerImportMetaUrl,
707 execPath,
708 relativeNoExtensionFromCaller,
@@ -493,28 +712,28 @@ export const resolveRunCompanionModulePath = ({
712 relativeNoExtensionFromCaller: string;
713 }): string => {
714 const currentFilePath = fileURLToPath(callerImportMetaUrl);
496 - const currentDirectory = path.dirname(currentFilePath);
497 - const executableDirectory = path.dirname(execPath);
498 - const baseName = path.basename(relativeNoExtensionFromCaller);
715 + const currentDirectory = pathSync.dirname(currentFilePath);
716 + const executableDirectory = pathSync.dirname(execPath);
717 + const baseName = pathSync.basename(relativeNoExtensionFromCaller);
718
719 const candidates = [
501 - path.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.ts`),
502 - path.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.js`),
503 - path.resolve(currentDirectory, 'services', `${baseName}.mjs`),
504 - path.resolve(currentDirectory, 'services', `${baseName}.js`),
505 - path.resolve(currentDirectory, `${baseName}.mjs`),
506 - path.resolve(currentDirectory, `${baseName}.js`),
507 - path.resolve(executableDirectory, `${baseName}.mjs`),
508 - path.resolve(executableDirectory, `${baseName}.js`),
720 + pathSync.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.ts`),
721 + pathSync.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.js`),
722 + pathSync.resolve(currentDirectory, 'services', `${baseName}.mjs`),
723 + pathSync.resolve(currentDirectory, 'services', `${baseName}.js`),
724 + pathSync.resolve(currentDirectory, `${baseName}.mjs`),
725 + pathSync.resolve(currentDirectory, `${baseName}.js`),
726 + pathSync.resolve(executableDirectory, `${baseName}.mjs`),
727 + pathSync.resolve(executableDirectory, `${baseName}.js`),
728 ];
729
730 for (const candidate of candidates) {
512 - if (fs.existsSync(candidate)) {
731 + if (fsSync.existsSync(candidate)) {
732 return candidate;
733 }
734 }
735
736 return currentFilePath.startsWith('/$bunfs/')
518 - ? path.resolve(executableDirectory, `${baseName}.mjs`)
519 - : path.resolve(currentDirectory, `${baseName}.mjs`);
737 + ? pathSync.resolve(executableDirectory, `${baseName}.mjs`)
738 + : pathSync.resolve(currentDirectory, `${baseName}.mjs`);
739 };
ts/packages/cli/src/services/run-helpers-runtime.ts
+3
@@ -1,5 +1,8 @@
1 +// eslint-disable-next-line no-restricted-imports -- sync fs for run-log appends, run-file writes, and CLI config reads in the child process, outside the Effect runtime
2 import * as fs from 'node:fs';
3 +// eslint-disable-next-line no-restricted-imports -- os.tmpdir() locates the fallback run-files directory in the child process, outside the Effect runtime
4 import * as os from 'node:os';
5 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
6 import * as path from 'node:path';
7 import process from 'node:process';
8 import { z } from 'zod';
ts/packages/cli/src/services/run-subagent-acp.ts
+9 -5
@@ -1,14 +1,18 @@
1 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
2 import * as fs from 'node:fs';
3 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
4 import { spawn } from 'node:child_process';
5 import { createRequire } from 'node:module';
6 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
7 import * as os from 'node:os';
8 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
9 import path from 'node:path';
10 import { Readable, Writable } from 'node:stream';
11 import * as acp from '@agentclientprotocol/sdk';
12 import type { MasterKind } from 'src/services/master-detector';
13 import {
10 - resolveRunCompanionAssetPath,
11 - resolveRunCompanionModulePath,
14 + resolveRunCompanionAssetPathSync,
15 + resolveRunCompanionModulePathSync,
16 RUN_CODEX_ACP_BINARY_TARGETS,
17 } from 'src/services/run-companion-modules';
18 import {
@@ -36,7 +40,7 @@ type LegacySetSessionModelConnection = {
40
41 const resolveShippedAdapterAsset = (target: InvokeAgentTarget): string | null => {
42 if (target === 'claude') {
39 - return resolveRunCompanionAssetPath({
43 + return resolveRunCompanionAssetPathSync({
44 callerImportMetaUrl: import.meta.url,
45 execPath: process.execPath,
46 relativePathFromRoot: 'acp-adapters/claude-code-acp.mjs',
@@ -50,7 +54,7 @@ const resolveShippedAdapterAsset = (target: InvokeAgentTarget): string | null =>
54 return null;
55 }
56
53 - return resolveRunCompanionAssetPath({
57 + return resolveRunCompanionAssetPathSync({
58 callerImportMetaUrl: import.meta.url,
59 execPath: process.execPath,
60 relativePathFromRoot: binaryTarget.relativePath,
@@ -131,7 +135,7 @@ export const resolveAcpAdapterCommand = (
135 };
136
137 const chunkFlushPattern = /[\s,.;:!?)\]}"]$/;
134 -const structuredOutputMcpModulePath = resolveRunCompanionModulePath({
138 +const structuredOutputMcpModulePath = resolveRunCompanionModulePathSync({
139 callerImportMetaUrl: import.meta.url,
140 execPath: process.execPath,
141 relativeNoExtensionFromCaller: './run-subagent-output-mcp',
ts/packages/cli/src/services/run-subagent-legacy.ts
+4
@@ -1,6 +1,10 @@
1 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
2 import * as fs from 'node:fs';
3 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
4 import * as os from 'node:os';
5 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
6 import * as path from 'node:path';
7 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
8 import { spawn } from 'node:child_process';
9 import type { MasterKind } from 'src/services/master-detector';
10 import {
ts/packages/cli/src/services/run-subagent-output-mcp.ts
+1
@@ -1,3 +1,4 @@
1 +// eslint-disable-next-line no-restricted-imports -- standalone MCP stdio sidecar entrypoint runs outside the CLI's Effect runtime; sync fs reads the schema file and writes the structured result file
2 import * as fs from 'node:fs';
3 import process from 'node:process';
4 import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
ts/packages/cli/src/services/setup-skill-installer.ts
+11 -3
@@ -13,7 +13,11 @@ import { NodeOs } from './node-os';
13 export const resolveSetupSkillReleaseTag = (
14 execPath = process.execPath,
15 fallbackVersion = APP_VERSION
16 -): string => readInstalledReleaseTag(execPath) ?? `@composio/cli@${fallbackVersion}`;
16 +): Effect.Effect<string, never, FileSystem.FileSystem | Path.Path> =>
17 + Effect.map(
18 + readInstalledReleaseTag(execPath),
19 + releaseTag => releaseTag ?? `@composio/cli@${fallbackVersion}`
20 + );
21
22 const checkClaudeSkillCurrent = (
23 fs: FileSystem.FileSystem,
@@ -111,12 +115,16 @@ export class SetupSkillInstaller extends Effect.Service<SetupSkillInstaller>()(
115 const os = yield* NodeOs;
116 const isCurrent = (releaseTag: string) =>
117 checkClaudeSkillCurrent(fs, path, os.homedir, releaseTag);
118 + const installedReleaseTag = resolveSetupSkillReleaseTag().pipe(
119 + Effect.provideService(FileSystem.FileSystem, fs),
120 + Effect.provideService(Path.Path, path)
121 + );
122
123 return {
116 - isClaudeSkillReady: isCurrent(resolveSetupSkillReleaseTag()),
124 + isClaudeSkillReady: Effect.flatMap(installedReleaseTag, isCurrent),
125 hasManagedClaudeSkill: hasManagedClaudeSkill(os.homedir),
126 ensureClaudeSkill: Effect.gen(function* () {
119 - const releaseTag = resolveSetupSkillReleaseTag();
127 + const releaseTag = yield* installedReleaseTag;
128 if (yield* isCurrent(releaseTag)) return false;
129
130 yield* installSkill({
ts/packages/cli/src/services/tool-file-uploads.ts
+2
@@ -1,4 +1,6 @@
1 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
2 import fs from 'node:fs/promises';
3 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
4 import path from 'node:path';
5 import type { Composio as RawComposioClient } from '@composio/client';
6 import { assertSafeFileUploadPath } from '@composio/core';
ts/packages/cli/src/services/tool-input-validation.ts
+1
@@ -1,3 +1,4 @@
1 +// eslint-disable-next-line no-restricted-imports -- migrated with the seam-rules slice (PR 6 of this stack)
2 import path from 'node:path';
3 import { FileSystem } from '@effect/platform';
4 import { Effect, Option } from 'effect';
ts/packages/cli/src/services/tool-permissions.ts
+3 -1
@@ -1,5 +1,7 @@
1 import http from 'node:http';
2 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
3 import fs from 'node:fs/promises';
4 +// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
5 import path from 'node:path';
6 import open from 'open';
7 import { detectCliPlatform } from '@composio/cli-local-tools';
@@ -958,7 +960,7 @@ const requestPermissionDecision = async (params: {
960 const nativeDecision = await requestNativeUiPermissionDecision(params).catch(() => undefined);
961 if (nativeDecision === 'allow_once' || nativeDecision === 'allow_session') return nativeDecision;
962 if (nativeDecision === 'deny' || nativeDecision === 'dismissed') return 'deny';
961 - return requestPermissionInBrowser({ ...params, agent: detectNativeUiCallerAgent() });
963 + return requestPermissionInBrowser({ ...params, agent: await detectNativeUiCallerAgent() });
964 };
965
966 export const gateToolExecution = (params: GateParams) =>
ts/packages/cli/src/services/tools-executor.ts
+2 -1
@@ -1,4 +1,4 @@
1 -import { FileSystem } from '@effect/platform';
1 +import { FileSystem, Path } from '@effect/platform';
2 import { Context, Effect, Layer } from 'effect';
3 import type { Composio } from '@composio/client';
4 import { executeLocalToolBySlug, resolveLocalTool } from '@composio/cli-local-tools';
@@ -57,6 +57,7 @@ export interface ToolsExecutor {
57 ToolExecuteResponse,
58 unknown,
59 | FileSystem.FileSystem
60 + | Path.Path
61 | NodeOs
62 | NodeProcess
63 | ComposioUserContext
ts/packages/cli/src/services/update-check.ts
+8 -2
@@ -1,12 +1,18 @@
1 +// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
2 import { readFileSync, mkdirSync } from 'node:fs';
3 +// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
4 import { writeFile } from 'node:fs/promises';
5 +// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
6 import { arch as getArch, homedir, platform as getPlatform } from 'node:os';
7 +// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
8 import { dirname, join } from 'node:path';
9 import semver from 'semver';
10 import { bold, cyanBright, dim } from 'src/ui/colors';
11 import { APP_VERSION, GITHUB_REPO } from '../constants';
12 import { isInteractiveTerminal } from 'src/utils/stdio';
9 -import { resolveInstalledCliVersion } from './run-companion-modules';
13 +// The sync bridge keeps this pre-migration module working until the
14 +// typed-error slice (PR 8 of this stack) makes it Effect-native.
15 +import { resolveInstalledCliVersionSync } from './run-companion-modules';
16
17 /**
18 * Background update check for @composio/cli.
@@ -69,7 +75,7 @@ function getCurrentBinaryAssetName(): string | undefined {
75
76 const defaultConfig: UpdateCheckConfig = {
77 stateFile: join(_home, 'update-check.json'),
72 - currentVersion: resolveInstalledCliVersion(process.execPath, APP_VERSION),
78 + currentVersion: resolveInstalledCliVersionSync(process.execPath, APP_VERSION),
79 checkIntervalMs: CHECK_INTERVAL_MS,
80 releasesUrl: `${GITHUB_REPO.API_BASE_URL}/repos/${GITHUB_REPO.OWNER}/${GITHUB_REPO.REPO}/releases?per_page=100`,
81 binaryAssetName: getCurrentBinaryAssetName(),
ts/packages/cli/src/services/upgrade-binary.ts
+552 -554
@@ -1,17 +1,15 @@
1 -import { Data, Effect, Config, Option } from 'effect';
2 -import { HttpClient, FileSystem } from '@effect/platform';
3 -import * as path from 'node:path';
4 -import { cp as copyPath, rm as removePath } from 'node:fs/promises';
1 +import { Data, Effect, Config, Match, Option, Predicate, Record as EffectRecord } from 'effect';
2 +import { HttpClient, HttpClientResponse, FileSystem, Path } from '@effect/platform';
3 import { APP_VERSION } from '../constants';
4 import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
5 import { GITHUB_CONFIG } from 'src/effects/github-config';
6 import { detectPlatform, type PlatformArch } from 'src/effects/detect-platform';
7 import { CompareSemverError, semverComparator } from 'src/effects/compare-semver';
10 -import { fetchLatestCliRelease, type GitHubRelease } from 'src/effects/resolve-cli-release';
8 +import { fetchLatestCliRelease, GitHubRelease } from 'src/effects/resolve-cli-release';
9 +import { parseChecksumsText, sha256Hex } from 'src/utils/checksums';
10
11 // Note: `node:zlib` does not support Github's zip files
12 import extractZip from 'extract-zip';
14 -import type { Predicate } from 'effect/Predicate';
13 import { renderPrettyError } from './utils/pretty-error';
14 import { TerminalUI } from './terminal-ui';
15 import {
@@ -37,607 +35,607 @@ const getBinaryAssetName = (platformArch: PlatformArch) =>
35 const hasPlatformBinaryAsset = (release: GitHubRelease, platformArch: PlatformArch) =>
36 release.assets.some(asset => asset.name === getBinaryAssetName(platformArch));
37
40 -// Service to manage CLI binary upgrades
41 -export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/UpgradeBinary', {
42 - accessors: true,
43 - // eslint-disable-next-line max-lines-per-function
44 - effect: Effect.gen(function* () {
45 - const httpClient = yield* HttpClient.HttpClient;
46 - const fs = yield* FileSystem.FileSystem;
47 - const githubConfig = yield* Config.all(GITHUB_CONFIG);
48 -
49 - /**
50 - * Fetch latest release from GitHub
51 - */
52 - const fetchGitHubJson = <T>({
53 - url,
54 - fetchErrorMessage,
55 - parseErrorMessage,
56 - }: {
57 - url: string;
58 - fetchErrorMessage: string;
59 - parseErrorMessage: string;
60 - }): Effect.Effect<T, UpgradeBinaryError, never> =>
61 - Effect.gen(function* () {
62 - yield* Effect.logDebug(`GET ${url}`);
38 +const GITHUB_CONFIG_ALL = Config.all(GITHUB_CONFIG);
39
64 - const response = yield* httpClient.get(url).pipe(
65 - Effect.catchAll(error =>
66 - Effect.fail(
67 - new UpgradeBinaryError({
68 - cause: error,
69 - message: fetchErrorMessage,
70 - })
71 - )
72 - )
73 - );
40 +// Dependencies resolved once at service construction time and threaded
41 +// through the module-level helpers below.
42 +interface UpgradeBinaryContext {
43 + readonly httpClient: HttpClient.HttpClient;
44 + readonly fs: FileSystem.FileSystem;
45 + readonly path: Path.Path;
46 + readonly githubConfig: Config.Config.Success<typeof GITHUB_CONFIG_ALL>;
47 +}
48
75 - if (response.status < 200 || response.status >= 300) {
76 - const pretty = yield* response.json.pipe(
77 - Effect.map(json => renderPrettyError(Object.entries(json as object))),
78 - Effect.catchAll(() => Effect.succeed(''))
49 +/**
50 + * Fetch latest release from GitHub
51 + */
52 +const fetchGitHubRelease = (
53 + { githubConfig, httpClient }: UpgradeBinaryContext,
54 + tag: string
55 +): Effect.Effect<GitHubRelease, UpgradeBinaryError, never> =>
56 + Effect.gen(function* () {
57 + const encodedTag = encodeURIComponent(tag);
58 + const url = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases/tags/${encodedTag}`;
59 + const fetchErrorMessage = `Failed to fetch tags/${tag} release from GitHub`;
60 + yield* Effect.logDebug(`GET ${url}`);
61 +
62 + const response = yield* httpClient.get(url).pipe(
63 + Effect.mapError(
64 + cause =>
65 + new UpgradeBinaryError({
66 + cause,
67 + message: fetchErrorMessage,
68 + })
69 + )
70 + );
71 +
72 + if (response.status < 200 || response.status >= 300) {
73 + const pretty = yield* response.json.pipe(
74 + Effect.map(json =>
75 + Predicate.isRecord(json) ? renderPrettyError(EffectRecord.toEntries(json)) : ''
76 + ),
77 + Effect.catchAll(() => Effect.succeed(''))
78 + );
79 +
80 + const cause = pretty ? `HTTP ${response.status}\n${pretty}` : `HTTP ${response.status}`;
81 + return yield* Effect.fail(
82 + new UpgradeBinaryError({
83 + cause,
84 + message: fetchErrorMessage,
85 + })
86 + );
87 + }
88 +
89 + return yield* HttpClientResponse.schemaBodyJson(GitHubRelease)(response).pipe(
90 + Effect.mapError(
91 + cause =>
92 + new UpgradeBinaryError({
93 + cause,
94 + message: 'Failed to parse GitHub release JSON response',
95 + })
96 + )
97 + );
98 + });
99 +
100 +const fetchLatestRelease = (
101 + ctx: UpgradeBinaryContext,
102 + platformArch: PlatformArch,
103 + options: {
104 + prerelease?: boolean;
105 + tag?: string;
106 + } = {}
107 +): Effect.Effect<GitHubRelease, UpgradeBinaryError, never> =>
108 + Effect.gen(function* () {
109 + const { githubConfig, httpClient } = ctx;
110 + const prerelease = options.prerelease ?? false;
111 + const explicitTag = options.tag ? Option.some(options.tag) : githubConfig.TAG;
112 + const release = yield* explicitTag.pipe(
113 + Option.match({
114 + onNone: Effect.fn(function* () {
115 + yield* Effect.logDebug(
116 + `No tag specified, resolving latest package-scoped CLI ${prerelease ? 'beta' : 'stable'} release`
117 );
80 -
81 - const cause = pretty ? `HTTP ${response.status}\n${pretty}` : `HTTP ${response.status}`;
82 - return yield* Effect.fail(
83 - new UpgradeBinaryError({
84 - cause,
85 - message: fetchErrorMessage,
86 - })
118 + const latest = yield* fetchLatestCliRelease({
119 + assetDescription: getBinaryAssetName(platformArch),
120 + channel: prerelease ? 'beta' : 'stable',
121 + githubConfig,
122 + hasRequiredAsset: release => hasPlatformBinaryAsset(release, platformArch),
123 + httpClient,
124 + }).pipe(
125 + Effect.mapError(
126 + error =>
127 + new UpgradeBinaryError({
128 + cause: error,
129 + message: Match.value(error.reason).pipe(
130 + Match.when('request', () => 'Failed to fetch releases from GitHub'),
131 + Match.when('http-status', () => 'Failed to fetch releases from GitHub'),
132 + Match.when('decode', () => 'Failed to parse GitHub releases JSON response'),
133 + Match.when(
134 + 'not-found',
135 + () =>
136 + `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`
137 + ),
138 + Match.when(
139 + 'compare',
140 + () =>
141 + `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`
142 + ),
143 + Match.exhaustive
144 + ),
145 + })
146 + )
147 );
88 - }
148
90 - return (yield* response.json.pipe(
91 - Effect.catchAll(error =>
92 - Effect.fail(
93 - new UpgradeBinaryError({
94 - cause: error,
95 - message: parseErrorMessage,
96 - })
97 - )
98 - )
99 - )) as T;
100 - });
101 -
102 - const fetchLatestRelease = (
103 - platformArch: PlatformArch,
104 - options: {
105 - prerelease?: boolean;
106 - tag?: string;
107 - } = {}
108 - ): Effect.Effect<GitHubRelease, UpgradeBinaryError, never> =>
109 - Effect.gen(function* () {
110 - const prerelease = options.prerelease ?? false;
111 - const explicitTag = options.tag ? Option.some(options.tag) : githubConfig.TAG;
112 - const release = yield* explicitTag.pipe(
113 - Option.match({
114 - onNone: Effect.fn(function* () {
115 - yield* Effect.logDebug(
116 - `No tag specified, resolving latest package-scoped CLI ${prerelease ? 'beta' : 'stable'} release`
117 - );
118 - const latest = yield* fetchLatestCliRelease({
119 - assetDescription: getBinaryAssetName(platformArch),
120 - channel: prerelease ? 'beta' : 'stable',
121 - githubConfig,
122 - hasRequiredAsset: release => hasPlatformBinaryAsset(release, platformArch),
123 - httpClient,
124 - }).pipe(
125 - Effect.mapError(
126 - error =>
127 - new UpgradeBinaryError({
128 - cause: error,
129 - message: error.message.startsWith('Failed to fetch ')
130 - ? 'Failed to fetch releases from GitHub'
131 - : error.message === 'Failed to parse GitHub releases JSON'
132 - ? 'Failed to parse GitHub releases JSON response'
133 - : `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`,
134 - })
135 - )
136 - );
137 -
138 - yield* Effect.logDebug(`Resolved latest CLI release tag: ${latest.tag_name}`);
139 - return latest;
140 - }),
141 - onSome: Effect.fn(function* (tag) {
142 - yield* Effect.logDebug(`Using tag: ${tag}`);
143 - const encodedTag = encodeURIComponent(tag);
144 - const url = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases/tags/${encodedTag}`;
145 - const release = yield* fetchGitHubJson<GitHubRelease>({
146 - url,
147 - fetchErrorMessage: `Failed to fetch tags/${tag} release from GitHub`,
148 - parseErrorMessage: 'Failed to parse GitHub release JSON response',
149 - });
150 -
151 - return release as GitHubRelease;
152 - }),
153 - })
154 - );
155 - return release;
156 - });
157 -
158 - /**
159 - * Check if update is available
160 - */
161 - const resolveCurrentReleaseIdentifier = (currentPath: string) =>
162 - readInstalledReleaseTag(currentPath) || `@composio/cli@${APP_VERSION}`;
163 -
164 - const isUpdateAvailable = (
165 - release: GitHubRelease,
166 - currentReleaseIdentifier: string
167 - ): Effect.Effect<boolean, CompareSemverError | UpgradeBinaryError, never> =>
168 - Effect.gen(function* () {
169 - // Current version is older than latest
170 - const isVersionOutdated: Predicate<number> = comparison => comparison < 0;
171 - const comparison = yield* semverComparator(currentReleaseIdentifier, release.tag_name);
172 - return isVersionOutdated(comparison);
173 - });
174 -
175 - /**
176 - * Download binary for current platform
177 - */
178 - const downloadBinary = (
179 - release: GitHubRelease,
180 - platformArch: PlatformArch
181 - ): Effect.Effect<{ name: string; data: Uint8Array }, UpgradeBinaryError, never> =>
182 - Effect.gen(function* () {
183 - yield* Effect.logDebug(
184 - `Looking up binary for ${platformArch.platform}-${platformArch.arch}`
185 - );
149 + yield* Effect.logDebug(`Resolved latest CLI release tag: ${latest.tag_name}`);
150 + return latest;
151 + }),
152 + onSome: Effect.fn(function* (tag) {
153 + yield* Effect.logDebug(`Using tag: ${tag}`);
154 + const release = yield* fetchGitHubRelease(ctx, tag);
155 +
156 + return release;
157 + }),
158 + })
159 + );
160 + return release;
161 + });
162 +
163 +const provideFsAndPath = <A, E>(
164 + { fs, path }: UpgradeBinaryContext,
165 + effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>
166 +) =>
167 + effect.pipe(
168 + Effect.provideService(FileSystem.FileSystem, fs),
169 + Effect.provideService(Path.Path, path)
170 + );
171
187 - const binaryName = getBinaryAssetName(platformArch);
172 +/**
173 + * Check if update is available
174 + */
175 +const resolveCurrentReleaseIdentifier = (ctx: UpgradeBinaryContext, currentPath: string) =>
176 + provideFsAndPath(ctx, readInstalledReleaseTag(currentPath)).pipe(
177 + Effect.map(releaseTag => releaseTag || `@composio/cli@${APP_VERSION}`)
178 + );
179 +
180 +const isUpdateAvailable = (
181 + release: GitHubRelease,
182 + currentReleaseIdentifier: string
183 +): Effect.Effect<boolean, CompareSemverError | UpgradeBinaryError, never> =>
184 + Effect.gen(function* () {
185 + // Current version is older than latest
186 + const isVersionOutdated = (comparison: number) => comparison < 0;
187 + const comparison = yield* semverComparator(currentReleaseIdentifier, release.tag_name);
188 + return isVersionOutdated(comparison);
189 + });
190
189 - const asset = release.assets.find(asset => asset.name === binaryName);
190 - if (!asset) {
191 - return yield* Effect.fail(
191 +/**
192 + * Download binary for current platform
193 + */
194 +const downloadBinary = (
195 + { httpClient }: UpgradeBinaryContext,
196 + release: GitHubRelease,
197 + platformArch: PlatformArch
198 +): Effect.Effect<{ name: string; data: Uint8Array }, UpgradeBinaryError, never> =>
199 + Effect.gen(function* () {
200 + yield* Effect.logDebug(`Looking up binary for ${platformArch.platform}-${platformArch.arch}`);
201 +
202 + const binaryName = getBinaryAssetName(platformArch);
203 +
204 + const asset = release.assets.find(asset => asset.name === binaryName);
205 + if (!asset) {
206 + return yield* Effect.fail(
207 + new UpgradeBinaryError({
208 + cause: `Binary not found: ${binaryName}`,
209 + message: `No binary available for ${platformArch.platform}-${platformArch.arch}`,
210 + })
211 + );
212 + }
213 +
214 + yield* Effect.logDebug(`Downloading ${asset.name}...`);
215 +
216 + const response = yield* Effect.gen(function* () {
217 + const resp = yield* httpClient.get(asset.browser_download_url).pipe(
218 + Effect.mapError(
219 + cause =>
220 new UpgradeBinaryError({
193 - cause: new Error(`Binary not found: ${binaryName}`),
194 - message: `No binary available for ${platformArch.platform}-${platformArch.arch}`,
221 + cause,
222 + message: `Failed to download binary: ${asset.name}`,
223 })
196 - );
197 - }
224 + )
225 + );
226 + if (resp.status < 200 || resp.status >= 300) {
227 + return yield* Effect.fail(
228 + new UpgradeBinaryError({
229 + cause: `HTTP ${resp.status}`,
230 + message: `Failed to download binary: ${asset.name}`,
231 + })
232 + );
233 + }
234 + return resp;
235 + });
236
199 - yield* Effect.logDebug(`Downloading ${asset.name}...`);
237 + const arrayBuffer = yield* Effect.gen(function* () {
238 + return yield* response.arrayBuffer;
239 + }).pipe(
240 + Effect.mapError(
241 + cause =>
242 + new UpgradeBinaryError({
243 + cause,
244 + message: 'Failed to read downloaded binary',
245 + })
246 + )
247 + );
248
201 - const response = yield* Effect.gen(function* () {
202 - const resp = yield* httpClient.get(asset.browser_download_url);
203 - if (resp.status < 200 || resp.status >= 300) {
204 - return yield* Effect.fail(
205 - new UpgradeBinaryError({
206 - cause: new Error(`HTTP ${resp.status}`),
207 - message: `Failed to download binary: ${asset.name}`,
208 - })
209 - );
210 - }
211 - return resp;
212 - }).pipe(
213 - Effect.catchAll(error =>
214 - Effect.fail(
215 - new UpgradeBinaryError({
216 - cause: new Error(String(error)),
217 - message: `Failed to download binary: ${asset.name}`,
218 - })
219 - )
220 - )
221 - );
249 + return {
250 + name: binaryName,
251 + data: new Uint8Array(arrayBuffer),
252 + };
253 + });
254
223 - const arrayBuffer = yield* Effect.gen(function* () {
224 - return yield* response.arrayBuffer;
225 - }).pipe(
226 - Effect.catchAll(error =>
227 - Effect.fail(
228 - new UpgradeBinaryError({
229 - cause: error as Error,
230 - message: 'Failed to read downloaded binary',
231 - })
232 - )
233 - )
234 - );
255 +/**
256 + * Fetch checksums.txt from a release, if available.
257 + * Returns the parsed map of filename -> expected SHA-256 hash, or None if not found.
258 + */
259 +const fetchChecksums = (
260 + { httpClient }: UpgradeBinaryContext,
261 + release: GitHubRelease
262 +): Effect.Effect<Option.Option<Map<string, string>>, never, never> =>
263 + Effect.gen(function* () {
264 + const checksumsAsset = release.assets.find(a => a.name === 'checksums.txt');
265 + if (!checksumsAsset) {
266 + yield* Effect.logDebug('No checksums.txt found in release assets');
267 + return Option.none();
268 + }
269 +
270 + const response = yield* httpClient
271 + .get(checksumsAsset.browser_download_url)
272 + .pipe(Effect.catchAll(() => Effect.succeed(null)));
273 +
274 + if (!response || response.status < 200 || response.status >= 300) {
275 + yield* Effect.logDebug('Failed to download checksums.txt');
276 + return Option.none();
277 + }
278 +
279 + const text = yield* response.text.pipe(Effect.catchAll(() => Effect.succeed('')));
280 + if (!text) {
281 + return Option.none();
282 + }
283 +
284 + return Option.some(parseChecksumsText(text));
285 + });
286
236 - return {
237 - name: binaryName,
238 - data: new Uint8Array(arrayBuffer),
239 - };
240 - });
241 -
242 - /**
243 - * Fetch checksums.txt from a release, if available.
244 - * Returns the parsed map of filename -> expected SHA-256 hash, or None if not found.
245 - */
246 - const fetchChecksums = (
247 - release: GitHubRelease
248 - ): Effect.Effect<Option.Option<Map<string, string>>, never, never> =>
249 - Effect.gen(function* () {
250 - const checksumsAsset = release.assets.find(a => a.name === 'checksums.txt');
251 - if (!checksumsAsset) {
252 - yield* Effect.logDebug('No checksums.txt found in release assets');
253 - return Option.none();
254 - }
287 +/**
288 + * Verify SHA-256 checksum of downloaded data against expected hash.
289 + */
290 +const verifyChecksum = (
291 + data: Uint8Array,
292 + expectedHash: string,
293 + fileName: string
294 +): Effect.Effect<void, UpgradeBinaryError> =>
295 + Effect.gen(function* () {
296 + const actual = yield* Effect.tryPromise({
297 + try: () => sha256Hex(data),
298 + catch: error =>
299 + new UpgradeBinaryError({
300 + cause: error,
301 + message: 'Failed to compute SHA-256 checksum',
302 + }),
303 + });
304
256 - const response = yield* httpClient
257 - .get(checksumsAsset.browser_download_url)
258 - .pipe(Effect.catchAll(() => Effect.succeed(null)));
305 + if (actual !== expectedHash) {
306 + return yield* Effect.fail(
307 + new UpgradeBinaryError({
308 + message: `Checksum mismatch for ${fileName}\n Expected: ${expectedHash}\n Actual: ${actual}`,
309 + })
310 + );
311 + }
312
260 - if (!response || response.status < 200 || response.status >= 300) {
261 - yield* Effect.logDebug('Failed to download checksums.txt');
262 - return Option.none();
263 - }
313 + yield* Effect.logDebug(`Checksum verified for ${fileName}`);
314 + });
315
265 - const text = yield* response.text.pipe(Effect.catchAll(() => Effect.succeed('')));
266 - if (!text) {
267 - return Option.none();
268 - }
316 +/**
317 + * Extract binary from zip archive using FileSystem
318 + */
319 +const extractBinary = (
320 + { fs, path }: UpgradeBinaryContext,
321 + { name, data }: { name: string; data: Uint8Array },
322 + tempDir: string
323 +): Effect.Effect<{ binaryPath: string; packageDir: string }, UpgradeBinaryError, never> =>
324 + Effect.gen(function* () {
325 + const zipPath = path.join(tempDir, name);
326 + const extractDir = path.join(tempDir, 'extract');
327 + const packageDir = path.join(extractDir, path.parse(name).name);
328 + const binaryPath = path.join(packageDir, CLI_BINARY_NAME);
329 +
330 + yield* Effect.logDebug(`Download zip to ${extractDir}`);
331 +
332 + // Write zip file
333 + yield* fs.writeFile(zipPath, data).pipe(
334 + Effect.mapError(
335 + cause =>
336 + new UpgradeBinaryError({
337 + cause,
338 + message: 'Failed to write zip file',
339 + })
340 + )
341 + );
342
270 - const checksums = new Map<string, string>();
271 - for (const line of text.split('\n')) {
272 - const trimmed = line.trim();
273 - if (!trimmed) continue;
274 - // Format: "<hash> <filename>" (two spaces, sha256sum compatible)
275 - const parts = trimmed.split(/\s+/);
276 - if (parts.length >= 2) {
277 - checksums.set(parts[1], parts[0]);
278 - }
279 - }
343 + // Create extract directory
344 + yield* fs.makeDirectory(extractDir, { recursive: true }).pipe(
345 + Effect.mapError(
346 + cause =>
347 + new UpgradeBinaryError({
348 + cause,
349 + message: 'Failed to create extract directory',
350 + })
351 + )
352 + );
353 +
354 + yield* Effect.tryPromise({
355 + try: async () => {
356 + await extractZip(zipPath, { dir: extractDir });
357 + },
358 + catch: error =>
359 + new UpgradeBinaryError({
360 + cause: error,
361 + message: 'Failed to extract zip archive',
362 + }),
363 + });
364
281 - return Option.some(checksums);
282 - });
283 -
284 - /**
285 - * Verify SHA-256 checksum of downloaded data against expected hash.
286 - */
287 - const verifyChecksum = (
288 - data: Uint8Array,
289 - expectedHash: string,
290 - fileName: string
291 - ): Effect.Effect<void, UpgradeBinaryError> =>
292 - Effect.gen(function* () {
293 - const hashBuffer = yield* Effect.tryPromise({
294 - try: () => {
295 - // Copy into a fresh ArrayBuffer to avoid SharedArrayBuffer type incompatibility
296 - const buf = new ArrayBuffer(data.byteLength);
297 - new Uint8Array(buf).set(data);
298 - return crypto.subtle.digest('SHA-256', buf);
299 - },
300 - catch: error =>
301 - new UpgradeBinaryError({
302 - cause: error as Error,
303 - message: 'Failed to compute SHA-256 checksum',
304 - }),
305 - });
365 + // Check if binary exists
366 + const exists = yield* fs.exists(binaryPath).pipe(Effect.catchAll(() => Effect.succeed(false)));
367 +
368 + if (!exists) {
369 + return yield* Effect.fail(
370 + new UpgradeBinaryError({
371 + cause: `Binary not found in archive: ${binaryPath}`,
372 + message: 'Extracted archive does not contain expected binary',
373 + })
374 + );
375 + }
376 +
377 + // Make executable
378 + yield* fs.chmod(binaryPath, 0o755).pipe(
379 + Effect.mapError(
380 + cause =>
381 + new UpgradeBinaryError({
382 + cause,
383 + message: 'Failed to make binary executable',
384 + })
385 + )
386 + );
387
307 - const actual = Array.from(new Uint8Array(hashBuffer))
308 - .map(b => b.toString(16).padStart(2, '0'))
309 - .join('');
388 + return {
389 + binaryPath,
390 + packageDir,
391 + };
392 + });
393
311 - if (actual !== expectedHash) {
312 - return yield* Effect.fail(
313 - new UpgradeBinaryError({
314 - message: `Checksum mismatch for ${fileName}\n Expected: ${expectedHash}\n Actual: ${actual}`,
315 - })
316 - );
317 - }
394 +/**
395 + * Get current executable path
396 + */
397 +const getCurrentExecutablePath = Effect.fn(function* () {
398 + // E.g., ~/.composio/composio
399 + const currentPath = process.execPath;
400
319 - yield* Effect.logDebug(`Checksum verified for ${fileName}`);
320 - });
401 + const runtimesPaths: Array<string | null> = [Bun.which('bun'), Bun.which('node')];
402
322 - /**
323 - * Extract binary from zip archive using FileSystem
324 - */
325 - const extractBinary = (
326 - { name, data }: { name: string; data: Uint8Array },
327 - tempDir: string
328 - ): Effect.Effect<{ binaryPath: string; packageDir: string }, UpgradeBinaryError, never> =>
329 - Effect.gen(function* () {
330 - const zipPath = path.join(tempDir, name);
331 - const extractDir = path.join(tempDir, 'extract');
332 - const packageDir = path.join(extractDir, path.parse(name).name);
333 - const binaryPath = path.join(packageDir, CLI_BINARY_NAME);
403 + if (runtimesPaths.includes(currentPath)) {
404 + return yield* Effect.fail(
405 + new UpgradeBinaryError({
406 + cause: 'Currently using Composio CLI via Bun or Node.js runtime',
407 + message:
408 + 'Cannot upgrade runtime binary. Please run the upgrade command from a self-contained Composio CLI binary.',
409 + })
410 + );
411 + }
412
335 - yield* Effect.logDebug(`Download zip to ${extractDir}`);
413 + return currentPath;
414 +});
415
337 - // Write zip file
338 - yield* fs.writeFile(zipPath, data).pipe(
339 - Effect.catchAll(error =>
340 - Effect.fail(
341 - new UpgradeBinaryError({
342 - cause: error as Error,
343 - message: 'Failed to write zip file',
344 - })
345 - )
346 - )
416 +/**
417 + * Replace current executable binary with the new target one.
418 + */
419 +const replaceBinary = (
420 + ctx: UpgradeBinaryContext,
421 + sourcePath: string,
422 + targetPath: string,
423 + options: {
424 + releaseTag?: string;
425 + } = {}
426 +): Effect.Effect<void, UpgradeBinaryError> =>
427 + Effect.gen(function* () {
428 + const { fs, path } = ctx;
429 + yield* Effect.logDebug(`Replacing binary: ${sourcePath} -> ${targetPath}`);
430 + yield* fs
431 + .copy(sourcePath, targetPath, {
432 + // Note: without `overwrite: true`, the copy operation will silently bail out
433 + overwrite: true,
434 + })
435 + .pipe(
436 + Effect.mapError(
437 + cause =>
438 + new UpgradeBinaryError({
439 + cause,
440 + message: 'Failed to replace binary',
441 + })
442 + )
443 + );
444 +
445 + const sourceDirectory = path.dirname(sourcePath);
446 + const targetDirectory = path.dirname(targetPath);
447 + const companionRelativePaths = yield* provideFsAndPath(
448 + ctx,
449 + collectExpectedRunCompanionAssetRelativePaths(sourceDirectory)
450 + );
451 + for (const relativePath of companionRelativePaths) {
452 + const sourceCompanion = path.join(sourceDirectory, relativePath);
453 + const sourceExists = yield* fs
454 + .exists(sourceCompanion)
455 + .pipe(Effect.catchAll(() => Effect.succeed(false)));
456 +
457 + if (!sourceExists) {
458 + return yield* Effect.fail(
459 + new UpgradeBinaryError({
460 + cause: `Missing companion module: ${sourceCompanion}`,
461 + message: 'Downloaded binary package is incomplete',
462 + })
463 );
464 + }
465
349 - // Create extract directory
350 - yield* fs.makeDirectory(extractDir, { recursive: true }).pipe(
351 - Effect.catchAll(error =>
352 - Effect.fail(
466 + const targetCompanion = path.join(targetDirectory, relativePath);
467 + yield* fs.makeDirectory(path.dirname(targetCompanion), { recursive: true }).pipe(
468 + Effect.mapError(
469 + cause =>
470 + new UpgradeBinaryError({
471 + cause,
472 + message: `Failed to create companion module directory: ${relativePath}`,
473 + })
474 + )
475 + );
476 +
477 + yield* fs
478 + .copy(sourceCompanion, targetCompanion, {
479 + overwrite: true,
480 + })
481 + .pipe(
482 + Effect.mapError(
483 + cause =>
484 new UpgradeBinaryError({
354 - cause: error as Error,
355 - message: 'Failed to create extract directory',
485 + cause,
486 + message: `Failed to replace companion module: ${relativePath}`,
487 })
357 - )
488 )
489 );
360 -
361 - yield* Effect.tryPromise({
362 - try: async () => {
363 - await extractZip(zipPath, { dir: extractDir });
364 - },
365 - catch: error =>
490 + }
491 +
492 + const localToolsAssetSource = path.join(sourceDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
493 + const localToolsAssetExists = yield* fs
494 + .exists(localToolsAssetSource)
495 + .pipe(Effect.catchAll(() => Effect.succeed(false)));
496 + if (localToolsAssetExists) {
497 + const localToolsAssetTarget = path.join(targetDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
498 + // Replace the whole asset directory: drop the previous tree, then copy
499 + // the new one (fs.copy is recursive for directories).
500 + yield* fs.remove(localToolsAssetTarget, { recursive: true, force: true }).pipe(
501 + Effect.andThen(fs.copy(localToolsAssetSource, localToolsAssetTarget, { overwrite: true })),
502 + Effect.mapError(
503 + error =>
504 new UpgradeBinaryError({
367 - cause: error as Error,
368 - message: 'Failed to extract zip archive',
369 - }),
370 - });
371 -
372 - // Check if binary exists
373 - const exists = yield* fs
374 - .exists(binaryPath)
375 - .pipe(Effect.catchAll(() => Effect.succeed(false)));
376 -
377 - if (!exists) {
378 - return yield* Effect.fail(
505 + cause: error,
506 + message: 'Failed to replace local-tool binary assets',
507 + })
508 + )
509 + );
510 + }
511 +
512 + const releaseTag = options.releaseTag;
513 + if (releaseTag) {
514 + yield* provideFsAndPath(ctx, writeInstalledReleaseTag(targetDirectory, releaseTag)).pipe(
515 + Effect.mapError(
516 + error =>
517 new UpgradeBinaryError({
380 - cause: new Error(`Binary not found in archive: ${binaryPath}`),
381 - message: 'Extracted archive does not contain expected binary',
518 + cause: error,
519 + message: 'Failed to update installed release metadata',
520 })
383 - );
521 + )
522 + );
523 + }
524 + });
525 +
526 +/**
527 + * Main upgrade function
528 + */
529 +const upgrade = (
530 + ctx: UpgradeBinaryContext,
531 + options: {
532 + prerelease?: boolean;
533 + tag?: string;
534 + } = {}
535 +) =>
536 + Effect.gen(function* () {
537 + const ui = yield* TerminalUI;
538 + const upgradeTargetOpt = yield* DEBUG_OVERRIDE_CONFIG['UPGRADE_TARGET'];
539 + const currentPath = yield* getCurrentExecutablePath();
540 + const prerelease = options.prerelease ?? false;
541 + const explicitTag = options.tag;
542 + const currentReleaseIdentifier = yield* resolveCurrentReleaseIdentifier(ctx, currentPath);
543 + yield* Effect.logDebug(`Current executable path: ${currentPath}`);
544 + yield* Effect.logDebug(`Current release identifier: ${currentReleaseIdentifier}`);
545 +
546 + yield* ui.intro('composio upgrade');
547 +
548 + // If local binary path is provided (for testing), use it directly
549 + if (Option.isSome(upgradeTargetOpt)) {
550 + yield* ui.log.info(`New local version available (current: ${currentReleaseIdentifier})`);
551 + yield* replaceBinary(ctx, upgradeTargetOpt.value, currentPath);
552 + yield* ui.outro('Upgrade completed');
553 + return undefined;
554 + }
555 +
556 + const didUpgrade = yield* ui.useMakeSpinner('Checking for updates...', spinner =>
557 + Effect.gen(function* () {
558 + const platformArch = yield* detectPlatform;
559 + const release = yield* fetchLatestRelease(ctx, platformArch, {
560 + prerelease,
561 + tag: explicitTag,
562 + });
563 + if (!explicitTag) {
564 + const updateAvailable = yield* isUpdateAvailable(release, currentReleaseIdentifier);
565 + if (!updateAvailable) {
566 + yield* spinner.stop('You are already running the latest version!');
567 + return false;
568 + }
569 + } else if (release.tag_name === currentReleaseIdentifier) {
570 + yield* Effect.logDebug(`Already running ${release.tag_name}; re-installing as requested`);
571 }
572
386 - // Make executable
387 - yield* fs.chmod(binaryPath, 0o755).pipe(
388 - Effect.catchAll(error =>
389 - Effect.fail(
390 - new UpgradeBinaryError({
391 - cause: error as Error,
392 - message: 'Failed to make binary executable',
393 - })
394 - )
395 - )
573 + yield* spinner.message(
574 + explicitTag
575 + ? `Installing ${release.tag_name} (current: ${currentReleaseIdentifier})...`
576 + : `New version available: ${release.tag_name} (current: ${currentReleaseIdentifier}). Downloading...`
577 );
578
398 - return {
399 - binaryPath,
400 - packageDir,
401 - };
402 - });
579 + const { name, data } = yield* downloadBinary(ctx, release, platformArch);
580
404 - /**
405 - * Get current executable path
406 - */
407 - const getCurrentExecutablePath = Effect.fn(function* () {
408 - // E.g., ~/.composio/composio
409 - const currentPath = process.execPath;
581 + yield* spinner.message('Verifying checksum...');
582
411 - const runtimesPaths = [Bun.which('bun'), Bun.which('node')] as Array<string | null>;
583 + const checksums = yield* fetchChecksums(ctx, release);
584 + if (Option.isSome(checksums)) {
585 + const expectedHash = checksums.value.get(name);
586 + if (expectedHash) {
587 + yield* verifyChecksum(data, expectedHash, name);
588 + } else {
589 + yield* Effect.logDebug(`No checksum entry found for ${name} — skipping verification`);
590 + }
591 + }
592
413 - if (runtimesPaths.includes(currentPath)) {
414 - return yield* Effect.fail(
415 - new UpgradeBinaryError({
416 - cause: new Error(`Currently using Composio CLI via Bun or Node.js runtime`),
417 - message:
418 - 'Cannot upgrade runtime binary. Please run the upgrade command from a self-contained Composio CLI binary.',
419 - })
420 - );
421 - }
593 + yield* spinner.message('Extracting...');
594
423 - return currentPath;
424 - });
425 -
426 - /**
427 - * Replace current executable binary with the new target one.
428 - */
429 - const replaceBinary = (
430 - sourcePath: string,
431 - targetPath: string,
432 - options: {
433 - releaseTag?: string;
434 - } = {}
435 - ): Effect.Effect<void, UpgradeBinaryError> =>
436 - Effect.gen(function* () {
437 - yield* Effect.logDebug(`Replacing binary: ${sourcePath} -> ${targetPath}`);
438 - yield* fs
439 - .copy(sourcePath, targetPath, {
440 - // Note: without `overwrite: true`, the copy operation will silently bail out
441 - overwrite: true,
442 - })
595 + // The temporary directory is automatically cleaned up
596 + const tmpDir = yield* ctx.fs
597 + .makeTempDirectoryScoped({ prefix: `${CLI_BINARY_NAME}-upgrade` })
598 .pipe(
444 - Effect.catchAll(error =>
445 - Effect.fail(
599 + Effect.mapError(
600 + cause =>
601 new UpgradeBinaryError({
447 - cause: error as Error,
448 - message: 'Failed to replace binary',
602 + cause,
603 + message: 'Failed to create temporary directory',
604 })
450 - )
605 )
606 );
607
454 - const sourceDirectory = path.dirname(sourcePath);
455 - const targetDirectory = path.dirname(targetPath);
456 - const companionRelativePaths =
457 - collectExpectedRunCompanionAssetRelativePaths(sourceDirectory);
458 - for (const relativePath of companionRelativePaths) {
459 - const sourceCompanion = path.join(sourceDirectory, relativePath);
460 - const sourceExists = yield* fs
461 - .exists(sourceCompanion)
462 - .pipe(Effect.catchAll(() => Effect.succeed(false)));
463 -
464 - if (!sourceExists) {
465 - return yield* Effect.fail(
466 - new UpgradeBinaryError({
467 - cause: new Error(`Missing companion module: ${sourceCompanion}`),
468 - message: 'Downloaded binary package is incomplete',
469 - })
470 - );
471 - }
472 -
473 - const targetCompanion = path.join(targetDirectory, relativePath);
474 - yield* fs.makeDirectory(path.dirname(targetCompanion), { recursive: true }).pipe(
475 - Effect.catchAll(error =>
476 - Effect.fail(
477 - new UpgradeBinaryError({
478 - cause: error as Error,
479 - message: `Failed to create companion module directory: ${relativePath}`,
480 - })
481 - )
482 - )
483 - );
484 -
485 - yield* fs
486 - .copy(sourceCompanion, targetCompanion, {
487 - overwrite: true,
488 - })
489 - .pipe(
490 - Effect.catchAll(error =>
491 - Effect.fail(
492 - new UpgradeBinaryError({
493 - cause: error as Error,
494 - message: `Failed to replace companion module: ${relativePath}`,
495 - })
496 - )
497 - )
498 - );
499 - }
500 -
501 - const localToolsAssetSource = path.join(sourceDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
502 - const localToolsAssetExists = yield* fs
503 - .exists(localToolsAssetSource)
504 - .pipe(Effect.catchAll(() => Effect.succeed(false)));
505 - if (localToolsAssetExists) {
506 - const localToolsAssetTarget = path.join(
507 - targetDirectory,
508 - LOCAL_TOOLS_BINARY_ASSET_DIRNAME
509 - );
510 - yield* Effect.tryPromise({
511 - try: async () => {
512 - await removePath(localToolsAssetTarget, { recursive: true, force: true });
513 - await copyPath(localToolsAssetSource, localToolsAssetTarget, { recursive: true });
514 - },
515 - catch: error =>
516 - new UpgradeBinaryError({
517 - cause: error as Error,
518 - message: 'Failed to replace local-tool binary assets',
519 - }),
520 - });
521 - }
608 + const extractedBinary = yield* extractBinary(ctx, { name, data }, tmpDir);
609 + yield* replaceBinary(ctx, extractedBinary.binaryPath, currentPath, {
610 + releaseTag: release.tag_name,
611 + });
612
523 - if (options.releaseTag) {
524 - yield* Effect.try({
525 - try: () => writeInstalledReleaseTag(targetDirectory, options.releaseTag!),
526 - catch: error =>
527 - new UpgradeBinaryError({
528 - cause: error as Error,
529 - message: 'Failed to update installed release metadata',
530 - }),
531 - });
532 - }
533 - });
534 -
535 - /**
536 - * Main upgrade function
537 - */
538 - const upgrade = (
539 - options: {
540 - prerelease?: boolean;
541 - tag?: string;
542 - } = {}
543 - ) =>
544 - Effect.gen(function* () {
545 - const ui = yield* TerminalUI;
546 - const upgradeTargetOpt = yield* DEBUG_OVERRIDE_CONFIG['UPGRADE_TARGET'];
547 - const currentPath = yield* getCurrentExecutablePath();
548 - const prerelease = options.prerelease ?? false;
549 - const explicitTag = options.tag;
550 - const currentReleaseIdentifier = resolveCurrentReleaseIdentifier(currentPath);
551 - yield* Effect.logDebug(`Current executable path: ${currentPath}`);
552 - yield* Effect.logDebug(`Current release identifier: ${currentReleaseIdentifier}`);
553 -
554 - yield* ui.intro('composio upgrade');
555 -
556 - // If local binary path is provided (for testing), use it directly
557 - if (Option.isSome(upgradeTargetOpt)) {
558 - yield* ui.log.info(`New local version available (current: ${currentReleaseIdentifier})`);
559 - yield* replaceBinary(upgradeTargetOpt.value, currentPath);
560 - yield* ui.outro('Upgrade completed');
561 - return undefined;
562 - }
613 + yield* spinner.stop('Upgrade completed!');
614 + return release.tag_name;
615 + })
616 + );
617
564 - const didUpgrade = yield* ui.useMakeSpinner('Checking for updates...', spinner =>
565 - Effect.gen(function* () {
566 - const platformArch = yield* detectPlatform;
567 - const release = yield* fetchLatestRelease(platformArch, {
568 - prerelease,
569 - tag: explicitTag,
570 - });
571 - if (!explicitTag) {
572 - const updateAvailable = yield* isUpdateAvailable(release, currentReleaseIdentifier);
573 - if (!updateAvailable) {
574 - yield* spinner.stop('You are already running the latest version!');
575 - return false;
576 - }
577 - } else if (release.tag_name === currentReleaseIdentifier) {
578 - yield* Effect.logDebug(
579 - `Already running ${release.tag_name}; re-installing as requested`
580 - );
581 - }
582 -
583 - yield* spinner.message(
584 - explicitTag
585 - ? `Installing ${release.tag_name} (current: ${currentReleaseIdentifier})...`
586 - : `New version available: ${release.tag_name} (current: ${currentReleaseIdentifier}). Downloading...`
587 - );
588 -
589 - const { name, data } = yield* downloadBinary(release, platformArch);
590 -
591 - yield* spinner.message('Verifying checksum...');
592 -
593 - const checksums = yield* fetchChecksums(release);
594 - if (Option.isSome(checksums)) {
595 - const expectedHash = checksums.value.get(name);
596 - if (expectedHash) {
597 - yield* verifyChecksum(data, expectedHash, name);
598 - } else {
599 - yield* Effect.logDebug(
600 - `No checksum entry found for ${name} — skipping verification`
601 - );
602 - }
603 - }
604 -
605 - yield* spinner.message('Extracting...');
606 -
607 - // The temporary directory is automatically cleaned up
608 - const tmpDir = yield* fs
609 - .makeTempDirectoryScoped({ prefix: `${CLI_BINARY_NAME}-upgrade}` })
610 - .pipe(
611 - Effect.catchAll(error =>
612 - Effect.fail(
613 - new UpgradeBinaryError({
614 - cause: error as Error,
615 - message: 'Failed to create temporary directory',
616 - })
617 - )
618 - )
619 - );
620 -
621 - const extractedBinary = yield* extractBinary({ name, data }, tmpDir);
622 - yield* replaceBinary(extractedBinary.binaryPath, currentPath, {
623 - releaseTag: release.tag_name,
624 - });
625 -
626 - yield* spinner.stop('Upgrade completed!');
627 - return release.tag_name;
628 - })
629 - );
618 + yield* ui.outro(
619 + didUpgrade ? 'Restart your terminal to use the new version.' : 'No upgrade needed.'
620 + );
621
631 - yield* ui.outro(
632 - didUpgrade ? 'Restart your terminal to use the new version.' : 'No upgrade needed.'
633 - );
622 + return didUpgrade || undefined; // release tag string, or undefined if no upgrade
623 + });
624
635 - return didUpgrade || undefined; // release tag string, or undefined if no upgrade
636 - });
625 +// Service to manage CLI binary upgrades
626 +export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/UpgradeBinary', {
627 + accessors: true,
628 + effect: Effect.gen(function* () {
629 + const ctx: UpgradeBinaryContext = {
630 + httpClient: yield* HttpClient.HttpClient,
631 + fs: yield* FileSystem.FileSystem,
632 + path: yield* Path.Path,
633 + githubConfig: yield* GITHUB_CONFIG_ALL,
634 + };
635
636 return {
639 - upgrade,
637 + upgrade: (options: { prerelease?: boolean; tag?: string } = {}) => upgrade(ctx, options),
638 } as const;
639 }),
642 - dependencies: [],
640 + dependencies: [Path.layer],
641 }) {}
ts/packages/cli/src/services/user-context.ts
+3 -3
@@ -1,6 +1,5 @@
1 -import { FileSystem } from '@effect/platform';
1 +import { FileSystem, Path } from '@effect/platform';
2 import { Effect, Context, Layer, Option } from 'effect';
3 -import path from 'path';
3 import {
4 type UserDataWithDefaults,
5 UserData,
@@ -151,6 +150,7 @@ export const rawComposioUserContextLive = Layer.effect(
150 ComposioUserContext,
151 Effect.gen(function* () {
152 const fs = yield* FileSystem.FileSystem;
153 + const path = yield* Path.Path;
154 const apiKey = yield* APP_CONFIG['USER_API_KEY'];
155 const baseURL = yield* APP_CONFIG['BASE_URL'];
156 const webURL = yield* APP_CONFIG['WEB_URL'];
@@ -354,7 +354,7 @@ const resolveMacOSBackend = (
354
355 /**
356 * Public layer that pre-provides the keyring and CLI-config deps,
357 - * leaving only `FileSystem` as the external requirement. The keyring
357 + * leaving only `FileSystem` and `Path` as external requirements. The keyring
358 * backend is chosen dynamically from the user's `config.json`
359 * `security` field — `"auto"` / `"keychain-subprocess"` select the
360 * subprocess path (default); `"keychain"` opts into the experimental
ts/packages/cli/src/utils/checksums.ts new
+29
@@ -0,0 +1,29 @@
1 +/**
2 + * Parse a sha256sum-compatible `checksums.txt` ("<hash> <filename>" per line)
3 + * into a filename -> expected-hash map. Blank lines are skipped.
4 + */
5 +export const parseChecksumsText = (text: string): Map<string, string> => {
6 + const checksums = new Map<string, string>();
7 + for (const line of text.split('\n')) {
8 + const trimmed = line.trim();
9 + if (!trimmed) continue;
10 + const parts = trimmed.split(/\s+/);
11 + if (parts.length >= 2) {
12 + checksums.set(parts[1]!, parts[0]!);
13 + }
14 + }
15 + return checksums;
16 +};
17 +
18 +/**
19 + * SHA-256 digest of `data` as a lowercase hex string. Copies into a fresh
20 + * ArrayBuffer so views over a SharedArrayBuffer are accepted too.
21 + */
22 +export const sha256Hex = async (data: Uint8Array): Promise<string> => {
23 + const buffer = new ArrayBuffer(data.byteLength);
24 + new Uint8Array(buffer).set(data);
25 + const digest = await crypto.subtle.digest('SHA-256', buffer);
26 + return Array.from(new Uint8Array(digest))
27 + .map(byte => byte.toString(16).padStart(2, '0'))
28 + .join('');
29 +};
ts/packages/cli/src/utils/djb2.ts new
+11
@@ -0,0 +1,11 @@
1 +/**
2 + * djb2 string hash (seed 5381, xor variant), normalized to a non-negative
3 + * 32-bit integer. Callers pick their own string encoding (hex, base36, ...).
4 + */
5 +export const djb2Hash = (value: string): number => {
6 + let hash = 5381;
7 + for (let index = 0; index < value.length; index += 1) {
8 + hash = (hash * 33) ^ value.charCodeAt(index);
9 + }
10 + return Math.abs(hash >>> 0);
11 +};
ts/packages/cli/src/utils/get-ancestors.ts
+15 -13
@@ -1,20 +1,22 @@
1 -import path from 'node:path';
1 +import { Path } from '@effect/platform';
2 +import { Effect } from 'effect';
3
4 /**
5 * Walk up from a directory to the filesystem root, collecting all ancestor paths.
6 * Returns an array starting with the resolved `cwd` and ending at the root.
7 */
7 -export const getAncestors = (cwd: string): string[] => {
8 - const resolved = path.resolve(cwd);
9 - const dirs = [resolved];
10 - let current = resolved;
8 +export const getAncestors = (cwd: string): Effect.Effect<string[], never, Path.Path> =>
9 + Effect.map(Path.Path, path => {
10 + const resolved = path.resolve(cwd);
11 + const dirs = [resolved];
12 + let current = resolved;
13
12 - while (true) {
13 - const parent = path.dirname(current);
14 - if (parent === current) break;
15 - dirs.push(parent);
16 - current = parent;
17 - }
14 + while (true) {
15 + const parent = path.dirname(current);
16 + if (parent === current) break;
17 + dirs.push(parent);
18 + current = parent;
19 + }
20
19 - return dirs;
20 -};
21 + return dirs;
22 + });
ts/packages/cli/test/__utils__/services/test-layer.ts
+4 -3
@@ -787,11 +787,12 @@ export const TestLayer = (input?: TestLiveInput) =>
787 })
788 );
789
790 - // Mock `node:os`
790 + // Mock operating-system details
791 const NodeOsTest = Layer.succeed(
792 NodeOs,
793 new NodeOs({
794 homedir: cwd,
795 + tmpdir: tempy.rootTemporaryDirectory,
796 arch: 'arm64',
797 platform: 'darwin',
798 })
@@ -809,7 +810,7 @@ export const TestLayer = (input?: TestLiveInput) =>
810
811 const ComposioUserContextTest = Layer.provideMerge(
812 ComposioUserContextLive,
812 - Layer.merge(BunFileSystem.layer, NodeOsTest)
813 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest)
814 );
815
816 let rawCliUserConfig = CliUserConfig.make({
@@ -832,7 +833,7 @@ export const TestLayer = (input?: TestLiveInput) =>
833 developerModeEnabled: rawCliUserConfig.developer.enabled,
834 developerDangerousCommandsEnabled: rawCliUserConfig.developer.destructiveActions,
835 experimentalFeatures: rawCliUserConfig.experimentalFeatures,
835 - artifactDirectory: undefined,
836 + artifactDirectory: Option.getOrUndefined(rawCliUserConfig.artifactDirectory),
837 experimentalSubagentTarget: 'auto' as const,
838 security: 'auto' as const,
839 };
ts/packages/cli/test/__utils__/typescript-compiler.ts
+8 -3
@@ -1,6 +1,7 @@
1 import { describe, it, expect, vi } from 'vitest';
2 import { Effect, Stream, String } from 'effect';
3 -import { Command } from '@effect/platform';
3 +import { Command, Path } from '@effect/platform';
4 +import { BunPath } from '@effect/platform-bun';
5 import ts from 'typescript';
6 import {
7 buildVirtualFileMap,
@@ -8,6 +9,10 @@ import {
9 patchCompilerHostWithVirtualFiles,
10 } from 'src/generation/typescript/virtual-compiler-host';
11
12 +// The ts.CompilerHost callbacks are synchronous, so the sync Path service
13 +// instance is resolved once up front and passed in as a plain parameter.
14 +const path = Effect.runSync(Effect.provide(Path.Path, BunPath.layer));
15 +
16 interface AssertTypeScriptIsValidInput {
17 files: {
18 [filename: string]: string;
@@ -53,7 +58,7 @@ export function assertTypeScriptIsValid({ files }: AssertTypeScriptIsValidInput)
58 const virtualFileNames = Array.from(virtualFileMap.keys());
59
60 const tsHost = ts.createCompilerHost(compilerOptions);
56 - patchCompilerHostWithVirtualFiles(tsHost, virtualFileMap, 'throw');
61 + patchCompilerHostWithVirtualFiles(tsHost, virtualFileMap, path, 'throw');
62
63 const program = ts.createProgram(virtualFileNames, compilerOptions, tsHost);
64
@@ -162,7 +167,7 @@ if (import.meta.vitest) {
167
168 tsHost.getSourceFile = getSourceFile;
169 tsHost.fileExists = fileExists;
165 - patchCompilerHostWithVirtualFiles(tsHost, virtualFileMap, 'throw');
170 + patchCompilerHostWithVirtualFiles(tsHost, virtualFileMap, path, 'throw');
171
172 expect(tsHost.fileExists('node_modules/@composio/core/index.d.ts')).toBe(false);
173 expect(() =>
ts/packages/cli/test/src/commands/run.cmd.test.ts
+229 -184
@@ -3,7 +3,9 @@ import * as os from 'node:os';
3 import * as path from 'node:path';
4 import { pathToFileURL } from 'node:url';
5 import { describe, expect, layer } from '@effect/vitest';
6 -import { Effect } from 'effect';
6 +import { Path } from '@effect/platform';
7 +import { BunContext } from '@effect/platform-bun';
8 +import { Effect, Exit } from 'effect';
9 import { afterEach, it, vi } from 'vitest';
10 import {
11 buildRunHelpersSource,
@@ -42,12 +44,11 @@ describe('CLI: composio run', () => {
44 Effect.gen(function* () {
45 const spawn = vi.fn(() => ({ exited: Promise.resolve(7) }));
46 const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
45 - const stderrWrite = vi
46 - .spyOn(process.stderr, 'write')
47 - .mockImplementation((() => true) as never);
47 + const stderrWrite = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
48 vi.stubGlobal('Bun', { spawn });
49
50 yield* cli(['run', 'console.log("hi")', '--flag', 'value']);
51 + const output = stderrWrite.mock.calls.map(([chunk]) => String(chunk));
52
53 expect(spawn).toHaveBeenCalledTimes(1);
54 const spawnConfig = (spawn as any).mock.calls[0][0] as {
@@ -70,9 +71,7 @@ describe('CLI: composio run', () => {
71 })
72 );
73 expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);
73 - expect(stderrWrite).toHaveBeenCalledWith(
74 - expect.stringMatching(/^RUN_LOG_FILE=.*run\.log\n$/)
75 - );
74 + expect(output).toContainEqual(expect.stringMatching(/^RUN_LOG_FILE=.*run\.log\n$/));
75 expect(exit).toHaveBeenCalledWith(7);
76 })
77 );
@@ -211,7 +210,7 @@ describe('CLI: composio run', () => {
210 it.scoped('[Given] no inline code and no --file [Then] it fails with a clear error', () =>
211 Effect.gen(function* () {
212 const exit = yield* cli(['run']).pipe(Effect.exit);
214 - expect(exit._tag).toBe('Failure');
213 + expect(Exit.isFailure(exit)).toBe(true);
214 })
215 );
216 });
@@ -245,17 +244,23 @@ describe('CLI: composio run', () => {
244
245 describe('buildRunHelpersSource', () => {
246 it('[Given] consumer context [Then] it embeds auth and consumer metadata in the helper source', () => {
248 - const source = buildRunHelpersSource(['/tmp/composio'], {
249 - apiKey: 'test_api_key',
250 - baseURL: 'https://api.example.test',
251 - webURL: 'https://app.example.test',
252 - orgId: 'org_test',
253 - consumerUserId: 'consumer_user_test',
254 - acpOnly: true,
255 - logsOff: true,
256 - dryRun: true,
257 - runLogFilePath: '/tmp/composio-run/run.log',
258 - });
247 + const source = buildRunHelpersSource(
248 + ['/tmp/composio'],
249 + {
250 + apiKey: 'test_api_key',
251 + baseURL: 'https://api.example.test',
252 + webURL: 'https://app.example.test',
253 + orgId: 'org_test',
254 + consumerUserId: 'consumer_user_test',
255 + acpOnly: true,
256 + logsOff: true,
257 + dryRun: true,
258 + runLogFilePath: '/tmp/composio-run/run.log',
259 + },
260 + {
261 + helpersRuntimeModuleUrl: pathToFileURL('/tmp/composio-run/run-helpers-runtime.mjs').href,
262 + }
263 + );
264
265 expect(source).toContain('import { installRunHelpers } from "file://');
266 expect(source).toContain('await installRunHelpers(');
@@ -382,191 +387,231 @@ describe('run-subagent-shared', () => {
387 });
388
389 describe('inferCliInvocationPrefix', () => {
385 - it('[Given] a compiled bunfs entrypoint [Then] it falls back to the binary path only', () => {
386 - expect(inferCliInvocationPrefix(['node', '/$bunfs/root/composio'])).toEqual([process.execPath]);
390 + layer(Path.layer)(it => {
391 + it.effect(
392 + '[Given] a compiled bunfs entrypoint [Then] it falls back to the binary path only',
393 + () =>
394 + Effect.gen(function* () {
395 + const pathService = yield* Path.Path;
396 + expect(inferCliInvocationPrefix(pathService, ['node', '/$bunfs/root/composio'])).toEqual([
397 + process.execPath,
398 + ]);
399 + })
400 + );
401 });
402 });
403
404 describe('resolveRunCompanionModulePath', () => {
391 - it('[Given] a bundled dist chunk [Then] it resolves sibling companion modules in dist', () => {
392 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-companion-dist-'));
393 - const callerPath = path.join(tempDir, 'commands-abc.mjs');
394 - const servicesDir = path.join(tempDir, 'services');
395 - const companionPath = path.join(servicesDir, 'run-subagent-shared.mjs');
396 - fs.writeFileSync(callerPath, '', 'utf8');
397 - fs.mkdirSync(servicesDir);
398 - fs.writeFileSync(companionPath, '', 'utf8');
399 -
400 - expect(
401 - resolveRunCompanionModulePath({
402 - callerImportMetaUrl: pathToFileURL(callerPath).href,
403 - execPath: '/tmp/composio',
404 - relativeNoExtensionFromCaller: '../services/run-subagent-shared',
405 - })
406 - ).toBe(companionPath);
407 - });
408 -
409 - it('[Given] a compiled bunfs caller [Then] it falls back to modules next to the binary', () => {
410 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-companion-bin-'));
411 - const execPath = path.join(tempDir, 'composio');
412 - const companionPath = path.join(tempDir, 'run-subagent-shared.mjs');
413 - fs.writeFileSync(companionPath, '', 'utf8');
405 + layer(BunContext.layer)(it => {
406 + it.effect(
407 + '[Given] a bundled dist chunk [Then] it resolves sibling companion modules in dist',
408 + () =>
409 + Effect.gen(function* () {
410 + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-companion-dist-'));
411 + const callerPath = path.join(tempDir, 'commands-abc.mjs');
412 + const servicesDir = path.join(tempDir, 'services');
413 + const companionPath = path.join(servicesDir, 'run-subagent-shared.mjs');
414 + fs.writeFileSync(callerPath, '', 'utf8');
415 + fs.mkdirSync(servicesDir);
416 + fs.writeFileSync(companionPath, '', 'utf8');
417 +
418 + expect(
419 + yield* resolveRunCompanionModulePath({
420 + callerImportMetaUrl: pathToFileURL(callerPath).href,
421 + execPath: '/tmp/composio',
422 + relativeNoExtensionFromCaller: '../services/run-subagent-shared',
423 + })
424 + ).toBe(companionPath);
425 + })
426 + );
427
415 - expect(
416 - resolveRunCompanionModulePath({
417 - callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
418 - execPath,
419 - relativeNoExtensionFromCaller: '../services/run-subagent-shared',
420 - })
421 - ).toBe(companionPath);
428 + it.effect(
429 + '[Given] a compiled bunfs caller [Then] it falls back to modules next to the binary',
430 + () =>
431 + Effect.gen(function* () {
432 + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-companion-bin-'));
433 + const execPath = path.join(tempDir, 'composio');
434 + const companionPath = path.join(tempDir, 'run-subagent-shared.mjs');
435 + fs.writeFileSync(companionPath, '', 'utf8');
436 +
437 + expect(
438 + yield* resolveRunCompanionModulePath({
439 + callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
440 + execPath,
441 + relativeNoExtensionFromCaller: '../services/run-subagent-shared',
442 + })
443 + ).toBe(companionPath);
444 + })
445 + );
446 });
447 });
448
449 describe('run companion install metadata', () => {
426 - it('[Given] an installed release tag file [Then] run helpers can read it back from the install dir', () => {
427 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-release-tag-'));
428 - const execPath = path.join(tempDir, 'composio');
429 -
430 - writeInstalledReleaseTag(tempDir, '@composio/cli@0.2.12');
431 -
432 - expect(readInstalledReleaseTag(execPath)).toBe('@composio/cli@0.2.12');
433 - });
434 -
435 - it('[Given] a partial companion install [Then] it reports only the missing companion files', () => {
436 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-'));
437 - const execPath = path.join(tempDir, 'composio');
438 - fs.writeFileSync(path.join(tempDir, RUN_COMPANION_MODULE_FILENAMES[0]!), '', 'utf8');
439 -
440 - expect(listMissingInstalledRunCompanionModules(execPath)).toEqual(
441 - [...RUN_COMPANION_MODULE_FILENAMES.slice(1), ...RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS]
442 - .slice()
443 - .sort()
444 - );
445 - });
450 + layer(BunContext.layer)(it => {
451 + it.effect(
452 + '[Given] an installed release tag file [Then] run helpers can read it back from the install dir',
453 + () =>
454 + Effect.gen(function* () {
455 + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-release-tag-'));
456 + const execPath = path.join(tempDir, 'composio');
457
447 - it('[Given] a nested companion dependency is missing [Then] it reports the missing helper asset', () => {
448 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-nested-'));
449 - const execPath = path.join(tempDir, 'composio');
450 - const servicesDir = path.join(tempDir, 'services');
451 - fs.mkdirSync(servicesDir, { recursive: true });
458 + yield* writeInstalledReleaseTag(tempDir, '@composio/cli@0.2.12');
459
453 - fs.writeFileSync(
454 - path.join(tempDir, 'run-helpers-runtime.mjs'),
455 - 'export * from "./services/run-helpers-runtime.mjs";\n',
456 - 'utf8'
457 - );
458 - fs.writeFileSync(
459 - path.join(tempDir, 'run-subagent-shared.mjs'),
460 - 'export * from "./services/run-subagent-shared.mjs";\n',
461 - 'utf8'
462 - );
463 - fs.writeFileSync(
464 - path.join(tempDir, 'run-subagent-acp.mjs'),
465 - 'export * from "./services/run-subagent-acp.mjs";\n',
466 - 'utf8'
467 - );
468 - fs.writeFileSync(
469 - path.join(tempDir, 'run-subagent-legacy.mjs'),
470 - 'export * from "./services/run-subagent-legacy.mjs";\n',
471 - 'utf8'
472 - );
473 - fs.writeFileSync(
474 - path.join(tempDir, 'run-subagent-output-mcp.mjs'),
475 - 'export * from "./services/run-subagent-output-mcp.mjs";\n',
476 - 'utf8'
460 + expect(yield* readInstalledReleaseTag(execPath)).toBe('@composio/cli@0.2.12');
461 + })
462 );
463
479 - fs.writeFileSync(
480 - path.join(servicesDir, 'run-helpers-runtime.mjs'),
481 - 'export const runtimeValue = 1;\n',
482 - 'utf8'
483 - );
484 - fs.writeFileSync(
485 - path.join(servicesDir, 'run-subagent-shared.mjs'),
486 - 'export const x = 1;\n',
487 - 'utf8'
488 - );
489 - fs.writeFileSync(
490 - path.join(servicesDir, 'run-subagent-acp.mjs'),
491 - 'export * from "../run-companion-modules-abc123.mjs";\n',
492 - 'utf8'
493 - );
494 - fs.writeFileSync(
495 - path.join(servicesDir, 'run-subagent-legacy.mjs'),
496 - 'export const y = 1;\n',
497 - 'utf8'
498 - );
499 - fs.writeFileSync(
500 - path.join(servicesDir, 'run-subagent-output-mcp.mjs'),
501 - 'export const z = 1;\n',
502 - 'utf8'
464 + it.effect(
465 + '[Given] a partial companion install [Then] it reports only the missing companion files',
466 + () =>
467 + Effect.gen(function* () {
468 + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-'));
469 + const execPath = path.join(tempDir, 'composio');
470 + fs.writeFileSync(path.join(tempDir, RUN_COMPANION_MODULE_FILENAMES[0]!), '', 'utf8');
471 +
472 + expect(yield* listMissingInstalledRunCompanionModules(execPath)).toEqual(
473 + [
474 + ...RUN_COMPANION_MODULE_FILENAMES.slice(1),
475 + ...RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS,
476 + ]
477 + .slice()
478 + .sort()
479 + );
480 + })
481 );
482
505 - expect(listMissingInstalledRunCompanionModules(execPath)).toContain(
506 - 'run-companion-modules-abc123.mjs'
507 - );
508 - });
483 + it.effect(
484 + '[Given] a nested companion dependency is missing [Then] it reports the missing helper asset',
485 + () =>
486 + Effect.gen(function* () {
487 + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-nested-'));
488 + const execPath = path.join(tempDir, 'composio');
489 + const servicesDir = path.join(tempDir, 'services');
490 + fs.mkdirSync(servicesDir, { recursive: true });
491 +
492 + fs.writeFileSync(
493 + path.join(tempDir, 'run-helpers-runtime.mjs'),
494 + 'export * from "./services/run-helpers-runtime.mjs";\n',
495 + 'utf8'
496 + );
497 + fs.writeFileSync(
498 + path.join(tempDir, 'run-subagent-shared.mjs'),
499 + 'export * from "./services/run-subagent-shared.mjs";\n',
500 + 'utf8'
501 + );
502 + fs.writeFileSync(
503 + path.join(tempDir, 'run-subagent-acp.mjs'),
504 + 'export * from "./services/run-subagent-acp.mjs";\n',
505 + 'utf8'
506 + );
507 + fs.writeFileSync(
508 + path.join(tempDir, 'run-subagent-legacy.mjs'),
509 + 'export * from "./services/run-subagent-legacy.mjs";\n',
510 + 'utf8'
511 + );
512 + fs.writeFileSync(
513 + path.join(tempDir, 'run-subagent-output-mcp.mjs'),
514 + 'export * from "./services/run-subagent-output-mcp.mjs";\n',
515 + 'utf8'
516 + );
517
510 - it('[Given] a named re-export dependency is missing [Then] it reports the missing helper asset', () => {
511 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-reexport-'));
512 - const execPath = path.join(tempDir, 'composio');
513 - const servicesDir = path.join(tempDir, 'services');
514 - fs.mkdirSync(servicesDir, { recursive: true });
518 + fs.writeFileSync(
519 + path.join(servicesDir, 'run-helpers-runtime.mjs'),
520 + 'export const runtimeValue = 1;\n',
521 + 'utf8'
522 + );
523 + fs.writeFileSync(
524 + path.join(servicesDir, 'run-subagent-shared.mjs'),
525 + 'export const x = 1;\n',
526 + 'utf8'
527 + );
528 + fs.writeFileSync(
529 + path.join(servicesDir, 'run-subagent-acp.mjs'),
530 + 'export * from "../run-companion-modules-abc123.mjs";\n',
531 + 'utf8'
532 + );
533 + fs.writeFileSync(
534 + path.join(servicesDir, 'run-subagent-legacy.mjs'),
535 + 'export const y = 1;\n',
536 + 'utf8'
537 + );
538 + fs.writeFileSync(
539 + path.join(servicesDir, 'run-subagent-output-mcp.mjs'),
540 + 'export const z = 1;\n',
541 + 'utf8'
542 + );
543
516 - fs.writeFileSync(
517 - path.join(tempDir, 'run-helpers-runtime.mjs'),
518 - 'export * from "./services/run-helpers-runtime.mjs";\n',
519 - 'utf8'
520 - );
521 - fs.writeFileSync(
522 - path.join(tempDir, 'run-subagent-shared.mjs'),
523 - 'export * from "./services/run-subagent-shared.mjs";\n',
524 - 'utf8'
525 - );
526 - fs.writeFileSync(
527 - path.join(tempDir, 'run-subagent-acp.mjs'),
528 - 'export * from "./services/run-subagent-acp.mjs";\n',
529 - 'utf8'
530 - );
531 - fs.writeFileSync(
532 - path.join(tempDir, 'run-subagent-legacy.mjs'),
533 - 'export * from "./services/run-subagent-legacy.mjs";\n',
534 - 'utf8'
535 - );
536 - fs.writeFileSync(
537 - path.join(tempDir, 'run-subagent-output-mcp.mjs'),
538 - 'export * from "./services/run-subagent-output-mcp.mjs";\n',
539 - 'utf8'
544 + expect(yield* listMissingInstalledRunCompanionModules(execPath)).toContain(
545 + 'run-companion-modules-abc123.mjs'
546 + );
547 + })
548 );
549
542 - fs.writeFileSync(
543 - path.join(servicesDir, 'run-helpers-runtime.mjs'),
544 - 'export const runtimeValue = 1;\n',
545 - 'utf8'
546 - );
547 - fs.writeFileSync(
548 - path.join(servicesDir, 'run-subagent-shared.mjs'),
549 - 'export const sharedValue = 1;\n',
550 - 'utf8'
551 - );
552 - fs.writeFileSync(
553 - path.join(servicesDir, 'run-subagent-acp.mjs'),
554 - 'export { helperValue } from "../run-companion-modules-def456.mjs";\n',
555 - 'utf8'
556 - );
557 - fs.writeFileSync(
558 - path.join(servicesDir, 'run-subagent-legacy.mjs'),
559 - 'export const legacyValue = 1;\n',
560 - 'utf8'
561 - );
562 - fs.writeFileSync(
563 - path.join(servicesDir, 'run-subagent-output-mcp.mjs'),
564 - 'export const outputValue = 1;\n',
565 - 'utf8'
566 - );
550 + it.effect(
551 + '[Given] a named re-export dependency is missing [Then] it reports the missing helper asset',
552 + () =>
553 + Effect.gen(function* () {
554 + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-reexport-'));
555 + const execPath = path.join(tempDir, 'composio');
556 + const servicesDir = path.join(tempDir, 'services');
557 + fs.mkdirSync(servicesDir, { recursive: true });
558 +
559 + fs.writeFileSync(
560 + path.join(tempDir, 'run-helpers-runtime.mjs'),
561 + 'export * from "./services/run-helpers-runtime.mjs";\n',
562 + 'utf8'
563 + );
564 + fs.writeFileSync(
565 + path.join(tempDir, 'run-subagent-shared.mjs'),
566 + 'export * from "./services/run-subagent-shared.mjs";\n',
567 + 'utf8'
568 + );
569 + fs.writeFileSync(
570 + path.join(tempDir, 'run-subagent-acp.mjs'),
571 + 'export * from "./services/run-subagent-acp.mjs";\n',
572 + 'utf8'
573 + );
574 + fs.writeFileSync(
575 + path.join(tempDir, 'run-subagent-legacy.mjs'),
576 + 'export * from "./services/run-subagent-legacy.mjs";\n',
577 + 'utf8'
578 + );
579 + fs.writeFileSync(
580 + path.join(tempDir, 'run-subagent-output-mcp.mjs'),
581 + 'export * from "./services/run-subagent-output-mcp.mjs";\n',
582 + 'utf8'
583 + );
584 +
585 + fs.writeFileSync(
586 + path.join(servicesDir, 'run-helpers-runtime.mjs'),
587 + 'export const runtimeValue = 1;\n',
588 + 'utf8'
589 + );
590 + fs.writeFileSync(
591 + path.join(servicesDir, 'run-subagent-shared.mjs'),
592 + 'export const sharedValue = 1;\n',
593 + 'utf8'
594 + );
595 + fs.writeFileSync(
596 + path.join(servicesDir, 'run-subagent-acp.mjs'),
597 + 'export { helperValue } from "../run-companion-modules-def456.mjs";\n',
598 + 'utf8'
599 + );
600 + fs.writeFileSync(
601 + path.join(servicesDir, 'run-subagent-legacy.mjs'),
602 + 'export const legacyValue = 1;\n',
603 + 'utf8'
604 + );
605 + fs.writeFileSync(
606 + path.join(servicesDir, 'run-subagent-output-mcp.mjs'),
607 + 'export const outputValue = 1;\n',
608 + 'utf8'
609 + );
610
568 - expect(listMissingInstalledRunCompanionModules(execPath)).toContain(
569 - 'run-companion-modules-def456.mjs'
611 + expect(yield* listMissingInstalledRunCompanionModules(execPath)).toContain(
612 + 'run-companion-modules-def456.mjs'
613 + );
614 + })
615 );
616 });
617 });
ts/packages/cli/test/src/effects/detect-platform.test.ts
+24 -21
@@ -1,5 +1,5 @@
1 import { describe, expect, it } from '@effect/vitest';
2 -import { Effect, Layer } from 'effect';
2 +import { Effect, Layer, Predicate } from 'effect';
3 import {
4 detectPlatform,
5 UnsupportedPlatformError,
@@ -15,6 +15,7 @@ const createMockNodeOs = <P extends NodeJS.Platform>(platform: P, arch: string)
15 NodeOs,
16 NodeOs.make({
17 homedir: '/mock/home',
18 + tmpdir: '/tmp',
19 platform: platform as NodeJS.Platform,
20 arch: arch as NodeJS.Architecture,
21 })
@@ -347,7 +348,7 @@ describe('detect-platform.ts', () => {
348 const error = new UnsupportedPlatformError({ platform: 'test', arch: 'test' });
349 expect(error).toBeInstanceOf(Error);
350 expect(error).toBeInstanceOf(UnsupportedPlatformError);
350 - expect(error._tag).toBe('UnsupportedPlatformError');
351 + expect(Predicate.isTagged(error, 'UnsupportedPlatformError')).toBe(true);
352 });
353
354 it('should contain platform and arch information', () => {
@@ -364,24 +365,26 @@ describe('detect-platform.ts', () => {
365 });
366
367 describe('Type Tests', () => {
367 - it('should return correct PlatformArch type for supported combinations', async () => {
368 - // This test verifies TypeScript types at runtime
369 - const testType = async (platform: string, arch: string): Promise<PlatformArch> => {
370 - return await Effect.runPromise(
371 - detectPlatform.pipe(Effect.provide(createMockNodeOs(platform as NodeJS.Platform, arch)))
372 - );
373 - };
374 -
375 - // These calls should compile without TypeScript errors
376 - await expect(testType('darwin', 'x64')).resolves.toEqual({ platform: 'darwin', arch: 'x64' });
377 - await expect(testType('darwin', 'arm64')).resolves.toEqual({
378 - platform: 'darwin',
379 - arch: 'aarch64',
380 - });
381 - await expect(testType('linux', 'aarch64')).resolves.toEqual({
382 - platform: 'linux',
383 - arch: 'aarch64',
384 - });
385 - });
368 + it.effect('should return correct PlatformArch type for supported combinations', () =>
369 + Effect.gen(function* () {
370 + // This test verifies TypeScript types at runtime
371 + const testType = (
372 + platform: string,
373 + arch: string
374 + ): Effect.Effect<PlatformArch, UnsupportedPlatformError> =>
375 + detectPlatform.pipe(Effect.provide(createMockNodeOs(platform as NodeJS.Platform, arch)));
376 +
377 + // These calls should compile without TypeScript errors
378 + expect(yield* testType('darwin', 'x64')).toEqual({ platform: 'darwin', arch: 'x64' });
379 + expect(yield* testType('darwin', 'arm64')).toEqual({
380 + platform: 'darwin',
381 + arch: 'aarch64',
382 + });
383 + expect(yield* testType('linux', 'aarch64')).toEqual({
384 + platform: 'linux',
385 + arch: 'aarch64',
386 + });
387 + })
388 + );
389 });
390 });
ts/packages/cli/test/src/generation/safe-output-path.test.ts
+4 -3
@@ -1,5 +1,6 @@
1 import path from 'node:path';
2 import { describe, expect, it, assert } from '@effect/vitest';
3 +import { BunPath } from '@effect/platform-bun';
4 import { Effect, Either } from 'effect';
5 import { safeOutputPath, SafeOutputPathError } from 'src/generation/safe-output-path';
6
@@ -12,7 +13,7 @@ describe('safeOutputPath', () => {
13
14 expect(filePath).toBe(path.join(outputDir, 'gmail.ts'));
15 expect(path.isAbsolute(filePath)).toBe(false);
15 - })
16 + }, Effect.provide(BunPath.layer))
17 );
18
19 it.effect(
@@ -25,7 +26,7 @@ describe('safeOutputPath', () => {
26 assert(Either.isLeft(result));
27 expect(result.left).toBeInstanceOf(SafeOutputPathError);
28 expect(result.left.filename).toBe(path.resolve('gmail.ts'));
28 - })
29 + }, Effect.provide(BunPath.layer))
30 );
31
32 it.effect(
@@ -36,6 +37,6 @@ describe('safeOutputPath', () => {
37 assert(Either.isLeft(result));
38 expect(result.left).toBeInstanceOf(SafeOutputPathError);
39 expect(result.left.filename).toBe('../gmail.ts');
39 - })
40 + }, Effect.provide(BunPath.layer))
41 );
42 });
ts/packages/cli/test/src/generation/typescript/generate.test.ts
+4 -3
@@ -1,4 +1,5 @@
1 import { describe, expect, it } from '@effect/vitest';
2 +import { BunPath } from '@effect/platform-bun';
3 import { createToolkitIndex } from 'src/generation/create-toolkit-index';
4 import { generateTypeScriptSources } from 'src/generation/typescript/generate';
5 import { makeTestToolkits } from 'test/__utils__/models/toolkits';
@@ -67,7 +68,7 @@ describe('generateTypeScriptSources', () => {
68 `);
69
70 assertTypeScriptIsValid({ files: { './index.ts': source } });
70 - })
71 + }, Effect.provide(BunPath.layer))
72 );
73
74 it.effect(
@@ -156,7 +157,7 @@ describe('generateTypeScriptSources', () => {
157 assertTypeScriptIsValid({
158 files: { './index.ts': sources[1][1], './slack.ts': sources[0][1] },
159 });
159 - })
160 + }, Effect.provide(BunPath.layer))
161 );
162
163 it.effect(
@@ -247,7 +248,7 @@ describe('generateTypeScriptSources', () => {
248 assertTypeScriptIsValid({
249 files: { './index.ts': sources[1][1], './slack.ts': sources[0][1] },
250 });
250 - })
251 + }, Effect.provide(BunPath.layer))
252 );
253 });
254 });
ts/packages/cli/test/src/services/cli-session-artifacts.test.ts new
+183
@@ -0,0 +1,183 @@
1 +import { FileSystem, Path } from '@effect/platform';
2 +import { describe, expect, layer } from '@effect/vitest';
3 +import { afterEach, vi } from 'vitest';
4 +import { ConfigProvider, Effect, Option } from 'effect';
5 +import * as tempy from 'tempy';
6 +import {
7 + appendCliSessionHistory,
8 + resolveArtifactsRoot,
9 + resolveCliSessionArtifacts,
10 + storeCliSessionArtifact,
11 +} from 'src/services/cli-session-artifacts';
12 +import { ComposioCliUserConfig } from 'src/services/cli-user-config';
13 +import { extendConfigProvider } from 'src/services/config';
14 +import { defaultNodeOs, NodeOs } from 'src/services/node-os';
15 +import { TestLive } from 'test/__utils__';
16 +
17 +const cacheEnabledTestConfigProvider = ConfigProvider.fromMap(
18 + new Map([['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false']])
19 +).pipe(extendConfigProvider);
20 +
21 +describe('CLI session artifacts', () => {
22 + afterEach(() => {
23 + vi.unstubAllEnvs();
24 + });
25 +
26 + layer(TestLive())(it => {
27 + it.scoped('resolves artifact roots in documented precedence order', () =>
28 + Effect.gen(function* () {
29 + const path = yield* Path.Path;
30 + const config = yield* ComposioCliUserConfig;
31 + const sessionRoot = tempy.temporaryDirectory();
32 + const cacheRoot = tempy.temporaryDirectory();
33 + const configuredRoot = tempy.temporaryDirectory();
34 + const temporaryRoot = tempy.temporaryDirectory();
35 + const root = resolveArtifactsRoot.pipe(
36 + Effect.provideService(
37 + NodeOs,
38 + defaultNodeOs({ homedir: tempy.temporaryDirectory(), tmpdir: temporaryRoot })
39 + )
40 + );
41 +
42 + yield* config.update({ artifactDirectory: Option.some(configuredRoot) });
43 + vi.stubEnv('COMPOSIO_SESSION_DIR', sessionRoot);
44 + vi.stubEnv('COMPOSIO_CACHE_DIR', cacheRoot);
45 + expect(yield* root).toBe(sessionRoot);
46 +
47 + vi.stubEnv('COMPOSIO_SESSION_DIR', ' ');
48 + expect(yield* root).toBe(cacheRoot);
49 +
50 + vi.stubEnv('COMPOSIO_CACHE_DIR', ' ');
51 + expect(yield* root).toBe(configuredRoot);
52 +
53 + yield* config.update({ artifactDirectory: Option.none() });
54 + expect(yield* root).toBe(path.join(temporaryRoot, 'composio'));
55 + })
56 + );
57 +
58 + it.scoped('stores a sanitized artifact with the requested extension', () =>
59 + Effect.gen(function* () {
60 + const fs = yield* FileSystem.FileSystem;
61 + const path = yield* Path.Path;
62 + const directoryPath = yield* fs.makeTempDirectoryScoped();
63 +
64 + const filePath = yield* storeCliSessionArtifact({
65 + contents: '{"ok":true}',
66 + name: 'github issue output',
67 + extension: '.json',
68 + directoryPath,
69 + });
70 +
71 + expect(filePath).toBeDefined();
72 + if (filePath === undefined) {
73 + return yield* Effect.die('Expected the session artifact to be stored');
74 + }
75 + expect(path.dirname(filePath)).toBe(directoryPath);
76 + expect(path.basename(filePath)).toMatch(/^github_issue_output_[a-f0-9]{8}\.json$/i);
77 + expect(yield* fs.readFileString(filePath)).toBe('{"ok":true}');
78 + })
79 + );
80 +
81 + it.scoped('returns undefined when the artifact directory cannot be created', () =>
82 + Effect.gen(function* () {
83 + const fs = yield* FileSystem.FileSystem;
84 + const filePath = yield* fs.makeTempFileScoped();
85 +
86 + expect(
87 + yield* storeCliSessionArtifact({
88 + contents: '{}',
89 + name: 'output',
90 + directoryPath: filePath,
91 + })
92 + ).toBeUndefined();
93 + })
94 + );
95 +
96 + it.scoped('stores an adhoc artifact when no CLI session is available', () =>
97 + Effect.gen(function* () {
98 + const path = yield* Path.Path;
99 + const artifactsRoot = tempy.temporaryDirectory();
100 + vi.stubEnv('COMPOSIO_SESSION_DIR', artifactsRoot);
101 +
102 + const filePath = yield* storeCliSessionArtifact({
103 + contents: '{}',
104 + name: 'adhoc output',
105 + });
106 +
107 + expect(filePath).toBeDefined();
108 + if (filePath === undefined) {
109 + return yield* Effect.die('Expected an adhoc artifact');
110 + }
111 + const directoryPath = path.dirname(filePath);
112 + expect(path.dirname(directoryPath)).toBe(artifactsRoot);
113 + expect(path.basename(directoryPath)).toMatch(/^adhoc_[a-f0-9]{12}$/i);
114 + })
115 + );
116 + });
117 +
118 + layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(it => {
119 + const sessionScope = {
120 + orgId: 'org_test',
121 + consumerUserId: 'consumer-user-test',
122 + } as const;
123 +
124 + it.scoped('stores artifacts under the current CLI session without a directory override', () =>
125 + Effect.gen(function* () {
126 + const path = yield* Path.Path;
127 + const artifactsRoot = tempy.temporaryDirectory();
128 + vi.stubEnv('COMPOSIO_SESSION_DIR', artifactsRoot);
129 +
130 + const filePath = yield* storeCliSessionArtifact({
131 + contents: '{"session":true}',
132 + name: 'session output',
133 + ...sessionScope,
134 + });
135 +
136 + expect(filePath).toBeDefined();
137 + if (filePath === undefined) {
138 + return yield* Effect.die('Expected a session-backed artifact');
139 + }
140 + const directoryPath = path.dirname(filePath);
141 + expect(path.dirname(directoryPath)).toBe(artifactsRoot);
142 + expect(path.basename(directoryPath)).toMatch(/^cli_s_[a-z0-9]+_[a-f0-9]{10}$/i);
143 + })
144 + );
145 +
146 + it.scoped('appends multiple JSONL history entries to the same session', () =>
147 + Effect.gen(function* () {
148 + const fs = yield* FileSystem.FileSystem;
149 + const artifactsRoot = tempy.temporaryDirectory();
150 + vi.stubEnv('COMPOSIO_SESSION_DIR', artifactsRoot);
151 +
152 + yield* appendCliSessionHistory({ entry: { sequence: 1 }, ...sessionScope });
153 + yield* appendCliSessionHistory({ entry: { sequence: 2 }, ...sessionScope });
154 + const artifacts = yield* resolveCliSessionArtifacts(sessionScope);
155 +
156 + expect(Option.isSome(artifacts)).toBe(true);
157 + if (Option.isNone(artifacts)) {
158 + return yield* Effect.die('Expected session artifacts');
159 + }
160 + const lines = (yield* fs.readFileString(artifacts.value.historyFilePath, 'utf8'))
161 + .trim()
162 + .split('\n')
163 + .map(line => JSON.parse(line) as { sessionId: string; sequence: number });
164 + expect(lines).toEqual([
165 + expect.objectContaining({ sessionId: artifacts.value.sessionId, sequence: 1 }),
166 + expect.objectContaining({ sessionId: artifacts.value.sessionId, sequence: 2 }),
167 + ]);
168 + })
169 + );
170 +
171 + it.scoped('keeps history writes best-effort when the artifact root is not a directory', () =>
172 + Effect.gen(function* () {
173 + const fs = yield* FileSystem.FileSystem;
174 + const rootFile = yield* fs.makeTempFileScoped();
175 + vi.stubEnv('COMPOSIO_SESSION_DIR', rootFile);
176 +
177 + yield* appendCliSessionHistory({ entry: { sequence: 1 }, ...sessionScope });
178 +
179 + expect(yield* fs.readFileString(rootFile, 'utf8')).toBe('');
180 + })
181 + );
182 + });
183 +});
ts/packages/cli/test/src/services/cli-user-config.test.ts
+30 -6
@@ -4,7 +4,7 @@ import fs from 'node:fs';
4 import { describe, it, vi } from '@effect/vitest';
5 import { assertEquals } from '@effect/vitest/utils';
6 import { FileSystem } from '@effect/platform';
7 -import { BunFileSystem } from '@effect/platform-bun';
7 +import { BunFileSystem, BunPath } from '@effect/platform-bun';
8 import { ConfigProvider, Effect, Layer } from 'effect';
9 import { extendConfigProvider } from 'src/services/config';
10 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
@@ -24,7 +24,7 @@ describe('ComposioCliUserConfig', () => {
24 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
25 const CliUserConfigTest = Layer.provideMerge(
26 ComposioCliUserConfigLive,
27 - Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
27 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
28 );
29
30 return Effect.gen(function* () {
@@ -55,7 +55,7 @@ describe('ComposioCliUserConfig', () => {
55 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
56 const CliUserConfigTest = Layer.provideMerge(
57 ComposioCliUserConfigLive,
58 - Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
58 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
59 );
60
61 return Effect.gen(function* () {
@@ -76,7 +76,7 @@ describe('ComposioCliUserConfig', () => {
76 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
77 const CliUserConfigTest = Layer.provideMerge(
78 ComposioCliUserConfigLive,
79 - Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
79 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
80 );
81
82 return Effect.gen(function* () {
@@ -117,7 +117,7 @@ describe('ComposioCliUserConfig', () => {
117 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
118 const CliUserConfigTest = Layer.provideMerge(
119 ComposioCliUserConfigLive,
120 - Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
120 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
121 );
122
123 return Effect.gen(function* () {
@@ -170,7 +170,7 @@ describe('ComposioCliUserConfig', () => {
170 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
171 const CliUserConfigTest = Layer.provideMerge(
172 ComposioCliUserConfigLive,
173 - Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
173 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
174 );
175
176 return Effect.gen(function* () {
@@ -205,6 +205,30 @@ describe('ComposioCliUserConfig', () => {
205 assertEquals(parsed.developer_dangerous_commands_enabled, undefined);
206 }).pipe(Effect.provide(CliUserConfigTest));
207 });
208 +
209 + it.scoped('replaces malformed persisted config with safe defaults', () => {
210 + const cwd = tempy.temporaryDirectory();
211 + const map = new Map([['DEBUG_OVERRIDE_VERSION', '1.2.3']]) satisfies Map<string, string>;
212 + fs.mkdirSync(path.join(cwd, '.composio'), { recursive: true });
213 + fs.writeFileSync(path.join(cwd, '.composio', 'config.json'), JSON.stringify(['not-an-object']));
214 +
215 + const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
216 + const CliUserConfigTest = Layer.provideMerge(
217 + ComposioCliUserConfigLive,
218 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
219 + );
220 +
221 + return Effect.gen(function* () {
222 + const config = yield* ComposioCliUserConfig;
223 + assertEquals(config.data.developerModeEnabled, true);
224 + assertEquals(config.data.developerDangerousCommandsEnabled, false);
225 + assertEquals(config.data.security, 'auto');
226 +
227 + const persisted = fs.readFileSync(path.join(cwd, '.composio', 'config.json'), 'utf8');
228 + assertEquals(Array.isArray(JSON.parse(persisted)), false);
229 + }).pipe(Effect.provide(CliUserConfigTest));
230 + });
231 +
232 it.effect('resolves sync config path from COMPOSIO_CACHE_DIR when provided', () => {
233 const cacheDir = tempy.temporaryDirectory();
234 process.env.COMPOSIO_CACHE_DIR = cacheDir;
ts/packages/cli/test/src/services/composio-client-singleton.test.ts
+126 -26
@@ -1,6 +1,7 @@
1 -import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
2 -import { BunFileSystem } from '@effect/platform-bun';
3 -import { ConfigProvider, Effect, Layer, Option } from 'effect';
1 +import { afterEach, beforeAll, describe, expect, it, vi } from '@effect/vitest';
2 +import { FileSystem, Path } from '@effect/platform';
3 +import { BunFileSystem, BunPath } from '@effect/platform-bun';
4 +import { ConfigProvider, Effect, Layer } from 'effect';
5 import { execSync } from 'node:child_process';
6 import * as tempy from 'tempy';
7 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -11,6 +12,7 @@ import { extendConfigProvider } from 'src/services/config';
12 const withConfigLayer = (map: Map<string, string>, homedir: string) =>
13 Layer.mergeAll(
14 BunFileSystem.layer,
15 + BunPath.layer,
16 Layer.succeed(NodeOs, defaultNodeOs({ homedir })),
17 Layer.setConfigProvider(extendConfigProvider(ConfigProvider.fromMap(map)))
18 );
@@ -21,6 +23,35 @@ const okResponse = () =>
23 headers: { 'Content-Type': 'application/json' },
24 });
25
26 +const cwdHash = (cwd: string): string => {
27 + let hash = 5381;
28 + for (let index = 0; index < cwd.length; index += 1) {
29 + hash = (hash * 33) ^ cwd.charCodeAt(index);
30 + }
31 + return Math.abs(hash >>> 0).toString(36);
32 +};
33 +
34 +const writeCliSessionCache = (
35 + homedir: string,
36 + session: { readonly id: string; readonly expiresAt: string }
37 +) =>
38 + Effect.gen(function* () {
39 + const fs = yield* FileSystem.FileSystem;
40 + const path = yield* Path.Path;
41 + const cacheDir = path.join(homedir, '.composio');
42 + yield* fs.makeDirectory(cacheDir, { recursive: true });
43 + yield* fs.writeFileString(
44 + path.join(cacheDir, 'consumer-short-term-cache.json'),
45 + JSON.stringify({
46 + test: {
47 + probablyMyCliSessionsByCwdHash: {
48 + [cwdHash(process.cwd())]: session,
49 + },
50 + },
51 + })
52 + );
53 + });
54 +
55 describe('ComposioClientSingleton headers', () => {
56 // Delete any real keychain entry so the subprocess keyring read
57 // inside ComposioUserContextLive (baked into
@@ -40,9 +71,10 @@ describe('ComposioClientSingleton headers', () => {
71
72 afterEach(() => {
73 vi.restoreAllMocks();
74 + vi.unstubAllEnvs();
75 });
76
45 - it('uses x-user-api-key and never x-api-key', async () => {
77 + it.effect('uses x-user-api-key and never x-api-key', () => {
78 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
79 const homedir = tempy.temporaryDirectory();
80 const configMap = new Map([
@@ -51,7 +83,7 @@ describe('ComposioClientSingleton headers', () => {
83 ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
84 ]);
85
54 - const program = Effect.gen(function* () {
86 + return Effect.gen(function* () {
87 const client = yield* ComposioClientSingleton.get();
88 yield* Effect.promise(() =>
89 client.tools
@@ -59,35 +91,78 @@ describe('ComposioClientSingleton headers', () => {
91 .then(() => undefined)
92 .catch(() => undefined)
93 );
94 +
95 + expect(fetchSpy).toHaveBeenCalledOnce();
96 + const [, init] = fetchSpy.mock.calls[0]!;
97 + const headers = new Headers((init as RequestInit).headers);
98 +
99 + expect(headers.get('x-user-api-key')).toBe('uak_from_user_env');
100 + expect(headers.has('x-api-key')).toBe(false);
101 + expect(headers.get('x-framework')).toBe('cli');
102 + expect(headers.get('x-source')).toBe('CLI');
103 + expect(headers.get('x-runtime')).toBe('NODEJS');
104 + expect(headers.get('x-sdk-version')).toBe(APP_VERSION);
105 + expect(headers.get('x-cli-session-id')).toBeNull();
106 }).pipe(
107 Effect.provide(
108 Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
109 )
110 );
111 + });
112
68 - await Effect.runPromise(program);
113 + // Fixed instants far in the future/past keep the expiry comparison
114 + // deterministic regardless of the clock the session-id reader consults.
115 + it.effect('includes the current cwd CLI session ID', () => {
116 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
117 + const homedir = tempy.temporaryDirectory();
118 + const configMap = new Map([
119 + ['COMPOSIO_USER_API_KEY', 'uak_from_user_env'],
120 + ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
121 + ]);
122
70 - expect(fetchSpy).toHaveBeenCalledOnce();
71 - const [, init] = fetchSpy.mock.calls[0]!;
72 - const headers = new Headers((init as RequestInit).headers);
123 + return Effect.gen(function* () {
124 + const path = yield* Path.Path;
125 + // The session-id reader resolves its cache dir from COMPOSIO_CACHE_DIR
126 + // (stubbed by the shared vitest setup) before falling back to homedir,
127 + // so point it at the directory this test writes the fixture into.
128 + vi.stubEnv('COMPOSIO_CACHE_DIR', path.join(homedir, '.composio'));
129 + yield* writeCliSessionCache(homedir, {
130 + id: 'cli_s_current',
131 + expiresAt: '2099-01-01T00:00:00.000Z',
132 + });
133 + const client = yield* ComposioClientSingleton.get();
134 + yield* Effect.promise(() =>
135 + client.tools
136 + .list({ limit: 1, toolkit_versions: 'latest' })
137 + .then(() => undefined)
138 + .catch(() => undefined)
139 + );
140
74 - expect(headers.get('x-user-api-key')).toBe('uak_from_user_env');
75 - expect(headers.has('x-api-key')).toBe(false);
76 - expect(headers.get('x-framework')).toBe('cli');
77 - expect(headers.get('x-source')).toBe('CLI');
78 - expect(headers.get('x-runtime')).toBe('NODEJS');
79 - expect(headers.get('x-sdk-version')).toBe(APP_VERSION);
141 + const [, init] = fetchSpy.mock.calls[0]!;
142 + const headers = new Headers((init as RequestInit).headers);
143 + expect(headers.get('x-cli-session-id')).toBe('cli_s_current');
144 + }).pipe(
145 + Effect.provide(
146 + Layer.provideMerge(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
147 + )
148 + );
149 });
150
82 - it('does not read COMPOSIO_API_KEY for user auth', async () => {
151 + it.effect('omits an expired cwd CLI session ID', () => {
152 const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
153 const homedir = tempy.temporaryDirectory();
154 const configMap = new Map([
86 - ['COMPOSIO_API_KEY', 'ak_only'],
155 + ['COMPOSIO_USER_API_KEY', 'uak_from_user_env'],
156 ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
157 ]);
158
90 - const program = Effect.gen(function* () {
159 + return Effect.gen(function* () {
160 + const path = yield* Path.Path;
161 + vi.stubEnv('COMPOSIO_CACHE_DIR', path.join(homedir, '.composio'));
162 + yield* writeCliSessionCache(homedir, {
163 + id: 'cli_s_expired',
164 + expiresAt: '1970-01-01T00:01:00.000Z',
165 + });
166 const client = yield* ComposioClientSingleton.get();
167 yield* Effect.promise(() =>
168 client.tools
@@ -95,20 +170,45 @@ describe('ComposioClientSingleton headers', () => {
170 .then(() => undefined)
171 .catch(() => undefined)
172 );
173 +
174 + const [, init] = fetchSpy.mock.calls[0]!;
175 + const headers = new Headers((init as RequestInit).headers);
176 + expect(headers.get('x-cli-session-id')).toBeNull();
177 }).pipe(
178 Effect.provide(
100 - Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
179 + Layer.provideMerge(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
180 )
181 );
182 + });
183 +
184 + it.effect('does not read COMPOSIO_API_KEY for user auth', () => {
185 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
186 + const homedir = tempy.temporaryDirectory();
187 + const configMap = new Map([
188 + ['COMPOSIO_API_KEY', 'ak_only'],
189 + ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
190 + ]);
191
104 - await Effect.runPromise(program);
192 + return Effect.gen(function* () {
193 + const client = yield* ComposioClientSingleton.get();
194 + yield* Effect.promise(() =>
195 + client.tools
196 + .list({ limit: 1, toolkit_versions: 'latest' })
197 + .then(() => undefined)
198 + .catch(() => undefined)
199 + );
200
106 - expect(fetchSpy).toHaveBeenCalledOnce();
107 - const [, init] = fetchSpy.mock.calls[0]!;
108 - const headers = new Headers((init as RequestInit).headers);
201 + expect(fetchSpy).toHaveBeenCalledOnce();
202 + const [, init] = fetchSpy.mock.calls[0]!;
203 + const headers = new Headers((init as RequestInit).headers);
204
110 - expect(headers.get('x-user-api-key')).toBeNull();
111 - expect(headers.has('x-api-key')).toBe(false);
112 - expect(headers.get('x-source')).toBe('CLI');
205 + expect(headers.get('x-user-api-key')).toBeNull();
206 + expect(headers.has('x-api-key')).toBe(false);
207 + expect(headers.get('x-source')).toBe('CLI');
208 + }).pipe(
209 + Effect.provide(
210 + Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
211 + )
212 + );
213 });
214 });
ts/packages/cli/test/src/services/detached-process.test.ts new
+22
@@ -0,0 +1,22 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import { DetachedProcessSpawnError, spawnDetached } from 'src/services/detached-process';
4 +
5 +describe('spawnDetached', () => {
6 + it.effect('fails when the executable does not exist', () =>
7 + Effect.gen(function* () {
8 + const command = '__composio_missing_detached_process__';
9 + const error = yield* spawnDetached(command, []).pipe(Effect.flip);
10 +
11 + expect(error).toBeInstanceOf(DetachedProcessSpawnError);
12 + expect(error.command).toBe(command);
13 + expect(String(error.cause)).toContain('ENOENT');
14 + })
15 + );
16 +
17 + it.effect('succeeds after the child process spawns', () =>
18 + Effect.gen(function* () {
19 + yield* spawnDetached(process.execPath, ['-e', 'process.exit(0)']);
20 + })
21 + );
22 +});
ts/packages/cli/test/src/services/node-os.test.ts new
+33
@@ -0,0 +1,33 @@
1 +import os from 'node:os';
2 +import { describe, expect, it } from '@effect/vitest';
3 +import { Effect } from 'effect';
4 +import { defaultNodeOs, NodeOs } from 'src/services/node-os';
5 +
6 +describe('NodeOs', () => {
7 + it.effect('exposes operating-system details through an Effect service', () =>
8 + Effect.gen(function* () {
9 + const nodeOs = yield* NodeOs;
10 +
11 + expect(nodeOs).toMatchObject({
12 + homedir: os.homedir(),
13 + tmpdir: os.tmpdir(),
14 + platform: os.platform(),
15 + arch: os.arch(),
16 + });
17 + }).pipe(Effect.provide(NodeOs.Default))
18 + );
19 +
20 + it('supports deterministic home and temporary directories in tests', () => {
21 + expect(
22 + defaultNodeOs({
23 + homedir: '/test/home',
24 + tmpdir: '/test/tmp',
25 + })
26 + ).toMatchObject({
27 + homedir: '/test/home',
28 + tmpdir: '/test/tmp',
29 + platform: os.platform(),
30 + arch: os.arch(),
31 + });
32 + });
33 +});
ts/packages/cli/test/src/services/run-companion-modules.test.ts new
+130
@@ -0,0 +1,130 @@
1 +import * as fs from 'node:fs';
2 +import * as os from 'node:os';
3 +import * as path from 'node:path';
4 +import { BunContext } from '@effect/platform-bun';
5 +import { afterEach, describe, expect, layer, vi } from '@effect/vitest';
6 +import { Effect } from 'effect';
7 +import { repairMissingInstalledRunCompanionModules } from 'src/services/run-companion-modules';
8 +import { BaseConfigProviderLive, extendConfigProvider } from 'src/services/config';
9 +
10 +describe('run-companion-modules', () => {
11 + afterEach(() => {
12 + vi.unstubAllGlobals();
13 + vi.unstubAllEnvs();
14 + });
15 +
16 + layer(BunContext.layer)(it => {
17 + it.effect(
18 + '[Given] malformed release metadata [Then] repair rejects it before using release assets',
19 + () => {
20 + const installDirectory = fs.mkdtempSync(
21 + path.join(os.tmpdir(), 'composio-run-repair-test-')
22 + );
23 + const fetchMock = vi.fn().mockResolvedValue(
24 + new Response(JSON.stringify({ tag_name: 123, assets: 'invalid' }), {
25 + status: 200,
26 + headers: { 'content-type': 'application/json' },
27 + })
28 + );
29 + vi.stubGlobal('fetch', fetchMock);
30 +
31 + return Effect.gen(function* () {
32 + const error = yield* repairMissingInstalledRunCompanionModules({
33 + callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
34 + execPath: path.join(installDirectory, 'composio'),
35 + appVersion: '0.0.0-test',
36 + }).pipe(Effect.flip);
37 +
38 + expect(error.message).toContain("Unable to restore the files required by 'composio run'");
39 + expect(fetchMock).toHaveBeenCalledOnce();
40 + }).pipe(
41 + Effect.ensuring(
42 + Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
43 + )
44 + );
45 + }
46 + );
47 +
48 + it.effect(
49 + '[Given] unprefixed GITHUB_* env under the CLI-wide prefixed provider [Then] repair honors the unprefixed contract',
50 + () => {
51 + const installDirectory = fs.mkdtempSync(
52 + path.join(os.tmpdir(), 'composio-run-repair-test-')
53 + );
54 + const fetchMock = vi.fn().mockResolvedValue(
55 + new Response(JSON.stringify({ tag_name: 123, assets: 'invalid' }), {
56 + status: 200,
57 + headers: { 'content-type': 'application/json' },
58 + })
59 + );
60 + vi.stubGlobal('fetch', fetchMock);
61 + vi.stubEnv('GITHUB_TAG', '@composio/cli@9.9.9-test');
62 + vi.stubEnv('GITHUB_API_BASE_URL', 'https://github-proxy.test');
63 + vi.stubEnv('GITHUB_OWNER', 'fork-owner');
64 + vi.stubEnv('GITHUB_REPO', 'fork-repo');
65 +
66 + return Effect.gen(function* () {
67 + yield* repairMissingInstalledRunCompanionModules({
68 + callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
69 + execPath: path.join(installDirectory, 'composio'),
70 + appVersion: '0.0.0-test',
71 + }).pipe(Effect.flip);
72 +
73 + expect(fetchMock).toHaveBeenCalledOnce();
74 + const requestUrl = String(fetchMock.mock.calls[0]?.[0]);
75 + expect(requestUrl).toBe(
76 + 'https://github-proxy.test/repos/fork-owner/fork-repo/releases/tags/%40composio%2Fcli%409.9.9-test'
77 + );
78 + }).pipe(
79 + // Simulate the cli-main runtime, whose provider rewrites config keys
80 + // to their COMPOSIO_-prefixed spelling.
81 + Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive)),
82 + Effect.ensuring(
83 + Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
84 + )
85 + );
86 + }
87 + );
88 +
89 + it.effect(
90 + '[Given] only COMPOSIO_-prefixed GITHUB_* env [Then] repair falls back to the prefixed spelling',
91 + () => {
92 + const installDirectory = fs.mkdtempSync(
93 + path.join(os.tmpdir(), 'composio-run-repair-test-')
94 + );
95 + const fetchMock = vi.fn().mockResolvedValue(
96 + new Response(JSON.stringify({ tag_name: 123, assets: 'invalid' }), {
97 + status: 200,
98 + headers: { 'content-type': 'application/json' },
99 + })
100 + );
101 + vi.stubGlobal('fetch', fetchMock);
102 + vi.stubEnv('GITHUB_TAG', undefined);
103 + vi.stubEnv('GITHUB_API_BASE_URL', undefined);
104 + vi.stubEnv('GITHUB_OWNER', undefined);
105 + vi.stubEnv('GITHUB_REPO', undefined);
106 + vi.stubEnv('COMPOSIO_GITHUB_TAG', '@composio/cli@8.8.8-test');
107 + vi.stubEnv('COMPOSIO_GITHUB_API_BASE_URL', 'https://prefixed-proxy.test');
108 +
109 + return Effect.gen(function* () {
110 + yield* repairMissingInstalledRunCompanionModules({
111 + callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
112 + execPath: path.join(installDirectory, 'composio'),
113 + appVersion: '0.0.0-test',
114 + }).pipe(Effect.flip);
115 +
116 + expect(fetchMock).toHaveBeenCalledOnce();
117 + const requestUrl = String(fetchMock.mock.calls[0]?.[0]);
118 + expect(requestUrl).toBe(
119 + 'https://prefixed-proxy.test/repos/ComposioHQ/composio/releases/tags/%40composio%2Fcli%408.8.8-test'
120 + );
121 + }).pipe(
122 + Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive)),
123 + Effect.ensuring(
124 + Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
125 + )
126 + );
127 + }
128 + );
129 + });
130 +});
ts/packages/cli/test/src/services/setup-skill-installer.test.ts
+4 -2
@@ -26,7 +26,9 @@ describe('SetupSkillInstaller', () => {
26 '@composio/cli@0.2.20-beta.42\n'
27 );
28
29 - expect(resolveSetupSkillReleaseTag(execPath, '0.3.0')).toBe('@composio/cli@0.2.20-beta.42');
29 + expect(yield* resolveSetupSkillReleaseTag(execPath, '0.3.0')).toBe(
30 + '@composio/cli@0.2.20-beta.42'
31 + );
32 })
33 );
34
@@ -35,7 +37,7 @@ describe('SetupSkillInstaller', () => {
37 const path = yield* Path.Path;
38 const installDir = tempy.temporaryDirectory();
39
38 - expect(resolveSetupSkillReleaseTag(path.join(installDir, 'composio'), '0.3.0')).toBe(
40 + expect(yield* resolveSetupSkillReleaseTag(path.join(installDir, 'composio'), '0.3.0')).toBe(
41 '@composio/cli@0.3.0'
42 );
43 })
ts/packages/cli/test/src/services/upgrade-binary.test.ts
+324 -298
@@ -1,6 +1,6 @@
1 import { describe, expect, it, vi } from '@effect/vitest';
2 import { ConfigProvider, Effect, Layer } from 'effect';
3 -import { FetchHttpClient } from '@effect/platform';
3 +import { FetchHttpClient, Path } from '@effect/platform';
4 import { BunFileSystem } from '@effect/platform-bun';
5 import { existsSync, mkdirSync, readFileSync, mkdtempSync, writeFileSync } from 'node:fs';
6 import { tmpdir } from 'node:os';
@@ -42,6 +42,7 @@ const NodeOsTest = Layer.succeed(
42 NodeOs,
43 new NodeOs({
44 homedir: '/tmp',
45 + tmpdir: '/tmp',
46 platform: 'darwin',
47 arch: 'arm64',
48 })
@@ -71,286 +72,311 @@ const runUpgrade = (
72 options?: {
73 prerelease?: boolean;
74 }
74 -) => makeUpgradeEffect(configEntries, options).pipe(Effect.flip, Effect.runPromise);
75 +) => makeUpgradeEffect(configEntries, options).pipe(Effect.flip);
76
77 const runUpgradeSuccess = (
78 configEntries: ReadonlyArray<[string, string]>,
79 options?: {
80 prerelease?: boolean;
81 }
81 -) => makeUpgradeEffect(configEntries, options).pipe(Effect.runPromise);
82 +) => makeUpgradeEffect(configEntries, options);
83 +
84 +/**
85 + * Bridge the promise-based `withHttpServer` harness into a scoped Effect:
86 + * acquisition starts the server and yields its base URL, and closing the
87 + * test scope lets `withHttpServer` run its teardown path.
88 + */
89 +const scopedHttpServer = (handler: Parameters<typeof withHttpServer>[0]) =>
90 + Effect.acquireRelease(
91 + Effect.promise(
92 + () =>
93 + new Promise<{ baseUrl: string; release: () => void; closed: Promise<void> }>(
94 + (resolveAcquire, rejectAcquire) => {
95 + let release!: () => void;
96 + const released = new Promise<void>(resolve => {
97 + release = resolve;
98 + });
99 + const closed = withHttpServer(handler, baseUrl => {
100 + resolveAcquire({ baseUrl, release, closed });
101 + return released;
102 + });
103 + closed.catch(rejectAcquire);
104 + }
105 + )
106 + ),
107 + ({ release, closed }) =>
108 + Effect.promise(() => {
109 + release();
110 + return closed;
111 + })
112 + ).pipe(Effect.map(({ baseUrl }) => baseUrl));
113 +
114 +const restoreStubsAndMocks = Effect.sync(() => {
115 + vi.unstubAllGlobals();
116 + vi.restoreAllMocks();
117 +});
118
119 describe('UpgradeBinary', () => {
84 - it('wraps non-2xx releases fetch failures with fetch context (no tag branch)', async () => {
120 + it.scoped('wraps non-2xx releases fetch failures with fetch context (no tag branch)', () => {
121 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
122
87 - try {
88 - await withHttpServer(
89 - (_req, res) => {
90 - res.writeHead(500, { 'content-type': 'application/json' });
91 - res.end(JSON.stringify({ message: 'rate limited' }));
92 - },
93 - async apiBaseUrl => {
94 - const error = await runUpgrade([
95 - ['GITHUB_API_BASE_URL', apiBaseUrl],
96 - ['GITHUB_OWNER', 'test-owner'],
97 - ['GITHUB_REPO', 'test-repo'],
98 - ]);
99 -
100 - expect(error).toBeInstanceOf(UpgradeBinaryError);
101 - if (!(error instanceof UpgradeBinaryError)) {
102 - throw error;
103 - }
104 - expect(error.message).toBe('Failed to fetch releases from GitHub');
105 - expect(String(error.cause)).toContain('HTTP 500');
106 - }
107 - );
108 - } finally {
109 - vi.unstubAllGlobals();
110 - vi.restoreAllMocks();
111 - }
123 + return Effect.gen(function* () {
124 + const apiBaseUrl = yield* scopedHttpServer((_req, res) => {
125 + res.writeHead(500, { 'content-type': 'application/json' });
126 + res.end(JSON.stringify({ message: 'rate limited' }));
127 + });
128 +
129 + const error = yield* runUpgrade([
130 + ['GITHUB_API_BASE_URL', apiBaseUrl],
131 + ['GITHUB_OWNER', 'test-owner'],
132 + ['GITHUB_REPO', 'test-repo'],
133 + ]);
134 +
135 + expect(error).toBeInstanceOf(UpgradeBinaryError);
136 + if (!(error instanceof UpgradeBinaryError)) {
137 + throw error;
138 + }
139 + expect(error.message).toBe('Failed to fetch releases from GitHub');
140 + expect(String(error.cause)).toContain('HTTP 500');
141 + }).pipe(Effect.ensuring(restoreStubsAndMocks));
142 });
143
114 - it('wraps tagged release JSON parse failures with parse context (tag branch)', async () => {
144 + it.scoped('wraps tagged release JSON parse failures with parse context (tag branch)', () => {
145 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
146
117 - try {
118 - await withHttpServer(
119 - (_req, res) => {
120 - res.writeHead(200, { 'content-type': 'application/json' });
121 - res.end('not-json');
122 - },
123 - async apiBaseUrl => {
124 - const error = await runUpgrade([
125 - ['GITHUB_API_BASE_URL', apiBaseUrl],
126 - ['GITHUB_OWNER', 'test-owner'],
127 - ['GITHUB_REPO', 'test-repo'],
128 - ['GITHUB_TAG', 'v9.9.9'],
129 - ]);
130 -
131 - expect(error).toBeInstanceOf(UpgradeBinaryError);
132 - if (!(error instanceof UpgradeBinaryError)) {
133 - throw error;
134 - }
135 - expect(error.message).toBe('Failed to parse GitHub release JSON response');
136 - }
137 - );
138 - } finally {
139 - vi.unstubAllGlobals();
140 - vi.restoreAllMocks();
141 - }
147 + return Effect.gen(function* () {
148 + const apiBaseUrl = yield* scopedHttpServer((_req, res) => {
149 + res.writeHead(200, { 'content-type': 'application/json' });
150 + res.end('not-json');
151 + });
152 +
153 + const error = yield* runUpgrade([
154 + ['GITHUB_API_BASE_URL', apiBaseUrl],
155 + ['GITHUB_OWNER', 'test-owner'],
156 + ['GITHUB_REPO', 'test-repo'],
157 + ['GITHUB_TAG', 'v9.9.9'],
158 + ]);
159 +
160 + expect(error).toBeInstanceOf(UpgradeBinaryError);
161 + if (!(error instanceof UpgradeBinaryError)) {
162 + throw error;
163 + }
164 + expect(error.message).toBe('Failed to parse GitHub release JSON response');
165 + }).pipe(Effect.ensuring(restoreStubsAndMocks));
166 });
167
144 - it('URL-encodes slash-containing tags in tagged release request path', async () => {
168 + it.scoped('rejects structurally invalid tagged release JSON', () => {
169 + vi.stubGlobal('Bun', { which: vi.fn(() => null) });
170 +
171 + return Effect.gen(function* () {
172 + const apiBaseUrl = yield* scopedHttpServer((_req, res) => {
173 + res.writeHead(200, { 'content-type': 'application/json' });
174 + res.end(JSON.stringify({ tag_name: 42, assets: 'not-an-array' }));
175 + });
176 +
177 + const error = yield* runUpgrade([
178 + ['GITHUB_API_BASE_URL', apiBaseUrl],
179 + ['GITHUB_OWNER', 'test-owner'],
180 + ['GITHUB_REPO', 'test-repo'],
181 + ['GITHUB_TAG', 'v9.9.9'],
182 + ]);
183 +
184 + expect(error).toBeInstanceOf(UpgradeBinaryError);
185 + if (!(error instanceof UpgradeBinaryError)) {
186 + throw error;
187 + }
188 + expect(error.message).toBe('Failed to parse GitHub release JSON response');
189 + }).pipe(Effect.ensuring(restoreStubsAndMocks));
190 + });
191 +
192 + it.scoped('URL-encodes slash-containing tags in tagged release request path', () => {
193 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
194 let receivedPath = '';
195
148 - try {
149 - await withHttpServer(
150 - (req, res) => {
151 - receivedPath = req.url ?? '';
152 - res.writeHead(500, { 'content-type': 'application/json' });
153 - res.end(JSON.stringify({ message: 'forced failure' }));
154 - },
155 - async apiBaseUrl => {
156 - const tag = '@composio/cli@0.1.24';
157 - const error = await runUpgrade([
158 - ['GITHUB_API_BASE_URL', apiBaseUrl],
159 - ['GITHUB_OWNER', 'test-owner'],
160 - ['GITHUB_REPO', 'test-repo'],
161 - ['GITHUB_TAG', tag],
162 - ]);
163 -
164 - expect(error).toBeInstanceOf(UpgradeBinaryError);
165 - if (!(error instanceof UpgradeBinaryError)) {
166 - throw error;
167 - }
168 - expect(receivedPath).toBe(
169 - `/repos/test-owner/test-repo/releases/tags/${encodeURIComponent(tag)}`
170 - );
171 - }
196 + return Effect.gen(function* () {
197 + const apiBaseUrl = yield* scopedHttpServer((req, res) => {
198 + receivedPath = req.url ?? '';
199 + res.writeHead(500, { 'content-type': 'application/json' });
200 + res.end(JSON.stringify({ message: 'forced failure' }));
201 + });
202 +
203 + const tag = '@composio/cli@0.1.24';
204 + const error = yield* runUpgrade([
205 + ['GITHUB_API_BASE_URL', apiBaseUrl],
206 + ['GITHUB_OWNER', 'test-owner'],
207 + ['GITHUB_REPO', 'test-repo'],
208 + ['GITHUB_TAG', tag],
209 + ]);
210 +
211 + expect(error).toBeInstanceOf(UpgradeBinaryError);
212 + if (!(error instanceof UpgradeBinaryError)) {
213 + throw error;
214 + }
215 + expect(receivedPath).toBe(
216 + `/repos/test-owner/test-repo/releases/tags/${encodeURIComponent(tag)}`
217 );
173 - } finally {
174 - vi.unstubAllGlobals();
175 - vi.restoreAllMocks();
176 - }
218 + }).pipe(Effect.ensuring(restoreStubsAndMocks));
219 });
220
179 - it('skips newer releases that do not contain a binary for the current platform', async () => {
221 + it.scoped('skips newer releases that do not contain a binary for the current platform', () => {
222 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
223
182 - try {
183 - await withHttpServer(
184 - (_req, res) => {
185 - res.writeHead(200, { 'content-type': 'application/json' });
186 - res.end(
187 - JSON.stringify([
188 - {
189 - tag_name: '@composio/cli@0.2.15',
190 - draft: false,
191 - prerelease: false,
192 - assets: [
193 - {
194 - name: 'composio-linux-x64.zip',
195 - browser_download_url: 'http://127.0.0.1/unused-linux.zip',
196 - },
197 - ],
198 - },
199 - {
200 - tag_name: '@composio/cli@0.2.14',
201 - draft: false,
202 - prerelease: false,
203 - assets: [
204 - {
205 - name: 'composio-darwin-aarch64.zip',
206 - browser_download_url: 'http://127.0.0.1/current-darwin.zip',
207 - },
208 - ],
209 - },
210 - ])
211 - );
212 - },
213 - async apiBaseUrl => {
214 - const result = await runUpgradeSuccess([
215 - ['GITHUB_API_BASE_URL', apiBaseUrl],
216 - ['GITHUB_OWNER', 'test-owner'],
217 - ['GITHUB_REPO', 'test-repo'],
218 - ]);
219 -
220 - expect(result).toBeUndefined();
221 - }
222 - );
223 - } finally {
224 - vi.unstubAllGlobals();
225 - vi.restoreAllMocks();
226 - }
224 + return Effect.gen(function* () {
225 + const apiBaseUrl = yield* scopedHttpServer((_req, res) => {
226 + res.writeHead(200, { 'content-type': 'application/json' });
227 + res.end(
228 + JSON.stringify([
229 + {
230 + tag_name: '@composio/cli@0.2.15',
231 + draft: false,
232 + prerelease: false,
233 + assets: [
234 + {
235 + name: 'composio-linux-x64.zip',
236 + browser_download_url: 'http://127.0.0.1/unused-linux.zip',
237 + },
238 + ],
239 + },
240 + {
241 + tag_name: '@composio/cli@0.2.14',
242 + draft: false,
243 + prerelease: false,
244 + assets: [
245 + {
246 + name: 'composio-darwin-aarch64.zip',
247 + browser_download_url: 'http://127.0.0.1/current-darwin.zip',
248 + },
249 + ],
250 + },
251 + ])
252 + );
253 + });
254 +
255 + const result = yield* runUpgradeSuccess([
256 + ['GITHUB_API_BASE_URL', apiBaseUrl],
257 + ['GITHUB_OWNER', 'test-owner'],
258 + ['GITHUB_REPO', 'test-repo'],
259 + ]);
260 +
261 + expect(result).toBeUndefined();
262 + }).pipe(Effect.ensuring(restoreStubsAndMocks));
263 });
264
229 - it('ignores prereleases when checking the stable channel', async () => {
265 + it.scoped('ignores prereleases when checking the stable channel', () => {
266 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
267
232 - try {
233 - await withHttpServer(
234 - (_req, res) => {
235 - res.writeHead(200, { 'content-type': 'application/json' });
236 - res.end(
237 - JSON.stringify([
238 - {
239 - tag_name: '@composio/cli@0.2.18-beta.9',
240 - draft: false,
241 - prerelease: true,
242 - assets: [
243 - {
244 - name: 'composio-darwin-aarch64.zip',
245 - browser_download_url: 'http://127.0.0.1/beta.zip',
246 - },
247 - ],
248 - },
249 - {
250 - tag_name: '@composio/cli@0.2.17',
251 - draft: false,
252 - prerelease: false,
253 - assets: [
254 - {
255 - name: 'composio-darwin-aarch64.zip',
256 - browser_download_url: 'http://127.0.0.1/stable.zip',
257 - },
258 - ],
259 - },
260 - ])
261 - );
262 - },
263 - async apiBaseUrl => {
264 - const result = await runUpgradeSuccess([
265 - ['GITHUB_API_BASE_URL', apiBaseUrl],
266 - ['GITHUB_OWNER', 'test-owner'],
267 - ['GITHUB_REPO', 'test-repo'],
268 - ]);
269 -
270 - expect(result).toBeUndefined();
271 - }
272 - );
273 - } finally {
274 - vi.unstubAllGlobals();
275 - vi.restoreAllMocks();
276 - }
268 + return Effect.gen(function* () {
269 + const apiBaseUrl = yield* scopedHttpServer((_req, res) => {
270 + res.writeHead(200, { 'content-type': 'application/json' });
271 + res.end(
272 + JSON.stringify([
273 + {
274 + tag_name: '@composio/cli@0.2.18-beta.9',
275 + draft: false,
276 + prerelease: true,
277 + assets: [
278 + {
279 + name: 'composio-darwin-aarch64.zip',
280 + browser_download_url: 'http://127.0.0.1/beta.zip',
281 + },
282 + ],
283 + },
284 + {
285 + tag_name: '@composio/cli@0.2.17',
286 + draft: false,
287 + prerelease: false,
288 + assets: [
289 + {
290 + name: 'composio-darwin-aarch64.zip',
291 + browser_download_url: 'http://127.0.0.1/stable.zip',
292 + },
293 + ],
294 + },
295 + ])
296 + );
297 + });
298 +
299 + const result = yield* runUpgradeSuccess([
300 + ['GITHUB_API_BASE_URL', apiBaseUrl],
301 + ['GITHUB_OWNER', 'test-owner'],
302 + ['GITHUB_REPO', 'test-repo'],
303 + ]);
304 +
305 + expect(result).toBeUndefined();
306 + }).pipe(Effect.ensuring(restoreStubsAndMocks));
307 });
308
279 - it('selects the latest prerelease when beta upgrades are requested', async () => {
309 + it.scoped('selects the latest prerelease when beta upgrades are requested', () => {
310 const installDir = mkdtempSync(path.join(tmpdir(), 'composio-beta-select-'));
311 const fakeExecPath = path.join(installDir, 'composio');
312 writeFileSync(path.join(installDir, 'release-tag.txt'), '@composio/cli@0.1.0-beta.0\n');
313 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
314 const execPathSpy = vi.spyOn(process, 'execPath', 'get').mockReturnValue(fakeExecPath);
315
286 - try {
287 - await withHttpServer(
288 - (_req, res) => {
289 - res.writeHead(200, { 'content-type': 'application/json' });
290 - res.end(
291 - JSON.stringify([
292 - {
293 - tag_name: '@composio/cli@0.2.19-beta.1',
294 - draft: false,
295 - prerelease: true,
296 - assets: [
297 - {
298 - name: 'composio-darwin-aarch64.zip',
299 - browser_download_url: 'http://127.0.0.1/beta-1.zip',
300 - },
301 - ],
302 - },
303 - {
304 - tag_name: '@composio/cli@0.2.19-beta.3',
305 - draft: false,
306 - prerelease: true,
307 - assets: [
308 - {
309 - name: 'composio-darwin-aarch64.zip',
310 - browser_download_url: 'http://127.0.0.1/beta-3.zip',
311 - },
312 - ],
313 - },
314 - {
315 - tag_name: '@composio/cli@0.2.17',
316 - draft: false,
317 - prerelease: false,
318 - assets: [
319 - {
320 - name: 'composio-darwin-aarch64.zip',
321 - browser_download_url: 'http://127.0.0.1/stable.zip',
322 - },
323 - ],
324 - },
325 - ])
326 - );
327 - },
328 - async apiBaseUrl => {
329 - const error = await runUpgrade(
330 - [
331 - ['GITHUB_API_BASE_URL', apiBaseUrl],
332 - ['GITHUB_OWNER', 'test-owner'],
333 - ['GITHUB_REPO', 'test-repo'],
334 - ],
335 - { prerelease: true }
336 - );
337 -
338 - expect(error).toBeInstanceOf(UpgradeBinaryError);
339 - if (!(error instanceof UpgradeBinaryError)) {
340 - throw error;
341 - }
342 - expect(error.message).toBe('Failed to download binary: composio-darwin-aarch64.zip');
343 - expect(String(error.cause)).toContain('beta-3.zip');
344 - }
316 + return Effect.gen(function* () {
317 + const apiBaseUrl = yield* scopedHttpServer((_req, res) => {
318 + res.writeHead(200, { 'content-type': 'application/json' });
319 + res.end(
320 + JSON.stringify([
321 + {
322 + tag_name: '@composio/cli@0.2.19-beta.1',
323 + draft: false,
324 + prerelease: true,
325 + assets: [
326 + {
327 + name: 'composio-darwin-aarch64.zip',
328 + browser_download_url: 'http://127.0.0.1/beta-1.zip',
329 + },
330 + ],
331 + },
332 + {
333 + tag_name: '@composio/cli@0.2.19-beta.3',
334 + draft: false,
335 + prerelease: true,
336 + assets: [
337 + {
338 + name: 'composio-darwin-aarch64.zip',
339 + browser_download_url: 'http://127.0.0.1/beta-3.zip',
340 + },
341 + ],
342 + },
343 + {
344 + tag_name: '@composio/cli@0.2.17',
345 + draft: false,
346 + prerelease: false,
347 + assets: [
348 + {
349 + name: 'composio-darwin-aarch64.zip',
350 + browser_download_url: 'http://127.0.0.1/stable.zip',
351 + },
352 + ],
353 + },
354 + ])
355 + );
356 + });
357 +
358 + const error = yield* runUpgrade(
359 + [
360 + ['GITHUB_API_BASE_URL', apiBaseUrl],
361 + ['GITHUB_OWNER', 'test-owner'],
362 + ['GITHUB_REPO', 'test-repo'],
363 + ],
364 + { prerelease: true }
365 );
346 - } finally {
347 - execPathSpy.mockRestore();
348 - vi.unstubAllGlobals();
349 - vi.restoreAllMocks();
350 - }
366 +
367 + expect(error).toBeInstanceOf(UpgradeBinaryError);
368 + if (!(error instanceof UpgradeBinaryError)) {
369 + throw error;
370 + }
371 + expect(error.message).toBe('Failed to download binary: composio-darwin-aarch64.zip');
372 + expect(String(error.cause)).toContain('beta-3.zip');
373 + }).pipe(
374 + Effect.ensuring(Effect.sync(() => execPathSpy.mockRestore())),
375 + Effect.ensuring(restoreStubsAndMocks)
376 + );
377 });
378
353 - it('copies local-tool bundled binary assets during local-target upgrades', async () => {
379 + it.effect('copies local-tool bundled binary assets during local-target upgrades', () => {
380 const installDir = mkdtempSync(path.join(tmpdir(), 'composio-local-tool-upgrade-target-'));
381 const sourceDir = mkdtempSync(path.join(tmpdir(), 'composio-local-tool-upgrade-source-'));
382 const fakeExecPath = path.join(installDir, 'composio');
@@ -375,78 +401,78 @@ describe('UpgradeBinary', () => {
401 mkdirSync(path.dirname(sourceLocalToolPath), { recursive: true });
402 writeFileSync(sourceLocalToolPath, 'imessage-sidecar');
403
378 - for (const relativePath of collectExpectedRunCompanionAssetRelativePaths(sourceDir)) {
379 - const companionPath = path.join(sourceDir, relativePath);
380 - mkdirSync(path.dirname(companionPath), { recursive: true });
381 - writeFileSync(companionPath, 'support-file');
382 - }
383 -
404 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
405 const execPathSpy = vi.spyOn(process, 'execPath', 'get').mockReturnValue(fakeExecPath);
406
387 - try {
388 - const result = await runUpgradeSuccess([['DEBUG_OVERRIDE_UPGRADE_TARGET', sourceBinaryPath]]);
407 + return Effect.gen(function* () {
408 + const companionRelativePaths = yield* collectExpectedRunCompanionAssetRelativePaths(
409 + sourceDir
410 + ).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, Path.layer)));
411 + for (const relativePath of companionRelativePaths) {
412 + const companionPath = path.join(sourceDir, relativePath);
413 + mkdirSync(path.dirname(companionPath), { recursive: true });
414 + writeFileSync(companionPath, 'support-file');
415 + }
416 +
417 + const result = yield* runUpgradeSuccess([
418 + ['DEBUG_OVERRIDE_UPGRADE_TARGET', sourceBinaryPath],
419 + ]);
420
421 expect(result).toBeUndefined();
422 expect(readFileSync(fakeExecPath, 'utf8')).toBe('new-binary');
423 expect(existsSync(installedLocalToolPath)).toBe(true);
424 expect(readFileSync(installedLocalToolPath, 'utf8')).toBe('imessage-sidecar');
394 - } finally {
395 - execPathSpy.mockRestore();
396 - vi.unstubAllGlobals();
397 - vi.restoreAllMocks();
398 - }
425 + }).pipe(
426 + Effect.ensuring(Effect.sync(() => execPathSpy.mockRestore())),
427 + Effect.ensuring(restoreStubsAndMocks)
428 + );
429 });
430
401 - it('uses the installed beta release tag when comparing beta updates', async () => {
431 + it.scoped('uses the installed beta release tag when comparing beta updates', () => {
432 const installDir = mkdtempSync(path.join(tmpdir(), 'composio-beta-upgrade-'));
433 const fakeExecPath = path.join(installDir, 'composio');
434 writeFileSync(path.join(installDir, 'release-tag.txt'), '@composio/cli@0.2.17-beta.1\n');
435 vi.stubGlobal('Bun', { which: vi.fn(() => null) });
436 const execPathSpy = vi.spyOn(process, 'execPath', 'get').mockReturnValue(fakeExecPath);
437
408 - try {
409 - await withHttpServer(
410 - (_req, res) => {
411 - res.writeHead(200, { 'content-type': 'application/json' });
412 - res.end(
413 - JSON.stringify([
414 - {
415 - tag_name: '@composio/cli@0.2.17-beta.3',
416 - draft: false,
417 - prerelease: true,
418 - assets: [
419 - {
420 - name: 'composio-darwin-aarch64.zip',
421 - browser_download_url: 'http://127.0.0.1/beta-3.zip',
422 - },
423 - ],
424 - },
425 - ])
426 - );
427 - },
428 - async apiBaseUrl => {
429 - const error = await runUpgrade(
430 - [
431 - ['GITHUB_API_BASE_URL', apiBaseUrl],
432 - ['GITHUB_OWNER', 'test-owner'],
433 - ['GITHUB_REPO', 'test-repo'],
434 - ],
435 - { prerelease: true }
436 - );
437 -
438 - expect(error).toBeInstanceOf(UpgradeBinaryError);
439 - if (!(error instanceof UpgradeBinaryError)) {
440 - throw error;
441 - }
442 - expect(error.message).toBe('Failed to download binary: composio-darwin-aarch64.zip');
443 - expect(String(error.cause)).toContain('beta-3.zip');
444 - }
438 + return Effect.gen(function* () {
439 + const apiBaseUrl = yield* scopedHttpServer((_req, res) => {
440 + res.writeHead(200, { 'content-type': 'application/json' });
441 + res.end(
442 + JSON.stringify([
443 + {
444 + tag_name: '@composio/cli@0.2.17-beta.3',
445 + draft: false,
446 + prerelease: true,
447 + assets: [
448 + {
449 + name: 'composio-darwin-aarch64.zip',
450 + browser_download_url: 'http://127.0.0.1/beta-3.zip',
451 + },
452 + ],
453 + },
454 + ])
455 + );
456 + });
457 +
458 + const error = yield* runUpgrade(
459 + [
460 + ['GITHUB_API_BASE_URL', apiBaseUrl],
461 + ['GITHUB_OWNER', 'test-owner'],
462 + ['GITHUB_REPO', 'test-repo'],
463 + ],
464 + { prerelease: true }
465 );
446 - } finally {
447 - execPathSpy.mockRestore();
448 - vi.unstubAllGlobals();
449 - vi.restoreAllMocks();
450 - }
466 +
467 + expect(error).toBeInstanceOf(UpgradeBinaryError);
468 + if (!(error instanceof UpgradeBinaryError)) {
469 + throw error;
470 + }
471 + expect(error.message).toBe('Failed to download binary: composio-darwin-aarch64.zip');
472 + expect(String(error.cause)).toContain('beta-3.zip');
473 + }).pipe(
474 + Effect.ensuring(Effect.sync(() => execPathSpy.mockRestore())),
475 + Effect.ensuring(restoreStubsAndMocks)
476 + );
477 });
478 });
ts/packages/cli/test/src/services/user-context.test.ts
+10 -10
@@ -1,7 +1,7 @@
1 import { describe, it } from '@effect/vitest';
2 import { assertEquals } from '@effect/vitest/utils';
3 import { FileSystem } from '@effect/platform';
4 -import { BunFileSystem } from '@effect/platform-bun';
4 +import { BunFileSystem, BunPath } from '@effect/platform-bun';
5 import { ConfigProvider, Effect, Layer, Option, Data } from 'effect';
6 import * as tempy from 'tempy';
7 import { ComposioUserContext, rawComposioUserContextLive } from 'src/services/user-context';
@@ -86,7 +86,7 @@ describe('ComposioUserContext', () => {
86 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
87 const ComposioUserContextTest = Layer.provideMerge(
88 ComposioUserContextLive,
89 - Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
89 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
90 );
91
92 return Effect.gen(function* () {
@@ -117,7 +117,7 @@ describe('ComposioUserContext', () => {
117 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
118 const ComposioUserContextTest = Layer.provideMerge(
119 ComposioUserContextLive,
120 - Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
120 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
121 );
122
123 return Effect.gen(function* () {
@@ -143,7 +143,7 @@ describe('ComposioUserContext', () => {
143 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
144 const ComposioUserContextTest = Layer.provideMerge(
145 ComposioUserContextLive,
146 - Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
146 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
147 );
148
149 return Effect.gen(function* () {
@@ -165,7 +165,7 @@ describe('ComposioUserContext', () => {
165 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
166 const ComposioUserContextTest = Layer.provideMerge(
167 ComposioUserContextLive,
168 - Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
168 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
169 );
170
171 return Effect.gen(function* () {
@@ -205,7 +205,7 @@ describe('ComposioUserContext', () => {
205 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
206 const ComposioUserContextTest = Layer.provideMerge(
207 ComposioUserContextLive,
208 - Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
208 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
209 );
210
211 return Effect.gen(function* () {
@@ -246,7 +246,7 @@ describe('ComposioUserContext', () => {
246 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
247 const ComposioUserContextTest = Layer.provideMerge(
248 ComposioUserContextLive,
249 - Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
249 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
250 );
251
252 return Effect.gen(function* () {
@@ -288,7 +288,7 @@ describe('ComposioUserContext', () => {
288 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
289 const ComposioUserContextTest = Layer.provideMerge(
290 ComposioUserContextLive,
291 - Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
291 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
292 );
293
294 return Effect.gen(function* () {
@@ -325,7 +325,7 @@ describe('ComposioUserContext', () => {
325 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
326 const ComposioUserContextTest = Layer.provideMerge(
327 ComposioUserContextLive,
328 - Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
328 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
329 );
330
331 return Effect.gen(function* () {
@@ -365,7 +365,7 @@ describe('ComposioUserContext', () => {
365 const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
366 const ComposioUserContextTest = Layer.provideMerge(
367 ComposioUserContextLive,
368 - Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
368 + Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
369 );
370
371 return Effect.gen(function* () {