Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

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

Alberto Schiabel4e26d36fd4b8
diff --git a/eslint.config.mjs b/eslint.config.mjs
index b8f61a6ae..693c6d42d 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -53,14 +53,26 @@ const cliRestrictedImportPaths = [
name: 'node:child_process',
message: 'Use Command from @effect/platform instead.',
},
+ {
+ name: 'fs',
+ message: 'Use FileSystem from @effect/platform instead.',
+ },
{
name: 'node:fs',
message: 'Use FileSystem from @effect/platform instead.',
},
+ {
+ name: 'os',
+ message: 'Use an Effect service instead of importing node:os directly.',
+ },
{
name: 'node:os',
message: 'Use an Effect service instead of importing node:os directly.',
},
+ {
+ name: 'path',
+ message: 'Use Path from @effect/platform instead.',
+ },
{
name: 'node:path',
message: 'Use Path from @effect/platform instead.',
@@ -69,7 +81,7 @@ const cliRestrictedImportPaths = [
const cliRestrictedImportPatterns = [
{
- group: ['node:fs/*'],
+ group: ['fs/*', 'node:fs/*'],
message: 'Use FileSystem from @effect/platform instead.',
},
];
@@ -174,15 +186,21 @@ export default [
{
files: ['ts/packages/cli/src/**/*.{ts,tsx}'],
rules: {
- // uncommented by the platform-imports PR of this stack (the
- // CommandDescriptor/Usage seam entries by the seam-rules PR).
- // 'no-restricted-imports': [
- // 'error',
- // {
- // paths: [...cliRestrictedImportPaths, ...cliDescriptorSeamRestrictedImportPaths],
- // patterns: [...cliRestrictedImportPatterns, ...cliDescriptorSeamRestrictedImportPatterns],
- // },
- // ],
+ 'no-restricted-imports': [
+ 'error',
+ {
+ paths: [
+ ...cliRestrictedImportPaths,
+ // uncommented by the seam-rules PR of this stack
+ // ...cliDescriptorSeamRestrictedImportPaths,
+ ],
+ patterns: [
+ ...cliRestrictedImportPatterns,
+ // uncommented by the seam-rules PR of this stack
+ // ...cliDescriptorSeamRestrictedImportPatterns,
+ ],
+ },
+ ],
// uncommented by the terminal-streams PR of this stack (the try/catch and
// process.env entries by the boundary-ratchet PR).
// 'no-restricted-syntax': ['error', ...cliRestrictedSyntax, ...cliProcessStreamRestrictions],
diff --git a/ts/packages/cli/scripts/install-binary.ts b/ts/packages/cli/scripts/install-binary.ts
index 05b3f4999..7fd887063 100644
--- a/ts/packages/cli/scripts/install-binary.ts
+++ b/ts/packages/cli/scripts/install-binary.ts
@@ -30,7 +30,8 @@ export function installBinary() {
yield* Effect.tryPromise(() => $`cp ${binaryPath} ${installDir}/composio`.quiet());
const sourceDirectory = path.dirname(path.resolve(binaryPath));
- const companionRelativePaths = collectExpectedRunCompanionAssetRelativePaths(sourceDirectory);
+ const companionRelativePaths =
+ yield* collectExpectedRunCompanionAssetRelativePaths(sourceDirectory);
for (const relativePath of companionRelativePaths) {
const sourcePath = path.join(sourceDirectory, relativePath);
diff --git a/ts/packages/cli/scripts/package-binaries.ts b/ts/packages/cli/scripts/package-binaries.ts
index 4fdd8ba23..3261d7559 100644
--- a/ts/packages/cli/scripts/package-binaries.ts
+++ b/ts/packages/cli/scripts/package-binaries.ts
@@ -50,7 +50,8 @@ export function packageBinaries() {
return;
}
- const companionRelativePaths = collectExpectedRunCompanionAssetRelativePaths(COMPANIONS_DIR);
+ const companionRelativePaths =
+ yield* collectExpectedRunCompanionAssetRelativePaths(COMPANIONS_DIR);
for (const relativePath of companionRelativePaths) {
const companionPath = path.join(COMPANIONS_DIR, relativePath);
const exists = yield* Effect.tryPromise(() => Bun.file(companionPath).exists());
diff --git a/ts/packages/cli/src/analytics/dispatch.ts b/ts/packages/cli/src/analytics/dispatch.ts
index 057c01446..f6013067a 100644
--- a/ts/packages/cli/src/analytics/dispatch.ts
+++ b/ts/packages/cli/src/analytics/dispatch.ts
@@ -1,7 +1,11 @@
+// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
import fs from 'node:fs';
+// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
import os from 'node:os';
+// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
import path from 'node:path';
import process from 'node:process';
+// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
import { spawn } from 'node:child_process';
import { Effect } from 'effect';
import type { AnalyticsEnvelope, TrackEvent } from './types';
diff --git a/ts/packages/cli/src/cli-main.ts b/ts/packages/cli/src/cli-main.ts
index c814e48f9..f6530783e 100644
--- a/ts/packages/cli/src/cli-main.ts
+++ b/ts/packages/cli/src/cli-main.ts
@@ -49,22 +49,22 @@ export const CliConfigLive = CliConfig.layer(ComposioCliConfig) satisfies Requir
export const ComposioUserContextLive = Layer.provide(
_ComposioUserContextLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
) satisfies RequiredLayer;
export const ComposioCliUserConfigLayer = Layer.provide(
ComposioCliUserConfigLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
);
export const ComposioSessionRepositoryLive = Layer.provide(
ComposioSessionRepository.Default,
- Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
) satisfies RequiredLayer;
export const ComposioToolkitsRepositoryLive = Layer.provide(
ComposioToolkitsRepository.Default,
- Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, ConfigLive)
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, ConfigLive)
) satisfies RequiredLayer;
export const ComposioToolkitsRepositoryCachedLive = Layer.provide(
@@ -74,17 +74,17 @@ export const ComposioToolkitsRepositoryCachedLive = Layer.provide(
export const UpgradeBinaryLive = Layer.provide(
UpgradeBinary.Default,
- Layer.mergeAll(BunFileSystem.layer, FetchHttpClient.layer)
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, FetchHttpClient.layer)
) satisfies RequiredLayer;
export const TriggersRealtimeLive = Layer.provide(
TriggersRealtime.Default,
- Layer.mergeAll(BunFileSystem.layer, NodeOs.Default)
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default)
) satisfies RequiredLayer;
export const ComposioClientSingletonLive = Layer.provide(
ComposioClientSingleton.Default,
- Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, ConfigLive)
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, ConfigLive)
) satisfies RequiredLayer;
export const ToolsExecutorLive = Layer.provide(
@@ -94,7 +94,7 @@ export const ToolsExecutorLive = Layer.provide(
export const ProjectContextLive = Layer.provide(
ProjectContext.Default,
- Layer.mergeAll(BunFileSystem.layer, NodeOs.Default, NodeProcess.Default)
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOs.Default, NodeProcess.Default)
) satisfies RequiredLayer;
export const SetupSkillInstallerLive = Layer.provide(
@@ -121,6 +121,7 @@ const layers = Layer.mergeAll(
ProjectContextLive,
BunContext.layer,
BunFileSystem.layer,
+ BunPath.layer,
FetchHttpClient.layer,
StdinLive,
TerminalUILive,
diff --git a/ts/packages/cli/src/commands/artifacts.cmd.ts b/ts/packages/cli/src/commands/artifacts.cmd.ts
index 575df594e..0b47114e5 100644
--- a/ts/packages/cli/src/commands/artifacts.cmd.ts
+++ b/ts/packages/cli/src/commands/artifacts.cmd.ts
@@ -11,10 +11,9 @@ const cwdCmd = Command.make('cwd').pipe(
Command.withHandler(() =>
Effect.gen(function* () {
const artifacts = yield* resolveCliSessionArtifacts();
- const directoryPath = Option.match(artifacts, {
- onNone: () => resolveArtifactsRoot(),
- onSome: value => value.directoryPath,
- });
+ const directoryPath = Option.isSome(artifacts)
+ ? artifacts.value.directoryPath
+ : yield* resolveArtifactsRoot;
process.stdout.write(`${directoryPath}\n`);
})
)
diff --git a/ts/packages/cli/src/commands/config/config.experimental.cmd.ts b/ts/packages/cli/src/commands/config/config.experimental.cmd.ts
index 5998ac8d8..fba477c44 100644
--- a/ts/packages/cli/src/commands/config/config.experimental.cmd.ts
+++ b/ts/packages/cli/src/commands/config/config.experimental.cmd.ts
@@ -1,15 +1,14 @@
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import { Command, Args } from '@effect/cli';
+import { Args, Command, HelpDoc, ValidationError } from '@effect/cli';
import { Effect, Option } from 'effect';
import { ComposioCliUserConfig } from 'src/services/cli-user-config';
import { TerminalUI } from 'src/services/terminal-ui';
import { NodeOs } from 'src/services/node-os';
import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
+import { discoverSkillRoots } from 'src/effects/discover-skill-roots';
import { buildComposioCliSkill } from '../../../skills-src/composio-cli/index';
import type { SkillFeatureFlag } from '../../../skills-src/composio-cli/reference-schema';
-const knownFeatures: readonly string[] = Object.values(CLI_EXPERIMENTAL_FEATURES);
+const knownFeatures: ReadonlyArray<SkillFeatureFlag> = Object.values(CLI_EXPERIMENTAL_FEATURES);
const featureArg = Args.text({ name: 'feature' }).pipe(
Args.withDescription(`Experimental feature name. Known features: ${knownFeatures.join(', ')}`),
@@ -21,55 +20,6 @@ const stateArg = Args.text({ name: 'state' }).pipe(
Args.optional
);
-const SKILL_NAME = 'composio-cli';
-
-/**
- * Find every directory where the composio-cli skill is currently installed.
- * Known locations:
- * ~/.agents/skills/composio-cli (canonical install target)
- * ~/.claude/skills/composio-cli (Claude Code — may be a symlink or a real dir)
- *
- * We resolve symlinks so we don't rebuild the same physical directory twice,
- * but we also rebuild any real (non-symlink) copies so everything stays in sync.
- */
-const discoverSkillRoots = (home: string): string[] => {
- const candidates = [path.join(home, '.agents', 'skills'), path.join(home, '.claude', 'skills')];
-
- const seen = new Set<string>();
- const roots: string[] = [];
-
- for (const parent of candidates) {
- const skillDir = path.join(parent, SKILL_NAME);
- try {
- const stat = fs.lstatSync(skillDir);
- if (stat.isSymbolicLink()) {
- // Resolve the symlink target — we'll rebuild the real directory it points to
- const realDir = fs.realpathSync(skillDir);
- const realParent = path.dirname(realDir);
- if (!seen.has(realParent)) {
- seen.add(realParent);
- roots.push(realParent);
- }
- } else if (stat.isDirectory()) {
- if (!seen.has(parent)) {
- seen.add(parent);
- roots.push(parent);
- }
- }
- } catch {
- // Directory doesn't exist — skip
- }
- }
-
- // Always include ~/.agents/skills as a fallback so there's at least one target
- const agentSkillsRoot = path.join(home, '.agents', 'skills');
- if (!seen.has(agentSkillsRoot)) {
- roots.push(agentSkillsRoot);
- }
-
- return roots;
-};
-
const rebuildSkill = Effect.gen(function* () {
const ui = yield* TerminalUI;
const os = yield* NodeOs;
@@ -79,16 +29,18 @@ const rebuildSkill = Effect.gen(function* () {
// Build the feature overrides from the current config
const featureOverrides: Partial<Record<SkillFeatureFlag, boolean>> = {};
for (const name of knownFeatures) {
- featureOverrides[name as SkillFeatureFlag] = cliConfig.isExperimentalFeatureEnabled(name);
+ featureOverrides[name] = cliConfig.isExperimentalFeatureEnabled(name);
}
- const roots = discoverSkillRoots(home);
+ const roots = yield* discoverSkillRoots(home);
for (const root of roots) {
- buildComposioCliSkill({
- channel: cliConfig.channel,
- outputRoot: root,
- featureOverrides,
- });
+ yield* Effect.try(() =>
+ buildComposioCliSkill({
+ channel: cliConfig.channel,
+ outputRoot: root,
+ featureOverrides,
+ })
+ );
}
yield* ui.log.step(
@@ -119,7 +71,7 @@ export const configExperimentalCmd = Command.make(
// Show any custom features not in the known list
for (const [name, value] of Object.entries(features)) {
- if (!knownFeatures.includes(name)) {
+ if (!knownFeatures.some(feature => feature === name)) {
lines.push(` ${name}: ${value ? 'on' : 'off'}`);
}
}
@@ -146,7 +98,9 @@ export const configExperimentalCmd = Command.make(
const stateValue = state.value.toLowerCase();
if (stateValue !== 'on' && stateValue !== 'off') {
yield* ui.log.error(`Invalid state "${state.value}". Use "on" or "off".`);
- return yield* Effect.fail(new Error(`Invalid state: ${state.value}`));
+ return yield* Effect.fail(
+ ValidationError.invalidValue(HelpDoc.p(`Invalid state: ${state.value}`))
+ );
}
const enabled = stateValue === 'on';
@@ -161,12 +115,13 @@ export const configExperimentalCmd = Command.make(
// Rebuild the skill so Claude Code picks up the new feature flags
yield* rebuildSkill.pipe(
- Effect.catchAll(error =>
- Effect.gen(function* () {
- yield* Effect.logDebug('Skill rebuild failed:', error);
- yield* ui.log.warn('Could not rebuild skill (non-fatal)');
- })
- )
+ Effect.tapError(error =>
+ Effect.all([
+ Effect.logDebug('Skill rebuild failed:', error),
+ ui.log.warn('Could not rebuild skill (non-fatal)'),
+ ])
+ ),
+ Effect.ignore
);
yield* ui.output(stateValue);
diff --git a/ts/packages/cli/src/commands/dev/dev.native-ui.cmd.ts b/ts/packages/cli/src/commands/dev/dev.native-ui.cmd.ts
index 84d814833..1039a122d 100644
--- a/ts/packages/cli/src/commands/dev/dev.native-ui.cmd.ts
+++ b/ts/packages/cli/src/commands/dev/dev.native-ui.cmd.ts
@@ -1,10 +1,15 @@
import { Command, Options } from '@effect/cli';
-import { Effect, Option } from 'effect';
-import { spawn } from 'node:child_process';
+import { Data, Effect, Option, Predicate } from 'effect';
import { ensureBundledBinaryExecutable } from '@composio/cli-local-tools';
+import { spawnDetached } from 'src/services/detached-process';
import { TerminalUI } from 'src/services/terminal-ui';
import { resolveNativeUiBinary } from 'src/services/native-ui-sidecar';
+class NativeUiSetupError extends Data.TaggedError('commands/NativeUiSetupError')<{
+ readonly message: string;
+ readonly cause: unknown;
+}> {}
+
const title = Options.text('title').pipe(
Options.withDefault('Composio'),
Options.withDescription('Title for the native sidecar window.')
@@ -29,16 +34,16 @@ export const devNativeUiCmd = Command.make('native-ui', { title, message, detail
Command.withHandler(({ title, message, detail, timeout }) =>
Effect.gen(function* () {
const ui = yield* TerminalUI;
- const resolved = resolveNativeUiBinary();
+ const resolved = yield* resolveNativeUiBinary;
- if (resolved._tag === 'unsupported') {
+ if (Predicate.isTagged(resolved, 'unsupported')) {
yield* ui.log.error(
`The native UI sidecar is currently only available on macOS (detected ${resolved.platform}).`
);
return;
}
- if (resolved._tag === 'missing') {
+ if (Predicate.isTagged(resolved, 'missing')) {
yield* ui.log.error('The native UI sidecar binary was not found.');
yield* ui.log.step(
`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
return;
}
- yield* Effect.tryPromise(() => ensureBundledBinaryExecutable(resolved.binaryPath));
+ yield* Effect.tryPromise({
+ try: () => ensureBundledBinaryExecutable(resolved.binaryPath),
+ catch: cause =>
+ new NativeUiSetupError({
+ message: `Failed to make the native UI sidecar binary executable: ${resolved.binaryPath}`,
+ cause,
+ }),
+ });
const args = ['--title', title, '--message', message, '--detail', detail];
const timeoutValue = Option.getOrUndefined(timeout)?.trim();
@@ -55,13 +67,10 @@ export const devNativeUiCmd = Command.make('native-ui', { title, message, detail
args.push('--timeout', timeoutValue);
}
- yield* Effect.sync(() => {
- const child = spawn(resolved.binaryPath, args, {
- detached: true,
- stdio: 'ignore',
- });
- child.unref();
- });
+ // The sidecar window must outlive the CLI process, so it goes through
+ // the sanctioned detached-spawn boundary instead of @effect/platform
+ // Command (whose processes are killed when their scope closes).
+ yield* spawnDetached(resolved.binaryPath, args);
yield* ui.log.success('Opened native UI sidecar.');
})
diff --git a/ts/packages/cli/src/commands/init.cmd.ts b/ts/packages/cli/src/commands/init.cmd.ts
index 486dd2480..75166bb82 100644
--- a/ts/packages/cli/src/commands/init.cmd.ts
+++ b/ts/packages/cli/src/commands/init.cmd.ts
@@ -1,7 +1,6 @@
-import path from 'node:path';
import { Command as CliCommand, Options } from '@effect/cli';
import { Effect, Option } from 'effect';
-import { FileSystem } from '@effect/platform';
+import { FileSystem, Path } from '@effect/platform';
import { ComposioUserContext } from 'src/services/user-context';
import { NodeProcess } from 'src/services/node-process';
import { projectKeysToJSON, type ProjectKeys } from 'src/models/project-keys';
@@ -43,6 +42,7 @@ const yesOpt = Options.boolean('yes').pipe(
const writeProjectConfig = (composioDir: string, selected: ProjectKeys) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
yield* fs
.makeDirectory(composioDir, { recursive: true })
@@ -76,6 +76,7 @@ const makeOutputJson = (selected: ProjectKeys, composioDir: string) =>
const getGlobalUserApiKey = () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const cacheDir = yield* setupCacheDir;
const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
const exists = yield* fs.exists(userConfigPath);
@@ -103,6 +104,7 @@ const ensureProjectApiKeyInEnv = (params: { cwd: string; selected: ProjectKeys }
const { cwd, selected } = params;
const ui = yield* TerminalUI;
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const ctx = yield* ComposioUserContext;
const envPath = path.join(cwd, '.env.local');
@@ -229,6 +231,7 @@ export const initCmd = CliCommand.make(
Effect.gen(function* () {
const ui = yield* TerminalUI;
const proc = yield* NodeProcess;
+ const path = yield* Path.Path;
yield* ui.intro('composio dev init');
diff --git a/ts/packages/cli/src/commands/install.cmd.ts b/ts/packages/cli/src/commands/install.cmd.ts
index 76fc6c024..29f97e085 100644
--- a/ts/packages/cli/src/commands/install.cmd.ts
+++ b/ts/packages/cli/src/commands/install.cmd.ts
@@ -1,7 +1,6 @@
-import path from 'node:path';
import process from 'node:process';
import { Command, Options } from '@effect/cli';
-import { FileSystem } from '@effect/platform';
+import { FileSystem, Path } from '@effect/platform';
import type { PlatformError } from '@effect/platform/Error';
import { Array as Arr, Effect } from 'effect';
import { ComposioCliUserConfig } from 'src/services/cli-user-config';
@@ -48,7 +47,7 @@ const COMPLETIONS_MARKER = '# Composio CLI completions';
const UNSAFE_PATH_CHARS = /[;`$|&"'()\n\r\\]/;
const isUnsafePath = (p: string): boolean => UNSAFE_PATH_CHARS.test(p);
-const detectShell = (): Shell | undefined => {
+const detectShell = (path: Path.Path): Shell | undefined => {
const shellEnv = process.env.SHELL ?? '';
const base = path.basename(shellEnv);
if (base === 'zsh') return 'zsh';
@@ -61,7 +60,7 @@ const detectShell = (): Shell | undefined => {
* Return candidate rc file paths for a shell, ordered by preference.
* For bash this mirrors the install.sh fallback: .bashrc then .bash_profile.
*/
-const rcFileCandidates = (shell: Shell, homedir: string): string[] => {
+const rcFileCandidates = (path: Path.Path, shell: Shell, homedir: string): string[] => {
switch (shell) {
case 'zsh':
return [path.join(homedir, '.zshrc')];
@@ -106,6 +105,7 @@ const pathBlockForShell = (shell: Shell, installDir: string): string => {
};
const buildShellConfig = (
+ path: Path.Path,
shell: Shell,
rcFile: string,
installDir: string,
@@ -150,12 +150,13 @@ export const installShellIntegration = (params: {
}): Effect.Effect<
void,
PlatformError,
- TerminalUI | NodeOs | FileSystem.FileSystem | ComposioCliUserConfig
+ TerminalUI | NodeOs | FileSystem.FileSystem | Path.Path | ComposioCliUserConfig
> =>
Effect.gen(function* () {
const ui = yield* TerminalUI;
const os = yield* NodeOs;
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
yield* ui.intro('composio install');
@@ -171,7 +172,7 @@ export const installShellIntegration = (params: {
}
// Detect user shell
- const shell = detectShell();
+ const shell = detectShell(path);
if (!shell) {
yield* ui.log.warn(
'Could not detect your shell. Manually add the following to your shell config:'
@@ -204,8 +205,8 @@ export const installShellIntegration = (params: {
completionScript = lines.length > 0 ? Arr.join(lines, '\n') : undefined;
}
- const rcFile = yield* resolveRcFile(rcFileCandidates(shell, os.homedir), fs);
- const config = buildShellConfig(shell, rcFile, installDir, completionScript, os.homedir);
+ const rcFile = yield* resolveRcFile(rcFileCandidates(path, shell, os.homedir), fs);
+ const config = buildShellConfig(path, shell, rcFile, installDir, completionScript, os.homedir);
const uniqueTargetFiles = [...new Set([config.pathFile, config.completionFile])];
const existingByFile = new Map<string, string>();
diff --git a/ts/packages/cli/src/commands/listen.cmd.ts b/ts/packages/cli/src/commands/listen.cmd.ts
index cbc6e7eea..64fcce272 100644
--- a/ts/packages/cli/src/commands/listen.cmd.ts
+++ b/ts/packages/cli/src/commands/listen.cmd.ts
@@ -1,8 +1,7 @@
import { Args, Command, Options } from '@effect/cli';
-import { FileSystem } from '@effect/platform';
+import { FileSystem, Path } from '@effect/platform';
import type { Composio as RawComposioClient } from '@composio/client';
import { Deferred, Effect, Either, Option, Runtime } from 'effect';
-import path from 'node:path';
import { requireAuth } from 'src/effects/require-auth';
import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -181,8 +180,6 @@ const extractEventFileId = (eventData: Record<string, unknown>): string => {
return `${Date.now()}-${crypto.randomUUID().slice(0, 8)}`;
};
-const resolveFallbackArtifactsDir = () => resolveArtifactsRoot();
-
const parseStreamPath = (expression: string): ReadonlyArray<string | number> => {
const trimmed = expression.trim();
if (!trimmed.startsWith('.')) {
@@ -379,6 +376,7 @@ export const listenCmd = Command.make(
const ui = yield* TerminalUI;
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const runtime = yield* Effect.runtime<never>();
const clientSingleton = yield* ComposioClientSingleton;
const realtime = yield* TriggersRealtime;
@@ -420,10 +418,9 @@ export const listenCmd = Command.make(
orgId: resolvedProject.orgId,
consumerUserId,
});
- const artifactsRoot = Option.match(artifactsOption, {
- onNone: () => resolveFallbackArtifactsDir(),
- onSome: value => value.directoryPath,
- });
+ const artifactsRoot = Option.isSome(artifactsOption)
+ ? artifactsOption.value.directoryPath
+ : yield* resolveArtifactsRoot;
const triggerDir = path.join(
artifactsRoot,
listeningToProjectEvent ? 'events' : 'triggers',
diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.ts
index d68f0651c..701082374 100644
--- a/ts/packages/cli/src/commands/login.cmd.ts
+++ b/ts/packages/cli/src/commands/login.cmd.ts
@@ -1,3 +1,4 @@
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import path from 'node:path';
import { Command, Options } from '@effect/cli';
import { FileSystem } from '@effect/platform';
diff --git a/ts/packages/cli/src/commands/py/commands/py.generate.cmd.ts b/ts/packages/cli/src/commands/py/commands/py.generate.cmd.ts
index 7c813937c..1692020ab 100644
--- a/ts/packages/cli/src/commands/py/commands/py.generate.cmd.ts
+++ b/ts/packages/cli/src/commands/py/commands/py.generate.cmd.ts
@@ -1,3 +1,4 @@
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import path from 'node:path';
import { Command, Options } from '@effect/cli';
import { pipe, Effect, Option, Array } from 'effect';
diff --git a/ts/packages/cli/src/commands/run.cmd.ts b/ts/packages/cli/src/commands/run.cmd.ts
index a290baaac..d2f493c36 100644
--- a/ts/packages/cli/src/commands/run.cmd.ts
+++ b/ts/packages/cli/src/commands/run.cmd.ts
@@ -1,9 +1,11 @@
+// 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
import * as fs from 'node:fs';
+// eslint-disable-next-line no-restricted-imports -- os.tmpdir and os.homedir locate the preload scratch directory and ~/.composio in the same synchronous helpers
import * as os from 'node:os';
-import * as path from 'node:path';
import process from 'node:process';
import { pathToFileURL } from 'node:url';
import { Args, Command, Options } from '@effect/cli';
+import { FileSystem, Path } from '@effect/platform';
import { Effect, Option } from 'effect';
import { ts } from 'ts-morph';
import { APP_VERSION } from 'src/constants';
@@ -147,6 +149,7 @@ export const wrapFileSourceForRun = (source: string): string => {
};
export const inferCliInvocationPrefix = (
+ path: Path.Path,
argv: ReadonlyArray<string> = process.argv
): ReadonlyArray<string> => {
const entrypoint = argv[1];
@@ -171,19 +174,22 @@ type RunHelperModuleUrls = {
readonly helpersRuntimeModuleUrl: string;
};
-const resolveRunHelperModuleUrls = (): RunHelperModuleUrls => ({
- helpersRuntimeModuleUrl: pathToFileURL(
- resolveRunCompanionModulePath({
- callerImportMetaUrl: import.meta.url,
- execPath: process.execPath,
- relativeNoExtensionFromCaller: '../services/run-helpers-runtime',
- })
- ).href,
-});
+const resolveRunHelperModuleUrls: Effect.Effect<
+ RunHelperModuleUrls,
+ never,
+ FileSystem.FileSystem | Path.Path
+> = Effect.map(
+ resolveRunCompanionModulePath({
+ callerImportMetaUrl: import.meta.url,
+ execPath: process.execPath,
+ relativeNoExtensionFromCaller: '../services/run-helpers-runtime',
+ }),
+ modulePath => ({ helpersRuntimeModuleUrl: pathToFileURL(modulePath).href })
+);
export const buildRunHelpersSource = (
cliPrefix: ReadonlyArray<string>,
context: RunHelperContext = {},
- moduleUrls: RunHelperModuleUrls = resolveRunHelperModuleUrls()
+ moduleUrls: RunHelperModuleUrls
): string =>
[
`import { installRunHelpers } from ${JSON.stringify(moduleUrls.helpersRuntimeModuleUrl)};`,
@@ -192,6 +198,7 @@ export const buildRunHelpersSource = (
].join('\n');
const createRunHelpersPreloadFile = (
+ path: Path.Path,
cliPrefix: ReadonlyArray<string>,
context: RunHelperContext,
moduleUrls: RunHelperModuleUrls
@@ -231,11 +238,13 @@ const createRunHelpersPreloadFile = (
};
export const buildRunCommand = ({
+ path,
file,
args,
preloadPath,
preloadDirectory,
}: {
+ path: Path.Path;
file: Option.Option<string>;
args: ReadonlyArray<string>;
preloadPath: string;
@@ -285,6 +294,7 @@ export const buildRunCommand = ({
const resolveRunHelperContext = () =>
Effect.gen(function* () {
+ const path = yield* Path.Path;
const userContext = yield* ComposioUserContext;
const apiKey = Option.getOrUndefined(userContext.data.apiKey);
const orgId = Option.getOrUndefined(userContext.data.orgId);
@@ -417,6 +427,7 @@ export const runCmd = Command.make('run', {
args,
}) =>
Effect.gen(function* () {
+ const path = yield* Path.Path;
const runId = process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID();
const perfDebug = isPerfDebugEnabled();
const toolDebug = isToolDebugEnabled();
@@ -446,25 +457,17 @@ export const runCmd = Command.make('run', {
skipToolParamsCheck,
skipChecks,
};
- const runHelperModuleUrls = yield* Effect.tryPromise({
- try: async () => {
- await repairMissingInstalledRunCompanionModules({
- callerImportMetaUrl: import.meta.url,
- execPath: process.execPath,
- appVersion: APP_VERSION,
- });
-
- return resolveRunHelperModuleUrls();
- },
- catch: error =>
- new Error(
- error instanceof Error
- ? error.message
- : `Failed to prepare the modules required by 'composio run': ${String(error)}`
- ),
- });
+ const runHelperModuleUrls = yield* repairMissingInstalledRunCompanionModules({
+ callerImportMetaUrl: import.meta.url,
+ execPath: process.execPath,
+ appVersion: APP_VERSION,
+ }).pipe(
+ Effect.mapError(error => new Error(error.message)),
+ Effect.andThen(resolveRunHelperModuleUrls)
+ );
const preload = createRunHelpersPreloadFile(
- inferCliInvocationPrefix(),
+ path,
+ inferCliInvocationPrefix(path),
helperContext,
runHelperModuleUrls
);
@@ -483,6 +486,7 @@ export const runCmd = Command.make('run', {
}).pipe(Effect.catchAll(() => Effect.void));
process.stderr.write(`RUN_LOG_FILE=${preload.runLogFilePath}\n`);
const runCommand = buildRunCommand({
+ path,
file,
args,
preloadPath: preload.preloadPath,
diff --git a/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts b/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
index 48ff1fc50..27a4a3700 100644
--- a/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+++ b/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
@@ -1,7 +1,6 @@
import { Command, Options } from '@effect/cli';
-import { FileSystem } from '@effect/platform';
+import { FileSystem, Path } from '@effect/platform';
import { Deferred, Effect, Option, Runtime } from 'effect';
-import path from 'node:path';
import { requireAuth } from 'src/effects/require-auth';
import { TerminalUI } from 'src/services/terminal-ui';
import { TriggersRealtime } from 'src/services/triggers-realtime';
@@ -180,6 +179,7 @@ export const triggersCmd$Listen = Command.make(
Effect.mapError(formatResolveCommandProjectError)
);
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const realtime = yield* TriggersRealtime;
const runtime = yield* Effect.runtime<never>();
const forwardUrl = Option.getOrUndefined(forward);
diff --git a/ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts b/ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts
index 9c8058a9e..7f551af5e 100644
--- a/ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts
+++ b/ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts
@@ -15,6 +15,7 @@
* and stored along with the generated TypeScript files. CJS is not supported.
*/
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import path from 'node:path';
import { Command, Options } from '@effect/cli';
import { Effect, Option, pipe, Array } from 'effect';
@@ -96,8 +97,7 @@ type FetchResult = {
toolkits: ReadonlyArray<Toolkit>;
triggerTypes: ReadonlyArray<TriggerType>;
typeableTools:
- | { withTypes: true; tools: ReadonlyArray<Tool> }
- | { withTypes: false; tools: ToolsAsEnums };
+ { withTypes: true; tools: ReadonlyArray<Tool> } | { withTypes: false; tools: ToolsAsEnums };
/** Map of lowercase toolkit slug to version (only includes non-'latest' versions) */
versionMap: ToolkitVersionOverrides;
};
diff --git a/ts/packages/cli/src/effect-errors/capture-errors.ts b/ts/packages/cli/src/effect-errors/capture-errors.ts
index d62f8e29f..4a668c45a 100644
--- a/ts/packages/cli/src/effect-errors/capture-errors.ts
+++ b/ts/packages/cli/src/effect-errors/capture-errors.ts
@@ -1,5 +1,6 @@
import type { PlatformError } from '@effect/platform/Error';
import type { FileSystem } from '@effect/platform/FileSystem';
+import type { Path } from '@effect/platform/Path';
import { Effect } from 'effect';
import { type Cause, isInterruptedOnly } from 'effect/Cause';
@@ -36,7 +37,7 @@ export const captureErrors = <E>(
options: CaptureErrorsOptions = {
stripCwd: true,
}
-): Effect.Effect<CapturedErrors, PlatformError | JsonParsingError, FileSystem> =>
+): Effect.Effect<CapturedErrors, PlatformError | JsonParsingError, FileSystem | Path> =>
Effect.gen(function* () {
if (isInterruptedOnly(cause)) {
return {
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts b/ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts
index 67d28bb33..8cf392a86 100644
--- a/ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts
@@ -1,5 +1,6 @@
import type { PlatformError } from '@effect/platform/Error';
import type { FileSystem } from '@effect/platform/FileSystem';
+import type { Path } from '@effect/platform/Path';
import { Effect } from 'effect';
import type { JsonParsingError } from 'effect-errors/dependencies/fs';
@@ -18,7 +19,7 @@ export const getErrorRelatedSources = (
): Effect.Effect<
ErrorRelatedSources | RawErrorLocation | undefined,
PlatformError | JsonParsingError,
- FileSystem
+ FileSystem | Path
> =>
Effect.gen(function* () {
const location = getErrorLocationFrom(sourceFile);
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts
index b4d987f40..4172cf793 100644
--- a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts
@@ -1,7 +1,6 @@
-import path from 'node:path';
-
import type { PlatformError } from '@effect/platform/Error';
import { FileSystem } from '@effect/platform/FileSystem';
+import { Path } from '@effect/platform/Path';
import { Effect, pipe } from 'effect';
import { type RawSourceMap, SourceMapConsumer } from 'source-map-js';
@@ -29,11 +28,12 @@ export const getSourcesFromMapFile = (
): Effect.Effect<
ErrorRelatedSources | RawErrorLocation | undefined,
PlatformError | JsonParsingError,
- FileSystem
+ FileSystem | Path
> =>
pipe(
Effect.gen(function* () {
const fs = yield* FileSystem;
+ const path = yield* Path;
const fileExists = yield* fs.exists(`${location.filePath}.map`);
if (!fileExists) {
return {
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts
index 037291e89..28b7476ca 100644
--- a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts
@@ -1,10 +1,14 @@
-import { Effect, Option, pipe } from 'effect';
+import { Effect, Option, Predicate, pipe } from 'effect';
import type { AnySpan, Span } from 'effect/Tracer';
import { splitSpansAttributesByTypes } from 'effect-errors/logic/spans';
import type { ErrorRelatedSources, RawErrorLocation } from './get-sources-from-map-file';
-import { maybeMapSourcemaps } from './maybe-map-sourcemaps';
+import {
+ isErrorRelatedSources,
+ isRawErrorLocation,
+ maybeMapSourcemaps,
+} from './maybe-map-sourcemaps';
export const getSourcesFromSpan = ({
span,
@@ -28,25 +32,24 @@ export const getSourcesFromSpan = ({
const spans = [];
let current: Span | AnySpan | undefined = span;
- while (current !== undefined && current._tag === 'Span') {
+ while (current !== undefined && Predicate.isTagged(current, 'Span')) {
const { name, attributes: allAttributes, status } = current;
const { attributes, stacktrace } = splitSpansAttributesByTypes(allAttributes);
const sourcesOrLocation = yield* maybeMapSourcemaps(name, stacktrace);
- const duration =
- status._tag === 'Ended'
- ? +`${(status.endTime - status.startTime) / BigInt(1000000)}`
- : undefined;
+ const duration = Predicate.isTagged(status, 'Ended')
+ ? +`${(status.endTime - status.startTime) / BigInt(1000000)}`
+ : undefined;
- sources.push(...sourcesOrLocation.filter(el => el._tag === 'sources'));
- location.push(...sourcesOrLocation.filter(el => el._tag === 'location'));
+ sources.push(...sourcesOrLocation.filter(isErrorRelatedSources));
+ location.push(...sourcesOrLocation.filter(isRawErrorLocation));
spans.push({
name,
attributes: Object.fromEntries(attributes),
durationInMilliseconds: duration,
startTime: status.startTime,
- endTime: status._tag === 'Ended' ? status.endTime : undefined,
+ endTime: Predicate.isTagged(status, 'Ended') ? status.endTime : undefined,
});
current = Option.getOrUndefined(current.parent);
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-stack.ts b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-stack.ts
index 6c1596e25..bf28a73c0 100644
--- a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-stack.ts
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-stack.ts
@@ -2,7 +2,11 @@ import { Effect, pipe } from 'effect';
import { removeNodeModulesEntriesFromStack } from 'effect-errors/logic/spans';
-import { maybeMapSourcemaps } from './maybe-map-sourcemaps';
+import {
+ isErrorRelatedSources,
+ isRawErrorLocation,
+ maybeMapSourcemaps,
+} from './maybe-map-sourcemaps';
export const getSourcesFromStack = (maybeStack: string | undefined) =>
pipe(
@@ -18,8 +22,8 @@ export const getSourcesFromStack = (maybeStack: string | undefined) =>
const sourcesOrLocation = yield* maybeMapSourcemaps('', relevantStackEntries);
return {
- sources: sourcesOrLocation.filter(el => el._tag === 'sources'),
- location: sourcesOrLocation.filter(el => el._tag === 'location'),
+ sources: sourcesOrLocation.filter(isErrorRelatedSources),
+ location: sourcesOrLocation.filter(isRawErrorLocation),
};
}),
Effect.withSpan('get-sources-from-stack')
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts b/ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts
index 525abe1cd..966ba7ac9 100644
--- a/ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts
@@ -1,6 +1,7 @@
import type { PlatformError } from '@effect/platform/Error';
import type { FileSystem } from '@effect/platform/FileSystem';
-import { Effect, pipe } from 'effect';
+import type { Path } from '@effect/platform/Path';
+import { Effect, Predicate, pipe } from 'effect';
import type { JsonParsingError } from 'effect-errors/dependencies/fs';
import { stackAtRegex } from 'effect-errors/logic/stack';
@@ -15,10 +16,16 @@ export type StackEntry = {
export type MaybeMappedSources = ErrorRelatedSources | RawErrorLocation | StackEntry;
+export const isErrorRelatedSources = (value: MaybeMappedSources): value is ErrorRelatedSources =>
+ Predicate.isTagged(value, 'sources');
+
+export const isRawErrorLocation = (value: MaybeMappedSources): value is RawErrorLocation =>
+ Predicate.isTagged(value, 'location');
+
export const maybeMapSourcemaps = (
name: string,
stacktrace: string[]
-): Effect.Effect<MaybeMappedSources[], PlatformError | JsonParsingError, FileSystem> =>
+): Effect.Effect<MaybeMappedSources[], PlatformError | JsonParsingError, FileSystem | Path> =>
pipe(
Effect.forEach(stacktrace, stackLine =>
Effect.gen(function* () {
@@ -33,7 +40,7 @@ export const maybeMapSourcemaps = (
runPath: stackLine.replaceAll(stackAtRegex, 'at '),
};
}
- if (details._tag === 'location') {
+ if (isRawErrorLocation(details)) {
return details;
}
diff --git a/ts/packages/cli/src/effects/core-dependency.ts b/ts/packages/cli/src/effects/core-dependency.ts
index 85115d3d1..da1e265f7 100644
--- a/ts/packages/cli/src/effects/core-dependency.ts
+++ b/ts/packages/cli/src/effects/core-dependency.ts
@@ -1,5 +1,4 @@
-import path from 'node:path';
-import { Command, FileSystem } from '@effect/platform';
+import { Command, FileSystem, Path } from '@effect/platform';
import { Effect, Match } from 'effect';
import {
ProjectEnvironmentDetector,
@@ -71,7 +70,7 @@ export const detectCoreDependencyPlan = (cwd: string) =>
} satisfies CoreDependencyPlan;
});
-const readPackageJson = (fs: FileSystem.FileSystem, dir: string) =>
+const readPackageJson = (fs: FileSystem.FileSystem, path: Path.Path, dir: string) =>
fs.readFileString(path.join(dir, 'package.json')).pipe(
Effect.andThen(content =>
Effect.try({
@@ -96,7 +95,8 @@ const detectJsDependencyVersion = (
plan: Extract<CoreDependencyPlan, { kind: 'js' }>
) =>
Effect.gen(function* () {
- const dirs = getAncestors(plan.rootDir);
+ const path = yield* Path.Path;
+ const dirs = yield* getAncestors(plan.rootDir);
for (const dir of dirs) {
const packageJsonPath = path.join(dir, 'node_modules', '@composio', 'core', 'package.json');
@@ -156,7 +156,7 @@ const detectJsDependencyVersion = (
}
for (const dir of dirs) {
- const pkg = yield* readPackageJson(fs, dir);
+ const pkg = yield* readPackageJson(fs, path, dir);
if (!pkg) {
continue;
}
diff --git a/ts/packages/cli/src/effects/discover-skill-roots.ts b/ts/packages/cli/src/effects/discover-skill-roots.ts
new file mode 100644
index 000000000..64048ae43
--- /dev/null
+++ b/ts/packages/cli/src/effects/discover-skill-roots.ts
@@ -0,0 +1,52 @@
+import { FileSystem, Path } from '@effect/platform';
+import { Effect, Option } from 'effect';
+
+const SKILL_NAME = 'composio-cli';
+
+/**
+ * Find every directory where the composio-cli skill is currently installed.
+ * Known locations:
+ * ~/.agents/skills/composio-cli (canonical install target)
+ * ~/.claude/skills/composio-cli (Claude Code — may be a symlink or a real dir)
+ *
+ * We resolve symlinks so we don't rebuild the same physical directory twice,
+ * but we also rebuild any real (non-symlink) copies so everything stays in sync.
+ */
+export const discoverSkillRoots = (home: string) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const candidates = [path.join(home, '.agents', 'skills'), path.join(home, '.claude', 'skills')];
+ const seen = new Set<string>();
+ const roots: string[] = [];
+
+ for (const parent of candidates) {
+ const skillDir = path.join(parent, SKILL_NAME);
+ const link = yield* fs.readLink(skillDir).pipe(Effect.option);
+ if (Option.isSome(link)) {
+ const realDir = yield* fs.realPath(skillDir).pipe(Effect.option);
+ if (Option.isNone(realDir)) continue;
+
+ const realParent = path.dirname(realDir.value);
+ if (!seen.has(realParent)) {
+ seen.add(realParent);
+ roots.push(realParent);
+ }
+ continue;
+ }
+
+ const stat = yield* fs.stat(skillDir).pipe(Effect.option);
+ if (Option.isSome(stat) && stat.value.type === 'Directory' && !seen.has(parent)) {
+ seen.add(parent);
+ roots.push(parent);
+ }
+ }
+
+ // Always include ~/.agents/skills as a fallback so there's at least one target
+ const agentSkillsRoot = path.join(home, '.agents', 'skills');
+ if (!seen.has(agentSkillsRoot)) {
+ roots.push(agentSkillsRoot);
+ }
+
+ return roots;
+ });
diff --git a/ts/packages/cli/src/effects/find-composio-core-generated.ts b/ts/packages/cli/src/effects/find-composio-core-generated.ts
index ba35cb988..aa6addb4e 100644
--- a/ts/packages/cli/src/effects/find-composio-core-generated.ts
+++ b/ts/packages/cli/src/effects/find-composio-core-generated.ts
@@ -1,5 +1,4 @@
-import path from 'node:path';
-import { Command, FileSystem } from '@effect/platform';
+import { Command, FileSystem, Path } from '@effect/platform';
import { Data, Effect, Match } from 'effect';
import {
JsPackageManagerDetector,
@@ -12,8 +11,12 @@ export class ComposioCorePkgNotFound extends Data.TaggedError('error/ComposioCor
readonly fix?: string;
}> {}
+const DEFAULT_PACKAGE_MANAGER: PackageManager = 'npm';
+
export function pyFindComposioCoreGenerated(cwd: string) {
return Effect.gen(function* () {
+ const path = yield* Path.Path;
+
/**
* Returns a `ComposioCorePkgNotFound` error with the given message and cause.
* 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) {
const pkgManager = yield* pkgManagerDetector.detectJsPackageManager(cwd).pipe(
Effect.andThen(pkgManager => pkgManager),
Effect.tapError(e => Effect.logError(e)),
- Effect.catchAll(() => Effect.succeed('npm' as PackageManager))
+ Effect.catchAll(() => Effect.succeed(DEFAULT_PACKAGE_MANAGER))
);
yield* Effect.logDebug({ pkgManager });
@@ -101,12 +104,13 @@ export function jsFindComposioCoreGenerated(cwd: string) {
}) satisfies Effect.Effect<never, ComposioCorePkgNotFound, JsPackageManagerDetector>;
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
yield* Effect.logDebug('Detecting package manager...');
const pkgManagerDetector = yield* JsPackageManagerDetector;
const pkgManager = yield* pkgManagerDetector.detectJsPackageManager(cwd).pipe(
Effect.tapError(e => Effect.logError(e)),
- Effect.catchAll(() => Effect.succeed('npm' as PackageManager))
+ Effect.catchAll(() => Effect.succeed(DEFAULT_PACKAGE_MANAGER))
);
yield* Effect.logDebug({ pkgManager });
diff --git a/ts/packages/cli/src/effects/json.ts b/ts/packages/cli/src/effects/json.ts
index 7c375ea30..f295a26aa 100644
--- a/ts/packages/cli/src/effects/json.ts
+++ b/ts/packages/cli/src/effects/json.ts
@@ -1,12 +1,18 @@
-import { Data, Effect } from 'effect';
+import { Data, Effect, Schema } from 'effect';
export class JSONParseError extends Data.TaggedError('effects/JSONParseError')<{
- readonly cause: Error;
+ readonly cause: unknown;
readonly message: string;
}> {}
+/**
+ * The canonical "JSON object" schema: a string-keyed record of unknown values.
+ * Import this instead of re-declaring `Schema.Record({ key: Schema.String,
+ * value: Schema.Unknown })` locally.
+ */
+export const JsonRecordSchema = Schema.Record({ key: Schema.String, value: Schema.Unknown });
+
export const JSONParse = (s: string) =>
- Effect.try({
- try: () => JSON.parse(s) as Record<string, unknown>,
- catch: e => new JSONParseError({ cause: e as Error, message: 'Failed to parse JSON' }),
- });
+ Schema.decodeUnknown(Schema.parseJson(JsonRecordSchema))(s).pipe(
+ Effect.mapError(cause => new JSONParseError({ cause, message: 'Failed to parse JSON' }))
+ );
diff --git a/ts/packages/cli/src/effects/setup-cache-dir.ts b/ts/packages/cli/src/effects/setup-cache-dir.ts
index 00228dce8..b0de31993 100644
--- a/ts/packages/cli/src/effects/setup-cache-dir.ts
+++ b/ts/packages/cli/src/effects/setup-cache-dir.ts
@@ -1,6 +1,5 @@
-import path from 'node:path';
import { Effect, pipe, Option } from 'effect';
-import { FileSystem } from '@effect/platform';
+import { FileSystem, Path } from '@effect/platform';
import * as constants from 'src/constants';
import { APP_CONFIG } from 'src/effects/app-config';
import { NodeOs } from 'src/services/node-os';
@@ -8,6 +7,7 @@ import { NodeOs } from 'src/services/node-os';
// Helper to create cache directory
export const setupCacheDir = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const os = yield* NodeOs;
const cacheDir = yield* pipe(
diff --git a/ts/packages/cli/src/effects/version.ts b/ts/packages/cli/src/effects/version.ts
index ed1831046..1111d0611 100644
--- a/ts/packages/cli/src/effects/version.ts
+++ b/ts/packages/cli/src/effects/version.ts
@@ -3,7 +3,10 @@ import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
import * as constants from 'src/constants';
import { resolveInstalledCliVersion } from 'src/services/run-companion-modules';
-export const getVersion = Effect.map(
+export const getVersion = Effect.flatMap(
DEBUG_OVERRIDE_CONFIG.VERSION,
- Option.getOrElse(() => resolveInstalledCliVersion(process.execPath, constants.APP_VERSION))
+ Option.match({
+ onNone: () => resolveInstalledCliVersion(process.execPath, constants.APP_VERSION),
+ onSome: version => Effect.succeed(version),
+ })
);
diff --git a/ts/packages/cli/src/generation/create-toolkit-index.ts b/ts/packages/cli/src/generation/create-toolkit-index.ts
index 006d66379..851174c15 100644
--- a/ts/packages/cli/src/generation/create-toolkit-index.ts
+++ b/ts/packages/cli/src/generation/create-toolkit-index.ts
@@ -84,37 +84,47 @@ export function createToolkitIndex(input: CreateToolkitIndexInput): Simplify<Too
);
}
-type TriggerTypeWithUppercaseSlug<T extends ToolkitName> = Omit<TriggerType, 'slug'> & {
- slug: `${Uppercase<T>}_${string}`;
+type ToolkitPrefixedSlug = `${ToolkitName}_${string}`;
+
+type TriggerTypeWithToolkitPrefix = Omit<TriggerType, 'slug'> & {
+ slug: ToolkitPrefixedSlug;
};
-type GroupByToolkitOutput<T extends ToolkitName> = [
- Uppercase<T>,
+type GroupByToolkitOutput = [
+ ToolkitName,
{
toolkit: Toolkit;
typeableTools:
- | { withTypes: false; tools: Array<`${Uppercase<T>}_${string}`> }
- | { withTypes: true; tools: Array<Tool & { slug: `${Uppercase<T>}_${string}` }> };
- triggerTypes: Array<TriggerTypeWithUppercaseSlug<T>>;
+ | { withTypes: false; tools: Array<ToolkitPrefixedSlug> }
+ | { withTypes: true; tools: Array<Tool & { slug: ToolkitPrefixedSlug }> };
+ triggerTypes: Array<TriggerTypeWithToolkitPrefix>;
},
];
+const hasToolkitSlugPrefix = <A extends { readonly slug: string }>(toolkitName: ToolkitName) => {
+ const hasPrefix = startsWith(`${toolkitName}_`);
+ return (value: A): value is A & { readonly slug: ToolkitPrefixedSlug } => hasPrefix(value.slug);
+};
+
const groupByToolkit =
- <const T extends string>(toolkit: Omit<Toolkit, 'name'> & { name: T }) =>
+ (toolkit: Toolkit) =>
({
typeableTools,
triggerTypes,
- }: Omit<CreateToolkitIndexInput, 'toolkits'>): GroupByToolkitOutput<T & ToolkitName> => {
- const toolkitName = pipe(toolkit.slug, String.toUpperCase, ToolkitName) as Uppercase<
- T & ToolkitName
- >;
+ }: Omit<CreateToolkitIndexInput, 'toolkits'>): GroupByToolkitOutput => {
+ const toolkitName = pipe(toolkit.slug, String.toUpperCase, ToolkitName);
+ const hasMatchingSlug = hasToolkitSlugPrefix(toolkitName);
+ const hasMatchingToolSlug = (
+ tool: Tool
+ ): tool is Tool & { readonly slug: ToolkitPrefixedSlug } => hasMatchingSlug(tool);
+ const hasMatchingTriggerSlug = (
+ triggerType: TriggerType
+ ): triggerType is TriggerTypeWithToolkitPrefix => hasMatchingSlug(triggerType);
const filteredTypeableTools = Match.value(typeableTools).pipe(
Match.when({ withTypes: true }, ({ withTypes, tools }) => ({
withTypes,
- tools: tools.filter(tool => startsWith(`${toolkitName}_`)(tool.slug)) as Array<
- Tool & { slug: `${typeof toolkitName}_${string}` }
- >,
+ tools: tools.filter(hasMatchingToolSlug),
})),
Match.when({ withTypes: false }, ({ withTypes, tools }) => ({
withTypes,
@@ -128,16 +138,11 @@ const groupByToolkit =
{
toolkit,
typeableTools: filteredTypeableTools,
- triggerTypes: triggerTypes.filter(triggerType =>
- startsWith(`${toolkitName}_`)(triggerType.slug)
- ) as Array<TriggerTypeWithUppercaseSlug<T & ToolkitName>>,
+ triggerTypes: triggerTypes.filter(hasMatchingTriggerSlug),
},
];
};
-function groupByToolkits({
- toolkits,
- ...rest
-}: CreateToolkitIndexInput): GroupByToolkitOutput<ToolkitName>[] {
+function groupByToolkits({ toolkits, ...rest }: CreateToolkitIndexInput): GroupByToolkitOutput[] {
return toolkits.map(toolkit => groupByToolkit(toolkit)(rest));
}
diff --git a/ts/packages/cli/src/generation/python/generate.ts b/ts/packages/cli/src/generation/python/generate.ts
index 7fc34ecc8..1ee3b896b 100644
--- a/ts/packages/cli/src/generation/python/generate.ts
+++ b/ts/packages/cli/src/generation/python/generate.ts
@@ -1,3 +1,4 @@
+import type { Path } from '@effect/platform';
import type { ToolkitIndex } from 'src/generation/create-toolkit-index';
import type { SourceFile } from 'src/generation/types';
import { Effect } from 'effect';
@@ -10,7 +11,9 @@ type GeneratePythonSourcesParams = {
};
export function generatePythonSources(params: GeneratePythonSourcesParams) {
- return (index: ToolkitIndex): Effect.Effect<Array<SourceFile>, SafeOutputPathError> => {
+ return (
+ index: ToolkitIndex
+ ): Effect.Effect<Array<SourceFile>, SafeOutputPathError, Path.Path> => {
const toolkiteSources = generatePythonToolkitSources(params.banner)(index);
return Effect.all(
diff --git a/ts/packages/cli/src/generation/safe-output-path.ts b/ts/packages/cli/src/generation/safe-output-path.ts
index c96a8a9d2..3f6d188f5 100644
--- a/ts/packages/cli/src/generation/safe-output-path.ts
+++ b/ts/packages/cli/src/generation/safe-output-path.ts
@@ -1,4 +1,4 @@
-import path from 'node:path';
+import { Path } from '@effect/platform';
import { Data, Effect } from 'effect';
export class SafeOutputPathError extends Data.TaggedError('generation/SafeOutputPathError')<{
@@ -22,24 +22,27 @@ export class SafeOutputPathError extends Data.TaggedError('generation/SafeOutput
export function safeOutputPath(
outputDir: string,
filename: string
-): Effect.Effect<string, SafeOutputPathError> {
- const resolvedDir = path.resolve(outputDir);
- const resolved = path.resolve(resolvedDir, filename);
- const relative = path.relative(resolvedDir, resolved);
- const isWithinOutputDir =
- relative === '' ||
- (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
+): Effect.Effect<string, SafeOutputPathError, Path.Path> {
+ return Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const resolvedDir = path.resolve(outputDir);
+ const resolved = path.resolve(resolvedDir, filename);
+ const relative = path.relative(resolvedDir, resolved);
+ const isWithinOutputDir =
+ relative === '' ||
+ (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
- if (path.isAbsolute(filename) || !isWithinOutputDir) {
- return Effect.fail(
- new SafeOutputPathError({
- filename,
- outputDir,
- resolvedPath: resolved,
- message: `Refusing unsafe generated filename: ${filename} resolves to ${resolved}`,
- })
- );
- }
+ if (path.isAbsolute(filename) || !isWithinOutputDir) {
+ return yield* Effect.fail(
+ new SafeOutputPathError({
+ filename,
+ outputDir,
+ resolvedPath: resolved,
+ message: `Refusing unsafe generated filename: ${filename} resolves to ${resolved}`,
+ })
+ );
+ }
- return Effect.succeed(path.join(outputDir, filename));
+ return path.join(outputDir, filename);
+ });
}
diff --git a/ts/packages/cli/src/generation/typescript/generate-index-source.ts b/ts/packages/cli/src/generation/typescript/generate-index-source.ts
index e7779021c..70f23cc3e 100644
--- a/ts/packages/cli/src/generation/typescript/generate-index-source.ts
+++ b/ts/packages/cli/src/generation/typescript/generate-index-source.ts
@@ -64,7 +64,7 @@ export function generateTypeScriptIndexMapSource(params: GenerateTypeScriptIndex
return (index: ToolkitIndex): string => {
const indexMapEntries = pipe(
index,
- Record.map((_, key) => ts.propertyValue(key, ts.namedValue(key as string))),
+ Record.map((_, key) => ts.propertyValue(key, ts.namedValue(key))),
Record.toEntries,
Arr.map(([_, value]) => value)
);
diff --git a/ts/packages/cli/src/generation/typescript/generate.ts b/ts/packages/cli/src/generation/typescript/generate.ts
index c3d19f794..dc66d42ac 100644
--- a/ts/packages/cli/src/generation/typescript/generate.ts
+++ b/ts/packages/cli/src/generation/typescript/generate.ts
@@ -1,5 +1,5 @@
import * as ts from '@composio/ts-builders';
-import path from 'node:path';
+import { Path } from '@effect/platform';
import { safeOutputPath, type SafeOutputPathError } from 'src/generation/safe-output-path';
import type { ToolkitIndex } from 'src/generation/create-toolkit-index';
import type { SourceFile } from 'src/generation/types';
@@ -20,8 +20,9 @@ type GenerateTypeScriptSourcesParams = {
export function generateTypeScriptSources(params: GenerateTypeScriptSourcesParams) {
return (
index: ToolkitIndex
- ): Effect.Effect<Array<SourceFile>, GenerateTypeScriptSourcesError, never> =>
+ ): Effect.Effect<Array<SourceFile>, GenerateTypeScriptSourcesError, Path.Path> =>
Effect.gen(function* () {
+ const path = yield* Path.Path;
const toolkitSources = yield* generateTypeScriptToolkitSources(params.banner)(index);
const indexSource = generateIndexSource(params)(index);
diff --git a/ts/packages/cli/src/generation/typescript/transpile.ts b/ts/packages/cli/src/generation/typescript/transpile.ts
index 290785e68..bb775de65 100644
--- a/ts/packages/cli/src/generation/typescript/transpile.ts
+++ b/ts/packages/cli/src/generation/typescript/transpile.ts
@@ -1,4 +1,5 @@
import ts from 'typescript';
+import { Path } from '@effect/platform';
import { Effect, Data } from 'effect';
import {
buildVirtualFileMap,
@@ -25,6 +26,8 @@ export function transpileTypeScriptSources({ sources, outputDir }: TranspileType
return yield* Effect.void;
}
+ const path = yield* Path.Path;
+
const compilerOptions = {
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.NodeNext,
@@ -42,7 +45,7 @@ export function transpileTypeScriptSources({ sources, outputDir }: TranspileType
const virtualFileNames = Array.from(virtualFileMap.keys());
const tsHost = ts.createCompilerHost(compilerOptions);
- patchCompilerHostWithVirtualFiles(tsHost, virtualFileMap, 'delegate');
+ patchCompilerHostWithVirtualFiles(tsHost, virtualFileMap, path, 'delegate');
const program = ts.createProgram(virtualFileNames, compilerOptions, tsHost);
const emitResult = program.emit();
diff --git a/ts/packages/cli/src/generation/typescript/virtual-compiler-host.ts b/ts/packages/cli/src/generation/typescript/virtual-compiler-host.ts
index 5e3b813d3..2c01fab1e 100644
--- a/ts/packages/cli/src/generation/typescript/virtual-compiler-host.ts
+++ b/ts/packages/cli/src/generation/typescript/virtual-compiler-host.ts
@@ -1,4 +1,4 @@
-import path from 'node:path';
+import type { Path } from '@effect/platform';
import ts from 'typescript';
/**
@@ -23,6 +23,9 @@ export function buildVirtualFileMap(
* Overrides both `getSourceFile` and `fileExists` so that module resolution
* can discover virtual files that don't exist on the real file system.
*
+ * @param path - `Path` service instance used for the synchronous
+ * normalize/resolve/relative lookups; the `ts.CompilerHost`
+ * callbacks are sync and cannot yield Effects.
* @param fallback - `'throw'` raises when a file cannot be resolved by the
* virtual file map, which keeps validation hosts isolated.
* `'delegate'` falls back to the real file system without
@@ -31,6 +34,7 @@ export function buildVirtualFileMap(
export function patchCompilerHostWithVirtualFiles(
tsHost: ts.CompilerHost,
virtualFileMap: Map<string, ts.SourceFile>,
+ path: Path.Path,
fallback: 'throw' | 'delegate' = 'delegate'
): void {
const currentDirectory = normalizeSlashes(tsHost.getCurrentDirectory());
@@ -40,7 +44,7 @@ export function patchCompilerHostWithVirtualFiles(
const virtualFileLookupMap = new Map<string, ts.SourceFile>();
for (const [filename, sourceFile] of virtualFileMap) {
- for (const lookupKey of getVirtualFileLookupKeys(filename, currentDirectory)) {
+ for (const lookupKey of getVirtualFileLookupKeys(path, filename, currentDirectory)) {
virtualFileLookupMap.set(canonicalizePath(lookupKey), sourceFile);
}
}
@@ -81,7 +85,11 @@ export function patchCompilerHostWithVirtualFiles(
};
}
-function getVirtualFileLookupKeys(filename: string, currentDirectory: string): string[] {
+function getVirtualFileLookupKeys(
+ path: Path.Path,
+ filename: string,
+ currentDirectory: string
+): string[] {
const normalizedFilename = normalizeSlashes(path.normalize(filename));
if (path.isAbsolute(normalizedFilename)) {
diff --git a/ts/packages/cli/src/services/agents.ts b/ts/packages/cli/src/services/agents.ts
index c404146fa..a17758159 100644
--- a/ts/packages/cli/src/services/agents.ts
+++ b/ts/packages/cli/src/services/agents.ts
@@ -1,6 +1,6 @@
-import { FileSystem } from '@effect/platform';
+import { FileSystem, Path } from '@effect/platform';
import { Data, Effect, Option, Predicate, Schema } from 'effect';
-import path from 'node:path';
+import { JsonRecordSchema } from 'src/effects/json';
import { setupCacheDir } from 'src/effects/setup-cache-dir';
import { ComposioUserContext } from 'src/services/user-context';
import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
@@ -10,7 +10,7 @@ export const DEFAULT_AGENTS_BASE_URL = 'https://agents.composio.dev';
export type AgentStatus = 'READY' | 'PENDING' | 'UNKNOWN';
-const UnknownFields = Schema.Record({ key: Schema.String, value: Schema.Unknown });
+const UnknownFields = JsonRecordSchema;
const AgentComposioCredentials = Schema.Struct({
member_id: Schema.optional(Schema.NullOr(Schema.String)),
@@ -157,6 +157,7 @@ export const safeAgentSummary = (identity: AgentIdentity): SafeAgentSummary => (
});
export const agentConfigPath = Effect.gen(function* () {
+ const path = yield* Path.Path;
const cacheDir = yield* setupCacheDir;
return path.join(cacheDir, AGENT_CONFIG_FILE_NAME);
});
diff --git a/ts/packages/cli/src/services/cli-session-artifacts.ts b/ts/packages/cli/src/services/cli-session-artifacts.ts
index fb3070187..835f46b73 100644
--- a/ts/packages/cli/src/services/cli-session-artifacts.ts
+++ b/ts/packages/cli/src/services/cli-session-artifacts.ts
@@ -1,28 +1,21 @@
-import fs from 'node:fs';
-import os from 'node:os';
-import path from 'node:path';
+import { FileSystem, Path } from '@effect/platform';
import { Effect, Option } from 'effect';
import { getOrCreateProbablyMyCliSessionIdForCurrentCwd } from 'src/services/consumer-short-term-cache';
-import { resolveCliConfigPathSync } from 'src/services/cli-user-config';
+import { ComposioCliUserConfig } from 'src/services/cli-user-config';
+import { NodeOs } from 'src/services/node-os';
-const readConfiguredArtifactDirectory = (): string | undefined => {
- try {
- const raw = fs.readFileSync(resolveCliConfigPathSync(), 'utf8');
- const parsed = JSON.parse(raw) as { artifact_directory?: unknown };
- return typeof parsed.artifact_directory === 'string' &&
- parsed.artifact_directory.trim().length > 0
- ? parsed.artifact_directory.trim()
- : undefined;
- } catch {
- return undefined;
- }
-};
+export const resolveArtifactsRoot = Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const os = yield* NodeOs;
+ const cliUserConfig = yield* ComposioCliUserConfig;
-export const resolveArtifactsRoot = (): string =>
- process.env.COMPOSIO_SESSION_DIR?.trim() ||
- process.env.COMPOSIO_CACHE_DIR?.trim() ||
- readConfiguredArtifactDirectory() ||
- path.join(os.tmpdir(), 'composio');
+ return (
+ process.env.COMPOSIO_SESSION_DIR?.trim() ||
+ process.env.COMPOSIO_CACHE_DIR?.trim() ||
+ cliUserConfig.data.artifactDirectory?.trim() ||
+ path.join(os.tmpdir, 'composio')
+ );
+});
const SESSION_HISTORY_FILE = 'session-history.jsonl';
@@ -42,19 +35,24 @@ export const resolveCliSessionArtifacts = (params?: {
readonly consumerUserId?: string;
}) =>
Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const sessionIdOption = yield* getOrCreateProbablyMyCliSessionIdForCurrentCwd(params).pipe(
- Effect.catchAll(() => Effect.succeed(Option.none<string>()))
+ Effect.option,
+ Effect.map(Option.flatten)
);
if (Option.isNone(sessionIdOption)) {
return Option.none<CliSessionArtifacts>();
}
- const directoryPath = path.join(resolveArtifactsRoot(), sessionIdOption.value);
- try {
- fs.mkdirSync(directoryPath, { recursive: true });
- } catch {
+ const directoryPath = path.join(yield* resolveArtifactsRoot, sessionIdOption.value);
+ const directoryCreated = yield* fs
+ .makeDirectory(directoryPath, { recursive: true })
+ .pipe(Effect.option, Effect.map(Option.isSome));
+ if (!directoryCreated) {
return Option.none<CliSessionArtifacts>();
}
+
return Option.some({
sessionId: sessionIdOption.value,
directoryPath,
@@ -68,6 +66,7 @@ export const appendCliSessionHistory = (params: {
readonly consumerUserId?: string;
}) =>
Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
const artifactsOption = yield* resolveCliSessionArtifacts({
orgId: params.orgId,
consumerUserId: params.consumerUserId,
@@ -81,11 +80,9 @@ export const appendCliSessionHistory = (params: {
sessionId: artifactsOption.value.sessionId,
...params.entry,
});
- try {
- fs.appendFileSync(artifactsOption.value.historyFilePath, `${line}\n`, 'utf8');
- } catch {
- // Best-effort — session history write is non-fatal.
- }
+ yield* fs
+ .writeFileString(artifactsOption.value.historyFilePath, `${line}\n`, { flag: 'a' })
+ .pipe(Effect.ignore);
});
export const storeCliSessionArtifact = (params: {
@@ -97,26 +94,32 @@ export const storeCliSessionArtifact = (params: {
readonly consumerUserId?: string;
}) =>
Effect.gen(function* () {
- const directoryPath =
- params.directoryPath ||
- Option.getOrUndefined(
- yield* resolveCliSessionArtifacts({
- orgId: params.orgId,
- consumerUserId: params.consumerUserId,
- }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
- ) ||
- path.join(resolveArtifactsRoot(), `adhoc_${randomToken(12)}`);
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directoryPath = yield* Effect.gen(function* () {
+ if (params.directoryPath) {
+ return params.directoryPath;
+ }
+
+ const artifactsOption = yield* resolveCliSessionArtifacts({
+ orgId: params.orgId,
+ consumerUserId: params.consumerUserId,
+ });
+ if (Option.isSome(artifactsOption)) {
+ return artifactsOption.value.directoryPath;
+ }
- try {
- fs.mkdirSync(directoryPath, { recursive: true });
+ return path.join(yield* resolveArtifactsRoot, `adhoc_${randomToken(12)}`);
+ });
+
+ return yield* Effect.gen(function* () {
+ yield* fs.makeDirectory(directoryPath, { recursive: true });
const extension = (params.extension ?? 'json').replace(/^\.+/, '') || 'json';
const filePath = path.join(
directoryPath,
`${sanitizeArtifactName(params.name)}_${randomToken()}.${extension}`
);
- fs.writeFileSync(filePath, params.contents, 'utf8');
+ yield* fs.writeFileString(filePath, params.contents);
return filePath;
- } catch {
- return undefined;
- }
+ }).pipe(Effect.option, Effect.map(Option.getOrUndefined));
});
diff --git a/ts/packages/cli/src/services/cli-user-config.ts b/ts/packages/cli/src/services/cli-user-config.ts
index ef624e8b4..149d46699 100644
--- a/ts/packages/cli/src/services/cli-user-config.ts
+++ b/ts/packages/cli/src/services/cli-user-config.ts
@@ -2,7 +2,9 @@ import { FileSystem } from '@effect/platform';
import type { PlatformError } from '@effect/platform/Error';
import { Context, Effect, Layer, Option } from 'effect';
import type { ParseError } from 'effect/ParseResult';
+// 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
import os from 'node:os';
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import path from 'node:path';
import { setupCacheDir } from 'src/effects/setup-cache-dir';
import { getVersion } from 'src/effects/version';
diff --git a/ts/packages/cli/src/services/composio-clients-cached.ts b/ts/packages/cli/src/services/composio-clients-cached.ts
index 2a75444c5..4ebd33093 100644
--- a/ts/packages/cli/src/services/composio-clients-cached.ts
+++ b/ts/packages/cli/src/services/composio-clients-cached.ts
@@ -1,6 +1,5 @@
-import path from 'node:path';
import { Effect, Option, ParseResult, Layer, Array as Arr } from 'effect';
-import { FileSystem } from '@effect/platform';
+import { FileSystem, Path } from '@effect/platform';
import { BunFileSystem } from '@effect/platform-bun';
import { setupCacheDir } from 'src/effects/setup-cache-dir';
import { FORCE_CONFIG } from 'src/effects/force-config';
@@ -35,6 +34,17 @@ export const CACHE_FILES = {
triggerTypes: 'trigger-types.json',
} as const;
+/**
+ * Cache filter that keeps only items whose slug starts with one of the
+ * requested toolkits' `<TOOLKIT>_` prefixes.
+ */
+const filterBySlugPrefixes =
+ (toolkitSlugs: ReadonlyArray<string>) =>
+ <T extends { readonly slug: string }>(data: ReadonlyArray<T>) => {
+ const prefixes = toolkitSlugs.map(s => `${s.toUpperCase()}_`);
+ return Effect.succeed(data.filter(t => prefixes.some(p => t.slug.toUpperCase().startsWith(p))));
+ };
+
/**
* Generic cache helper function that handles both cache read/write with graceful error handling.
*/
@@ -48,6 +58,7 @@ function createCachedEffect<T, E, R>(
// First define the cache-handling function that will run with all required services
const cacheEffect = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const cacheDir = yield* setupCacheDir;
const cacheFilePath = path.join(cacheDir, cacheFileName);
@@ -107,7 +118,7 @@ function createCachedEffect<T, E, R>(
// This ensures the returned effect has the same error type as the original computation
// by providing all the required cache services
return handledCacheEffect.pipe(
- Effect.provide(Layer.mergeAll(BunFileSystem.layer, NodeOs.Default))
+ Effect.provide(Layer.mergeAll(BunFileSystem.layer, Path.layer, NodeOs.Default))
) as Effect.Effect<T, E, R>;
}
@@ -186,12 +197,7 @@ export const ComposioToolkitsRepositoryCached = Layer.effect(
getTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) => {
const cacheFilter =
toolkitSlugs && toolkitSlugs.length > 0
- ? (data: TriggerTypes) => {
- const prefixes = toolkitSlugs.map(s => `${s.toUpperCase()}_`);
- return Effect.succeed(
- data.filter(t => prefixes.some(p => t.slug.toUpperCase().startsWith(p)))
- );
- }
+ ? (data: TriggerTypes) => filterBySlugPrefixes(toolkitSlugs)(data)
: undefined;
return createCachedEffect(
CACHE_FILES.triggerTypes,
@@ -205,12 +211,7 @@ export const ComposioToolkitsRepositoryCached = Layer.effect(
getTools: (toolkitSlugs?: ReadonlyArray<string>) => {
const cacheFilter =
toolkitSlugs && toolkitSlugs.length > 0
- ? (data: Tools) => {
- const prefixes = toolkitSlugs.map(s => `${s.toUpperCase()}_`);
- return Effect.succeed(
- data.filter(t => prefixes.some(p => t.slug.toUpperCase().startsWith(p)))
- );
- }
+ ? (data: Tools) => filterBySlugPrefixes(toolkitSlugs)(data)
: undefined;
return createCachedEffect(
CACHE_FILES.tools,
diff --git a/ts/packages/cli/src/services/consumer-short-term-cache.ts b/ts/packages/cli/src/services/consumer-short-term-cache.ts
index 2b130efcd..700f4f564 100644
--- a/ts/packages/cli/src/services/consumer-short-term-cache.ts
+++ b/ts/packages/cli/src/services/consumer-short-term-cache.ts
@@ -1,5 +1,4 @@
-import path from 'node:path';
-import { FileSystem } from '@effect/platform';
+import { FileSystem, Path } from '@effect/platform';
import { Effect, Option, Record as EffectRecord, Schema } from 'effect';
import { APP_CONFIG } from 'src/effects/app-config';
import { setupCacheDir } from 'src/effects/setup-cache-dir';
@@ -76,7 +75,11 @@ export const decodeCacheStateTolerant = (raw: string): CacheState =>
const cacheKey = (orgId: string, consumerUserId: string) => `${orgId}:${consumerUserId}`;
-const cachePath = (cacheDir: string) => path.join(cacheDir, CACHE_FILE);
+const cachePath = Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const cacheDir = yield* setupCacheDir;
+ return path.join(cacheDir, CACHE_FILE);
+});
const cwdHash = (cwd: string): string => {
let hash = 5381;
@@ -131,8 +134,7 @@ const resolveSearchSessionMetadata = (params: {
const readCache = () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
- const cacheDir = yield* setupCacheDir;
- const filePath = cachePath(cacheDir);
+ const filePath = yield* cachePath;
if (!(yield* fs.exists(filePath))) {
return {} satisfies CacheState;
}
@@ -146,7 +148,7 @@ const writeCache = (state: CacheState) =>
const cacheDir = yield* setupCacheDir;
yield* fs.makeDirectory(cacheDir, { recursive: true }).pipe(Effect.catchAll(() => Effect.void));
yield* fs
- .writeFileString(cachePath(cacheDir), JSON.stringify(state, null, 2))
+ .writeFileString(yield* cachePath, JSON.stringify(state, null, 2))
.pipe(Effect.catchAll(() => Effect.void));
});
@@ -393,8 +395,7 @@ export const getFreshConsumerToolRouterConnectedAccountsFromCache = (params: {
export const invalidateConsumerConnectedToolkitsCache = () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
- const cacheDir = yield* setupCacheDir;
- const filePath = cachePath(cacheDir);
+ const filePath = yield* cachePath;
if (yield* fs.exists(filePath)) {
yield* fs.remove(filePath);
}
diff --git a/ts/packages/cli/src/services/detached-process.ts b/ts/packages/cli/src/services/detached-process.ts
new file mode 100644
index 000000000..45086105d
--- /dev/null
+++ b/ts/packages/cli/src/services/detached-process.ts
@@ -0,0 +1,64 @@
+// 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.
+import { spawn } from 'node:child_process';
+import { Data, Effect } from 'effect';
+
+export class DetachedProcessSpawnError extends Data.TaggedError(
+ 'services/DetachedProcessSpawnError'
+)<{
+ readonly command: string;
+ readonly cause: unknown;
+}> {}
+
+/**
+ * Spawns a process that outlives the CLI: detached from the CLI's process
+ * group so terminal signals never reach it, and unref'd so the CLI event loop
+ * never waits on it. All stdio is ignored unless stderr passthrough is
+ * requested (telemetry debug output).
+ */
+export const spawnDetached = (
+ command: string,
+ args: ReadonlyArray<string>,
+ options?: { readonly inheritStderr?: boolean }
+): Effect.Effect<void, DetachedProcessSpawnError> =>
+ Effect.try({
+ try: () =>
+ spawn(command, [...args], {
+ detached: true,
+ stdio: options?.inheritStderr === true ? ['ignore', 'ignore', 'inherit'] : 'ignore',
+ // Leaving `env` unset makes the child inherit the complete parent environment.
+ }),
+ catch: cause => new DetachedProcessSpawnError({ command, cause }),
+ }).pipe(
+ Effect.flatMap(child =>
+ Effect.async<void, DetachedProcessSpawnError>(resume => {
+ let settled = false;
+
+ const cleanup = () => {
+ child.removeListener('spawn', onSpawn);
+ child.removeListener('error', onError);
+ };
+
+ const settle = (result: Effect.Effect<void, DetachedProcessSpawnError>) => {
+ if (settled) {
+ return;
+ }
+
+ settled = true;
+ cleanup();
+ resume(result);
+ };
+
+ const onSpawn = () => {
+ child.unref();
+ settle(Effect.void);
+ };
+
+ const onError = (cause: Error) => {
+ settle(Effect.fail(new DetachedProcessSpawnError({ command, cause })));
+ };
+
+ child.once('spawn', onSpawn);
+ child.once('error', onError);
+ })
+ )
+ );
diff --git a/ts/packages/cli/src/services/js-package-manager-detector.ts b/ts/packages/cli/src/services/js-package-manager-detector.ts
index b40216cfb..219bd4d26 100644
--- a/ts/packages/cli/src/services/js-package-manager-detector.ts
+++ b/ts/packages/cli/src/services/js-package-manager-detector.ts
@@ -1,7 +1,6 @@
import { BunFileSystem } from '@effect/platform-bun';
import { Data, Effect, Option, Schema, pipe } from 'effect';
-import { FileSystem } from '@effect/platform';
-import * as path from 'path';
+import { FileSystem, Path } from '@effect/platform';
const toError = (e: unknown): Error => (e instanceof Error ? e : new Error(String(e)));
@@ -36,6 +35,7 @@ export class JsPackageManagerDetector extends Effect.Service<JsPackageManagerDet
yield* Effect.logDebug('[JsPackageManagerDetector] Identifying JS package manager...');
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const parsePackageManager = (pm: string): Option.Option<PackageManager> => {
if (pm.startsWith('pnpm@')) return Option.some('pnpm');
@@ -151,6 +151,6 @@ export class JsPackageManagerDetector extends Effect.Service<JsPackageManagerDet
detectJsPackageManager,
};
}),
- dependencies: [BunFileSystem.layer],
+ dependencies: [BunFileSystem.layer, Path.layer],
}
) {}
diff --git a/ts/packages/cli/src/services/master-detector.ts b/ts/packages/cli/src/services/master-detector.ts
index 90870caa8..529d3e0d4 100644
--- a/ts/packages/cli/src/services/master-detector.ts
+++ b/ts/packages/cli/src/services/master-detector.ts
@@ -1,6 +1,6 @@
export type MasterKind = 'claude' | 'codex' | 'user';
-const hasEnvPrefix = (env: Record<string, string | undefined>, prefix: string): boolean =>
+export const hasEnvPrefix = (env: Record<string, string | undefined>, prefix: string): boolean =>
Object.keys(env).some(key => key.startsWith(prefix));
export const detectMaster = (env: Record<string, string | undefined> = process.env): MasterKind => {
diff --git a/ts/packages/cli/src/services/native-ui-sidecar.ts b/ts/packages/cli/src/services/native-ui-sidecar.ts
index f35fb2efc..e60bdaaac 100644
--- a/ts/packages/cli/src/services/native-ui-sidecar.ts
+++ b/ts/packages/cli/src/services/native-ui-sidecar.ts
@@ -1,14 +1,24 @@
-import { execFileSync, spawn } from 'node:child_process';
-import fsSync from 'node:fs';
-import fs from 'node:fs/promises';
-import os from 'node:os';
-import path from 'node:path';
-import { Config, ConfigProvider, Effect, Option, Predicate, Schema } from 'effect';
+import { Command, CommandExecutor, FileSystem, Path } from '@effect/platform';
+import { BunContext } from '@effect/platform-bun';
+import {
+ Cause,
+ Config,
+ ConfigProvider,
+ Data,
+ Duration,
+ Effect,
+ Exit,
+ Option,
+ Predicate,
+ Schema,
+ Stream,
+} from 'effect';
import {
detectCliPlatform,
ensureBundledBinaryExecutable,
getLocalToolsBundleRootCandidates,
} from '@composio/cli-local-tools';
+import { hasEnvPrefix } from 'src/services/master-detector';
const NATIVE_UI_BINARY_NAME = 'composio-native-ui';
@@ -30,12 +40,32 @@ export type NativeUiBinaryResolution =
readonly platform: string;
};
-interface NativeUiDecisionPayload {
- readonly decision?: NativeUiPermissionDecision;
+export class NativeUiBinarySetupError extends Data.TaggedError(
+ 'services/NativeUiBinarySetupError'
+)<{
+ readonly binaryPath: string;
+ readonly cause: unknown;
+}> {
+ override get message(): string {
+ return `Failed to make the native UI sidecar binary executable: ${this.binaryPath}`;
+ }
+}
+
+export class NativeUiDecisionMissingError extends Data.TaggedError(
+ 'services/NativeUiDecisionMissingError'
+)<{
+ readonly binaryPath: string;
+}> {
+ override get message(): string {
+ return 'Native permission prompt exited without a decision.';
+ }
}
-const hasEnvPrefix = (env: NodeJS.ProcessEnv, prefix: string): boolean =>
- Object.keys(env).some(key => key.startsWith(prefix));
+// Caller-agent detection scans the whole environment for agent-specific
+// prefixes (OPENCLAW_*, CLAUDE_*, CODEX_*). effect/Config can only read named
+// keys, so this module keeps a single raw-env boundary, mirroring the
+// node-os.ts precedent.
+const rawProcessEnv: NodeJS.ProcessEnv = process.env;
const FALSY_ENV_FLAG_VALUES: ReadonlyArray<string> = ['0', 'false', 'no', 'off'];
@@ -97,38 +127,49 @@ const normalizeCallerAgent = (value?: string): NativeUiCallerAgent | undefined =
return undefined;
};
-const detectCallerAgentFromProcessTree = (): NativeUiCallerAgent | undefined => {
+const PS_TREE_MAX_DEPTH = 8;
+
+// Mirrors the former execFileSync('ps', ...) lookup: any spawn failure (or a
+// non-zero exit, which leaves stdout empty) resolves to undefined.
+const psParentEntry = (
+ pid: number
+): Effect.Effect<string | undefined, never, CommandExecutor.CommandExecutor> =>
+ Command.make('ps', '-o', 'ppid=', '-o', 'comm=', '-p', String(pid)).pipe(
+ // The child never reads interactive input: hand it an immediately-closed
+ // stdin pipe (EOF), matching the previous `stdio: ['ignore', ...]` spawn.
+ Command.stdin(Stream.empty),
+ Command.string,
+ Effect.map(output => output.trim()),
+ Effect.orElseSucceed(() => undefined)
+ );
+
+const detectCallerAgentFromProcessTree: Effect.Effect<
+ NativeUiCallerAgent | undefined,
+ never,
+ CommandExecutor.CommandExecutor
+> = Effect.gen(function* () {
if (process.platform === 'win32') return undefined;
let pid = process.ppid;
- for (let depth = 0; depth < 8 && pid > 1; depth += 1) {
- try {
- const output = execFileSync('ps', ['-o', 'ppid=', '-o', 'comm=', '-p', String(pid)], {
- encoding: 'utf8',
- stdio: ['ignore', 'pipe', 'ignore'],
- }).trim();
- if (!output) return undefined;
-
- const match = output.match(/^(\d+)\s+(.+)$/);
- if (!match) return undefined;
-
- const command = match[2]?.toLowerCase() ?? '';
- if (command.includes('openclaw') || command.includes('open-claw')) return 'openclaw';
- if (command.includes('claude')) return 'claude';
- if (command.includes('codex')) return 'codex';
-
- pid = Number(match[1]);
- } catch {
- return undefined;
- }
+ for (let depth = 0; depth < PS_TREE_MAX_DEPTH && pid > 1; depth += 1) {
+ const output = yield* psParentEntry(pid);
+ if (output === undefined || output === '') return undefined;
+
+ const match = output.match(/^(\d+)\s+(.+)$/);
+ if (!match) return undefined;
+
+ const command = match[2]?.toLowerCase() ?? '';
+ if (command.includes('openclaw') || command.includes('open-claw')) return 'openclaw';
+ if (command.includes('claude')) return 'claude';
+ if (command.includes('codex')) return 'codex';
+
+ pid = Number(match[1]);
}
return undefined;
-};
+});
-export const detectNativeUiCallerAgent = (
- env: NodeJS.ProcessEnv = process.env
-): NativeUiCallerAgent => {
+const detectCallerAgentFromEnv = (env: NodeJS.ProcessEnv): NativeUiCallerAgent | undefined => {
const explicit = normalizeCallerAgent(env.COMPOSIO_CALLER_AGENT ?? env.COMPOSIO_AGENT);
if (explicit) return explicit;
@@ -136,10 +177,29 @@ export const detectNativeUiCallerAgent = (
if (hasEnvPrefix(env, 'CLAUDE_')) return 'claude';
if (hasEnvPrefix(env, 'CODEX_')) return 'codex';
- return detectCallerAgentFromProcessTree() ?? 'composio';
+ return undefined;
};
-export const resolveNativeUiBinary = (): NativeUiBinaryResolution => {
+export const detectNativeUiCallerAgentEffect = (
+ env: NodeJS.ProcessEnv = rawProcessEnv
+): Effect.Effect<NativeUiCallerAgent, never, CommandExecutor.CommandExecutor> =>
+ Effect.gen(function* () {
+ const fromEnv = detectCallerAgentFromEnv(env);
+ if (fromEnv !== undefined) return fromEnv;
+
+ return (yield* detectCallerAgentFromProcessTree) ?? 'composio';
+ });
+
+export const detectNativeUiCallerAgent = (
+ env: NodeJS.ProcessEnv = rawProcessEnv
+): Promise<NativeUiCallerAgent> =>
+ Effect.runPromise(Effect.provide(detectNativeUiCallerAgentEffect(env), BunContext.layer));
+
+export const resolveNativeUiBinary: Effect.Effect<
+ NativeUiBinaryResolution,
+ never,
+ FileSystem.FileSystem | Path.Path
+> = Effect.gen(function* () {
const platform = detectCliPlatform();
if (!platform.startsWith('darwin-')) {
return {
@@ -148,26 +208,35 @@ export const resolveNativeUiBinary = (): NativeUiBinaryResolution => {
};
}
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+
const candidates = getLocalToolsBundleRootCandidates().map(root =>
path.join(root, NATIVE_UI_BINARY_NAME, platform, NATIVE_UI_BINARY_NAME)
);
- const binaryPath = candidates.find(candidate => fsSync.existsSync(candidate));
-
- return binaryPath
- ? {
- _tag: 'found',
- binaryPath,
- }
- : {
- _tag: 'missing',
- platform,
- candidates,
- };
-};
+ const binaryPath = yield* Effect.findFirst(candidates, candidate =>
+ fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))
+ );
+
+ return Option.match(binaryPath, {
+ onNone: (): NativeUiBinaryResolution => ({
+ _tag: 'missing',
+ platform,
+ candidates,
+ }),
+ onSome: (binaryPath): NativeUiBinaryResolution => ({
+ _tag: 'found',
+ binaryPath,
+ }),
+ });
+});
+
+const NativeUiDecisionPayloadSchema = Schema.parseJson(Schema.Struct({ decision: Schema.String }));
const parseDecisionPayload = (raw: string): NativeUiPermissionDecision | undefined => {
- const payload = JSON.parse(raw) as NativeUiDecisionPayload;
- const decision = payload.decision;
+ const decision = Option.getOrUndefined(
+ Schema.decodeUnknownOption(NativeUiDecisionPayloadSchema)(raw)
+ )?.decision;
return decision === 'allow_once' ||
decision === 'allow_session' ||
decision === 'deny' ||
@@ -176,81 +245,117 @@ const parseDecisionPayload = (raw: string): NativeUiPermissionDecision | undefin
: undefined;
};
+type DialogExit =
+ | {
+ readonly _tag: 'exited';
+ // undefined when the dialog was terminated by a signal, which the
+ // previous 'exit' handler saw as `code === null` (treated as non-zero).
+ readonly exitCode: number | undefined;
+ }
+ | {
+ readonly _tag: 'timedOut';
+ };
+
+const requestNativeUiPermissionDecisionEffect = (params: {
+ readonly toolSlug: string;
+ readonly accountLabel?: string;
+ readonly timeoutSeconds?: number;
+}) =>
+ Effect.gen(function* () {
+ if (yield* isInteractivePermissionUiDisabled) return undefined;
+
+ const resolved = yield* resolveNativeUiBinary;
+ if (!Predicate.isTagged(resolved, 'found')) return undefined;
+
+ yield* Effect.tryPromise({
+ try: () => ensureBundledBinaryExecutable(resolved.binaryPath),
+ catch: cause => new NativeUiBinarySetupError({ binaryPath: resolved.binaryPath, cause }),
+ });
+
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+
+ // Removed when the surrounding scope closes, replacing the try/finally rm.
+ const tempDir = yield* fs.makeTempDirectoryScoped({
+ prefix: 'composio-native-ui-decision-',
+ });
+ const callbackFile = path.join(tempDir, 'decision.json');
+ const timeoutSeconds = params.timeoutSeconds ?? 30;
+ const callerAgent = yield* detectNativeUiCallerAgentEffect();
+
+ const args = [
+ '--tool',
+ params.toolSlug,
+ '--account',
+ params.accountLabel ?? 'default connection',
+ '--caller-agent',
+ callerAgent,
+ '--subtitle',
+ 'Approve once, allow for 1 hour, or deny.',
+ '--allow-session-label',
+ 'Allow for 1 hr',
+ '--callback-file',
+ callbackFile,
+ '--timeout',
+ String(timeoutSeconds),
+ ];
+
+ const child = yield* Command.start(
+ // The dialog never reads interactive input: hand it an immediately-closed
+ // stdin pipe (EOF), matching the previous `stdio: 'ignore'` spawn.
+ Command.make(resolved.binaryPath, ...args).pipe(Command.stdin(Stream.empty))
+ );
+
+ // The previous spawn ignored the dialog's output entirely; drain the pipes
+ // so the dialog can never block on a full pipe buffer.
+ yield* Effect.fork(Effect.ignore(Stream.runDrain(child.stdout)));
+ yield* Effect.fork(Effect.ignore(Stream.runDrain(child.stderr)));
+
+ const dialogExit = yield* child.exitCode.pipe(
+ Effect.map((exitCode): DialogExit => ({ _tag: 'exited', exitCode })),
+ // exitCode fails when the dialog was terminated by a signal; fold it into
+ // the signal-termination shape instead of surfacing a PlatformError.
+ Effect.orElseSucceed((): DialogExit => ({ _tag: 'exited', exitCode: undefined })),
+ Effect.timeoutTo({
+ duration: Duration.seconds(timeoutSeconds + 5),
+ onSuccess: (exit: DialogExit) => exit,
+ onTimeout: (): DialogExit => ({ _tag: 'timedOut' }),
+ })
+ );
+
+ // SIGKILL rather than leaving the scope finalizer's SIGTERM to clean up:
+ // the finalizer awaits the child's exit, so a dialog that ignored SIGTERM
+ // would stall this permission gate instead of resolving as dismissed.
+ if (dialogExit._tag === 'timedOut') {
+ yield* Effect.ignore(child.kill('SIGKILL'));
+ return 'dismissed';
+ }
+
+ // If the sidecar exits without writing a callback file, treat a non-zero
+ // exit as a dismissal. A zero exit without a callback is unexpected.
+ const decision = yield* fs.readFileString(callbackFile).pipe(
+ Effect.map(parseDecisionPayload),
+ Effect.orElseSucceed(() => undefined)
+ );
+ if (decision !== undefined) return decision;
+
+ if (dialogExit.exitCode === 0) {
+ return yield* new NativeUiDecisionMissingError({ binaryPath: resolved.binaryPath });
+ }
+ return 'dismissed';
+ }).pipe(Effect.scoped);
+
export const requestNativeUiPermissionDecision = async (params: {
readonly toolSlug: string;
readonly accountLabel?: string;
readonly timeoutSeconds?: number;
}): Promise<NativeUiPermissionDecision | undefined> => {
- if (await Effect.runPromise(isInteractivePermissionUiDisabled)) return undefined;
-
- const resolved = resolveNativeUiBinary();
- if (!Predicate.isTagged(resolved, 'found')) return undefined;
-
- await ensureBundledBinaryExecutable(resolved.binaryPath);
-
- const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'composio-native-ui-decision-'));
- const callbackFile = path.join(tempDir, 'decision.json');
- const timeoutSeconds = params.timeoutSeconds ?? 30;
-
- try {
- return await new Promise<NativeUiPermissionDecision>((resolve, reject) => {
- const args = [
- '--tool',
- params.toolSlug,
- '--account',
- params.accountLabel ?? 'default connection',
- '--caller-agent',
- detectNativeUiCallerAgent(),
- '--subtitle',
- 'Approve once, allow for 1 hour, or deny.',
- '--allow-session-label',
- 'Allow for 1 hr',
- '--callback-file',
- callbackFile,
- '--timeout',
- String(timeoutSeconds),
- ];
-
- const child = spawn(resolved.binaryPath, args, {
- detached: false,
- stdio: 'ignore',
- });
-
- const timeout = setTimeout(
- () => {
- child.kill();
- resolve('dismissed');
- },
- (timeoutSeconds + 5) * 1000
- );
-
- child.on('error', error => {
- clearTimeout(timeout);
- reject(error);
- });
-
- child.on('exit', async code => {
- clearTimeout(timeout);
- try {
- const raw = await fs.readFile(callbackFile, 'utf8');
- const decision = parseDecisionPayload(raw);
- if (decision) {
- resolve(decision);
- return;
- }
- } catch {
- // If the sidecar exits without writing a callback file, treat a non-zero
- // exit as a dismissal. A zero exit without a callback is unexpected.
- }
-
- if (code === 0) {
- reject(new Error('Native permission prompt exited without a decision.'));
- } else {
- resolve('dismissed');
- }
- });
- });
- } finally {
- await fs.rm(tempDir, { recursive: true, force: true });
- }
+ const exit = await Effect.runPromiseExit(
+ Effect.provide(requestNativeUiPermissionDecisionEffect(params), BunContext.layer)
+ );
+ if (Exit.isSuccess(exit)) return exit.value;
+
+ // Surface the original error instance (callers recover from any rejection),
+ // not a FiberFailure wrapper.
+ throw Cause.squash(exit.cause);
};
diff --git a/ts/packages/cli/src/services/node-os.ts b/ts/packages/cli/src/services/node-os.ts
index ebd08cd62..b3d3595b2 100644
--- a/ts/packages/cli/src/services/node-os.ts
+++ b/ts/packages/cli/src/services/node-os.ts
@@ -1,15 +1,22 @@
+// eslint-disable-next-line no-restricted-imports -- This Effect service is the sole node:os boundary for CLI source.
import os from 'node:os';
import { Effect } from 'effect';
-// Service to that wraps `node:os`, for testing purposes.
+// Injectable operating-system details for testing purposes.
export class NodeOs extends Effect.Service<NodeOs>()('services/NodeOs', {
sync: () => ({
homedir: os.homedir(),
+ tmpdir: os.tmpdir(),
platform: os.platform(),
arch: os.arch(),
}),
dependencies: [],
}) {}
-export const defaultNodeOs = ({ homedir }: { homedir: string }) =>
- new NodeOs({ homedir, platform: os.platform(), arch: os.arch() });
+export const defaultNodeOs = ({
+ homedir,
+ tmpdir = os.tmpdir(),
+}: {
+ homedir: string;
+ tmpdir?: string;
+}) => new NodeOs({ homedir, tmpdir, platform: os.platform(), arch: os.arch() });
diff --git a/ts/packages/cli/src/services/project-context.ts b/ts/packages/cli/src/services/project-context.ts
index 80e4dcacc..7a2f024f8 100644
--- a/ts/packages/cli/src/services/project-context.ts
+++ b/ts/packages/cli/src/services/project-context.ts
@@ -1,13 +1,11 @@
-import path from 'node:path';
import { Effect, Option } from 'effect';
-import { FileSystem } from '@effect/platform';
+import { FileSystem, Path } from '@effect/platform';
import { NodeOs } from 'src/services/node-os';
import { NodeProcess } from 'src/services/node-process';
import { APP_CONFIG } from 'src/effects/app-config';
+import { getAncestors } from 'src/utils/get-ancestors';
import * as constants from 'src/constants';
import { type ProjectKeys, projectKeysFromJSON } from 'src/models/project-keys';
-import type { PlatformError } from '@effect/platform/Error';
-import type { ParseError } from 'effect/ParseResult';
/**
* Keys allowed in `.composio/.env` files.
@@ -55,6 +53,7 @@ const parseEnvFile = (content: string): Map<string, string> => {
export class ProjectContext extends Effect.Service<ProjectContext>()('services/ProjectContext', {
effect: Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const proc = yield* NodeProcess;
const os = yield* NodeOs;
@@ -80,10 +79,9 @@ export class ProjectContext extends Effect.Service<ProjectContext>()('services/P
}
// 2. Walk up from CWD, stop at homedir (not filesystem root)
- let dir = proc.cwd;
const stopAt = os.homedir;
- while (true) {
+ for (const dir of yield* getAncestors(proc.cwd)) {
const composioDir = path.join(dir, constants.PROJECT_COMPOSIO_DIR);
// 2a. Check .composio/.env
@@ -141,15 +139,14 @@ export class ProjectContext extends Effect.Service<ProjectContext>()('services/P
}
// Stop at homedir to avoid reading from system directories
- if (dir === stopAt || dir === path.dirname(dir)) break;
- dir = path.dirname(dir);
+ if (dir === stopAt) break;
}
// 3. Nothing found
yield* Effect.logDebug('ProjectContext: no context found');
return Option.none<ProjectKeys>();
- }),
+ }).pipe(Effect.provideService(Path.Path, path)),
};
}),
- dependencies: [],
+ dependencies: [Path.layer],
}) {}
diff --git a/ts/packages/cli/src/services/project-environment-detector.ts b/ts/packages/cli/src/services/project-environment-detector.ts
index 03d77f882..fa8757dc5 100644
--- a/ts/packages/cli/src/services/project-environment-detector.ts
+++ b/ts/packages/cli/src/services/project-environment-detector.ts
@@ -1,7 +1,6 @@
import { BunFileSystem } from '@effect/platform-bun';
-import { FileSystem } from '@effect/platform';
+import { FileSystem, Path } from '@effect/platform';
import { Data, Effect, Match } from 'effect';
-import * as path from 'node:path';
import process from 'node:process';
import { getAncestors } from 'src/utils/get-ancestors';
@@ -99,7 +98,7 @@ const isTsConfig = (name: string) => {
return lower === 'tsconfig.json' || (lower.startsWith('tsconfig.') && lower.endsWith('.json'));
};
-const countExtensions = (files: string[]) => {
+const countExtensions = (path: Path.Path, files: string[]) => {
let ts = 0;
let js = 0;
let py = 0;
@@ -156,7 +155,7 @@ const SYSTEM_ROOTS = new Set([
]);
/** Reject system roots (/, /tmp, /var, /private/tmp, etc.) as project roots. */
-const isSystemRoot = (dir: string): boolean => {
+const isSystemRoot = (path: Path.Path, dir: string): boolean => {
const resolved = path.resolve(dir);
if (SYSTEM_ROOTS.has(resolved)) return true;
const parent = path.dirname(resolved);
@@ -209,7 +208,7 @@ const makeReadDirectoryOptional = (fs: FileSystem.FileSystem) => (dir: string) =
const makeReadFileStringOptional = (fs: FileSystem.FileSystem) => (filePath: string) =>
fs.readFileString(filePath).pipe(Effect.catchAll(() => Effect.succeed<string | null>(null)));
-const makeReadPackageJson = (fs: FileSystem.FileSystem) => {
+const makeReadPackageJson = (fs: FileSystem.FileSystem, path: Path.Path) => {
const readFileStringOptional = makeReadFileStringOptional(fs);
return (dir: string) =>
Effect.gen(function* () {
@@ -228,6 +227,7 @@ const makeReadPackageJson = (fs: FileSystem.FileSystem) => {
const analyzeDirectory = (
fs: FileSystem.FileSystem,
+ path: Path.Path,
dir: string
): Effect.Effect<DirEvidence, ProjectEnvironmentDetectorError> =>
Effect.gen(function* () {
@@ -243,7 +243,7 @@ const analyzeDirectory = (
);
const readDirectoryOptional = makeReadDirectoryOptional(fs);
const readFileStringOptional = makeReadFileStringOptional(fs);
- const readPackageJson = makeReadPackageJson(fs);
+ const readPackageJson = makeReadPackageJson(fs, path);
const lowerFiles = files.map(file => file.toLowerCase());
const fileSet = new Set(lowerFiles);
@@ -354,7 +354,7 @@ const analyzeDirectory = (
}
// Score from file extensions
- const extensionCounts = countExtensions(files);
+ const extensionCounts = countExtensions(path, files);
if (extensionCounts.ts > 0) {
tsScore += Math.min(3, extensionCounts.ts);
jsHints.tsFiles = true;
@@ -372,7 +372,7 @@ const analyzeDirectory = (
if (!fileSet.has(subdir)) continue;
const actualSubdir = fileByLower.get(subdir) ?? subdir;
const subFiles = yield* readDirectoryOptional(path.join(dir, actualSubdir));
- const subCounts = countExtensions(subFiles);
+ const subCounts = countExtensions(path, subFiles);
if (subCounts.ts > 0) {
tsScore += Math.min(2, subCounts.ts);
jsHints.tsFiles = true;
@@ -404,13 +404,14 @@ const analyzeDirectory = (
const detectLanguage = (fs: FileSystem.FileSystem, cwd: string) =>
Effect.gen(function* () {
- const dirs = getAncestors(cwd);
+ const path = yield* Path.Path;
+ const dirs = yield* getAncestors(cwd);
let bestWeak: ReturnType<typeof pickBestWeak> | null = null;
let ambiguous: { dir: string; details: string } | null = null;
for (const [depth, dir] of dirs.entries()) {
- const evidence = yield* analyzeDirectory(fs, dir);
- const systemRoot = isSystemRoot(dir);
+ const evidence = yield* analyzeDirectory(fs, path, dir);
+ const systemRoot = isSystemRoot(path, dir);
if (evidence.strongJs && evidence.strongPy) {
if (depth === 0 && !systemRoot) {
@@ -441,7 +442,7 @@ const detectLanguage = (fs: FileSystem.FileSystem, cwd: string) =>
bestWeak = weakCandidate;
}
- if (bestWeak && !isSystemRoot(bestWeak.dir))
+ if (bestWeak && !isSystemRoot(path, bestWeak.dir))
return {
language: bestWeak.language,
rootDir: bestWeak.dir,
@@ -470,9 +471,10 @@ const detectLanguage = (fs: FileSystem.FileSystem, cwd: string) =>
const detectJsPackageManager = (fs: FileSystem.FileSystem, cwd: string) =>
Effect.gen(function* () {
+ const path = yield* Path.Path;
const readDirectoryOptional = makeReadDirectoryOptional(fs);
- const readPackageJson = makeReadPackageJson(fs);
- const dirs = getAncestors(cwd);
+ const readPackageJson = makeReadPackageJson(fs, path);
+ const dirs = yield* getAncestors(cwd);
for (const dir of dirs) {
const files = yield* readDirectoryOptional(dir);
@@ -504,9 +506,10 @@ const detectJsPackageManager = (fs: FileSystem.FileSystem, cwd: string) =>
const detectPythonPackageManager = (fs: FileSystem.FileSystem, cwd: string) =>
Effect.gen(function* () {
+ const path = yield* Path.Path;
const readDirectoryOptional = makeReadDirectoryOptional(fs);
const readFileStringOptional = makeReadFileStringOptional(fs);
- const dirs = getAncestors(cwd);
+ const dirs = yield* getAncestors(cwd);
let fallback: PythonPackageManager | null = null;
for (const dir of dirs) {
@@ -550,6 +553,7 @@ export class ProjectEnvironmentDetector extends Effect.Service<ProjectEnvironmen
{
effect: Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const detectProjectEnvironment = (
cwd: string
@@ -576,14 +580,16 @@ export class ProjectEnvironmentDetector extends Effect.Service<ProjectEnvironmen
rootDir: detection.rootDir,
evidence: detection.evidence.evidence,
} satisfies ProjectEnvironment;
- });
+ }).pipe(Effect.provideService(Path.Path, path));
return {
detectProjectEnvironment,
- detectJsPackageManager: (cwd: string) => detectJsPackageManager(fs, cwd),
- detectPythonPackageManager: (cwd: string) => detectPythonPackageManager(fs, cwd),
+ detectJsPackageManager: (cwd: string) =>
+ detectJsPackageManager(fs, cwd).pipe(Effect.provideService(Path.Path, path)),
+ detectPythonPackageManager: (cwd: string) =>
+ detectPythonPackageManager(fs, cwd).pipe(Effect.provideService(Path.Path, path)),
};
}),
- dependencies: [BunFileSystem.layer],
+ dependencies: [BunFileSystem.layer, Path.layer],
}
) {}
diff --git a/ts/packages/cli/src/services/run-companion-modules.ts b/ts/packages/cli/src/services/run-companion-modules.ts
index 881a83925..c85733145 100644
--- a/ts/packages/cli/src/services/run-companion-modules.ts
+++ b/ts/packages/cli/src/services/run-companion-modules.ts
@@ -1,23 +1,38 @@
-import * as fs from 'node:fs';
-import * as os from 'node:os';
-import * as path from 'node:path';
+// Companion-module asset resolution and self-repair helpers shared by the CLI runtime,
+// the bundled `composio run` companion modules, and the binary build scripts. Every
+// helper is an Effect over the @effect/platform FileSystem/Path services; consumers
+// outside the CLI runtime (companion runtimes, scripts) provide their own platform layers.
import { fileURLToPath } from 'node:url';
+import { FileSystem, Path } from '@effect/platform';
+import type { PlatformError } from '@effect/platform/Error';
+import { Config, ConfigProvider, Data, Effect, Option, Schema } from 'effect';
import extractZip from 'extract-zip';
+import { GitHubRelease } from 'src/effects/resolve-cli-release';
+import { BaseConfigProviderLive, extendConfigProvider } from 'src/services/config';
+import { parseChecksumsText, sha256Hex } from 'src/utils/checksums';
-export const RUN_COMPANION_MODULE_BASENAMES = [
+export const RUN_COMPANION_MODULE_BASENAMES: ReadonlyArray<string> = [
'run-helpers-runtime',
'run-subagent-shared',
'run-subagent-acp',
'run-subagent-legacy',
'run-subagent-output-mcp',
-] as const;
+];
export const RUN_COMPANION_MODULE_FILENAMES = RUN_COMPANION_MODULE_BASENAMES.map(
name => `${name}.mjs`
);
export const RUN_COMPANION_RELEASE_TAG_FILENAME = 'release-tag.txt';
-export const RUN_CODEX_ACP_BINARY_TARGETS = [
+type RunCodexAcpBinaryTarget = {
+ readonly platform: NodeJS.Platform;
+ readonly arch: string;
+ readonly packageName: string;
+ readonly binaryFileName: string;
+ readonly relativePath: string;
+};
+
+export const RUN_CODEX_ACP_BINARY_TARGETS: ReadonlyArray<RunCodexAcpBinaryTarget> = [
{
platform: 'darwin',
arch: 'arm64',
@@ -46,102 +61,128 @@ export const RUN_CODEX_ACP_BINARY_TARGETS = [
binaryFileName: 'codex-acp',
relativePath: 'acp-adapters/codex/linux-x64/codex-acp',
},
-] as const;
-export const RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS = [
+];
+export const RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS: ReadonlyArray<string> = [
'acp-adapters/claude-code-acp.mjs',
// cli.js from @anthropic-ai/claude-agent-sdk must live next to claude-code-acp.mjs.
// The bundled adapter uses import.meta.url to locate it at runtime.
'acp-adapters/cli.js',
...RUN_CODEX_ACP_BINARY_TARGETS.map(target => target.relativePath),
-] as const;
+];
+
+export class RunCompanionRepairError extends Data.TaggedError('services/RunCompanionRepairError')<{
+ readonly message: string;
+ readonly cause?: unknown;
+}> {}
const relativeImportPattern =
/(?:import\s+(?:[^'"]+?\s+from\s+)?|export\s+(?:\*\s+from\s+|\{[^}]+\}\s+from\s+)|import\s*\()\s*["'](\.{1,2}\/[^"']+?\.mjs)["']/g;
const isImportGraphFile = (relativePath: string) => /\.(?:m?js|ts)$/.test(relativePath);
+const fileExists = (fs: FileSystem.FileSystem, filePath: string) =>
+ fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
+
const collectRelativeImportPaths = ({
+ fs,
+ path,
rootDir,
relativePath,
collected,
recordMissingPaths = false,
}: {
+ fs: FileSystem.FileSystem;
+ path: Path.Path;
rootDir: string;
relativePath: string;
collected: Set<string>;
recordMissingPaths?: boolean;
-}): void => {
- const normalizedRelativePath = relativePath.replaceAll(path.sep, '/');
- if (collected.has(normalizedRelativePath)) {
- return;
- }
-
- const absolutePath = path.join(rootDir, normalizedRelativePath);
- const exists = fs.existsSync(absolutePath);
- if (!exists && !recordMissingPaths) {
- return;
- }
-
- collected.add(normalizedRelativePath);
- if (!exists) {
- return;
- }
+}): Effect.Effect<void> =>
+ Effect.gen(function* () {
+ const normalizedRelativePath = relativePath.replaceAll(path.sep, '/');
+ if (collected.has(normalizedRelativePath)) {
+ return;
+ }
- if (!isImportGraphFile(normalizedRelativePath)) {
- return;
- }
+ const absolutePath = path.join(rootDir, normalizedRelativePath);
+ const exists = yield* fileExists(fs, absolutePath);
+ if (!exists && !recordMissingPaths) {
+ return;
+ }
- const source = fs.readFileSync(absolutePath, 'utf8');
- for (const match of source.matchAll(relativeImportPattern)) {
- const specifier = match[1];
- if (!specifier) {
- continue;
+ collected.add(normalizedRelativePath);
+ if (!exists) {
+ return;
}
- const dependencyRelativePath = path
- .relative(rootDir, path.resolve(path.dirname(absolutePath), specifier))
- .replaceAll(path.sep, '/');
+ if (!isImportGraphFile(normalizedRelativePath)) {
+ return;
+ }
- collectRelativeImportPaths({
- rootDir,
- relativePath: dependencyRelativePath,
- collected,
- recordMissingPaths,
- });
- }
-};
+ const source = yield* Effect.orDie(fs.readFileString(absolutePath, 'utf8'));
+ for (const match of source.matchAll(relativeImportPattern)) {
+ const specifier = match[1];
+ if (!specifier) {
+ continue;
+ }
-export const collectRunCompanionAssetRelativePaths = (rootDir: string): ReadonlyArray<string> => {
- const collected = new Set<string>();
+ const dependencyRelativePath = path
+ .relative(rootDir, path.resolve(path.dirname(absolutePath), specifier))
+ .replaceAll(path.sep, '/');
- for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
- collectRelativeImportPaths({
- rootDir,
- relativePath: fileName,
- collected,
- });
- }
+ yield* collectRelativeImportPaths({
+ fs,
+ path,
+ rootDir,
+ relativePath: dependencyRelativePath,
+ collected,
+ recordMissingPaths,
+ });
+ }
+ });
- if (collected.size === 0) {
- for (const baseName of RUN_COMPANION_MODULE_BASENAMES) {
- collectRelativeImportPaths({
+export const collectRunCompanionAssetRelativePaths = (
+ rootDir: string
+): Effect.Effect<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const collected = new Set<string>();
+
+ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
+ yield* collectRelativeImportPaths({
+ fs,
+ path,
rootDir,
- relativePath: path.posix.join('services', `${baseName}.mjs`),
+ relativePath: fileName,
collected,
});
}
- }
- for (const relativePath of RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS) {
- collectRelativeImportPaths({
- rootDir,
- relativePath,
- collected,
- });
- }
+ if (collected.size === 0) {
+ for (const baseName of RUN_COMPANION_MODULE_BASENAMES) {
+ yield* collectRelativeImportPaths({
+ fs,
+ path,
+ rootDir,
+ relativePath: `services/${baseName}.mjs`,
+ collected,
+ });
+ }
+ }
- return [...collected].sort();
-};
+ for (const relativePath of RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS) {
+ yield* collectRelativeImportPaths({
+ fs,
+ path,
+ rootDir,
+ relativePath,
+ collected,
+ });
+ }
+
+ return [...collected].sort();
+ });
export const resolveRunCompanionAssetPath = ({
callerImportMetaUrl,
@@ -151,69 +192,62 @@ export const resolveRunCompanionAssetPath = ({
callerImportMetaUrl: string;
execPath: string;
relativePathFromRoot: string;
-}): string | null => {
- const currentFilePath = fileURLToPath(callerImportMetaUrl);
- const currentDirectory = path.dirname(currentFilePath);
- const executableDirectory = path.dirname(execPath);
-
- const candidates = [
- path.resolve(currentDirectory, relativePathFromRoot),
- path.resolve(currentDirectory, '..', relativePathFromRoot),
- path.resolve(executableDirectory, relativePathFromRoot),
- ];
-
- for (const candidate of candidates) {
- if (fs.existsSync(candidate)) {
- return candidate;
- }
- }
-
- return null;
-};
+}): Effect.Effect<string | null, never, FileSystem.FileSystem | Path.Path> =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const currentFilePath = fileURLToPath(callerImportMetaUrl);
+ const currentDirectory = path.dirname(currentFilePath);
+ const executableDirectory = path.dirname(execPath);
+
+ const candidates = [
+ path.resolve(currentDirectory, relativePathFromRoot),
+ path.resolve(currentDirectory, '..', relativePathFromRoot),
+ path.resolve(executableDirectory, relativePathFromRoot),
+ ];
+
+ const found = yield* Effect.findFirst(candidates, candidate => fileExists(fs, candidate));
+ return Option.getOrNull(found);
+ });
export const collectExpectedRunCompanionAssetRelativePaths = (
rootDir: string
-): ReadonlyArray<string> => {
- const collected = new Set<string>();
-
- for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
- collectRelativeImportPaths({
- rootDir,
- relativePath: fileName,
- collected,
- recordMissingPaths: true,
- });
- }
-
- for (const relativePath of RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS) {
- collectRelativeImportPaths({
- rootDir,
- relativePath,
- collected,
- recordMissingPaths: true,
- });
- }
-
- return [...collected].sort();
-};
+): Effect.Effect<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const collected = new Set<string>();
+
+ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
+ yield* collectRelativeImportPaths({
+ fs,
+ path,
+ rootDir,
+ relativePath: fileName,
+ collected,
+ recordMissingPaths: true,
+ });
+ }
-type GitHubReleaseAsset = {
- name: string;
- browser_download_url: string;
-};
+ for (const relativePath of RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS) {
+ yield* collectRelativeImportPaths({
+ fs,
+ path,
+ rootDir,
+ relativePath,
+ collected,
+ recordMissingPaths: true,
+ });
+ }
-type GitHubRelease = {
- tag_name: string;
- assets: GitHubReleaseAsset[];
-};
+ return [...collected].sort();
+ });
const DEFAULT_GITHUB_CONFIG = {
apiBaseUrl: 'https://api.github.com',
owner: 'ComposioHQ',
repo: 'composio',
-} as const;
-
-const resolveCompanionInstallDirectory = (execPath: string) => path.dirname(execPath);
+};
const resolveBinaryAssetName = ({
platform = process.platform,
@@ -232,23 +266,32 @@ const resolveBinaryAssetName = ({
case 'linux-arm64':
return 'composio-linux-aarch64.zip';
default:
- throw new Error(`Unsupported platform for run companion repair: ${platform}-${arch}`);
+ return undefined;
}
};
-const readTextFileIfPresent = (filePath: string) => {
- if (!fs.existsSync(filePath)) {
- return undefined;
- }
+const readTextFileIfPresent = (fs: FileSystem.FileSystem, filePath: string) =>
+ Effect.gen(function* () {
+ const exists = yield* fileExists(fs, filePath);
+ if (!exists) {
+ return undefined;
+ }
- const value = fs.readFileSync(filePath, 'utf8').trim();
- return value.length > 0 ? value : undefined;
-};
+ const value = (yield* Effect.orDie(fs.readFileString(filePath, 'utf8'))).trim();
+ return value.length > 0 ? value : undefined;
+ });
-export const readInstalledReleaseTag = (execPath: string) =>
- readTextFileIfPresent(
- path.join(resolveCompanionInstallDirectory(execPath), RUN_COMPANION_RELEASE_TAG_FILENAME)
- );
+export const readInstalledReleaseTag = (
+ execPath: string
+): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ return yield* readTextFileIfPresent(
+ fs,
+ path.join(path.dirname(execPath), RUN_COMPANION_RELEASE_TAG_FILENAME)
+ );
+ });
export const normalizeCliReleaseVersion = (releaseIdentifier: string): string => {
const trimmed = releaseIdentifier.trim();
@@ -261,33 +304,53 @@ export const normalizeCliReleaseVersion = (releaseIdentifier: string): string =>
return trimmed;
};
-export const resolveInstalledCliVersion = (execPath: string, fallbackVersion: string): string =>
- normalizeCliReleaseVersion(readInstalledReleaseTag(execPath) ?? fallbackVersion);
-
-export const writeInstalledReleaseTag = (installDir: string, releaseTag: string) => {
- fs.writeFileSync(
- path.join(installDir, RUN_COMPANION_RELEASE_TAG_FILENAME),
- `${releaseTag}\n`,
- 'utf8'
+export const resolveInstalledCliVersion = (
+ execPath: string,
+ fallbackVersion: string
+): Effect.Effect<string, never, FileSystem.FileSystem | Path.Path> =>
+ Effect.map(readInstalledReleaseTag(execPath), releaseTag =>
+ normalizeCliReleaseVersion(releaseTag ?? fallbackVersion)
);
-};
-export const listMissingInstalledRunCompanionModules = (execPath: string) => {
- const installDirectory = resolveCompanionInstallDirectory(execPath);
- return collectExpectedRunCompanionAssetRelativePaths(installDirectory).filter(
- relativePath => !fs.existsSync(path.join(installDirectory, relativePath))
- );
-};
+export const writeInstalledReleaseTag = (
+ installDir: string,
+ releaseTag: string
+): Effect.Effect<void, PlatformError, FileSystem.FileSystem | Path.Path> =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ yield* fs.writeFileString(
+ path.join(installDir, RUN_COMPANION_RELEASE_TAG_FILENAME),
+ `${releaseTag}\n`
+ );
+ });
-const fetchGitHubJson = async <T>({
- url,
- accessToken,
- fetchErrorMessage,
-}: {
- url: string;
- accessToken?: string;
- fetchErrorMessage: string;
-}): Promise<T> => {
+export const listMissingInstalledRunCompanionModules = (
+ execPath: string
+): Effect.Effect<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const installDirectory = path.dirname(execPath);
+ const expectedRelativePaths =
+ yield* collectExpectedRunCompanionAssetRelativePaths(installDirectory);
+ return yield* Effect.filter(expectedRelativePaths, relativePath =>
+ Effect.map(fileExists(fs, path.join(installDirectory, relativePath)), exists => !exists)
+ );
+ });
+
+const fetchGitHubJson = async <A, I>(
+ schema: Schema.Schema<A, I>,
+ {
+ url,
+ accessToken,
+ fetchErrorMessage,
+ }: {
+ url: string;
+ accessToken?: string;
+ fetchErrorMessage: string;
+ }
+): Promise<A> => {
const response = await fetch(url, {
headers: {
Accept: 'application/vnd.github+json',
@@ -301,7 +364,7 @@ const fetchGitHubJson = async <T>({
throw new Error(`${fetchErrorMessage} (HTTP ${response.status}${body ? `: ${body}` : ''})`);
}
- return (await response.json()) as T;
+ return Schema.decodeUnknownPromise(schema)(await response.json());
};
const fetchChecksums = async ({
@@ -324,21 +387,7 @@ const fetchChecksums = async ({
return undefined;
}
- const text = await response.text();
- const checksums = new Map<string, string>();
- for (const line of text.split('\n')) {
- const trimmed = line.trim();
- if (!trimmed) {
- continue;
- }
-
- const parts = trimmed.split(/\s+/);
- if (parts.length >= 2) {
- checksums.set(parts[1]!, parts[0]!);
- }
- }
-
- return checksums;
+ return parseChecksumsText(await response.text());
};
const verifyChecksum = async ({
@@ -350,10 +399,7 @@ const verifyChecksum = async ({
expectedHash: string;
fileName: string;
}) => {
- const digest = await crypto.subtle.digest('SHA-256', data.slice().buffer);
- const actualHash = Array.from(new Uint8Array(digest))
- .map(byte => byte.toString(16).padStart(2, '0'))
- .join('');
+ const actualHash = await sha256Hex(data);
if (actualHash !== expectedHash) {
throw new Error(
@@ -362,6 +408,19 @@ const verifyChecksum = async ({
}
};
+const toRepairError = (error: unknown) =>
+ new RunCompanionRepairError({
+ message: error instanceof Error ? error.message : String(error),
+ cause: error,
+ });
+
+// Self-repair honors the unprefixed GITHUB_* contract (set by CI and the binary
+// build workflow, mirrored by cli-local-tools) first, then falls back to the
+// CLI-wide COMPOSIO_-prefixed spelling installed by cli-main's config provider.
+const repairConfigProvider = BaseConfigProviderLive.pipe(
+ ConfigProvider.orElse(() => extendConfigProvider(BaseConfigProviderLive))
+);
+
const resolveRepairReleaseTag = ({
execPath,
appVersion,
@@ -369,11 +428,40 @@ const resolveRepairReleaseTag = ({
execPath: string;
appVersion: string;
}) =>
- process.env.GITHUB_TAG?.trim() ||
- readInstalledReleaseTag(execPath) ||
- `@composio/cli@${appVersion}`;
+ Effect.gen(function* () {
+ // GITHUB_TAG pins the release used for self-repair (set by the binary build workflow).
+ const pinnedTag = yield* Effect.orDie(
+ Config.option(Config.string('GITHUB_TAG')).pipe(
+ Config.map(tag => Option.getOrUndefined(Option.map(tag, value => value.trim())))
+ )
+ ).pipe(Effect.withConfigProvider(repairConfigProvider));
+ if (pinnedTag) {
+ return pinnedTag;
+ }
-export const repairMissingInstalledRunCompanionModules = async ({
+ const installedTag = yield* readInstalledReleaseTag(execPath);
+ return installedTag || `@composio/cli@${appVersion}`;
+ });
+
+const nonEmptyConfigWithFallback = (name: string, fallback: string) =>
+ Config.string(name).pipe(
+ Config.map(value => value || fallback),
+ Config.withDefault(fallback)
+ );
+
+// The GITHUB_* overrides let CI and forks redirect the self-repair download.
+const githubRepairConfig = Effect.orDie(
+ Effect.all({
+ apiBaseUrl: nonEmptyConfigWithFallback('GITHUB_API_BASE_URL', DEFAULT_GITHUB_CONFIG.apiBaseUrl),
+ owner: nonEmptyConfigWithFallback('GITHUB_OWNER', DEFAULT_GITHUB_CONFIG.owner),
+ repo: nonEmptyConfigWithFallback('GITHUB_REPO', DEFAULT_GITHUB_CONFIG.repo),
+ accessToken: Config.option(Config.string('GITHUB_ACCESS_TOKEN')).pipe(
+ Config.map(Option.getOrUndefined)
+ ),
+ })
+).pipe(Effect.withConfigProvider(repairConfigProvider));
+
+export const repairMissingInstalledRunCompanionModules = ({
callerImportMetaUrl,
execPath,
appVersion,
@@ -381,109 +469,240 @@ export const repairMissingInstalledRunCompanionModules = async ({
callerImportMetaUrl: string;
execPath: string;
appVersion: string;
-}) => {
- const currentFilePath = fileURLToPath(callerImportMetaUrl);
- if (!currentFilePath.startsWith('/$bunfs/')) {
- return { repaired: false as const };
- }
+}): Effect.Effect<
+ { readonly repaired: false } | { readonly repaired: true; readonly releaseTag: string },
+ RunCompanionRepairError | PlatformError,
+ FileSystem.FileSystem | Path.Path
+> =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+
+ const currentFilePath = fileURLToPath(callerImportMetaUrl);
+ if (!currentFilePath.startsWith('/$bunfs/')) {
+ return { repaired: false as const };
+ }
- const missingModules = listMissingInstalledRunCompanionModules(execPath);
- if (missingModules.length === 0) {
- return { repaired: false as const };
- }
+ const missingModules = yield* listMissingInstalledRunCompanionModules(execPath);
+ if (missingModules.length === 0) {
+ return { repaired: false as const };
+ }
- const releaseTag = resolveRepairReleaseTag({ execPath, appVersion });
- const githubConfig = {
- apiBaseUrl: process.env.GITHUB_API_BASE_URL || DEFAULT_GITHUB_CONFIG.apiBaseUrl,
- owner: process.env.GITHUB_OWNER || DEFAULT_GITHUB_CONFIG.owner,
- repo: process.env.GITHUB_REPO || DEFAULT_GITHUB_CONFIG.repo,
- accessToken: process.env.GITHUB_ACCESS_TOKEN,
- };
-
- const encodedTag = encodeURIComponent(releaseTag);
- const release = await fetchGitHubJson<GitHubRelease>({
- url: `${githubConfig.apiBaseUrl}/repos/${githubConfig.owner}/${githubConfig.repo}/releases/tags/${encodedTag}`,
- accessToken: githubConfig.accessToken,
- fetchErrorMessage: `Failed to fetch release metadata for ${releaseTag} while repairing run companion modules`,
- }).catch(error => {
- throw new Error(
- [
- `Unable to restore the files required by 'composio run' for ${releaseTag}.`,
- error instanceof Error ? error.message : String(error),
- `Reinstall the CLI, or set GITHUB_TAG to the exact release tag for this build and try again.`,
- ].join('\n')
+ const releaseTag = yield* resolveRepairReleaseTag({ execPath, appVersion });
+ const githubConfig = yield* githubRepairConfig;
+
+ const encodedTag = encodeURIComponent(releaseTag);
+ const release = yield* Effect.tryPromise({
+ try: () =>
+ fetchGitHubJson(GitHubRelease, {
+ url: `${githubConfig.apiBaseUrl}/repos/${githubConfig.owner}/${githubConfig.repo}/releases/tags/${encodedTag}`,
+ accessToken: githubConfig.accessToken,
+ fetchErrorMessage: `Failed to fetch release metadata for ${releaseTag} while repairing run companion modules`,
+ }),
+ catch: error =>
+ new RunCompanionRepairError({
+ message: [
+ `Unable to restore the files required by 'composio run' for ${releaseTag}.`,
+ error instanceof Error ? error.message : String(error),
+ `Reinstall the CLI, or set GITHUB_TAG to the exact release tag for this build and try again.`,
+ ].join('\n'),
+ cause: error,
+ }),
+ });
+
+ const assetName = resolveBinaryAssetName({});
+ if (!assetName) {
+ return yield* Effect.fail(
+ new RunCompanionRepairError({
+ message: `Unsupported platform for run companion repair: ${process.platform}-${process.arch}`,
+ })
+ );
+ }
+
+ const asset = release.assets.find(candidate => candidate.name === assetName);
+ if (!asset) {
+ return yield* Effect.fail(
+ new RunCompanionRepairError({
+ message: `Release ${release.tag_name} does not contain ${assetName}; cannot restore run companion modules.`,
+ })
+ );
+ }
+
+ const archiveData = yield* Effect.tryPromise({
+ try: async () => {
+ const archiveResponse = await fetch(asset.browser_download_url, {
+ headers: githubConfig.accessToken
+ ? { Authorization: `Bearer ${githubConfig.accessToken}` }
+ : undefined,
+ });
+ if (!archiveResponse.ok) {
+ throw new Error(
+ `Failed to download ${asset.name} from ${release.tag_name} while repairing run companion modules (HTTP ${archiveResponse.status}).`
+ );
+ }
+ return new Uint8Array(await archiveResponse.arrayBuffer());
+ },
+ catch: toRepairError,
+ });
+
+ const checksums = yield* Effect.tryPromise({
+ try: () =>
+ fetchChecksums({
+ release,
+ accessToken: githubConfig.accessToken,
+ }),
+ catch: toRepairError,
+ });
+ const expectedChecksum = checksums?.get(asset.name);
+ if (expectedChecksum) {
+ yield* Effect.tryPromise({
+ try: () =>
+ verifyChecksum({
+ data: archiveData,
+ expectedHash: expectedChecksum,
+ fileName: asset.name,
+ }),
+ catch: toRepairError,
+ });
+ }
+
+ return yield* Effect.scoped(
+ Effect.gen(function* () {
+ const tempDirectory = yield* fs.makeTempDirectoryScoped({
+ prefix: 'composio-run-repair-',
+ });
+ const archivePath = path.join(tempDirectory, asset.name);
+ const extractDirectory = path.join(tempDirectory, 'extract');
+ const packageDirectory = path.join(extractDirectory, path.parse(asset.name).name);
+ yield* fs.writeFile(archivePath, archiveData);
+ yield* fs.makeDirectory(extractDirectory, { recursive: true });
+ yield* Effect.tryPromise({
+ try: () => extractZip(archivePath, { dir: extractDirectory }),
+ catch: toRepairError,
+ });
+
+ const installDirectory = path.dirname(execPath);
+ const companionRelativePaths =
+ yield* collectExpectedRunCompanionAssetRelativePaths(packageDirectory);
+
+ for (const relativePath of companionRelativePaths) {
+ const sourcePath = path.join(packageDirectory, relativePath);
+ const sourceExists = yield* fileExists(fs, sourcePath);
+ if (!sourceExists) {
+ return yield* Effect.fail(
+ new RunCompanionRepairError({
+ message: `Release ${release.tag_name} is missing ${relativePath}; cannot restore the files required by 'composio run'.`,
+ })
+ );
+ }
+
+ const targetPath = path.join(installDirectory, relativePath);
+ yield* fs.makeDirectory(path.dirname(targetPath), { recursive: true });
+ yield* fs.copyFile(sourcePath, targetPath);
+ }
+
+ yield* writeInstalledReleaseTag(installDirectory, release.tag_name);
+ return {
+ repaired: true as const,
+ releaseTag: release.tag_name,
+ };
+ })
);
});
- const assetName = resolveBinaryAssetName({});
- const asset = release.assets.find(candidate => candidate.name === assetName);
- if (!asset) {
- throw new Error(
- `Release ${release.tag_name} does not contain ${assetName}; cannot restore run companion modules.`
+export const resolveRunCompanionModulePath = ({
+ callerImportMetaUrl,
+ execPath,
+ relativeNoExtensionFromCaller,
+}: {
+ callerImportMetaUrl: string;
+ execPath: string;
+ relativeNoExtensionFromCaller: string;
+}): Effect.Effect<string, never, FileSystem.FileSystem | Path.Path> =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const currentFilePath = fileURLToPath(callerImportMetaUrl);
+ const currentDirectory = path.dirname(currentFilePath);
+ const executableDirectory = path.dirname(execPath);
+ const baseName = path.basename(relativeNoExtensionFromCaller);
+
+ const candidates = [
+ path.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.ts`),
+ path.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.js`),
+ path.resolve(currentDirectory, 'services', `${baseName}.mjs`),
+ path.resolve(currentDirectory, 'services', `${baseName}.js`),
+ path.resolve(currentDirectory, `${baseName}.mjs`),
+ path.resolve(currentDirectory, `${baseName}.js`),
+ path.resolve(executableDirectory, `${baseName}.mjs`),
+ path.resolve(executableDirectory, `${baseName}.js`),
+ ];
+
+ const found = yield* Effect.findFirst(candidates, candidate => fileExists(fs, candidate));
+ return Option.getOrElse(found, () =>
+ currentFilePath.startsWith('/$bunfs/')
+ ? path.resolve(executableDirectory, `${baseName}.mjs`)
+ : path.resolve(currentDirectory, `${baseName}.mjs`)
);
- }
-
- const archiveResponse = await fetch(asset.browser_download_url, {
- headers: githubConfig.accessToken
- ? { Authorization: `Bearer ${githubConfig.accessToken}` }
- : undefined,
});
- if (!archiveResponse.ok) {
- throw new Error(
- `Failed to download ${asset.name} from ${release.tag_name} while repairing run companion modules (HTTP ${archiveResponse.status}).`
- );
- }
- const archiveData = new Uint8Array(await archiveResponse.arrayBuffer());
- const checksums = await fetchChecksums({
- release,
- accessToken: githubConfig.accessToken,
- });
- const expectedChecksum = checksums?.get(asset.name);
- if (expectedChecksum) {
- await verifyChecksum({
- data: archiveData,
- expectedHash: expectedChecksum,
- fileName: asset.name,
- });
+// ── Temporary sync bridges ──────────────────────────────────────────────
+//
+// The callers below still run outside the Effect runtime and are migrated
+// wholesale by the typed-error slice (PR 8 of this stack), which deletes this
+// whole section: update-check.ts and run-subagent-acp.ts. Do not add new
+// callers.
+
+// 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)
+import * as fsSync from 'node:fs';
+// 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)
+import * as pathSync from 'node:path';
+
+const readTextFileIfPresentSync = (filePath: string) => {
+ if (!fsSync.existsSync(filePath)) {
+ return undefined;
}
- const tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-repair-'));
- try {
- const archivePath = path.join(tempDirectory, asset.name);
- const extractDirectory = path.join(tempDirectory, 'extract');
- const packageDirectory = path.join(extractDirectory, path.parse(asset.name).name);
- fs.writeFileSync(archivePath, archiveData);
- fs.mkdirSync(extractDirectory, { recursive: true });
- await extractZip(archivePath, { dir: extractDirectory });
-
- const installDirectory = resolveCompanionInstallDirectory(execPath);
- const companionRelativePaths = collectExpectedRunCompanionAssetRelativePaths(packageDirectory);
-
- for (const relativePath of companionRelativePaths) {
- const sourcePath = path.join(packageDirectory, relativePath);
- if (!fs.existsSync(sourcePath)) {
- throw new Error(
- `Release ${release.tag_name} is missing ${relativePath}; cannot restore the files required by 'composio run'.`
- );
- }
+ const value = fsSync.readFileSync(filePath, 'utf8').trim();
+ return value.length > 0 ? value : undefined;
+};
- const targetPath = path.join(installDirectory, relativePath);
- fs.mkdirSync(path.dirname(targetPath), { recursive: true });
- fs.copyFileSync(sourcePath, targetPath);
- }
+export const resolveInstalledCliVersionSync = (execPath: string, fallbackVersion: string): string =>
+ normalizeCliReleaseVersion(
+ readTextFileIfPresentSync(
+ pathSync.join(pathSync.dirname(execPath), RUN_COMPANION_RELEASE_TAG_FILENAME)
+ ) ?? fallbackVersion
+ );
- writeInstalledReleaseTag(installDirectory, release.tag_name);
- return {
- repaired: true as const,
- releaseTag: release.tag_name,
- };
- } finally {
- fs.rmSync(tempDirectory, { recursive: true, force: true });
+export const resolveRunCompanionAssetPathSync = ({
+ callerImportMetaUrl,
+ execPath,
+ relativePathFromRoot,
+}: {
+ callerImportMetaUrl: string;
+ execPath: string;
+ relativePathFromRoot: string;
+}): string | null => {
+ const currentFilePath = fileURLToPath(callerImportMetaUrl);
+ const currentDirectory = pathSync.dirname(currentFilePath);
+ const executableDirectory = pathSync.dirname(execPath);
+
+ const candidates = [
+ pathSync.resolve(currentDirectory, relativePathFromRoot),
+ pathSync.resolve(currentDirectory, '..', relativePathFromRoot),
+ pathSync.resolve(executableDirectory, relativePathFromRoot),
+ ];
+
+ for (const candidate of candidates) {
+ if (fsSync.existsSync(candidate)) {
+ return candidate;
+ }
}
+
+ return null;
};
-export const resolveRunCompanionModulePath = ({
+export const resolveRunCompanionModulePathSync = ({
callerImportMetaUrl,
execPath,
relativeNoExtensionFromCaller,
@@ -493,28 +712,28 @@ export const resolveRunCompanionModulePath = ({
relativeNoExtensionFromCaller: string;
}): string => {
const currentFilePath = fileURLToPath(callerImportMetaUrl);
- const currentDirectory = path.dirname(currentFilePath);
- const executableDirectory = path.dirname(execPath);
- const baseName = path.basename(relativeNoExtensionFromCaller);
+ const currentDirectory = pathSync.dirname(currentFilePath);
+ const executableDirectory = pathSync.dirname(execPath);
+ const baseName = pathSync.basename(relativeNoExtensionFromCaller);
const candidates = [
- path.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.ts`),
- path.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.js`),
- path.resolve(currentDirectory, 'services', `${baseName}.mjs`),
- path.resolve(currentDirectory, 'services', `${baseName}.js`),
- path.resolve(currentDirectory, `${baseName}.mjs`),
- path.resolve(currentDirectory, `${baseName}.js`),
- path.resolve(executableDirectory, `${baseName}.mjs`),
- path.resolve(executableDirectory, `${baseName}.js`),
+ pathSync.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.ts`),
+ pathSync.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.js`),
+ pathSync.resolve(currentDirectory, 'services', `${baseName}.mjs`),
+ pathSync.resolve(currentDirectory, 'services', `${baseName}.js`),
+ pathSync.resolve(currentDirectory, `${baseName}.mjs`),
+ pathSync.resolve(currentDirectory, `${baseName}.js`),
+ pathSync.resolve(executableDirectory, `${baseName}.mjs`),
+ pathSync.resolve(executableDirectory, `${baseName}.js`),
];
for (const candidate of candidates) {
- if (fs.existsSync(candidate)) {
+ if (fsSync.existsSync(candidate)) {
return candidate;
}
}
return currentFilePath.startsWith('/$bunfs/')
- ? path.resolve(executableDirectory, `${baseName}.mjs`)
- : path.resolve(currentDirectory, `${baseName}.mjs`);
+ ? pathSync.resolve(executableDirectory, `${baseName}.mjs`)
+ : pathSync.resolve(currentDirectory, `${baseName}.mjs`);
};
diff --git a/ts/packages/cli/src/services/run-helpers-runtime.ts b/ts/packages/cli/src/services/run-helpers-runtime.ts
index 4f9967596..db02429af 100644
--- a/ts/packages/cli/src/services/run-helpers-runtime.ts
+++ b/ts/packages/cli/src/services/run-helpers-runtime.ts
@@ -1,5 +1,8 @@
+// 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
import * as fs from 'node:fs';
+// eslint-disable-next-line no-restricted-imports -- os.tmpdir() locates the fallback run-files directory in the child process, outside the Effect runtime
import * as os from 'node:os';
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import * as path from 'node:path';
import process from 'node:process';
import { z } from 'zod';
diff --git a/ts/packages/cli/src/services/run-subagent-acp.ts b/ts/packages/cli/src/services/run-subagent-acp.ts
index 76146fd82..4f3df36f4 100644
--- a/ts/packages/cli/src/services/run-subagent-acp.ts
+++ b/ts/packages/cli/src/services/run-subagent-acp.ts
@@ -1,14 +1,18 @@
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import * as fs from 'node:fs';
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import * as os from 'node:os';
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import path from 'node:path';
import { Readable, Writable } from 'node:stream';
import * as acp from '@agentclientprotocol/sdk';
import type { MasterKind } from 'src/services/master-detector';
import {
- resolveRunCompanionAssetPath,
- resolveRunCompanionModulePath,
+ resolveRunCompanionAssetPathSync,
+ resolveRunCompanionModulePathSync,
RUN_CODEX_ACP_BINARY_TARGETS,
} from 'src/services/run-companion-modules';
import {
@@ -36,7 +40,7 @@ type LegacySetSessionModelConnection = {
const resolveShippedAdapterAsset = (target: InvokeAgentTarget): string | null => {
if (target === 'claude') {
- return resolveRunCompanionAssetPath({
+ return resolveRunCompanionAssetPathSync({
callerImportMetaUrl: import.meta.url,
execPath: process.execPath,
relativePathFromRoot: 'acp-adapters/claude-code-acp.mjs',
@@ -50,7 +54,7 @@ const resolveShippedAdapterAsset = (target: InvokeAgentTarget): string | null =>
return null;
}
- return resolveRunCompanionAssetPath({
+ return resolveRunCompanionAssetPathSync({
callerImportMetaUrl: import.meta.url,
execPath: process.execPath,
relativePathFromRoot: binaryTarget.relativePath,
@@ -131,7 +135,7 @@ export const resolveAcpAdapterCommand = (
};
const chunkFlushPattern = /[\s,.;:!?)\]}"]$/;
-const structuredOutputMcpModulePath = resolveRunCompanionModulePath({
+const structuredOutputMcpModulePath = resolveRunCompanionModulePathSync({
callerImportMetaUrl: import.meta.url,
execPath: process.execPath,
relativeNoExtensionFromCaller: './run-subagent-output-mcp',
diff --git a/ts/packages/cli/src/services/run-subagent-legacy.ts b/ts/packages/cli/src/services/run-subagent-legacy.ts
index a0221ad06..157cb0b3b 100644
--- a/ts/packages/cli/src/services/run-subagent-legacy.ts
+++ b/ts/packages/cli/src/services/run-subagent-legacy.ts
@@ -1,6 +1,10 @@
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import * as fs from 'node:fs';
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import * as os from 'node:os';
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import * as path from 'node:path';
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import { spawn } from 'node:child_process';
import type { MasterKind } from 'src/services/master-detector';
import {
diff --git a/ts/packages/cli/src/services/run-subagent-output-mcp.ts b/ts/packages/cli/src/services/run-subagent-output-mcp.ts
index 82bca980d..bb9febbab 100644
--- a/ts/packages/cli/src/services/run-subagent-output-mcp.ts
+++ b/ts/packages/cli/src/services/run-subagent-output-mcp.ts
@@ -1,3 +1,4 @@
+// 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
import * as fs from 'node:fs';
import process from 'node:process';
import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
diff --git a/ts/packages/cli/src/services/setup-skill-installer.ts b/ts/packages/cli/src/services/setup-skill-installer.ts
index 917513477..b588d0767 100644
--- a/ts/packages/cli/src/services/setup-skill-installer.ts
+++ b/ts/packages/cli/src/services/setup-skill-installer.ts
@@ -13,7 +13,11 @@ import { NodeOs } from './node-os';
export const resolveSetupSkillReleaseTag = (
execPath = process.execPath,
fallbackVersion = APP_VERSION
-): string => readInstalledReleaseTag(execPath) ?? `@composio/cli@${fallbackVersion}`;
+): Effect.Effect<string, never, FileSystem.FileSystem | Path.Path> =>
+ Effect.map(
+ readInstalledReleaseTag(execPath),
+ releaseTag => releaseTag ?? `@composio/cli@${fallbackVersion}`
+ );
const checkClaudeSkillCurrent = (
fs: FileSystem.FileSystem,
@@ -111,12 +115,16 @@ export class SetupSkillInstaller extends Effect.Service<SetupSkillInstaller>()(
const os = yield* NodeOs;
const isCurrent = (releaseTag: string) =>
checkClaudeSkillCurrent(fs, path, os.homedir, releaseTag);
+ const installedReleaseTag = resolveSetupSkillReleaseTag().pipe(
+ Effect.provideService(FileSystem.FileSystem, fs),
+ Effect.provideService(Path.Path, path)
+ );
return {
- isClaudeSkillReady: isCurrent(resolveSetupSkillReleaseTag()),
+ isClaudeSkillReady: Effect.flatMap(installedReleaseTag, isCurrent),
hasManagedClaudeSkill: hasManagedClaudeSkill(os.homedir),
ensureClaudeSkill: Effect.gen(function* () {
- const releaseTag = resolveSetupSkillReleaseTag();
+ const releaseTag = yield* installedReleaseTag;
if (yield* isCurrent(releaseTag)) return false;
yield* installSkill({
diff --git a/ts/packages/cli/src/services/tool-file-uploads.ts b/ts/packages/cli/src/services/tool-file-uploads.ts
index 9091e89a6..6f5b743e7 100644
--- a/ts/packages/cli/src/services/tool-file-uploads.ts
+++ b/ts/packages/cli/src/services/tool-file-uploads.ts
@@ -1,4 +1,6 @@
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import fs from 'node:fs/promises';
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import path from 'node:path';
import type { Composio as RawComposioClient } from '@composio/client';
import { assertSafeFileUploadPath } from '@composio/core';
diff --git a/ts/packages/cli/src/services/tool-input-validation.ts b/ts/packages/cli/src/services/tool-input-validation.ts
index 639778569..a7007ed32 100644
--- a/ts/packages/cli/src/services/tool-input-validation.ts
+++ b/ts/packages/cli/src/services/tool-input-validation.ts
@@ -1,3 +1,4 @@
+// eslint-disable-next-line no-restricted-imports -- migrated with the seam-rules slice (PR 6 of this stack)
import path from 'node:path';
import { FileSystem } from '@effect/platform';
import { Effect, Option } from 'effect';
diff --git a/ts/packages/cli/src/services/tool-permissions.ts b/ts/packages/cli/src/services/tool-permissions.ts
index 8e43d6e38..a404f8bce 100644
--- a/ts/packages/cli/src/services/tool-permissions.ts
+++ b/ts/packages/cli/src/services/tool-permissions.ts
@@ -1,5 +1,7 @@
import http from 'node:http';
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import fs from 'node:fs/promises';
+// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
import path from 'node:path';
import open from 'open';
import { detectCliPlatform } from '@composio/cli-local-tools';
@@ -958,7 +960,7 @@ const requestPermissionDecision = async (params: {
const nativeDecision = await requestNativeUiPermissionDecision(params).catch(() => undefined);
if (nativeDecision === 'allow_once' || nativeDecision === 'allow_session') return nativeDecision;
if (nativeDecision === 'deny' || nativeDecision === 'dismissed') return 'deny';
- return requestPermissionInBrowser({ ...params, agent: detectNativeUiCallerAgent() });
+ return requestPermissionInBrowser({ ...params, agent: await detectNativeUiCallerAgent() });
};
export const gateToolExecution = (params: GateParams) =>
diff --git a/ts/packages/cli/src/services/tools-executor.ts b/ts/packages/cli/src/services/tools-executor.ts
index 020fa435a..ede32deb9 100644
--- a/ts/packages/cli/src/services/tools-executor.ts
+++ b/ts/packages/cli/src/services/tools-executor.ts
@@ -1,4 +1,4 @@
-import { FileSystem } from '@effect/platform';
+import { FileSystem, Path } from '@effect/platform';
import { Context, Effect, Layer } from 'effect';
import type { Composio } from '@composio/client';
import { executeLocalToolBySlug, resolveLocalTool } from '@composio/cli-local-tools';
@@ -57,6 +57,7 @@ export interface ToolsExecutor {
ToolExecuteResponse,
unknown,
| FileSystem.FileSystem
+ | Path.Path
| NodeOs
| NodeProcess
| ComposioUserContext
diff --git a/ts/packages/cli/src/services/update-check.ts b/ts/packages/cli/src/services/update-check.ts
index 553d97a76..c448adb5c 100644
--- a/ts/packages/cli/src/services/update-check.ts
+++ b/ts/packages/cli/src/services/update-check.ts
@@ -1,12 +1,18 @@
+// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
import { readFileSync, mkdirSync } from 'node:fs';
+// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
import { writeFile } from 'node:fs/promises';
+// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
import { arch as getArch, homedir, platform as getPlatform } from 'node:os';
+// eslint-disable-next-line no-restricted-imports -- migrated with the terminal-streams slice (PR 5 of this stack)
import { dirname, join } from 'node:path';
import semver from 'semver';
import { bold, cyanBright, dim } from 'src/ui/colors';
import { APP_VERSION, GITHUB_REPO } from '../constants';
import { isInteractiveTerminal } from 'src/utils/stdio';
-import { resolveInstalledCliVersion } from './run-companion-modules';
+// The sync bridge keeps this pre-migration module working until the
+// typed-error slice (PR 8 of this stack) makes it Effect-native.
+import { resolveInstalledCliVersionSync } from './run-companion-modules';
/**
* Background update check for @composio/cli.
@@ -69,7 +75,7 @@ function getCurrentBinaryAssetName(): string | undefined {
const defaultConfig: UpdateCheckConfig = {
stateFile: join(_home, 'update-check.json'),
- currentVersion: resolveInstalledCliVersion(process.execPath, APP_VERSION),
+ currentVersion: resolveInstalledCliVersionSync(process.execPath, APP_VERSION),
checkIntervalMs: CHECK_INTERVAL_MS,
releasesUrl: `${GITHUB_REPO.API_BASE_URL}/repos/${GITHUB_REPO.OWNER}/${GITHUB_REPO.REPO}/releases?per_page=100`,
binaryAssetName: getCurrentBinaryAssetName(),
diff --git a/ts/packages/cli/src/services/upgrade-binary.ts b/ts/packages/cli/src/services/upgrade-binary.ts
index 757d0c32c..ce57f5b2f 100644
--- a/ts/packages/cli/src/services/upgrade-binary.ts
+++ b/ts/packages/cli/src/services/upgrade-binary.ts
@@ -1,17 +1,15 @@
-import { Data, Effect, Config, Option } from 'effect';
-import { HttpClient, FileSystem } from '@effect/platform';
-import * as path from 'node:path';
-import { cp as copyPath, rm as removePath } from 'node:fs/promises';
+import { Data, Effect, Config, Match, Option, Predicate, Record as EffectRecord } from 'effect';
+import { HttpClient, HttpClientResponse, FileSystem, Path } from '@effect/platform';
import { APP_VERSION } from '../constants';
import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
import { GITHUB_CONFIG } from 'src/effects/github-config';
import { detectPlatform, type PlatformArch } from 'src/effects/detect-platform';
import { CompareSemverError, semverComparator } from 'src/effects/compare-semver';
-import { fetchLatestCliRelease, type GitHubRelease } from 'src/effects/resolve-cli-release';
+import { fetchLatestCliRelease, GitHubRelease } from 'src/effects/resolve-cli-release';
+import { parseChecksumsText, sha256Hex } from 'src/utils/checksums';
// Note: `node:zlib` does not support Github's zip files
import extractZip from 'extract-zip';
-import type { Predicate } from 'effect/Predicate';
import { renderPrettyError } from './utils/pretty-error';
import { TerminalUI } from './terminal-ui';
import {
@@ -37,607 +35,607 @@ const getBinaryAssetName = (platformArch: PlatformArch) =>
const hasPlatformBinaryAsset = (release: GitHubRelease, platformArch: PlatformArch) =>
release.assets.some(asset => asset.name === getBinaryAssetName(platformArch));
-// Service to manage CLI binary upgrades
-export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/UpgradeBinary', {
- accessors: true,
- // eslint-disable-next-line max-lines-per-function
- effect: Effect.gen(function* () {
- const httpClient = yield* HttpClient.HttpClient;
- const fs = yield* FileSystem.FileSystem;
- const githubConfig = yield* Config.all(GITHUB_CONFIG);
-
- /**
- * Fetch latest release from GitHub
- */
- const fetchGitHubJson = <T>({
- url,
- fetchErrorMessage,
- parseErrorMessage,
- }: {
- url: string;
- fetchErrorMessage: string;
- parseErrorMessage: string;
- }): Effect.Effect<T, UpgradeBinaryError, never> =>
- Effect.gen(function* () {
- yield* Effect.logDebug(`GET ${url}`);
+const GITHUB_CONFIG_ALL = Config.all(GITHUB_CONFIG);
- const response = yield* httpClient.get(url).pipe(
- Effect.catchAll(error =>
- Effect.fail(
- new UpgradeBinaryError({
- cause: error,
- message: fetchErrorMessage,
- })
- )
- )
- );
+// Dependencies resolved once at service construction time and threaded
+// through the module-level helpers below.
+interface UpgradeBinaryContext {
+ readonly httpClient: HttpClient.HttpClient;
+ readonly fs: FileSystem.FileSystem;
+ readonly path: Path.Path;
+ readonly githubConfig: Config.Config.Success<typeof GITHUB_CONFIG_ALL>;
+}
- if (response.status < 200 || response.status >= 300) {
- const pretty = yield* response.json.pipe(
- Effect.map(json => renderPrettyError(Object.entries(json as object))),
- Effect.catchAll(() => Effect.succeed(''))
+/**
+ * Fetch latest release from GitHub
+ */
+const fetchGitHubRelease = (
+ { githubConfig, httpClient }: UpgradeBinaryContext,
+ tag: string
+): Effect.Effect<GitHubRelease, UpgradeBinaryError, never> =>
+ Effect.gen(function* () {
+ const encodedTag = encodeURIComponent(tag);
+ const url = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases/tags/${encodedTag}`;
+ const fetchErrorMessage = `Failed to fetch tags/${tag} release from GitHub`;
+ yield* Effect.logDebug(`GET ${url}`);
+
+ const response = yield* httpClient.get(url).pipe(
+ Effect.mapError(
+ cause =>
+ new UpgradeBinaryError({
+ cause,
+ message: fetchErrorMessage,
+ })
+ )
+ );
+
+ if (response.status < 200 || response.status >= 300) {
+ const pretty = yield* response.json.pipe(
+ Effect.map(json =>
+ Predicate.isRecord(json) ? renderPrettyError(EffectRecord.toEntries(json)) : ''
+ ),
+ Effect.catchAll(() => Effect.succeed(''))
+ );
+
+ const cause = pretty ? `HTTP ${response.status}\n${pretty}` : `HTTP ${response.status}`;
+ return yield* Effect.fail(
+ new UpgradeBinaryError({
+ cause,
+ message: fetchErrorMessage,
+ })
+ );
+ }
+
+ return yield* HttpClientResponse.schemaBodyJson(GitHubRelease)(response).pipe(
+ Effect.mapError(
+ cause =>
+ new UpgradeBinaryError({
+ cause,
+ message: 'Failed to parse GitHub release JSON response',
+ })
+ )
+ );
+ });
+
+const fetchLatestRelease = (
+ ctx: UpgradeBinaryContext,
+ platformArch: PlatformArch,
+ options: {
+ prerelease?: boolean;
+ tag?: string;
+ } = {}
+): Effect.Effect<GitHubRelease, UpgradeBinaryError, never> =>
+ Effect.gen(function* () {
+ const { githubConfig, httpClient } = ctx;
+ const prerelease = options.prerelease ?? false;
+ const explicitTag = options.tag ? Option.some(options.tag) : githubConfig.TAG;
+ const release = yield* explicitTag.pipe(
+ Option.match({
+ onNone: Effect.fn(function* () {
+ yield* Effect.logDebug(
+ `No tag specified, resolving latest package-scoped CLI ${prerelease ? 'beta' : 'stable'} release`
);
-
- const cause = pretty ? `HTTP ${response.status}\n${pretty}` : `HTTP ${response.status}`;
- return yield* Effect.fail(
- new UpgradeBinaryError({
- cause,
- message: fetchErrorMessage,
- })
+ const latest = yield* fetchLatestCliRelease({
+ assetDescription: getBinaryAssetName(platformArch),
+ channel: prerelease ? 'beta' : 'stable',
+ githubConfig,
+ hasRequiredAsset: release => hasPlatformBinaryAsset(release, platformArch),
+ httpClient,
+ }).pipe(
+ Effect.mapError(
+ error =>
+ new UpgradeBinaryError({
+ cause: error,
+ message: Match.value(error.reason).pipe(
+ Match.when('request', () => 'Failed to fetch releases from GitHub'),
+ Match.when('http-status', () => 'Failed to fetch releases from GitHub'),
+ Match.when('decode', () => 'Failed to parse GitHub releases JSON response'),
+ Match.when(
+ 'not-found',
+ () =>
+ `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`
+ ),
+ Match.when(
+ 'compare',
+ () =>
+ `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`
+ ),
+ Match.exhaustive
+ ),
+ })
+ )
);
- }
- return (yield* response.json.pipe(
- Effect.catchAll(error =>
- Effect.fail(
- new UpgradeBinaryError({
- cause: error,
- message: parseErrorMessage,
- })
- )
- )
- )) as T;
- });
-
- const fetchLatestRelease = (
- platformArch: PlatformArch,
- options: {
- prerelease?: boolean;
- tag?: string;
- } = {}
- ): Effect.Effect<GitHubRelease, UpgradeBinaryError, never> =>
- Effect.gen(function* () {
- const prerelease = options.prerelease ?? false;
- const explicitTag = options.tag ? Option.some(options.tag) : githubConfig.TAG;
- const release = yield* explicitTag.pipe(
- Option.match({
- onNone: Effect.fn(function* () {
- yield* Effect.logDebug(
- `No tag specified, resolving latest package-scoped CLI ${prerelease ? 'beta' : 'stable'} release`
- );
- const latest = yield* fetchLatestCliRelease({
- assetDescription: getBinaryAssetName(platformArch),
- channel: prerelease ? 'beta' : 'stable',
- githubConfig,
- hasRequiredAsset: release => hasPlatformBinaryAsset(release, platformArch),
- httpClient,
- }).pipe(
- Effect.mapError(
- error =>
- new UpgradeBinaryError({
- cause: error,
- message: error.message.startsWith('Failed to fetch ')
- ? 'Failed to fetch releases from GitHub'
- : error.message === 'Failed to parse GitHub releases JSON'
- ? 'Failed to parse GitHub releases JSON response'
- : `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`,
- })
- )
- );
-
- yield* Effect.logDebug(`Resolved latest CLI release tag: ${latest.tag_name}`);
- return latest;
- }),
- onSome: Effect.fn(function* (tag) {
- yield* Effect.logDebug(`Using tag: ${tag}`);
- const encodedTag = encodeURIComponent(tag);
- const url = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases/tags/${encodedTag}`;
- const release = yield* fetchGitHubJson<GitHubRelease>({
- url,
- fetchErrorMessage: `Failed to fetch tags/${tag} release from GitHub`,
- parseErrorMessage: 'Failed to parse GitHub release JSON response',
- });
-
- return release as GitHubRelease;
- }),
- })
- );
- return release;
- });
-
- /**
- * Check if update is available
- */
- const resolveCurrentReleaseIdentifier = (currentPath: string) =>
- readInstalledReleaseTag(currentPath) || `@composio/cli@${APP_VERSION}`;
-
- const isUpdateAvailable = (
- release: GitHubRelease,
- currentReleaseIdentifier: string
- ): Effect.Effect<boolean, CompareSemverError | UpgradeBinaryError, never> =>
- Effect.gen(function* () {
- // Current version is older than latest
- const isVersionOutdated: Predicate<number> = comparison => comparison < 0;
- const comparison = yield* semverComparator(currentReleaseIdentifier, release.tag_name);
- return isVersionOutdated(comparison);
- });
-
- /**
- * Download binary for current platform
- */
- const downloadBinary = (
- release: GitHubRelease,
- platformArch: PlatformArch
- ): Effect.Effect<{ name: string; data: Uint8Array }, UpgradeBinaryError, never> =>
- Effect.gen(function* () {
- yield* Effect.logDebug(
- `Looking up binary for ${platformArch.platform}-${platformArch.arch}`
- );
+ yield* Effect.logDebug(`Resolved latest CLI release tag: ${latest.tag_name}`);
+ return latest;
+ }),
+ onSome: Effect.fn(function* (tag) {
+ yield* Effect.logDebug(`Using tag: ${tag}`);
+ const release = yield* fetchGitHubRelease(ctx, tag);
+
+ return release;
+ }),
+ })
+ );
+ return release;
+ });
+
+const provideFsAndPath = <A, E>(
+ { fs, path }: UpgradeBinaryContext,
+ effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>
+) =>
+ effect.pipe(
+ Effect.provideService(FileSystem.FileSystem, fs),
+ Effect.provideService(Path.Path, path)
+ );
- const binaryName = getBinaryAssetName(platformArch);
+/**
+ * Check if update is available
+ */
+const resolveCurrentReleaseIdentifier = (ctx: UpgradeBinaryContext, currentPath: string) =>
+ provideFsAndPath(ctx, readInstalledReleaseTag(currentPath)).pipe(
+ Effect.map(releaseTag => releaseTag || `@composio/cli@${APP_VERSION}`)
+ );
+
+const isUpdateAvailable = (
+ release: GitHubRelease,
+ currentReleaseIdentifier: string
+): Effect.Effect<boolean, CompareSemverError | UpgradeBinaryError, never> =>
+ Effect.gen(function* () {
+ // Current version is older than latest
+ const isVersionOutdated = (comparison: number) => comparison < 0;
+ const comparison = yield* semverComparator(currentReleaseIdentifier, release.tag_name);
+ return isVersionOutdated(comparison);
+ });
- const asset = release.assets.find(asset => asset.name === binaryName);
- if (!asset) {
- return yield* Effect.fail(
+/**
+ * Download binary for current platform
+ */
+const downloadBinary = (
+ { httpClient }: UpgradeBinaryContext,
+ release: GitHubRelease,
+ platformArch: PlatformArch
+): Effect.Effect<{ name: string; data: Uint8Array }, UpgradeBinaryError, never> =>
+ Effect.gen(function* () {
+ yield* Effect.logDebug(`Looking up binary for ${platformArch.platform}-${platformArch.arch}`);
+
+ const binaryName = getBinaryAssetName(platformArch);
+
+ const asset = release.assets.find(asset => asset.name === binaryName);
+ if (!asset) {
+ return yield* Effect.fail(
+ new UpgradeBinaryError({
+ cause: `Binary not found: ${binaryName}`,
+ message: `No binary available for ${platformArch.platform}-${platformArch.arch}`,
+ })
+ );
+ }
+
+ yield* Effect.logDebug(`Downloading ${asset.name}...`);
+
+ const response = yield* Effect.gen(function* () {
+ const resp = yield* httpClient.get(asset.browser_download_url).pipe(
+ Effect.mapError(
+ cause =>
new UpgradeBinaryError({
- cause: new Error(`Binary not found: ${binaryName}`),
- message: `No binary available for ${platformArch.platform}-${platformArch.arch}`,
+ cause,
+ message: `Failed to download binary: ${asset.name}`,
})
- );
- }
+ )
+ );
+ if (resp.status < 200 || resp.status >= 300) {
+ return yield* Effect.fail(
+ new UpgradeBinaryError({
+ cause: `HTTP ${resp.status}`,
+ message: `Failed to download binary: ${asset.name}`,
+ })
+ );
+ }
+ return resp;
+ });
- yield* Effect.logDebug(`Downloading ${asset.name}...`);
+ const arrayBuffer = yield* Effect.gen(function* () {
+ return yield* response.arrayBuffer;
+ }).pipe(
+ Effect.mapError(
+ cause =>
+ new UpgradeBinaryError({
+ cause,
+ message: 'Failed to read downloaded binary',
+ })
+ )
+ );
- const response = yield* Effect.gen(function* () {
- const resp = yield* httpClient.get(asset.browser_download_url);
- if (resp.status < 200 || resp.status >= 300) {
- return yield* Effect.fail(
- new UpgradeBinaryError({
- cause: new Error(`HTTP ${resp.status}`),
- message: `Failed to download binary: ${asset.name}`,
- })
- );
- }
- return resp;
- }).pipe(
- Effect.catchAll(error =>
- Effect.fail(
- new UpgradeBinaryError({
- cause: new Error(String(error)),
- message: `Failed to download binary: ${asset.name}`,
- })
- )
- )
- );
+ return {
+ name: binaryName,
+ data: new Uint8Array(arrayBuffer),
+ };
+ });
- const arrayBuffer = yield* Effect.gen(function* () {
- return yield* response.arrayBuffer;
- }).pipe(
- Effect.catchAll(error =>
- Effect.fail(
- new UpgradeBinaryError({
- cause: error as Error,
- message: 'Failed to read downloaded binary',
- })
- )
- )
- );
+/**
+ * Fetch checksums.txt from a release, if available.
+ * Returns the parsed map of filename -> expected SHA-256 hash, or None if not found.
+ */
+const fetchChecksums = (
+ { httpClient }: UpgradeBinaryContext,
+ release: GitHubRelease
+): Effect.Effect<Option.Option<Map<string, string>>, never, never> =>
+ Effect.gen(function* () {
+ const checksumsAsset = release.assets.find(a => a.name === 'checksums.txt');
+ if (!checksumsAsset) {
+ yield* Effect.logDebug('No checksums.txt found in release assets');
+ return Option.none();
+ }
+
+ const response = yield* httpClient
+ .get(checksumsAsset.browser_download_url)
+ .pipe(Effect.catchAll(() => Effect.succeed(null)));
+
+ if (!response || response.status < 200 || response.status >= 300) {
+ yield* Effect.logDebug('Failed to download checksums.txt');
+ return Option.none();
+ }
+
+ const text = yield* response.text.pipe(Effect.catchAll(() => Effect.succeed('')));
+ if (!text) {
+ return Option.none();
+ }
+
+ return Option.some(parseChecksumsText(text));
+ });
- return {
- name: binaryName,
- data: new Uint8Array(arrayBuffer),
- };
- });
-
- /**
- * Fetch checksums.txt from a release, if available.
- * Returns the parsed map of filename -> expected SHA-256 hash, or None if not found.
- */
- const fetchChecksums = (
- release: GitHubRelease
- ): Effect.Effect<Option.Option<Map<string, string>>, never, never> =>
- Effect.gen(function* () {
- const checksumsAsset = release.assets.find(a => a.name === 'checksums.txt');
- if (!checksumsAsset) {
- yield* Effect.logDebug('No checksums.txt found in release assets');
- return Option.none();
- }
+/**
+ * Verify SHA-256 checksum of downloaded data against expected hash.
+ */
+const verifyChecksum = (
+ data: Uint8Array,
+ expectedHash: string,
+ fileName: string
+): Effect.Effect<void, UpgradeBinaryError> =>
+ Effect.gen(function* () {
+ const actual = yield* Effect.tryPromise({
+ try: () => sha256Hex(data),
+ catch: error =>
+ new UpgradeBinaryError({
+ cause: error,
+ message: 'Failed to compute SHA-256 checksum',
+ }),
+ });
- const response = yield* httpClient
- .get(checksumsAsset.browser_download_url)
- .pipe(Effect.catchAll(() => Effect.succeed(null)));
+ if (actual !== expectedHash) {
+ return yield* Effect.fail(
+ new UpgradeBinaryError({
+ message: `Checksum mismatch for ${fileName}\n Expected: ${expectedHash}\n Actual: ${actual}`,
+ })
+ );
+ }
- if (!response || response.status < 200 || response.status >= 300) {
- yield* Effect.logDebug('Failed to download checksums.txt');
- return Option.none();
- }
+ yield* Effect.logDebug(`Checksum verified for ${fileName}`);
+ });
- const text = yield* response.text.pipe(Effect.catchAll(() => Effect.succeed('')));
- if (!text) {
- return Option.none();
- }
+/**
+ * Extract binary from zip archive using FileSystem
+ */
+const extractBinary = (
+ { fs, path }: UpgradeBinaryContext,
+ { name, data }: { name: string; data: Uint8Array },
+ tempDir: string
+): Effect.Effect<{ binaryPath: string; packageDir: string }, UpgradeBinaryError, never> =>
+ Effect.gen(function* () {
+ const zipPath = path.join(tempDir, name);
+ const extractDir = path.join(tempDir, 'extract');
+ const packageDir = path.join(extractDir, path.parse(name).name);
+ const binaryPath = path.join(packageDir, CLI_BINARY_NAME);
+
+ yield* Effect.logDebug(`Download zip to ${extractDir}`);
+
+ // Write zip file
+ yield* fs.writeFile(zipPath, data).pipe(
+ Effect.mapError(
+ cause =>
+ new UpgradeBinaryError({
+ cause,
+ message: 'Failed to write zip file',
+ })
+ )
+ );
- const checksums = new Map<string, string>();
- for (const line of text.split('\n')) {
- const trimmed = line.trim();
- if (!trimmed) continue;
- // Format: "<hash> <filename>" (two spaces, sha256sum compatible)
- const parts = trimmed.split(/\s+/);
- if (parts.length >= 2) {
- checksums.set(parts[1], parts[0]);
- }
- }
+ // Create extract directory
+ yield* fs.makeDirectory(extractDir, { recursive: true }).pipe(
+ Effect.mapError(
+ cause =>
+ new UpgradeBinaryError({
+ cause,
+ message: 'Failed to create extract directory',
+ })
+ )
+ );
+
+ yield* Effect.tryPromise({
+ try: async () => {
+ await extractZip(zipPath, { dir: extractDir });
+ },
+ catch: error =>
+ new UpgradeBinaryError({
+ cause: error,
+ message: 'Failed to extract zip archive',
+ }),
+ });
- return Option.some(checksums);
- });
-
- /**
- * Verify SHA-256 checksum of downloaded data against expected hash.
- */
- const verifyChecksum = (
- data: Uint8Array,
- expectedHash: string,
- fileName: string
- ): Effect.Effect<void, UpgradeBinaryError> =>
- Effect.gen(function* () {
- const hashBuffer = yield* Effect.tryPromise({
- try: () => {
- // Copy into a fresh ArrayBuffer to avoid SharedArrayBuffer type incompatibility
- const buf = new ArrayBuffer(data.byteLength);
- new Uint8Array(buf).set(data);
- return crypto.subtle.digest('SHA-256', buf);
- },
- catch: error =>
- new UpgradeBinaryError({
- cause: error as Error,
- message: 'Failed to compute SHA-256 checksum',
- }),
- });
+ // Check if binary exists
+ const exists = yield* fs.exists(binaryPath).pipe(Effect.catchAll(() => Effect.succeed(false)));
+
+ if (!exists) {
+ return yield* Effect.fail(
+ new UpgradeBinaryError({
+ cause: `Binary not found in archive: ${binaryPath}`,
+ message: 'Extracted archive does not contain expected binary',
+ })
+ );
+ }
+
+ // Make executable
+ yield* fs.chmod(binaryPath, 0o755).pipe(
+ Effect.mapError(
+ cause =>
+ new UpgradeBinaryError({
+ cause,
+ message: 'Failed to make binary executable',
+ })
+ )
+ );
- const actual = Array.from(new Uint8Array(hashBuffer))
- .map(b => b.toString(16).padStart(2, '0'))
- .join('');
+ return {
+ binaryPath,
+ packageDir,
+ };
+ });
- if (actual !== expectedHash) {
- return yield* Effect.fail(
- new UpgradeBinaryError({
- message: `Checksum mismatch for ${fileName}\n Expected: ${expectedHash}\n Actual: ${actual}`,
- })
- );
- }
+/**
+ * Get current executable path
+ */
+const getCurrentExecutablePath = Effect.fn(function* () {
+ // E.g., ~/.composio/composio
+ const currentPath = process.execPath;
- yield* Effect.logDebug(`Checksum verified for ${fileName}`);
- });
+ const runtimesPaths: Array<string | null> = [Bun.which('bun'), Bun.which('node')];
- /**
- * Extract binary from zip archive using FileSystem
- */
- const extractBinary = (
- { name, data }: { name: string; data: Uint8Array },
- tempDir: string
- ): Effect.Effect<{ binaryPath: string; packageDir: string }, UpgradeBinaryError, never> =>
- Effect.gen(function* () {
- const zipPath = path.join(tempDir, name);
- const extractDir = path.join(tempDir, 'extract');
- const packageDir = path.join(extractDir, path.parse(name).name);
- const binaryPath = path.join(packageDir, CLI_BINARY_NAME);
+ if (runtimesPaths.includes(currentPath)) {
+ return yield* Effect.fail(
+ new UpgradeBinaryError({
+ cause: 'Currently using Composio CLI via Bun or Node.js runtime',
+ message:
+ 'Cannot upgrade runtime binary. Please run the upgrade command from a self-contained Composio CLI binary.',
+ })
+ );
+ }
- yield* Effect.logDebug(`Download zip to ${extractDir}`);
+ return currentPath;
+});
- // Write zip file
- yield* fs.writeFile(zipPath, data).pipe(
- Effect.catchAll(error =>
- Effect.fail(
- new UpgradeBinaryError({
- cause: error as Error,
- message: 'Failed to write zip file',
- })
- )
- )
+/**
+ * Replace current executable binary with the new target one.
+ */
+const replaceBinary = (
+ ctx: UpgradeBinaryContext,
+ sourcePath: string,
+ targetPath: string,
+ options: {
+ releaseTag?: string;
+ } = {}
+): Effect.Effect<void, UpgradeBinaryError> =>
+ Effect.gen(function* () {
+ const { fs, path } = ctx;
+ yield* Effect.logDebug(`Replacing binary: ${sourcePath} -> ${targetPath}`);
+ yield* fs
+ .copy(sourcePath, targetPath, {
+ // Note: without `overwrite: true`, the copy operation will silently bail out
+ overwrite: true,
+ })
+ .pipe(
+ Effect.mapError(
+ cause =>
+ new UpgradeBinaryError({
+ cause,
+ message: 'Failed to replace binary',
+ })
+ )
+ );
+
+ const sourceDirectory = path.dirname(sourcePath);
+ const targetDirectory = path.dirname(targetPath);
+ const companionRelativePaths = yield* provideFsAndPath(
+ ctx,
+ collectExpectedRunCompanionAssetRelativePaths(sourceDirectory)
+ );
+ for (const relativePath of companionRelativePaths) {
+ const sourceCompanion = path.join(sourceDirectory, relativePath);
+ const sourceExists = yield* fs
+ .exists(sourceCompanion)
+ .pipe(Effect.catchAll(() => Effect.succeed(false)));
+
+ if (!sourceExists) {
+ return yield* Effect.fail(
+ new UpgradeBinaryError({
+ cause: `Missing companion module: ${sourceCompanion}`,
+ message: 'Downloaded binary package is incomplete',
+ })
);
+ }
- // Create extract directory
- yield* fs.makeDirectory(extractDir, { recursive: true }).pipe(
- Effect.catchAll(error =>
- Effect.fail(
+ const targetCompanion = path.join(targetDirectory, relativePath);
+ yield* fs.makeDirectory(path.dirname(targetCompanion), { recursive: true }).pipe(
+ Effect.mapError(
+ cause =>
+ new UpgradeBinaryError({
+ cause,
+ message: `Failed to create companion module directory: ${relativePath}`,
+ })
+ )
+ );
+
+ yield* fs
+ .copy(sourceCompanion, targetCompanion, {
+ overwrite: true,
+ })
+ .pipe(
+ Effect.mapError(
+ cause =>
new UpgradeBinaryError({
- cause: error as Error,
- message: 'Failed to create extract directory',
+ cause,
+ message: `Failed to replace companion module: ${relativePath}`,
})
- )
)
);
-
- yield* Effect.tryPromise({
- try: async () => {
- await extractZip(zipPath, { dir: extractDir });
- },
- catch: error =>
+ }
+
+ const localToolsAssetSource = path.join(sourceDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
+ const localToolsAssetExists = yield* fs
+ .exists(localToolsAssetSource)
+ .pipe(Effect.catchAll(() => Effect.succeed(false)));
+ if (localToolsAssetExists) {
+ const localToolsAssetTarget = path.join(targetDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
+ // Replace the whole asset directory: drop the previous tree, then copy
+ // the new one (fs.copy is recursive for directories).
+ yield* fs.remove(localToolsAssetTarget, { recursive: true, force: true }).pipe(
+ Effect.andThen(fs.copy(localToolsAssetSource, localToolsAssetTarget, { overwrite: true })),
+ Effect.mapError(
+ error =>
new UpgradeBinaryError({
- cause: error as Error,
- message: 'Failed to extract zip archive',
- }),
- });
-
- // Check if binary exists
- const exists = yield* fs
- .exists(binaryPath)
- .pipe(Effect.catchAll(() => Effect.succeed(false)));
-
- if (!exists) {
- return yield* Effect.fail(
+ cause: error,
+ message: 'Failed to replace local-tool binary assets',
+ })
+ )
+ );
+ }
+
+ const releaseTag = options.releaseTag;
+ if (releaseTag) {
+ yield* provideFsAndPath(ctx, writeInstalledReleaseTag(targetDirectory, releaseTag)).pipe(
+ Effect.mapError(
+ error =>
new UpgradeBinaryError({
- cause: new Error(`Binary not found in archive: ${binaryPath}`),
- message: 'Extracted archive does not contain expected binary',
+ cause: error,
+ message: 'Failed to update installed release metadata',
})
- );
+ )
+ );
+ }
+ });
+
+/**
+ * Main upgrade function
+ */
+const upgrade = (
+ ctx: UpgradeBinaryContext,
+ options: {
+ prerelease?: boolean;
+ tag?: string;
+ } = {}
+) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const upgradeTargetOpt = yield* DEBUG_OVERRIDE_CONFIG['UPGRADE_TARGET'];
+ const currentPath = yield* getCurrentExecutablePath();
+ const prerelease = options.prerelease ?? false;
+ const explicitTag = options.tag;
+ const currentReleaseIdentifier = yield* resolveCurrentReleaseIdentifier(ctx, currentPath);
+ yield* Effect.logDebug(`Current executable path: ${currentPath}`);
+ yield* Effect.logDebug(`Current release identifier: ${currentReleaseIdentifier}`);
+
+ yield* ui.intro('composio upgrade');
+
+ // If local binary path is provided (for testing), use it directly
+ if (Option.isSome(upgradeTargetOpt)) {
+ yield* ui.log.info(`New local version available (current: ${currentReleaseIdentifier})`);
+ yield* replaceBinary(ctx, upgradeTargetOpt.value, currentPath);
+ yield* ui.outro('Upgrade completed');
+ return undefined;
+ }
+
+ const didUpgrade = yield* ui.useMakeSpinner('Checking for updates...', spinner =>
+ Effect.gen(function* () {
+ const platformArch = yield* detectPlatform;
+ const release = yield* fetchLatestRelease(ctx, platformArch, {
+ prerelease,
+ tag: explicitTag,
+ });
+ if (!explicitTag) {
+ const updateAvailable = yield* isUpdateAvailable(release, currentReleaseIdentifier);
+ if (!updateAvailable) {
+ yield* spinner.stop('You are already running the latest version!');
+ return false;
+ }
+ } else if (release.tag_name === currentReleaseIdentifier) {
+ yield* Effect.logDebug(`Already running ${release.tag_name}; re-installing as requested`);
}
- // Make executable
- yield* fs.chmod(binaryPath, 0o755).pipe(
- Effect.catchAll(error =>
- Effect.fail(
- new UpgradeBinaryError({
- cause: error as Error,
- message: 'Failed to make binary executable',
- })
- )
- )
+ yield* spinner.message(
+ explicitTag
+ ? `Installing ${release.tag_name} (current: ${currentReleaseIdentifier})...`
+ : `New version available: ${release.tag_name} (current: ${currentReleaseIdentifier}). Downloading...`
);
- return {
- binaryPath,
- packageDir,
- };
- });
+ const { name, data } = yield* downloadBinary(ctx, release, platformArch);
- /**
- * Get current executable path
- */
- const getCurrentExecutablePath = Effect.fn(function* () {
- // E.g., ~/.composio/composio
- const currentPath = process.execPath;
+ yield* spinner.message('Verifying checksum...');
- const runtimesPaths = [Bun.which('bun'), Bun.which('node')] as Array<string | null>;
+ const checksums = yield* fetchChecksums(ctx, release);
+ if (Option.isSome(checksums)) {
+ const expectedHash = checksums.value.get(name);
+ if (expectedHash) {
+ yield* verifyChecksum(data, expectedHash, name);
+ } else {
+ yield* Effect.logDebug(`No checksum entry found for ${name} — skipping verification`);
+ }
+ }
- if (runtimesPaths.includes(currentPath)) {
- return yield* Effect.fail(
- new UpgradeBinaryError({
- cause: new Error(`Currently using Composio CLI via Bun or Node.js runtime`),
- message:
- 'Cannot upgrade runtime binary. Please run the upgrade command from a self-contained Composio CLI binary.',
- })
- );
- }
+ yield* spinner.message('Extracting...');
- return currentPath;
- });
-
- /**
- * Replace current executable binary with the new target one.
- */
- const replaceBinary = (
- sourcePath: string,
- targetPath: string,
- options: {
- releaseTag?: string;
- } = {}
- ): Effect.Effect<void, UpgradeBinaryError> =>
- Effect.gen(function* () {
- yield* Effect.logDebug(`Replacing binary: ${sourcePath} -> ${targetPath}`);
- yield* fs
- .copy(sourcePath, targetPath, {
- // Note: without `overwrite: true`, the copy operation will silently bail out
- overwrite: true,
- })
+ // The temporary directory is automatically cleaned up
+ const tmpDir = yield* ctx.fs
+ .makeTempDirectoryScoped({ prefix: `${CLI_BINARY_NAME}-upgrade` })
.pipe(
- Effect.catchAll(error =>
- Effect.fail(
+ Effect.mapError(
+ cause =>
new UpgradeBinaryError({
- cause: error as Error,
- message: 'Failed to replace binary',
+ cause,
+ message: 'Failed to create temporary directory',
})
- )
)
);
- const sourceDirectory = path.dirname(sourcePath);
- const targetDirectory = path.dirname(targetPath);
- const companionRelativePaths =
- collectExpectedRunCompanionAssetRelativePaths(sourceDirectory);
- for (const relativePath of companionRelativePaths) {
- const sourceCompanion = path.join(sourceDirectory, relativePath);
- const sourceExists = yield* fs
- .exists(sourceCompanion)
- .pipe(Effect.catchAll(() => Effect.succeed(false)));
-
- if (!sourceExists) {
- return yield* Effect.fail(
- new UpgradeBinaryError({
- cause: new Error(`Missing companion module: ${sourceCompanion}`),
- message: 'Downloaded binary package is incomplete',
- })
- );
- }
-
- const targetCompanion = path.join(targetDirectory, relativePath);
- yield* fs.makeDirectory(path.dirname(targetCompanion), { recursive: true }).pipe(
- Effect.catchAll(error =>
- Effect.fail(
- new UpgradeBinaryError({
- cause: error as Error,
- message: `Failed to create companion module directory: ${relativePath}`,
- })
- )
- )
- );
-
- yield* fs
- .copy(sourceCompanion, targetCompanion, {
- overwrite: true,
- })
- .pipe(
- Effect.catchAll(error =>
- Effect.fail(
- new UpgradeBinaryError({
- cause: error as Error,
- message: `Failed to replace companion module: ${relativePath}`,
- })
- )
- )
- );
- }
-
- const localToolsAssetSource = path.join(sourceDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
- const localToolsAssetExists = yield* fs
- .exists(localToolsAssetSource)
- .pipe(Effect.catchAll(() => Effect.succeed(false)));
- if (localToolsAssetExists) {
- const localToolsAssetTarget = path.join(
- targetDirectory,
- LOCAL_TOOLS_BINARY_ASSET_DIRNAME
- );
- yield* Effect.tryPromise({
- try: async () => {
- await removePath(localToolsAssetTarget, { recursive: true, force: true });
- await copyPath(localToolsAssetSource, localToolsAssetTarget, { recursive: true });
- },
- catch: error =>
- new UpgradeBinaryError({
- cause: error as Error,
- message: 'Failed to replace local-tool binary assets',
- }),
- });
- }
+ const extractedBinary = yield* extractBinary(ctx, { name, data }, tmpDir);
+ yield* replaceBinary(ctx, extractedBinary.binaryPath, currentPath, {
+ releaseTag: release.tag_name,
+ });
- if (options.releaseTag) {
- yield* Effect.try({
- try: () => writeInstalledReleaseTag(targetDirectory, options.releaseTag!),
- catch: error =>
- new UpgradeBinaryError({
- cause: error as Error,
- message: 'Failed to update installed release metadata',
- }),
- });
- }
- });
-
- /**
- * Main upgrade function
- */
- const upgrade = (
- options: {
- prerelease?: boolean;
- tag?: string;
- } = {}
- ) =>
- Effect.gen(function* () {
- const ui = yield* TerminalUI;
- const upgradeTargetOpt = yield* DEBUG_OVERRIDE_CONFIG['UPGRADE_TARGET'];
- const currentPath = yield* getCurrentExecutablePath();
- const prerelease = options.prerelease ?? false;
- const explicitTag = options.tag;
- const currentReleaseIdentifier = resolveCurrentReleaseIdentifier(currentPath);
- yield* Effect.logDebug(`Current executable path: ${currentPath}`);
- yield* Effect.logDebug(`Current release identifier: ${currentReleaseIdentifier}`);
-
- yield* ui.intro('composio upgrade');
-
- // If local binary path is provided (for testing), use it directly
- if (Option.isSome(upgradeTargetOpt)) {
- yield* ui.log.info(`New local version available (current: ${currentReleaseIdentifier})`);
- yield* replaceBinary(upgradeTargetOpt.value, currentPath);
- yield* ui.outro('Upgrade completed');
- return undefined;
- }
+ yield* spinner.stop('Upgrade completed!');
+ return release.tag_name;
+ })
+ );
- const didUpgrade = yield* ui.useMakeSpinner('Checking for updates...', spinner =>
- Effect.gen(function* () {
- const platformArch = yield* detectPlatform;
- const release = yield* fetchLatestRelease(platformArch, {
- prerelease,
- tag: explicitTag,
- });
- if (!explicitTag) {
- const updateAvailable = yield* isUpdateAvailable(release, currentReleaseIdentifier);
- if (!updateAvailable) {
- yield* spinner.stop('You are already running the latest version!');
- return false;
- }
- } else if (release.tag_name === currentReleaseIdentifier) {
- yield* Effect.logDebug(
- `Already running ${release.tag_name}; re-installing as requested`
- );
- }
-
- yield* spinner.message(
- explicitTag
- ? `Installing ${release.tag_name} (current: ${currentReleaseIdentifier})...`
- : `New version available: ${release.tag_name} (current: ${currentReleaseIdentifier}). Downloading...`
- );
-
- const { name, data } = yield* downloadBinary(release, platformArch);
-
- yield* spinner.message('Verifying checksum...');
-
- const checksums = yield* fetchChecksums(release);
- if (Option.isSome(checksums)) {
- const expectedHash = checksums.value.get(name);
- if (expectedHash) {
- yield* verifyChecksum(data, expectedHash, name);
- } else {
- yield* Effect.logDebug(
- `No checksum entry found for ${name} — skipping verification`
- );
- }
- }
-
- yield* spinner.message('Extracting...');
-
- // The temporary directory is automatically cleaned up
- const tmpDir = yield* fs
- .makeTempDirectoryScoped({ prefix: `${CLI_BINARY_NAME}-upgrade}` })
- .pipe(
- Effect.catchAll(error =>
- Effect.fail(
- new UpgradeBinaryError({
- cause: error as Error,
- message: 'Failed to create temporary directory',
- })
- )
- )
- );
-
- const extractedBinary = yield* extractBinary({ name, data }, tmpDir);
- yield* replaceBinary(extractedBinary.binaryPath, currentPath, {
- releaseTag: release.tag_name,
- });
-
- yield* spinner.stop('Upgrade completed!');
- return release.tag_name;
- })
- );
+ yield* ui.outro(
+ didUpgrade ? 'Restart your terminal to use the new version.' : 'No upgrade needed.'
+ );
- yield* ui.outro(
- didUpgrade ? 'Restart your terminal to use the new version.' : 'No upgrade needed.'
- );
+ return didUpgrade || undefined; // release tag string, or undefined if no upgrade
+ });
- return didUpgrade || undefined; // release tag string, or undefined if no upgrade
- });
+// Service to manage CLI binary upgrades
+export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/UpgradeBinary', {
+ accessors: true,
+ effect: Effect.gen(function* () {
+ const ctx: UpgradeBinaryContext = {
+ httpClient: yield* HttpClient.HttpClient,
+ fs: yield* FileSystem.FileSystem,
+ path: yield* Path.Path,
+ githubConfig: yield* GITHUB_CONFIG_ALL,
+ };
return {
- upgrade,
+ upgrade: (options: { prerelease?: boolean; tag?: string } = {}) => upgrade(ctx, options),
} as const;
}),
- dependencies: [],
+ dependencies: [Path.layer],
}) {}
diff --git a/ts/packages/cli/src/services/user-context.ts b/ts/packages/cli/src/services/user-context.ts
index 23f87fded..7827c77b2 100644
--- a/ts/packages/cli/src/services/user-context.ts
+++ b/ts/packages/cli/src/services/user-context.ts
@@ -1,6 +1,5 @@
-import { FileSystem } from '@effect/platform';
+import { FileSystem, Path } from '@effect/platform';
import { Effect, Context, Layer, Option } from 'effect';
-import path from 'path';
import {
type UserDataWithDefaults,
UserData,
@@ -151,6 +150,7 @@ export const rawComposioUserContextLive = Layer.effect(
ComposioUserContext,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
const apiKey = yield* APP_CONFIG['USER_API_KEY'];
const baseURL = yield* APP_CONFIG['BASE_URL'];
const webURL = yield* APP_CONFIG['WEB_URL'];
@@ -354,7 +354,7 @@ const resolveMacOSBackend = (
/**
* Public layer that pre-provides the keyring and CLI-config deps,
- * leaving only `FileSystem` as the external requirement. The keyring
+ * leaving only `FileSystem` and `Path` as external requirements. The keyring
* backend is chosen dynamically from the user's `config.json`
* `security` field — `"auto"` / `"keychain-subprocess"` select the
* subprocess path (default); `"keychain"` opts into the experimental
diff --git a/ts/packages/cli/src/utils/checksums.ts b/ts/packages/cli/src/utils/checksums.ts
new file mode 100644
index 000000000..ae11da250
--- /dev/null
+++ b/ts/packages/cli/src/utils/checksums.ts
@@ -0,0 +1,29 @@
+/**
+ * Parse a sha256sum-compatible `checksums.txt` ("<hash> <filename>" per line)
+ * into a filename -> expected-hash map. Blank lines are skipped.
+ */
+export const parseChecksumsText = (text: string): Map<string, string> => {
+ const checksums = new Map<string, string>();
+ for (const line of text.split('\n')) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+ const parts = trimmed.split(/\s+/);
+ if (parts.length >= 2) {
+ checksums.set(parts[1]!, parts[0]!);
+ }
+ }
+ return checksums;
+};
+
+/**
+ * SHA-256 digest of `data` as a lowercase hex string. Copies into a fresh
+ * ArrayBuffer so views over a SharedArrayBuffer are accepted too.
+ */
+export const sha256Hex = async (data: Uint8Array): Promise<string> => {
+ const buffer = new ArrayBuffer(data.byteLength);
+ new Uint8Array(buffer).set(data);
+ const digest = await crypto.subtle.digest('SHA-256', buffer);
+ return Array.from(new Uint8Array(digest))
+ .map(byte => byte.toString(16).padStart(2, '0'))
+ .join('');
+};
diff --git a/ts/packages/cli/src/utils/djb2.ts b/ts/packages/cli/src/utils/djb2.ts
new file mode 100644
index 000000000..b989d33a0
--- /dev/null
+++ b/ts/packages/cli/src/utils/djb2.ts
@@ -0,0 +1,11 @@
+/**
+ * djb2 string hash (seed 5381, xor variant), normalized to a non-negative
+ * 32-bit integer. Callers pick their own string encoding (hex, base36, ...).
+ */
+export const djb2Hash = (value: string): number => {
+ let hash = 5381;
+ for (let index = 0; index < value.length; index += 1) {
+ hash = (hash * 33) ^ value.charCodeAt(index);
+ }
+ return Math.abs(hash >>> 0);
+};
diff --git a/ts/packages/cli/src/utils/get-ancestors.ts b/ts/packages/cli/src/utils/get-ancestors.ts
index f5873e590..e7cc52bc3 100644
--- a/ts/packages/cli/src/utils/get-ancestors.ts
+++ b/ts/packages/cli/src/utils/get-ancestors.ts
@@ -1,20 +1,22 @@
-import path from 'node:path';
+import { Path } from '@effect/platform';
+import { Effect } from 'effect';
/**
* Walk up from a directory to the filesystem root, collecting all ancestor paths.
* Returns an array starting with the resolved `cwd` and ending at the root.
*/
-export const getAncestors = (cwd: string): string[] => {
- const resolved = path.resolve(cwd);
- const dirs = [resolved];
- let current = resolved;
+export const getAncestors = (cwd: string): Effect.Effect<string[], never, Path.Path> =>
+ Effect.map(Path.Path, path => {
+ const resolved = path.resolve(cwd);
+ const dirs = [resolved];
+ let current = resolved;
- while (true) {
- const parent = path.dirname(current);
- if (parent === current) break;
- dirs.push(parent);
- current = parent;
- }
+ while (true) {
+ const parent = path.dirname(current);
+ if (parent === current) break;
+ dirs.push(parent);
+ current = parent;
+ }
- return dirs;
-};
+ return dirs;
+ });
diff --git a/ts/packages/cli/test/__utils__/services/test-layer.ts b/ts/packages/cli/test/__utils__/services/test-layer.ts
index e8a28cb03..1bcc22c4a 100644
--- a/ts/packages/cli/test/__utils__/services/test-layer.ts
+++ b/ts/packages/cli/test/__utils__/services/test-layer.ts
@@ -787,11 +787,12 @@ export const TestLayer = (input?: TestLiveInput) =>
})
);
- // Mock `node:os`
+ // Mock operating-system details
const NodeOsTest = Layer.succeed(
NodeOs,
new NodeOs({
homedir: cwd,
+ tmpdir: tempy.rootTemporaryDirectory,
arch: 'arm64',
platform: 'darwin',
})
@@ -809,7 +810,7 @@ export const TestLayer = (input?: TestLiveInput) =>
const ComposioUserContextTest = Layer.provideMerge(
ComposioUserContextLive,
- Layer.merge(BunFileSystem.layer, NodeOsTest)
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest)
);
let rawCliUserConfig = CliUserConfig.make({
@@ -832,7 +833,7 @@ export const TestLayer = (input?: TestLiveInput) =>
developerModeEnabled: rawCliUserConfig.developer.enabled,
developerDangerousCommandsEnabled: rawCliUserConfig.developer.destructiveActions,
experimentalFeatures: rawCliUserConfig.experimentalFeatures,
- artifactDirectory: undefined,
+ artifactDirectory: Option.getOrUndefined(rawCliUserConfig.artifactDirectory),
experimentalSubagentTarget: 'auto' as const,
security: 'auto' as const,
};
diff --git a/ts/packages/cli/test/__utils__/typescript-compiler.ts b/ts/packages/cli/test/__utils__/typescript-compiler.ts
index 08d4ffa26..b16317882 100644
--- a/ts/packages/cli/test/__utils__/typescript-compiler.ts
+++ b/ts/packages/cli/test/__utils__/typescript-compiler.ts
@@ -1,6 +1,7 @@
import { describe, it, expect, vi } from 'vitest';
import { Effect, Stream, String } from 'effect';
-import { Command } from '@effect/platform';
+import { Command, Path } from '@effect/platform';
+import { BunPath } from '@effect/platform-bun';
import ts from 'typescript';
import {
buildVirtualFileMap,
@@ -8,6 +9,10 @@ import {
patchCompilerHostWithVirtualFiles,
} from 'src/generation/typescript/virtual-compiler-host';
+// The ts.CompilerHost callbacks are synchronous, so the sync Path service
+// instance is resolved once up front and passed in as a plain parameter.
+const path = Effect.runSync(Effect.provide(Path.Path, BunPath.layer));
+
interface AssertTypeScriptIsValidInput {
files: {
[filename: string]: string;
@@ -53,7 +58,7 @@ export function assertTypeScriptIsValid({ files }: AssertTypeScriptIsValidInput)
const virtualFileNames = Array.from(virtualFileMap.keys());
const tsHost = ts.createCompilerHost(compilerOptions);
- patchCompilerHostWithVirtualFiles(tsHost, virtualFileMap, 'throw');
+ patchCompilerHostWithVirtualFiles(tsHost, virtualFileMap, path, 'throw');
const program = ts.createProgram(virtualFileNames, compilerOptions, tsHost);
@@ -162,7 +167,7 @@ if (import.meta.vitest) {
tsHost.getSourceFile = getSourceFile;
tsHost.fileExists = fileExists;
- patchCompilerHostWithVirtualFiles(tsHost, virtualFileMap, 'throw');
+ patchCompilerHostWithVirtualFiles(tsHost, virtualFileMap, path, 'throw');
expect(tsHost.fileExists('node_modules/@composio/core/index.d.ts')).toBe(false);
expect(() =>
diff --git a/ts/packages/cli/test/src/commands/run.cmd.test.ts b/ts/packages/cli/test/src/commands/run.cmd.test.ts
index dd83f99fc..430f63393 100644
--- a/ts/packages/cli/test/src/commands/run.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/run.cmd.test.ts
@@ -3,7 +3,9 @@ import * as os from 'node:os';
import * as path from 'node:path';
import { pathToFileURL } from 'node:url';
import { describe, expect, layer } from '@effect/vitest';
-import { Effect } from 'effect';
+import { Path } from '@effect/platform';
+import { BunContext } from '@effect/platform-bun';
+import { Effect, Exit } from 'effect';
import { afterEach, it, vi } from 'vitest';
import {
buildRunHelpersSource,
@@ -42,12 +44,11 @@ describe('CLI: composio run', () => {
Effect.gen(function* () {
const spawn = vi.fn(() => ({ exited: Promise.resolve(7) }));
const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
- const stderrWrite = vi
- .spyOn(process.stderr, 'write')
- .mockImplementation((() => true) as never);
+ const stderrWrite = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
vi.stubGlobal('Bun', { spawn });
yield* cli(['run', 'console.log("hi")', '--flag', 'value']);
+ const output = stderrWrite.mock.calls.map(([chunk]) => String(chunk));
expect(spawn).toHaveBeenCalledTimes(1);
const spawnConfig = (spawn as any).mock.calls[0][0] as {
@@ -70,9 +71,7 @@ describe('CLI: composio run', () => {
})
);
expect(spawnConfig.stdio).toEqual(['inherit', 'inherit', 'inherit']);
- expect(stderrWrite).toHaveBeenCalledWith(
- expect.stringMatching(/^RUN_LOG_FILE=.*run\.log\n$/)
- );
+ expect(output).toContainEqual(expect.stringMatching(/^RUN_LOG_FILE=.*run\.log\n$/));
expect(exit).toHaveBeenCalledWith(7);
})
);
@@ -211,7 +210,7 @@ describe('CLI: composio run', () => {
it.scoped('[Given] no inline code and no --file [Then] it fails with a clear error', () =>
Effect.gen(function* () {
const exit = yield* cli(['run']).pipe(Effect.exit);
- expect(exit._tag).toBe('Failure');
+ expect(Exit.isFailure(exit)).toBe(true);
})
);
});
@@ -245,17 +244,23 @@ describe('CLI: composio run', () => {
describe('buildRunHelpersSource', () => {
it('[Given] consumer context [Then] it embeds auth and consumer metadata in the helper source', () => {
- const source = buildRunHelpersSource(['/tmp/composio'], {
- apiKey: 'test_api_key',
- baseURL: 'https://api.example.test',
- webURL: 'https://app.example.test',
- orgId: 'org_test',
- consumerUserId: 'consumer_user_test',
- acpOnly: true,
- logsOff: true,
- dryRun: true,
- runLogFilePath: '/tmp/composio-run/run.log',
- });
+ const source = buildRunHelpersSource(
+ ['/tmp/composio'],
+ {
+ apiKey: 'test_api_key',
+ baseURL: 'https://api.example.test',
+ webURL: 'https://app.example.test',
+ orgId: 'org_test',
+ consumerUserId: 'consumer_user_test',
+ acpOnly: true,
+ logsOff: true,
+ dryRun: true,
+ runLogFilePath: '/tmp/composio-run/run.log',
+ },
+ {
+ helpersRuntimeModuleUrl: pathToFileURL('/tmp/composio-run/run-helpers-runtime.mjs').href,
+ }
+ );
expect(source).toContain('import { installRunHelpers } from "file://');
expect(source).toContain('await installRunHelpers(');
@@ -382,191 +387,231 @@ describe('run-subagent-shared', () => {
});
describe('inferCliInvocationPrefix', () => {
- it('[Given] a compiled bunfs entrypoint [Then] it falls back to the binary path only', () => {
- expect(inferCliInvocationPrefix(['node', '/$bunfs/root/composio'])).toEqual([process.execPath]);
+ layer(Path.layer)(it => {
+ it.effect(
+ '[Given] a compiled bunfs entrypoint [Then] it falls back to the binary path only',
+ () =>
+ Effect.gen(function* () {
+ const pathService = yield* Path.Path;
+ expect(inferCliInvocationPrefix(pathService, ['node', '/$bunfs/root/composio'])).toEqual([
+ process.execPath,
+ ]);
+ })
+ );
});
});
describe('resolveRunCompanionModulePath', () => {
- it('[Given] a bundled dist chunk [Then] it resolves sibling companion modules in dist', () => {
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-companion-dist-'));
- const callerPath = path.join(tempDir, 'commands-abc.mjs');
- const servicesDir = path.join(tempDir, 'services');
- const companionPath = path.join(servicesDir, 'run-subagent-shared.mjs');
- fs.writeFileSync(callerPath, '', 'utf8');
- fs.mkdirSync(servicesDir);
- fs.writeFileSync(companionPath, '', 'utf8');
-
- expect(
- resolveRunCompanionModulePath({
- callerImportMetaUrl: pathToFileURL(callerPath).href,
- execPath: '/tmp/composio',
- relativeNoExtensionFromCaller: '../services/run-subagent-shared',
- })
- ).toBe(companionPath);
- });
-
- it('[Given] a compiled bunfs caller [Then] it falls back to modules next to the binary', () => {
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-companion-bin-'));
- const execPath = path.join(tempDir, 'composio');
- const companionPath = path.join(tempDir, 'run-subagent-shared.mjs');
- fs.writeFileSync(companionPath, '', 'utf8');
+ layer(BunContext.layer)(it => {
+ it.effect(
+ '[Given] a bundled dist chunk [Then] it resolves sibling companion modules in dist',
+ () =>
+ Effect.gen(function* () {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-companion-dist-'));
+ const callerPath = path.join(tempDir, 'commands-abc.mjs');
+ const servicesDir = path.join(tempDir, 'services');
+ const companionPath = path.join(servicesDir, 'run-subagent-shared.mjs');
+ fs.writeFileSync(callerPath, '', 'utf8');
+ fs.mkdirSync(servicesDir);
+ fs.writeFileSync(companionPath, '', 'utf8');
+
+ expect(
+ yield* resolveRunCompanionModulePath({
+ callerImportMetaUrl: pathToFileURL(callerPath).href,
+ execPath: '/tmp/composio',
+ relativeNoExtensionFromCaller: '../services/run-subagent-shared',
+ })
+ ).toBe(companionPath);
+ })
+ );
- expect(
- resolveRunCompanionModulePath({
- callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
- execPath,
- relativeNoExtensionFromCaller: '../services/run-subagent-shared',
- })
- ).toBe(companionPath);
+ it.effect(
+ '[Given] a compiled bunfs caller [Then] it falls back to modules next to the binary',
+ () =>
+ Effect.gen(function* () {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-companion-bin-'));
+ const execPath = path.join(tempDir, 'composio');
+ const companionPath = path.join(tempDir, 'run-subagent-shared.mjs');
+ fs.writeFileSync(companionPath, '', 'utf8');
+
+ expect(
+ yield* resolveRunCompanionModulePath({
+ callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
+ execPath,
+ relativeNoExtensionFromCaller: '../services/run-subagent-shared',
+ })
+ ).toBe(companionPath);
+ })
+ );
});
});
describe('run companion install metadata', () => {
- it('[Given] an installed release tag file [Then] run helpers can read it back from the install dir', () => {
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-release-tag-'));
- const execPath = path.join(tempDir, 'composio');
-
- writeInstalledReleaseTag(tempDir, '@composio/[email protected]');
-
- expect(readInstalledReleaseTag(execPath)).toBe('@composio/[email protected]');
- });
-
- it('[Given] a partial companion install [Then] it reports only the missing companion files', () => {
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-'));
- const execPath = path.join(tempDir, 'composio');
- fs.writeFileSync(path.join(tempDir, RUN_COMPANION_MODULE_FILENAMES[0]!), '', 'utf8');
-
- expect(listMissingInstalledRunCompanionModules(execPath)).toEqual(
- [...RUN_COMPANION_MODULE_FILENAMES.slice(1), ...RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS]
- .slice()
- .sort()
- );
- });
+ layer(BunContext.layer)(it => {
+ it.effect(
+ '[Given] an installed release tag file [Then] run helpers can read it back from the install dir',
+ () =>
+ Effect.gen(function* () {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-release-tag-'));
+ const execPath = path.join(tempDir, 'composio');
- it('[Given] a nested companion dependency is missing [Then] it reports the missing helper asset', () => {
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-nested-'));
- const execPath = path.join(tempDir, 'composio');
- const servicesDir = path.join(tempDir, 'services');
- fs.mkdirSync(servicesDir, { recursive: true });
+ yield* writeInstalledReleaseTag(tempDir, '@composio/[email protected]');
- fs.writeFileSync(
- path.join(tempDir, 'run-helpers-runtime.mjs'),
- 'export * from "./services/run-helpers-runtime.mjs";\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(tempDir, 'run-subagent-shared.mjs'),
- 'export * from "./services/run-subagent-shared.mjs";\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(tempDir, 'run-subagent-acp.mjs'),
- 'export * from "./services/run-subagent-acp.mjs";\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(tempDir, 'run-subagent-legacy.mjs'),
- 'export * from "./services/run-subagent-legacy.mjs";\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(tempDir, 'run-subagent-output-mcp.mjs'),
- 'export * from "./services/run-subagent-output-mcp.mjs";\n',
- 'utf8'
+ expect(yield* readInstalledReleaseTag(execPath)).toBe('@composio/[email protected]');
+ })
);
- fs.writeFileSync(
- path.join(servicesDir, 'run-helpers-runtime.mjs'),
- 'export const runtimeValue = 1;\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(servicesDir, 'run-subagent-shared.mjs'),
- 'export const x = 1;\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(servicesDir, 'run-subagent-acp.mjs'),
- 'export * from "../run-companion-modules-abc123.mjs";\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(servicesDir, 'run-subagent-legacy.mjs'),
- 'export const y = 1;\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(servicesDir, 'run-subagent-output-mcp.mjs'),
- 'export const z = 1;\n',
- 'utf8'
+ it.effect(
+ '[Given] a partial companion install [Then] it reports only the missing companion files',
+ () =>
+ Effect.gen(function* () {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-'));
+ const execPath = path.join(tempDir, 'composio');
+ fs.writeFileSync(path.join(tempDir, RUN_COMPANION_MODULE_FILENAMES[0]!), '', 'utf8');
+
+ expect(yield* listMissingInstalledRunCompanionModules(execPath)).toEqual(
+ [
+ ...RUN_COMPANION_MODULE_FILENAMES.slice(1),
+ ...RUN_COMPANION_STATIC_ASSET_RELATIVE_PATHS,
+ ]
+ .slice()
+ .sort()
+ );
+ })
);
- expect(listMissingInstalledRunCompanionModules(execPath)).toContain(
- 'run-companion-modules-abc123.mjs'
- );
- });
+ it.effect(
+ '[Given] a nested companion dependency is missing [Then] it reports the missing helper asset',
+ () =>
+ Effect.gen(function* () {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-nested-'));
+ const execPath = path.join(tempDir, 'composio');
+ const servicesDir = path.join(tempDir, 'services');
+ fs.mkdirSync(servicesDir, { recursive: true });
+
+ fs.writeFileSync(
+ path.join(tempDir, 'run-helpers-runtime.mjs'),
+ 'export * from "./services/run-helpers-runtime.mjs";\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(tempDir, 'run-subagent-shared.mjs'),
+ 'export * from "./services/run-subagent-shared.mjs";\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(tempDir, 'run-subagent-acp.mjs'),
+ 'export * from "./services/run-subagent-acp.mjs";\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(tempDir, 'run-subagent-legacy.mjs'),
+ 'export * from "./services/run-subagent-legacy.mjs";\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(tempDir, 'run-subagent-output-mcp.mjs'),
+ 'export * from "./services/run-subagent-output-mcp.mjs";\n',
+ 'utf8'
+ );
- it('[Given] a named re-export dependency is missing [Then] it reports the missing helper asset', () => {
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-reexport-'));
- const execPath = path.join(tempDir, 'composio');
- const servicesDir = path.join(tempDir, 'services');
- fs.mkdirSync(servicesDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(servicesDir, 'run-helpers-runtime.mjs'),
+ 'export const runtimeValue = 1;\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(servicesDir, 'run-subagent-shared.mjs'),
+ 'export const x = 1;\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(servicesDir, 'run-subagent-acp.mjs'),
+ 'export * from "../run-companion-modules-abc123.mjs";\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(servicesDir, 'run-subagent-legacy.mjs'),
+ 'export const y = 1;\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(servicesDir, 'run-subagent-output-mcp.mjs'),
+ 'export const z = 1;\n',
+ 'utf8'
+ );
- fs.writeFileSync(
- path.join(tempDir, 'run-helpers-runtime.mjs'),
- 'export * from "./services/run-helpers-runtime.mjs";\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(tempDir, 'run-subagent-shared.mjs'),
- 'export * from "./services/run-subagent-shared.mjs";\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(tempDir, 'run-subagent-acp.mjs'),
- 'export * from "./services/run-subagent-acp.mjs";\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(tempDir, 'run-subagent-legacy.mjs'),
- 'export * from "./services/run-subagent-legacy.mjs";\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(tempDir, 'run-subagent-output-mcp.mjs'),
- 'export * from "./services/run-subagent-output-mcp.mjs";\n',
- 'utf8'
+ expect(yield* listMissingInstalledRunCompanionModules(execPath)).toContain(
+ 'run-companion-modules-abc123.mjs'
+ );
+ })
);
- fs.writeFileSync(
- path.join(servicesDir, 'run-helpers-runtime.mjs'),
- 'export const runtimeValue = 1;\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(servicesDir, 'run-subagent-shared.mjs'),
- 'export const sharedValue = 1;\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(servicesDir, 'run-subagent-acp.mjs'),
- 'export { helperValue } from "../run-companion-modules-def456.mjs";\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(servicesDir, 'run-subagent-legacy.mjs'),
- 'export const legacyValue = 1;\n',
- 'utf8'
- );
- fs.writeFileSync(
- path.join(servicesDir, 'run-subagent-output-mcp.mjs'),
- 'export const outputValue = 1;\n',
- 'utf8'
- );
+ it.effect(
+ '[Given] a named re-export dependency is missing [Then] it reports the missing helper asset',
+ () =>
+ Effect.gen(function* () {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-missing-reexport-'));
+ const execPath = path.join(tempDir, 'composio');
+ const servicesDir = path.join(tempDir, 'services');
+ fs.mkdirSync(servicesDir, { recursive: true });
+
+ fs.writeFileSync(
+ path.join(tempDir, 'run-helpers-runtime.mjs'),
+ 'export * from "./services/run-helpers-runtime.mjs";\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(tempDir, 'run-subagent-shared.mjs'),
+ 'export * from "./services/run-subagent-shared.mjs";\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(tempDir, 'run-subagent-acp.mjs'),
+ 'export * from "./services/run-subagent-acp.mjs";\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(tempDir, 'run-subagent-legacy.mjs'),
+ 'export * from "./services/run-subagent-legacy.mjs";\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(tempDir, 'run-subagent-output-mcp.mjs'),
+ 'export * from "./services/run-subagent-output-mcp.mjs";\n',
+ 'utf8'
+ );
+
+ fs.writeFileSync(
+ path.join(servicesDir, 'run-helpers-runtime.mjs'),
+ 'export const runtimeValue = 1;\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(servicesDir, 'run-subagent-shared.mjs'),
+ 'export const sharedValue = 1;\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(servicesDir, 'run-subagent-acp.mjs'),
+ 'export { helperValue } from "../run-companion-modules-def456.mjs";\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(servicesDir, 'run-subagent-legacy.mjs'),
+ 'export const legacyValue = 1;\n',
+ 'utf8'
+ );
+ fs.writeFileSync(
+ path.join(servicesDir, 'run-subagent-output-mcp.mjs'),
+ 'export const outputValue = 1;\n',
+ 'utf8'
+ );
- expect(listMissingInstalledRunCompanionModules(execPath)).toContain(
- 'run-companion-modules-def456.mjs'
+ expect(yield* listMissingInstalledRunCompanionModules(execPath)).toContain(
+ 'run-companion-modules-def456.mjs'
+ );
+ })
);
});
});
diff --git a/ts/packages/cli/test/src/effects/detect-platform.test.ts b/ts/packages/cli/test/src/effects/detect-platform.test.ts
index 3ca0248bf..5b1c2b861 100644
--- a/ts/packages/cli/test/src/effects/detect-platform.test.ts
+++ b/ts/packages/cli/test/src/effects/detect-platform.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from '@effect/vitest';
-import { Effect, Layer } from 'effect';
+import { Effect, Layer, Predicate } from 'effect';
import {
detectPlatform,
UnsupportedPlatformError,
@@ -15,6 +15,7 @@ const createMockNodeOs = <P extends NodeJS.Platform>(platform: P, arch: string)
NodeOs,
NodeOs.make({
homedir: '/mock/home',
+ tmpdir: '/tmp',
platform: platform as NodeJS.Platform,
arch: arch as NodeJS.Architecture,
})
@@ -347,7 +348,7 @@ describe('detect-platform.ts', () => {
const error = new UnsupportedPlatformError({ platform: 'test', arch: 'test' });
expect(error).toBeInstanceOf(Error);
expect(error).toBeInstanceOf(UnsupportedPlatformError);
- expect(error._tag).toBe('UnsupportedPlatformError');
+ expect(Predicate.isTagged(error, 'UnsupportedPlatformError')).toBe(true);
});
it('should contain platform and arch information', () => {
@@ -364,24 +365,26 @@ describe('detect-platform.ts', () => {
});
describe('Type Tests', () => {
- it('should return correct PlatformArch type for supported combinations', async () => {
- // This test verifies TypeScript types at runtime
- const testType = async (platform: string, arch: string): Promise<PlatformArch> => {
- return await Effect.runPromise(
- detectPlatform.pipe(Effect.provide(createMockNodeOs(platform as NodeJS.Platform, arch)))
- );
- };
-
- // These calls should compile without TypeScript errors
- await expect(testType('darwin', 'x64')).resolves.toEqual({ platform: 'darwin', arch: 'x64' });
- await expect(testType('darwin', 'arm64')).resolves.toEqual({
- platform: 'darwin',
- arch: 'aarch64',
- });
- await expect(testType('linux', 'aarch64')).resolves.toEqual({
- platform: 'linux',
- arch: 'aarch64',
- });
- });
+ it.effect('should return correct PlatformArch type for supported combinations', () =>
+ Effect.gen(function* () {
+ // This test verifies TypeScript types at runtime
+ const testType = (
+ platform: string,
+ arch: string
+ ): Effect.Effect<PlatformArch, UnsupportedPlatformError> =>
+ detectPlatform.pipe(Effect.provide(createMockNodeOs(platform as NodeJS.Platform, arch)));
+
+ // These calls should compile without TypeScript errors
+ expect(yield* testType('darwin', 'x64')).toEqual({ platform: 'darwin', arch: 'x64' });
+ expect(yield* testType('darwin', 'arm64')).toEqual({
+ platform: 'darwin',
+ arch: 'aarch64',
+ });
+ expect(yield* testType('linux', 'aarch64')).toEqual({
+ platform: 'linux',
+ arch: 'aarch64',
+ });
+ })
+ );
});
});
diff --git a/ts/packages/cli/test/src/generation/safe-output-path.test.ts b/ts/packages/cli/test/src/generation/safe-output-path.test.ts
index c8ac6671a..1219b98d1 100644
--- a/ts/packages/cli/test/src/generation/safe-output-path.test.ts
+++ b/ts/packages/cli/test/src/generation/safe-output-path.test.ts
@@ -1,5 +1,6 @@
import path from 'node:path';
import { describe, expect, it, assert } from '@effect/vitest';
+import { BunPath } from '@effect/platform-bun';
import { Effect, Either } from 'effect';
import { safeOutputPath, SafeOutputPathError } from 'src/generation/safe-output-path';
@@ -12,7 +13,7 @@ describe('safeOutputPath', () => {
expect(filePath).toBe(path.join(outputDir, 'gmail.ts'));
expect(path.isAbsolute(filePath)).toBe(false);
- })
+ }, Effect.provide(BunPath.layer))
);
it.effect(
@@ -25,7 +26,7 @@ describe('safeOutputPath', () => {
assert(Either.isLeft(result));
expect(result.left).toBeInstanceOf(SafeOutputPathError);
expect(result.left.filename).toBe(path.resolve('gmail.ts'));
- })
+ }, Effect.provide(BunPath.layer))
);
it.effect(
@@ -36,6 +37,6 @@ describe('safeOutputPath', () => {
assert(Either.isLeft(result));
expect(result.left).toBeInstanceOf(SafeOutputPathError);
expect(result.left.filename).toBe('../gmail.ts');
- })
+ }, Effect.provide(BunPath.layer))
);
});
diff --git a/ts/packages/cli/test/src/generation/typescript/generate.test.ts b/ts/packages/cli/test/src/generation/typescript/generate.test.ts
index a96110313..230407a61 100644
--- a/ts/packages/cli/test/src/generation/typescript/generate.test.ts
+++ b/ts/packages/cli/test/src/generation/typescript/generate.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from '@effect/vitest';
+import { BunPath } from '@effect/platform-bun';
import { createToolkitIndex } from 'src/generation/create-toolkit-index';
import { generateTypeScriptSources } from 'src/generation/typescript/generate';
import { makeTestToolkits } from 'test/__utils__/models/toolkits';
@@ -67,7 +68,7 @@ describe('generateTypeScriptSources', () => {
`);
assertTypeScriptIsValid({ files: { './index.ts': source } });
- })
+ }, Effect.provide(BunPath.layer))
);
it.effect(
@@ -156,7 +157,7 @@ describe('generateTypeScriptSources', () => {
assertTypeScriptIsValid({
files: { './index.ts': sources[1][1], './slack.ts': sources[0][1] },
});
- })
+ }, Effect.provide(BunPath.layer))
);
it.effect(
@@ -247,7 +248,7 @@ describe('generateTypeScriptSources', () => {
assertTypeScriptIsValid({
files: { './index.ts': sources[1][1], './slack.ts': sources[0][1] },
});
- })
+ }, Effect.provide(BunPath.layer))
);
});
});
diff --git a/ts/packages/cli/test/src/services/cli-session-artifacts.test.ts b/ts/packages/cli/test/src/services/cli-session-artifacts.test.ts
new file mode 100644
index 000000000..0a92c050d
--- /dev/null
+++ b/ts/packages/cli/test/src/services/cli-session-artifacts.test.ts
@@ -0,0 +1,183 @@
+import { FileSystem, Path } from '@effect/platform';
+import { describe, expect, layer } from '@effect/vitest';
+import { afterEach, vi } from 'vitest';
+import { ConfigProvider, Effect, Option } from 'effect';
+import * as tempy from 'tempy';
+import {
+ appendCliSessionHistory,
+ resolveArtifactsRoot,
+ resolveCliSessionArtifacts,
+ storeCliSessionArtifact,
+} from 'src/services/cli-session-artifacts';
+import { ComposioCliUserConfig } from 'src/services/cli-user-config';
+import { extendConfigProvider } from 'src/services/config';
+import { defaultNodeOs, NodeOs } from 'src/services/node-os';
+import { TestLive } from 'test/__utils__';
+
+const cacheEnabledTestConfigProvider = ConfigProvider.fromMap(
+ new Map([['COMPOSIO_DISABLE_CONNECTED_ACCOUNT_CACHE', 'false']])
+).pipe(extendConfigProvider);
+
+describe('CLI session artifacts', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ layer(TestLive())(it => {
+ it.scoped('resolves artifact roots in documented precedence order', () =>
+ Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const config = yield* ComposioCliUserConfig;
+ const sessionRoot = tempy.temporaryDirectory();
+ const cacheRoot = tempy.temporaryDirectory();
+ const configuredRoot = tempy.temporaryDirectory();
+ const temporaryRoot = tempy.temporaryDirectory();
+ const root = resolveArtifactsRoot.pipe(
+ Effect.provideService(
+ NodeOs,
+ defaultNodeOs({ homedir: tempy.temporaryDirectory(), tmpdir: temporaryRoot })
+ )
+ );
+
+ yield* config.update({ artifactDirectory: Option.some(configuredRoot) });
+ vi.stubEnv('COMPOSIO_SESSION_DIR', sessionRoot);
+ vi.stubEnv('COMPOSIO_CACHE_DIR', cacheRoot);
+ expect(yield* root).toBe(sessionRoot);
+
+ vi.stubEnv('COMPOSIO_SESSION_DIR', ' ');
+ expect(yield* root).toBe(cacheRoot);
+
+ vi.stubEnv('COMPOSIO_CACHE_DIR', ' ');
+ expect(yield* root).toBe(configuredRoot);
+
+ yield* config.update({ artifactDirectory: Option.none() });
+ expect(yield* root).toBe(path.join(temporaryRoot, 'composio'));
+ })
+ );
+
+ it.scoped('stores a sanitized artifact with the requested extension', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directoryPath = yield* fs.makeTempDirectoryScoped();
+
+ const filePath = yield* storeCliSessionArtifact({
+ contents: '{"ok":true}',
+ name: 'github issue output',
+ extension: '.json',
+ directoryPath,
+ });
+
+ expect(filePath).toBeDefined();
+ if (filePath === undefined) {
+ return yield* Effect.die('Expected the session artifact to be stored');
+ }
+ expect(path.dirname(filePath)).toBe(directoryPath);
+ expect(path.basename(filePath)).toMatch(/^github_issue_output_[a-f0-9]{8}\.json$/i);
+ expect(yield* fs.readFileString(filePath)).toBe('{"ok":true}');
+ })
+ );
+
+ it.scoped('returns undefined when the artifact directory cannot be created', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const filePath = yield* fs.makeTempFileScoped();
+
+ expect(
+ yield* storeCliSessionArtifact({
+ contents: '{}',
+ name: 'output',
+ directoryPath: filePath,
+ })
+ ).toBeUndefined();
+ })
+ );
+
+ it.scoped('stores an adhoc artifact when no CLI session is available', () =>
+ Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const artifactsRoot = tempy.temporaryDirectory();
+ vi.stubEnv('COMPOSIO_SESSION_DIR', artifactsRoot);
+
+ const filePath = yield* storeCliSessionArtifact({
+ contents: '{}',
+ name: 'adhoc output',
+ });
+
+ expect(filePath).toBeDefined();
+ if (filePath === undefined) {
+ return yield* Effect.die('Expected an adhoc artifact');
+ }
+ const directoryPath = path.dirname(filePath);
+ expect(path.dirname(directoryPath)).toBe(artifactsRoot);
+ expect(path.basename(directoryPath)).toMatch(/^adhoc_[a-f0-9]{12}$/i);
+ })
+ );
+ });
+
+ layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(it => {
+ const sessionScope = {
+ orgId: 'org_test',
+ consumerUserId: 'consumer-user-test',
+ } as const;
+
+ it.scoped('stores artifacts under the current CLI session without a directory override', () =>
+ Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const artifactsRoot = tempy.temporaryDirectory();
+ vi.stubEnv('COMPOSIO_SESSION_DIR', artifactsRoot);
+
+ const filePath = yield* storeCliSessionArtifact({
+ contents: '{"session":true}',
+ name: 'session output',
+ ...sessionScope,
+ });
+
+ expect(filePath).toBeDefined();
+ if (filePath === undefined) {
+ return yield* Effect.die('Expected a session-backed artifact');
+ }
+ const directoryPath = path.dirname(filePath);
+ expect(path.dirname(directoryPath)).toBe(artifactsRoot);
+ expect(path.basename(directoryPath)).toMatch(/^cli_s_[a-z0-9]+_[a-f0-9]{10}$/i);
+ })
+ );
+
+ it.scoped('appends multiple JSONL history entries to the same session', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const artifactsRoot = tempy.temporaryDirectory();
+ vi.stubEnv('COMPOSIO_SESSION_DIR', artifactsRoot);
+
+ yield* appendCliSessionHistory({ entry: { sequence: 1 }, ...sessionScope });
+ yield* appendCliSessionHistory({ entry: { sequence: 2 }, ...sessionScope });
+ const artifacts = yield* resolveCliSessionArtifacts(sessionScope);
+
+ expect(Option.isSome(artifacts)).toBe(true);
+ if (Option.isNone(artifacts)) {
+ return yield* Effect.die('Expected session artifacts');
+ }
+ const lines = (yield* fs.readFileString(artifacts.value.historyFilePath, 'utf8'))
+ .trim()
+ .split('\n')
+ .map(line => JSON.parse(line) as { sessionId: string; sequence: number });
+ expect(lines).toEqual([
+ expect.objectContaining({ sessionId: artifacts.value.sessionId, sequence: 1 }),
+ expect.objectContaining({ sessionId: artifacts.value.sessionId, sequence: 2 }),
+ ]);
+ })
+ );
+
+ it.scoped('keeps history writes best-effort when the artifact root is not a directory', () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const rootFile = yield* fs.makeTempFileScoped();
+ vi.stubEnv('COMPOSIO_SESSION_DIR', rootFile);
+
+ yield* appendCliSessionHistory({ entry: { sequence: 1 }, ...sessionScope });
+
+ expect(yield* fs.readFileString(rootFile, 'utf8')).toBe('');
+ })
+ );
+ });
+});
diff --git a/ts/packages/cli/test/src/services/cli-user-config.test.ts b/ts/packages/cli/test/src/services/cli-user-config.test.ts
index a6a9f3c1d..5158a1c47 100644
--- a/ts/packages/cli/test/src/services/cli-user-config.test.ts
+++ b/ts/packages/cli/test/src/services/cli-user-config.test.ts
@@ -4,7 +4,7 @@ import fs from 'node:fs';
import { describe, it, vi } from '@effect/vitest';
import { assertEquals } from '@effect/vitest/utils';
import { FileSystem } from '@effect/platform';
-import { BunFileSystem } from '@effect/platform-bun';
+import { BunFileSystem, BunPath } from '@effect/platform-bun';
import { ConfigProvider, Effect, Layer } from 'effect';
import { extendConfigProvider } from 'src/services/config';
import { defaultNodeOs, NodeOs } from 'src/services/node-os';
@@ -24,7 +24,7 @@ describe('ComposioCliUserConfig', () => {
const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
const CliUserConfigTest = Layer.provideMerge(
ComposioCliUserConfigLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
);
return Effect.gen(function* () {
@@ -55,7 +55,7 @@ describe('ComposioCliUserConfig', () => {
const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
const CliUserConfigTest = Layer.provideMerge(
ComposioCliUserConfigLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
);
return Effect.gen(function* () {
@@ -76,7 +76,7 @@ describe('ComposioCliUserConfig', () => {
const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
const CliUserConfigTest = Layer.provideMerge(
ComposioCliUserConfigLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
);
return Effect.gen(function* () {
@@ -117,7 +117,7 @@ describe('ComposioCliUserConfig', () => {
const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
const CliUserConfigTest = Layer.provideMerge(
ComposioCliUserConfigLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
);
return Effect.gen(function* () {
@@ -170,7 +170,7 @@ describe('ComposioCliUserConfig', () => {
const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
const CliUserConfigTest = Layer.provideMerge(
ComposioCliUserConfigLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
);
return Effect.gen(function* () {
@@ -205,6 +205,30 @@ describe('ComposioCliUserConfig', () => {
assertEquals(parsed.developer_dangerous_commands_enabled, undefined);
}).pipe(Effect.provide(CliUserConfigTest));
});
+
+ it.scoped('replaces malformed persisted config with safe defaults', () => {
+ const cwd = tempy.temporaryDirectory();
+ const map = new Map([['DEBUG_OVERRIDE_VERSION', '1.2.3']]) satisfies Map<string, string>;
+ fs.mkdirSync(path.join(cwd, '.composio'), { recursive: true });
+ fs.writeFileSync(path.join(cwd, '.composio', 'config.json'), JSON.stringify(['not-an-object']));
+
+ const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
+ const CliUserConfigTest = Layer.provideMerge(
+ ComposioCliUserConfigLive,
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
+ );
+
+ return Effect.gen(function* () {
+ const config = yield* ComposioCliUserConfig;
+ assertEquals(config.data.developerModeEnabled, true);
+ assertEquals(config.data.developerDangerousCommandsEnabled, false);
+ assertEquals(config.data.security, 'auto');
+
+ const persisted = fs.readFileSync(path.join(cwd, '.composio', 'config.json'), 'utf8');
+ assertEquals(Array.isArray(JSON.parse(persisted)), false);
+ }).pipe(Effect.provide(CliUserConfigTest));
+ });
+
it.effect('resolves sync config path from COMPOSIO_CACHE_DIR when provided', () => {
const cacheDir = tempy.temporaryDirectory();
process.env.COMPOSIO_CACHE_DIR = cacheDir;
diff --git a/ts/packages/cli/test/src/services/composio-client-singleton.test.ts b/ts/packages/cli/test/src/services/composio-client-singleton.test.ts
index 8d8960870..a242777f2 100644
--- a/ts/packages/cli/test/src/services/composio-client-singleton.test.ts
+++ b/ts/packages/cli/test/src/services/composio-client-singleton.test.ts
@@ -1,6 +1,7 @@
-import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
-import { BunFileSystem } from '@effect/platform-bun';
-import { ConfigProvider, Effect, Layer, Option } from 'effect';
+import { afterEach, beforeAll, describe, expect, it, vi } from '@effect/vitest';
+import { FileSystem, Path } from '@effect/platform';
+import { BunFileSystem, BunPath } from '@effect/platform-bun';
+import { ConfigProvider, Effect, Layer } from 'effect';
import { execSync } from 'node:child_process';
import * as tempy from 'tempy';
import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -11,6 +12,7 @@ import { extendConfigProvider } from 'src/services/config';
const withConfigLayer = (map: Map<string, string>, homedir: string) =>
Layer.mergeAll(
BunFileSystem.layer,
+ BunPath.layer,
Layer.succeed(NodeOs, defaultNodeOs({ homedir })),
Layer.setConfigProvider(extendConfigProvider(ConfigProvider.fromMap(map)))
);
@@ -21,6 +23,35 @@ const okResponse = () =>
headers: { 'Content-Type': 'application/json' },
});
+const cwdHash = (cwd: string): string => {
+ let hash = 5381;
+ for (let index = 0; index < cwd.length; index += 1) {
+ hash = (hash * 33) ^ cwd.charCodeAt(index);
+ }
+ return Math.abs(hash >>> 0).toString(36);
+};
+
+const writeCliSessionCache = (
+ homedir: string,
+ session: { readonly id: string; readonly expiresAt: string }
+) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const cacheDir = path.join(homedir, '.composio');
+ yield* fs.makeDirectory(cacheDir, { recursive: true });
+ yield* fs.writeFileString(
+ path.join(cacheDir, 'consumer-short-term-cache.json'),
+ JSON.stringify({
+ test: {
+ probablyMyCliSessionsByCwdHash: {
+ [cwdHash(process.cwd())]: session,
+ },
+ },
+ })
+ );
+ });
+
describe('ComposioClientSingleton headers', () => {
// Delete any real keychain entry so the subprocess keyring read
// inside ComposioUserContextLive (baked into
@@ -40,9 +71,10 @@ describe('ComposioClientSingleton headers', () => {
afterEach(() => {
vi.restoreAllMocks();
+ vi.unstubAllEnvs();
});
- it('uses x-user-api-key and never x-api-key', async () => {
+ it.effect('uses x-user-api-key and never x-api-key', () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
const homedir = tempy.temporaryDirectory();
const configMap = new Map([
@@ -51,7 +83,7 @@ describe('ComposioClientSingleton headers', () => {
['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
]);
- const program = Effect.gen(function* () {
+ return Effect.gen(function* () {
const client = yield* ComposioClientSingleton.get();
yield* Effect.promise(() =>
client.tools
@@ -59,35 +91,78 @@ describe('ComposioClientSingleton headers', () => {
.then(() => undefined)
.catch(() => undefined)
);
+
+ expect(fetchSpy).toHaveBeenCalledOnce();
+ const [, init] = fetchSpy.mock.calls[0]!;
+ const headers = new Headers((init as RequestInit).headers);
+
+ expect(headers.get('x-user-api-key')).toBe('uak_from_user_env');
+ expect(headers.has('x-api-key')).toBe(false);
+ expect(headers.get('x-framework')).toBe('cli');
+ expect(headers.get('x-source')).toBe('CLI');
+ expect(headers.get('x-runtime')).toBe('NODEJS');
+ expect(headers.get('x-sdk-version')).toBe(APP_VERSION);
+ expect(headers.get('x-cli-session-id')).toBeNull();
}).pipe(
Effect.provide(
Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
)
);
+ });
- await Effect.runPromise(program);
+ // Fixed instants far in the future/past keep the expiry comparison
+ // deterministic regardless of the clock the session-id reader consults.
+ it.effect('includes the current cwd CLI session ID', () => {
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
+ const homedir = tempy.temporaryDirectory();
+ const configMap = new Map([
+ ['COMPOSIO_USER_API_KEY', 'uak_from_user_env'],
+ ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
+ ]);
- expect(fetchSpy).toHaveBeenCalledOnce();
- const [, init] = fetchSpy.mock.calls[0]!;
- const headers = new Headers((init as RequestInit).headers);
+ return Effect.gen(function* () {
+ const path = yield* Path.Path;
+ // The session-id reader resolves its cache dir from COMPOSIO_CACHE_DIR
+ // (stubbed by the shared vitest setup) before falling back to homedir,
+ // so point it at the directory this test writes the fixture into.
+ vi.stubEnv('COMPOSIO_CACHE_DIR', path.join(homedir, '.composio'));
+ yield* writeCliSessionCache(homedir, {
+ id: 'cli_s_current',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ });
+ const client = yield* ComposioClientSingleton.get();
+ yield* Effect.promise(() =>
+ client.tools
+ .list({ limit: 1, toolkit_versions: 'latest' })
+ .then(() => undefined)
+ .catch(() => undefined)
+ );
- expect(headers.get('x-user-api-key')).toBe('uak_from_user_env');
- expect(headers.has('x-api-key')).toBe(false);
- expect(headers.get('x-framework')).toBe('cli');
- expect(headers.get('x-source')).toBe('CLI');
- expect(headers.get('x-runtime')).toBe('NODEJS');
- expect(headers.get('x-sdk-version')).toBe(APP_VERSION);
+ const [, init] = fetchSpy.mock.calls[0]!;
+ const headers = new Headers((init as RequestInit).headers);
+ expect(headers.get('x-cli-session-id')).toBe('cli_s_current');
+ }).pipe(
+ Effect.provide(
+ Layer.provideMerge(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
+ )
+ );
});
- it('does not read COMPOSIO_API_KEY for user auth', async () => {
+ it.effect('omits an expired cwd CLI session ID', () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
const homedir = tempy.temporaryDirectory();
const configMap = new Map([
- ['COMPOSIO_API_KEY', 'ak_only'],
+ ['COMPOSIO_USER_API_KEY', 'uak_from_user_env'],
['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
]);
- const program = Effect.gen(function* () {
+ return Effect.gen(function* () {
+ const path = yield* Path.Path;
+ vi.stubEnv('COMPOSIO_CACHE_DIR', path.join(homedir, '.composio'));
+ yield* writeCliSessionCache(homedir, {
+ id: 'cli_s_expired',
+ expiresAt: '1970-01-01T00:01:00.000Z',
+ });
const client = yield* ComposioClientSingleton.get();
yield* Effect.promise(() =>
client.tools
@@ -95,20 +170,45 @@ describe('ComposioClientSingleton headers', () => {
.then(() => undefined)
.catch(() => undefined)
);
+
+ const [, init] = fetchSpy.mock.calls[0]!;
+ const headers = new Headers((init as RequestInit).headers);
+ expect(headers.get('x-cli-session-id')).toBeNull();
}).pipe(
Effect.provide(
- Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
+ Layer.provideMerge(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
)
);
+ });
+
+ it.effect('does not read COMPOSIO_API_KEY for user auth', () => {
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(okResponse());
+ const homedir = tempy.temporaryDirectory();
+ const configMap = new Map([
+ ['COMPOSIO_API_KEY', 'ak_only'],
+ ['COMPOSIO_BASE_URL', 'https://backend.composio.dev'],
+ ]);
- await Effect.runPromise(program);
+ return Effect.gen(function* () {
+ const client = yield* ComposioClientSingleton.get();
+ yield* Effect.promise(() =>
+ client.tools
+ .list({ limit: 1, toolkit_versions: 'latest' })
+ .then(() => undefined)
+ .catch(() => undefined)
+ );
- expect(fetchSpy).toHaveBeenCalledOnce();
- const [, init] = fetchSpy.mock.calls[0]!;
- const headers = new Headers((init as RequestInit).headers);
+ expect(fetchSpy).toHaveBeenCalledOnce();
+ const [, init] = fetchSpy.mock.calls[0]!;
+ const headers = new Headers((init as RequestInit).headers);
- expect(headers.get('x-user-api-key')).toBeNull();
- expect(headers.has('x-api-key')).toBe(false);
- expect(headers.get('x-source')).toBe('CLI');
+ expect(headers.get('x-user-api-key')).toBeNull();
+ expect(headers.has('x-api-key')).toBe(false);
+ expect(headers.get('x-source')).toBe('CLI');
+ }).pipe(
+ Effect.provide(
+ Layer.provide(ComposioClientSingleton.Default, withConfigLayer(configMap, homedir))
+ )
+ );
});
});
diff --git a/ts/packages/cli/test/src/services/detached-process.test.ts b/ts/packages/cli/test/src/services/detached-process.test.ts
new file mode 100644
index 000000000..186da56b9
--- /dev/null
+++ b/ts/packages/cli/test/src/services/detached-process.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from '@effect/vitest';
+import { Effect } from 'effect';
+import { DetachedProcessSpawnError, spawnDetached } from 'src/services/detached-process';
+
+describe('spawnDetached', () => {
+ it.effect('fails when the executable does not exist', () =>
+ Effect.gen(function* () {
+ const command = '__composio_missing_detached_process__';
+ const error = yield* spawnDetached(command, []).pipe(Effect.flip);
+
+ expect(error).toBeInstanceOf(DetachedProcessSpawnError);
+ expect(error.command).toBe(command);
+ expect(String(error.cause)).toContain('ENOENT');
+ })
+ );
+
+ it.effect('succeeds after the child process spawns', () =>
+ Effect.gen(function* () {
+ yield* spawnDetached(process.execPath, ['-e', 'process.exit(0)']);
+ })
+ );
+});
diff --git a/ts/packages/cli/test/src/services/node-os.test.ts b/ts/packages/cli/test/src/services/node-os.test.ts
new file mode 100644
index 000000000..ca73cb5a6
--- /dev/null
+++ b/ts/packages/cli/test/src/services/node-os.test.ts
@@ -0,0 +1,33 @@
+import os from 'node:os';
+import { describe, expect, it } from '@effect/vitest';
+import { Effect } from 'effect';
+import { defaultNodeOs, NodeOs } from 'src/services/node-os';
+
+describe('NodeOs', () => {
+ it.effect('exposes operating-system details through an Effect service', () =>
+ Effect.gen(function* () {
+ const nodeOs = yield* NodeOs;
+
+ expect(nodeOs).toMatchObject({
+ homedir: os.homedir(),
+ tmpdir: os.tmpdir(),
+ platform: os.platform(),
+ arch: os.arch(),
+ });
+ }).pipe(Effect.provide(NodeOs.Default))
+ );
+
+ it('supports deterministic home and temporary directories in tests', () => {
+ expect(
+ defaultNodeOs({
+ homedir: '/test/home',
+ tmpdir: '/test/tmp',
+ })
+ ).toMatchObject({
+ homedir: '/test/home',
+ tmpdir: '/test/tmp',
+ platform: os.platform(),
+ arch: os.arch(),
+ });
+ });
+});
diff --git a/ts/packages/cli/test/src/services/run-companion-modules.test.ts b/ts/packages/cli/test/src/services/run-companion-modules.test.ts
new file mode 100644
index 000000000..4bf111c0c
--- /dev/null
+++ b/ts/packages/cli/test/src/services/run-companion-modules.test.ts
@@ -0,0 +1,130 @@
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { BunContext } from '@effect/platform-bun';
+import { afterEach, describe, expect, layer, vi } from '@effect/vitest';
+import { Effect } from 'effect';
+import { repairMissingInstalledRunCompanionModules } from 'src/services/run-companion-modules';
+import { BaseConfigProviderLive, extendConfigProvider } from 'src/services/config';
+
+describe('run-companion-modules', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ });
+
+ layer(BunContext.layer)(it => {
+ it.effect(
+ '[Given] malformed release metadata [Then] repair rejects it before using release assets',
+ () => {
+ const installDirectory = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'composio-run-repair-test-')
+ );
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ tag_name: 123, assets: 'invalid' }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ );
+ vi.stubGlobal('fetch', fetchMock);
+
+ return Effect.gen(function* () {
+ const error = yield* repairMissingInstalledRunCompanionModules({
+ callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
+ execPath: path.join(installDirectory, 'composio'),
+ appVersion: '0.0.0-test',
+ }).pipe(Effect.flip);
+
+ expect(error.message).toContain("Unable to restore the files required by 'composio run'");
+ expect(fetchMock).toHaveBeenCalledOnce();
+ }).pipe(
+ Effect.ensuring(
+ Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
+ )
+ );
+ }
+ );
+
+ it.effect(
+ '[Given] unprefixed GITHUB_* env under the CLI-wide prefixed provider [Then] repair honors the unprefixed contract',
+ () => {
+ const installDirectory = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'composio-run-repair-test-')
+ );
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ tag_name: 123, assets: 'invalid' }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubEnv('GITHUB_TAG', '@composio/[email protected]');
+ vi.stubEnv('GITHUB_API_BASE_URL', 'https://github-proxy.test');
+ vi.stubEnv('GITHUB_OWNER', 'fork-owner');
+ vi.stubEnv('GITHUB_REPO', 'fork-repo');
+
+ return Effect.gen(function* () {
+ yield* repairMissingInstalledRunCompanionModules({
+ callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
+ execPath: path.join(installDirectory, 'composio'),
+ appVersion: '0.0.0-test',
+ }).pipe(Effect.flip);
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const requestUrl = String(fetchMock.mock.calls[0]?.[0]);
+ expect(requestUrl).toBe(
+ 'https://github-proxy.test/repos/fork-owner/fork-repo/releases/tags/%40composio%2Fcli%409.9.9-test'
+ );
+ }).pipe(
+ // Simulate the cli-main runtime, whose provider rewrites config keys
+ // to their COMPOSIO_-prefixed spelling.
+ Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive)),
+ Effect.ensuring(
+ Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
+ )
+ );
+ }
+ );
+
+ it.effect(
+ '[Given] only COMPOSIO_-prefixed GITHUB_* env [Then] repair falls back to the prefixed spelling',
+ () => {
+ const installDirectory = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'composio-run-repair-test-')
+ );
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ tag_name: 123, assets: 'invalid' }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubEnv('GITHUB_TAG', undefined);
+ vi.stubEnv('GITHUB_API_BASE_URL', undefined);
+ vi.stubEnv('GITHUB_OWNER', undefined);
+ vi.stubEnv('GITHUB_REPO', undefined);
+ vi.stubEnv('COMPOSIO_GITHUB_TAG', '@composio/[email protected]');
+ vi.stubEnv('COMPOSIO_GITHUB_API_BASE_URL', 'https://prefixed-proxy.test');
+
+ return Effect.gen(function* () {
+ yield* repairMissingInstalledRunCompanionModules({
+ callerImportMetaUrl: 'file:///$bunfs/root/commands.mjs',
+ execPath: path.join(installDirectory, 'composio'),
+ appVersion: '0.0.0-test',
+ }).pipe(Effect.flip);
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const requestUrl = String(fetchMock.mock.calls[0]?.[0]);
+ expect(requestUrl).toBe(
+ 'https://prefixed-proxy.test/repos/ComposioHQ/composio/releases/tags/%40composio%2Fcli%408.8.8-test'
+ );
+ }).pipe(
+ Effect.withConfigProvider(extendConfigProvider(BaseConfigProviderLive)),
+ Effect.ensuring(
+ Effect.sync(() => fs.rmSync(installDirectory, { recursive: true, force: true }))
+ )
+ );
+ }
+ );
+ });
+});
diff --git a/ts/packages/cli/test/src/services/setup-skill-installer.test.ts b/ts/packages/cli/test/src/services/setup-skill-installer.test.ts
index dcb2f9db9..d39d45510 100644
--- a/ts/packages/cli/test/src/services/setup-skill-installer.test.ts
+++ b/ts/packages/cli/test/src/services/setup-skill-installer.test.ts
@@ -26,7 +26,9 @@ describe('SetupSkillInstaller', () => {
'@composio/[email protected]\n'
);
- expect(resolveSetupSkillReleaseTag(execPath, '0.3.0')).toBe('@composio/[email protected]');
+ expect(yield* resolveSetupSkillReleaseTag(execPath, '0.3.0')).toBe(
+ '@composio/[email protected]'
+ );
})
);
@@ -35,7 +37,7 @@ describe('SetupSkillInstaller', () => {
const path = yield* Path.Path;
const installDir = tempy.temporaryDirectory();
- expect(resolveSetupSkillReleaseTag(path.join(installDir, 'composio'), '0.3.0')).toBe(
+ expect(yield* resolveSetupSkillReleaseTag(path.join(installDir, 'composio'), '0.3.0')).toBe(
'@composio/[email protected]'
);
})
diff --git a/ts/packages/cli/test/src/services/upgrade-binary.test.ts b/ts/packages/cli/test/src/services/upgrade-binary.test.ts
index 9e9439562..43b2a5568 100644
--- a/ts/packages/cli/test/src/services/upgrade-binary.test.ts
+++ b/ts/packages/cli/test/src/services/upgrade-binary.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from '@effect/vitest';
import { ConfigProvider, Effect, Layer } from 'effect';
-import { FetchHttpClient } from '@effect/platform';
+import { FetchHttpClient, Path } from '@effect/platform';
import { BunFileSystem } from '@effect/platform-bun';
import { existsSync, mkdirSync, readFileSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -42,6 +42,7 @@ const NodeOsTest = Layer.succeed(
NodeOs,
new NodeOs({
homedir: '/tmp',
+ tmpdir: '/tmp',
platform: 'darwin',
arch: 'arm64',
})
@@ -71,286 +72,311 @@ const runUpgrade = (
options?: {
prerelease?: boolean;
}
-) => makeUpgradeEffect(configEntries, options).pipe(Effect.flip, Effect.runPromise);
+) => makeUpgradeEffect(configEntries, options).pipe(Effect.flip);
const runUpgradeSuccess = (
configEntries: ReadonlyArray<[string, string]>,
options?: {
prerelease?: boolean;
}
-) => makeUpgradeEffect(configEntries, options).pipe(Effect.runPromise);
+) => makeUpgradeEffect(configEntries, options);
+
+/**
+ * Bridge the promise-based `withHttpServer` harness into a scoped Effect:
+ * acquisition starts the server and yields its base URL, and closing the
+ * test scope lets `withHttpServer` run its teardown path.
+ */
+const scopedHttpServer = (handler: Parameters<typeof withHttpServer>[0]) =>
+ Effect.acquireRelease(
+ Effect.promise(
+ () =>
+ new Promise<{ baseUrl: string; release: () => void; closed: Promise<void> }>(
+ (resolveAcquire, rejectAcquire) => {
+ let release!: () => void;
+ const released = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const closed = withHttpServer(handler, baseUrl => {
+ resolveAcquire({ baseUrl, release, closed });
+ return released;
+ });
+ closed.catch(rejectAcquire);
+ }
+ )
+ ),
+ ({ release, closed }) =>
+ Effect.promise(() => {
+ release();
+ return closed;
+ })
+ ).pipe(Effect.map(({ baseUrl }) => baseUrl));
+
+const restoreStubsAndMocks = Effect.sync(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
describe('UpgradeBinary', () => {
- it('wraps non-2xx releases fetch failures with fetch context (no tag branch)', async () => {
+ it.scoped('wraps non-2xx releases fetch failures with fetch context (no tag branch)', () => {
vi.stubGlobal('Bun', { which: vi.fn(() => null) });
- try {
- await withHttpServer(
- (_req, res) => {
- res.writeHead(500, { 'content-type': 'application/json' });
- res.end(JSON.stringify({ message: 'rate limited' }));
- },
- async apiBaseUrl => {
- const error = await runUpgrade([
- ['GITHUB_API_BASE_URL', apiBaseUrl],
- ['GITHUB_OWNER', 'test-owner'],
- ['GITHUB_REPO', 'test-repo'],
- ]);
-
- expect(error).toBeInstanceOf(UpgradeBinaryError);
- if (!(error instanceof UpgradeBinaryError)) {
- throw error;
- }
- expect(error.message).toBe('Failed to fetch releases from GitHub');
- expect(String(error.cause)).toContain('HTTP 500');
- }
- );
- } finally {
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
- }
+ return Effect.gen(function* () {
+ const apiBaseUrl = yield* scopedHttpServer((_req, res) => {
+ res.writeHead(500, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ message: 'rate limited' }));
+ });
+
+ const error = yield* runUpgrade([
+ ['GITHUB_API_BASE_URL', apiBaseUrl],
+ ['GITHUB_OWNER', 'test-owner'],
+ ['GITHUB_REPO', 'test-repo'],
+ ]);
+
+ expect(error).toBeInstanceOf(UpgradeBinaryError);
+ if (!(error instanceof UpgradeBinaryError)) {
+ throw error;
+ }
+ expect(error.message).toBe('Failed to fetch releases from GitHub');
+ expect(String(error.cause)).toContain('HTTP 500');
+ }).pipe(Effect.ensuring(restoreStubsAndMocks));
});
- it('wraps tagged release JSON parse failures with parse context (tag branch)', async () => {
+ it.scoped('wraps tagged release JSON parse failures with parse context (tag branch)', () => {
vi.stubGlobal('Bun', { which: vi.fn(() => null) });
- try {
- await withHttpServer(
- (_req, res) => {
- res.writeHead(200, { 'content-type': 'application/json' });
- res.end('not-json');
- },
- async apiBaseUrl => {
- const error = await runUpgrade([
- ['GITHUB_API_BASE_URL', apiBaseUrl],
- ['GITHUB_OWNER', 'test-owner'],
- ['GITHUB_REPO', 'test-repo'],
- ['GITHUB_TAG', 'v9.9.9'],
- ]);
-
- expect(error).toBeInstanceOf(UpgradeBinaryError);
- if (!(error instanceof UpgradeBinaryError)) {
- throw error;
- }
- expect(error.message).toBe('Failed to parse GitHub release JSON response');
- }
- );
- } finally {
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
- }
+ return Effect.gen(function* () {
+ const apiBaseUrl = yield* scopedHttpServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end('not-json');
+ });
+
+ const error = yield* runUpgrade([
+ ['GITHUB_API_BASE_URL', apiBaseUrl],
+ ['GITHUB_OWNER', 'test-owner'],
+ ['GITHUB_REPO', 'test-repo'],
+ ['GITHUB_TAG', 'v9.9.9'],
+ ]);
+
+ expect(error).toBeInstanceOf(UpgradeBinaryError);
+ if (!(error instanceof UpgradeBinaryError)) {
+ throw error;
+ }
+ expect(error.message).toBe('Failed to parse GitHub release JSON response');
+ }).pipe(Effect.ensuring(restoreStubsAndMocks));
});
- it('URL-encodes slash-containing tags in tagged release request path', async () => {
+ it.scoped('rejects structurally invalid tagged release JSON', () => {
+ vi.stubGlobal('Bun', { which: vi.fn(() => null) });
+
+ return Effect.gen(function* () {
+ const apiBaseUrl = yield* scopedHttpServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ tag_name: 42, assets: 'not-an-array' }));
+ });
+
+ const error = yield* runUpgrade([
+ ['GITHUB_API_BASE_URL', apiBaseUrl],
+ ['GITHUB_OWNER', 'test-owner'],
+ ['GITHUB_REPO', 'test-repo'],
+ ['GITHUB_TAG', 'v9.9.9'],
+ ]);
+
+ expect(error).toBeInstanceOf(UpgradeBinaryError);
+ if (!(error instanceof UpgradeBinaryError)) {
+ throw error;
+ }
+ expect(error.message).toBe('Failed to parse GitHub release JSON response');
+ }).pipe(Effect.ensuring(restoreStubsAndMocks));
+ });
+
+ it.scoped('URL-encodes slash-containing tags in tagged release request path', () => {
vi.stubGlobal('Bun', { which: vi.fn(() => null) });
let receivedPath = '';
- try {
- await withHttpServer(
- (req, res) => {
- receivedPath = req.url ?? '';
- res.writeHead(500, { 'content-type': 'application/json' });
- res.end(JSON.stringify({ message: 'forced failure' }));
- },
- async apiBaseUrl => {
- const tag = '@composio/[email protected]';
- const error = await runUpgrade([
- ['GITHUB_API_BASE_URL', apiBaseUrl],
- ['GITHUB_OWNER', 'test-owner'],
- ['GITHUB_REPO', 'test-repo'],
- ['GITHUB_TAG', tag],
- ]);
-
- expect(error).toBeInstanceOf(UpgradeBinaryError);
- if (!(error instanceof UpgradeBinaryError)) {
- throw error;
- }
- expect(receivedPath).toBe(
- `/repos/test-owner/test-repo/releases/tags/${encodeURIComponent(tag)}`
- );
- }
+ return Effect.gen(function* () {
+ const apiBaseUrl = yield* scopedHttpServer((req, res) => {
+ receivedPath = req.url ?? '';
+ res.writeHead(500, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ message: 'forced failure' }));
+ });
+
+ const tag = '@composio/[email protected]';
+ const error = yield* runUpgrade([
+ ['GITHUB_API_BASE_URL', apiBaseUrl],
+ ['GITHUB_OWNER', 'test-owner'],
+ ['GITHUB_REPO', 'test-repo'],
+ ['GITHUB_TAG', tag],
+ ]);
+
+ expect(error).toBeInstanceOf(UpgradeBinaryError);
+ if (!(error instanceof UpgradeBinaryError)) {
+ throw error;
+ }
+ expect(receivedPath).toBe(
+ `/repos/test-owner/test-repo/releases/tags/${encodeURIComponent(tag)}`
);
- } finally {
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
- }
+ }).pipe(Effect.ensuring(restoreStubsAndMocks));
});
- it('skips newer releases that do not contain a binary for the current platform', async () => {
+ it.scoped('skips newer releases that do not contain a binary for the current platform', () => {
vi.stubGlobal('Bun', { which: vi.fn(() => null) });
- try {
- await withHttpServer(
- (_req, res) => {
- res.writeHead(200, { 'content-type': 'application/json' });
- res.end(
- JSON.stringify([
- {
- tag_name: '@composio/[email protected]',
- draft: false,
- prerelease: false,
- assets: [
- {
- name: 'composio-linux-x64.zip',
- browser_download_url: 'http://127.0.0.1/unused-linux.zip',
- },
- ],
- },
- {
- tag_name: '@composio/[email protected]',
- draft: false,
- prerelease: false,
- assets: [
- {
- name: 'composio-darwin-aarch64.zip',
- browser_download_url: 'http://127.0.0.1/current-darwin.zip',
- },
- ],
- },
- ])
- );
- },
- async apiBaseUrl => {
- const result = await runUpgradeSuccess([
- ['GITHUB_API_BASE_URL', apiBaseUrl],
- ['GITHUB_OWNER', 'test-owner'],
- ['GITHUB_REPO', 'test-repo'],
- ]);
-
- expect(result).toBeUndefined();
- }
- );
- } finally {
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
- }
+ return Effect.gen(function* () {
+ const apiBaseUrl = yield* scopedHttpServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(
+ JSON.stringify([
+ {
+ tag_name: '@composio/[email protected]',
+ draft: false,
+ prerelease: false,
+ assets: [
+ {
+ name: 'composio-linux-x64.zip',
+ browser_download_url: 'http://127.0.0.1/unused-linux.zip',
+ },
+ ],
+ },
+ {
+ tag_name: '@composio/[email protected]',
+ draft: false,
+ prerelease: false,
+ assets: [
+ {
+ name: 'composio-darwin-aarch64.zip',
+ browser_download_url: 'http://127.0.0.1/current-darwin.zip',
+ },
+ ],
+ },
+ ])
+ );
+ });
+
+ const result = yield* runUpgradeSuccess([
+ ['GITHUB_API_BASE_URL', apiBaseUrl],
+ ['GITHUB_OWNER', 'test-owner'],
+ ['GITHUB_REPO', 'test-repo'],
+ ]);
+
+ expect(result).toBeUndefined();
+ }).pipe(Effect.ensuring(restoreStubsAndMocks));
});
- it('ignores prereleases when checking the stable channel', async () => {
+ it.scoped('ignores prereleases when checking the stable channel', () => {
vi.stubGlobal('Bun', { which: vi.fn(() => null) });
- try {
- await withHttpServer(
- (_req, res) => {
- res.writeHead(200, { 'content-type': 'application/json' });
- res.end(
- JSON.stringify([
- {
- tag_name: '@composio/[email protected]',
- draft: false,
- prerelease: true,
- assets: [
- {
- name: 'composio-darwin-aarch64.zip',
- browser_download_url: 'http://127.0.0.1/beta.zip',
- },
- ],
- },
- {
- tag_name: '@composio/[email protected]',
- draft: false,
- prerelease: false,
- assets: [
- {
- name: 'composio-darwin-aarch64.zip',
- browser_download_url: 'http://127.0.0.1/stable.zip',
- },
- ],
- },
- ])
- );
- },
- async apiBaseUrl => {
- const result = await runUpgradeSuccess([
- ['GITHUB_API_BASE_URL', apiBaseUrl],
- ['GITHUB_OWNER', 'test-owner'],
- ['GITHUB_REPO', 'test-repo'],
- ]);
-
- expect(result).toBeUndefined();
- }
- );
- } finally {
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
- }
+ return Effect.gen(function* () {
+ const apiBaseUrl = yield* scopedHttpServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(
+ JSON.stringify([
+ {
+ tag_name: '@composio/[email protected]',
+ draft: false,
+ prerelease: true,
+ assets: [
+ {
+ name: 'composio-darwin-aarch64.zip',
+ browser_download_url: 'http://127.0.0.1/beta.zip',
+ },
+ ],
+ },
+ {
+ tag_name: '@composio/[email protected]',
+ draft: false,
+ prerelease: false,
+ assets: [
+ {
+ name: 'composio-darwin-aarch64.zip',
+ browser_download_url: 'http://127.0.0.1/stable.zip',
+ },
+ ],
+ },
+ ])
+ );
+ });
+
+ const result = yield* runUpgradeSuccess([
+ ['GITHUB_API_BASE_URL', apiBaseUrl],
+ ['GITHUB_OWNER', 'test-owner'],
+ ['GITHUB_REPO', 'test-repo'],
+ ]);
+
+ expect(result).toBeUndefined();
+ }).pipe(Effect.ensuring(restoreStubsAndMocks));
});
- it('selects the latest prerelease when beta upgrades are requested', async () => {
+ it.scoped('selects the latest prerelease when beta upgrades are requested', () => {
const installDir = mkdtempSync(path.join(tmpdir(), 'composio-beta-select-'));
const fakeExecPath = path.join(installDir, 'composio');
writeFileSync(path.join(installDir, 'release-tag.txt'), '@composio/[email protected]\n');
vi.stubGlobal('Bun', { which: vi.fn(() => null) });
const execPathSpy = vi.spyOn(process, 'execPath', 'get').mockReturnValue(fakeExecPath);
- try {
- await withHttpServer(
- (_req, res) => {
- res.writeHead(200, { 'content-type': 'application/json' });
- res.end(
- JSON.stringify([
- {
- tag_name: '@composio/[email protected]',
- draft: false,
- prerelease: true,
- assets: [
- {
- name: 'composio-darwin-aarch64.zip',
- browser_download_url: 'http://127.0.0.1/beta-1.zip',
- },
- ],
- },
- {
- tag_name: '@composio/[email protected]',
- draft: false,
- prerelease: true,
- assets: [
- {
- name: 'composio-darwin-aarch64.zip',
- browser_download_url: 'http://127.0.0.1/beta-3.zip',
- },
- ],
- },
- {
- tag_name: '@composio/[email protected]',
- draft: false,
- prerelease: false,
- assets: [
- {
- name: 'composio-darwin-aarch64.zip',
- browser_download_url: 'http://127.0.0.1/stable.zip',
- },
- ],
- },
- ])
- );
- },
- async apiBaseUrl => {
- const error = await runUpgrade(
- [
- ['GITHUB_API_BASE_URL', apiBaseUrl],
- ['GITHUB_OWNER', 'test-owner'],
- ['GITHUB_REPO', 'test-repo'],
- ],
- { prerelease: true }
- );
-
- expect(error).toBeInstanceOf(UpgradeBinaryError);
- if (!(error instanceof UpgradeBinaryError)) {
- throw error;
- }
- expect(error.message).toBe('Failed to download binary: composio-darwin-aarch64.zip');
- expect(String(error.cause)).toContain('beta-3.zip');
- }
+ return Effect.gen(function* () {
+ const apiBaseUrl = yield* scopedHttpServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(
+ JSON.stringify([
+ {
+ tag_name: '@composio/[email protected]',
+ draft: false,
+ prerelease: true,
+ assets: [
+ {
+ name: 'composio-darwin-aarch64.zip',
+ browser_download_url: 'http://127.0.0.1/beta-1.zip',
+ },
+ ],
+ },
+ {
+ tag_name: '@composio/[email protected]',
+ draft: false,
+ prerelease: true,
+ assets: [
+ {
+ name: 'composio-darwin-aarch64.zip',
+ browser_download_url: 'http://127.0.0.1/beta-3.zip',
+ },
+ ],
+ },
+ {
+ tag_name: '@composio/[email protected]',
+ draft: false,
+ prerelease: false,
+ assets: [
+ {
+ name: 'composio-darwin-aarch64.zip',
+ browser_download_url: 'http://127.0.0.1/stable.zip',
+ },
+ ],
+ },
+ ])
+ );
+ });
+
+ const error = yield* runUpgrade(
+ [
+ ['GITHUB_API_BASE_URL', apiBaseUrl],
+ ['GITHUB_OWNER', 'test-owner'],
+ ['GITHUB_REPO', 'test-repo'],
+ ],
+ { prerelease: true }
);
- } finally {
- execPathSpy.mockRestore();
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
- }
+
+ expect(error).toBeInstanceOf(UpgradeBinaryError);
+ if (!(error instanceof UpgradeBinaryError)) {
+ throw error;
+ }
+ expect(error.message).toBe('Failed to download binary: composio-darwin-aarch64.zip');
+ expect(String(error.cause)).toContain('beta-3.zip');
+ }).pipe(
+ Effect.ensuring(Effect.sync(() => execPathSpy.mockRestore())),
+ Effect.ensuring(restoreStubsAndMocks)
+ );
});
- it('copies local-tool bundled binary assets during local-target upgrades', async () => {
+ it.effect('copies local-tool bundled binary assets during local-target upgrades', () => {
const installDir = mkdtempSync(path.join(tmpdir(), 'composio-local-tool-upgrade-target-'));
const sourceDir = mkdtempSync(path.join(tmpdir(), 'composio-local-tool-upgrade-source-'));
const fakeExecPath = path.join(installDir, 'composio');
@@ -375,78 +401,78 @@ describe('UpgradeBinary', () => {
mkdirSync(path.dirname(sourceLocalToolPath), { recursive: true });
writeFileSync(sourceLocalToolPath, 'imessage-sidecar');
- for (const relativePath of collectExpectedRunCompanionAssetRelativePaths(sourceDir)) {
- const companionPath = path.join(sourceDir, relativePath);
- mkdirSync(path.dirname(companionPath), { recursive: true });
- writeFileSync(companionPath, 'support-file');
- }
-
vi.stubGlobal('Bun', { which: vi.fn(() => null) });
const execPathSpy = vi.spyOn(process, 'execPath', 'get').mockReturnValue(fakeExecPath);
- try {
- const result = await runUpgradeSuccess([['DEBUG_OVERRIDE_UPGRADE_TARGET', sourceBinaryPath]]);
+ return Effect.gen(function* () {
+ const companionRelativePaths = yield* collectExpectedRunCompanionAssetRelativePaths(
+ sourceDir
+ ).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, Path.layer)));
+ for (const relativePath of companionRelativePaths) {
+ const companionPath = path.join(sourceDir, relativePath);
+ mkdirSync(path.dirname(companionPath), { recursive: true });
+ writeFileSync(companionPath, 'support-file');
+ }
+
+ const result = yield* runUpgradeSuccess([
+ ['DEBUG_OVERRIDE_UPGRADE_TARGET', sourceBinaryPath],
+ ]);
expect(result).toBeUndefined();
expect(readFileSync(fakeExecPath, 'utf8')).toBe('new-binary');
expect(existsSync(installedLocalToolPath)).toBe(true);
expect(readFileSync(installedLocalToolPath, 'utf8')).toBe('imessage-sidecar');
- } finally {
- execPathSpy.mockRestore();
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
- }
+ }).pipe(
+ Effect.ensuring(Effect.sync(() => execPathSpy.mockRestore())),
+ Effect.ensuring(restoreStubsAndMocks)
+ );
});
- it('uses the installed beta release tag when comparing beta updates', async () => {
+ it.scoped('uses the installed beta release tag when comparing beta updates', () => {
const installDir = mkdtempSync(path.join(tmpdir(), 'composio-beta-upgrade-'));
const fakeExecPath = path.join(installDir, 'composio');
writeFileSync(path.join(installDir, 'release-tag.txt'), '@composio/[email protected]\n');
vi.stubGlobal('Bun', { which: vi.fn(() => null) });
const execPathSpy = vi.spyOn(process, 'execPath', 'get').mockReturnValue(fakeExecPath);
- try {
- await withHttpServer(
- (_req, res) => {
- res.writeHead(200, { 'content-type': 'application/json' });
- res.end(
- JSON.stringify([
- {
- tag_name: '@composio/[email protected]',
- draft: false,
- prerelease: true,
- assets: [
- {
- name: 'composio-darwin-aarch64.zip',
- browser_download_url: 'http://127.0.0.1/beta-3.zip',
- },
- ],
- },
- ])
- );
- },
- async apiBaseUrl => {
- const error = await runUpgrade(
- [
- ['GITHUB_API_BASE_URL', apiBaseUrl],
- ['GITHUB_OWNER', 'test-owner'],
- ['GITHUB_REPO', 'test-repo'],
- ],
- { prerelease: true }
- );
-
- expect(error).toBeInstanceOf(UpgradeBinaryError);
- if (!(error instanceof UpgradeBinaryError)) {
- throw error;
- }
- expect(error.message).toBe('Failed to download binary: composio-darwin-aarch64.zip');
- expect(String(error.cause)).toContain('beta-3.zip');
- }
+ return Effect.gen(function* () {
+ const apiBaseUrl = yield* scopedHttpServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(
+ JSON.stringify([
+ {
+ tag_name: '@composio/[email protected]',
+ draft: false,
+ prerelease: true,
+ assets: [
+ {
+ name: 'composio-darwin-aarch64.zip',
+ browser_download_url: 'http://127.0.0.1/beta-3.zip',
+ },
+ ],
+ },
+ ])
+ );
+ });
+
+ const error = yield* runUpgrade(
+ [
+ ['GITHUB_API_BASE_URL', apiBaseUrl],
+ ['GITHUB_OWNER', 'test-owner'],
+ ['GITHUB_REPO', 'test-repo'],
+ ],
+ { prerelease: true }
);
- } finally {
- execPathSpy.mockRestore();
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
- }
+
+ expect(error).toBeInstanceOf(UpgradeBinaryError);
+ if (!(error instanceof UpgradeBinaryError)) {
+ throw error;
+ }
+ expect(error.message).toBe('Failed to download binary: composio-darwin-aarch64.zip');
+ expect(String(error.cause)).toContain('beta-3.zip');
+ }).pipe(
+ Effect.ensuring(Effect.sync(() => execPathSpy.mockRestore())),
+ Effect.ensuring(restoreStubsAndMocks)
+ );
});
});
diff --git a/ts/packages/cli/test/src/services/user-context.test.ts b/ts/packages/cli/test/src/services/user-context.test.ts
index b2d96eb0f..915a97864 100644
--- a/ts/packages/cli/test/src/services/user-context.test.ts
+++ b/ts/packages/cli/test/src/services/user-context.test.ts
@@ -1,7 +1,7 @@
import { describe, it } from '@effect/vitest';
import { assertEquals } from '@effect/vitest/utils';
import { FileSystem } from '@effect/platform';
-import { BunFileSystem } from '@effect/platform-bun';
+import { BunFileSystem, BunPath } from '@effect/platform-bun';
import { ConfigProvider, Effect, Layer, Option, Data } from 'effect';
import * as tempy from 'tempy';
import { ComposioUserContext, rawComposioUserContextLive } from 'src/services/user-context';
@@ -86,7 +86,7 @@ describe('ComposioUserContext', () => {
const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
const ComposioUserContextTest = Layer.provideMerge(
ComposioUserContextLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
);
return Effect.gen(function* () {
@@ -117,7 +117,7 @@ describe('ComposioUserContext', () => {
const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
const ComposioUserContextTest = Layer.provideMerge(
ComposioUserContextLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
);
return Effect.gen(function* () {
@@ -143,7 +143,7 @@ describe('ComposioUserContext', () => {
const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
const ComposioUserContextTest = Layer.provideMerge(
ComposioUserContextLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
);
return Effect.gen(function* () {
@@ -165,7 +165,7 @@ describe('ComposioUserContext', () => {
const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
const ComposioUserContextTest = Layer.provideMerge(
ComposioUserContextLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
);
return Effect.gen(function* () {
@@ -205,7 +205,7 @@ describe('ComposioUserContext', () => {
const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
const ComposioUserContextTest = Layer.provideMerge(
ComposioUserContextLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
);
return Effect.gen(function* () {
@@ -246,7 +246,7 @@ describe('ComposioUserContext', () => {
const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
const ComposioUserContextTest = Layer.provideMerge(
ComposioUserContextLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
);
return Effect.gen(function* () {
@@ -288,7 +288,7 @@ describe('ComposioUserContext', () => {
const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
const ComposioUserContextTest = Layer.provideMerge(
ComposioUserContextLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
);
return Effect.gen(function* () {
@@ -325,7 +325,7 @@ describe('ComposioUserContext', () => {
const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
const ComposioUserContextTest = Layer.provideMerge(
ComposioUserContextLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
);
return Effect.gen(function* () {
@@ -365,7 +365,7 @@ describe('ComposioUserContext', () => {
const NodeOsTest = Layer.succeed(NodeOs, defaultNodeOs({ homedir: cwd }));
const ComposioUserContextTest = Layer.provideMerge(
ComposioUserContextLive,
- Layer.mergeAll(BunFileSystem.layer, NodeOsTest, withMapConfigProvider(map))
+ Layer.mergeAll(BunFileSystem.layer, BunPath.layer, NodeOsTest, withMapConfigProvider(map))
);
return Effect.gen(function* () {