Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
refactor(cli): enforce typed Effect error boundaries and v4 readiness seams (#3884)
Alberto Schiabelaaabe9922b07
diff --git a/ts/packages/cli/AGENTS.md b/ts/packages/cli/AGENTS.mdindex 16bca84ab..c8b3af9aa 100644--- a/ts/packages/cli/AGENTS.md+++ b/ts/packages/cli/AGENTS.md@@ -67,7 +67,6 @@ Options use `Options.text()`, `Options.boolean()`, `Options.choice()`, `Options.| `ComposioToolkitsRepository` | API client — fetches toolkits, tools, trigger types; validates versions || `ComposioToolkitsRepositoryCached` | Decorator over base repository with file-based caching and graceful fallback || `NodeOs` | OS abstraction (`homedir`, `platform`, `arch`) |-| `EnvLangDetector` | Detects project language (TS/Python) from config / lock files || `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions || `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |diff --git a/ts/packages/cli/scripts/build-all-binaries.ts b/ts/packages/cli/scripts/build-all-binaries.tsindex d7e4e10e5..9636c8eba 100644--- a/ts/packages/cli/scripts/build-all-binaries.ts+++ b/ts/packages/cli/scripts/build-all-binaries.ts@@ -12,11 +12,11 @@* Output: `dist/binaries/composio-*`*/-import process from 'node:process';import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLevel } from 'effect';import { Command } from '@effect/platform';import { BunContext, BunRuntime } from '@effect/platform-bun';import { buildCompanionModules, copyLocalToolBinaryAssets, teardown } from './_shared';+import { BinaryBuildError } from './build-error';/*** All cross-compilation targets and their artifact names.@@ -69,7 +69,11 @@ function runBunBuild(target: string, outfile: string) {);if (exitCode !== 0) {- return yield* Effect.fail(new Error(`Failed to build binary for ${target}`));+ return yield* new BinaryBuildError({+ message: `Failed to build binary for ${target}`,+ target,+ exitCode,+ });}});}diff --git a/ts/packages/cli/scripts/build-binary-cross.ts b/ts/packages/cli/scripts/build-binary-cross.tsindex d506d81cf..2b316385f 100644--- a/ts/packages/cli/scripts/build-binary-cross.ts+++ b/ts/packages/cli/scripts/build-binary-cross.ts@@ -19,6 +19,7 @@ import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLeveimport { Command } from '@effect/platform';import { BunContext, BunRuntime } from '@effect/platform-bun';import { buildCompanionModules, copyLocalToolBinaryAssets, teardown } from './_shared';+import { BinaryBuildError } from './build-error';/*** Maps Bun cross-compilation targets to Composio artifact names.@@ -103,7 +104,11 @@ export function buildBinaryCross() {process.exitCode = exitCode;if (exitCode !== 0) {- return yield* Effect.fail(new Error(`Failed to cross-compile binary for ${target}`));+ return yield* new BinaryBuildError({+ message: `Failed to cross-compile binary for ${target}`,+ target,+ exitCode,+ });}const companionOutputDir = './dist/binaries/companions';diff --git a/ts/packages/cli/scripts/build-binary.ts b/ts/packages/cli/scripts/build-binary.tsindex 25e7f0a57..31179a414 100644--- a/ts/packages/cli/scripts/build-binary.ts+++ b/ts/packages/cli/scripts/build-binary.ts@@ -3,6 +3,7 @@ import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLeveimport { Command } from '@effect/platform';import { BunContext, BunRuntime } from '@effect/platform-bun';import { buildCompanionModules, copyLocalToolBinaryAssets, teardown } from './_shared';+import { BinaryBuildError } from './build-error';/*** Usage: `bun scripts/build-binary.ts`@@ -68,7 +69,10 @@ export function buildBinary() {process.exitCode = exitCode;if (exitCode !== 0) {- return yield* Effect.fail(new Error('Failed to build binary'));+ return yield* new BinaryBuildError({+ message: 'Failed to build binary',+ exitCode,+ });}yield* Effect.logDebug('', 'Binary built successfully');diff --git a/ts/packages/cli/scripts/build-error.ts b/ts/packages/cli/scripts/build-error.tsnew file mode 100644index 000000000..e55549e17--- /dev/null+++ b/ts/packages/cli/scripts/build-error.ts@@ -0,0 +1,7 @@+import { Data } from 'effect';++export class BinaryBuildError extends Data.TaggedError('scripts/BinaryBuildError')<{+ readonly message: string;+ readonly target?: string;+ readonly exitCode: number;+}> {}diff --git a/ts/packages/cli/src/analytics/events.ts b/ts/packages/cli/src/analytics/events.tsindex a35e7bf62..e0f5e327f 100644--- a/ts/packages/cli/src/analytics/events.ts+++ b/ts/packages/cli/src/analytics/events.ts@@ -87,6 +87,9 @@ const TOOL_VALIDATION_CODES: ReadonlySet<number> = new Set([1607, // Upstream_ValidationError3702, // ComposioTools_ValidationError]);+// A parent `composio run` process hands these values to child CLI invocations through the+// environment at spawn time; the event builders below are plain synchronous functions that+// run outside any Effect context, so effect/Config is not available here.const getInvocationOrigin = (): string => process.env.COMPOSIO_CLI_INVOCATION_ORIGIN ?? 'cli';const getParentRunId = (): string | undefined => process.env.COMPOSIO_CLI_PARENT_RUN_ID;diff --git a/ts/packages/cli/src/cli-main.ts b/ts/packages/cli/src/cli-main.tsindex f80a1c9a5..0e9b513f2 100644--- a/ts/packages/cli/src/cli-main.ts+++ b/ts/packages/cli/src/cli-main.ts@@ -236,7 +236,7 @@ showUpdateNotice.pipe(stripCwd: true,});const filteredErrors = captured.errors.filter(- error => error.errorType !== 'ToolExecutionError'+ error => error.errorType !== 'ReportedToolExecutionError');if (captured.interrupted || filteredErrors.length > 0) {const message = prettyPrintFromCapturedErrors(diff --git a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.tsindex 220004db1..72af71f1f 100644--- a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts+++ b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts@@ -1,4 +1,4 @@-import { Args, Command, Options } from '@effect/cli';+import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';import { Data, Effect, Option, Schedule } from 'effect';import type { Composio as RawComposioClient } from '@composio/client';import open from 'open';@@ -27,6 +27,17 @@ import { ComposioCliUserConfig } from 'src/services/cli-user-config';import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';import { decodeConnectedAccountItemsWithFallback } from 'src/effects/decode-connected-account-list';+class ConnectionPollingError extends Data.TaggedError('commands/ConnectionPollingError')<{+ readonly message: string;+ readonly connectedAccountId: string;+ readonly status: string;+}> {}++class MissingLinkUserIdError extends Data.TaggedError('commands/MissingLinkUserIdError')<{+ readonly message: string;+ readonly flow: 'list' | 'legacy' | 'tool-router';+}> {}+class ConnectedAccountsDecodeError extends Data.TaggedError('commands/ConnectedAccountsDecodeError')<{@@ -34,6 +45,20 @@ class ConnectedAccountsDecodeError extends Data.TaggedError(readonly cause: unknown;}> {}+class ConnectedAccountsRequestError extends Data.TaggedError(+ 'commands/ConnectedAccountsRequestError'+)<{+ readonly message: string;+ readonly cause: unknown;+}> {}++class BrowserOpenError extends Data.TaggedError('commands/BrowserOpenError')<{+ readonly message: string;+ readonly cause: unknown;+}> {}++const invalidOptionValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));+const toolkit = Args.text({ name: 'toolkit' }).pipe(Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),Args.optional@@ -105,20 +130,21 @@ const waitForActiveConnection = (Effect.gen(function* () {yield* showRedirectUrl(ui, redirectUrl, { manual: noBrowser });- let urlSchemeValid = false;- try {- const parsed = new URL(redirectUrl);- urlSchemeValid = parsed.protocol === 'https:' || parsed.protocol === 'http:';- } catch {- // ignore- }+ const parsedUrl = Option.liftThrowable((value: string) => new URL(value))(redirectUrl);+ const urlSchemeValid = Option.exists(+ parsedUrl,+ parsed => parsed.protocol === 'https:' || parsed.protocol === 'http:'+ );if (!urlSchemeValid) {yield* ui.log.warn(`Redirect URL has an unexpected scheme: ${redirectUrl}`);yield* ui.log.info('Open the URL manually if you trust the source.');} else if (!noBrowser) {- yield* Effect.tryPromise(() => open(redirectUrl, { wait: false })).pipe(- Effect.catchAll(error =>+ yield* Effect.tryPromise({+ try: () => open(redirectUrl, { wait: false }),+ catch: cause => new BrowserOpenError({ message: 'Failed to open the browser.', cause }),+ }).pipe(+ Effect.catchTag('commands/BrowserOpenError', error =>Effect.gen(function* () {yield* Effect.logDebug('Failed to open browser:', error);yield* ui.log.warn('Could not open the browser automatically.');@@ -131,15 +157,22 @@ const waitForActiveConnection = (yield* ui.useMakeSpinner('Waiting for authentication...', spinner =>Effect.retry(Effect.gen(function* () {- const account = yield* Effect.tryPromise(() =>- client.connectedAccounts.retrieve(connectedAccountId)- );+ const account = yield* Effect.tryPromise({+ try: () => client.connectedAccounts.retrieve(connectedAccountId),+ catch: cause =>+ new ConnectedAccountsRequestError({+ message: `Failed to fetch connected account "${connectedAccountId}".`,+ cause,+ }),+ });if (account.status === 'ACTIVE') {return account;}- return yield* Effect.fail(- new Error(`Connection status is still '${account.status}', waiting for 'ACTIVE'`)- );+ return yield* new ConnectionPollingError({+ message: `Connection status is still '${account.status}', waiting for 'ACTIVE'`,+ connectedAccountId,+ status: account.status,+ });}),Schedule.exponential('0.3 seconds').pipe(Schedule.intersect(Schedule.recurs(15)),@@ -224,8 +257,13 @@ const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string, noBrowser: boo);if (!noBrowser) {- yield* Effect.tryPromise(() => open(dashboardUrl, { wait: false })).pipe(- Effect.catchAll(() => ui.log.warn('Could not open the browser automatically.'))+ yield* Effect.tryPromise({+ try: () => open(dashboardUrl, { wait: false }),+ catch: cause => new BrowserOpenError({ message: 'Failed to open the browser.', cause }),+ }).pipe(+ Effect.catchTag('commands/BrowserOpenError', () =>+ ui.log.warn('Could not open the browser automatically.')+ ));}@@ -257,7 +295,7 @@ const resolveNormalizedAliasOption = (alias: Option.Option<string>) =>const normalizedAlias = normalizeAlias(alias.value);if (normalizedAlias.length === 0) {- return yield* Effect.fail(new Error('`--alias` cannot be empty.'));+ return yield* Effect.fail(invalidOptionValue('`--alias` cannot be empty.'));}return Option.some(normalizedAlias);@@ -269,15 +307,21 @@ const listActiveConnectedAccounts = (params: {readonly toolkitSlug?: string;readonly authConfigId?: string;}) =>- Effect.tryPromise(() =>- params.client.connectedAccounts.list({- user_ids: [params.userId],- toolkit_slugs: params.toolkitSlug ? [params.toolkitSlug] : undefined,- auth_config_ids: params.authConfigId ? [params.authConfigId] : undefined,- statuses: ['ACTIVE'],- limit: 100,- })- );+ Effect.tryPromise({+ try: () =>+ params.client.connectedAccounts.list({+ user_ids: [params.userId],+ toolkit_slugs: params.toolkitSlug ? [params.toolkitSlug] : undefined,+ auth_config_ids: params.authConfigId ? [params.authConfigId] : undefined,+ statuses: ['ACTIVE'],+ limit: 100,+ }),+ catch: cause =>+ new ConnectedAccountsRequestError({+ message: `Failed to list connected accounts for user "${params.userId}".`,+ cause,+ }),+ });const formatExistingAccountLabels = (items: ReadonlyArray<{@@ -310,12 +354,12 @@ const ensureAliasForAdditionalAccount = (params: {}) =>Effect.gen(function* () {if (Option.isSome(params.alias)) {- return true as const;+ return true;}const existingIds = new Set(params.existingAccounts.items.map(item => item.id));if (params.existingAccounts.items.length === 0 || existingIds.has(params.connectedAccountId)) {- return true as const;+ return true;}yield* params.ui.log.error(@@ -325,7 +369,7 @@ const ensureAliasForAdditionalAccount = (params: {formatExistingAccountLabels(params.existingAccounts.items),'Existing accounts');- return false as const;+ return false;});const resolveLinkUserId = (params: {@@ -348,7 +392,8 @@ const resolveLinkUserId = (params: {}) =>Effect.gen(function* () {const resolvedProjectContext = yield* params.projectContext.resolve.pipe(- Effect.catchAll(() => Effect.succeed(Option.none()))+ Effect.option,+ Effect.map(Option.flatten));const localTestUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);@@ -421,21 +466,28 @@ const handleListConnectedAccounts = (params: {});if (Option.isNone(resolvedUserId)) {- return yield* Effect.fail(- new Error('Missing user id. Provide --user-id or run composio dev init/login first.')- );+ return yield* new MissingLinkUserIdError({+ message: 'Missing user id. Provide --user-id or run composio dev init/login first.',+ flow: 'list',+ });}const accounts = yield* params.ui.withSpinner(`Listing connected accounts for "${toolkitSlug}"...`,- Effect.tryPromise(() =>- client.connectedAccounts.list({- toolkit_slugs: [toolkitSlug],- user_ids: [resolvedUserId.value],- statuses: ['ACTIVE'],- limit: 100,- })- )+ Effect.tryPromise({+ try: () =>+ client.connectedAccounts.list({+ toolkit_slugs: [toolkitSlug],+ user_ids: [resolvedUserId.value],+ statuses: ['ACTIVE'],+ limit: 100,+ }),+ catch: cause =>+ new ConnectedAccountsRequestError({+ message: `Failed to list connected accounts for "${toolkitSlug}".`,+ cause,+ }),+ }));const connectedAccounts = yield* decodeConnectedAccountItemsWithFallback(accounts.items).pipe(Effect.mapError(@@ -456,7 +508,7 @@ const handleListConnectedAccounts = (params: {connectedAccounts: resolveDefaultConnectedAccountsByToolkit(connectedAccounts),availableConnectedAccounts: groupCachedConnectedAccountsByToolkit(connectedAccounts),},- }).pipe(Effect.catchAll(() => Effect.void));+ }).pipe(Effect.ignore);}if (connectedAccounts.length === 0) {@@ -514,7 +566,8 @@ const handleLegacyAuthConfigLink = (params: {}) =>Effect.gen(function* () {const resolvedProjectContext = yield* params.projectContext.resolve.pipe(- Effect.catchAll(() => Effect.succeed(Option.none()))+ Effect.option,+ Effect.map(Option.flatten));const localTestUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);const globalTestUserId = params.userContext.data.testUserId;@@ -524,11 +577,10 @@ const handleLegacyAuthConfigLink = (params: {});if (Option.isNone(resolvedUserId)) {- return yield* Effect.fail(- new Error(- 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.'- )- );+ return yield* new MissingLinkUserIdError({+ message: 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.',+ flow: 'legacy',+ });}if (Option.isNone(params.projectName) && Option.isNone(resolvedProjectContext)) {yield* params.ui.log.error(@@ -555,17 +607,27 @@ const handleLegacyAuthConfigLink = (params: {client,userId: resolvedUserId.value,authConfigId: params.authConfigId,- }).pipe(Effect.catchAll(() => Effect.succeed({ items: [] })));+ }).pipe(+ // Auxiliary fetch powering the --alias hint only: a transient list+ // failure must not abort the link flow.+ Effect.catchAll(() => Effect.succeed({ items: [] }))+ );const linkOpt = yield* params.ui.withSpinner('Creating link session...',- Effect.tryPromise(() =>- client.link.create({- auth_config_id: params.authConfigId,- user_id: resolvedUserId.value,- ...(Option.isSome(normalizedAlias) && { alias: normalizedAlias.value }),- })- )+ Effect.tryPromise({+ try: () =>+ client.link.create({+ auth_config_id: params.authConfigId,+ user_id: resolvedUserId.value,+ ...(Option.isSome(normalizedAlias) && { alias: normalizedAlias.value }),+ }),+ catch: cause =>+ new ConnectedAccountsRequestError({+ message: `Failed to create link for auth config "${params.authConfigId}".`,+ cause,+ }),+ })).pipe(Effect.asSome,@@ -656,7 +718,7 @@ const runConnectedAccountsLink = (params: {if (params.rootOnly) {if (Option.isSome(params.authConfig)) {return yield* Effect.fail(- new Error(+ invalidOptionValue('Top-level `composio link` is consumer-only and does not accept `--auth-config`. Use `composio dev connected-accounts link --auth-config ...` for developer-scoped usage.'));@@ -714,7 +776,8 @@ const runConnectedAccountsLink = (params: {return;}- const toolkitSlug = Option.getOrThrow(params.toolkit);+ if (Option.isNone(params.toolkit)) return;+ const toolkitSlug = params.toolkit.value;const resolvedProject = yield* resolveCommandProject({mode: 'consumer',projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),@@ -727,11 +790,11 @@ const runConnectedAccountsLink = (params: {onNone: () => userContext.data.testUserId,});if (Option.isNone(resolvedUserId)) {- return yield* Effect.fail(- new Error(- 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'- )- );+ return yield* new MissingLinkUserIdError({+ message:+ 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',+ flow: 'tool-router',+ });}const client = yield* clientSingleton.getFor({orgId: resolvedProject.orgId,@@ -741,7 +804,11 @@ const runConnectedAccountsLink = (params: {client,userId: resolvedUserId.value,toolkitSlug,- }).pipe(Effect.catchAll(() => Effect.succeed({ items: [] })));+ }).pipe(+ // Auxiliary fetch powering the --alias hint only: a transient list+ // failure must not abort the link flow.+ Effect.catchAll(() => Effect.succeed({ items: [] }))+ );const linkOpt = yield* ui.withSpinner(@@ -757,12 +824,20 @@ const runConnectedAccountsLink = (params: {}: undefined,});- return yield* Effect.tryPromise(() =>- client.toolRouter.session.link(sessionId, {- toolkit: toolkitSlug,- ...(Option.isSome(normalizedAliasOption) && { alias: normalizedAliasOption.value }),- })- );+ return yield* Effect.tryPromise({+ try: () =>+ client.toolRouter.session.link(sessionId, {+ toolkit: toolkitSlug,+ ...(Option.isSome(normalizedAliasOption) && {+ alias: normalizedAliasOption.value,+ }),+ }),+ catch: cause =>+ new ConnectedAccountsRequestError({+ message: `Failed to create link for toolkit "${toolkitSlug}".`,+ cause,+ }),+ });})).pipe(@@ -784,9 +859,7 @@ const runConnectedAccountsLink = (params: {return Option.none();})),- Effect.tap(() =>- invalidateConsumerConnectedToolkitsCache().pipe(Effect.catchAll(() => Effect.void))- )+ Effect.tap(() => invalidateConsumerConnectedToolkitsCache().pipe(Effect.ignore)));if (Option.isNone(linkOpt)) return;@@ -832,7 +905,7 @@ const runConnectedAccountsLink = (params: {connectedAccountId: connAccountId,redirectUrl,},- }).pipe(Effect.catchAll(() => Effect.void));+ }).pipe(Effect.ignore);} else {yield* waitForActiveConnection(ui, client, connAccountId, redirectUrl, params.noBrowser);yield* appendCliSessionHistory({@@ -846,7 +919,7 @@ const runConnectedAccountsLink = (params: {connectedAccountId: connAccountId,redirectUrl,},- }).pipe(Effect.catchAll(() => Effect.void));+ }).pipe(Effect.ignore);}});diff --git a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.list.cmd.ts b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.list.cmd.tsindex d91389a33..ee6a686dd 100644--- a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.list.cmd.ts+++ b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.list.cmd.ts@@ -1,5 +1,5 @@import { Command, Options } from '@effect/cli';-import { Effect, Option } from 'effect';+import { Data, Effect, Option } from 'effect';import type { ConnectedAccountListParams } from '@composio/client/resources/connected-accounts';import { ComposioClientSingleton } from 'src/services/composio-clients';import { TerminalUI } from 'src/services/terminal-ui';@@ -13,6 +13,13 @@ import {} from 'src/services/command-project';import { formatConnectedAccountsTable, formatConnectedAccountsJson } from '../format';+class ConnectedAccountsListRequestError extends Data.TaggedError(+ 'commands/ConnectedAccountsListRequestError'+)<{+ readonly message: string;+ readonly cause: unknown;+}> {}+const toolkits = Options.text('toolkits').pipe(Options.withDescription('Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'@@ -73,18 +80,24 @@ export const connectedAccountsCmd$List = Command.make(const rawResult = yield* ui.withSpinner('Fetching connected accounts...',- Effect.tryPromise(() =>- client.connectedAccounts.list({- toolkit_slugs: toolkitSlugs,- user_ids: Option.isSome(userId) ? [userId.value] : undefined,- // Bypass the stale Stainless union (still missing 'REVOKED')- // until @composio/client is regenerated.- statuses: Option.isSome(status)- ? ([status.value] as ConnectedAccountListParams['statuses'])- : undefined,- limit: clampLimit(limit),- })- )+ Effect.tryPromise({+ try: () =>+ client.connectedAccounts.list({+ toolkit_slugs: toolkitSlugs,+ user_ids: Option.isSome(userId) ? [userId.value] : undefined,+ // Bypass the stale Stainless union (still missing 'REVOKED')+ // until @composio/client is regenerated.+ statuses: Option.isSome(status)+ ? ([status.value] as ConnectedAccountListParams['statuses'])+ : undefined,+ limit: clampLimit(limit),+ }),+ catch: cause =>+ new ConnectedAccountsListRequestError({+ message: 'Failed to list connected accounts.',+ cause,+ }),+ }));const result = yield* decodeConnectedAccountListWithFallback(rawResult);diff --git a/ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts b/ts/packages/cli/src/commands/connections/commands/connections.list.cmd.tsindex 435d41139..1b6fd32b9 100644--- a/ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts+++ b/ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts@@ -1,5 +1,5 @@import { Command, Options } from '@effect/cli';-import { Effect, Option } from 'effect';+import { Data, Effect, Option } from 'effect';import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';import { requireAuth } from 'src/effects/require-auth';import type { ConnectedAccountItem } from 'src/models/connected-accounts';@@ -14,6 +14,17 @@ import {getConsumerPermissionSnapshot,} from 'src/services/tool-permissions';+class MissingConnectionsConsumerUserIdError extends Data.TaggedError(+ 'commands/MissingConnectionsConsumerUserIdError'+)<{+ readonly message: string;+}> {}++class ConnectionsListRequestError extends Data.TaggedError('commands/ConnectionsListRequestError')<{+ readonly message: string;+ readonly cause: unknown;+}> {}+const toolkit = Options.text('toolkit').pipe(Options.withDescription('Filter by toolkit slug (e.g. "gmail")'),Options.optional@@ -32,7 +43,7 @@ const formatConnectionsJson = (Record<string, Array<{ status: string; alias?: string | null; word_id?: string | null }>>>((acc, item) => {const toolkit = item.toolkit.slug;- const includeAlias = toolkitCounts.get(toolkit)! > 1;+ const includeAlias = (toolkitCounts.get(toolkit) ?? 0) > 1;const entry = {status: item.status,...(includeAlias ? { alias: item.alias ?? null } : {}),@@ -63,22 +74,28 @@ export const connectionsCmd$List = Command.make('list', { toolkit }, ({ toolkitconst consumerUserId = resolvedProject.consumerUserId;if (!consumerUserId) {- return yield* Effect.fail(- new Error('Missing consumer user id. Run `composio login` and try again.')- );+ return yield* new MissingConnectionsConsumerUserIdError({+ message: 'Missing consumer user id. Run `composio login` and try again.',+ });}const client = yield* clientSingleton.getFor({orgId: resolvedProject.orgId,projectId: resolvedProject.projectId,});- const rawResult = yield* Effect.tryPromise(() =>- client.connectedAccounts.list({- toolkit_slugs: toolkitSlug ? [toolkitSlug] : undefined,- user_ids: [consumerUserId],- limit: 1000,- })- );+ const rawResult = yield* Effect.tryPromise({+ try: () =>+ client.connectedAccounts.list({+ toolkit_slugs: toolkitSlug ? [toolkitSlug] : undefined,+ user_ids: [consumerUserId],+ limit: 1000,+ }),+ catch: cause =>+ new ConnectionsListRequestError({+ message: 'Failed to list connections.',+ cause,+ }),+ });const result = yield* decodeConnectedAccountListWithFallback(rawResult);const permissionSnapshot = yield* getConsumerPermissionSnapshot({orgId: resolvedProject.orgId,diff --git a/ts/packages/cli/src/commands/connections/commands/connections.remove.cmd.ts b/ts/packages/cli/src/commands/connections/commands/connections.remove.cmd.tsindex 307e8dfaa..8dd6bfec4 100644--- a/ts/packages/cli/src/commands/connections/commands/connections.remove.cmd.ts+++ b/ts/packages/cli/src/commands/connections/commands/connections.remove.cmd.ts@@ -1,5 +1,5 @@import { Args, Command } from '@effect/cli';-import { Effect } from 'effect';+import { Data, Effect } from 'effect';import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';import { requireAuth } from 'src/effects/require-auth';import type { ConnectedAccountItem } from 'src/models/connected-accounts';@@ -12,6 +12,19 @@ import { TerminalUI } from 'src/services/terminal-ui';import { bold } from 'src/ui/colors';import { redact } from 'src/ui/redact';+class MissingConnectionRemovalConsumerUserIdError extends Data.TaggedError(+ 'commands/MissingConnectionRemovalConsumerUserIdError'+)<{+ readonly message: string;+}> {}++class ConnectionsRemovalRequestError extends Data.TaggedError(+ 'commands/ConnectionsRemovalRequestError'+)<{+ readonly message: string;+ readonly cause: unknown;+}> {}+const account = Args.text({ name: 'account' }).pipe(Args.withDescription('Connection selector: toolkit slug, alias, word_id, or connected account ID'));@@ -60,12 +73,14 @@ const resolveAccount = (params: {const idMatches = matches.filter(item => normalizeSelector(item.id) === normalizeSelector(params.selector));- if (idMatches.length === 1) {- return idMatches[0]!;+ const idMatch = idMatches[0];+ if (idMatch && idMatches.length === 1) {+ return idMatch;}- if (matches.length === 1) {- return matches[0]!;+ const match = matches[0];+ if (match && matches.length === 1) {+ return match;}return {@@ -89,9 +104,9 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ accoconst consumerUserId = resolvedProject.consumerUserId;if (!consumerUserId) {- return yield* Effect.fail(- new Error('Missing consumer user id. Run `composio login` and try again.')- );+ return yield* new MissingConnectionRemovalConsumerUserIdError({+ message: 'Missing consumer user id. Run `composio login` and try again.',+ });}const client = yield* clientSingleton.getFor({@@ -100,12 +115,18 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ acco});const rawResult = yield* ui.withSpinner('Fetching connections...',- Effect.tryPromise(() =>- client.connectedAccounts.list({- user_ids: [consumerUserId],- limit: 1000,- })- )+ Effect.tryPromise({+ try: () =>+ client.connectedAccounts.list({+ user_ids: [consumerUserId],+ limit: 1000,+ }),+ catch: cause =>+ new ConnectionsRemovalRequestError({+ message: 'Failed to list connections.',+ cause,+ }),+ }));const result = yield* decodeConnectedAccountListWithFallback(rawResult);const resolved = resolveAccount({ accounts: result.items, selector: account });@@ -130,7 +151,14 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ accoyield* ui.withSpinner(`Removing ${resolved.toolkit.slug} connection...`,- Effect.tryPromise(() => client.connectedAccounts.delete(resolved.id)),+ Effect.tryPromise({+ try: () => client.connectedAccounts.delete(resolved.id),+ catch: cause =>+ new ConnectionsRemovalRequestError({+ message: `Failed to remove connected account "${resolved.id}".`,+ cause,+ }),+ }),{successMessage: `Removed ${resolved.toolkit.slug} connection.`,errorMessage: `Failed to remove ${resolved.toolkit.slug} connection.`,diff --git a/ts/packages/cli/src/commands/dev.cmd.ts b/ts/packages/cli/src/commands/dev.cmd.tsindex 10c8246c2..3104bee82 100644--- a/ts/packages/cli/src/commands/dev.cmd.ts+++ b/ts/packages/cli/src/commands/dev.cmd.ts@@ -10,7 +10,7 @@ import { connectedAccountsCmd } from './connected-accounts/connected-accounts.cmimport { triggersCmd } from './triggers/triggers.cmd';import { projectsCmd } from './projects/projects.cmd';import { devNativeUiCmd } from './dev/dev.native-ui.cmd';-import { ComposioCliUserConfig, resolveCliConfigPathSync } from 'src/services/cli-user-config';+import { ComposioCliUserConfig, resolveCliConfigPath } from 'src/services/cli-user-config';import { Stdin } from 'src/services/stdin';import { TerminalUI } from 'src/services/terminal-ui';import type { CommandVisibility } from './feature-tags';@@ -51,9 +51,10 @@ const applyDeveloperModeChange = (enabled: boolean) =>if (enabled) {if (!stdin.isTTY()) {+ const configPath = yield* resolveCliConfigPath;yield* ui.log.error('Enabling developer mode requires an interactive terminal.');yield* ui.log.step(- `Set "developer.enabled": true manually in ${resolveCliConfigPathSync()} if you really want to enable it outside an interactive session.`+ `Set "developer.enabled": true manually in ${configPath} if you really want to enable it outside an interactive session.`);return;}@@ -85,7 +86,8 @@ const applyDeveloperModeChange = (enabled: boolean) =>? 'Developer mode enabled.': 'Developer mode disabled. Only `composio dev --mode on|off` remains available.');- yield* ui.log.step(`Config updated: ${resolveCliConfigPathSync()}`);+ const configPath = yield* resolveCliConfigPath;+ yield* ui.log.step(`Config updated: ${configPath}`);});const promptForDeveloperMode = () =>diff --git a/ts/packages/cli/src/commands/listen.cmd.ts b/ts/packages/cli/src/commands/listen.cmd.tsindex 64fcce272..be7347a22 100644--- a/ts/packages/cli/src/commands/listen.cmd.ts+++ b/ts/packages/cli/src/commands/listen.cmd.ts@@ -1,7 +1,7 @@-import { Args, Command, Options } from '@effect/cli';+import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';import { FileSystem, Path } from '@effect/platform';import type { Composio as RawComposioClient } from '@composio/client';-import { Deferred, Effect, Either, Option, Runtime } from 'effect';+import { Data, Deferred, Effect, Either, Option, Predicate, Runtime } from 'effect';import { requireAuth } from 'src/effects/require-auth';import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';import { ComposioClientSingleton } from 'src/services/composio-clients';@@ -25,6 +25,29 @@ import { ComposioCliUserConfig } from 'src/services/cli-user-config';import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';import { matchesTriggerListenFilters } from './triggers/filter';import { parseTriggerListenEvent } from './triggers/parse';+import { decodeConnectedAccountItemsWithFallback } from 'src/effects/decode-connected-account-list';++type TriggerCreateParams = NonNullable<+ Parameters<RawComposioClient['triggerInstances']['upsert']>[1]+>;++export class ListenCommandError extends Data.TaggedError('commands/ListenCommandError')<{+ readonly reason:+ | 'project_context'+ | 'connected_accounts'+ | 'connected_account_not_found'+ | 'create_trigger'+ | 'disable_trigger';+ readonly message: string;+ readonly slug?: string;+ readonly toolkitSlug?: string;+ readonly cause?: unknown;+}> {}++const invalidOptionValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));++const errorMessage = (error: unknown): string =>+ Predicate.isError(error) ? error.message : String(error);const slug = Args.text({ name: 'slug' }).pipe(Args.withDescription(@@ -73,6 +96,27 @@ const debug = Options.boolean('debug').pipe(const sanitizePathPart = (value: string): string =>value.replace(/[^A-Z0-9._-]+/gi, '-').replace(/^-+|-+$/g, '') || 'unknown';+const disableTemporaryTrigger = (params: {+ client: RawComposioClient;+ ui: TerminalUI;+ slug: string;+ triggerId: string;+}) =>+ Effect.tryPromise({+ try: () =>+ params.client.triggerInstances.manage.update(params.triggerId, { status: 'disable' }),+ catch: cause =>+ new ListenCommandError({+ reason: 'disable_trigger',+ message: `Failed to disable temporary trigger "${params.triggerId}": ${String(cause)}`,+ slug: params.slug,+ cause,+ }),+ }).pipe(+ Effect.tapError(error => params.ui.log.warn(error.message)),+ Effect.ignore+ );+const isProjectEventType = (value: string): boolean => value.startsWith('composio.');const resolveParamsInput = (input: Option.Option<string>) =>@@ -80,13 +124,12 @@ const resolveParamsInput = (input: Option.Option<string>) =>const parseCreateParams = (raw: string) =>parseJsonRecord(raw).pipe(- Either.mapLeft(- error =>- new Error(- error.reason === 'not-a-record'- ? "Expected --params to be an object, e.g. -p '{ trigger_config: { ... } }'."- : "Invalid --params input. Provide JSON or a JS-style object literal, e.g. -p '{ trigger_config: { ... } }'."- )+ Either.mapLeft(error =>+ invalidOptionValue(+ error.reason === 'not-a-record'+ ? "Expected --params to be an object, e.g. -p '{ trigger_config: { ... } }'."+ : "Invalid --params input. Provide JSON or a JS-style object literal, e.g. -p '{ trigger_config: { ... } }'."+ )));@@ -97,7 +140,7 @@ const assertSupportedListenParams = (params: {}) =>params.listeningToProjectEvent && Object.keys(params.createParamsInput).length > 0? Effect.fail(- new Error(+ invalidOptionValue(`--params is only supported for trigger slugs. "${params.slug}" is a project-level composio.* event type and does not create a temporary trigger.`))@@ -113,7 +156,7 @@ const resolveConnectedAccountIdForTrigger = (params: {const toolkitSlug = toolkitFromToolSlug(params.slug);if (!toolkitSlug) {return yield* Effect.fail(- new Error(+ invalidOptionValue(`Could not infer a toolkit from trigger slug "${params.slug}". Use a standard trigger slug such as "GMAIL_NEW_GMAIL_MESSAGE", or a project event type such as "composio.connected_account.expired".`));@@ -127,31 +170,50 @@ const resolveConnectedAccountIdForTrigger = (params: {statuses: ['ACTIVE'],limit: 100,}),- catch: error =>- new Error(`Failed to list connected accounts for "${toolkitSlug}": ${String(error)}`),+ catch: cause =>+ new ListenCommandError({+ reason: 'connected_accounts',+ message: `Failed to list connected accounts for "${toolkitSlug}": ${String(cause)}`,+ slug: params.slug,+ toolkitSlug,+ cause,+ }),});+ const selectableAccounts = yield* decodeConnectedAccountItemsWithFallback(+ connectedAccounts.items+ ).pipe(+ Effect.mapError(+ cause =>+ new ListenCommandError({+ reason: 'connected_accounts',+ message: `Connected accounts for toolkit "${toolkitSlug}" did not match the expected response shape.`,+ slug: params.slug,+ toolkitSlug,+ cause,+ })+ )+ );const selectedAccount = resolveConnectedAccountSelection(- connectedAccounts.items as Parameters<typeof resolveConnectedAccountSelection>[0],+ selectableAccounts,Option.getOrUndefined(params.account));if (selectedAccount?.id) {return selectedAccount.id;}- const choices = formatConnectedAccountChoices(- connectedAccounts.items as Parameters<typeof formatConnectedAccountChoices>[0]- );+ const choices = formatConnectedAccountChoices(selectableAccounts);const suffix =Option.isSome(params.account) && choices.length > 0? ` Available accounts: ${choices.join(', ')}.`: '';- return yield* Effect.fail(- new Error(- Option.isSome(params.account)- ? `No connected account matched "${params.account.value}" for toolkit "${toolkitSlug}" and consumer user "${params.consumerUserId}".${suffix}`- : `No active connected account found for toolkit "${toolkitSlug}" and consumer user "${params.consumerUserId}". Run \`composio link ${toolkitSlug}\` first.`- )- );+ return yield* new ListenCommandError({+ reason: 'connected_account_not_found',+ message: Option.isSome(params.account)+ ? `No connected account matched "${params.account.value}" for toolkit "${toolkitSlug}" and consumer user "${params.consumerUserId}".${suffix}`+ : `No active connected account found for toolkit "${toolkitSlug}" and consumer user "${params.consumerUserId}". Run \`composio link ${toolkitSlug}\` first.`,+ slug: params.slug,+ toolkitSlug,+ });});const emitStreamLine = (line: string, ui: TerminalUI) =>Effect.gen(function* () {@@ -163,13 +225,8 @@ const eventTypeOf = (eventData: Record<string, unknown>): string | undefined =>typeof eventData.type === 'string' && eventData.type.length > 0 ? eventData.type : undefined;const extractEventFileId = (eventData: Record<string, unknown>): string => {- const candidates = [- eventData.id,- eventData.log_id,- typeof eventData.metadata === 'object' && eventData.metadata !== null- ? (eventData.metadata as Record<string, unknown>).id- : undefined,- ];+ const metadata = Predicate.isRecord(eventData.metadata) ? eventData.metadata : undefined;+ const candidates = [eventData.id, eventData.log_id, metadata?.id];for (const candidate of candidates) {if (typeof candidate === 'string' && candidate.length > 0) {@@ -180,36 +237,43 @@ const extractEventFileId = (eventData: Record<string, unknown>): string => {return `${Date.now()}-${crypto.randomUUID().slice(0, 8)}`;};-const parseStreamPath = (expression: string): ReadonlyArray<string | number> => {- const trimmed = expression.trim();- if (!trimmed.startsWith('.')) {- throw new Error('Expected --stream to contain a jq-like path starting with "."');- }-- const pathTokens: Array<string | number> = [];- const tokenPattern = /(?:\.([A-Za-z0-9_-]+))|(?:\[(\d+)\])/g;- let lastIndex = 0;-- for (const match of trimmed.matchAll(tokenPattern)) {- if ((match.index ?? -1) !== lastIndex) {- throw new Error(- 'Unsupported --stream expression. Use a jq-like path such as ".foo.bar" or ".items[0].id".'+const parseStreamPath = (expression: string) =>+ Effect.gen(function* () {+ const trimmed = expression.trim();+ if (!trimmed.startsWith('.')) {+ return yield* Effect.fail(+ invalidOptionValue('Expected --stream to contain a jq-like path starting with "."'));}- if (match[1]) pathTokens.push(match[1]);- if (match[2]) pathTokens.push(Number(match[2]));- lastIndex += match[0].length;- }+ const pathTokens: Array<string | number> = [];+ const tokenPattern = /(?:\.([A-Za-z0-9_-]+))|(?:\[(\d+)\])/g;+ let lastIndex = 0;++ for (const match of trimmed.matchAll(tokenPattern)) {+ if ((match.index ?? -1) !== lastIndex) {+ return yield* Effect.fail(+ invalidOptionValue(+ 'Unsupported --stream expression. Use a jq-like path such as ".foo.bar" or ".items[0].id".'+ )+ );+ }- if (lastIndex !== trimmed.length) {- throw new Error(- 'Unsupported --stream expression. Use a jq-like path such as ".foo.bar" or ".items[0].id".'- );- }+ if (match[1]) pathTokens.push(match[1]);+ if (match[2]) pathTokens.push(Number(match[2]));+ lastIndex += match[0].length;+ }- return pathTokens;-};+ if (lastIndex !== trimmed.length) {+ return yield* Effect.fail(+ invalidOptionValue(+ 'Unsupported --stream expression. Use a jq-like path such as ".foo.bar" or ".items[0].id".'+ )+ );+ }++ return pathTokens;+ });const applyStreamPath = (value: unknown, pathTokens: ReadonlyArray<string | number>): unknown => {let current = value;@@ -222,11 +286,11 @@ const applyStreamPath = (value: unknown, pathTokens: ReadonlyArray<string | numbcontinue;}- if (typeof current !== 'object' || current === null || Array.isArray(current)) {+ if (!Predicate.isRecord(current)) {return undefined;}- current = (current as Record<string, unknown>)[token];+ current = current[token];}return current;@@ -279,25 +343,23 @@ const TIMEOUT_UNITS_MS: Record<string, number> = {days: 86_400_000,};-const parseTimeoutMs = (value: string): number => {- const trimmed = value.trim().toLowerCase();- const match = /^(\d+(?:\.\d+)?)\s*([a-z]+)$/.exec(trimmed);- if (!match) {- throw new Error(- 'Invalid --timeout value. Use a duration such as "30s", "5m", "1hr", or "1day".'- );- }-- const amount = Number(match[1]);- const unitMs = TIMEOUT_UNITS_MS[match[2]];- if (!Number.isFinite(amount) || amount <= 0 || unitMs === undefined) {- throw new Error(- 'Invalid --timeout value. Use a duration such as "30s", "5m", "1hr", or "1day".'- );- }+const parseTimeoutMs = (value: string) =>+ Effect.gen(function* () {+ const trimmed = value.trim().toLowerCase();+ const match = /^(\d+(?:\.\d+)?)\s*([a-z]+)$/.exec(trimmed);+ const amount = Number(match?.[1]);+ const unit = match?.[2];+ const unitMs = unit === undefined ? undefined : TIMEOUT_UNITS_MS[unit];+ if (!match || !Number.isFinite(amount) || amount <= 0 || unitMs === undefined) {+ return yield* Effect.fail(+ invalidOptionValue(+ 'Invalid --timeout value. Use a duration such as "30s", "5m", "1hr", or "1day".'+ )+ );+ }- return Math.round(amount * unitMs);-};+ return Math.round(amount * unitMs);+ });const resolveListenSetup = (params: {readonly slug: string;@@ -314,10 +376,13 @@ const resolveListenSetup = (params: {};}) =>Effect.gen(function* () {- if (!params.resolvedProject.consumerUserId) {- return yield* Effect.fail(- new Error('No consumer user is available in the current project context.')- );+ const consumerUserId = params.resolvedProject.consumerUserId;+ if (!consumerUserId) {+ return yield* new ListenCommandError({+ reason: 'project_context',+ message: 'No consumer user is available in the current project context.',+ slug: params.slug,+ });}const listeningToProjectEvent = isProjectEventType(params.slug);@@ -336,34 +401,34 @@ const resolveListenSetup = (params: {: yield* resolveConnectedAccountIdForTrigger({client: params.client,slug: params.slug,- consumerUserId: params.resolvedProject.consumerUserId,+ consumerUserId,account: params.account,});- const createParams = listeningToProjectEvent+ const createParams: TriggerCreateParams | undefined = listeningToProjectEvent? undefined- : ({+ : {...createParamsInput,connected_account_id: resolvedConnectedAccountId,- } as Parameters<typeof params.client.triggerInstances.upsert>[1]);+ };++ const timeoutMs = Option.isSome(params.timeout)+ ? yield* parseTimeoutMs(params.timeout.value)+ : undefined;+ const streamPath = Option.isSome(params.stream)+ ? params.stream.value.trim().length === 0+ ? []+ : yield* parseStreamPath(params.stream.value)+ : undefined;return {listeningToProjectEvent,createParams,- timeoutMs: Option.match(params.timeout, {- onNone: () => undefined,- onSome: value => parseTimeoutMs(value),- }),- streamPath: Option.match(params.stream, {- onNone: () => undefined,- onSome: value => {- const trimmed = value.trim();- return trimmed.length === 0 ? [] : parseStreamPath(trimmed);- },- }),+ timeoutMs,+ streamPath,shouldStream: Option.isSome(params.stream),maxEventsLimit: Option.getOrUndefined(params.maxEvents),- consumerUserId: params.resolvedProject.consumerUserId,+ consumerUserId,};});@@ -382,7 +447,15 @@ export const listenCmd = Command.make(const realtime = yield* TriggersRealtime;const resolvedProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(- Effect.mapError(formatResolveCommandProjectError)+ Effect.mapError(cause => {+ const formatted = formatResolveCommandProjectError(cause);+ return new ListenCommandError({+ reason: 'project_context',+ message: formatted.message,+ slug,+ cause,+ });+ }));const client = yield* clientSingleton.getFor({@@ -440,8 +513,13 @@ export const listenCmd = Command.make(? Effect.succeed<null | { trigger_id: string }>(null): Effect.tryPromise({try: () => client.triggerInstances.upsert(slug, createParams),- catch: error =>- new Error(`Failed to create temporary trigger "${slug}": ${String(error)}`),+ catch: cause =>+ new ListenCommandError({+ reason: 'create_trigger',+ message: `Failed to create temporary trigger "${slug}": ${String(cause)}`,+ slug,+ cause,+ }),}),createdTrigger =>Effect.gen(function* () {@@ -478,15 +556,16 @@ export const listenCmd = Command.make(const filterResult =createdTrigger === null? eventTypeOf(eventData) === slug- : matchesTriggerListenFilters(+ : parsedTriggerEvent !== undefined &&+ matchesTriggerListenFilters({ triggerId: createdTrigger.trigger_id },- parsedTriggerEvent!+ parsedTriggerEvent);if (debug) {yield* emitStreamLine(createdTrigger === null? `[debug] event.type=${eventTypeOf(eventData) ?? '<missing>'} match=${filterResult}`- : `[debug] parsed.id=${parsedTriggerEvent!.id} triggerSlug=${parsedTriggerEvent!.triggerSlug} trigger_id=${createdTrigger.trigger_id} match=${filterResult}`,+ : `[debug] parsed.id=${parsedTriggerEvent?.id ?? '<missing>'} triggerSlug=${parsedTriggerEvent?.triggerSlug ?? '<missing>'} trigger_id=${createdTrigger.trigger_id} match=${filterResult}`,ui);}@@ -533,9 +612,8 @@ export const listenCmd = Command.make(yield* Deferred.succeed(stopWhenDone, 'max-events').pipe(Effect.ignore);}}).pipe(- Effect.catchAll(error =>- ui.log.warn(error instanceof Error ? error.message : String(error))- )+ Effect.tapError(error => ui.log.warn(errorMessage(error))),+ Effect.ignore));};@@ -589,18 +667,7 @@ export const listenCmd = Command.make(created =>created === null? Effect.void- : Effect.tryPromise({- try: () =>- client.triggerInstances.manage.update(created.trigger_id, { status: 'disable' }),- catch: error =>- new Error(- `Failed to disable temporary trigger "${created.trigger_id}": ${String(error)}`- ),- }).pipe(- Effect.catchAll(error =>- ui.log.warn(error instanceof Error ? error.message : String(error))- )- )+ : disableTemporaryTrigger({ client, ui, slug, triggerId: created.trigger_id })).pipe(Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>Effect.gen(function* () {diff --git a/ts/packages/cli/src/commands/local-tools/commands/local-tools.configure.cmd.ts b/ts/packages/cli/src/commands/local-tools/commands/local-tools.configure.cmd.tsindex 8d44d2d98..1a906f023 100644--- a/ts/packages/cli/src/commands/local-tools/commands/local-tools.configure.cmd.ts+++ b/ts/packages/cli/src/commands/local-tools/commands/local-tools.configure.cmd.ts@@ -1,4 +1,4 @@-import { Args, Command, Options } from '@effect/cli';+import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';import {getLocalToolsMetaPath,isLocalToolkitSlug,@@ -7,7 +7,7 @@ import {updateLocalToolMeta,type LocalToolMetaEntry,} from '@composio/cli-local-tools';-import { Effect, Option } from 'effect';+import { Data, Effect, Option, Predicate } from 'effect';import { TerminalUI } from 'src/services/terminal-ui';import { bold, gray } from 'src/ui/colors';@@ -58,6 +58,19 @@ type ConfigureTarget =readonly toolkitSlug: string;};+export class LocalToolsConfigureError extends Data.TaggedError(+ 'commands/local-tools/LocalToolsConfigureError'+)<{+ readonly message: string;+ readonly target: ConfigureTarget;+ readonly cause: unknown;+}> {}++const errorMessage = (error: unknown): string =>+ Predicate.isError(error) ? error.message : String(error);++const invalidValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));+const resolveTarget = (value: string): ConfigureTarget | null => {const localTool = resolveLocalTool(value, { includeUnsupported: true });if (localTool) {@@ -137,7 +150,7 @@ export const localToolsCmd$Configure = Command.make(const target = resolveTarget(selector);if (!target) {return yield* Effect.fail(- new Error(+ invalidValue(`Unknown local toolkit/tool "${selector}". Run \`composio local-tools list --all-platforms\` to inspect valid selectors.`));@@ -145,16 +158,28 @@ export const localToolsCmd$Configure = Command.make(const patch = buildPatch({ command, disable, enable, authenticated, unauthenticated });if ('error' in patch) {- return yield* Effect.fail(new Error(patch.error));+ return yield* Effect.fail(invalidValue(patch.error));}- const metadata = yield* Effect.tryPromise(() =>- target.kind === 'toolkit'- ? updateLocalToolkitMeta(target.key, patch)- : updateLocalToolMeta(target.key, patch)- );+ const metadata = yield* Effect.tryPromise({+ try: () =>+ target.kind === 'toolkit'+ ? updateLocalToolkitMeta(target.key, patch)+ : updateLocalToolMeta(target.key, patch),+ catch: cause =>+ new LocalToolsConfigureError({+ message: errorMessage(cause),+ target,+ cause,+ }),+ });const entry =- target.kind === 'toolkit' ? metadata.toolkits[target.key]! : metadata.tools[target.key]!;+ target.kind === 'toolkit' ? metadata.toolkits[target.key] : metadata.tools[target.key];+ if (!entry) {+ return yield* Effect.dieMessage(+ `Local tools metadata invariant violated: ${target.kind} ${target.key} was not updated`+ );+ }const metadataPath = getLocalToolsMetaPath();const payload = { metadataPath, target, entry };diff --git a/ts/packages/cli/src/commands/local-tools/commands/local-tools.doctor.cmd.ts b/ts/packages/cli/src/commands/local-tools/commands/local-tools.doctor.cmd.tsindex 6ecca0596..984143c45 100644--- a/ts/packages/cli/src/commands/local-tools/commands/local-tools.doctor.cmd.ts+++ b/ts/packages/cli/src/commands/local-tools/commands/local-tools.doctor.cmd.ts@@ -6,7 +6,7 @@ import {type LocalReadinessStatus,type LocalToolsReadinessReport,} from '@composio/cli-local-tools';-import { Effect, Option } from 'effect';+import { Data, Effect, Option, Predicate } from 'effect';import { TerminalUI } from 'src/services/terminal-ui';import { bold, gray, green, red } from 'src/ui/colors';import { truncate } from 'src/ui/truncate';@@ -31,6 +31,18 @@ const toolkits = Options.text('toolkits').pipe(Options.withDescription('Filter by local toolkit slugs, comma-separated'));+export class LocalToolsDoctorError extends Data.TaggedError(+ 'commands/local-tools/LocalToolsDoctorError'+)<{+ readonly message: string;+ readonly operation: 'check' | 'strict';+ readonly notReadyTools: ReadonlyArray<string>;+ readonly cause?: unknown;+}> {}++const errorMessage = (error: unknown): string =>+ Predicate.isError(error) ? error.message : String(error);+const parseToolkitFilter = (value: Option.Option<string>): ReadonlyArray<string> | undefined => {const raw = Option.getOrUndefined(value);if (!raw?.trim()) return undefined;@@ -59,9 +71,11 @@ const statusLabel = (status: LocalReadinessStatus): string => {return red(status);};-const hasProblems = (report: LocalToolsReadinessReport): boolean =>- report.toolkits.some(toolkit =>- toolkit.tools.some(tool => tool.status !== 'ready' && tool.status !== 'unsupported')+const notReadyTools = (report: LocalToolsReadinessReport): ReadonlyArray<string> =>+ report.toolkits.flatMap(toolkit =>+ toolkit.tools+ .filter(tool => tool.status !== 'ready' && tool.status !== 'unsupported')+ .map(tool => tool.finalSlug));const formatDoctorReport = (report: LocalToolsReadinessReport, metadataPath: string): string => {@@ -115,12 +129,20 @@ export const localToolsCmd$Doctor = Command.make(const ui = yield* TerminalUI;const toolkitFilter = parseToolkitFilter(toolkits);const metadataPath = getLocalToolsMetaPath();- const report = yield* Effect.tryPromise(() =>- checkLocalToolkitsReadiness({- includeUnsupported: allPlatforms,- toolkits: toolkitFilter,- })- );+ const report = yield* Effect.tryPromise({+ try: () =>+ checkLocalToolkitsReadiness({+ includeUnsupported: allPlatforms,+ toolkits: toolkitFilter,+ }),+ catch: cause =>+ new LocalToolsDoctorError({+ message: errorMessage(cause),+ operation: 'check',+ notReadyTools: [],+ cause,+ }),+ });if (json) {yield* ui.output(JSON.stringify({ metadataPath, ...report }, null, 2), { force: true });@@ -128,10 +150,15 @@ export const localToolsCmd$Doctor = Command.make(yield* ui.log.message(formatDoctorReport(report, metadataPath));}- if (strict && hasProblems(report)) {- return yield* Effect.fail(- new Error('One or more local tools are not ready. Run without --strict for setup hints.')- );+ if (strict) {+ const problems = notReadyTools(report);+ if (problems.length > 0) {+ return yield* new LocalToolsDoctorError({+ message: 'One or more local tools are not ready. Run without --strict for setup hints.',+ operation: 'strict',+ notReadyTools: problems,+ });+ }}})).pipe(diff --git a/ts/packages/cli/src/commands/local-tools/commands/local-tools.meta.cmd.ts b/ts/packages/cli/src/commands/local-tools/commands/local-tools.meta.cmd.tsindex 5d283e3fb..92593ff46 100644--- a/ts/packages/cli/src/commands/local-tools/commands/local-tools.meta.cmd.ts+++ b/ts/packages/cli/src/commands/local-tools/commands/local-tools.meta.cmd.ts@@ -5,10 +5,15 @@ import {readLocalToolsMeta,writeLocalToolsMeta,} from '@composio/cli-local-tools';-import { Effect } from 'effect';+import { Data, Effect } from 'effect';import { TerminalUI } from 'src/services/terminal-ui';import { bold, gray } from 'src/ui/colors';+class LocalToolsMetaError extends Data.TaggedError('commands/LocalToolsMetaError')<{+ readonly message: string;+ readonly cause: unknown;+}> {}+const json = Options.boolean('json').pipe(Options.withDefault(false),Options.withDescription('Print the metadata file contents as JSON')@@ -24,16 +29,31 @@ export const localToolsCmd$Meta = Command.make('meta', { json, init }, ({ json,const ui = yield* TerminalUI;const metadataPath = getLocalToolsMetaPath();const meta = init- ? yield* Effect.tryPromise(async () => {- const existing = await readLocalToolsMeta();- const next =- Object.keys(existing.tools).length === 0 && Object.keys(existing.toolkits).length === 0- ? createEmptyLocalToolsMeta()- : existing;- await writeLocalToolsMeta(next);- return next;+ ? yield* Effect.tryPromise({+ try: async () => {+ const existing = await readLocalToolsMeta();+ const next =+ Object.keys(existing.tools).length === 0 &&+ Object.keys(existing.toolkits).length === 0+ ? createEmptyLocalToolsMeta()+ : existing;+ await writeLocalToolsMeta(next);+ return next;+ },+ catch: cause =>+ new LocalToolsMetaError({+ message: `Failed to initialize the local tools metadata file at ${metadataPath}.`,+ cause,+ }),})- : yield* Effect.tryPromise(() => readLocalToolsMeta());+ : yield* Effect.tryPromise({+ try: () => readLocalToolsMeta(),+ catch: cause =>+ new LocalToolsMetaError({+ message: `Failed to read the local tools metadata file at ${metadataPath}.`,+ cause,+ }),+ });const payload = {metadataPath,diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.tsindex fb4872ca4..c34234e71 100644--- a/ts/packages/cli/src/commands/login.cmd.ts+++ b/ts/packages/cli/src/commands/login.cmd.ts@@ -1,8 +1,6 @@-// 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';-import { DateTime, Effect, Option, Schedule } from 'effect';+import { Command, HelpDoc, Options, ValidationError } from '@effect/cli';+import { FileSystem, Path } from '@effect/platform';+import { Data, DateTime, Effect, Option, Schedule, Schema } from 'effect';import open from 'open';import {ComposioSessionRepository,@@ -82,40 +80,45 @@ const LOGIN_POLL_INTERVAL_SECONDS = 5;const LOGIN_POLL_TIMEOUT_SECONDS = 10 * 60;const LOGIN_POLL_RETRIES = Math.ceil(LOGIN_POLL_TIMEOUT_SECONDS / LOGIN_POLL_INTERVAL_SECONDS);-type PendingLoginSession = {- readonly key: string;- readonly loginUrl: string;- readonly expiresAt: string;- readonly cachedAt: string;-};+const PendingLoginSession = Schema.Struct({+ key: Schema.String,+ loginUrl: Schema.String,+ expiresAt: Schema.String,+ cachedAt: Schema.String,+});+type PendingLoginSession = Schema.Schema.Type<typeof PendingLoginSession>;++class PendingLoginError extends Data.TaggedError('commands/PendingLoginError')<{+ readonly message: string;+ readonly reason: 'invalid' | 'missing' | 'expired';+ readonly cause?: unknown;+}> {}++class LoginSessionError extends Data.TaggedError('commands/LoginSessionError')<{+ readonly message: string;+ readonly operation: 'load' | 'poll';+ readonly status?: string;+ readonly cause?: unknown;+}> {}++class LoginBrowserOpenError extends Data.TaggedError('commands/LoginBrowserOpenError')<{+ readonly message: string;+ readonly cause: unknown;+}> {}++class InvalidOrganizationError extends Data.TaggedError('commands/InvalidOrganizationError')<{+ readonly message: string;+ readonly requestedOrg: string;+}> {}++const invalidOptionValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));const pendingLoginPath = Effect.gen(function* () {+ const path = yield* Path.Path;const cacheDir = yield* setupCacheDir;return path.join(cacheDir, PENDING_LOGIN_FILE_NAME);});-const isRecord = (value: unknown): value is Record<string, unknown> =>- typeof value === 'object' && value !== null;--const parsePendingLoginSession = (raw: string): PendingLoginSession => {- const parsed: unknown = JSON.parse(raw);- if (- !isRecord(parsed) ||- typeof parsed.key !== 'string' ||- typeof parsed.loginUrl !== 'string' ||- typeof parsed.expiresAt !== 'string' ||- typeof parsed.cachedAt !== 'string'- ) {- throw new Error('Pending login cache is invalid');- }- return {- key: parsed.key,- loginUrl: parsed.loginUrl,- expiresAt: parsed.expiresAt,- cachedAt: parsed.cachedAt,- };-};-const writePendingLoginSession = (session: Omit<PendingLoginSession, 'cachedAt'>) =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;@@ -130,7 +133,7 @@ const writePendingLoginSession = (session: Omit<PendingLoginSession, 'cachedAt'>const clearPendingLoginSession = Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;const filePath = yield* pendingLoginPath;- yield* fs.remove(filePath).pipe(Effect.catchAll(() => Effect.void));+ yield* fs.remove(filePath).pipe(Effect.ignore);});const readPendingLoginSession = Effect.gen(function* () {@@ -138,20 +141,30 @@ const readPendingLoginSession = Effect.gen(function* () {const filePath = yield* pendingLoginPath;const exists = yield* fs.exists(filePath);if (!exists) {- return yield* Effect.fail(- new Error('No pending login found. Run `composio login < /dev/null` first.')- );+ return yield* new PendingLoginError({+ message: 'No pending login found. Run `composio login < /dev/null` first.',+ reason: 'missing',+ });}- const session = yield* fs- .readFileString(filePath, 'utf8')- .pipe(Effect.map(parsePendingLoginSession));+ const session = yield* fs.readFileString(filePath, 'utf8').pipe(+ Effect.flatMap(Schema.decodeUnknown(Schema.parseJson(PendingLoginSession))),+ Effect.mapError(+ cause =>+ new PendingLoginError({+ message: 'Pending login cache is invalid',+ reason: 'invalid',+ cause,+ })+ )+ );const cachedAt = Date.parse(session.cachedAt);if (!Number.isFinite(cachedAt) || Date.now() - cachedAt > PENDING_LOGIN_TTL_MS) {yield* clearPendingLoginSession;- return yield* Effect.fail(- new Error('Pending login expired. Run `composio login < /dev/null` again.')- );+ return yield* new PendingLoginError({+ message: 'Pending login expired. Run `composio login < /dev/null` again.',+ reason: 'expired',+ });}return session;@@ -293,9 +306,10 @@ const resolveDirectLoginOrganization = (params: {if (!match) {yield* ui.log.error(`Organization "${requestedOrg}" was not found for this API key.`);- return yield* Effect.fail(- new Error('Invalid organization. Run `composio orgs list` to inspect available orgs.')- );+ return yield* new InvalidOrganizationError({+ message: 'Invalid organization. Run `composio orgs list` to inspect available orgs.',+ requestedOrg,+ });}return match;@@ -436,17 +450,17 @@ const loginWithKey = (params: {const ctx = yield* ComposioUserContext;const client = yield* ComposioSessionRepository;- const getSessionEffect = client- .getSession({ id: params.key })- .pipe(- Effect.catchAll(() =>- Effect.fail(- new Error(- 'Session not found or expired. Run `composio login --no-wait` to get a new session.'- )- )- )- );+ const getSessionEffect = client.getSession({ id: params.key }).pipe(+ Effect.mapError(+ cause =>+ new LoginSessionError({+ message:+ 'Session not found or expired. Run `composio login --no-wait` to get a new session.',+ operation: 'load',+ cause,+ })+ )+ );let linkedSession;if (params.noWait) {@@ -454,7 +468,11 @@ const loginWithKey = (params: {if (session.status !== 'linked') {yield* ui.log.error('Login not complete. Open the URL and finish authentication.');yield* ui.log.info('Then run `composio login --key <key>` again.');- return yield* Effect.fail(new Error('Session not yet linked'));+ return yield* new LoginSessionError({+ message: 'Session not yet linked',+ operation: 'poll',+ status: session.status,+ });}linkedSession = session;} else {@@ -465,9 +483,11 @@ const loginWithKey = (params: {if (currentSession.status === 'linked') {return currentSession;}- return yield* Effect.fail(- new Error(`Session status is still '${currentSession.status}', waiting for 'linked'`)- );+ return yield* new LoginSessionError({+ message: `Session status is still '${currentSession.status}', waiting for 'linked'`,+ operation: 'poll',+ status: currentSession.status,+ });}),Schedule.exponential('0.3 seconds').pipe(Schedule.intersect(Schedule.recurs(params.pollRetries ?? 15)),@@ -495,7 +515,7 @@ const loginWithKey = (params: {Effect.catchAll(error =>Effect.gen(function* () {yield* Effect.logDebug('Failed to list organizations after login:', error);- return [] as ReadonlyArray<OrganizationSummary>;+ return [];})))@@ -642,8 +662,12 @@ export const browserLogin = (params: {yield* ui.output(url);if (!effectiveNoBrowser) {- yield* Effect.tryPromise(() => open(url, { wait: false })).pipe(- Effect.catchAll(error =>+ yield* Effect.tryPromise({+ try: () => open(url, { wait: false }),+ catch: cause =>+ new LoginBrowserOpenError({ message: 'Failed to open the browser.', cause }),+ }).pipe(+ Effect.catchTag('commands/LoginBrowserOpenError', error =>Effect.gen(function* () {yield* Effect.logDebug('Failed to open browser:', error);yield* ui.log.warn('Could not open the browser automatically.');@@ -662,9 +686,11 @@ export const browserLogin = (params: {if (currentSession.status === 'linked') {return currentSession;}- return yield* Effect.fail(- new Error(`Session status is still '${currentSession.status}', waiting for 'linked'`)- );+ return yield* new LoginSessionError({+ message: `Session status is still '${currentSession.status}', waiting for 'linked'`,+ operation: 'poll',+ status: currentSession.status,+ });}),Schedule.exponential('0.3 seconds').pipe(Schedule.intersect(Schedule.recurs(15)),@@ -788,7 +814,9 @@ export const loginCmd = Command.make(}if (Option.isSome(key) && Option.isSome(userApiKey)) {- return yield* Effect.fail(new Error('Use either `--key` or `--user-api-key`, not both.'));+ return yield* Effect.fail(+ invalidOptionValue('Use either `--key` or `--user-api-key`, not both.')+ );}if (@@ -796,7 +824,7 @@ export const loginCmd = Command.make((noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey) || agent)) {return yield* Effect.fail(- new Error(+ invalidOptionValue('`--poll` cannot be combined with browser, session, direct-login, or agent flags.'));@@ -804,17 +832,19 @@ export const loginCmd = Command.make(if (agent && (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey))) {return yield* Effect.fail(- new Error('`--agent` cannot be combined with browser, session, or direct-login flags.')+ invalidOptionValue(+ '`--agent` cannot be combined with browser, session, or direct-login flags.'+ ));}if (Option.isSome(org) && Option.isNone(userApiKey)) {- return yield* Effect.fail(new Error('`--org` requires `--user-api-key`.'));+ return yield* Effect.fail(invalidOptionValue('`--org` requires `--user-api-key`.'));}if (Option.isSome(userApiKey) && (noBrowser || noWait || Option.isSome(key))) {return yield* Effect.fail(- new Error(+ invalidOptionValue('`--user-api-key` is a direct login path and cannot be combined with browser or session flags.'));diff --git a/ts/packages/cli/src/commands/logs-cmd/commands/logs.tools.cmd.ts b/ts/packages/cli/src/commands/logs-cmd/commands/logs.tools.cmd.tsindex f75b34306..15a855c30 100644--- a/ts/packages/cli/src/commands/logs-cmd/commands/logs.tools.cmd.ts+++ b/ts/packages/cli/src/commands/logs-cmd/commands/logs.tools.cmd.ts@@ -1,5 +1,5 @@import { Args, Command, Options } from '@effect/cli';-import { Effect, Option } from 'effect';+import { Data, Effect, Option } from 'effect';import { requireAuth } from 'src/effects/require-auth';import { TerminalUI } from 'src/services/terminal-ui';import { ComposioClientSingleton } from 'src/services/composio-clients';@@ -9,6 +9,11 @@ import { formatToolLogInfo, formatToolLogsTable } from '../format';import { commandHintStep } from 'src/services/command-hints';import { toSearchParam } from '../utils';+class ToolLogsRequestError extends Data.TaggedError('commands/ToolLogsRequestError')<{+ readonly message: string;+ readonly cause: unknown;+}> {}+type ToolLogFilterInput = {tool?: string;toolkit?: string;@@ -185,7 +190,14 @@ export const logsCmd$Tools = Command.make(if (toolLogId) {const toolLog = yield* ui.withSpinner(`Fetching tool log "${toolLogId}"...`,- Effect.tryPromise(() => client.logs.tools.retrieve(toolLogId))+ Effect.tryPromise({+ try: () => client.logs.tools.retrieve(toolLogId),+ catch: cause =>+ new ToolLogsRequestError({+ message: `Failed to fetch tool log "${toolLogId}".`,+ cause,+ }),+ }));yield* ui.log.info(@@ -197,16 +209,22 @@ export const logsCmd$Tools = Command.make(const response = yield* ui.withSpinner('Fetching tool logs...',- Effect.tryPromise(() =>- client.logs.tools.list({- cursor: Option.getOrUndefined(cursor) ?? null,- from: Option.getOrUndefined(from),- to: Option.getOrUndefined(to),- limit: clampedLimit,- case_sensitive: caseSensitive,- search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,- })- )+ Effect.tryPromise({+ try: () =>+ client.logs.tools.list({+ cursor: Option.getOrUndefined(cursor) ?? null,+ from: Option.getOrUndefined(from),+ to: Option.getOrUndefined(to),+ limit: clampedLimit,+ case_sensitive: caseSensitive,+ search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,+ }),+ catch: cause =>+ new ToolLogsRequestError({+ message: 'Failed to fetch tool logs.',+ cause,+ }),+ }));const logs = response.data ?? [];diff --git a/ts/packages/cli/src/commands/logs-cmd/commands/logs.triggers.cmd.ts b/ts/packages/cli/src/commands/logs-cmd/commands/logs.triggers.cmd.tsindex 3175ef6f0..430878b7b 100644--- a/ts/packages/cli/src/commands/logs-cmd/commands/logs.triggers.cmd.ts+++ b/ts/packages/cli/src/commands/logs-cmd/commands/logs.triggers.cmd.ts@@ -1,14 +1,20 @@import { Args, Command, Options } from '@effect/cli';-import { Effect, Option } from 'effect';+import { Data, Effect, Option } from 'effect';import { requireAuth } from 'src/effects/require-auth';import { TerminalUI } from 'src/services/terminal-ui';import { ComposioClientSingleton } from 'src/services/composio-clients';import { clampLimit } from 'src/ui/clamp-limit';import { parseCsv } from 'src/commands/triggers/parse-csv';import { formatTriggerLogInfo, formatTriggerLogsTable } from '../format';+import { decodeTriggerLogRecord } from '../trigger-log-record';import { commandHintStep } from 'src/services/command-hints';import { toSearchParam } from '../utils';+class TriggerLogsRequestError extends Data.TaggedError('commands/TriggerLogsRequestError')<{+ readonly message: string;+ readonly cause: unknown;+}> {}+const cursor = Options.text('cursor').pipe(Options.withDescription('Cursor for pagination'),Options.optional@@ -149,34 +155,45 @@ export const logsCmd$Triggers = Command.make(if (triggerLogId) {const triggerLog = yield* ui.withSpinner(`Fetching trigger log "${triggerLogId}"...`,- Effect.tryPromise(() => client.logs.triggers.retrieve(triggerLogId))+ Effect.tryPromise({+ try: () => client.logs.triggers.retrieve(triggerLogId),+ catch: cause =>+ new TriggerLogsRequestError({+ message: `Failed to fetch trigger log "${triggerLogId}".`,+ cause,+ }),+ }));- const triggerLogData = triggerLog as unknown as Record<string, unknown>;- const normalizedLogData = getTriggerLogRecord(triggerLogData);- const payload = getTriggerPayload(normalizedLogData);- const response = getTriggerResponse(normalizedLogData);+ const record = decodeTriggerLogRecord(triggerLog);yield* ui.log.info(- `${formatTriggerLogInfo(triggerLog)}\n\nPayload:\n${JSON.stringify(payload, null, 2)}\n\nResponse:\n${JSON.stringify(response, null, 2)}`+ `${formatTriggerLogInfo(record)}\n\nPayload:\n${JSON.stringify(record.payload, null, 2)}\n\nResponse:\n${JSON.stringify(record.response, null, 2)}`);+ // Raw API payload for scripts; only human-readable formatting uses the decoded record.yield* ui.output(JSON.stringify(triggerLog, null, 2));return;}const response = yield* ui.withSpinner('Fetching trigger logs...',- Effect.tryPromise(() =>- client.logs.triggers.list({- cursor: Option.getOrUndefined(cursor),- from: Option.getOrUndefined(from),- to: Option.getOrUndefined(to),- limit: clampedLimit,- time: Option.getOrUndefined(time),- search: Option.getOrUndefined(search),- include_payload: includePayload,- search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,- })- )+ Effect.tryPromise({+ try: () =>+ client.logs.triggers.list({+ cursor: Option.getOrUndefined(cursor),+ from: Option.getOrUndefined(from),+ to: Option.getOrUndefined(to),+ limit: clampedLimit,+ time: Option.getOrUndefined(time),+ search: Option.getOrUndefined(search),+ include_payload: includePayload,+ search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,+ }),+ catch: cause =>+ new TriggerLogsRequestError({+ message: 'Failed to fetch trigger logs.',+ cause,+ }),+ }));const logs = response.data ?? [];@@ -188,7 +205,7 @@ export const logsCmd$Triggers = Command.make(}yield* ui.log.info(- `Listing ${logs.length} trigger log${logs.length === 1 ? '' : 's'}\n\n${formatTriggerLogsTable(logs)}`+ `Listing ${logs.length} trigger log${logs.length === 1 ? '' : 's'}\n\n${formatTriggerLogsTable(logs.map(decodeTriggerLogRecord))}`);const firstLogId = logs[0]?.id;@@ -207,50 +224,3 @@ export const logsCmd$Triggers = Command.make(yield* ui.output(JSON.stringify(response, null, 2));})).pipe(Command.withDescription('List trigger logs.'));--export const getTriggerLogRecord = (record: Record<string, unknown>): Record<string, unknown> => {- const log = record.log;- if (log && typeof log === 'object') return log as Record<string, unknown>;- return record;-};--export const getTriggerPayload = (record: Record<string, unknown>): unknown => {- const meta = record.meta;- const metaRecord = meta && typeof meta === 'object' ? (meta as Record<string, unknown>) : {};- const rawPayload =- metaRecord.triggerProviderPayload ??- metaRecord.triggerClientPayload ??- record.payloadReceived ??- record.payload ??- null;-- return parseMaybeJson(rawPayload);-};--export const getTriggerResponse = (record: Record<string, unknown>): unknown => {- const meta = record.meta;- const metaRecord = meta && typeof meta === 'object' ? (meta as Record<string, unknown>) : {};- const rawResponse =- metaRecord.triggerClientResponse ??- metaRecord.triggerProviderResponse ??- record.response ??- null;-- return parseMaybeJson(rawResponse);-};--export const parseMaybeJson = (value: unknown): unknown => {- if (typeof value !== 'string') return value;- const trimmed = value.trim();- if (- (trimmed.startsWith('{') && trimmed.endsWith('}')) ||- (trimmed.startsWith('[') && trimmed.endsWith(']'))- ) {- try {- return JSON.parse(trimmed);- } catch {- return value;- }- }- return value;-};diff --git a/ts/packages/cli/src/commands/logs-cmd/format.ts b/ts/packages/cli/src/commands/logs-cmd/format.tsindex a96e47998..144c39748 100644--- a/ts/packages/cli/src/commands/logs-cmd/format.ts+++ b/ts/packages/cli/src/commands/logs-cmd/format.ts@@ -1,8 +1,8 @@import type { Logs } from '@composio/client/resources/logs/logs';+import type { TriggerLogRecord } from 'src/commands/logs-cmd/trigger-log-record';import { bold, gray, green, red } from 'src/ui/colors';import { truncate } from 'src/ui/truncate';-type TriggerLog = Logs.TriggerListResponse.Data;type ToolLog = Logs.ToolListResponse.Data;type ToolLogDetailed = Logs.ToolRetrieveResponse;@@ -26,7 +26,7 @@ const TOOL_LOG_TABLE = {connectedAccountId: 20,} as const;-export const formatTriggerLogsTable = (logs: ReadonlyArray<TriggerLog>): string => {+export const formatTriggerLogsTable = (logs: ReadonlyArray<TriggerLogRecord>): string => {const header = [bold('Created At'.padEnd(TRIGGER_LOG_TABLE.createdAt)),bold('Log Id'.padEnd(TRIGGER_LOG_TABLE.id)),@@ -44,13 +44,15 @@ export const formatTriggerLogsTable = (logs: ReadonlyArray<TriggerLog>): string));const id = (log.id ?? '-').padEnd(TRIGGER_LOG_TABLE.id);- const triggerId = truncate(getTriggerId(log), TRIGGER_LOG_TABLE.triggerId).padEnd(+ const triggerId = truncate(+ valueOrDash(log.table.triggerId),TRIGGER_LOG_TABLE.triggerId- );+ ).padEnd(TRIGGER_LOG_TABLE.triggerId);const app = truncate(log.appName ?? '-', TRIGGER_LOG_TABLE.app).padEnd(TRIGGER_LOG_TABLE.app);- const triggerName = truncate(getTriggerName(log), TRIGGER_LOG_TABLE.triggerName).padEnd(+ const triggerName = truncate(+ valueOrDash(log.table.triggerName),TRIGGER_LOG_TABLE.triggerName- );+ ).padEnd(TRIGGER_LOG_TABLE.triggerName);const triggerUserId = truncate(log.entityId ?? '-', TRIGGER_LOG_TABLE.triggerUserId).padEnd(TRIGGER_LOG_TABLE.triggerUserId);@@ -118,46 +120,6 @@ const valueOrDash = (value: string | null | undefined): string => {return normalizedValue.length > 0 ? normalizedValue : '-';};-const getTriggerId = (log: TriggerLog): string => {- const dynamicLog = log as unknown as Record<string, unknown>;- const dynamicMeta = (dynamicLog.meta ?? {}) as Record<string, unknown>;- const triggerId =- typeof dynamicMeta.triggerNanoId === 'string'- ? dynamicMeta.triggerNanoId- : typeof dynamicMeta.trigger_nano_id === 'string'- ? dynamicMeta.trigger_nano_id- : typeof dynamicMeta.triggerId === 'string'- ? dynamicMeta.triggerId- : typeof dynamicMeta.trigger_id === 'string'- ? dynamicMeta.trigger_id- : typeof dynamicLog.triggerNanoId === 'string'- ? dynamicLog.triggerNanoId- : typeof dynamicLog.trigger_nano_id === 'string'- ? dynamicLog.trigger_nano_id- : typeof dynamicLog.triggerId === 'string'- ? dynamicLog.triggerId- : typeof dynamicLog.trigger_id === 'string'- ? dynamicLog.trigger_id- : null;- return valueOrDash(triggerId);-};--const getTriggerName = (log: TriggerLog): string => {- const dynamicLog = log as unknown as Record<string, unknown>;- const dynamicMeta = (dynamicLog.meta ?? {}) as Record<string, unknown>;- const triggerName =- typeof dynamicMeta.triggerName === 'string'- ? dynamicMeta.triggerName- : typeof dynamicMeta.trigger_name === 'string'- ? dynamicMeta.trigger_name- : typeof dynamicLog.triggerName === 'string'- ? dynamicLog.triggerName- : typeof dynamicLog.trigger_name === 'string'- ? dynamicLog.trigger_name- : null;- return valueOrDash(triggerName);-};-const formatEpoch = (value: number): string => {const date = new Date(value);if (Number.isNaN(date.getTime())) return '-';@@ -186,83 +148,19 @@ export const formatToolLogInfo = (toolLog: ToolLogDetailed): string => {return lines.join('\n');};-export const formatTriggerLogInfo = (triggerLog: unknown): string => {- const rawLog = triggerLog as Record<string, unknown>;- const logCandidate = rawLog.log;- const log =- logCandidate && typeof logCandidate === 'object'- ? (logCandidate as Record<string, unknown>)- : rawLog;+export const formatTriggerLogInfo = (triggerLog: TriggerLogRecord): string => {+ const { detail } = triggerLog;const lines: string[] = [];- lines.push(`${bold('logId:')} ${valueOrDash(getRecordString(log, ['id', 'logId', 'log_id']))}`);- lines.push(- `${bold('triggerId:')} ${valueOrDash(getRecordString(log, ['triggerId', 'trigger_id']))}`- );- lines.push(- `${bold('triggerNanoId:')} ${valueOrDash(- getRecordString(log, ['triggerNanoId', 'trigger_nano_id'])- )}`- );- lines.push(- `${bold('trigger:')} ${valueOrDash(getRecordString(log, ['triggerName', 'trigger_name']))}`- );- lines.push(`${bold('Status:')} ${valueOrDash(getRecordString(log, ['status']))}`);- lines.push(- `${bold('toolkit:')} ${valueOrDash(getRecordString(log, ['appName', 'toolkit', 'toolkit_key']))}`- );- lines.push(- `${bold('Connection ID:')} ${valueOrDash(- getRecordString(log, ['connectionId', 'connection_id', 'connectedAccountId'])- )}`- );- lines.push(- `${bold('Entity:')} ${valueOrDash(getRecordString(log, ['entityId', 'entity_id', 'userId']))}`- );- lines.push(- `${bold('Created At:')} ${formatCreatedAt(- getRecordNumberOrString(log, ['createdAt', 'created_at'])- )}`- );+ lines.push(`${bold('logId:')} ${valueOrDash(detail.logId)}`);+ lines.push(`${bold('triggerId:')} ${valueOrDash(detail.triggerId)}`);+ lines.push(`${bold('triggerNanoId:')} ${valueOrDash(detail.triggerNanoId)}`);+ lines.push(`${bold('trigger:')} ${valueOrDash(detail.triggerName)}`);+ lines.push(`${bold('Status:')} ${valueOrDash(detail.status)}`);+ lines.push(`${bold('toolkit:')} ${valueOrDash(detail.toolkit)}`);+ lines.push(`${bold('Connection ID:')} ${valueOrDash(detail.connectionId)}`);+ lines.push(`${bold('Entity:')} ${valueOrDash(detail.entityId)}`);+ lines.push(`${bold('Created At:')} ${formatCreatedAt(detail.createdAt)}`);return lines.join('\n');};--const getRecordString = (record: Record<string, unknown>, keys: ReadonlyArray<string>) => {- for (const key of keys) {- const value = record[key];- if (typeof value === 'string') return value;- }-- const meta = record.meta;- if (meta && typeof meta === 'object') {- const metaRecord = meta as Record<string, unknown>;- for (const key of keys) {- const value = metaRecord[key];- if (typeof value === 'string') return value;- }- }-- return null;-};--const getRecordNumberOrString = (- record: Record<string, unknown>,- keys: ReadonlyArray<string>-): number | string | null => {- for (const key of keys) {- const value = record[key];- if (typeof value === 'number' || typeof value === 'string') return value;- }-- const meta = record.meta;- if (meta && typeof meta === 'object') {- const metaRecord = meta as Record<string, unknown>;- for (const key of keys) {- const value = metaRecord[key];- if (typeof value === 'number' || typeof value === 'string') return value;- }- }-- return null;-};diff --git a/ts/packages/cli/src/commands/logs-cmd/trigger-log-record.ts b/ts/packages/cli/src/commands/logs-cmd/trigger-log-record.tsnew file mode 100644index 000000000..4567f3149--- /dev/null+++ b/ts/packages/cli/src/commands/logs-cmd/trigger-log-record.ts@@ -0,0 +1,295 @@+import { Option, Schema } from 'effect';++/**+ * Tolerant normalization of trigger-log API payloads.+ *+ * The `@composio/client` type (`Logs.TriggerListResponse.Data`) declares+ * trigger metadata under `meta` in camelCase, but the API has historically+ * served camelCase and snake_case variants at both the top level and under+ * `meta`. Instead of mining those aliases with `as ... as Record` casts at+ * every call site, payloads are decoded once at the API boundary into the+ * canonical {@link TriggerLogRecord} shape.+ *+ * Decoding is deliberately lenient: wrongly-typed fields behave as absent and+ * a completely garbage payload decodes to an empty record, so formatting+ * falls back to `'-'` placeholders instead of failing the command.+ */++/** Decodes to the string value when present, treating any other type as absent. */+const LenientString = Schema.transform(Schema.Unknown, Schema.UndefinedOr(Schema.String), {+ strict: true,+ decode: value => (typeof value === 'string' ? value : undefined),+ encode: value => value,+});++/** Decodes to the string or number value when present, treating any other type as absent. */+const LenientTimestamp = Schema.transform(+ Schema.Unknown,+ Schema.UndefinedOr(Schema.Union(Schema.String, Schema.Number)),+ {+ strict: true,+ decode: value => (typeof value === 'string' || typeof value === 'number' ? value : undefined),+ encode: value => value,+ }+);++/**+ * Every alias the CLI has ever mined from trigger logs. The same aliases can+ * appear at the top level of a record and under its `meta` object.+ */+const aliasFields = {+ id: Schema.optional(LenientString),+ logId: Schema.optional(LenientString),+ log_id: Schema.optional(LenientString),+ triggerId: Schema.optional(LenientString),+ trigger_id: Schema.optional(LenientString),+ triggerNanoId: Schema.optional(LenientString),+ trigger_nano_id: Schema.optional(LenientString),+ triggerName: Schema.optional(LenientString),+ trigger_name: Schema.optional(LenientString),+ status: Schema.optional(LenientString),+ appName: Schema.optional(LenientString),+ toolkit: Schema.optional(LenientString),+ toolkit_key: Schema.optional(LenientString),+ connectionId: Schema.optional(LenientString),+ connection_id: Schema.optional(LenientString),+ connectedAccountId: Schema.optional(LenientString),+ entityId: Schema.optional(LenientString),+ entity_id: Schema.optional(LenientString),+ userId: Schema.optional(LenientString),+ createdAt: Schema.optional(LenientTimestamp),+ created_at: Schema.optional(LenientTimestamp),+};++const RawTriggerLogMeta = Schema.Struct({+ ...aliasFields,+ triggerProviderPayload: Schema.optional(Schema.Unknown),+ triggerClientPayload: Schema.optional(Schema.Unknown),+ triggerClientResponse: Schema.optional(Schema.Unknown),+ triggerProviderResponse: Schema.optional(Schema.Unknown),+});+type RawTriggerLogMeta = typeof RawTriggerLogMeta.Type;++const decodeMetaOption = Schema.decodeUnknownOption(RawTriggerLogMeta);++/** Any non-record `meta` behaves like an absent one. */+const LenientMeta = Schema.transform(+ Schema.Unknown,+ Schema.UndefinedOr(Schema.typeSchema(RawTriggerLogMeta)),+ {+ strict: true,+ decode: value => Option.getOrUndefined(decodeMetaOption(value)),+ encode: value => value,+ }+);++const rawLevelFields = {+ ...aliasFields,+ payloadReceived: Schema.optional(Schema.Unknown),+ payload: Schema.optional(Schema.Unknown),+ response: Schema.optional(Schema.Unknown),+ meta: Schema.optional(LenientMeta),+};++const RawTriggerLogLevel = Schema.Struct(rawLevelFields);+type RawTriggerLogLevel = typeof RawTriggerLogLevel.Type;++const decodeLevelOption = Schema.decodeUnknownOption(RawTriggerLogLevel);++/**+ * `logs.triggers.retrieve` responses wrap the record under `log`. Any object+ * there is used as the record (even one that yields no fields); everything+ * else falls back to the top level.+ */+const LenientNestedLog = Schema.transform(+ Schema.Unknown,+ Schema.UndefinedOr(Schema.typeSchema(RawTriggerLogLevel)),+ {+ strict: true,+ decode: value =>+ typeof value === 'object' && value !== null+ ? Option.getOrElse(decodeLevelOption(value), (): RawTriggerLogLevel => ({}))+ : undefined,+ encode: value => value,+ }+);++const RawTriggerLog = Schema.Struct({+ ...rawLevelFields,+ log: Schema.optional(LenientNestedLog),+});++/**+ * Canonical trigger-log shape consumed by the `logs triggers` formatting code.+ *+ * - Top-level fields hold the values exactly as the client type declares them+ * (the plain list-table columns).+ * - `detail` holds alias-resolved fields for the info block. Precedence: the+ * listed aliases at the top level of the record first, then the same+ * aliases under `meta`.+ * - `table` holds the trigger columns of the list table, which historically+ * resolved `meta` aliases first (nano id preferred over plain id) and only+ * then the top level.+ */+export const TriggerLogRecord = Schema.Struct({+ id: Schema.optional(Schema.String),+ appName: Schema.optional(Schema.String),+ entityId: Schema.optional(Schema.String),+ connectionId: Schema.optional(Schema.String),+ createdAt: Schema.optional(Schema.Union(Schema.String, Schema.Number)),+ detail: Schema.Struct({+ /** `id` → `logId` → `log_id`, top level then `meta`. */+ logId: Schema.optional(Schema.String),+ /** `triggerId` → `trigger_id`, top level then `meta`. */+ triggerId: Schema.optional(Schema.String),+ /** `triggerNanoId` → `trigger_nano_id`, top level then `meta`. */+ triggerNanoId: Schema.optional(Schema.String),+ /** `triggerName` → `trigger_name`, top level then `meta`. */+ triggerName: Schema.optional(Schema.String),+ /** `status`, top level then `meta`. */+ status: Schema.optional(Schema.String),+ /** `appName` → `toolkit` → `toolkit_key`, top level then `meta`. */+ toolkit: Schema.optional(Schema.String),+ /** `connectionId` → `connection_id` → `connectedAccountId`, top level then `meta`. */+ connectionId: Schema.optional(Schema.String),+ /** `entityId` → `entity_id` → `userId`, top level then `meta`. */+ entityId: Schema.optional(Schema.String),+ /** `createdAt` → `created_at`, top level then `meta`. */+ createdAt: Schema.optional(Schema.Union(Schema.String, Schema.Number)),+ }),+ table: Schema.Struct({+ /** Nano id preferred over plain id; `meta` aliases before top-level ones. */+ triggerId: Schema.optional(Schema.String),+ /** `triggerName` → `trigger_name`, `meta` then top level. */+ triggerName: Schema.optional(Schema.String),+ }),+ /**+ * `meta.triggerProviderPayload` → `meta.triggerClientPayload` →+ * `payloadReceived` → `payload` → `null`, JSON-parsed when it looks like JSON.+ */+ payload: Schema.Unknown,+ /**+ * `meta.triggerClientResponse` → `meta.triggerProviderResponse` →+ * `response` → `null`, JSON-parsed when it looks like JSON.+ */+ response: Schema.Unknown,+});+export type TriggerLogRecord = typeof TriggerLogRecord.Type;++/** Parses strings that look like JSON objects/arrays, passing everything else through. */+export const parseMaybeJson = (value: unknown): unknown => {+ if (typeof value !== 'string') return value;+ const trimmed = value.trim();+ if (+ (trimmed.startsWith('{') && trimmed.endsWith('}')) ||+ (trimmed.startsWith('[') && trimmed.endsWith(']'))+ ) {+ return Option.getOrElse(+ Option.liftThrowable((input: string): unknown => JSON.parse(input))(trimmed),+ () => value+ );+ }+ return value;+};++const normalizeLevel = (level: RawTriggerLogLevel): TriggerLogRecord => {+ const meta = level.meta;++ return {+ id: level.id,+ appName: level.appName,+ entityId: level.entityId,+ connectionId: level.connectionId,+ createdAt: level.createdAt,+ detail: {+ logId: level.id ?? level.logId ?? level.log_id ?? meta?.id ?? meta?.logId ?? meta?.log_id,+ triggerId: level.triggerId ?? level.trigger_id ?? meta?.triggerId ?? meta?.trigger_id,+ triggerNanoId:+ level.triggerNanoId ??+ level.trigger_nano_id ??+ meta?.triggerNanoId ??+ meta?.trigger_nano_id,+ triggerName:+ level.triggerName ?? level.trigger_name ?? meta?.triggerName ?? meta?.trigger_name,+ status: level.status ?? meta?.status,+ toolkit:+ level.appName ??+ level.toolkit ??+ level.toolkit_key ??+ meta?.appName ??+ meta?.toolkit ??+ meta?.toolkit_key,+ connectionId:+ level.connectionId ??+ level.connection_id ??+ level.connectedAccountId ??+ meta?.connectionId ??+ meta?.connection_id ??+ meta?.connectedAccountId,+ entityId:+ level.entityId ??+ level.entity_id ??+ level.userId ??+ meta?.entityId ??+ meta?.entity_id ??+ meta?.userId,+ createdAt: level.createdAt ?? level.created_at ?? meta?.createdAt ?? meta?.created_at,+ },+ table: {+ triggerId:+ meta?.triggerNanoId ??+ meta?.trigger_nano_id ??+ meta?.triggerId ??+ meta?.trigger_id ??+ level.triggerNanoId ??+ level.trigger_nano_id ??+ level.triggerId ??+ level.trigger_id,+ triggerName:+ meta?.triggerName ?? meta?.trigger_name ?? level.triggerName ?? level.trigger_name,+ },+ payload: parseMaybeJson(+ meta?.triggerProviderPayload ??+ meta?.triggerClientPayload ??+ level.payloadReceived ??+ level.payload ??+ null+ ),+ response: parseMaybeJson(+ meta?.triggerClientResponse ?? meta?.triggerProviderResponse ?? level.response ?? null+ ),+ };+};++const TriggerLogRecordFromRaw = Schema.transform(RawTriggerLog, TriggerLogRecord, {+ strict: true,+ decode: raw => normalizeLevel(raw.log ?? raw),+ encode: record => ({+ id: record.id,+ appName: record.appName,+ entityId: record.entityId,+ connectionId: record.connectionId,+ createdAt: record.createdAt,+ logId: record.detail.logId,+ triggerId: record.detail.triggerId,+ triggerNanoId: record.detail.triggerNanoId,+ triggerName: record.detail.triggerName,+ status: record.detail.status,+ toolkit: record.detail.toolkit,+ payload: record.payload,+ response: record.response,+ }),+});++const decodeTriggerLogRecordOption = Schema.decodeUnknownOption(TriggerLogRecordFromRaw);++/** Canonical record produced when a payload cannot be decoded at all. */+export const emptyTriggerLogRecord: TriggerLogRecord = normalizeLevel({});++/**+ * Decodes an unknown trigger-log payload into the canonical+ * {@link TriggerLogRecord}, falling back to {@link emptyTriggerLogRecord}+ * (which formats as `'-'` placeholders) when the payload is not an object.+ */+export const decodeTriggerLogRecord = (input: unknown): TriggerLogRecord =>+ Option.getOrElse(decodeTriggerLogRecordOption(input), () => emptyTriggerLogRecord);diff --git a/ts/packages/cli/src/commands/proxy.cmd.ts b/ts/packages/cli/src/commands/proxy.cmd.tsindex f6a12ff52..cbf4e7860 100644--- a/ts/packages/cli/src/commands/proxy.cmd.ts+++ b/ts/packages/cli/src/commands/proxy.cmd.ts@@ -1,5 +1,5 @@import { Args, Command, Options } from '@effect/cli';-import { Effect, Either, Option } from 'effect';+import { Data, Effect, Either, Option } from 'effect';import type {SessionProxyExecuteParams,SessionProxyExecuteResponse,@@ -62,20 +62,33 @@ type ProxyMethod = Extract<'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'>;-const SUPPORTED_PROXY_METHODS = [+const SUPPORTED_PROXY_METHODS: ReadonlyArray<ProxyMethod> = ['GET','POST','PUT','DELETE','PATCH',-] as const satisfies ReadonlyArray<ProxyMethod>;+];++export class ProxyCommandError extends Data.TaggedError('commands/ProxyCommandError')<{+ readonly reason: 'missing_consumer_user' | 'toolkit_not_connected';+ readonly message: string;+ readonly toolkit?: string;+ readonly endpoint?: string;+}> {}++class ProxyRequestError extends Data.TaggedError('commands/ProxyRequestError')<{+ readonly message: string;+ readonly cause: unknown;+}> {}export const normalizeProxyMethod = (value: string): ProxyMethod => {const normalized = value.trim().toUpperCase();- if (!SUPPORTED_PROXY_METHODS.includes(normalized as ProxyMethod)) {+ const supported = SUPPORTED_PROXY_METHODS.find(method => method === normalized);+ if (!supported) {throw new Error('Unsupported method. Use one of GET, POST, PUT, DELETE, PATCH.');}- return normalized as ProxyMethod;+ return supported;};export const parseProxyHeader = (value: string): { name: string; value: string } => {@@ -162,17 +175,9 @@ const handleProxyExecutionError = (params: {].join('\n'),'Tips');- const output = formatProxyErrorOutput({- error: mapped.message,- toolkit: params.toolkit,- endpoint: params.endpoint,- slug: mapped.slugValue,- });- yield* params.ui.output(output);- return yield* Effect.fail(mapped.normalized);+ } else {+ yield* params.ui.log.error(mapped.message);}-- yield* params.ui.log.error(mapped.message);const output = formatProxyErrorOutput({error: mapped.message,toolkit: params.toolkit,@@ -234,7 +239,12 @@ const runProxyConnectedToolkitFailFast = (params: {2));- return yield* Effect.fail(new Error(message));+ return yield* new ProxyCommandError({+ reason: 'toolkit_not_connected',+ message,+ toolkit: params.toolkit,+ endpoint: params.endpoint,+ });}});@@ -272,9 +282,10 @@ export const proxyCmd = Command.make('proxy', {);if (resolvedProject.projectType !== 'CONSUMER' || !resolvedProject.consumerUserId) {- return yield* Effect.fail(- new Error('No consumer project user is available for proxy execution in this context.')- );+ return yield* new ProxyCommandError({+ reason: 'missing_consumer_user',+ message: 'No consumer project user is available for proxy execution in this context.',+ });}const consumerUserId = resolvedProject.consumerUserId;const normalizedToolkit = toolkit.toLowerCase();@@ -289,14 +300,16 @@ export const proxyCmd = Command.make('proxy', {});const normalizedMethod = normalizeProxyMethod(method);- const headerParameters = headers.map(header => {- const parsed = parseProxyHeader(header);- return {- name: parsed.name,- type: 'header' as const,- value: parsed.value,- };- });+ const headerParameters: NonNullable<SessionProxyExecuteParams['parameters']> = headers.map(+ header => {+ const parsed = parseProxyHeader(header);+ return {+ name: parsed.name,+ type: 'header',+ value: parsed.value,+ };+ }+ );const rawBody = yield* resolveBodyInput(data);const parsedBody = rawBody === undefined ? undefined : parseProxyBody(rawBody);@@ -316,26 +329,32 @@ export const proxyCmd = Command.make('proxy', {},});- const resultEither = yield* Effect.tryPromise(() =>- client.toolRouter.session.proxyExecute(sessionId, {- toolkit_slug: normalizedToolkit,- endpoint,- method: normalizedMethod,- ...(parsedBody !== undefined ? { body: parsedBody } : {}),- ...(headerParameters.length > 0 ? { parameters: headerParameters } : {}),+ return yield* Effect.tryPromise({+ try: () =>+ client.toolRouter.session.proxyExecute(sessionId, {+ toolkit_slug: normalizedToolkit,+ endpoint,+ method: normalizedMethod,+ ...(parsedBody !== undefined ? { body: parsedBody } : {}),+ ...(headerParameters.length > 0 ? { parameters: headerParameters } : {}),+ }),+ catch: cause =>+ new ProxyRequestError({+ message: `Failed to proxy ${normalizedMethod} ${endpoint} via "${normalizedToolkit}".`,+ cause,+ }),+ }).pipe(+ Effect.matchEffect({+ onFailure: error =>+ handleProxyExecutionError({+ ui,+ error,+ toolkit: normalizedToolkit,+ endpoint,+ }),+ onSuccess: Effect.succeed,})- ).pipe(Effect.either);-- if (resultEither._tag === 'Left') {- return yield* handleProxyExecutionError({- ui,- error: resultEither.left,- toolkit: normalizedToolkit,- endpoint,- });- }-- return resultEither.right;+ );}));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.tsindex 1692020ab..ba5aed075 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,8 +1,6 @@-// 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';-import { FileSystem } from '@effect/platform';+import { Command, HelpDoc, Options, ValidationError } from '@effect/cli';+import { Array, Data, Effect, Option, pipe, String } from 'effect';+import { FileSystem, Path } from '@effect/platform';import { ComposioToolkitsRepository } from 'src/services/composio-clients';import { logMetrics } from 'src/effects/log-metrics';import type { GetCmdParams } from 'src/type-utils';@@ -18,6 +16,16 @@ import {import { validateToolkitVersionOverrides } from 'src/effects/validate-toolkit-versions';import { TerminalUI } from 'src/services/terminal-ui';+export class PythonGenerationWriteError extends Data.TaggedError(+ 'commands/PythonGenerationWriteError'+)<{+ readonly cause: unknown;+ readonly filePath: string;+ readonly message: string;+}> {}++const invalidGenerateValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));+export const outputOpt = Options.optional(Options.directory('output-dir', {exists: 'either',@@ -54,6 +62,7 @@ export function generatePythonTypeStubs({const process = yield* NodeProcess;const cwd = process.cwd;const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;const client = yield* ComposioToolkitsRepository;yield* ui.intro('composio generate py');@@ -69,7 +78,7 @@ export function generatePythonTypeStubs({const normalizedPath = path.normalize(outputDir);if (normalizedPath.includes('node_modules')) {return Effect.fail(- new Error(+ invalidGenerateValue('Output directory cannot be inside node_modules. Please specify a different directory.'));@@ -106,7 +115,7 @@ export function generatePythonTypeStubs({.pipe(Effect.catchTag('services/InvalidToolkitsError', error =>Effect.fail(- new Error(+ invalidGenerateValue(`Invalid toolkit(s): ${error.invalidToolkits.join(', ')}. ` +`Available toolkits: ${error.availableToolkits.slice(0, 10).join(', ')}${error.availableToolkits.length > 10 ? '...' : ''}`)@@ -144,9 +153,10 @@ export function generatePythonTypeStubs({// Build version map for toolkits being generated (using validated overrides)const versionMap: ToolkitVersionOverrides = new Map();for (const toolkit of toolkits) {- const version = validatedOverrides.get(toolkit.slug.toLowerCase() as Lowercase<string>);+ const normalizedSlug = String.toLowerCase(toolkit.slug);+ const version = validatedOverrides.get(normalizedSlug);if (version && version !== 'latest') {- versionMap.set(toolkit.slug.toLowerCase() as Lowercase<string>, version);+ versionMap.set(normalizedSlug, version);}}@@ -167,15 +177,19 @@ export function generatePythonTypeStubs({yield* pipe(Effect.all(sources.map(([filePath, content]) =>- fs- .writeFileString(filePath, content)- .pipe(- Effect.mapError(error => new Error(`Failed to write file ${filePath}: ${error}`))+ fs.writeFileString(filePath, content).pipe(+ Effect.mapError(+ cause =>+ new PythonGenerationWriteError({+ cause,+ filePath,+ message: `Failed to write file ${filePath}`,+ }))+ )),{ concurrency: 1 }- ),- Effect.mapError(error => new Error(`Failed to write generated files: ${error}`))+ ));yield* spinner.stop('Type stubs generated successfully');diff --git a/ts/packages/cli/src/commands/setup.cmd.ts b/ts/packages/cli/src/commands/setup.cmd.tsindex fa58e61bd..90bbe9a14 100644--- a/ts/packages/cli/src/commands/setup.cmd.ts+++ b/ts/packages/cli/src/commands/setup.cmd.ts@@ -1,5 +1,5 @@import { Command, Options } from '@effect/cli';-import { Effect } from 'effect';+import { Effect, Predicate } from 'effect';import {detectSetupTargets,inspectSetupTargets,@@ -10,13 +10,12 @@ import {SetupCommandError,uninstallSetupTargets,type AgentHost,- type SetupTarget,} from 'src/services/setup';import { TerminalUI } from 'src/services/terminal-ui';import { SetupSkillInstaller } from 'src/services/setup-skill-installer';const target = Options.choice('target', SETUP_TARGETS).pipe(- Options.withDefault('auto' as SetupTarget),+ Options.withDefault('auto'),Options.withDescription('Agent host to configure: auto, claude, codex, or all'));@@ -45,7 +44,14 @@ const formatTargets = (targets: ReadonlyArray<AgentHost>): string =>targets.map(target => TARGET_LABELS[target]).join(' and ');const errorMessage = (error: unknown): string =>- error instanceof Error ? error.message : String(error);+ Predicate.isError(error) ? error.message : String(error);++const setupCommandError = (message: string, operation: 'setup' | 'uninstall', cause?: unknown) =>+ new SetupCommandError({+ message,+ operation,+ ...(cause === undefined ? {} : { cause }),+ });const setupBaseCmd = Command.make('setup',@@ -53,6 +59,8 @@ const setupBaseCmd = Command.make(({ target, yes, ifPresent, uninstall }) =>Effect.gen(function* () {const ui = yield* TerminalUI;+ const terminal = yield* ui.capabilities;+ const operation = uninstall ? 'uninstall' : 'setup';yield* ui.intro(uninstall ? 'composio setup --uninstall' : 'composio setup');const detections = yield* detectSetupTargets(target);@@ -70,10 +78,9 @@ const setupBaseCmd = Command.make(yield* ui.log.info(`${formatTargets(notDetected)} not detected.`);}if (target === 'all' && notDetected.length > 0) {- return yield* Effect.fail(- new Error(- `\`--target all\` requires Claude Code and Codex. Missing: ${formatTargets(notDetected)}. Install the missing agent host, or use \`--target auto\` to operate on detected hosts only.`- )+ return yield* setupCommandError(+ `\`--target all\` requires Claude Code and Codex. Missing: ${formatTargets(notDetected)}. Install the missing agent host, or use \`--target auto\` to operate on detected hosts only.`,+ operation);}if (unsupported.length > 0) {@@ -82,7 +89,7 @@ const setupBaseCmd = Command.make(.filter((message): message is string => Boolean(message)).join(' ');if (target !== 'auto') {- return yield* Effect.fail(new Error(reason));+ return yield* setupCommandError(reason, operation);}yield* ui.log.warn(`${formatTargets(unsupported.map(result => result.target))} plugin setup skipped. ${reason}`@@ -94,22 +101,20 @@ const setupBaseCmd = Command.make();return;}- return yield* Effect.fail(new Error(reason));+ return yield* setupCommandError(reason, operation);}}if (detected.length === 0) {if (target === 'claude' || target === 'codex') {- return yield* Effect.fail(- new Error(- `${target} is not installed or not available on PATH. Install it and rerun \`composio setup${uninstall ? ' --uninstall' : ''} --target ${target}\`.`- )+ return yield* setupCommandError(+ `${target} is not installed or not available on PATH. Install it and rerun \`composio setup${uninstall ? ' --uninstall' : ''} --target ${target}\`.`,+ operation);}if (!ifPresent || target !== 'auto') {- return yield* Effect.fail(- new Error(- `No supported agent host was detected. Install Claude Code or Codex, then rerun \`composio setup${uninstall ? ' --uninstall' : ''}\`.`- )+ return yield* setupCommandError(+ `No supported agent host was detected. Install Claude Code or Codex, then rerun \`composio setup${uninstall ? ' --uninstall' : ''}\`.`,+ operation);}yield* ui.outro(@@ -145,9 +150,10 @@ const setupBaseCmd = Command.make(}if (!yes && removable.length > 0) {- if (!(yield* ui.capabilities).isInteractive) {- return yield* Effect.fail(- new Error('Non-interactive uninstall requires `--yes` to approve local changes.')+ if (!terminal.isInteractive) {+ return yield* setupCommandError(+ 'Non-interactive uninstall requires `--yes` to approve local changes.',+ operation);}const confirmed = yield* ui.confirm(@@ -185,9 +191,10 @@ const setupBaseCmd = Command.make(const pendingPlugins = pending.filter(status => !isSetupPluginReady(status));if (!yes) {- if (!(yield* ui.capabilities).isInteractive) {- return yield* Effect.fail(- new Error('Non-interactive setup requires `--yes` to approve local changes.')+ if (!terminal.isInteractive) {+ return yield* setupCommandError(+ 'Non-interactive setup requires `--yes` to approve local changes.',+ operation);}@@ -206,7 +213,12 @@ const setupBaseCmd = Command.make(for (const result of results) {if (!result.plugin_changed) continue;- const initial = pending.find(status => status.target === result.target)!;+ const initial = pending.find(status => status.target === result.target);+ if (!initial) {+ return yield* Effect.dieMessage(+ `Setup invariant violated: missing initial state for ${result.target}`+ );+ }let action = 'configured and enabled';if (!initial.plugin_installed) action = 'installed and enabled';else if (!initial.plugin_enabled) action = 'enabled';@@ -217,12 +229,10 @@ const setupBaseCmd = Command.make(yield* ui.outro('Composio setup complete.');}).pipe(- Effect.mapError(- error =>- new SetupCommandError({- message: errorMessage(error),- operation: uninstall ? 'uninstall' : 'setup',- })+ Effect.mapError(error =>+ error instanceof SetupCommandError+ ? error+ : setupCommandError(errorMessage(error), uninstall ? 'uninstall' : 'setup', error))));diff --git a/ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts b/ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.tsindex 0ae348e40..f17f4d3eb 100644--- a/ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts+++ b/ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts@@ -1,5 +1,5 @@import { Args, Command, Options } from '@effect/cli';-import { Effect, Option } from 'effect';+import { Data, Effect, Option } from 'effect';import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';import { TerminalUI } from 'src/services/terminal-ui';import { requireAuth } from 'src/effects/require-auth';@@ -9,6 +9,11 @@ import { ProjectContext } from 'src/services/project-context';import { ComposioUserContext } from 'src/services/user-context';import { formatToolkitInfo, formatToolkitInfoJson } from '../format';+class ToolkitsInfoRequestError extends Data.TaggedError('commands/ToolkitsInfoRequestError')<{+ readonly message: string;+ readonly cause: unknown;+}> {}+const slug = Args.text({ name: 'slug' }).pipe(Args.withDescription('Toolkit slug (e.g. "gmail")'),Args.optional@@ -88,9 +93,14 @@ export const toolkitsCmd$Info = Command.make(if (Option.isSome(resolvedUserId)) {const client = yield* clientSingleton.get();const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value);- const sessionToolkits = yield* Effect.tryPromise(() =>- client.toolRouter.session.toolkits(sessionId, { toolkits: [slugValue] })- );+ const sessionToolkits = yield* Effect.tryPromise({+ try: () => client.toolRouter.session.toolkits(sessionId, { toolkits: [slugValue] }),+ catch: cause =>+ new ToolkitsInfoRequestError({+ message: `Failed to fetch toolkit "${slugValue}".`,+ cause,+ }),+ });return { toolkit: sessionToolkits.items[0], detailedToolkitOpt };}@@ -162,9 +172,7 @@ export const toolkitsCmd$Info = Command.make();// Next step hint- yield* ui.log.step(- `To list tools in this toolkit:\n> composio tools list "${toolkit.slug}"`- );+ yield* ui.log.step(`To list tools in this toolkit:\n> composio tools list "${toolkit.slug}"`);yield* ui.output(formatToolkitInfoJson(toolkit, detailedToolkit, allDetails));})diff --git a/ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts b/ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.tsindex 6e5c3ec5f..12d4f42b8 100644--- a/ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts+++ b/ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts@@ -1,6 +1,6 @@import process from 'node:process';import { Command, Options } from '@effect/cli';-import { Effect, Option } from 'effect';+import { Data, Effect, Option } from 'effect';import { TerminalUI } from 'src/services/terminal-ui';import { requireAuth } from 'src/effects/require-auth';import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';@@ -11,6 +11,11 @@ import { clampLimit } from 'src/ui/clamp-limit';import { extractMessage } from 'src/utils/api-error-extraction';import { mergeToolkitData, formatToolkitsJson, formatToolkitsTable } from '../format';+class ToolkitsListRequestError extends Data.TaggedError('commands/ToolkitsListRequestError')<{+ readonly message: string;+ readonly cause: unknown;+}> {}+const query = Options.text('query').pipe(Options.withDescription('Text search by name, slug, or description'),Options.optional@@ -126,15 +131,21 @@ export const toolkitsCmd$List = Command.make(let sessionFailed = false;if (sessionContext) {const { client, sessionId } = sessionContext;- sessionItems = yield* Effect.tryPromise(() =>- client.toolRouter.session.toolkits(sessionId, {- search: Option.getOrUndefined(query),- limit: clampedLimit,- is_connected: Option.getOrUndefined(connected),- })- ).pipe(+ sessionItems = yield* Effect.tryPromise({+ try: () =>+ client.toolRouter.session.toolkits(sessionId, {+ search: Option.getOrUndefined(query),+ limit: clampedLimit,+ is_connected: Option.getOrUndefined(connected),+ }),+ catch: cause =>+ new ToolkitsListRequestError({+ message: 'Failed to fetch session toolkits.',+ cause,+ }),+ }).pipe(Effect.map(r => r.items),- Effect.catchAll(error =>+ Effect.catchTag('commands/ToolkitsListRequestError', error =>Effect.logDebug('Failed to fetch session toolkits:', error).pipe(Effect.as([] as ReadonlyArray<diff --git a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.tsindex 4ab570991..d347af39a 100644--- a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts+++ b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts@@ -1,8 +1,8 @@-import { Args, Command, Options } from '@effect/cli';+import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';import type { Composio } from '@composio/client';import { isLocalToolSlug } from '@composio/cli-local-tools';import util from 'node:util';-import { Effect, Option, Either, Exit, Fiber, Cause, HashSet } from 'effect';+import { Cause, Data, Effect, Either, Exit, Fiber, HashSet, Option, Predicate } from 'effect';import { encodingForModel } from 'js-tiktoken';import { redact } from 'src/ui/redact';import { parseJsonRecord } from 'src/utils/parse-json';@@ -19,7 +19,12 @@ import {validateToolInputArgumentsWithDefinition,} from 'src/services/tool-input-validation';import { TerminalUI } from 'src/services/terminal-ui';-import { ToolsExecutor, detectInBandWarning } from 'src/services/tools-executor';+import { logToolDebug, makePerfDebugLogger } from 'src/services/runtime-debug-logger';+import {+ LocalToolsDisabledError,+ ToolsExecutor,+ detectInBandWarning,+} from 'src/services/tools-executor';import type { ToolExecuteParams, ToolExecuteResponse } from 'src/services/tools-executor';import { ComposioToolkitsRepository } from 'src/services/composio-clients';import { ComposioUserContext } from 'src/services/user-context';@@ -40,7 +45,6 @@ import {formatResolveCommandProjectError,} from 'src/services/command-project';import { commandHintStep } from 'src/services/command-hints';-import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';import {getFreshConsumerConnectedToolkitsFromCache,refreshConsumerConnectedToolkitsCache,@@ -63,6 +67,7 @@ import {import * as constants from 'src/constants';import { ComposioCliUserConfig } from 'src/services/cli-user-config';import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';+import { decodeConnectedAccountItemsWithFallback } from 'src/effects/decode-connected-account-list';const slug = Args.text({ name: 'slug' }).pipe(Args.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')@@ -130,15 +135,39 @@ const resolveInput = (input: Option.Option<string>) =>missingValue: '{}',});+const invalidArguments = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));++type ToolExecutionErrorFields = {+ readonly reason:+ | 'invalid_arguments'+ | 'file_input'+ | 'connected_account'+ | 'missing_user_id'+ | 'unsupported_local_file'+ | 'connection_check'+ | 'execution_failed'+ | 'parallel_failed';+ readonly message: string;+ readonly toolSlug?: string;+ readonly cause?: unknown;+};++export class ToolExecutionError extends Data.TaggedError(+ 'ToolExecutionError'+)<ToolExecutionErrorFields> {}++class ReportedToolExecutionError extends Data.TaggedError(+ 'ReportedToolExecutionError'+)<ToolExecutionErrorFields> {}+const parseArguments = (raw: string) =>parseJsonRecord(raw).pipe(- Either.mapLeft(- error =>- new Error(- error.reason === 'not-a-record'- ? 'Expected a JSON object for tool arguments, e.g. -d \'{ "key": "value" }\''- : 'Invalid JSON input. Provide JSON or a JS-style object literal, e.g. -d \'{ "key": "value" }\''- )+ Either.mapLeft(error =>+ invalidArguments(+ error.reason === 'not-a-record'+ ? 'Expected a JSON object for tool arguments, e.g. -d \'{ "key": "value" }\''+ : 'Invalid JSON input. Provide JSON or a JS-style object literal, e.g. -d \'{ "key": "value" }\''+ )));@@ -148,13 +177,13 @@ const hasNestedKey = (): boolean => {let current: unknown = record;for (const key of pathParts) {- if (typeof current !== 'object' || current === null || Array.isArray(current)) {+ if (!Predicate.isRecord(current)) {return false;}- if (!(key in (current as Record<string, unknown>))) {+ if (!(key in current)) {return false;}- current = (current as Record<string, unknown>)[key];+ current = current[key];}return true;};@@ -176,10 +205,7 @@ const setNestedKey = (}const next = current[key];- const nextObject =- typeof next === 'object' && next !== null && !Array.isArray(next)- ? { ...(next as Record<string, unknown>) }- : {};+ const nextObject = Predicate.isRecord(next) ? { ...next } : {};current[key] = nextObject;current = nextObject;}@@ -197,28 +223,28 @@ const injectSingleFileArgument = (params: {const uploadablePaths = findFileUploadablePaths(params.schema);if (uploadablePaths.length === 0) {- return yield* Effect.fail(- new Error(- `Tool "${params.slug}" has no file_uploadable input. Remove --file or pass JSON via -d.`- )- );+ return yield* new ToolExecutionError({+ reason: 'file_input',+ toolSlug: params.slug,+ message: `Tool "${params.slug}" has no file_uploadable input. Remove --file or pass JSON via -d.`,+ });}if (uploadablePaths.length > 1) {- return yield* Effect.fail(- new Error(- `Tool "${params.slug}" has multiple file_uploadable inputs (${uploadablePaths.map(parts => parts.join('.')).join(', ')}). Pass the target field explicitly with -d instead of --file.`- )- );+ return yield* new ToolExecutionError({+ reason: 'file_input',+ toolSlug: params.slug,+ message: `Tool "${params.slug}" has multiple file_uploadable inputs (${uploadablePaths.map(parts => parts.join('.')).join(', ')}). Pass the target field explicitly with -d instead of --file.`,+ });}const targetPath = uploadablePaths[0] ?? [];if (hasNestedKey(params.args, targetPath)) {- return yield* Effect.fail(- new Error(- `Cannot use --file because "${targetPath.join('.')}" is already set in -d. Remove that field or omit --file.`- )- );+ return yield* new ToolExecutionError({+ reason: 'file_input',+ toolSlug: params.slug,+ message: `Cannot use --file because "${targetPath.join('.')}" is already set in -d. Remove that field or omit --file.`,+ });}return setNestedKey(params.args, targetPath, params.filePath);@@ -256,25 +282,26 @@ const ciRedactReplacer = (_key: string, value: unknown): unknown => {return value;};-const formatUnknownObject = (value: object): string => {- try {- return JSON.stringify(value, null, 2);- } catch {- return util.inspect(value, { depth: 5, breakLength: 120 });- }-};+// JSON.stringify throws synchronously on circular or BigInt-bearing API+// payloads; fall back to util.inspect so the formatter stays a plain string+// function for its callers.+const formatUnknownObject = (value: object): string =>+ Either.getOrElse(+ Either.try(() => JSON.stringify(value, null, 2)),+ () => util.inspect(value, { depth: 5, breakLength: 120 })+ );const redactRequestId = (value: object): object => {if (!value || typeof value !== 'object' || Array.isArray(value)) {return value;}- const record = value as Record<string, unknown>;- const requestId = record.request_id;+ if (!Predicate.isRecord(value)) return value;+ const requestId = value.request_id;if (typeof requestId !== 'string') {return value;}return {- ...record,+ ...value,request_id: redact({ value: requestId }),};};@@ -300,6 +327,10 @@ type StoredExecuteOutputSummary = {readonly outputFilePath: string;};+type PreparedExecuteOutput =+ | { readonly kind: 'inline'; readonly json: string }+ | { readonly kind: 'file'; readonly summary: StoredExecuteOutputSummary };+const serializeExecuteOutput = (result: unknown): string =>JSON.stringify(result, ciRedactReplacer, 2);@@ -348,24 +379,7 @@ const persistLargeExecuteOutput = (toolSlug: string, json: string, sharedDirecto} satisfies StoredExecuteOutputSummary;});-const perfDebugEpoch = Date.now();-const perfDebugLog = (label: string, details: Record<string, unknown> = {}) => {- if (!isPerfDebugEnabled()) return;- // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)- process.stderr.write(- `[perf] ${JSON.stringify({- phase: 'event',- label,- elapsedMs: Date.now() - perfDebugEpoch,- ...details,- })}\n`- );-};-const toolDebugLog = (label: string, details: Record<string, unknown> = {}) => {- if (!isToolDebugEnabled()) return;- // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)- process.stderr.write(`[tool-debug] ${JSON.stringify({ label, ...details })}\n`);-};+const perfDebugLog = makePerfDebugLogger();const prepareExecuteOutput = (toolSlug: string,@@ -377,18 +391,18 @@ const prepareExecuteOutput = (const tokenCount = getExecuteOutputEncoder().encode(json).length;if (tokenCount <= EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD || !shouldStoreLargeExecuteOutput()) {return {- kind: 'inline' as const,+ kind: 'inline',json,- };+ } satisfies PreparedExecuteOutput;}return {- kind: 'file' as const,+ kind: 'file',summary: {...(yield* persistLargeExecuteOutput(toolSlug, json, sharedDirectory)),logId: result.logId,} satisfies StoredExecuteOutputSummary,- };+ } satisfies PreparedExecuteOutput;});const emitExecuteFailureTelemetry = (params: {@@ -403,10 +417,10 @@ const emitExecuteFailureTelemetry = (params: {}) =>Effect.gen(function* () {const normalized = params.mappedError?.normalized ?? normalizeCliError(params.error);- const failureOrigin =+ const failureOrigin: 'fast_fail' | 'main_endpoint' =normalized instanceof ToolInputValidationError || params.stage !== 'execution'- ? ('fast_fail' as const)- : ('main_endpoint' as const);+ ? 'fast_fail'+ : 'main_endpoint';if (normalized instanceof ToolInputValidationError) {yield* trackCliEventEffect(@@ -706,14 +720,6 @@ const handleExecutionError = (return { error: mapped.message, slug: slugValue };});-class ToolExecutionError extends Error {- readonly _tag = 'ToolExecutionError';- constructor(readonly message: string) {- super(message);- this.name = 'ToolExecutionError';- }-}-type CachedValidationDecision ={ readonly status: 'valid' | 'stale' } | { readonly status: 'fail'; readonly error: unknown };@@ -754,12 +760,12 @@ const spawnBackgroundValidationGuard = (params: {};}) =>Effect.gen(function* () {- perfDebugLog('execute.validation.background_spawn', { slug: params.slug });+ yield* perfDebugLog('execute.validation.background_spawn', { slug: params.slug });const validationFiber = yield* validateToolInputArguments(params.slug, params.args, {orgId: params.resolvedProject.orgId,projectId: params.resolvedProject.projectId,}).pipe(Effect.forkDaemon);- perfDebugLog('execute.validation.background_spawned', { slug: params.slug });+ yield* perfDebugLog('execute.validation.background_spawned', { slug: params.slug });return validationGuardFromFiber(validationFiber);});@@ -774,7 +780,7 @@ const initializeValidationState = (params: {}) =>Effect.gen(function* () {if (!params.cachedDefinition) {- perfDebugLog('execute.validation.cache_miss', { slug: params.slug });+ yield* perfDebugLog('execute.validation.cache_miss', { slug: params.slug });return {cacheHit: false,validationGuard: Effect.never,@@ -783,7 +789,7 @@ const initializeValidationState = (params: {}const cachedDefinition = params.cachedDefinition;- perfDebugLog('execute.validation.cache_hit', {+ yield* perfDebugLog('execute.validation.cache_hit', {slug: params.slug,cachedVersion: cachedDefinition.version,});@@ -796,46 +802,47 @@ const initializeValidationState = (params: {}).pipe(Effect.tap(result =>- Effect.sync(() =>- perfDebugLog('execute.validation.version_check_done', {- slug: params.slug,- cachedVersion: cachedDefinition.version,- latestVersion: result.latestVersion,- isStale: result.isStale,- })- )+ perfDebugLog('execute.validation.version_check_done', {+ slug: params.slug,+ cachedVersion: cachedDefinition.version,+ latestVersion: result.latestVersion,+ isStale: result.isStale,+ })),- Effect.either,+ Effect.option,Effect.forkDaemon);const cachedValidationDecisionFiber = yield* Effect.gen(function* () {- perfDebugLog('execute.validation.cached_start', { slug: params.slug });- const result = yield* validateToolInputArgumentsWithDefinition(+ yield* perfDebugLog('execute.validation.cached_start', { slug: params.slug });+ const validationDecision = yield* validateToolInputArgumentsWithDefinition(params.slug,params.args,cachedDefinition- ).pipe(Effect.either);- perfDebugLog('execute.validation.cached_end', {+ ).pipe(+ Effect.match({+ onFailure: error => ({ status: 'fail', error }) satisfies CachedValidationDecision,+ onSuccess: () => ({ status: 'valid' }) satisfies CachedValidationDecision,+ })+ );+ yield* perfDebugLog('execute.validation.cached_end', {slug: params.slug,- successful: Either.isRight(result),+ successful: validationDecision.status === 'valid',});- if (Either.isRight(result)) {- return { status: 'valid' as const };+ if (validationDecision.status === 'valid') {+ return validationDecision;}- const freshnessEither = yield* Fiber.join(versionCheckFiber);- const isStale = Either.isRight(freshnessEither) && freshnessEither.right.isStale;- perfDebugLog('execute.validation.cached_failed', {+ const freshnessResult = yield* Fiber.join(versionCheckFiber);+ const isStale = Option.isSome(freshnessResult) && freshnessResult.value.isStale;+ yield* perfDebugLog('execute.validation.cached_failed', {slug: params.slug,cacheStillCurrent: !isStale,});return isStale- ? { status: 'stale' as const }- : { status: 'fail' as const, error: result.left };+ ? ({ status: 'stale' } satisfies CachedValidationDecision)+ : validationDecision;}).pipe(Effect.forkDaemon);- const awaitCachedValidationDecision = Fiber.join(- cachedValidationDecisionFiber- ) as Effect.Effect<CachedValidationDecision, never>;+ const awaitCachedValidationDecision = Fiber.join(cachedValidationDecisionFiber);return {cacheHit: true,@@ -964,7 +971,7 @@ const resolveExplicitConnectedAccount = (params: {readonly toolkitSlug?: string;readonly userId: string;readonly selector: Option.Option<string>;-}): Effect.Effect<string | undefined, Error> =>+}) =>Effect.gen(function* () {if (!params.toolkitSlug) return undefined;const toolkitSlug = params.toolkitSlug;@@ -977,14 +984,28 @@ const resolveExplicitConnectedAccount = (params: {statuses: ['ACTIVE'],limit: 100,}),- catch: error =>- new Error(- `Failed to load connected accounts for toolkit "${toolkitSlug}": ${String(error)}`- ),+ catch: cause =>+ new ToolExecutionError({+ reason: 'connected_account',+ toolSlug: params.toolkitSlug,+ message: `Failed to load connected accounts for toolkit "${toolkitSlug}": ${String(cause)}`,+ cause,+ }),});+ const selectableAccounts = yield* decodeConnectedAccountItemsWithFallback(accounts.items).pipe(+ Effect.mapError(+ cause =>+ new ToolExecutionError({+ reason: 'connected_account',+ toolSlug: toolkitSlug,+ message: `Connected accounts for toolkit "${toolkitSlug}" did not match the expected response shape.`,+ cause,+ })+ )+ );const selected = resolveConnectedAccountSelection(- accounts.items as Parameters<typeof resolveConnectedAccountSelection>[0],+ selectableAccounts,Option.getOrUndefined(params.selector));@@ -996,18 +1017,16 @@ const resolveExplicitConnectedAccount = (params: {return undefined;}- const choices = formatConnectedAccountChoices(- accounts.items as Parameters<typeof formatConnectedAccountChoices>[0]- );+ const choices = formatConnectedAccountChoices(selectableAccounts);const hint =choices.length > 0? ` Available accounts: ${choices.join(', ')}.`: ' No active connected accounts were found for that toolkit.';- return yield* Effect.fail(- new Error(- `No connected account matched "${params.selector.value}" for toolkit "${toolkitSlug}".${hint}`- )- );+ return yield* new ToolExecutionError({+ reason: 'connected_account',+ toolSlug: toolkitSlug,+ message: `No connected account matched "${params.selector.value}" for toolkit "${toolkitSlug}".${hint}`,+ });});const resolveExecuteContext = (params: RunToolsExecuteParams) =>@@ -1022,16 +1041,20 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>isLocalToolSlug(params.slug) &&!cliConfig.isExperimentalFeatureEnabled(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS)) {- return yield* Effect.fail(- new Error(- `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${params.slug}.`- )- );+ return yield* new LocalToolsDisabledError({+ toolSlug: params.slug,+ feature: CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,+ message: `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${params.slug}.`,+ });}if (isLocalToolSlug(params.slug)) {if (Option.isSome(params.file)) {- return yield* Effect.fail(new Error('--file is not supported for local tools yet.'));+ return yield* new ToolExecutionError({+ reason: 'unsupported_local_file',+ toolSlug: params.slug,+ message: '--file is not supported for local tools yet.',+ });}return {ui,@@ -1074,13 +1097,14 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>});if (Option.isNone(resolvedUserId)) {- return yield* Effect.fail(- new Error(+ return yield* new ToolExecutionError({+ reason: 'missing_user_id',+ toolSlug: params.slug,+ message:params.projectMode === 'developer'? 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.'- : 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'- )- );+ : 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',+ });}const client = yield* clientSingleton.getFor({@@ -1180,7 +1204,7 @@ const runConnectedToolkitFailFast = (params: {}) =>Effect.gen(function* () {if (params.skipConnectionCheck || params.skipChecks) {- perfDebugLog('execute.connected_toolkits.skipped', {+ yield* perfDebugLog('execute.connected_toolkits.skipped', {slug: params.slug,reason: params.skipChecks ? 'skip-checks' : 'skip-connection-check',});@@ -1189,7 +1213,7 @@ const runConnectedToolkitFailFast = (params: {if (params.resolvedProject.projectType !== 'CONSUMER') return;if (isLocalToolSlug(params.slug)) return;- perfDebugLog('execute.connected_toolkits.refresh_start', {+ yield* perfDebugLog('execute.connected_toolkits.refresh_start', {slug: params.slug,orgId: params.resolvedProject.orgId,consumerUserId: params.resolvedUserId,@@ -1199,24 +1223,20 @@ const runConnectedToolkitFailFast = (params: {consumerUserId: params.resolvedUserId,}).pipe(Effect.tap(() =>- Effect.sync(() =>- perfDebugLog('execute.connected_toolkits.refresh_end', {- slug: params.slug,- orgId: params.resolvedProject.orgId,- consumerUserId: params.resolvedUserId,- successful: true,- })- )+ perfDebugLog('execute.connected_toolkits.refresh_end', {+ slug: params.slug,+ orgId: params.resolvedProject.orgId,+ consumerUserId: params.resolvedUserId,+ successful: true,+ })),Effect.catchAll(() =>- Effect.sync(() =>- perfDebugLog('execute.connected_toolkits.refresh_end', {- slug: params.slug,- orgId: params.resolvedProject.orgId,- consumerUserId: params.resolvedUserId,- successful: false,- })- )+ perfDebugLog('execute.connected_toolkits.refresh_end', {+ slug: params.slug,+ orgId: params.resolvedProject.orgId,+ consumerUserId: params.resolvedUserId,+ successful: false,+ })),Effect.forkDaemon,Effect.asVoid@@ -1229,7 +1249,7 @@ const runConnectedToolkitFailFast = (params: {orgId: params.resolvedProject.orgId,consumerUserId: params.resolvedUserId,});- perfDebugLog(+ yield* perfDebugLog(Option.isSome(cachedToolkits)? 'execute.connected_toolkits.cache_hit': 'execute.connected_toolkits.cache_miss',@@ -1243,7 +1263,7 @@ const runConnectedToolkitFailFast = (params: {);if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(toolkit)) {- perfDebugLog('execute.connected_toolkits.fail_fast', {+ yield* perfDebugLog('execute.connected_toolkits.fail_fast', {slug: params.slug,toolkit,orgId: params.resolvedProject.orgId,@@ -1264,11 +1284,22 @@ const runConnectedToolkitFailFast = (params: {2));- return yield* Effect.fail(new ToolExecutionError(message));+ return yield* new ToolExecutionError({+ reason: 'connection_check',+ toolSlug: params.slug,+ message,+ });}});-// eslint-disable-next-line max-lines-per-function+const executeSessionHistoryScope = (resolvedProject: ResolvedExecuteContext['resolvedProject']) =>+ resolvedProject.projectType === 'CONSUMER'+ ? {+ orgId: resolvedProject.orgId,+ consumerUserId: resolvedProject.consumerUserId,+ }+ : {};+const runExecuteWithSpinner = (params: {readonly slug: string;readonly surface: 'root' | 'dev';@@ -1290,7 +1321,7 @@ const runExecuteWithSpinner = (params: {const cachedDefinition = verificationDisabled? null: yield* getCachedToolInputDefinition(params.slug);- const validationState = verificationDisabled+ const validationState: ValidationState = verificationDisabled? ({cacheHit: false,validationGuard: Effect.never,@@ -1368,14 +1399,7 @@ const runExecuteWithSpinner = (params: {);yield* writeExecuteStdout(params.ui, JSON.stringify(summary, ciRedactReplacer, 2));yield* appendCliSessionHistory({- orgId:- params.resolvedProject.projectType === 'CONSUMER'- ? params.resolvedProject.orgId- : undefined,- consumerUserId:- params.resolvedProject.projectType === 'CONSUMER'- ? params.resolvedProject.consumerUserId- : undefined,+ ...executeSessionHistoryScope(params.resolvedProject),entry: {command: 'execute',status: 'dry-run',@@ -1386,61 +1410,63 @@ const runExecuteWithSpinner = (params: {return;}- perfDebugLog('execute.tool_call.start', { slug: params.slug });- const resultEither = yield* params.executor- .execute(params.slug, params.executeParams)- .pipe(Effect.raceFirst(validationGuard))- .pipe(Effect.either);- toolDebugLog('execute_result', {- slug: params.slug,- result: Either.isRight(resultEither) ? resultEither.right : resultEither.left,- });- perfDebugLog('execute.tool_call.end', {- slug: params.slug,- successful: Either.isRight(resultEither),- });-- if (Either.isLeft(resultEither)) {- yield* invalidateToolInputDefinition(params.slug).pipe(- Effect.catchAll(() => Effect.void)- );- yield* spinner.error();- const summary = yield* handleExecutionError(params.ui, resultEither.left, {- toolSlug: params.slug,- args: params.args,- surface: params.surface,- projectMode: params.projectMode,- stage: 'execution',- });- yield* writeExecuteStdout(- params.ui,- JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)- );- yield* appendCliSessionHistory({- orgId:- params.resolvedProject.projectType === 'CONSUMER'- ? params.resolvedProject.orgId- : undefined,- consumerUserId:- params.resolvedProject.projectType === 'CONSUMER'- ? params.resolvedProject.consumerUserId- : undefined,- entry: {- command: 'execute',- status: 'error',- slug: params.slug,- arguments: params.args,- error: summary.error,- },- }).pipe(Effect.catchAll(() => Effect.void));- return yield* Effect.fail(new ToolExecutionError(summary.error));- }-- const result = resultEither.right;+ yield* perfDebugLog('execute.tool_call.start', { slug: params.slug });+ const result = yield* params.executor.execute(params.slug, params.executeParams).pipe(+ Effect.raceFirst(validationGuard),+ Effect.matchEffect({+ onFailure: error =>+ Effect.gen(function* () {+ yield* logToolDebug('execute_result', { slug: params.slug, result: error });+ yield* perfDebugLog('execute.tool_call.end', {+ slug: params.slug,+ successful: false,+ });+ yield* invalidateToolInputDefinition(params.slug).pipe(+ Effect.catchAll(() => Effect.void)+ );+ yield* spinner.error();+ const summary = yield* handleExecutionError(params.ui, error, {+ toolSlug: params.slug,+ args: params.args,+ surface: params.surface,+ projectMode: params.projectMode,+ stage: 'execution',+ });+ yield* writeExecuteStdout(+ params.ui,+ JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)+ );+ yield* appendCliSessionHistory({+ ...executeSessionHistoryScope(params.resolvedProject),+ entry: {+ command: 'execute',+ status: 'error',+ slug: params.slug,+ arguments: params.args,+ error: summary.error,+ },+ }).pipe(Effect.catchAll(() => Effect.void));+ return yield* new ReportedToolExecutionError({+ reason: 'execution_failed',+ toolSlug: params.slug,+ message: summary.error,+ });+ }),+ onSuccess: result =>+ Effect.gen(function* () {+ yield* logToolDebug('execute_result', { slug: params.slug, result });+ yield* perfDebugLog('execute.tool_call.end', {+ slug: params.slug,+ successful: true,+ });+ return result;+ }),+ })+ );if (validationState.awaitCachedValidationDecision) {const decision = yield* validationState.awaitCachedValidationDecision;if (decision.status === 'fail') {- perfDebugLog('execute.validation.post_success_failure_ignored', {+ yield* perfDebugLog('execute.validation.post_success_failure_ignored', {slug: params.slug,});}@@ -1464,7 +1490,11 @@ const runExecuteWithSpinner = (params: {logId: result.logId,});yield* writeExecuteStdout(params.ui, JSON.stringify(result, ciRedactReplacer, 2));- return yield* Effect.fail(new ToolExecutionError(summary.error));+ return yield* new ReportedToolExecutionError({+ reason: 'execution_failed',+ toolSlug: params.slug,+ message: summary.error,+ });}yield* spinner.stop(`Execution successful${executionSuccessSuffix(result)}`);@@ -1481,14 +1511,7 @@ const runExecuteWithSpinner = (params: {);yield* writeExecuteStdout(params.ui, JSON.stringify(output.summary, ciRedactReplacer, 2));yield* appendCliSessionHistory({- orgId:- params.resolvedProject.projectType === 'CONSUMER'- ? params.resolvedProject.orgId- : undefined,- consumerUserId:- params.resolvedProject.projectType === 'CONSUMER'- ? params.resolvedProject.consumerUserId- : undefined,+ ...executeSessionHistoryScope(params.resolvedProject),entry: {command: 'execute',status: 'success',@@ -1505,14 +1528,7 @@ const runExecuteWithSpinner = (params: {yield* writeExecuteStdout(params.ui, output.json);yield* appendCliSessionHistory({- orgId:- params.resolvedProject.projectType === 'CONSUMER'- ? params.resolvedProject.orgId- : undefined,- consumerUserId:- params.resolvedProject.projectType === 'CONSUMER'- ? params.resolvedProject.consumerUserId- : undefined,+ ...executeSessionHistoryScope(params.resolvedProject),entry: {command: 'execute',status: 'success',@@ -1535,11 +1551,11 @@ const runToolsExecute = (params: RunToolsExecuteParams) =>isLocalToolSlug(params.slug) &&!cliConfig.isExperimentalFeatureEnabled(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS)) {- return yield* Effect.fail(- new Error(- `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${params.slug}.`- )- );+ return yield* new LocalToolsDisabledError({+ toolSlug: params.slug,+ feature: CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,+ message: `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${params.slug}.`,+ });}if (params.getSchema) {@@ -1574,7 +1590,7 @@ const runToolsExecute = (params: RunToolsExecuteParams) =>skipConnectionCheck: params.skipConnectionCheck,skipChecks: params.skipChecks,});- toolDebugLog('execute_params', {+ yield* logToolDebug('execute_params', {slug: params.slug,userId: context.resolvedUserId,connectedAccountId: context.selectedConnectedAccountId,@@ -1582,7 +1598,7 @@ const runToolsExecute = (params: RunToolsExecuteParams) =>projectId: context.resolvedProject.projectId,orgId: context.resolvedProject.orgId,});- perfDebugLog('execute.prepare', {+ yield* perfDebugLog('execute.prepare', {slug: params.slug,surface: params.surface,projectMode: params.projectMode,@@ -1603,7 +1619,7 @@ const runToolsExecute = (params: RunToolsExecuteParams) =>});});-const parseParallelExecuteArgs = (+export const parseParallelExecuteArgs = (args: ReadonlyArray<string>,config: {readonly surface: 'root' | 'dev';@@ -1611,153 +1627,181 @@ const parseParallelExecuteArgs = (readonly allowUserId: boolean;readonly allowProjectName: boolean;}-): ParsedParallelExecuteArgs => {- let getSchema = false;- let dryRun = false;- let skipConnectionCheck = false;- let skipToolParamsCheck = false;- let skipChecks = false;- let account = Option.none<string>();- let userId = Option.none<string>();- let projectName = Option.none<string>();- const specs: ParallelExecuteSpec[] = [];- let currentSpec: ParallelExecuteSpec | null = null;-- const pushCurrentSpec = () => {- if (!currentSpec) return;- specs.push(currentSpec);- currentSpec = null;- };+) =>+ Effect.gen(function* () {+ let getSchema = false;+ let dryRun = false;+ let skipConnectionCheck = false;+ let skipToolParamsCheck = false;+ let skipChecks = false;+ let account = Option.none<string>();+ let userId = Option.none<string>();+ let projectName = Option.none<string>();+ const specs: ParallelExecuteSpec[] = [];+ let currentSpec: ParallelExecuteSpec | null = null;++ const pushCurrentSpec = () => {+ if (!currentSpec) return;+ specs.push(currentSpec);+ currentSpec = null;+ };- const readValue = (token: string, index: number) => {- if (token.includes('=')) {- return {- value: token.slice(token.indexOf('=') + 1),- nextIndex: index,- };- }+ const readValue = (token: string, index: number) => {+ if (token.includes('=')) {+ return Effect.succeed({+ value: token.slice(token.indexOf('=') + 1),+ nextIndex: index,+ });+ }- const next = args[index + 1];- if (!next) {- throw new Error(`Missing value for ${token}.`);- }- return { value: next, nextIndex: index + 1 };- };+ const next = args[index + 1];+ if (!next) {+ return Effect.fail(invalidArguments(`Missing value for ${token}.`));+ }+ return Effect.succeed({ value: next, nextIndex: index + 1 });+ };- for (let i = 0; i < args.length; i += 1) {- const token = args[i];- if (!token) continue;+ for (let i = 0; i < args.length; i += 1) {+ const token = args[i];+ if (!token) continue;- if (token === '--parallel' || token === '-p') {- continue;- }- if (token === '--get-schema') {- getSchema = true;- continue;- }- if (token === '--dry-run') {- dryRun = true;- continue;- }- if (token === '--skip-connection-check') {- skipConnectionCheck = true;- continue;- }- if (token === '--skip-tool-params-check') {- skipToolParamsCheck = true;- continue;- }- if (token === '--skip-checks') {- skipChecks = true;- continue;- }- if (token === '--account' || token.startsWith('--account=')) {- const parsed = readValue(token, i);- account = Option.some(parsed.value);- i = parsed.nextIndex;- continue;- }- if (token === '--user-id' || token.startsWith('--user-id=')) {- if (!config.allowUserId) {- throw new Error(`${token} is not supported for this execute command.`);+ if (token === '--parallel' || token === '-p') {+ continue;}- const parsed = readValue(token, i);- userId = Option.some(parsed.value);- i = parsed.nextIndex;- continue;- }- if (token === '--project-name' || token.startsWith('--project-name=')) {- if (!config.allowProjectName) {- throw new Error(`${token} is not supported for this execute command.`);+ if (token === '--get-schema') {+ getSchema = true;+ continue;}- const parsed = readValue(token, i);- projectName = Option.some(parsed.value);- i = parsed.nextIndex;- continue;- }- if (- token === '--data' ||- token === '-d' ||- token.startsWith('--data=') ||- token.startsWith('-d=')- ) {- if (!currentSpec) {- throw new Error(- `Expected a tool slug before ${token}. Use: composio execute --parallel TOOL_SLUG -d '{}' TOOL_SLUG_2 -d '{}'.`+ if (token === '--dry-run') {+ dryRun = true;+ continue;+ }+ if (token === '--skip-connection-check') {+ skipConnectionCheck = true;+ continue;+ }+ if (token === '--skip-tool-params-check') {+ skipToolParamsCheck = true;+ continue;+ }+ if (token === '--skip-checks') {+ skipChecks = true;+ continue;+ }+ if (token === '--account' || token.startsWith('--account=')) {+ const parsed = yield* readValue(token, i);+ if (currentSpec) {+ currentSpec = {+ slug: currentSpec.slug,+ data: currentSpec.data,+ account: Option.some(parsed.value),+ };+ } else {+ account = Option.some(parsed.value);+ }+ i = parsed.nextIndex;+ continue;+ }+ if (token === '--user-id' || token.startsWith('--user-id=')) {+ if (!config.allowUserId) {+ return yield* Effect.fail(+ invalidArguments(`${token} is not supported for this execute command.`)+ );+ }+ const parsed = yield* readValue(token, i);+ userId = Option.some(parsed.value);+ i = parsed.nextIndex;+ continue;+ }+ if (token === '--project-name' || token.startsWith('--project-name=')) {+ if (!config.allowProjectName) {+ return yield* Effect.fail(+ invalidArguments(`${token} is not supported for this execute command.`)+ );+ }+ const parsed = yield* readValue(token, i);+ projectName = Option.some(parsed.value);+ i = parsed.nextIndex;+ continue;+ }+ if (+ token === '--data' ||+ token === '-d' ||+ token.startsWith('--data=') ||+ token.startsWith('-d=')+ ) {+ if (!currentSpec) {+ return yield* Effect.fail(+ invalidArguments(+ `Expected a tool slug before ${token}. Use: composio execute --parallel TOOL_SLUG -d '{}' TOOL_SLUG_2 -d '{}'.`+ )+ );+ }+ const parsed = yield* readValue(token, i);+ currentSpec = {+ slug: currentSpec.slug,+ data: Option.some(parsed.value),+ account: currentSpec.account,+ };+ i = parsed.nextIndex;+ continue;+ }+ if (token.startsWith('-')) {+ return yield* Effect.fail(+ invalidArguments(`Unknown option for parallel execute: ${token}`));}- const parsed = readValue(token, i);++ pushCurrentSpec();currentSpec = {- slug: currentSpec.slug,- data: Option.some(parsed.value),- account: currentSpec.account,+ slug: token,+ data: Option.none(),+ account,};- i = parsed.nextIndex;- continue;- }- if (token.startsWith('-')) {- throw new Error(`Unknown option for parallel execute: ${token}`);}pushCurrentSpec();- currentSpec = {- slug: token,- data: Option.none(),- account,- };- }- pushCurrentSpec();+ if (specs.length === 0) {+ return yield* Effect.fail(+ invalidArguments(+ "No tool slugs were provided. Use: composio execute --parallel TOOL_SLUG -d '{}' TOOL_SLUG_2 -d '{}'."+ )+ );+ }- if (specs.length === 0) {- throw new Error(- "No tool slugs were provided. Use: composio execute --parallel TOOL_SLUG -d '{}' TOOL_SLUG_2 -d '{}'."- );- }+ return {+ specs,+ userId,+ projectName,+ surface: config.surface,+ projectMode: config.projectMode,+ getSchema,+ dryRun,+ skipConnectionCheck,+ skipToolParamsCheck,+ skipChecks,+ account,+ } satisfies ParsedParallelExecuteArgs;+ });- return {- specs,- userId,- projectName,- surface: config.surface,- projectMode: config.projectMode,- getSchema,- dryRun,- skipConnectionCheck,- skipToolParamsCheck,- skipChecks,- account,- };+type ParallelExecuteCommand = {+ readonly matched: boolean;+ readonly tail: ReadonlyArray<string>;+ readonly surface: 'root' | 'dev';+ readonly projectMode: 'consumer' | 'developer';+ readonly allowUserId: boolean;+ readonly allowProjectName: boolean;};-const isParallelExecuteCommand = (argv: ReadonlyArray<string>) => {+const isParallelExecuteCommand = (argv: ReadonlyArray<string>): ParallelExecuteCommand | null => {const args = argv.slice(2);if (args[0] === 'execute') {return {matched: args.includes('--parallel') || args.includes('-p'),tail: args.slice(1),- surface: 'root' as const,- projectMode: 'consumer' as const,+ surface: 'root',+ projectMode: 'consumer',allowUserId: false,allowProjectName: false,};@@ -1766,8 +1810,8 @@ const isParallelExecuteCommand = (argv: ReadonlyArray<string>) => {return {matched: args.includes('--parallel') || args.includes('-p'),tail: args.slice(2),- surface: 'dev' as const,- projectMode: 'developer' as const,+ surface: 'dev',+ projectMode: 'developer',allowUserId: true,allowProjectName: true,};@@ -1805,9 +1849,11 @@ const checkConnectedToolkitOrFail = (params: {});if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(toolkit)) {- throw new ToolExecutionError(- `Toolkit "${toolkit}" is not connected for this user (cached within the last 5 minutes). If you just connected the account, use --skip-connection-check.`- );+ return yield* new ToolExecutionError({+ reason: 'connection_check',+ toolSlug: params.slug,+ message: `Toolkit "${toolkit}" is not connected for this user (cached within the last 5 minutes). If you just connected the account, use --skip-connection-check.`,+ });}});@@ -1894,9 +1940,10 @@ const runParallelSchemaFetchFromParsed = (params: ParsedParallelExecuteArgs) =>));if (!successful) {- return yield* Effect.fail(- new ToolExecutionError('One or more parallel tool executions failed.')- );+ return yield* new ReportedToolExecutionError({+ reason: 'parallel_failed',+ message: 'One or more parallel tool executions failed.',+ });}}});@@ -1941,76 +1988,76 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>Effect.gen(function* () {const toolSlug = spec.slug;- try {- yield* checkConnectedToolkitOrFail({- slug: toolSlug,- resolvedProject: context.resolvedProject,- resolvedUserId: context.resolvedUserId,- skipConnectionCheck: params.skipConnectionCheck,- skipChecks: params.skipChecks,- });-- if (params.dryRun) {- const verificationDisabled = params.skipChecks || params.skipToolParamsCheck;- const definition = verificationDisabled- ? null- : yield* getOrFetchToolInputDefinition(toolSlug, {- orgId: context.resolvedProject.orgId,- projectId: context.resolvedProject.projectId,- });- if (definition) {- yield* validateToolInputArgumentsWithDefinition(toolSlug, context.args, definition);- }- return {- successful: true,- dryRun: true,- slug: toolSlug,- arguments: context.args,- userId: context.resolvedUserId,- schemaPath: definition?.schemaPath,- schemaVersion: definition?.version,- } satisfies DryRunSummary;- }+ yield* checkConnectedToolkitOrFail({+ slug: toolSlug,+ resolvedProject: context.resolvedProject,+ resolvedUserId: context.resolvedUserId,+ skipConnectionCheck: params.skipConnectionCheck,+ skipChecks: params.skipChecks,+ });- if (!params.skipChecks && !params.skipToolParamsCheck) {- const definition = yield* getOrFetchToolInputDefinition(toolSlug, {- orgId: context.resolvedProject.orgId,- projectId: context.resolvedProject.projectId,- });+ if (params.dryRun) {+ const verificationDisabled = params.skipChecks || params.skipToolParamsCheck;+ const definition = verificationDisabled+ ? null+ : yield* getOrFetchToolInputDefinition(toolSlug, {+ orgId: context.resolvedProject.orgId,+ projectId: context.resolvedProject.projectId,+ });+ if (definition) {yield* validateToolInputArgumentsWithDefinition(toolSlug, context.args, definition);}+ return {+ successful: true,+ dryRun: true,+ slug: toolSlug,+ arguments: context.args,+ userId: context.resolvedUserId,+ schemaPath: definition?.schemaPath,+ schemaVersion: definition?.version,+ } satisfies DryRunSummary;+ }- const result = yield* context.executor.execute(toolSlug, context.executeParams);- if (!result.successful) {- return {- slug: toolSlug,- successful: false,- error: result.error ?? 'Execution failed.',- logId: result.logId,- };- }-- const output = yield* prepareExecuteOutput(toolSlug, result, context.executeOutputDir);- if (output.kind === 'file') {- return {- slug: toolSlug,- ...output.summary,- };- }+ if (!params.skipChecks && !params.skipToolParamsCheck) {+ const definition = yield* getOrFetchToolInputDefinition(toolSlug, {+ orgId: context.resolvedProject.orgId,+ projectId: context.resolvedProject.projectId,+ });+ yield* validateToolInputArgumentsWithDefinition(toolSlug, context.args, definition);+ }+ const result = yield* context.executor.execute(toolSlug, context.executeParams);+ if (!result.successful) {return {slug: toolSlug,- ...result,+ successful: false,+ error: result.error ?? 'Execution failed.',+ logId: result.logId,};- } catch (error) {- const mapped = mapComposioError({ error, toolSlug });+ }++ const output = yield* prepareExecuteOutput(toolSlug, result, context.executeOutputDir);+ if (output.kind === 'file') {return {slug: toolSlug,- successful: false,- error: mapped.message,+ ...output.summary,};}- }),++ return {+ slug: toolSlug,+ ...result,+ };+ }).pipe(+ Effect.catchAll(error => {+ const mapped = mapComposioError({ error, toolSlug: spec.slug });+ return Effect.succeed({+ slug: spec.slug,+ successful: false,+ error: mapped.message,+ } satisfies ParallelExecuteResult);+ })+ ),{ concurrency: 'unbounded' });@@ -2071,9 +2118,10 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>}if (!successful) {- return yield* Effect.fail(- new ToolExecutionError('One or more parallel tool executions failed.')- );+ return yield* new ReportedToolExecutionError({+ reason: 'parallel_failed',+ message: 'One or more parallel tool executions failed.',+ });}});@@ -2083,15 +2131,11 @@ export const runParallelToolsExecuteFromArgv = (argv: ReadonlyArray<string>) =>return null;}- return Effect.try({- try: () =>- parseParallelExecuteArgs(command.tail, {- surface: command.surface,- projectMode: command.projectMode,- allowUserId: command.allowUserId,- allowProjectName: command.allowProjectName,- }),- catch: error => (error instanceof Error ? error : new Error(String(error))),+ return parseParallelExecuteArgs(command.tail, {+ surface: command.surface,+ projectMode: command.projectMode,+ allowUserId: command.allowUserId,+ allowProjectName: command.allowProjectName,}).pipe(Effect.flatMap(runParallelToolsExecuteFromParsed));};diff --git a/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.tsindex 8fc3c4a9d..432f5cb32 100644--- a/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts+++ b/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts@@ -1,6 +1,7 @@import { Args, Command, Options } from '@effect/cli';import { isLocalToolkitSlug } from '@composio/cli-local-tools';-import { Effect, Option } from 'effect';+import type { SessionSearchResponse } from '@composio/client/resources/tool-router';+import { Data, Effect, Option } from 'effect';import { TerminalUI } from 'src/services/terminal-ui';import { requireAuth } from 'src/effects/require-auth';import { setupCacheDir } from 'src/effects/setup-cache-dir';@@ -59,35 +60,22 @@ const human = Options.boolean('human').pipe(Options.withDescription('Show formatted human-readable search output'));-type SearchToolSchema = {- tool_slug: string;- toolkit: string;- description?: string;- input_schema?: Record<string, unknown>;- output_schema?: Record<string, unknown>;-};+type SearchToolSchema = SessionSearchResponse.ToolSchemas;+type SearchResultRecord = SessionSearchResponse.Result;+type SearchResponseRecord = Pick<+ SessionSearchResponse,+ 'results' | 'toolkit_connection_statuses' | 'tool_schemas' | 'next_steps_guidance' | 'error'+>;-type SearchResultRecord = {- use_case: string;- primary_tool_slugs: string[];- related_tool_slugs: string[];- recommended_plan_steps?: string[];- reference_workbench_snippets?: unknown;- plan_id?: string;-};+export class ToolsSearchInputError extends Data.TaggedError('commands/ToolsSearchInputError')<{+ readonly reason: 'missing_query' | 'missing_user_id';+ readonly message: string;+}> {}-type ToolkitConnectionStatusRecord = {- toolkit: string;- has_active_connection: boolean;-};--type SearchResponseRecord = {- results: SearchResultRecord[];- toolkit_connection_statuses: ToolkitConnectionStatusRecord[];- tool_schemas: Record<string, SearchToolSchema>;- next_steps_guidance: string[];- error: string | null;-};+class ToolsSearchRequestError extends Data.TaggedError('commands/ToolsSearchRequestError')<{+ readonly message: string;+ readonly cause: unknown;+}> {}const stripSearchResultMetadata = <T extends { reference_workbench_snippets?: unknown; plan_id?: unknown },@@ -137,9 +125,9 @@ const collectToolsForResult = (params: {description: schema.description ?? '',tags: [],available_versions: [],- input_parameters: (schema.input_schema ?? {}) as Record<string, unknown>,- output_parameters: (schema.output_schema ?? {}) as Record<string, unknown>,- } as Tool);+ input_parameters: schema.input_schema ?? {},+ output_parameters: schema.output_schema ?? {},+ });if (toolsList.length >= params.limit) break;}@@ -195,7 +183,10 @@ const buildSearchJsonPayload = (params: {yield* Effect.forEach(primaryToolSlugs, slug =>Effect.gen(function* () {const definition = yield* getOrFetchToolInputDefinition(slug, params.projectScope);- return [slug, toHomeRelativePath(cacheDir, definition.schemaPath)] as const;+ return [slug, toHomeRelativePath(cacheDir, definition.schemaPath)] satisfies readonly [+ string,+ string,+ ];})));@@ -228,7 +219,7 @@ const buildSearchJsonPayload = (params: {'You can directly proceed with these steps without waiting for the user to ask. Link accounts first if needed, then execute tools.',steps: params.nextSteps,},- } as const;+ };});const emitHumanSearchOutput = (params: {@@ -313,7 +304,10 @@ const runToolsSearch = (params: {const emitJson = params.json || !emitHuman;const queries = params.query.map(q => q.trim()).filter(Boolean);if (queries.length === 0) {- return yield* Effect.fail(new Error('At least one query is required.'));+ return yield* new ToolsSearchInputError({+ reason: 'missing_query',+ message: 'At least one query is required.',+ });}const toolkitFilter = Option.getOrUndefined(params.toolkits);const toolkitList =@@ -337,11 +331,11 @@ const runToolsSearch = (params: {onNone: () => userContext.data.testUserId,});if (Option.isNone(resolvedUserId)) {- return yield* Effect.fail(- new Error(- 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'- )- );+ return yield* new ToolsSearchInputError({+ reason: 'missing_user_id',+ message:+ 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',+ });}const clientSingleton = yield* ComposioClientSingleton;const client = yield* clientSingleton.getFor({@@ -373,9 +367,14 @@ const runToolsSearch = (params: {queries: queries.map(query => ({ use_case: query })),...(localExperimentalPayload ? { experimental: localExperimentalPayload } : {}),};- const searchResponse = yield* Effect.tryPromise(() =>- client.toolRouter.session.search(sessionId, searchPayload)- );+ const searchResponse = yield* Effect.tryPromise({+ try: () => client.toolRouter.session.search(sessionId, searchPayload),+ catch: cause =>+ new ToolsSearchRequestError({+ message: 'Failed to search tools.',+ cause,+ }),+ });return {searchResponse,projectScope: {@@ -435,9 +434,7 @@ const runToolsSearch = (params: {? searchResponse.tool_schemas[firstSlug]: undefined;const firstToolkit = firstSchema?.toolkit;- const firstPayload = buildMinimalPayloadFromSchema(- (firstSchema?.input_schema ?? {}) as Record<string, unknown>- );+ const firstPayload = buildMinimalPayloadFromSchema(firstSchema?.input_schema ?? {});const firstPayloadJson = JSON.stringify(firstPayload);const firstDataArg =Object.keys(firstPayload).length === 0 ? '-d "{}"' : `-d '${firstPayloadJson}'`;diff --git a/ts/packages/cli/src/commands/triggers/commands/triggers.list.cmd.ts b/ts/packages/cli/src/commands/triggers/commands/triggers.list.cmd.tsindex 93808cc32..5a9b4afb2 100644--- a/ts/packages/cli/src/commands/triggers/commands/triggers.list.cmd.ts+++ b/ts/packages/cli/src/commands/triggers/commands/triggers.list.cmd.ts@@ -1,7 +1,7 @@-import { Args, Command, Options } from '@effect/cli';+import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';import { Effect } from 'effect';import { requireAuth } from 'src/effects/require-auth';-import { ComposioToolkitsRepository, InvalidToolkitsError } from 'src/services/composio-clients';+import { ComposioToolkitsRepository } from 'src/services/composio-clients';import { TerminalUI } from 'src/services/terminal-ui';import { clampLimit } from 'src/ui/clamp-limit';import { formatTriggerTypesJson, formatTriggerTypesTable } from '../format';@@ -39,7 +39,7 @@ const makeTriggersListCommand = ({ noResultsCommand, infoCommand }: TriggersListconst clampedLimit = clampLimit(limit);yield* repo.validateToolkits([toolkit]).pipe(- Effect.catchTag('services/InvalidToolkitsError', (error: InvalidToolkitsError) =>+ Effect.catchTag('services/InvalidToolkitsError', error =>Effect.gen(function* () {const availableExample = error.availableToolkits.slice(0, 8).join(', ');yield* ui.log.error(@@ -47,7 +47,9 @@ const makeTriggersListCommand = ({ noResultsCommand, infoCommand }: TriggersList);yield* ui.log.step(`List valid toolkits with:\n> ${noResultsCommand}`);return yield* Effect.fail(- new Error(`Invalid toolkit slug "${toolkit}" for trigger listing.`)+ ValidationError.invalidValue(+ HelpDoc.p(`Invalid toolkit slug "${toolkit}" for trigger listing.`)+ ));}))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.tsindex 7f551af5e..a872d97b9 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,12 +15,10 @@* 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';+import { Command, HelpDoc, Options, ValidationError } from '@effect/cli';+import { Array, Data, Effect, Option, pipe } from 'effect';import { Match } from 'effect';-import { FileSystem } from '@effect/platform';+import { FileSystem, Path } from '@effect/platform';import { ComposioToolkitsRepository } from 'src/services/composio-clients';import { logMetrics } from 'src/effects/log-metrics';import { NodeProcess } from 'src/services/node-process';@@ -42,6 +40,16 @@ import {import { validateToolkitVersionOverrides } from 'src/effects/validate-toolkit-versions';import { TerminalUI, type SpinnerHandle } from 'src/services/terminal-ui';+export class TypeScriptGenerationWriteError extends Data.TaggedError(+ 'commands/TypeScriptGenerationWriteError'+)<{+ readonly cause: unknown;+ readonly filePath: string;+ readonly message: string;+}> {}++const invalidGenerateValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));+export const outputOpt = Options.optional(Options.directory('output-dir', {exists: 'either',@@ -112,7 +120,7 @@ function fetchFilteredData(typeTools: boolean,versionOverrides: ToolkitVersionOverrides,spinner: SpinnerHandle-): Effect.Effect<FetchResult, Error, never> {+): Effect.Effect<FetchResult, Error | ValidationError.ValidationError, never> {return Effect.gen(function* () {yield* spinner.message(`Fetching data for ${slugs.length} toolkit(s): ${slugs.join(', ')}...`);@@ -132,7 +140,7 @@ function fetchFilteredData(.pipe(Effect.catchTag('services/InvalidToolkitsError', error =>Effect.fail(- new Error(+ invalidGenerateValue(`Invalid toolkit(s): ${error.invalidToolkits.join(', ')}. Toolkit not found.`))@@ -227,7 +235,7 @@ function fetchAllDataFastPath(toolkits: allToolkits,triggerTypes: allTriggerTypes,typeableTools: allTypeableTools,- versionMap: new Map() as ToolkitVersionOverrides,+ versionMap: new Map<Lowercase<string>, string>(),};});}@@ -316,13 +324,16 @@ function fetchAllData(/*** Validates that the output directory is not inside node_modules*/-function validateOutputDir(outputDir: string): Effect.Effect<string, Error, FileSystem.FileSystem> {+function validateOutputDir(+ outputDir: string+): Effect.Effect<string, ValidationError.ValidationError, Path.Path> {return Effect.gen(function* () {+ const path = yield* Path.Path;const normalizedPath = path.normalize(outputDir);if (normalizedPath.includes('node_modules')) {return yield* Effect.fail(- new Error(+ invalidGenerateValue('Output directory cannot be inside node_modules. Please specify a different directory.'));@@ -419,15 +430,19 @@ export function generateTypescriptTypeStubs({yield* pipe(Effect.all(sources.map(([filePath, content]) =>- fs- .writeFileString(filePath, content)- .pipe(- Effect.mapError(error => new Error(`Failed to write file ${filePath}: ${error}`))+ fs.writeFileString(filePath, content).pipe(+ Effect.mapError(+ cause =>+ new TypeScriptGenerationWriteError({+ cause,+ filePath,+ message: `Failed to write file ${filePath}`,+ }))+ )),{ concurrency: 'unbounded' }- ),- Effect.mapError(error => new Error(`Failed to write generated files: ${error}`))+ ));// Compile TypeScript to JavaScript if neededdiff --git a/ts/packages/cli/src/effect-errors/logic/errors/index.ts b/ts/packages/cli/src/effect-errors/logic/errors/index.tsindex 9d20f2e52..6e47700a7 100644--- a/ts/packages/cli/src/effect-errors/logic/errors/index.ts+++ b/ts/packages/cli/src/effect-errors/logic/errors/index.ts@@ -1,2 +1,3 @@export * from './capture-errors-from-cause';export * from './parse-error';+export * from './span-annotation';diff --git a/ts/packages/cli/src/effect-errors/logic/errors/parse-error.ts b/ts/packages/cli/src/effect-errors/logic/errors/parse-error.tsindex ee5f75c52..a414e57d8 100644--- a/ts/packages/cli/src/effect-errors/logic/errors/parse-error.ts+++ b/ts/packages/cli/src/effect-errors/logic/errors/parse-error.ts@@ -1,14 +1,10 @@-import { hasProperty } from 'effect/Predicate';-import type { Span } from 'effect/Tracer';-import { PrettyError } from 'effect-errors/types';import { extractErrorDetails } from './extract-error-details';--const spanSymbol = Symbol.for('effect/SpanAnnotation');+import { extractSpanAnnotation } from './span-annotation';export const parseError = (error: unknown): PrettyError => {- const maybeSpan = hasProperty(error, spanSymbol) ? (error[spanSymbol] as Span) : undefined;+ const maybeSpan = extractSpanAnnotation(error);const { message, type, isPlainString } = extractErrorDetails(error);if (error instanceof Error) {diff --git a/ts/packages/cli/src/effect-errors/logic/errors/span-annotation.ts b/ts/packages/cli/src/effect-errors/logic/errors/span-annotation.tsnew file mode 100644index 000000000..c1e4294c1--- /dev/null+++ b/ts/packages/cli/src/effect-errors/logic/errors/span-annotation.ts@@ -0,0 +1,27 @@+import { hasProperty, isString, isTagged } from 'effect/Predicate';+import type { Span } from 'effect/Tracer';++// Effect v3 internal: `Effect.fail`/`Effect.die` proxy object errors so the+// fiber's current span is readable under this global registry symbol. There is+// no public API for it, and `Symbol.for` succeeds even on Effect versions that+// stop setting it, so keep every read behind this adapter — the canary test in+// test/src/effect-errors/span-annotation.test.ts breaks loudly when an+// `effect` upgrade drops the mechanism.+const spanSymbol = Symbol.for('effect/SpanAnnotation');++const looksLikeSpan = (value: unknown): value is Span =>+ isTagged(value, 'Span') &&+ hasProperty(value, 'name') &&+ isString(value.name) &&+ hasProperty(value, 'status') &&+ hasProperty(value, 'attributes') &&+ hasProperty(value, 'parent');++export const extractSpanAnnotation = (error: unknown): Span | undefined => {+ if (!hasProperty(error, spanSymbol)) {+ return undefined;+ }++ const value = error[spanSymbol];+ return looksLikeSpan(value) ? value : undefined;+};diff --git a/ts/packages/cli/src/effects/create-tool-router-session.ts b/ts/packages/cli/src/effects/create-tool-router-session.tsindex dc0b71238..1b0e1b5a7 100644--- a/ts/packages/cli/src/effects/create-tool-router-session.ts+++ b/ts/packages/cli/src/effects/create-tool-router-session.ts@@ -1,4 +1,4 @@-import { Effect, Option } from 'effect';+import { Data, Effect, Option } from 'effect';import type { Composio } from '@composio/client';import {createLocalToolRouterExperimentalPayload,@@ -57,6 +57,20 @@ export interface CreatedToolRouterSession {readonly connectedAccountWordIds?: Record<string, string>;}+export class LocalToolRouterDisabledError extends Data.TaggedError(+ 'effects/LocalToolRouterDisabledError'+)<{+ readonly message: string;+ readonly requestedToolkits: ReadonlyArray<string>;+}> {}++export class ToolRouterSessionCreateError extends Data.TaggedError(+ 'effects/ToolRouterSessionCreateError'+)<{+ readonly message: string;+ readonly cause: unknown;+}> {}+/*** Create an ephemeral Tool Router session for the given user ID.* Returns the session id plus any local-tool custom payload bound to the session.@@ -91,9 +105,10 @@ export const createToolRouterSessionContext = (requestedToolkits.length === 0 || requestedLocalToolkits.length > 0;if (!localToolsEnabled && requestedLocalToolkits.length > 0) {return yield* Effect.fail(- new Error(- `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before using toolkit filter(s): ${requestedLocalToolkits.join(', ')}.`- )+ new LocalToolRouterDisabledError({+ message: `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before using toolkit filter(s): ${requestedLocalToolkits.join(', ')}.`,+ requestedToolkits: requestedLocalToolkits,+ }));}const localExperimentalPayload =@@ -204,23 +219,30 @@ export const createToolRouterSessionContext = (: {}),};- return yield* Effect.tryPromise(() =>- client.toolRouter.session.create({- user_id: userId,- auth_configs: connectionContext.authConfigs,- connected_accounts: connectionContext.connectedAccounts,- manage_connections: { enable: options?.manageConnections ?? false },- multi_account: options?.multiAccount- ? {- enable: options.multiAccount.enable,- max_accounts_per_toolkit: options.multiAccount.maxAccountsPerToolkit,- require_explicit_selection: options.multiAccount.requireExplicitSelection,- }- : undefined,- toolkits: remoteToolkits.length > 0 ? { enable: [...remoteToolkits] } : undefined,- experimental: Object.keys(experimentalPayload).length > 0 ? experimentalPayload : undefined,- })- ).pipe(+ return yield* Effect.tryPromise({+ try: () =>+ client.toolRouter.session.create({+ user_id: userId,+ auth_configs: connectionContext.authConfigs,+ connected_accounts: connectionContext.connectedAccounts,+ manage_connections: { enable: options?.manageConnections ?? false },+ multi_account: options?.multiAccount+ ? {+ enable: options.multiAccount.enable,+ max_accounts_per_toolkit: options.multiAccount.maxAccountsPerToolkit,+ require_explicit_selection: options.multiAccount.requireExplicitSelection,+ }+ : undefined,+ toolkits: remoteToolkits.length > 0 ? { enable: [...remoteToolkits] } : undefined,+ experimental:+ Object.keys(experimentalPayload).length > 0 ? experimentalPayload : undefined,+ }),+ catch: cause =>+ new ToolRouterSessionCreateError({+ message: 'Failed to create a Tool Router session.',+ cause,+ }),+ }).pipe(Effect.map((session): CreatedToolRouterSession => ({sessionId: session.session_id,localExperimentalPayload,diff --git a/ts/packages/cli/src/effects/from-lazy-json.ts b/ts/packages/cli/src/effects/from-lazy-json.tsindex 566d0f2a3..d95e2c0ed 100644--- a/ts/packages/cli/src/effects/from-lazy-json.ts+++ b/ts/packages/cli/src/effects/from-lazy-json.ts@@ -11,6 +11,7 @@ import {ConfigProvider,ConfigProviderPathPatch,HashSet,+ Predicate,} from 'effect';import { JSONParse, JSONParseError } from 'src/effects/json';@@ -106,7 +107,7 @@ export const configProviderFromLazyJson = (filePath: string) =>const pathNotFoundError = ConfigError.MissingData([], `Path ${filePath} not found`);const handlePlatformError = (error: PlatformError.PlatformError) =>- error._tag === 'SystemError' && error.reason === 'NotFound'+ Predicate.isTagged(error, 'SystemError') && error.reason === 'NotFound'? Effect.fail(pathNotFoundError): Effect.fail(sourceError(error));diff --git a/ts/packages/cli/src/effects/install-skill.ts b/ts/packages/cli/src/effects/install-skill.tsindex 6786c3e9b..0c51dd5e2 100644--- a/ts/packages/cli/src/effects/install-skill.ts+++ b/ts/packages/cli/src/effects/install-skill.ts@@ -1,4 +1,4 @@-import { Effect, Config, Option } from 'effect';+import { Config, Data, Effect, Option } from 'effect';import { FileSystem, HttpClient, Path } from '@effect/platform';import { NodeOs } from 'src/services/node-os';import { TerminalUI } from 'src/services/terminal-ui';@@ -6,6 +6,7 @@ import { GITHUB_CONFIG } from 'src/effects/github-config';import { APP_VERSION, type CliReleaseChannel } from 'src/constants';import {fetchLatestCliRelease,+ fetchCliReleaseByTag,type GitHubRelease,type GitHubRepoConfig,} from 'src/effects/resolve-cli-release';@@ -36,6 +37,13 @@ type GitHubConfig = GitHubRepoConfig & {ACCESS_TOKEN: Option.Option<string>;};+export class SkillInstallError extends Data.TaggedError('effects/SkillInstallError')<{+ readonly cause?: unknown;+ readonly message: string;+ readonly phase: 'release' | 'download' | 'extract';+ readonly status?: number;+}> {}+const hasSkillAsset = (release: GitHubRelease) =>release.assets.some(asset => asset.name === SKILL_ASSET_NAME);@@ -142,44 +150,59 @@ export const installSkill = (options?: {releaseTag: options?.releaseTag,});- // Find the skill asset URL from the release- const releaseUrl = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases/tags/${encodeURIComponent(tag)}`;- const releaseResponse = yield* httpClient- .get(releaseUrl)- .pipe(- Effect.catchAll(error => Effect.fail(new Error(`Failed to fetch release ${tag}: ${error}`)))- );-- if (releaseResponse.status < 200 || releaseResponse.status >= 300) {- return yield* Effect.fail(- new Error(`Release ${tag} not found (HTTP ${releaseResponse.status})`)- );- }-- const release = (yield* releaseResponse.json.pipe(- Effect.catchAll(() => Effect.fail(new Error('Failed to parse release JSON')))- )) as { assets: Array<{ name: string; browser_download_url: string }> };+ const release = yield* fetchCliReleaseByTag({ githubConfig, httpClient, tag }).pipe(+ Effect.mapError(+ error =>+ new SkillInstallError({+ cause: error,+ message: error.message,+ phase: 'release',+ status: error.status,+ })+ )+ );const skillAsset = release.assets.find(a => a.name === SKILL_ASSET_NAME);if (!skillAsset) {return yield* Effect.fail(- new Error(`Skill asset ${SKILL_ASSET_NAME} not found in release ${tag}`)+ new SkillInstallError({+ message: `Skill asset ${SKILL_ASSET_NAME} not found in release ${tag}`,+ phase: 'release',+ }));}// Download the skill zip- const downloadResponse = yield* httpClient- .get(skillAsset.browser_download_url)- .pipe(Effect.catchAll(error => Effect.fail(new Error(`Failed to download skill: ${error}`))));+ const downloadResponse = yield* httpClient.get(skillAsset.browser_download_url).pipe(+ Effect.mapError(+ cause =>+ new SkillInstallError({+ cause,+ message: 'Failed to download skill',+ phase: 'download',+ })+ )+ );if (downloadResponse.status < 200 || downloadResponse.status >= 300) {return yield* Effect.fail(- new Error(`Failed to download skill (HTTP ${downloadResponse.status})`)+ new SkillInstallError({+ message: `Failed to download skill (HTTP ${downloadResponse.status})`,+ phase: 'download',+ status: downloadResponse.status,+ }));}const zipData = yield* downloadResponse.arrayBuffer.pipe(- Effect.catchAll(() => Effect.fail(new Error('Failed to read skill zip data')))+ Effect.mapError(+ cause =>+ new SkillInstallError({+ cause,+ message: 'Failed to read skill zip data',+ phase: 'download',+ })+ ));// Extract to a temp dir, then move into place@@ -192,13 +215,23 @@ export const installSkill = (options?: {yield* Effect.tryPromise({try: () => extractZip(zipPath, { dir: tmpDir }),- catch: error => new Error(`Failed to extract skill zip: ${error}`),+ catch: cause =>+ new SkillInstallError({+ cause,+ message: 'Failed to extract skill zip',+ phase: 'extract',+ }),});// The zip contains composio-cli/ directoryconst extractedDir = path.join(tmpDir, SKILL_NAME);if (!(yield* fs.exists(extractedDir))) {- return yield* Effect.fail(new Error('Extracted skill directory not found'));+ return yield* Effect.fail(+ new SkillInstallError({+ message: 'Extracted skill directory not found',+ phase: 'extract',+ })+ );}yield* Effect.gen(function* () {diff --git a/ts/packages/cli/src/effects/resolve-optional-text-input.ts b/ts/packages/cli/src/effects/resolve-optional-text-input.tsindex b2020a140..7ed017ae9 100644--- a/ts/packages/cli/src/effects/resolve-optional-text-input.ts+++ b/ts/packages/cli/src/effects/resolve-optional-text-input.ts@@ -1,3 +1,4 @@+import { HelpDoc, ValidationError } from '@effect/cli';import { FileSystem } from '@effect/platform';import { Effect, Option } from 'effect';@@ -22,7 +23,9 @@ export const resolveOptionalTextInput = (if (value.startsWith('@')) {const filePath = value.slice(1).trim();if (!filePath) {- return yield* Effect.fail(new Error('Missing file path after "@" in --data'));+ return yield* Effect.fail(+ ValidationError.invalidValue(HelpDoc.p('Missing file path after "@" in --data'))+ );}return yield* fs.readFileString(filePath, 'utf-8');}diff --git a/ts/packages/cli/src/effects/validate-toolkit-versions.ts b/ts/packages/cli/src/effects/validate-toolkit-versions.tsindex 929e57f63..65fcc5e36 100644--- a/ts/packages/cli/src/effects/validate-toolkit-versions.ts+++ b/ts/packages/cli/src/effects/validate-toolkit-versions.ts@@ -1,4 +1,4 @@-import { Effect } from 'effect';+import { Data, Effect } from 'effect';import colors from 'picocolors';import { S_BAR, unicodeOr } from '@clack/prompts';import { TerminalUI } from 'src/services/terminal-ui';@@ -12,13 +12,17 @@ import type { ToolkitVersionOverrides } from './toolkit-version-overrides';* Custom error class for invalid toolkit versions that preserves structured data.* This allows consumers to access both the human-readable message and the machine-readable data.*/-export class InvalidToolkitVersionsValidationError extends Error {+export class InvalidToolkitVersionsValidationError extends Data.TaggedError(+ 'effects/InvalidToolkitVersionsValidationError'+)<{readonly invalidVersions: ReadonlyArray<InvalidVersionDetail>;-+ readonly message: string;+}> {constructor(invalidVersions: ReadonlyArray<InvalidVersionDetail>) {- super(formatInvalidVersionsError(invalidVersions));- this.name = 'InvalidToolkitVersionsValidationError';- this.invalidVersions = invalidVersions;+ super({+ invalidVersions,+ message: formatInvalidVersionsError(invalidVersions),+ });}/**@@ -26,12 +30,20 @@ export class InvalidToolkitVersionsValidationError extends Error {*/toJSON(): { error: string; invalidVersions: ReadonlyArray<InvalidVersionDetail> } {return {- error: this.name,+ error: 'InvalidToolkitVersionsValidationError',invalidVersions: this.invalidVersions,};}}+export class ToolkitVersionValidationError extends Data.TaggedError(+ 'effects/ToolkitVersionValidationError'+)<{+ readonly cause?: unknown;+ readonly message: string;+ readonly reason: 'invalid-toolkit' | 'request' | 'decode' | 'client-unavailable';+}> {}+const MAX_VERSIONS_TO_SHOW = 5;const S_CORNER_BOTTOM_LEFT = unicodeOr('╰', '+');const S_STEP_ERROR = unicodeOr('▲', 'x');@@ -141,7 +153,11 @@ export const validateToolkitVersionOverrides = ({versionOverrides,toolkitSlugsFilter,client,-}: ValidateVersionsOptions): Effect.Effect<ValidateVersionsResult, Error, TerminalUI> =>+}: ValidateVersionsOptions): Effect.Effect<+ ValidateVersionsResult,+ InvalidToolkitVersionsValidationError | ToolkitVersionValidationError,+ TerminalUI+> =>Effect.gen(function* () {const ui = yield* TerminalUI;@@ -164,20 +180,40 @@ export const validateToolkitVersionOverrides = ({),Effect.catchTag('services/InvalidToolkitsError', error =>Effect.fail(- new Error(- `Invalid toolkit(s) in version overrides: ${error.invalidToolkits.join(', ')}. ` +- `Check that the toolkit slug is correct (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL, not COMPOSIO_TOOLKIT_VERSION_GMAL).`- )+ new ToolkitVersionValidationError({+ cause: error,+ message:+ `Invalid toolkit(s) in version overrides: ${error.invalidToolkits.join(', ')}. ` ++ `Check that the toolkit slug is correct (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL, not COMPOSIO_TOOLKIT_VERSION_GMAL).`,+ reason: 'invalid-toolkit',+ }))),Effect.catchTag('services/HttpServerError', error =>- Effect.fail(new Error(`Failed to validate toolkit versions: ${error.cause}`))+ Effect.fail(+ new ToolkitVersionValidationError({+ cause: error,+ message: 'Failed to validate toolkit versions',+ reason: 'request',+ })+ )),Effect.catchTag('services/HttpDecodingError', error =>- Effect.fail(new Error(`Failed to decode toolkit response: ${error.cause}`))+ Effect.fail(+ new ToolkitVersionValidationError({+ cause: error,+ message: 'Failed to decode toolkit response',+ reason: 'decode',+ })+ )),Effect.catchTag('NoSuchElementException', () =>- Effect.fail(new Error('API client not initialized'))+ Effect.fail(+ new ToolkitVersionValidationError({+ message: 'API client not initialized',+ reason: 'client-unavailable',+ })+ )));diff --git a/ts/packages/cli/src/models/cli-user-config.ts b/ts/packages/cli/src/models/cli-user-config.tsindex 34fc9039a..2629d7640 100644--- a/ts/packages/cli/src/models/cli-user-config.ts+++ b/ts/packages/cli/src/models/cli-user-config.ts@@ -76,7 +76,7 @@ export const CliUserConfig = Schema.Struct({* no behavior change on upgrade).*/security: Schema.optionalWith(SecurityBackend, {- default: () => 'auto' as const,+ default: (): SecurityBackend => 'auto',}),}).annotations({identifier: 'CliUserConfig',diff --git a/ts/packages/cli/src/models/utils/json-transform-schema.ts b/ts/packages/cli/src/models/utils/json-transform-schema.tsindex 54550cb3e..8b466e428 100644--- a/ts/packages/cli/src/models/utils/json-transform-schema.ts+++ b/ts/packages/cli/src/models/utils/json-transform-schema.ts@@ -1,4 +1,7 @@-import { Schema, ParseResult } from 'effect';+import { ParseResult, Predicate, Schema } from 'effect';++const errorMessage = (error: unknown): string =>+ Predicate.isError(error) ? error.message : String(error);export function JSONTransformSchema<To extends Schema.Schema.Any>(to: To) {return Schema.transformOrFail(Schema.String, to, {@@ -6,12 +9,12 @@ export function JSONTransformSchema<To extends Schema.Schema.Any>(to: To) {encode: (obj, _options, ast) =>ParseResult.try({try: () => JSON.stringify(obj),- catch: e => new ParseResult.Type(ast, obj, (e as Error).message),+ catch: error => new ParseResult.Type(ast, obj, errorMessage(error)),}),decode: (str, _options, ast) =>ParseResult.try({try: () => JSON.parse(str),- catch: e => new ParseResult.Type(ast, str, (e as Error).message),+ catch: error => new ParseResult.Type(ast, str, errorMessage(error)),}),});}diff --git a/ts/packages/cli/src/services/cli-user-config.ts b/ts/packages/cli/src/services/cli-user-config.tsindex 149d46699..7760ca22e 100644--- a/ts/packages/cli/src/services/cli-user-config.ts+++ b/ts/packages/cli/src/services/cli-user-config.ts@@ -1,11 +1,10 @@-import { FileSystem } from '@effect/platform';+import { FileSystem, Path } from '@effect/platform';import type { PlatformError } from '@effect/platform/Error';-import { Context, Effect, Layer, Option } from 'effect';+import { Context, Effect, Layer, Option, Predicate, Schema } 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 unavailableimport 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 { JsonRecordSchema } from 'src/effects/json';import { setupCacheDir } from 'src/effects/setup-cache-dir';import { getVersion } from 'src/effects/version';import {@@ -36,11 +35,41 @@ export type CliUserConfigResolved = {const detectReleaseChannel = (version: string): CliReleaseChannel =>/-[0-9A-Za-z.-]+$/.test(version) ? 'beta' : 'stable';+const DEFAULT_CLI_USER_CONFIG = CliUserConfig.make({+ developer: {+ enabled: true,+ destructiveActions: false,+ },+ experimentalFeatures: {},+ artifactDirectory: Option.none(),+ experimentalSubagent: Option.none(),+ security: 'auto',+});++const decodeConfigJson = Schema.decodeUnknown(Schema.parseJson(JsonRecordSchema));++// The sync resolvers below run from non-Effect call sites (the+// run-helpers-runtime child process), so the Path service is materialized once+// from its pure default layer instead of being yielded from context.+const syncPath = Effect.runSync(Path.Path.pipe(Effect.provide(Path.layer)));+export const resolveCliConfigDirectorySync = (): string =>- process.env.COMPOSIO_CACHE_DIR?.trim() || path.join(os.homedir(), constants.USER_COMPOSIO_DIR);+ process.env.COMPOSIO_CACHE_DIR?.trim() ||+ syncPath.join(os.homedir(), constants.USER_COMPOSIO_DIR);export const resolveCliConfigPathSync = (): string =>- path.join(resolveCliConfigDirectorySync(), constants.CLI_CONFIG_FILE_NAME);+ syncPath.join(resolveCliConfigDirectorySync(), constants.CLI_CONFIG_FILE_NAME);++/**+ * Effect-based resolver for the CLI config file path. Prefer this over+ * `resolveCliConfigPathSync` inside Effect-hosted code: it honors the+ * COMPOSIO_CACHE_DIR override via `effect/Config` and the NodeOs service.+ */+export const resolveCliConfigPath = Effect.gen(function* () {+ const path = yield* Path.Path;+ const configDir = yield* setupCacheDir;+ return path.join(configDir, constants.CLI_CONFIG_FILE_NAME);+});export class ComposioCliUserConfig extends Context.Tag('ComposioCliUserConfig')<ComposioCliUserConfig,@@ -76,30 +105,17 @@ export const ComposioCliUserConfigLive = Layer.effect(const fs = yield* FileSystem.FileSystem;const version = yield* getVersion;const channel = detectReleaseChannel(version);- const configDir = yield* setupCacheDir;- const jsonConfigPath = path.join(configDir, constants.CLI_CONFIG_FILE_NAME);+ const jsonConfigPath = yield* resolveCliConfigPath;- let rawConfig = CliUserConfig.make({- developer: {- enabled: true,- destructiveActions: false,- },- experimentalFeatures: {},- artifactDirectory: Option.none(),- experimentalSubagent: Option.none(),- security: 'auto',- });+ let rawConfig = DEFAULT_CLI_USER_CONFIG;const normalizeRawConfigJson = (value: unknown): unknown => {- if (!value || typeof value !== 'object' || Array.isArray(value)) {+ if (!Predicate.isRecord(value)) {return value;}- const record = { ...(value as Record<string, unknown>) };- const existingDeveloper =- record.developer && typeof record.developer === 'object' && !Array.isArray(record.developer)- ? { ...(record.developer as Record<string, unknown>) }- : {};+ const record = { ...value };+ const existingDeveloper = Predicate.isRecord(record.developer) ? { ...record.developer } : {};if (!('enabled' in existingDeveloper) && 'developer_mode_enabled' in record) {existingDeveloper.enabled = record.developer_mode_enabled;@@ -137,29 +153,13 @@ export const ComposioCliUserConfigLive = Layer.effect(const load = Effect.gen(function* () {const configJson = yield* fs.readFileString(jsonConfigPath, 'utf8');- rawConfig = yield* cliUserConfigFromJSON(- JSON.stringify(normalizeRawConfigJson(JSON.parse(configJson)))- );+ const parsed = yield* decodeConfigJson(configJson);+ rawConfig = yield* cliUserConfigFromJSON(JSON.stringify(normalizeRawConfigJson(parsed)));return rawConfig;});if (yield* fs.exists(jsonConfigPath)) {- yield* load.pipe(- Effect.catchAll(() =>- persist(- CliUserConfig.make({- developer: {- enabled: true,- destructiveActions: false,- },- experimentalFeatures: {},- artifactDirectory: Option.none(),- experimentalSubagent: Option.none(),- security: 'auto',- })- )- )- );+ yield* load.pipe(Effect.catchAll(() => persist(DEFAULT_CLI_USER_CONFIG)));} else {yield* persist(rawConfig);}diff --git a/ts/packages/cli/src/services/command-hints.ts b/ts/packages/cli/src/services/command-hints.tsindex 147b4b718..3bb8c37c3 100644--- a/ts/packages/cli/src/services/command-hints.ts+++ b/ts/packages/cli/src/services/command-hints.ts@@ -1,7 +1,11 @@+import { Record as EffectRecord } from 'effect';+type HintParams = Readonly<Record<string, string | undefined>>;-const getParam = (params: HintParams | undefined, key: string, fallback: string) =>- params?.[key]?.trim() ? params[key]! : fallback;+const getParam = (params: HintParams | undefined, key: string, fallback: string) => {+ const value = params?.[key];+ return value?.trim() ? value : fallback;+};export type CommandHintId =| 'root.search'@@ -120,7 +124,7 @@ export const commandHintLinks = (id: CommandHintId): ReadonlyArray<CommandHintIdCOMMAND_HINTS[id].links ?? [];export const renderCommandHintGraph = () => ({- nodes: (Object.keys(COMMAND_HINTS) as CommandHintId[]).map(id => ({+ nodes: EffectRecord.toEntries(COMMAND_HINTS).map(([id]) => ({id,example: commandHintExample(id),links: [...commandHintLinks(id)],diff --git a/ts/packages/cli/src/services/command-project.ts b/ts/packages/cli/src/services/command-project.tsindex 4e729e3b0..9244c77d3 100644--- a/ts/packages/cli/src/services/command-project.ts+++ b/ts/packages/cli/src/services/command-project.ts@@ -1,4 +1,4 @@-import { Data, Effect, Option } from 'effect';+import { Data, Effect, Option, Predicate } from 'effect';import { ProjectContext } from './project-context';import { ComposioUserContext } from './user-context';import {@@ -6,8 +6,6 @@ import {findDeveloperProjectByName,DeveloperProjectNotFoundError,AmbiguousDeveloperProjectNameError,- type HttpDecodingError,- type HttpServerError,} from './composio-clients';export type ProjectMode = 'consumer' | 'developer';@@ -15,10 +13,7 @@ export type ProjectMode = 'consumer' | 'developer';export type CliProjectType = 'CONSUMER' | 'DEVELOPER';export type CliProjectResolutionSource =- | 'consumer-default'- | 'developer-project-name'- | 'developer-local-config'- | 'developer-explicit';+ 'consumer-default' | 'developer-project-name' | 'developer-local-config' | 'developer-explicit';export interface ResolvedCommandProject {readonly orgId: string;@@ -29,13 +24,11 @@ export interface ResolvedCommandProject {readonly source: CliProjectResolutionSource;}-export class MissingDefaultOrgError extends Data.TaggedError(- 'services/MissingDefaultOrgError'-)<{}> {}+export class MissingDefaultOrgError extends Data.TaggedError('services/MissingDefaultOrgError') {}export class MissingDeveloperProjectError extends Data.TaggedError('services/MissingDeveloperProjectError'-)<{}> {}+) {}const requireDefaultOrg = (orgId: Option.Option<string>) =>Option.match(orgId, {@@ -117,15 +110,7 @@ export const resolveCommandProject = (params: { mode: ProjectMode; projectName?:projectType: 'DEVELOPER',source: 'developer-local-config',} satisfies ResolvedCommandProject;- }) as Effect.Effect<- ResolvedCommandProject,- | MissingDefaultOrgError- | MissingDeveloperProjectError- | DeveloperProjectNotFoundError- | AmbiguousDeveloperProjectNameError- | HttpServerError- | HttpDecodingError- >;+ });export const formatResolveCommandProjectError = (error: unknown): Error => {if (error instanceof MissingDefaultOrgError) {@@ -148,11 +133,12 @@ export const formatResolveCommandProjectError = (error: unknown): Error => {`Developer project name "${error.projectName}" is ambiguous in org "${error.orgId}". Use an exact unique project name.`);}- if (typeof error === 'object' && error && 'details' in error) {- const details = (error as { details?: { message?: string } }).details;- if (details?.message) {- return new Error(details.message);- }+ if (+ Predicate.hasProperty(error, 'details') &&+ Predicate.hasProperty(error.details, 'message') &&+ Predicate.isString(error.details.message)+ ) {+ return new Error(error.details.message);}if (error instanceof Error) {return error;diff --git a/ts/packages/cli/src/services/composio-clients.ts b/ts/packages/cli/src/services/composio-clients.tsindex 678c96257..cd4cab42c 100644--- a/ts/packages/cli/src/services/composio-clients.ts+++ b/ts/packages/cli/src/services/composio-clients.ts@@ -32,15 +32,16 @@ import {type ToolkitVersionSpec,type ToolkitVersionOverrides,} from 'src/effects/toolkit-version-overrides';+import { JsonRecordSchema } from 'src/effects/json';import { Session, RetrievedSession } from 'src/models/session';import { TriggerType, TriggerTypes, TriggerTypesAsEnums } from 'src/models/trigger-types';import * as constants from 'src/constants';import { getCurrentCwdSessionId } from 'src/analytics/dispatch';import { ComposioUserContext, ComposioUserContextLive } from './user-context';-import { NodeOs } from './node-os';import { ProjectContext } from './project-context';import type { NoSuchElementException } from 'effect/Cause';import { renderPrettyError } from './utils/pretty-error';+import { NodeOs } from './node-os';/*** Error types@@ -99,6 +100,16 @@ export class HttpDecodingError extends Data.TaggedError('services/HttpDecodingErexport type HttpError = HttpServerError | HttpDecodingError;+// Sort items by slug.+// TODO: make sure this happens on the server-side.+const sortBySlug = <T extends { readonly slug: string }>(+ items: ReadonlyArray<T>+): ReadonlyArray<T> =>+ Array.sort(+ items,+ Order.mapInput(Order.string, (item: T) => item.slug)+ );+const validateToolkitVersionsImpl = (client: {toolkits: {@@ -293,8 +304,8 @@ export const ToolDetailedResponse = Schema.Struct({description: Schema.String,tags: Schema.Array(Schema.String),available_versions: Schema.Array(Schema.String),- input_parameters: Schema.Record({ key: Schema.String, value: Schema.Unknown }),- output_parameters: Schema.Record({ key: Schema.String, value: Schema.Unknown }),+ input_parameters: JsonRecordSchema,+ output_parameters: JsonRecordSchema,no_auth: Schema.optionalWith(Schema.Boolean, { default: () => false }),toolkit: Schema.optionalWith(Schema.Struct({@@ -1365,8 +1376,7 @@ const buildDefaultHeaders = (params: {};// Utility function for calling the Composio API and decoding its response.-// eslint-disable-next-line @typescript-eslint/no-explicit-any-const callClient = <T, S extends Schema.Schema<any, any>>(+const callClient = <T, S extends Schema.Schema.AnyNoContext>(clientSingleton: ComposioClientSingleton,apiCall: (client: _RawComposioClient) => APIPromise<T>,responseSchema: S@@ -1407,17 +1417,16 @@ const callClient = <T, S extends Schema.Schema<any, any>>(return { metrics, data: typedJson };});-// Schema constraint for paginated responses-type PaginatedSchema = Schema.Schema<- {- // eslint-disable-next-line @typescript-eslint/no-explicit-any- items: ReadonlyArray<any>;- next_cursor: string | null;- total_pages: number;- },- // eslint-disable-next-line @typescript-eslint/no-explicit-any- any->;+// Schema constraint for paginated responses: the decoded page must expose the+// pagination envelope, expressed through the schema's `Type` phantom property so+// concrete item types stay free of `any`.+type PaginatedSchema = Schema.Schema.AnyNoContext & {+ readonly Type: {+ readonly items: ReadonlyArray<unknown>;+ readonly next_cursor: string | null;+ readonly total_pages: number;+ };+};// Maximum items per page allowed by the serverconst MAX_PAGE_SIZE = 1000;@@ -2071,14 +2080,7 @@ export class ComposioToolkitsRepository extends Effect.Service<ComposioToolkitsRconst getToolkits = () =>client.toolkits.list().pipe(Effect.map(response => response.items),- Effect.flatMap(- Effect.fn(function* (toolkits) {- // Sort apps by slug.- // TODO: make sure this happens on the server-side.- const orderBySlug = Order.mapInput(Order.string, (app: Toolkit) => app.slug);- return Array.sort(toolkits, orderBySlug) as ReadonlyArray<Toolkit>;- })- )+ Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>));/**@@ -2107,16 +2109,7 @@ export class ComposioToolkitsRepository extends Effect.Service<ComposioToolkitsR)),{ concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }- ).pipe(- Effect.flatMap(- Effect.fn(function* (toolkits) {- // Sort apps by slug.- // TODO: make sure this happens on the server-side.- const orderBySlug = Order.mapInput(Order.string, (app: Toolkit) => app.slug);- return Array.sort(toolkits, orderBySlug) as ReadonlyArray<Toolkit>;- })- )- );+ ).pipe(Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>));return {getToolkits,@@ -2131,14 +2124,7 @@ export class ComposioToolkitsRepository extends Effect.Service<ComposioToolkitsRgetTools: (toolkitSlugs?: ReadonlyArray<string>) =>client.tools.list(toolkitSlugs ?? []).pipe(Effect.map(response => response.items),- Effect.flatMap(- Effect.fn(function* (tools) {- // Sort apps by slug.- // TODO: make sure this happens on the server-side.- const orderBySlug = Order.mapInput(Order.string, (app: Tool) => app.slug);- return Array.sort(tools, orderBySlug) as ReadonlyArray<Tool>;- })- )+ Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)),/*** Fetches tools with per-toolkit version support.@@ -2148,14 +2134,7 @@ export class ComposioToolkitsRepository extends Effect.Service<ComposioToolkitsRgetToolsByVersionSpecs: (specs: ReadonlyArray<ToolkitVersionSpec>) =>client.tools.listByVersionSpecs(specs).pipe(Effect.map(response => response.items),- Effect.flatMap(- Effect.fn(function* (tools) {- // Sort apps by slug.- // TODO: make sure this happens on the server-side.- const orderBySlug = Order.mapInput(Order.string, (app: Tool) => app.slug);- return Array.sort(tools, orderBySlug) as ReadonlyArray<Tool>;- })- )+ Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)),getTriggerTypesAsEnums: () => client.triggersTypes.retrieveEnum(),/**@@ -2171,14 +2150,7 @@ export class ComposioToolkitsRepository extends Effect.Service<ComposioToolkitsRgetTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) =>client.triggersTypes.list(toolkitSlugs).pipe(Effect.map(response => response.items),- Effect.flatMap(- Effect.fn(function* (triggerTypes) {- // Sort apps by slug.- // TODO: make sure this happens on the server-side.- const orderBySlug = Order.mapInput(Order.string, (app: TriggerType) => app.slug);- return Array.sort(triggerTypes, orderBySlug) as ReadonlyArray<TriggerType>;- })- )+ Effect.map(items => sortBySlug(items) as ReadonlyArray<TriggerType>)),/*** Validates that the given toolkit slugs are valid by comparing them against the listdiff --git a/ts/packages/cli/src/services/composio-error-overrides.ts b/ts/packages/cli/src/services/composio-error-overrides.tsindex 1048a10c2..97ceb6b9d 100644--- a/ts/packages/cli/src/services/composio-error-overrides.ts+++ b/ts/packages/cli/src/services/composio-error-overrides.ts@@ -1,9 +1,11 @@+import { Predicate } from 'effect';import {extractApiErrorDetails,extractMessage,extractSlug,type ApiErrorDetails,} from 'src/utils/api-error-extraction';+import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';const NO_CONNECTION_SLUGS: ReadonlySet<string> = new Set(['ActionExecute_ConnectedAccountNotFound',@@ -14,22 +16,22 @@ const extractNestedDetails = (value: unknown): unknown => {let current: unknown = value;const seen = new Set<unknown>();- while (current && typeof current === 'object' && !seen.has(current)) {+ while (Predicate.isObject(current) && !seen.has(current)) {seen.add(current);- if ('details' in current) {- const details = (current as { details?: unknown }).details;+ if (Predicate.hasProperty(current, 'details')) {+ const details = current.details;if (details !== undefined) {return details;}}- if ('error' in current) {- current = (current as { error?: unknown }).error;+ if (Predicate.hasProperty(current, 'error')) {+ current = current.error;continue;}- if ('cause' in current) {- current = (current as { cause?: unknown }).cause;+ if (Predicate.hasProperty(current, 'cause')) {+ current = current.cause;continue;}break;@@ -42,19 +44,19 @@ export const normalizeCliError = (error: unknown): unknown => {let current: unknown = error;const seen = new Set<unknown>();- while (current && typeof current === 'object' && !seen.has(current)) {+ while (Predicate.isObject(current) && !seen.has(current)) {seen.add(current);if (current instanceof Error) {return current;}- if ('error' in current) {- current = (current as { error?: unknown }).error;+ if (Predicate.hasProperty(current, 'error')) {+ current = current.error;continue;}- if ('cause' in current) {- current = (current as { cause?: unknown }).cause;+ if (Predicate.hasProperty(current, 'cause')) {+ current = current.cause;continue;}break;@@ -78,10 +80,10 @@ export const buildNoActiveConnectionMessage = (params: {return `No active connection found for toolkit "${params.toolkit}". Run \`composio link ${params.toolkit}\`, then retry.`;}if (params.toolSlug) {- const idx = params.toolSlug.indexOf('_');- const toolkit =- idx <= 0 ? params.toolSlug.toLowerCase() : params.toolSlug.slice(0, idx).toLowerCase();- if (toolkit !== 'composio') {+ // `toolkitFromToolSlug` returns the whole slug lowercased when there is no+ // underscore, so keep the explicit 'composio' guard for the bare-slug case.+ const toolkit = toolkitFromToolSlug(params.toolSlug);+ if (toolkit && toolkit !== 'composio') {return `No active connection found for toolkit "${toolkit}". Run \`composio link ${toolkit}\`, then retry.`;}}diff --git a/ts/packages/cli/src/services/connected-account-selection.ts b/ts/packages/cli/src/services/connected-account-selection.tsindex 826078323..b41ffcd97 100644--- a/ts/packages/cli/src/services/connected-account-selection.ts+++ b/ts/packages/cli/src/services/connected-account-selection.ts@@ -20,15 +20,15 @@ export type CachedConnectedAccountSummary = typeof CachedConnectedAccountSummaryconst normalizeSelector = (value: string): string => value.trim().toLowerCase();-const parseTimestamp = (value: string | undefined): number => {+const parseTimestamp = (value: string | null | undefined): number => {if (!value) return 0;const parsed = Date.parse(value);return Number.isFinite(parsed) ? parsed : 0;};-const compareNewestFirst = (- left: Pick<ConnectedAccountItem, 'updated_at' | 'created_at'>,- right: Pick<ConnectedAccountItem, 'updated_at' | 'created_at'>+export const compareNewestFirst = (+ left: { readonly updated_at?: string | null; readonly created_at?: string | null },+ right: { readonly updated_at?: string | null; readonly created_at?: string | null }): number =>Math.max(parseTimestamp(right.updated_at), parseTimestamp(right.created_at)) -Math.max(parseTimestamp(left.updated_at), parseTimestamp(left.created_at));diff --git a/ts/packages/cli/src/services/consumer-short-term-cache.ts b/ts/packages/cli/src/services/consumer-short-term-cache.tsindex 700f4f564..eea8c5b8e 100644--- a/ts/packages/cli/src/services/consumer-short-term-cache.ts+++ b/ts/packages/cli/src/services/consumer-short-term-cache.ts@@ -1,6 +1,7 @@import { FileSystem, Path } from '@effect/platform';import { Effect, Option, Record as EffectRecord, Schema } from 'effect';import { APP_CONFIG } from 'src/effects/app-config';+import { JsonRecordSchema } from 'src/effects/json';import { setupCacheDir } from 'src/effects/setup-cache-dir';import { NodeProcess } from 'src/services/node-process';import {@@ -10,6 +11,8 @@ import {resolveConsumerProject,} from 'src/services/composio-clients';import { resolveCommandProject } from 'src/services/command-project';+import { collectDecodedEntries } from 'src/utils/collect-decoded-entries';+import { djb2Hash } from 'src/utils/djb2';import { resolveToolRouterSessionConnections } from 'src/services/tool-router-session-connections';import { ComposioUserContext } from 'src/services/user-context';import {@@ -45,15 +48,14 @@ const CacheEntrySchema = Schema.Struct({})),});+export type ConsumerToolRouterAuthConfigMappings =typeof ConsumerToolRouterAuthConfigMappingsSchema.Type;export type ConsumerToolRouterConnectedAccountMappings =typeof ConsumerToolRouterConnectedAccountMappingsSchema.Type;type CacheEntry = typeof CacheEntrySchema.Type;type CacheState = { readonly [key: string]: CacheEntry };-const decodeCacheShell = Schema.decodeUnknownOption(- Schema.parseJson(Schema.Record({ key: Schema.String, value: Schema.Unknown }))-);+const decodeCacheShell = Schema.decodeUnknownOption(Schema.parseJson(JsonRecordSchema));const decodeCacheEntry = Schema.decodeUnknownOption(CacheEntrySchema);// Per-entry decode: one stale or version-skewed entry (e.g. written by a@@ -62,15 +64,7 @@ const decodeCacheEntry = Schema.decodeUnknownOption(CacheEntrySchema);export const decodeCacheStateTolerant = (raw: string): CacheState =>Option.match(decodeCacheShell(raw), {onNone: (): CacheState => ({}),- onSome: shell =>- Object.fromEntries(- Object.entries(shell).flatMap(([key, value]) =>- Option.match(decodeCacheEntry(value), {- onNone: () => [],- onSome: entry => [[key, entry] as const],- })- )- ),+ onSome: shell => collectDecodedEntries(shell, decodeCacheEntry),});const cacheKey = (orgId: string, consumerUserId: string) => `${orgId}:${consumerUserId}`;@@ -81,13 +75,7 @@ const cachePath = Effect.gen(function* () {return path.join(cacheDir, CACHE_FILE);});-const cwdHash = (cwd: string): string => {- let hash = 5381;- for (let i = 0; i < cwd.length; i += 1) {- hash = (hash * 33) ^ cwd.charCodeAt(i);- }- return Math.abs(hash >>> 0).toString(36);-};+const cwdHash = (cwd: string): string => djb2Hash(cwd).toString(36);const createProbablyMyCliSessionId = (cwd: string): string => {const random = crypto.randomUUID().replace(/-/g, '').slice(0, 10);@@ -146,9 +134,10 @@ const writeCache = (state: CacheState) =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;const cacheDir = yield* setupCacheDir;+ const filePath = yield* cachePath;yield* fs.makeDirectory(cacheDir, { recursive: true }).pipe(Effect.catchAll(() => Effect.void));yield* fs- .writeFileString(yield* cachePath, JSON.stringify(state, null, 2))+ .writeFileString(filePath, JSON.stringify(state, null, 2)).pipe(Effect.catchAll(() => Effect.void));});@@ -268,48 +257,43 @@ const mergeConnectedAccountMappings = (params: {});};-export const getFreshConsumerConnectedToolkitsFromCache = (params: {- orgId: string;- consumerUserId: string;-}) =>+// Shared prefix of every getFresh*FromCache accessor: bail to Option.none()+// when the cache is disabled, the entry is missing, or its TTL has passed.+const getFreshCacheEntry = (params: { orgId: string; consumerUserId: string }) =>Effect.gen(function* () {const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;if (disabled) {- return Option.none<ReadonlyArray<string>>();+ return Option.none<CacheEntry>();}const state = yield* readCache();const entry = state[cacheKey(params.orgId, params.consumerUserId)];if (!entry) {- return Option.none<ReadonlyArray<string>>();+ return Option.none<CacheEntry>();}const expiresAtMs = Date.parse(entry.expiresAt);if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) {- return Option.none<ReadonlyArray<string>>();+ return Option.none<CacheEntry>();}- return Option.some(entry.toolkits);+ return Option.some(entry);});+export const getFreshConsumerConnectedToolkitsFromCache = (params: {+ orgId: string;+ consumerUserId: string;+}) => getFreshCacheEntry(params).pipe(Effect.map(Option.map(entry => entry.toolkits)));+export const getFreshConsumerToolRouterAuthConfigsFromCache = (params: {orgId: string;consumerUserId: string;toolkits?: ReadonlyArray<string>;}) =>Effect.gen(function* () {- const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;- if (disabled) {- return Option.none<ConsumerToolRouterAuthConfigMappings>();- }- const state = yield* readCache();- const entry = state[cacheKey(params.orgId, params.consumerUserId)];- if (!entry) {- return Option.none<ConsumerToolRouterAuthConfigMappings>();- }- const expiresAtMs = Date.parse(entry.expiresAt);- if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) {+ const entry = yield* getFreshCacheEntry(params);+ if (Option.isNone(entry)) {return Option.none<ConsumerToolRouterAuthConfigMappings>();}- const mappings = normalizeAuthConfigMappings(entry.toolRouterAuthConfigs);+ const mappings = normalizeAuthConfigMappings(entry.value.toolRouterAuthConfigs);if (!mappings) {return Option.none<ConsumerToolRouterAuthConfigMappings>();}@@ -339,21 +323,12 @@ export const getFreshConsumerToolRouterConnectedAccountsFromCache = (params: {toolkits?: ReadonlyArray<string>;}) =>Effect.gen(function* () {- const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;- if (disabled) {- return Option.none<ConsumerToolRouterConnectedAccountMappings>();- }- const state = yield* readCache();- const entry = state[cacheKey(params.orgId, params.consumerUserId)];- if (!entry) {- return Option.none<ConsumerToolRouterConnectedAccountMappings>();- }- const expiresAtMs = Date.parse(entry.expiresAt);- if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) {+ const entry = yield* getFreshCacheEntry(params);+ if (Option.isNone(entry)) {return Option.none<ConsumerToolRouterConnectedAccountMappings>();}- const mappings = normalizeConnectedAccountMappings(entry.toolRouterConnectedAccounts);+ const mappings = normalizeConnectedAccountMappings(entry.value.toolRouterConnectedAccounts);if (!mappings) {return Option.none<ConsumerToolRouterConnectedAccountMappings>();}@@ -363,25 +338,23 @@ export const getFreshConsumerToolRouterConnectedAccountsFromCache = (params: {}const requestedToolkits = params.toolkits.map(toolkit => toolkit.toLowerCase());- const filteredConnectedAccounts = requestedToolkits.reduce<Record<string, string>>(- (acc, toolkit) => {+ const filteredConnectedAccounts = EffectRecord.fromEntries(+ requestedToolkits.flatMap(toolkit => {const connectedAccountId = mappings.connectedAccounts?.[toolkit];- if (typeof connectedAccountId === 'string') {- acc[toolkit] = connectedAccountId;- }- return acc;- },- {}+ return typeof connectedAccountId === 'string'+ ? [[toolkit, connectedAccountId] as const]+ : [];+ })+ );+ const filteredAvailableConnectedAccounts: Record<+ string,+ ReadonlyArray<CachedConnectedAccountSummary>+ > = EffectRecord.fromEntries(+ requestedToolkits.flatMap(toolkit => {+ const accounts = mappings.availableConnectedAccounts?.[toolkit];+ return Array.isArray(accounts) && accounts.length > 0 ? [[toolkit, accounts] as const] : [];+ }));- const filteredAvailableConnectedAccounts = requestedToolkits.reduce<- Record<string, ReadonlyArray<CachedConnectedAccountSummary>>- >((acc, toolkit) => {- const accounts = mappings.availableConnectedAccounts?.[toolkit];- if (Array.isArray(accounts) && accounts.length > 0) {- acc[toolkit] = accounts;- }- return acc;- }, {});const filtered = normalizeConnectedAccountMappings({connectedAccounts: filteredConnectedAccounts,availableConnectedAccounts: filteredAvailableConnectedAccounts,diff --git a/ts/packages/cli/src/services/env-lang-detector.ts b/ts/packages/cli/src/services/env-lang-detector.tsdeleted file mode 100644index 3d758b997..000000000--- a/ts/packages/cli/src/services/env-lang-detector.ts+++ /dev/null@@ -1,213 +0,0 @@-import { BunFileSystem } from '@effect/platform-bun';-import { pipe, Data, Effect } from 'effect';-import { FileSystem } from '@effect/platform';--export class EnvLangDetectorError extends Data.TaggedError('services/DetectEnvLangError')<{- readonly cause: Error;- readonly message: string;-}> {}--// Service that attempts to detect the language of the project in the current working directory.-export class EnvLangDetector extends Effect.Service<EnvLangDetector>()('services/EnvLangDetector', {- effect: Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;-- return {- detectEnvLanguage: (- cwd: string- ): Effect.Effect<'TypeScript' | 'Python', EnvLangDetectorError, never> =>- Effect.gen(function* () {- const files = yield* pipe(- fs.readDirectory(cwd),- Effect.catchAll(e =>- Effect.fail(- new EnvLangDetectorError({ cause: e, message: `Failed to read directory ${cwd}` })- )- )- );-- // Convert to lowercase for case-insensitive comparison- const fileNames = files.map(f => f.toLowerCase());- yield* Effect.logDebug(`Files in directory ${cwd}:\n${fileNames.join('\n')}`);-- // TypeScript project indicators (in order of precedence)- const typescriptIndicators = [- 'tsconfig.json',- 'package.json',- 'yarn.lock',- 'package-lock.json',- 'pnpm-lock.yaml',- 'bun.lockb',- 'deno.json',- 'deno.jsonc',- ];-- // Python project indicators (in order of precedence)- const pythonIndicators = [- 'pyproject.toml',- 'setup.py',- 'requirements.txt',- 'pipfile',- 'pipfile.lock',- 'poetry.lock',- 'conda.yaml',- 'environment.yml',- 'setup.cfg',- 'tox.ini',- 'pytest.ini',- '__pycache__',- ];-- // Check for TypeScript indicators first- const hasTypescriptIndicator = typescriptIndicators.some(indicator =>- fileNames.includes(indicator)- );-- // Check for Python indicators- const hasPythonIndicator = pythonIndicators.some(indicator =>- fileNames.includes(indicator)- );-- yield* Effect.logDebug(`TypeScript indicators found: ${hasTypescriptIndicator}`);- yield* Effect.logDebug(`Python indicators found: ${hasPythonIndicator}`);-- // Additional checks for file extensions if no clear indicators found- if (!hasTypescriptIndicator && !hasPythonIndicator) {- // Get actual file names (not lowercase) for extension checking- const hasTypeScriptFiles = files.some(- file => file.endsWith('.ts') || file.endsWith('.tsx') || file.endsWith('.mts')- );-- const hasPythonFiles = files.some(- file =>- file.endsWith('.py') ||- file.endsWith('.pyw') ||- file.endsWith('.pyi') ||- file.endsWith('.pyx')- );-- if (hasTypeScriptFiles && !hasPythonFiles) {- return 'TypeScript' as const;- }-- if (hasPythonFiles && !hasTypeScriptFiles) {- return 'Python' as const;- }-- // If both or neither are found, check for more files by reading subdirectories- // This is a more exhaustive check- const allFiles: string[] = [];-- // Don't recurse into common directories that might contain false positives- const skipDirs = [- '.composio',- 'node_modules',- '.git',- '__pycache__',- '.venv',- 'venv',- 'env',- 'dist',- 'build',- ];-- // Recursively collect files from immediate subdirectories- yield* Effect.logInfo('Checking subdirectories for more files...');-- for (const item of files) {- const itemPath = `${cwd}/${item}`;- const stat = yield* pipe(- fs.stat(cwd),- Effect.catchAll(e =>- Effect.fail(- new EnvLangDetectorError({- cause: e,- message: `Failed to read file ${itemPath}`,- })- )- )- );-- if (stat.type === 'Directory') {- if (!skipDirs.includes(item.toLowerCase())) {- const subFiles = yield* pipe(- fs.readDirectory(item),- Effect.catchAll(e =>- Effect.fail(- new EnvLangDetectorError({- cause: e,- message: `Failed to read directory ${item}`,- })- )- )- );- allFiles.push(...subFiles);- }- }- }-- const allFileNames = [...files, ...allFiles];-- const deepTsFiles = allFileNames.filter(- file => file.endsWith('.ts') || file.endsWith('.tsx') || file.endsWith('.mts')- ).length;-- const deepPyFiles = allFileNames.filter(- file =>- file.endsWith('.py') ||- file.endsWith('.pyw') ||- file.endsWith('.pyi') ||- file.endsWith('.pyx')- ).length;-- // Decide based on which has more files- if (deepTsFiles > deepPyFiles && deepTsFiles > 0) {- return 'TypeScript' as const;- }-- if (deepPyFiles > deepTsFiles && deepPyFiles > 0) {- return 'Python' as const;- }- }-- // Prioritize based on strength of indicators- if (hasTypescriptIndicator && hasPythonIndicator) {- // Both present - prioritize based on most definitive files- const strongTsIndicators = ['tsconfig.json', 'package.json'];- const strongPyIndicators = ['pyproject.toml', 'setup.py'];-- const hasStrongTs = strongTsIndicators.some(indicator => fileNames.includes(indicator));- const hasStrongPy = strongPyIndicators.some(indicator => fileNames.includes(indicator));-- if (hasStrongTs && !hasStrongPy) {- return 'TypeScript' as const;- }- if (hasStrongPy && !hasStrongTs) {- return 'Python' as const;- }-- // If both have strong indicators, default to TypeScript- // (this is arbitrary but package.json is very common)- return 'TypeScript' as const;- }-- if (hasTypescriptIndicator) {- return 'TypeScript' as const;- }-- if (hasPythonIndicator) {- return 'Python' as const;- }-- // No clear indicators found- return yield* Effect.fail(- new EnvLangDetectorError({- cause: new Error('Unable to detect project language'),- message: `Could not determine if directory '${cwd}' contains a Python or TypeScript project. No recognizable project files or patterns found.`,- })- );- }),- };- }),- dependencies: [BunFileSystem.layer],-}) {}diff --git a/ts/packages/cli/src/services/run-companion-modules.ts b/ts/packages/cli/src/services/run-companion-modules.tsindex c85733145..dcd6bcab3 100644--- a/ts/packages/cli/src/services/run-companion-modules.ts+++ b/ts/packages/cli/src/services/run-companion-modules.ts@@ -645,95 +645,3 @@ export const resolveRunCompanionModulePath = ({: path.resolve(currentDirectory, `${baseName}.mjs`));});--// ── 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 value = fsSync.readFileSync(filePath, 'utf8').trim();- return value.length > 0 ? value : undefined;-};--export const resolveInstalledCliVersionSync = (execPath: string, fallbackVersion: string): string =>- normalizeCliReleaseVersion(- readTextFileIfPresentSync(- pathSync.join(pathSync.dirname(execPath), RUN_COMPANION_RELEASE_TAG_FILENAME)- ) ?? fallbackVersion- );--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 resolveRunCompanionModulePathSync = ({- callerImportMetaUrl,- execPath,- relativeNoExtensionFromCaller,-}: {- callerImportMetaUrl: string;- execPath: string;- relativeNoExtensionFromCaller: string;-}): string => {- const currentFilePath = fileURLToPath(callerImportMetaUrl);- const currentDirectory = pathSync.dirname(currentFilePath);- const executableDirectory = pathSync.dirname(execPath);- const baseName = pathSync.basename(relativeNoExtensionFromCaller);-- const candidates = [- 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 (fsSync.existsSync(candidate)) {- return candidate;- }- }-- return currentFilePath.startsWith('/$bunfs/')- ? 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.tsindex 019f52a70..cca3bdd25 100644--- a/ts/packages/cli/src/services/run-helpers-runtime.ts+++ b/ts/packages/cli/src/services/run-helpers-runtime.ts@@ -1,16 +1,25 @@+// This module is preloaded into the user's spawned child process, where no Effect+// runtime or @effect/platform layers are provided, so it uses sync Node builtins.// 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 runtimeimport * 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 runtimeimport * 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 { Path } from '@effect/platform';+import { Effect, Predicate, Schema } from 'effect';import { z } from 'zod';+import { JsonRecordSchema } from 'src/effects/json';import { resolveCliConfigPathSync } from 'src/services/cli-user-config';-import type { MasterKind } from 'src/services/master-detector';-import { isAcpInvokeError } from 'src/services/run-subagent-shared';+import { detectMaster, type MasterKind } from 'src/services/master-detector';+import {+ isAcpInvokeError,+ parseJson,+ type HelperDebugLog,+ type InvokeAgentNormalizedOptions,+} from 'src/services/run-subagent-shared';import { invokeAcpSubAgent } from 'src/services/run-subagent-acp';import { invokeLegacySubAgent } from 'src/services/run-subagent-legacy';+import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';export type RunHelperContext = {readonly apiKey?: string;@@ -41,59 +50,25 @@ type RunHelpersInstallParams = {readonly helperContext?: RunHelperContext;};-type RunCliResult =- | undefined- | string- | number- | boolean- | {- readonly successful?: boolean;- readonly storedInFile?: boolean;- readonly outputFilePath?: string | null;- readonly tokenCount?: number | null;- readonly error?: string | null;- readonly data?: unknown;- readonly [key: string]: unknown;- };+type RunCliResult = unknown;-type PromptableResult = {- readonly prompt?: () => string;- readonly data?: unknown;- readonly [key: string]: unknown;-};--type StructuredSchemaInput =- | {- readonly safeParse?: (value: unknown) => unknown;- readonly _def?: unknown;- }- | Record<string, unknown>;--type NormalizedInvokeAgentOptions = {- readonly target?: string;- readonly model?: string;- readonly schema?: StructuredSchemaInput;- readonly jsonSchema?: Record<string, unknown>;- readonly structuredSchema?: Record<string, unknown>;- readonly zodSchema?: StructuredSchemaInput;-};--type RunGlobalScope = typeof globalThis & {- z: typeof z;- zod: typeof z;- search: (query: string, options?: Record<string, unknown>) => Promise<RunCliResult>;- execute: (slug: string, data?: unknown, options?: { account?: string }) => Promise<RunCliResult>;- experimental_subAgent: (prompt: string, options?: Record<string, unknown>) => Promise<unknown>;- invokeAgent: (prompt: string, options?: Record<string, unknown>) => Promise<unknown>;- proxy: (- toolkit: string- ) => Promise<(input: string | URL, init?: RequestInit) => Promise<Response>>;- __composioRunContext: {- readonly outputDir: string | null;- readonly logFilePath: string | null;- };- __composioConsumerContext: RunHelperContext;-};+const JsonObject = JsonRecordSchema;+const ExperimentalSubagentConfig = Schema.Struct({+ experimental_subagent: Schema.optional(+ Schema.Struct({ target: Schema.optional(Schema.Unknown) })+ ),+});+const decodeExperimentalSubagentConfig = Schema.decodeUnknownSync(+ Schema.parseJson(ExperimentalSubagentConfig)+);+const ProxySessionResponse = Schema.Struct({ session_id: Schema.NonEmptyString });+const ProxyExecuteResponse = Schema.Struct({+ headers: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.String })),+ binary_data: Schema.optional(Schema.Struct({ url: Schema.optional(Schema.String) })),+ data: Schema.optional(Schema.Unknown),+ status: Schema.optional(Schema.Number),+});+type ProxyExecuteResponse = Schema.Schema.Type<typeof ProxyExecuteResponse>;const experimentalSubAgentSchema = {type: 'function',@@ -135,7 +110,7 @@ const experimentalSubAgentSchema = {logFilePath: { description: 'Path to the local run log file for helper execution details.' },},},-} as const;+};const proxySchema = {type: 'function',@@ -165,9 +140,7 @@ const proxySchema = {},},},-} as const;--const runGlobals = globalThis as RunGlobalScope;+};const encodeBase64 = (bytes: Uint8Array): string => {let binary = '';@@ -177,141 +150,337 @@ const encodeBase64 = (bytes: Uint8Array): string => {return btoa(binary);};-// eslint-disable-next-line max-lines-per-function-export const installRunHelpers = async ({- cliPrefix,- helperContext = {},-}: RunHelpersInstallParams): Promise<void> => {- runGlobals.z = z;- runGlobals.zod = z;+// ---------------------------------------------------------------------------+// Pure helpers — no run-context captures, hoisted to module scope+// ---------------------------------------------------------------------------- const perfDebugEnabled =- helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === '1';- const toolDebugEnabled =- helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === '1';- const perfDebugStart = Date.now();- let perfDebugSeq = 0;- const executeId = () => crypto.randomUUID().slice(0, 8);- const proxySessionCache = new Map<string, string>();- const composioBaseURL = (helperContext.baseURL || 'https://backend.composio.dev').replace(- /\/$/,- ''- );- const sharedRunOutputDir =- typeof helperContext.runOutputDir === 'string' && helperContext.runOutputDir.length > 0- ? helperContext.runOutputDir- : null;- const sharedRunLogFilePath =- typeof helperContext.runLogFilePath === 'string' && helperContext.runLogFilePath.length > 0- ? helperContext.runLogFilePath- : null;+const executeId = () => crypto.randomUUID().slice(0, 8);- const appendRunLogLine = (line: string) => {- if (!sharedRunLogFilePath || line.length === 0) return;- fs.appendFileSync(sharedRunLogFilePath, `${line}\n`, 'utf8');- };+const truncateDebugText = (value: unknown, max = 240) => {+ const text = typeof value === 'string' ? value : String(value ?? '');+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;+};- const perfDebugLog = (phase: string, label: string, details: Record<string, unknown> = {}) => {- if (!perfDebugEnabled) return;- const elapsedMs = Date.now() - perfDebugStart;- const payload = { phase, label, elapsedMs, ...details };- // eslint-disable-next-line no-console- console.error(`[perf] ${JSON.stringify(payload)}`);+const previewDebugValue = (value: unknown): string => {+ if (value == null) return '';+ if (typeof value === 'string') return truncateDebugText(value.replace(/\s+/g, ' ').trim());+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);+ if (Array.isArray(value)) return `array(${value.length})`;+ if (Predicate.isRecord(value)) {+ const preferred = ['message', 'error', 'title', 'summary', 'brief', 'status'];+ for (const key of preferred) {+ const candidate = value[key];+ if (typeof candidate === 'string' && candidate.trim().length > 0) {+ return truncateDebugText(candidate.trim());+ }+ }+ return `object{${Object.keys(value).slice(0, 4).join(', ')}}`;+ }+ return truncateDebugText(String(value));+};++const formatHelperDebugEvent = (step: string, details: Record<string, unknown> = {}) => {+ switch (step) {+ case 'subAgent.target':+ return `[experimental_subAgent] triggered with ${details.resolvedTarget}`;+ case 'subAgent.acp.resolve':+ return `[experimental_subAgent] ACP via ${details.source} (${details.target})`;+ case 'subAgent.acp.initialized':+ return `[experimental_subAgent] ACP initialized (${details.target})`;+ case 'subAgent.acp.session':+ return `[experimental_subAgent] session ready (${details.target})`;+ case 'subAgent.acp.model':+ return details.applied === true+ ? `[experimental_subAgent] model=${details.model}`+ : `[experimental_subAgent] model unchanged (${details.model})`;+ case 'subAgent.acp.message': {+ const text = previewDebugValue(details.text);+ return text ? `[experimental_subAgent] ${text}` : null;+ }+ case 'subAgent.acp.thought': {+ const text = previewDebugValue(details.text);+ return text ? `[experimental_subAgent:thinking] ${text}` : null;+ }+ case 'subAgent.acp.tool_call': {+ const locations = Array.isArray(details.locations) ? details.locations : [];+ const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';+ return `[experimental_subAgent:tool] ${details.status || 'pending'} ${+ details.title || details.kind || 'tool'+ }${where}`;+ }+ case 'subAgent.acp.tool_call_update': {+ const locations = Array.isArray(details.locations) ? details.locations : [];+ const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';+ const preview = previewDebugValue(details.rawOutput);+ return `[experimental_subAgent:tool] ${details.status || 'update'} ${+ details.title || details.toolCallId || details.kind || 'tool'+ }${where}${preview ? ` -> ${preview}` : ''}`;+ }+ case 'subAgent.acp.plan': {+ const entries = Array.isArray(details.entries)+ ? details.entries.filter(Predicate.isRecord)+ : [];+ if (entries.length === 0) return '[experimental_subAgent:plan] updated';+ const summary = entries+ .slice(0, 3)+ .map(entry => {+ const status = typeof entry.status === 'string' ? entry.status : 'pending';+ const content = typeof entry.content === 'string' ? entry.content : '';+ return `${status}:${truncateDebugText(content, 48)}`;+ })+ .join(' | ');+ return `[experimental_subAgent:plan] ${summary}`;+ }+ case 'subAgent.acp.fallback':+ return `[experimental_subAgent] ACP fallback (${details.code})`;+ case 'execute.prepare':+ return `[execute] ${details.slug}`;+ case 'search.prepare':+ return `[search] ${truncateDebugText(details.query || '', 96)}`;+ case 'proxy.request':+ return `[proxy] ${details.method} ${truncateDebugText(details.endpoint || '', 96)}`;+ case 'cli.result': {+ const command = typeof details.command === 'string' ? details.command : 'cli';+ const state = details.successful === false ? 'failed' : 'ok';+ const preview = previewDebugValue(details.preview);+ return `[${command}] ${state}${preview ? ` ${preview}` : ''}`;+ }+ case 'cli.error': {+ const command = typeof details.command === 'string' ? details.command : 'cli';+ const stderr = previewDebugValue(details.stderr);+ return `[${command}] failed${stderr ? ` ${stderr}` : ''}`;+ }+ default:+ return null;+ }+};++const stringifyForPrompt = (value: unknown): string => {+ if (value === undefined) return 'undefined';+ if (value === null) return 'null';+ if (typeof value === 'string') return value;+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {+ return String(value);+ }+ try {+ return JSON.stringify(value, null, 2);+ } catch {+ return String(value);+ }+};++const attachPromptMethod = <T>(value: T): T => {+ if (!Predicate.isRecord(value)) return value;+ if (typeof value.prompt === 'function') return value;+ Object.defineProperty(value, 'prompt', {+ value: () => stringifyForPrompt('data' in value ? value.data : value),+ enumerable: false,+ });+ return value;+};++const isPlainObjectForExecute = Predicate.isRecord;++const runFileExtensionFromMimeType = (mimeType: string | undefined): string => {+ if (typeof mimeType !== 'string' || mimeType.trim().length === 0) return 'bin';+ const normalized = mimeType.split(';')[0]?.trim().toLowerCase() ?? '';+ const explicit: Record<string, string> = {+ 'text/plain': 'txt',+ 'application/json': 'json',+ 'application/pdf': 'pdf',+ 'image/jpeg': 'jpg',+ 'image/png': 'png',+ 'image/webp': 'webp',+ 'image/gif': 'gif',};+ if (explicit[normalized]) return explicit[normalized];+ const subtype = normalized.split('/')[1] || 'bin';+ return subtype.includes('+') ? (subtype.split('+').pop() ?? 'bin') : subtype;+};- const truncateDebugText = (value: unknown, max = 240) => {- const text = typeof value === 'string' ? value : String(value ?? '');- return text.length > max ? `${text.slice(0, max - 1)}…` : text;+const describeDebugValue = (value: unknown) => {+ if (Array.isArray(value)) return { type: 'array', length: value.length };+ if (Predicate.isRecord(value)) {+ return { type: 'object', keys: Object.keys(value).slice(0, 20) };+ }+ return {+ type: typeof value,+ value: typeof value === 'string' ? value.slice(0, 200) : (value ?? null),};+};- const previewDebugValue = (value: unknown): string => {- if (value == null) return '';- if (typeof value === 'string') return truncateDebugText(value.replace(/\s+/g, ' ').trim());- if (typeof value === 'number' || typeof value === 'boolean') return String(value);- if (Array.isArray(value)) return `array(${value.length})`;- if (typeof value === 'object') {- const record = value as Record<string, unknown>;- const preferred = ['message', 'error', 'title', 'summary', 'brief', 'status'];- for (const key of preferred) {- if (typeof record[key] === 'string' && record[key].trim().length > 0) {- return truncateDebugText(record[key].trim());- }+const summarizeCliResultPreview = (result: RunCliResult): unknown => {+ if (!Predicate.isRecord(result)) return result;+ if ('data' in result && result.data !== undefined) return result.data;+ if (typeof result.error === 'string' && result.error.trim().length > 0)+ return result.error.trim();+ return result;+};++const readConfiguredExperimentalSubagentTarget = (): 'auto' | 'claude' | 'codex' => {+ try {+ const raw = fs.readFileSync(resolveCliConfigPathSync(), 'utf8');+ const parsed = decodeExperimentalSubagentConfig(raw);+ const target = parsed.experimental_subagent?.target;+ return target === 'claude' || target === 'codex' || target === 'auto' ? target : 'auto';+ } catch {+ return 'auto';+ }+};++const normalizeInvokeAgentOptions = (+ options: Record<string, unknown> = {}+): InvokeAgentNormalizedOptions => {+ if (options == null || typeof options !== 'object' || Array.isArray(options)) {+ throw new Error('experimental_subAgent() options must be an object when provided.');+ }+ if (options.schema !== undefined && options.jsonSchema !== undefined) {+ throw new Error(+ 'experimental_subAgent() accepts either options.schema or options.jsonSchema, not both.'+ );+ }+ const requestedTarget = options.target;+ if (+ requestedTarget !== undefined &&+ requestedTarget !== 'claude' &&+ requestedTarget !== 'codex' &&+ requestedTarget !== 'user'+ ) {+ throw new Error(+ 'experimental_subAgent() target must be "claude", "codex", or "user" when provided.'+ );+ }+ const inputSchema = options.schema ?? options.jsonSchema;+ let structuredSchema: Record<string, unknown> | undefined;+ let zodSchema: z.ZodType | undefined;+ if (inputSchema !== undefined) {+ if (inputSchema instanceof z.ZodType) {+ if (typeof z.toJSONSchema !== 'function') {+ throw new Error(+ 'experimental_subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.'+ );}- return `object{${Object.keys(record).slice(0, 4).join(', ')}}`;+ zodSchema = inputSchema;+ const generatedSchema = z.toJSONSchema(inputSchema);+ structuredSchema = Schema.decodeUnknownSync(JsonObject)(generatedSchema);+ } else if (Predicate.isRecord(inputSchema)) {+ structuredSchema = inputSchema;+ } else {+ throw new Error('experimental_subAgent() schema must be a Zod schema or JSON Schema object.');}- return truncateDebugText(String(value));+ }+ return {+ ...(requestedTarget === undefined ? {} : { target: requestedTarget }),+ ...(typeof options.model === 'string' ? { model: options.model } : {}),+ ...(options.schema === undefined ? {} : { schema: options.schema }),+ ...(options.jsonSchema === undefined ? {} : { jsonSchema: options.jsonSchema }),+ ...(structuredSchema === undefined ? {} : { structuredSchema }),+ ...(zodSchema === undefined ? {} : { zodSchema }),};+};- const formatHelperDebugEvent = (step: string, details: Record<string, unknown> = {}) => {- switch (step) {- case 'subAgent.target':- return `[experimental_subAgent] triggered with ${details.resolvedTarget}`;- case 'subAgent.acp.resolve':- return `[experimental_subAgent] ACP via ${details.source} (${details.target})`;- case 'subAgent.acp.initialized':- return `[experimental_subAgent] ACP initialized (${details.target})`;- case 'subAgent.acp.session':- return `[experimental_subAgent] session ready (${details.target})`;- case 'subAgent.acp.model':- return details.applied === true- ? `[experimental_subAgent] model=${details.model}`- : `[experimental_subAgent] model unchanged (${details.model})`;- case 'subAgent.acp.message': {- const text = previewDebugValue(details.text);- return text ? `[experimental_subAgent] ${text}` : null;- }- case 'subAgent.acp.thought': {- const text = previewDebugValue(details.text);- return text ? `[experimental_subAgent:thinking] ${text}` : null;- }- case 'subAgent.acp.tool_call': {- const locations = Array.isArray(details.locations) ? details.locations : [];- const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';- return `[experimental_subAgent:tool] ${details.status || 'pending'} ${- details.title || details.kind || 'tool'- }${where}`;- }- case 'subAgent.acp.tool_call_update': {- const locations = Array.isArray(details.locations) ? details.locations : [];- const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';- const preview = previewDebugValue(details.rawOutput);- return `[experimental_subAgent:tool] ${details.status || 'update'} ${- details.title || details.toolCallId || details.kind || 'tool'- }${where}${preview ? ` -> ${preview}` : ''}`;- }- case 'subAgent.acp.plan': {- const entries = Array.isArray(details.entries)- ? (details.entries as Array<{ status?: string; content?: string }>)- : [];- if (entries.length === 0) return '[experimental_subAgent:plan] updated';- const summary = entries- .slice(0, 3)- .map(entry => `${entry.status}:${truncateDebugText(entry.content || '', 48)}`)- .join(' | ');- return `[experimental_subAgent:plan] ${summary}`;- }- case 'subAgent.acp.fallback':- return `[experimental_subAgent] ACP fallback (${details.code})`;- case 'execute.prepare':- return `[execute] ${details.slug}`;- case 'search.prepare':- return `[search] ${truncateDebugText(details.query || '', 96)}`;- case 'proxy.request':- return `[proxy] ${details.method} ${truncateDebugText(details.endpoint || '', 96)}`;- case 'cli.result': {- const command = typeof details.command === 'string' ? details.command : 'cli';- const state = details.successful === false ? 'failed' : 'ok';- const preview = previewDebugValue(details.preview);- return `[${command}] ${state}${preview ? ` ${preview}` : ''}`;- }- case 'cli.error': {- const command = typeof details.command === 'string' ? details.command : 'cli';- const stderr = previewDebugValue(details.stderr);- return `[${command}] failed${stderr ? ` ${stderr}` : ''}`;- }- default:- return null;- }+const normalizeProxyToolkit = (toolkit: string) => {+ if (typeof toolkit !== 'string' || toolkit.trim().length === 0) {+ throw new Error('proxy() requires a non-empty toolkit string.');+ }+ return toolkit.trim();+};++const normalizeFetchHeaders = (headers: HeadersInit | undefined) => {+ if (!headers) return [];+ const normalized: Array<{ name: string; type: string; value: string }> = [];+ new Headers(headers).forEach((value, name) => {+ normalized.push({ name, type: 'header', value });+ });+ return normalized;+};++const normalizeFetchBody = async (body: unknown) => {+ if (body === undefined || body === null) return undefined;+ if (typeof body === 'string' || typeof body === 'number' || typeof body === 'boolean')+ return body;+ if (typeof Blob !== 'undefined' && body instanceof Blob) return await body.text();+ if (body instanceof ArrayBuffer) return encodeBase64(new Uint8Array(body));+ if (ArrayBuffer.isView(body)) {+ return encodeBase64(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));+ }+ return body;+};++const normalizeFetchInput = async (input: unknown, init: RequestInit = {}) => {+ if (typeof Request !== 'undefined' && input instanceof Request) {+ throw new Error(+ 'proxy() does not support passing a Request instance yet. Pass a URL string and init instead.'+ );+ }+ const endpoint = input instanceof URL ? input.toString() : input;+ if (typeof endpoint !== 'string' || endpoint.trim().length === 0) {+ throw new Error('proxy fetch requires a non-empty URL string or URL object.');+ }+ const method = typeof init.method === 'string' ? init.method.toUpperCase() : 'GET';+ if (!['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].includes(method)) {+ throw new Error('proxy fetch only supports GET, POST, PUT, DELETE, PATCH.');+ }+ return {+ endpoint: endpoint.trim(),+ method,+ parameters: normalizeFetchHeaders(init.headers),+ body: await normalizeFetchBody(init.body),+ };+};++const toProxyResponse = async (result: ProxyExecuteResponse) => {+ const headers = new Headers(result?.headers || {});+ if (result?.binary_data?.url) {+ const binaryResponse = await fetch(result.binary_data.url);+ binaryResponse.headers.forEach((value, key) => {+ if (!headers.has(key)) headers.set(key, value);+ });+ return new Response(binaryResponse.body, {+ status: result.status ?? binaryResponse.status,+ headers,+ });+ }+ if (result?.data === undefined || result?.data === null) {+ return new Response(null, { status: result?.status ?? 200, headers });+ }+ if (typeof result.data === 'string') {+ if (!headers.has('content-type')) headers.set('content-type', 'text/plain; charset=utf-8');+ return new Response(result.data, { status: result.status ?? 200, headers });+ }+ if (!headers.has('content-type')) headers.set('content-type', 'application/json; charset=utf-8');+ return new Response(JSON.stringify(result.data), { status: result.status ?? 200, headers });+};++// ---------------------------------------------------------------------------+// Helper factories — capture the per-run context passed by installRunHelpers+// ---------------------------------------------------------------------------++type RunHelperLoggers = {+ readonly perfDebugLog: (phase: string, label: string, details?: Record<string, unknown>) => void;+ readonly helperDebugLog: HelperDebugLog;+};++const createRunHelperLoggers = (params: {+ readonly helperContext: RunHelperContext;+ readonly writeError: (line: string) => void;+ readonly sharedRunLogFilePath: string | null;+ readonly perfDebugEnabled: boolean;+ readonly perfDebugStart: number;+}): RunHelperLoggers => {+ const { helperContext, writeError, sharedRunLogFilePath, perfDebugEnabled, perfDebugStart } =+ params;++ const appendRunLogLine = (line: string) => {+ if (!sharedRunLogFilePath || line.length === 0) return;+ fs.appendFileSync(sharedRunLogFilePath, `${line}\n`, 'utf8');+ };++ const perfDebugLog = (phase: string, label: string, details: Record<string, unknown> = {}) => {+ if (!perfDebugEnabled) return;+ const elapsedMs = Date.now() - perfDebugStart;+ const payload = { phase, label, elapsedMs, ...details };+ writeError(`[perf] ${JSON.stringify(payload)}`);};const shouldStreamHelperLog = (step: string, formattedLine: string | null): boolean => {@@ -320,71 +489,24 @@ export const installRunHelpers = async ({return formattedLine !== null && (step.startsWith('subAgent.') || step.startsWith('agent.'));};- const helperDebugLog = (step: string, details: Record<string, unknown> = {}) => {+ const helperDebugLog: HelperDebugLog = (step, details = {}) => {const formattedLine = formatHelperDebugEvent(step, details);const elapsedMs = Date.now() - perfDebugStart;const line = formattedLine ?? `[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`;appendRunLogLine(line);if (shouldStreamHelperLog(step, formattedLine)) {- // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)- process.stderr.write(`${line}\n`);- }- };-- const parseJson = (text: string): unknown => {- const value = text.trim();- if (!value) return undefined;- try {- return JSON.parse(value);- } catch {- return value;- }- };-- const stringifyForPrompt = (value: unknown): string => {- if (value === undefined) return 'undefined';- if (value === null) return 'null';- if (typeof value === 'string') return value;- if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {- return String(value);- }- try {- return JSON.stringify(value, null, 2);- } catch {- return String(value);+ writeError(line);}};- const attachPromptMethod = <T>(value: T): T => {- if (!value || typeof value !== 'object' || Array.isArray(value)) return value;- const promptable = value as PromptableResult;- if (typeof promptable.prompt === 'function') return value;- Object.defineProperty(promptable, 'prompt', {- value: () => stringifyForPrompt('data' in promptable ? promptable.data : promptable),- enumerable: false,- });- return value;- };+ return { perfDebugLog, helperDebugLog };+};- const isPlainObjectForExecute = (value: unknown): value is Record<string, unknown> =>- typeof value === 'object' && value !== null && !Array.isArray(value);-- const runFileExtensionFromMimeType = (mimeType: string | undefined): string => {- if (typeof mimeType !== 'string' || mimeType.trim().length === 0) return 'bin';- const normalized = mimeType.split(';')[0]?.trim().toLowerCase() ?? '';- const explicit: Record<string, string> = {- 'text/plain': 'txt',- 'application/json': 'json',- 'application/pdf': 'pdf',- 'image/jpeg': 'jpg',- 'image/png': 'png',- 'image/webp': 'webp',- 'image/gif': 'gif',- };- if (explicit[normalized]) return explicit[normalized];- const subtype = normalized.split('/')[1] || 'bin';- return subtype.includes('+') ? (subtype.split('+').pop() ?? 'bin') : subtype;- };+const createExecutePayloadMaterializer = (params: {+ readonly path: Path.Path;+ readonly sharedRunOutputDir: string | null;+}): ((value: unknown) => Promise<unknown>) => {+ const { path, sharedRunOutputDir } = params;const writeTempExecuteFile = async (value: unknown): Promise<unknown> => {const outputDir = sharedRunOutputDir || path.join(os.tmpdir(), 'composio-run-files');@@ -427,8 +549,24 @@ export const installRunHelpers = async ({return value;};+ return materializeExecutePayload;+};++const createCliRunner = (params: {+ readonly cliPrefix: ReadonlyArray<string>;+ readonly helperContext: RunHelperContext;+ readonly sharedRunOutputDir: string | null;+ readonly perfDebugEnabled: boolean;+ readonly toolDebugEnabled: boolean;+ readonly loggers: RunHelperLoggers;+}): ((args: ReadonlyArray<string>) => Promise<RunCliResult>) => {+ const { cliPrefix, helperContext, sharedRunOutputDir, perfDebugEnabled, toolDebugEnabled } =+ params;+ const { perfDebugLog, helperDebugLog } = params.loggers;+ let perfDebugSeq = 0;+const maybeLoadStoredCliResult = (result: RunCliResult): RunCliResult => {- if (!result || typeof result !== 'object' || result.storedInFile !== true) {+ if (!Predicate.isRecord(result) || result.storedInFile !== true) {return attachPromptMethod(result);}helperDebugLog('cli.result.stored_in_file', {@@ -445,31 +583,12 @@ export const installRunHelpers = async ({});};- const describeDebugValue = (value: unknown) => {- if (Array.isArray(value)) return { type: 'array', length: value.length };- if (value && typeof value === 'object') {- return { type: 'object', keys: Object.keys(value as Record<string, unknown>).slice(0, 20) };- }- return {- type: typeof value,- value: typeof value === 'string' ? value.slice(0, 200) : (value ?? null),- };- };-- const summarizeCliResultPreview = (result: RunCliResult): unknown => {- if (result == null || typeof result !== 'object') return result;- if ('data' in result && result.data !== undefined) return result.data;- if (typeof result.error === 'string' && result.error.trim().length > 0)- return result.error.trim();- return result;- };-const logCliResultPreview = (requestId: string,command: string | undefined,result: RunCliResult) => {- if (!result || typeof result !== 'object') {+ if (!Predicate.isRecord(result)) {helperDebugLog('cli.result', {requestId,command,@@ -491,211 +610,10 @@ export const installRunHelpers = async ({});};- const detectInvokeAgentMaster = (): MasterKind | 'user' => {- if (- helperContext.master === 'claude' ||- helperContext.master === 'codex' ||- helperContext.master === 'user'- ) {- return helperContext.master;- }- const envKeys = Object.keys(process.env || {});- if (envKeys.some(key => key.startsWith('CODEX_'))) return 'codex';- if (envKeys.some(key => key.startsWith('CLAUDE_'))) return 'claude';- return 'user';- };-- const readConfiguredExperimentalSubagentTarget = (): 'auto' | 'claude' | 'codex' => {- try {- const raw = fs.readFileSync(resolveCliConfigPathSync(), 'utf8');- const parsed = JSON.parse(raw) as {- experimental_subagent?: { target?: unknown };- };- const target = parsed.experimental_subagent?.target;- return target === 'claude' || target === 'codex' || target === 'auto' ? target : 'auto';- } catch {- return 'auto';- }- };-- const resolveInvokeAgentTarget = (requestedTarget?: string): 'claude' | 'codex' => {- if (requestedTarget === 'claude' || requestedTarget === 'codex') return requestedTarget;- const configuredTarget = readConfiguredExperimentalSubagentTarget();- if (configuredTarget === 'claude' || configuredTarget === 'codex') return configuredTarget;- const detected = requestedTarget === 'user' ? 'user' : detectInvokeAgentMaster();- if (detected === 'codex' || detected === 'claude') return detected;- if (typeof Bun.which === 'function' && Bun.which('codex')) return 'codex';- if (typeof Bun.which === 'function' && Bun.which('claude')) return 'claude';- throw new Error(- 'experimental_subAgent() could not determine an agent CLI. Current master is user; install codex or claude, or pass { target: "codex" | "claude" }.'- );- };-- const normalizeInvokeAgentOptions = (- options: Record<string, unknown> = {}- ): NormalizedInvokeAgentOptions => {- if (options == null || typeof options !== 'object' || Array.isArray(options)) {- throw new Error('experimental_subAgent() options must be an object when provided.');- }- if (options.schema !== undefined && options.jsonSchema !== undefined) {- throw new Error(- 'experimental_subAgent() accepts either options.schema or options.jsonSchema, not both.'- );- }- const inputSchema = (options.schema ?? options.jsonSchema) as StructuredSchemaInput | undefined;- let structuredSchema: Record<string, unknown> | undefined;- let zodSchema: StructuredSchemaInput | undefined;- if (inputSchema !== undefined) {- if (- typeof inputSchema === 'object' &&- inputSchema !== null &&- 'safeParse' in inputSchema &&- typeof inputSchema.safeParse === 'function' &&- '_def' in inputSchema- ) {- if (typeof z.toJSONSchema !== 'function') {- throw new Error(- 'experimental_subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.'- );- }- zodSchema = inputSchema;- structuredSchema = z.toJSONSchema(inputSchema as never) as Record<string, unknown>;- } else if (- typeof inputSchema === 'object' &&- inputSchema !== null &&- !Array.isArray(inputSchema)- ) {- structuredSchema = inputSchema;- } else {- throw new Error(- 'experimental_subAgent() schema must be a Zod schema or JSON Schema object.'- );- }- }- return { ...options, structuredSchema, zodSchema };- };-- const requireConsumerProxyContext = () => {- if (!helperContext.apiKey) {- throw new Error('proxy() requires an authenticated Composio user session.');- }- if (!helperContext.orgId || !helperContext.consumerProjectId || !helperContext.consumerUserId) {- throw new Error(- 'proxy() requires a consumer project context so it can use the consumer project credentials.'- );- }- return {- apiKey: helperContext.apiKey,- orgId: helperContext.orgId,- projectId: helperContext.consumerProjectId,- userId: helperContext.consumerUserId,- };- };-- const normalizeProxyToolkit = (toolkit: string) => {- if (typeof toolkit !== 'string' || toolkit.trim().length === 0) {- throw new Error('proxy() requires a non-empty toolkit string.');- }- return toolkit.trim();- };-- const normalizeFetchHeaders = (headers: HeadersInit | undefined) => {- if (!headers) return [];- return [...(new Headers(headers) as unknown as Iterable<[string, string]>)].map(- ([name, value]) => ({- name,- type: 'header',- value,- })- );- };-- const normalizeFetchBody = async (body: unknown) => {- if (body === undefined || body === null) return undefined;- if (typeof body === 'string' || typeof body === 'number' || typeof body === 'boolean')- return body;- if (typeof Blob !== 'undefined' && body instanceof Blob) return await body.text();- if (body instanceof ArrayBuffer) return encodeBase64(new Uint8Array(body));- if (ArrayBuffer.isView(body)) {- return encodeBase64(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));- }- return body;- };-- const normalizeFetchInput = async (input: unknown, init: RequestInit = {}) => {- if (typeof Request !== 'undefined' && input instanceof Request) {- throw new Error(- 'proxy() does not support passing a Request instance yet. Pass a URL string and init instead.'- );- }- const endpoint = input instanceof URL ? input.toString() : input;- if (typeof endpoint !== 'string' || endpoint.trim().length === 0) {- throw new Error('proxy fetch requires a non-empty URL string or URL object.');- }- const method = typeof init.method === 'string' ? init.method.toUpperCase() : 'GET';- if (!['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].includes(method)) {- throw new Error('proxy fetch only supports GET, POST, PUT, DELETE, PATCH.');- }- return {- endpoint: endpoint.trim(),- method,- parameters: normalizeFetchHeaders(init.headers),- body: await normalizeFetchBody(init.body),- };- };-- const fetchComposioJson = async (pathname: string, body: Record<string, unknown>) => {- const auth = requireConsumerProxyContext();- const response = await fetch(`${composioBaseURL}${pathname}`, {- method: 'POST',- headers: {- 'content-type': 'application/json',- 'x-user-api-key': auth.apiKey,- 'x-org-id': auth.orgId,- 'x-project-id': auth.projectId,- },- body: JSON.stringify(body),- });- const raw = await response.text();- const parsed = parseJson(raw);- if (!response.ok) {- const detail =- typeof parsed === 'string'- ? parsed- : (((parsed as { message?: string; error?: string } | undefined)?.message ||- (parsed as { message?: string; error?: string } | undefined)?.error ||- raw.trim()) ??- undefined);- const error = new Error(- `Composio proxy request failed with status ${response.status}${detail ? `: ${detail}` : ''}`- );- Object.assign(error, { status: response.status, response: parsed ?? raw });- throw error;- }- return parsed;- };-- const getProxySessionId = async (toolkit: string) => {- const cached = proxySessionCache.get(toolkit);- if (cached) return cached;- const auth = requireConsumerProxyContext();- const created = (await fetchComposioJson('/api/v3/tool_router/session', {- user_id: auth.userId,- manage_connections: { enable: false },- toolkits: { enable: [toolkit] },- })) as { session_id?: string };- const sessionId = created?.session_id;- if (typeof sessionId !== 'string' || sessionId.length === 0) {- throw new Error('Composio proxy session creation returned no session_id.');- }- proxySessionCache.set(toolkit, sessionId);- return sessionId;- };-const runCliJson = async (args: ReadonlyArray<string>): Promise<RunCliResult> => {const requestId = `${args[0] ?? 'cli'}#${++perfDebugSeq}`;helperDebugLog('cli.start', { requestId, args });- const env = {+ const env: Record<string, string | undefined> = {...process.env,...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),@@ -706,7 +624,7 @@ export const installRunHelpers = async ({...(perfDebugEnabled ? { COMPOSIO_PERF_DEBUG: '1' } : {}),...(toolDebugEnabled ? { COMPOSIO_TOOL_DEBUG: '1' } : {}),};- delete (env as Record<string, string | undefined>).BUN_BE_BUN;+ delete env.BUN_BE_BUN;perfDebugLog('start', requestId, { cmd: args });const child = Bun.spawn({cmd: [...cliPrefix, ...args],@@ -715,7 +633,7 @@ export const installRunHelpers = async ({});const stdout = child.stdout ? await new Response(child.stdout).text() : '';const stderr = child.stderr ? await new Response(child.stderr).text() : '';- const result = maybeLoadStoredCliResult(parseJson(stdout) as RunCliResult);+ const result = maybeLoadStoredCliResult(parseJson(stdout));const exitCode = await child.exited;if (exitCode !== 0) {perfDebugLog('error', requestId, { exitCode, stderr: stderr.trim() || undefined });@@ -754,7 +672,28 @@ export const installRunHelpers = async ({return result;};- runGlobals.search = async (query, options = {}) => {+ return runCliJson;+};++const createSearchAndExecuteHelpers = (params: {+ readonly helperContext: RunHelperContext;+ readonly sharedRunOutputDir: string | null;+ readonly runCliJson: (args: ReadonlyArray<string>) => Promise<RunCliResult>;+ readonly materializeExecutePayload: (value: unknown) => Promise<unknown>;+ readonly helperDebugLog: HelperDebugLog;+}) => {+ const {+ helperContext,+ sharedRunOutputDir,+ runCliJson,+ materializeExecutePayload,+ helperDebugLog,+ } = params;++ const search = async (+ query: string,+ options: Record<string, unknown> = {}+ ): Promise<RunCliResult> => {helperDebugLog('search.prepare', { query, options });const args = ['search', query];if (Array.isArray(options.toolkits) && options.toolkits.length > 0) {@@ -768,7 +707,11 @@ export const installRunHelpers = async ({return runCliJson(args);};- runGlobals.execute = async (slug, data = {}, options = {}) => {+ const execute = async (+ slug: string,+ data: unknown = {},+ options: { account?: string } = {}+ ): Promise<RunCliResult> => {helperDebugLog('execute.prepare', {slug,hasData: data !== undefined,@@ -795,7 +738,7 @@ export const installRunHelpers = async ({}}const result = await runCliJson(args);- if (result && typeof result === 'object' && result.successful === false) {+ if (Predicate.isRecord(result) && result.successful === false) {const message =typeof result.error === 'string' && result.error.trim().length > 0? result.error.trim()@@ -807,6 +750,39 @@ export const installRunHelpers = async ({return result;};+ return { search, execute };+};++const createExperimentalSubAgent = (params: {+ readonly helperContext: RunHelperContext;+ readonly helperDebugLog: HelperDebugLog;+}) => {+ const { helperContext, helperDebugLog } = params;++ const detectInvokeAgentMaster = (): MasterKind | 'user' => {+ if (+ helperContext.master === 'claude' ||+ helperContext.master === 'codex' ||+ helperContext.master === 'user'+ ) {+ return helperContext.master;+ }+ return detectMaster();+ };++ const resolveInvokeAgentTarget = (requestedTarget?: string): 'claude' | 'codex' => {+ if (requestedTarget === 'claude' || requestedTarget === 'codex') return requestedTarget;+ const configuredTarget = readConfiguredExperimentalSubagentTarget();+ if (configuredTarget === 'claude' || configuredTarget === 'codex') return configuredTarget;+ const detected = requestedTarget === 'user' ? 'user' : detectInvokeAgentMaster();+ if (detected === 'codex' || detected === 'claude') return detected;+ if (typeof Bun.which === 'function' && Bun.which('codex')) return 'codex';+ if (typeof Bun.which === 'function' && Bun.which('claude')) return 'claude';+ throw new Error(+ 'experimental_subAgent() could not determine an agent CLI. Current master is user; install codex or claude, or pass { target: "codex" | "claude" }.'+ );+ };+const experimentalSubAgentImpl = async (prompt: string,options: Record<string, unknown> = {}@@ -829,8 +805,7 @@ export const installRunHelpers = async ({try {const response = await invokeAcpSubAgent({prompt: prompt.trim(),- options:- normalizedOptions as import('src/services/run-subagent-shared').InvokeAgentNormalizedOptions,+ options: normalizedOptions,master,target,allowedReadRoots: Array.isArray(helperContext.readAccessRoots)@@ -849,8 +824,7 @@ export const installRunHelpers = async ({});const response = await invokeLegacySubAgent({prompt: prompt.trim(),- options:- normalizedOptions as import('src/services/run-subagent-shared').InvokeAgentNormalizedOptions,+ options: normalizedOptions,master,target,helperDebugLog,@@ -859,43 +833,86 @@ export const installRunHelpers = async ({}};- runGlobals.experimental_subAgent = experimentalSubAgentImpl;- Object.defineProperty(runGlobals.experimental_subAgent, 'schema', {- value: experimentalSubAgentSchema,- });- runGlobals.invokeAgent = experimentalSubAgentImpl;- Object.defineProperty(runGlobals.invokeAgent, 'schema', { value: experimentalSubAgentSchema });-- const toProxyResponse = async (result: {- readonly headers?: Record<string, string>;- readonly binary_data?: { readonly url?: string };- readonly data?: unknown;- readonly status?: number;- }) => {- const headers = new Headers(result?.headers || {});- if (result?.binary_data?.url) {- const binaryResponse = await fetch(result.binary_data.url);- binaryResponse.headers.forEach((value, key) => {- if (!headers.has(key)) headers.set(key, value);- });- return new Response(binaryResponse.body, {- status: result.status ?? binaryResponse.status,- headers,- });+ Object.defineProperty(experimentalSubAgentImpl, 'schema', { value: experimentalSubAgentSchema });+ return experimentalSubAgentImpl;+};++const createProxyHelper = (params: {+ readonly helperContext: RunHelperContext;+ readonly composioBaseURL: string;+ readonly helperDebugLog: HelperDebugLog;+}) => {+ const { helperContext, composioBaseURL, helperDebugLog } = params;+ const proxySessionCache = new Map<string, string>();++ const requireConsumerProxyContext = () => {+ if (!helperContext.apiKey) {+ throw new Error('proxy() requires an authenticated Composio user session.');}- if (result?.data === undefined || result?.data === null) {- return new Response(null, { status: result?.status ?? 200, headers });+ if (!helperContext.orgId || !helperContext.consumerProjectId || !helperContext.consumerUserId) {+ throw new Error(+ 'proxy() requires a consumer project context so it can use the consumer project credentials.'+ );}- if (typeof result.data === 'string') {- if (!headers.has('content-type')) headers.set('content-type', 'text/plain; charset=utf-8');- return new Response(result.data, { status: result.status ?? 200, headers });+ return {+ apiKey: helperContext.apiKey,+ orgId: helperContext.orgId,+ projectId: helperContext.consumerProjectId,+ userId: helperContext.consumerUserId,+ };+ };++ const fetchComposioJson = async (pathname: string, body: Record<string, unknown>) => {+ const auth = requireConsumerProxyContext();+ const response = await fetch(`${composioBaseURL}${pathname}`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'x-user-api-key': auth.apiKey,+ 'x-org-id': auth.orgId,+ 'x-project-id': auth.projectId,+ },+ body: JSON.stringify(body),+ });+ const raw = await response.text();+ const parsed = parseJson(raw);+ if (!response.ok) {+ const responseMessage = Predicate.isRecord(parsed) ? parsed.message : undefined;+ const responseError = Predicate.isRecord(parsed) ? parsed.error : undefined;+ const detail =+ typeof parsed === 'string'+ ? parsed+ : typeof responseMessage === 'string'+ ? responseMessage+ : typeof responseError === 'string'+ ? responseError+ : raw.trim() || undefined;+ const error = new Error(+ `Composio proxy request failed with status ${response.status}${detail ? `: ${detail}` : ''}`+ );+ Object.assign(error, { status: response.status, response: parsed ?? raw });+ throw error;}- if (!headers.has('content-type'))- headers.set('content-type', 'application/json; charset=utf-8');- return new Response(JSON.stringify(result.data), { status: result.status ?? 200, headers });+ return parsed;+ };++ const getProxySessionId = async (toolkit: string) => {+ const cached = proxySessionCache.get(toolkit);+ if (cached) return cached;+ const auth = requireConsumerProxyContext();+ const created = await Schema.decodeUnknownPromise(ProxySessionResponse)(+ await fetchComposioJson('/api/v3/tool_router/session', {+ user_id: auth.userId,+ manage_connections: { enable: false },+ toolkits: { enable: [toolkit] },+ })+ );+ const sessionId = created.session_id;+ proxySessionCache.set(toolkit, sessionId);+ return sessionId;};- runGlobals.proxy = async (toolkit: string) => {+ const proxy = async (toolkit: string) => {const normalizedToolkit = normalizeProxyToolkit(toolkit);helperDebugLog('proxy.session', {toolkit: normalizedToolkit,@@ -909,39 +926,104 @@ export const installRunHelpers = async ({method: request.method,endpoint: request.endpoint,});- const result = (await fetchComposioJson(- `/api/v3/tool_router/session/${sessionId}/proxy_execute`,- {+ const result = await Schema.decodeUnknownPromise(ProxyExecuteResponse)(+ await fetchComposioJson(`/api/v3/tool_router/session/${sessionId}/proxy_execute`, {toolkit_slug: normalizedToolkit,endpoint: request.endpoint,method: request.method,...(request.body !== undefined ? { body: request.body } : {}),...(request.parameters.length > 0? {- parameters: request.parameters.map(- (parameter: { name: string; type: string; value: string }) => ({- name: parameter.name,- type: parameter.type,- value: String(parameter.value),- })- ),+ parameters: request.parameters.map(parameter => ({+ name: parameter.name,+ type: parameter.type,+ value: String(parameter.value),+ })),}: {}),- }- )) as {- readonly headers?: Record<string, string>;- readonly binary_data?: { readonly url?: string };- readonly data?: unknown;- readonly status?: number;- };+ })+ );return toProxyResponse(result);};Object.defineProperty(proxyFetch, 'toolkit', { value: normalizedToolkit });return proxyFetch;};- Object.defineProperty(runGlobals.proxy, 'schema', { value: proxySchema });- Object.defineProperty(runGlobals, '__composioRunContext', {+ Object.defineProperty(proxy, 'schema', { value: proxySchema });+ return proxy;+};++export const installRunHelpers = async ({+ cliPrefix,+ helperContext = {},+}: RunHelpersInstallParams): Promise<void> => {+ // This preload runs in the user's child process, outside the CLI runtime.+ // Resolve the live services once at that boundary and keep all writes centralized.+ const terminal = Effect.runSync(TerminalUI.pipe(Effect.provide(TerminalUILive)));+ const path = Effect.runSync(Path.Path.pipe(Effect.provide(Path.layer)));+ const writeError = (line: string) => Effect.runSync(terminal.error(line));++ Reflect.set(globalThis, 'z', z);+ Reflect.set(globalThis, 'zod', z);++ const perfDebugEnabled =+ helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === '1';+ const toolDebugEnabled =+ helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === '1';+ const perfDebugStart = Date.now();+ const composioBaseURL = (helperContext.baseURL || 'https://backend.composio.dev').replace(+ /\/$/,+ ''+ );+ const sharedRunOutputDir =+ typeof helperContext.runOutputDir === 'string' && helperContext.runOutputDir.length > 0+ ? helperContext.runOutputDir+ : null;+ const sharedRunLogFilePath =+ typeof helperContext.runLogFilePath === 'string' && helperContext.runLogFilePath.length > 0+ ? helperContext.runLogFilePath+ : null;++ const loggers = createRunHelperLoggers({+ helperContext,+ writeError,+ sharedRunLogFilePath,+ perfDebugEnabled,+ perfDebugStart,+ });+ const { helperDebugLog } = loggers;++ const materializeExecutePayload = createExecutePayloadMaterializer({+ path,+ sharedRunOutputDir,+ });+ const runCliJson = createCliRunner({+ cliPrefix,+ helperContext,+ sharedRunOutputDir,+ perfDebugEnabled,+ toolDebugEnabled,+ loggers,+ });+ const { search, execute } = createSearchAndExecuteHelpers({+ helperContext,+ sharedRunOutputDir,+ runCliJson,+ materializeExecutePayload,+ helperDebugLog,+ });++ const experimentalSubAgentImpl = createExperimentalSubAgent({ helperContext, helperDebugLog });+ Reflect.set(globalThis, 'experimental_subAgent', experimentalSubAgentImpl);+ Reflect.set(globalThis, 'invokeAgent', experimentalSubAgentImpl);++ const proxy = createProxyHelper({ helperContext, composioBaseURL, helperDebugLog });++ Reflect.set(globalThis, 'search', search);+ Reflect.set(globalThis, 'execute', execute);+ Reflect.set(globalThis, 'proxy', proxy);++ Object.defineProperty(globalThis, '__composioRunContext', {value: Object.freeze({outputDir: sharedRunOutputDir,logFilePath: sharedRunLogFilePath,@@ -949,7 +1031,7 @@ export const installRunHelpers = async ({configurable: true,});- Object.defineProperty(runGlobals, '__composioConsumerContext', {+ Object.defineProperty(globalThis, '__composioConsumerContext', {value: helperContext,configurable: true,});diff --git a/ts/packages/cli/src/services/run-subagent-acp.ts b/ts/packages/cli/src/services/run-subagent-acp.tsindex 4f3df36f4..c0686c8aa 100644--- a/ts/packages/cli/src/services/run-subagent-acp.ts+++ b/ts/packages/cli/src/services/run-subagent-acp.ts@@ -1,18 +1,14 @@-// 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 type { Readable } from 'node:stream';import * as acp from '@agentclientprotocol/sdk';+import { Command, FileSystem, Path } from '@effect/platform';+import { BunContext } from '@effect/platform-bun';+import { Cause, Config, Effect, Exit, Layer, Option, Predicate, Queue, Stream } from 'effect';import type { MasterKind } from 'src/services/master-detector';+import { NodeOs } from 'src/services/node-os';import {- resolveRunCompanionAssetPathSync,- resolveRunCompanionModulePathSync,+ resolveRunCompanionAssetPath,+ resolveRunCompanionModulePath,RUN_CODEX_ACP_BINARY_TARGETS,} from 'src/services/run-companion-modules';import {@@ -38,9 +34,82 @@ type LegacySetSessionModelConnection = {}) => Promise<unknown>;};-const resolveShippedAdapterAsset = (target: InvokeAgentTarget): string | null => {+type AcpAdapterCommand = {+ readonly cmd: readonly [string, ...ReadonlyArray<string>];+ readonly env?: Readonly<Record<string, string>>;+ readonly source: 'shipped' | 'bundled' | 'which' | 'npx';+};++// This module is bundled as a standalone `composio run` companion module, so it+// provides its own platform layers instead of assuming the CLI runtime.+const RunSubAgentAcpLive = Layer.mergeAll(BunContext.layer, NodeOs.Default);++const getLegacySetSessionModel = (+ connection: unknown+): LegacySetSessionModelConnection['unstable_setSessionModel'] => {+ if (!Predicate.hasProperty(connection, 'unstable_setSessionModel')) {+ return undefined;+ }+ const method = connection.unstable_setSessionModel;+ return Predicate.isFunction(method) ? async params => method.call(connection, params) : undefined;+};++export const readableStreamFromNode = (input: Readable): ReadableStream<Uint8Array> => {+ let cleanup = () => undefined;++ return new ReadableStream<Uint8Array>({+ start: controller => {+ const onData = (chunk: Buffer | string) => {+ controller.enqueue(+ typeof chunk === 'string' ? new TextEncoder().encode(chunk) : Uint8Array.from(chunk)+ );+ if ((controller.desiredSize ?? 1) <= 0) {+ input.pause();+ }+ };+ const onEnd = () => {+ cleanup();+ controller.close();+ };+ const onError = (error: Error) => {+ cleanup();+ controller.error(error);+ };+ cleanup = () => {+ input.off('data', onData);+ input.off('end', onEnd);+ input.off('error', onError);+ };+ input.on('data', onData);+ input.once('end', onEnd);+ input.once('error', onError);+ },+ pull: () => {+ input.resume();+ },+ cancel: reason => {+ cleanup();+ input.destroy(reason instanceof Error ? reason : undefined);+ },+ });+};++// Bridges the ACP connection's outgoing ndjson writes into an Effect Queue that+// a forked fiber drains into the child's stdin Sink. A bounded queue keeps the+// child's stdin backpressure visible to the ACP writer, and shutting the queue+// down on close/abort ends the stdin stream (EOF) for the child.+const writableStreamFromQueue = (queue: Queue.Queue<Uint8Array>): WritableStream<Uint8Array> =>+ new WritableStream<Uint8Array>({+ write: chunk => Effect.runPromise(Effect.asVoid(Queue.offer(queue, chunk))),+ close: () => Effect.runPromise(Queue.shutdown(queue)),+ abort: () => Effect.runPromise(Queue.shutdown(queue)),+ });++const resolveShippedAdapterAsset = (+ target: InvokeAgentTarget+): Effect.Effect<string | null, never, FileSystem.FileSystem | Path.Path> => {if (target === 'claude') {- return resolveRunCompanionAssetPathSync({+ return resolveRunCompanionAssetPath({callerImportMetaUrl: import.meta.url,execPath: process.execPath,relativePathFromRoot: 'acp-adapters/claude-code-acp.mjs',@@ -51,10 +120,10 @@ const resolveShippedAdapterAsset = (target: InvokeAgentTarget): string | null =>candidate => candidate.platform === process.platform && candidate.arch === process.arch);if (!binaryTarget) {- return null;+ return Effect.succeed(null);}- return resolveRunCompanionAssetPathSync({+ return resolveRunCompanionAssetPath({callerImportMetaUrl: import.meta.url,execPath: process.execPath,relativePathFromRoot: binaryTarget.relativePath,@@ -66,82 +135,81 @@ const resolveInstalledAdapter = (target: InvokeAgentTarget): string | null => {target === 'claude'? '@zed-industries/claude-code-acp/dist/index.js': '@zed-industries/codex-acp/bin/codex-acp.js';- try {- const require = createRequire(import.meta.url);- return require.resolve(specifier);- } catch {- return null;- }+ const require = createRequire(import.meta.url);+ return Option.getOrNull(Option.liftThrowable(() => require.resolve(specifier))());};export const resolveAcpAdapterCommand = (target: InvokeAgentTarget-): {- readonly cmd: ReadonlyArray<string>;- readonly env?: Readonly<Record<string, string>>;- readonly source: 'shipped' | 'bundled' | 'which' | 'npx';-} => {- const binary = target === 'claude' ? 'claude-code-acp' : 'codex-acp';- const packageName =- target === 'claude' ? '@zed-industries/claude-code-acp' : '@zed-industries/codex-acp';-- // 1. Prefer shipped companion assets next to the CLI binary / dist bundle.- const shipped = resolveShippedAdapterAsset(target);- if (shipped) {- if (target === 'codex') {+): Effect.Effect<AcpAdapterCommand, never, FileSystem.FileSystem | Path.Path> =>+ Effect.gen(function* () {+ const binary = target === 'claude' ? 'claude-code-acp' : 'codex-acp';+ const packageName =+ target === 'claude' ? '@zed-industries/claude-code-acp' : '@zed-industries/codex-acp';++ // 1. Prefer shipped companion assets next to the CLI binary / dist bundle.+ const shipped = yield* resolveShippedAdapterAsset(target);+ if (shipped) {+ if (target === 'codex') {+ return {+ cmd: [shipped],+ source: 'shipped',+ } satisfies AcpAdapterCommand;+ }+return {- cmd: [shipped],+ cmd: [process.execPath, shipped],+ env: {+ BUN_BE_BUN: '1',+ },source: 'shipped',- };+ } satisfies AcpAdapterCommand;}- return {- cmd: [process.execPath, shipped],- env: {- BUN_BE_BUN: '1',- },- source: 'shipped',- };- }-- // 2. Try the installed dependency bundle next (no npx overhead).- const bundled = resolveInstalledAdapter(target);- if (bundled) {- return {- cmd: [process.execPath, bundled],- env: {- BUN_BE_BUN: '1',- },- source: 'bundled',- };- }-- // 3. Check if the binary is on PATH.- if (typeof Bun !== 'undefined' && typeof Bun.which === 'function') {- const resolved = Bun.which(binary);- if (resolved) {+ // 2. Try the installed dependency bundle next (no npx overhead).+ const bundled = resolveInstalledAdapter(target);+ if (bundled) {return {- cmd: [resolved],- source: 'which',- };+ cmd: [process.execPath, bundled],+ env: {+ BUN_BE_BUN: '1',+ },+ source: 'bundled',+ } satisfies AcpAdapterCommand;}- }- // 4. Fall back to npx.- return {- cmd: [process.platform === 'win32' ? 'npx.cmd' : 'npx', '-y', packageName],- source: 'npx',- };-};+ // 3. Check if the binary is on PATH.+ if (typeof Bun !== 'undefined' && typeof Bun.which === 'function') {+ const resolved = Bun.which(binary);+ if (resolved) {+ return {+ cmd: [resolved],+ source: 'which',+ } satisfies AcpAdapterCommand;+ }+ }++ // 4. Fall back to npx.+ return {+ cmd: [process.platform === 'win32' ? 'npx.cmd' : 'npx', '-y', packageName],+ source: 'npx',+ } satisfies AcpAdapterCommand;+ });const chunkFlushPattern = /[\s,.;:!?)\]}"]$/;-const structuredOutputMcpModulePath = resolveRunCompanionModulePathSync({+const resolveStructuredOutputMcpModulePath = resolveRunCompanionModulePath({callerImportMetaUrl: import.meta.url,execPath: process.execPath,relativeNoExtensionFromCaller: './run-subagent-output-mcp',});-const collectToolCallPaths = (value: unknown, results: Set<string>, parentKey?: string): void => {+const collectToolCallPaths = (+ value: unknown,+ results: Set<string>,+ pathApi: Path.Path,+ homedir: string,+ parentKey?: string+): void => {if (typeof value === 'string') {const key = parentKey?.toLowerCase() ?? '';if (@@ -153,7 +221,7 @@ const collectToolCallPaths = (value: unknown, results: Set<string>, parentKey?:) {results.add(value);} else if (key === 'command' || key === 'cmd') {- for (const candidatePath of extractPathsFromCommandText(value)) {+ for (const candidatePath of extractPathsFromCommandText(value, pathApi, homedir)) {results.add(candidatePath);}}@@ -177,7 +245,7 @@ const collectToolCallPaths = (value: unknown, results: Set<string>, parentKey?:}for (const entry of value) {- collectToolCallPaths(entry, results);+ collectToolCallPaths(entry, results, pathApi, homedir);}return;}@@ -187,11 +255,15 @@ const collectToolCallPaths = (value: unknown, results: Set<string>, parentKey?:}for (const [key, nestedValue] of Object.entries(value)) {- collectToolCallPaths(nestedValue, results, key);+ collectToolCallPaths(nestedValue, results, pathApi, homedir, key);}};-const extractPathsFromCommandText = (command: string): ReadonlyArray<string> => {+const extractPathsFromCommandText = (+ command: string,+ pathApi: Path.Path,+ homedir: string+): ReadonlyArray<string> => {const results = new Set<string>();const matches = command.matchAll(/(^|[\s"'`])((?:~\/|\/)[^\s"'`|&;<>]+)/g);for (const match of matches) {@@ -200,14 +272,16 @@ const extractPathsFromCommandText = (command: string): ReadonlyArray<string> =>continue;}- results.add(rawPath.startsWith('~/') ? path.join(os.homedir(), rawPath.slice(2)) : rawPath);+ results.add(rawPath.startsWith('~/') ? pathApi.join(homedir, rawPath.slice(2)) : rawPath);}return [...results];};const extractToolCallPaths = (- toolCall: Pick<acp.RequestPermissionRequest, 'toolCall'>['toolCall']+ toolCall: Pick<acp.RequestPermissionRequest, 'toolCall'>['toolCall'],+ pathApi: Path.Path,+ homedir: string): ReadonlyArray<string> => {const paths = new Set<string>();for (const location of toolCall.locations ?? []) {@@ -216,9 +290,9 @@ const extractToolCallPaths = (}}- collectToolCallPaths(toolCall.rawInput, paths);+ collectToolCallPaths(toolCall.rawInput, paths, pathApi, homedir);if (typeof toolCall.title === 'string') {- for (const candidatePath of extractPathsFromCommandText(toolCall.title)) {+ for (const candidatePath of extractPathsFromCommandText(toolCall.title, pathApi, homedir)) {paths.add(candidatePath);}}@@ -325,7 +399,9 @@ class RunSubAgentClient {constructor(private readonly helperDebugLog: HelperDebugLog,- private readonly allowedReadRoots: ReadonlyArray<string>+ private readonly allowedReadRoots: ReadonlyArray<string>,+ private readonly pathApi: Path.Path,+ private readonly homedir: string) {this.messageLogger = new BufferedChunkLogger('subAgent.acp.message', helperDebugLog);this.thoughtLogger = new BufferedChunkLogger('subAgent.acp.thought', helperDebugLog);@@ -334,7 +410,7 @@ class RunSubAgentClient {async requestPermission(params: acp.RequestPermissionRequest): Promise<acp.RequestPermissionResponse> {- const requestedPaths = extractToolCallPaths(params.toolCall);+ const requestedPaths = extractToolCallPaths(params.toolCall, this.pathApi, this.homedir);const decision = selectPermissionOutcome(params, this.allowedReadRoots);this.helperDebugLog('subAgent.acp.permission', {toolCallId: params.toolCall.toolCallId,@@ -417,7 +493,7 @@ const createFallbackError = (type StructuredOutputMcpContext = {readonly mcpServer: acp.McpServerStdio;readonly resultFilePath: string;- readonly cleanup: () => void;+ readonly cleanup: Effect.Effect<void>;};export const createStructuredOutputMcpContext = ({@@ -426,63 +502,79 @@ export const createStructuredOutputMcpContext = ({}: {options: InvokeAgentNormalizedOptions;helperDebugLog: HelperDebugLog;-}): StructuredOutputMcpContext | null => {- if (!options.structuredSchema) {- return null;- }+}): Effect.Effect<StructuredOutputMcpContext | null, never, FileSystem.FileSystem | Path.Path> =>+ Effect.gen(function* () {+ const structuredSchema = options.structuredSchema;+ if (!structuredSchema) {+ return null;+ }- let tempDirectory: string | null = null;- try {- // Keep this on an OS temp dir for now. Repointing MCP schema/result files into- // session artifacts needs a broader bundling + run-companion test pass so we- // don't break structured sub-agent output in packaged CLI builds.- tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-subagent-output-mcp-'));- const schemaFilePath = path.join(tempDirectory, 'schema.json');- const resultFilePath = path.join(tempDirectory, 'result.json');- fs.writeFileSync(schemaFilePath, JSON.stringify(options.structuredSchema), 'utf8');-- helperDebugLog('subAgent.acp.structured_output_tool', {- modulePath: structuredOutputMcpModulePath,- schemaFilePath,- resultFilePath,- });+ const fs = yield* FileSystem.FileSystem;+ const pathApi = yield* Path.Path;+ const structuredOutputMcpModulePath = yield* resolveStructuredOutputMcpModulePath;- return {- mcpServer: {- name: 'composio-structured-output',- command: process.execPath,- args: [- structuredOutputMcpModulePath,- '--schema-file',- schemaFilePath,- '--result-file',- resultFilePath,- ],- env: [- {- name: 'BUN_BE_BUN',- value: '1',- },- ],- },- resultFilePath,- cleanup: () => {- if (tempDirectory) {- fs.rmSync(tempDirectory, { recursive: true, force: true });- }- },- };- } catch (error) {- if (tempDirectory) {- fs.rmSync(tempDirectory, { recursive: true, force: true });- }- helperDebugLog('subAgent.acp.structured_output_tool_failed', {- error: error instanceof Error ? error.message : String(error),- modulePath: structuredOutputMcpModulePath,+ const build = Effect.gen(function* () {+ // Keep this on an OS temp dir for now. Repointing MCP schema/result files into+ // session artifacts needs a broader bundling + run-companion test pass so we+ // don't break structured sub-agent output in packaged CLI builds.+ const tempDirectory = yield* fs.makeTempDirectory({+ prefix: 'composio-subagent-output-mcp-',+ });+ const removeTempDirectory = Effect.ignore(+ fs.remove(tempDirectory, { recursive: true, force: true })+ );+ const schemaFilePath = pathApi.join(tempDirectory, 'schema.json');+ const resultFilePath = pathApi.join(tempDirectory, 'result.json');+ yield* Effect.try({+ try: () => JSON.stringify(structuredSchema),+ catch: error => error,+ }).pipe(+ Effect.flatMap(schemaJson => fs.writeFileString(schemaFilePath, schemaJson)),+ Effect.tapError(() => removeTempDirectory)+ );++ helperDebugLog('subAgent.acp.structured_output_tool', {+ modulePath: structuredOutputMcpModulePath,+ schemaFilePath,+ resultFilePath,+ });++ const context: StructuredOutputMcpContext = {+ mcpServer: {+ name: 'composio-structured-output',+ command: process.execPath,+ args: [+ structuredOutputMcpModulePath,+ '--schema-file',+ schemaFilePath,+ '--result-file',+ resultFilePath,+ ],+ env: [+ {+ name: 'BUN_BE_BUN',+ value: '1',+ },+ ],+ },+ resultFilePath,+ cleanup: removeTempDirectory,+ };+ return context;});- return null;- }-};++ return yield* build.pipe(+ Effect.catchAll(error =>+ Effect.sync(() => {+ helperDebugLog('subAgent.acp.structured_output_tool_failed', {+ error: error instanceof Error ? error.message : String(error),+ modulePath: structuredOutputMcpModulePath,+ });+ return null;+ })+ )+ );+ });const maybeReadStructuredOutputFromTool = ({context,@@ -492,124 +584,258 @@ const maybeReadStructuredOutputFromTool = ({context: StructuredOutputMcpContext | null;options: InvokeAgentNormalizedOptions;helperDebugLog: HelperDebugLog;-}): unknown | undefined => {- if (!context || !options.structuredSchema || !fs.existsSync(context.resultFilePath)) {- return undefined;- }+}): Effect.Effect<unknown, never, FileSystem.FileSystem> =>+ Effect.gen(function* () {+ const structuredSchema = options.structuredSchema;+ if (!context || !structuredSchema) {+ return undefined;+ }- try {- const rawPayload = JSON.parse(fs.readFileSync(context.resultFilePath, 'utf8')) as unknown;- const parsed = unwrapStructuredOutputToolPayload(rawPayload, options.structuredSchema);- helperDebugLog('subAgent.acp.structured_output_tool_result', {- resultFilePath: context.resultFilePath,- });- return validateStructuredOutput(parsed, options);- } catch (error) {- helperDebugLog('subAgent.acp.structured_output_tool_result_failed', {- resultFilePath: context.resultFilePath,- error: error instanceof Error ? error.message : String(error),- });- return undefined;- }+ const fs = yield* FileSystem.FileSystem;+ const resultFileExists = yield* fs+ .exists(context.resultFilePath)+ .pipe(Effect.orElseSucceed(() => false));+ if (!resultFileExists) {+ return undefined;+ }++ const read = fs.readFileString(context.resultFilePath).pipe(+ Effect.flatMap(rawText =>+ Effect.try({+ try: () => {+ const rawPayload: unknown = JSON.parse(rawText);+ const parsed = unwrapStructuredOutputToolPayload(rawPayload, structuredSchema);+ helperDebugLog('subAgent.acp.structured_output_tool_result', {+ resultFilePath: context.resultFilePath,+ });+ return validateStructuredOutput(parsed, options);+ },+ catch: error => error,+ })+ )+ );++ return yield* read.pipe(+ Effect.catchAll(error =>+ Effect.sync<unknown>(() => {+ helperDebugLog('subAgent.acp.structured_output_tool_result_failed', {+ resultFilePath: context.resultFilePath,+ error: error instanceof Error ? error.message : String(error),+ });+ return undefined;+ })+ )+ );+ });++type InvokeAcpSubAgentParams = {+ prompt: string;+ options: InvokeAgentNormalizedOptions;+ master: MasterKind;+ target: InvokeAgentTarget;+ allowedReadRoots: ReadonlyArray<string>;+ helperDebugLog: HelperDebugLog;};-export const invokeAcpSubAgent = async ({- prompt,+// Turns the accumulated agent text into the final response, retrying once with+// a structured-repair prompt when a structured schema was requested and the+// first finalize attempt failed. Non-structured failures propagate unchanged.+const finalizeWithStructuredRepair = ({+ client,options,master,target,- allowedReadRoots,+ structuredOutputMcp,helperDebugLog,+ runPrompt,+ stderrSuffix,}: {- prompt: string;+ client: RunSubAgentClient;options: InvokeAgentNormalizedOptions;master: MasterKind;target: InvokeAgentTarget;- allowedReadRoots: ReadonlyArray<string>;+ structuredOutputMcp: StructuredOutputMcpContext | null;helperDebugLog: HelperDebugLog;-}): Promise<InvokeAgentResponse> => {- const structuredOutputMcp = createStructuredOutputMcpContext({- options,- helperDebugLog,- });- const resolved = resolveAcpAdapterCommand(target);- helperDebugLog('subAgent.acp.resolve', {- target,- source: resolved.source,- command: resolved.cmd[0],- args: resolved.cmd.slice(1),+ runPrompt: (text: string) => Effect.Effect<acp.PromptResponse, AcpInvokeError>;+ stderrSuffix: () => string;+}): Effect.Effect<InvokeAgentResponse, unknown, FileSystem.FileSystem> => {+ const finalizeText = Effect.try({+ try: () => finalizeInvokeAgentText(client.getText(), options),+ catch: error => error,});- const { CLAUDECODE: _, ...childEnv } = process.env;- const child = spawn(resolved.cmd[0]!, resolved.cmd.slice(1), {- cwd: process.cwd(),- env: resolved.env- ? {- ...childEnv,- ...resolved.env,+ return finalizeText.pipe(+ Effect.map(payload => toInvokeAgentResponse(master, target, payload)),+ Effect.catchAll(error => {+ const structuredSchema = options.structuredSchema;+ if (!structuredSchema) {+ return Effect.fail(error);+ }++ return Effect.gen(function* () {+ helperDebugLog('subAgent.acp.structured_repair', {+ target,+ reason: error instanceof Error ? error.message : String(error),+ });++ const repairResponse = yield* runPrompt(+ buildStructuredRepairPrompt(+ structuredSchema,+ structuredOutputMcp ? ACP_STRUCTURED_OUTPUT_TOOL_NAME : undefined+ )+ );++ if (repairResponse.stopReason === 'cancelled') {+ return yield* Effect.fail(+ createFallbackError(+ 'prompt_failed',+ `${target} ACP repair prompt was cancelled${stderrSuffix()}`+ )+ );}- : childEnv,- stdio: ['pipe', 'pipe', 'pipe'],- });- let stderr = '';- child.stderr?.setEncoding('utf8');- child.stderr?.on('data', chunk => {- stderr += chunk;- });+ const repairedStructuredOutput = yield* maybeReadStructuredOutputFromTool({+ context: structuredOutputMcp,+ options,+ helperDebugLog,+ });+ if (repairedStructuredOutput !== undefined) {+ return toInvokeAgentResponse(master, target, {+ result: null,+ structuredOutput: repairedStructuredOutput,+ });+ }- const closePromise = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(- (resolve, reject) => {- child.once('error', reject);- child.once('close', (code, signal) => resolve({ code, signal }));- }+ const payload = yield* finalizeText;+ return toInvokeAgentResponse(master, target, payload);+ });+ }));+};- if (!child.stdin || !child.stdout) {- child.kill();- throw createFallbackError('spawn_failed', `Failed to spawn ${target} ACP adapter.`);- }+const invokeAcpSubAgentEffect = ({+ prompt,+ options,+ master,+ target,+ allowedReadRoots,+ helperDebugLog,+}: InvokeAcpSubAgentParams) =>+ Effect.gen(function* () {+ const pathApi = yield* Path.Path;+ const nodeOs = yield* NodeOs;- const client = new RunSubAgentClient(helperDebugLog, [- ...new Set(allowedReadRoots.map(root => path.resolve(root))),- ]);- const stream = acp.ndJsonStream(- Writable.toWeb(child.stdin) as unknown as WritableStream<Uint8Array>,- Readable.toWeb(child.stdout) as unknown as ReadableStream<Uint8Array>- );- const connection = new acp.ClientSideConnection(() => client, stream);+ const structuredOutputMcp = yield* createStructuredOutputMcpContext({+ options,+ helperDebugLog,+ });+ yield* Effect.addFinalizer(() =>+ structuredOutputMcp ? structuredOutputMcp.cleanup : Effect.void+ );- try {- const initialized = await connection- .initialize({- protocolVersion: acp.PROTOCOL_VERSION,- clientCapabilities: {},+ const resolved = yield* resolveAcpAdapterCommand(target);+ helperDebugLog('subAgent.acp.resolve', {+ target,+ source: resolved.source,+ command: resolved.cmd[0],+ args: resolved.cmd.slice(1),+ });++ // The Claude Code CLI refuses to start when it inherits CLAUDECODE=1 (its+ // nested-session guard checks `process.env.CLAUDECODE === "1"`). The+ // platform Command executor always spreads process.env into the child, so+ // the variable cannot be dropped; mask it with an empty string instead —+ // falsy and distinct from the guarded "1" — only when the parent has it set.+ const claudeCode = yield* Config.option(Config.string('CLAUDECODE'));+ const childEnv: Record<string, string> = {+ ...(Option.isSome(claudeCode) ? { CLAUDECODE: '' } : {}),+ ...(resolved.env ?? {}),+ };++ const stdinQueue = yield* Queue.bounded<Uint8Array>(16);+ const [executable, ...commandArgs] = resolved.cmd;+ const command = Command.make(executable, ...commandArgs).pipe(Command.env(childEnv));++ const child = yield* Command.start(command).pipe(+ Effect.mapError(error =>+ createFallbackError('spawn_failed', `Failed to spawn ${target} ACP adapter.`, error)+ )+ );++ // Teardown parity with the previous finally block: SIGTERM the child, wait+ // for it to exit for at most 200ms, then SIGKILL it if it is still alive.+ // Registered after Command.start so it runs before the executor's own+ // scope finalizer (which would otherwise await a stubborn child forever).+ yield* Effect.addFinalizer(() =>+ Effect.gen(function* () {+ yield* Effect.interruptible(child.kill('SIGTERM')).pipe(+ Effect.timeout('200 millis'),+ Effect.ignore+ );+ const stillRunning = yield* child.isRunning.pipe(Effect.orElseSucceed(() => false));+ if (stillRunning) {+ yield* Effect.ignore(child.kill('SIGKILL'));+ }})- .catch(error => {- throw createFallbackError(+ );++ let stderrText = '';+ yield* Stream.runForEach(Stream.decodeText(child.stderr), text =>+ Effect.sync(() => {+ stderrText += text;+ })+ ).pipe(Effect.ignore, Effect.forkScoped);+ const stderrSuffix = () => (stderrText.trim() ? `: ${stderrText.trim()}` : '');++ yield* Stream.run(Stream.fromQueue(stdinQueue), child.stdin).pipe(+ Effect.ignore,+ Effect.forkScoped+ );++ const client = new RunSubAgentClient(+ helperDebugLog,+ [...new Set(allowedReadRoots.map(root => pathApi.resolve(root)))],+ pathApi,+ nodeOs.homedir+ );+ const stream = acp.ndJsonStream(+ writableStreamFromQueue(stdinQueue),+ Stream.toReadableStream(child.stdout)+ );+ const connection = new acp.ClientSideConnection(() => client, stream);++ const initialized = yield* Effect.tryPromise({+ try: () =>+ connection.initialize({+ protocolVersion: acp.PROTOCOL_VERSION,+ clientCapabilities: {},+ }),+ catch: error =>+ createFallbackError('initialize_failed',- `${target} ACP initialize failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,+ `${target} ACP initialize failed${stderrSuffix()}`,error- );- });+ ),+ });helperDebugLog('subAgent.acp.initialized', {target,protocolVersion: initialized.protocolVersion,});- const session = await connection- .newSession({- cwd: process.cwd(),- mcpServers: structuredOutputMcp ? [structuredOutputMcp.mcpServer] : [],- })- .catch(error => {- throw createFallbackError(+ const session = yield* Effect.tryPromise({+ try: () =>+ connection.newSession({+ cwd: process.cwd(),+ mcpServers: structuredOutputMcp ? [structuredOutputMcp.mcpServer] : [],+ }),+ catch: error =>+ createFallbackError('session_failed',- `${target} ACP session creation failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,+ `${target} ACP session creation failed${stderrSuffix()}`,error- );- });+ ),+ });helperDebugLog('subAgent.acp.session', {target,@@ -617,30 +843,28 @@ export const invokeAcpSubAgent = async ({});if (typeof options.model === 'string' && options.model.trim().length > 0) {- const setSessionModel = (connection as LegacySetSessionModelConnection)- .unstable_setSessionModel;- try {- if (typeof setSessionModel !== 'function') {- throw new Error('ACP session model selection is not supported by this connection');- }+ const model = options.model.trim();+ const setSessionModel = getLegacySetSessionModel(connection);+ const modelFailure =+ setSessionModel === undefined+ ? 'ACP session model selection is not supported by this connection'+ : yield* Effect.tryPromise({+ try: () => setSessionModel({ sessionId: session.sessionId, modelId: model }),+ catch: error => (error instanceof Error ? error.message : String(error)),+ }).pipe(+ Effect.match({+ onSuccess: (): string | undefined => undefined,+ onFailure: message => message,+ })+ );- await setSessionModel.call(connection, {- sessionId: session.sessionId,- modelId: options.model.trim(),- });- helperDebugLog('subAgent.acp.model', {- target,- model: options.model.trim(),- applied: true,- });- } catch (error) {- helperDebugLog('subAgent.acp.model', {- target,- model: options.model.trim(),- applied: false,- error: error instanceof Error ? error.message : String(error),- });- }+ helperDebugLog('subAgent.acp.model', {+ target,+ model,+ ...(modelFailure === undefined+ ? { applied: true }+ : { applied: false, error: modelFailure }),+ });}const promptText =@@ -651,37 +875,36 @@ export const invokeAcpSubAgent = async ({ACP_STRUCTURED_OUTPUT_TOOL_NAME): buildStructuredPrompt(prompt, options.structuredSchema);- const runPrompt = async (promptText: string) =>- connection- .prompt({- sessionId: session.sessionId,- prompt: [{ type: 'text', text: promptText }],- })- .catch(error => {- if (connection.signal.aborted) {- throw createFallbackError(- 'connection_closed',- `${target} ACP connection closed before prompt completion${stderr.trim() ? `: ${stderr.trim()}` : ''}`,- error- );- }- throw createFallbackError(- 'prompt_failed',- `${target} ACP prompt failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,- error- );- });+ const runPrompt = (text: string) =>+ Effect.tryPromise({+ try: () =>+ connection.prompt({+ sessionId: session.sessionId,+ prompt: [{ type: 'text', text }],+ }),+ catch: error =>+ connection.signal.aborted+ ? createFallbackError(+ 'connection_closed',+ `${target} ACP connection closed before prompt completion${stderrSuffix()}`,+ error+ )+ : createFallbackError(+ 'prompt_failed',+ `${target} ACP prompt failed${stderrSuffix()}`,+ error+ ),+ });- const response = await runPrompt(promptText);+ const response = yield* runPrompt(promptText);if (response.stopReason === 'cancelled') {- throw createFallbackError(- 'prompt_failed',- `${target} ACP prompt was cancelled${stderr.trim() ? `: ${stderr.trim()}` : ''}`+ return yield* Effect.fail(+ createFallbackError('prompt_failed', `${target} ACP prompt was cancelled${stderrSuffix()}`));}- const structuredOutput = maybeReadStructuredOutputFromTool({+ const structuredOutput = yield* maybeReadStructuredOutputFromTool({context: structuredOutputMcp,options,helperDebugLog,@@ -693,58 +916,29 @@ export const invokeAcpSubAgent = async ({});}- let payload: Pick<InvokeAgentResponse, 'result' | 'structuredOutput'>;- try {- payload = finalizeInvokeAgentText(client.getText(), options);- } catch (error) {- if (!options.structuredSchema) {- throw error;- }-- helperDebugLog('subAgent.acp.structured_repair', {- target,- reason: error instanceof Error ? error.message : String(error),- });-- const repairResponse = await runPrompt(- buildStructuredRepairPrompt(- options.structuredSchema,- structuredOutputMcp ? ACP_STRUCTURED_OUTPUT_TOOL_NAME : undefined- )- );-- if (repairResponse.stopReason === 'cancelled') {- throw createFallbackError(- 'prompt_failed',- `${target} ACP repair prompt was cancelled${stderr.trim() ? `: ${stderr.trim()}` : ''}`- );- }-- const repairedStructuredOutput = maybeReadStructuredOutputFromTool({- context: structuredOutputMcp,- options,- helperDebugLog,- });- if (repairedStructuredOutput !== undefined) {- return toInvokeAgentResponse(master, target, {- result: null,- structuredOutput: repairedStructuredOutput,- });- }-- payload = finalizeInvokeAgentText(client.getText(), options);- }+ return yield* finalizeWithStructuredRepair({+ client,+ options,+ master,+ target,+ structuredOutputMcp,+ helperDebugLog,+ runPrompt,+ stderrSuffix,+ });+ });- return toInvokeAgentResponse(master, target, payload);- } finally {- structuredOutputMcp?.cleanup();- child.kill();- await Promise.race([- closePromise.catch(() => undefined),- new Promise(resolve => setTimeout(resolve, 200)),- ]);- if (!child.killed) {- child.kill('SIGKILL');- }+export const invokeAcpSubAgent = async (+ params: InvokeAcpSubAgentParams+): Promise<InvokeAgentResponse> => {+ const exit = await Effect.runPromiseExit(+ invokeAcpSubAgentEffect(params).pipe(Effect.scoped, Effect.provide(RunSubAgentAcpLive))+ );+ if (Exit.isSuccess(exit)) {+ return exit.value;}++ // Surface the original error instance (callers branch on AcpInvokeError and+ // its code), not a FiberFailure wrapper.+ throw Cause.squash(exit.cause);};diff --git a/ts/packages/cli/src/services/run-subagent-legacy.ts b/ts/packages/cli/src/services/run-subagent-legacy.tsindex 157cb0b3b..7b0670592 100644--- a/ts/packages/cli/src/services/run-subagent-legacy.ts+++ b/ts/packages/cli/src/services/run-subagent-legacy.ts@@ -1,11 +1,6 @@-// 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 { Command, FileSystem, Path } from '@effect/platform';+import { BunContext } from '@effect/platform-bun';+import { Cause, Data, Effect, Exit, Predicate, Stream } from 'effect';import type { MasterKind } from 'src/services/master-detector';import {parseJson,@@ -16,117 +11,131 @@ import {type InvokeAgentTarget,} from 'src/services/run-subagent-shared';-const runExternalCommandText = async (- cmd: ReadonlyArray<string>,- helperDebugLog: HelperDebugLog-) => {- helperDebugLog('agent.spawn', { command: cmd[0], args: cmd.slice(1) });-- const child = spawn(cmd[0]!, cmd.slice(1), {- cwd: process.cwd(),- env: process.env,- stdio: ['ignore', 'pipe', 'pipe'],- });-- const stdoutChunks: string[] = [];- const stderrChunks: string[] = [];+class SubAgentCommandFailedError extends Data.TaggedError('SubAgentCommandFailedError')<{+ readonly command: string;+ readonly exitCode: number;+ readonly details: string;+}> {+ override get message(): string {+ const suffix = this.details ? `: ${this.details}` : '';+ return `${this.command} failed with exit code ${this.exitCode}${suffix}`;+ }+}- child.stdout?.setEncoding('utf8');- child.stdout?.on('data', chunk => stdoutChunks.push(chunk));- child.stderr?.setEncoding('utf8');- child.stderr?.on('data', chunk => stderrChunks.push(chunk));+class SubAgentNonJsonOutputError extends Data.TaggedError('SubAgentNonJsonOutputError')<{+ readonly target: InvokeAgentTarget;+}> {+ override get message(): string {+ return `${this.target} returned non-JSON output in experimental_subAgent().`;+ }+}- const exitCode = await new Promise<number>((resolve, reject) => {- child.once('error', reject);- child.once('close', code => resolve(code ?? 0));- });+const collectUtf8Text = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>+ Stream.mkString(Stream.decodeText(stream));- const stdout = stdoutChunks.join('');- const stderr = stderrChunks.join('');+const runExternalCommandText = (+ cmd: readonly [string, ...Array<string>],+ helperDebugLog: HelperDebugLog+) =>+ Effect.gen(function* () {+ const [executable, ...commandArgs] = cmd;+ helperDebugLog('agent.spawn', { command: cmd[0], args: cmd.slice(1) });++ // The child never reads interactive input: hand it an immediately-closed+ // stdin pipe (EOF), matching the previous `stdio: ['ignore', ...]` spawn.+ const command = Command.make(executable, ...commandArgs).pipe(Command.stdin(Stream.empty));++ const [exitCode, stdout, stderr] = yield* Effect.scoped(+ Effect.flatMap(Command.start(command), child =>+ Effect.all([child.exitCode, collectUtf8Text(child.stdout), collectUtf8Text(child.stderr)], {+ concurrency: 3,+ })+ )+ );++ if (exitCode !== 0) {+ const details = stderr.trim() || stdout.trim();+ helperDebugLog('agent.error', {+ command: cmd[0],+ exitCode,+ stderr: stderr.trim() || undefined,+ });+ return yield* new SubAgentCommandFailedError({ command: executable, exitCode, details });+ }- if (exitCode !== 0) {- const details = stderr.trim() || stdout.trim();- const suffix = details ? `: ${details}` : '';- helperDebugLog('agent.error', {+ helperDebugLog('agent.done', {command: cmd[0],exitCode,- stderr: stderr.trim() || undefined,+ stdoutBytes: stdout.length,+ stderrBytes: stderr.length,});- throw new Error(`${cmd[0]} failed with exit code ${exitCode}${suffix}`);- }-- helperDebugLog('agent.done', {- command: cmd[0],- exitCode,- stdoutBytes: stdout.length,- stderrBytes: stderr.length,+ return { stdout, stderr, exitCode };});- return { stdout, stderr, exitCode };-};-const invokeClaudeLegacy = async (+const invokeClaudeLegacy = (prompt: string,options: InvokeAgentNormalizedOptions,master: MasterKind,helperDebugLog: HelperDebugLog-): Promise<InvokeAgentResponse> => {- helperDebugLog('subAgent.prepare', {- target: 'claude',- transport: 'legacy',- hasSchema: options.structuredSchema !== undefined,- });+) =>+ Effect.gen(function* () {+ helperDebugLog('subAgent.prepare', {+ target: 'claude',+ transport: 'legacy',+ hasSchema: options.structuredSchema !== undefined,+ });- const args = ['claude', '--bare', '-p', '--output-format', 'json'];- if (typeof options.model === 'string' && options.model.trim().length > 0) {- args.push('--model', options.model.trim());- }- if (options.structuredSchema !== undefined) {- args.push('--json-schema', JSON.stringify(options.structuredSchema));- }- args.push(prompt);+ const args: [string, ...Array<string>] = ['claude', '--bare', '-p', '--output-format', 'json'];+ if (typeof options.model === 'string' && options.model.trim().length > 0) {+ args.push('--model', options.model.trim());+ }+ if (options.structuredSchema !== undefined) {+ args.push('--json-schema', JSON.stringify(options.structuredSchema));+ }+ args.push(prompt);- const result = await runExternalCommandText(args, helperDebugLog);- const parsed = parseJson(result.stdout.trim());- if (!parsed || typeof parsed !== 'object') {- throw new Error('claude returned non-JSON output in experimental_subAgent().');- }+ const result = yield* runExternalCommandText(args, helperDebugLog);+ const parsed = parseJson(result.stdout.trim());+ if (!Predicate.isRecord(parsed)) {+ return yield* new SubAgentNonJsonOutputError({ target: 'claude' });+ }- const payload =- options.structuredSchema !== undefined- ? {- result: null,- structuredOutput: (parsed as { structured_output?: unknown }).structured_output ?? null,- }- : {- result:- typeof (parsed as { result?: unknown }).result === 'string'- ? (parsed as { result: string }).result- : null,- structuredOutput: null,- };-- return toInvokeAgentResponse(master, 'claude', payload);-};+ const payload =+ options.structuredSchema !== undefined+ ? {+ result: null,+ structuredOutput: parsed.structured_output ?? null,+ }+ : {+ result: typeof parsed.result === 'string' ? parsed.result : null,+ structuredOutput: null,+ };++ return toInvokeAgentResponse(master, 'claude', payload);+ });-const invokeCodexLegacy = async (+const invokeCodexLegacy = (prompt: string,options: InvokeAgentNormalizedOptions,master: MasterKind,helperDebugLog: HelperDebugLog-): Promise<InvokeAgentResponse> => {- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-invoke-agent-'));- const outputPath = path.join(tempDir, 'last-message.txt');- const args = [- 'codex',- 'exec',- '--skip-git-repo-check',- '--sandbox',- 'read-only',- '-o',- outputPath,- ];-- try {+) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;++ const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: 'composio-invoke-agent-' });+ const outputPath = path.join(tempDir, 'last-message.txt');+ const args: [string, ...Array<string>] = [+ 'codex',+ 'exec',+ '--skip-git-repo-check',+ '--sandbox',+ 'read-only',+ '-o',+ outputPath,+ ];+helperDebugLog('subAgent.prepare', {target: 'codex',transport: 'legacy',@@ -139,14 +148,14 @@ const invokeCodexLegacy = async (if (options.structuredSchema !== undefined) {const schemaPath = path.join(tempDir, 'schema.json');- fs.writeFileSync(schemaPath, JSON.stringify(options.structuredSchema), 'utf8');+ yield* fs.writeFileString(schemaPath, JSON.stringify(options.structuredSchema));args.push('--output-schema', schemaPath);}args.push(prompt);- await runExternalCommandText(args, helperDebugLog);+ yield* runExternalCommandText(args, helperDebugLog);- const text = fs.readFileSync(outputPath, 'utf8').trim();+ const text = (yield* fs.readFileString(outputPath)).trim();if (options.structuredSchema !== undefined) {return toInvokeAgentResponse(master, 'codex', {result: null,@@ -158,10 +167,7 @@ const invokeCodexLegacy = async (result: text,structuredOutput: null,});- } finally {- fs.rmSync(tempDir, { recursive: true, force: true });- }-};+ }).pipe(Effect.scoped);export const invokeLegacySubAgent = async ({prompt,@@ -176,9 +182,17 @@ export const invokeLegacySubAgent = async ({target: InvokeAgentTarget;helperDebugLog: HelperDebugLog;}): Promise<InvokeAgentResponse> => {- if (target === 'claude') {- return invokeClaudeLegacy(prompt, options, master, helperDebugLog);+ const program =+ target === 'claude'+ ? invokeClaudeLegacy(prompt, options, master, helperDebugLog)+ : invokeCodexLegacy(prompt, options, master, helperDebugLog);++ const exit = await Effect.runPromiseExit(Effect.provide(program, BunContext.layer));+ if (Exit.isSuccess(exit)) {+ return exit.value;}- return invokeCodexLegacy(prompt, options, master, helperDebugLog);+ // Surface the original error instance (same message callers matched on+ // before), not a FiberFailure wrapper.+ throw Cause.squash(exit.cause);};diff --git a/ts/packages/cli/src/services/run-subagent-output-mcp.ts b/ts/packages/cli/src/services/run-subagent-output-mcp.tsindex f834c121e..498958344 100644--- a/ts/packages/cli/src/services/run-subagent-output-mcp.ts+++ b/ts/packages/cli/src/services/run-subagent-output-mcp.ts@@ -4,10 +4,13 @@ import process from 'node:process';import { jsonSchemaToZod } from '@composio/json-schema-to-zod';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';+import { Effect } from 'effect';import {ACP_STRUCTURED_OUTPUT_TOOL_NAME,buildStructuredOutputToolSchema,+ decodeStructuredSchemaJson,} from 'src/services/run-subagent-shared';+import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';const readFlag = (name: string): string => {const index = process.argv.indexOf(name);@@ -22,7 +25,7 @@ const main = async (): Promise<void> => {const schemaFilePath = readFlag('--schema-file');const resultFilePath = readFlag('--result-file');const schemaText = fs.readFileSync(schemaFilePath, 'utf8');- const structuredSchema = JSON.parse(schemaText) as Record<string, unknown>;+ const structuredSchema = decodeStructuredSchemaJson(schemaText);const toolInputSchema = jsonSchemaToZod(buildStructuredOutputToolSchema(structuredSchema));const server = new McpServer({@@ -57,7 +60,9 @@ const main = async (): Promise<void> => {void main().catch(error => {const message = error instanceof Error ? (error.stack ?? error.message) : String(error);- // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)- process.stderr.write(`${message}\n`);+ Effect.gen(function* () {+ const ui = yield* TerminalUI;+ yield* ui.error(message);+ }).pipe(Effect.provide(TerminalUILive), Effect.runSync);process.exit(1);});diff --git a/ts/packages/cli/src/services/run-subagent-shared.ts b/ts/packages/cli/src/services/run-subagent-shared.tsindex 0c4aeacb4..7c41cb770 100644--- a/ts/packages/cli/src/services/run-subagent-shared.ts+++ b/ts/packages/cli/src/services/run-subagent-shared.ts@@ -1,3 +1,5 @@+import { Either, Predicate, Schema } from 'effect';+import { JsonRecordSchema } from 'src/effects/json';import type { MasterKind } from 'src/services/master-detector';export type InvokeAgentTarget = 'claude' | 'codex';@@ -46,12 +48,19 @@ export class AcpInvokeError extends Error {}}+const isAcpInvokeFailure = (value: unknown): value is AcpInvokeFailure =>+ value === 'adapter_not_found' ||+ value === 'spawn_failed' ||+ value === 'initialize_failed' ||+ value === 'session_failed' ||+ value === 'prompt_failed' ||+ value === 'connection_closed';+export const isAcpInvokeError = (value: unknown): value is AcpInvokeError =>- !!value &&- typeof value === 'object' &&- (value as { name?: unknown }).name === 'AcpInvokeError' &&- typeof (value as { message?: unknown }).message === 'string' &&- typeof (value as { code?: unknown }).code === 'string';+ Predicate.isRecord(value) &&+ value.name === 'AcpInvokeError' &&+ typeof value.message === 'string' &&+ isAcpInvokeFailure(value.code);export const toInvokeAgentResponse = (master: MasterKind,@@ -69,26 +78,29 @@ export const toInvokeAgentResponse = (: {}),});+/**+ * Sync JSON probe shared with the non-Effect child-process runtime; `Either`+ * is pure data from the already-bundled `effect` package, so it is safe there.+ */+const parseJsonEither = (text: string): Either.Either<unknown, unknown> =>+ Either.try((): unknown => JSON.parse(text));+export const parseJson = (text: string): unknown => {const value = text.trim();if (!value) {return undefined;}- try {- return JSON.parse(value);- } catch {- return value;- }+ // Non-JSON sub-agent stdout is returned verbatim by design.+ return Either.getOrElse(parseJsonEither(value), (): unknown => value);};+const decodeStructuredSchema = Schema.decodeUnknownSync(Schema.parseJson(JsonRecordSchema));++export const decodeStructuredSchemaJson = (text: string): Record<string, unknown> =>+ decodeStructuredSchema(text);+const summarizeValidationError = (error: unknown): string => {- const issues =- error &&- typeof error === 'object' &&- 'issues' in error &&- Array.isArray((error as { issues?: unknown[] }).issues)- ? (error as { issues: Array<{ path?: unknown[]; message?: unknown }> }).issues- : [];+ const issues = Predicate.isRecord(error) && Array.isArray(error.issues) ? error.issues : [];if (issues.length === 0) {return 'Invalid structured output.';@@ -97,6 +109,9 @@ const summarizeValidationError = (error: unknown): string => {return issues.slice(0, 5).map(issue => {+ if (!Predicate.isRecord(issue)) {+ return '<root>: Invalid value';+ }const path =Array.isArray(issue.path) && issue.path.length > 0 ? issue.path.join('.') : '<root>';const message = typeof issue.message === 'string' ? issue.message : 'Invalid value';@@ -165,13 +180,8 @@ export const unwrapStructuredOutputToolPayload = (return payload;}- if (- payload &&- typeof payload === 'object' &&- !Array.isArray(payload) &&- ACP_STRUCTURED_OUTPUT_WRAPPER_KEY in payload- ) {- return (payload as Record<string, unknown>)[ACP_STRUCTURED_OUTPUT_WRAPPER_KEY];+ if (Predicate.isRecord(payload) && ACP_STRUCTURED_OUTPUT_WRAPPER_KEY in payload) {+ return payload[ACP_STRUCTURED_OUTPUT_WRAPPER_KEY];}return payload;@@ -239,11 +249,12 @@ const tryParseStructuredJson = (text: string): unknown | undefined => {return undefined;}- try {- return JSON.parse(trimmed);- } catch {- // Fall through to more permissive extraction for agents that emit a short- // status line before the final JSON payload.+ // A parse failure here is the signal to fall through to more permissive+ // extraction for agents that emit a short status line before the final JSON+ // payload, not an error to surface.+ const direct = parseJsonEither(trimmed);+ if (Either.isRight(direct)) {+ return direct.right;}const fencedMatches = [...trimmed.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];@@ -253,10 +264,11 @@ const tryParseStructuredJson = (text: string): unknown | undefined => {continue;}- try {- return JSON.parse(candidate);- } catch {- // Keep scanning for a valid fenced block.+ // Probes each fenced block for valid JSON; an invalid block just advances+ // the scan to the next one.+ const fenced = parseJsonEither(candidate);+ if (Either.isRight(fenced)) {+ return fenced.right;}}@@ -333,29 +345,33 @@ const tryParseStructuredJson = (text: string): unknown | undefined => {}const candidate = trimmed.slice(start, end + 1);- try {- const parsed = JSON.parse(candidate);- const nextCandidate = {- length: candidate.length,- start,- isObject: !Array.isArray(parsed) && parsed !== null && typeof parsed === 'object',- value: parsed,- };+ // Probes each balanced {...}/[...] substring for valid JSON inside a+ // tight scanning loop; a failure just skips the candidate so the scan can+ // keep looking for a larger valid JSON payload.+ const parsedCandidate = parseJsonEither(candidate);+ if (Either.isLeft(parsedCandidate)) {+ continue;+ }- if (- !bestCandidate ||- nextCandidate.length > bestCandidate.length ||- (nextCandidate.length === bestCandidate.length &&- nextCandidate.isObject &&- !bestCandidate.isObject) ||- (nextCandidate.length === bestCandidate.length &&- nextCandidate.isObject === bestCandidate.isObject &&- nextCandidate.start < bestCandidate.start)- ) {- bestCandidate = nextCandidate;- }- } catch {- // Keep scanning for a larger valid JSON payload.+ const parsed = parsedCandidate.right;+ const nextCandidate = {+ length: candidate.length,+ start,+ isObject: !Array.isArray(parsed) && parsed !== null && typeof parsed === 'object',+ value: parsed,+ };++ if (+ !bestCandidate ||+ nextCandidate.length > bestCandidate.length ||+ (nextCandidate.length === bestCandidate.length &&+ nextCandidate.isObject &&+ !bestCandidate.isObject) ||+ (nextCandidate.length === bestCandidate.length &&+ nextCandidate.isObject === bestCandidate.isObject &&+ nextCandidate.start < bestCandidate.start)+ ) {+ bestCandidate = nextCandidate;}}diff --git a/ts/packages/cli/src/services/setup.ts b/ts/packages/cli/src/services/setup.tsindex 156b2ecd7..22725333b 100644--- a/ts/packages/cli/src/services/setup.ts+++ b/ts/packages/cli/src/services/setup.ts@@ -1,5 +1,5 @@-import { Command } from '@effect/platform';-import { Data, Effect } from 'effect';+import { Command, Error as PlatformError } from '@effect/platform';+import { Data, Effect, Either, Option, Predicate, Schema } from 'effect';import semver from 'semver';import { CommandRunner, type CommandResult } from './command-runner';import { SetupSkillInstaller } from './setup-skill-installer';@@ -120,23 +120,40 @@ const MINIMUM_CODEX_SETUP_VERSION = '0.139.0';export class SetupCommandError extends Data.TaggedError('services/SetupCommandError')<{readonly message: string;readonly operation: 'setup' | 'uninstall';+ readonly cause?: unknown;}> {}-const asRecord = (value: unknown): Record<string, unknown> | undefined => {- if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined;- return value as Record<string, unknown>;-};+type SetupFailureStage = 'detect' | 'inspect' | 'validate' | 'mutate' | 'verify' | 'skill';-const isRecord = (value: unknown): value is Record<string, unknown> =>- asRecord(value) !== undefined;+export class SetupProcessError extends Data.TaggedError('services/SetupProcessError')<{+ readonly message: string;+ readonly target: AgentHost;+ readonly stage: SetupFailureStage;+ readonly cause?: unknown;+}> {}-const parseJson = (value: string): unknown => {- try {- return JSON.parse(value) as unknown;- } catch {- return undefined;- }-};+const setupProcessError = (params: {+ readonly adapter: SetupTargetAdapter;+ readonly stage: SetupFailureStage;+ readonly message: string;+ readonly cause?: unknown;+}) =>+ new SetupProcessError({+ message: params.message,+ target: params.adapter.target,+ stage: params.stage,+ ...(params.cause === undefined ? {} : { cause: params.cause }),+ });++const asRecord = (value: unknown): Record<string, unknown> | undefined =>+ Predicate.isRecord(value) ? value : undefined;++const decodeJsonOption = Schema.decodeUnknownOption(Schema.parseJson());++const parseJson = (value: string): unknown | undefined =>+ Option.getOrUndefined(decodeJsonOption(value));++const isRecord = Predicate.isRecord;const recordsFrom = (value: unknown,@@ -174,21 +191,21 @@ const normalizeGitHubRepository = (value: string): string | undefined => {let repository = trimmed;if (/^[a-z][a-z0-9+.-]*:\/\//i.test(repository)) {- try {- const url = new URL(repository);- const isCanonicalGitHubUrl =- url.protocol === 'https:' &&- url.hostname.toLowerCase() === 'github.com' &&- url.port === '' &&- url.username === '' &&- url.password === '' &&- url.search === '' &&- url.hash === '';- if (!isCanonicalGitHubUrl) return undefined;- repository = url.pathname;- } catch {- return undefined;- }+ // new URL() throws on malformed input; an unparseable repository string+ // simply normalizes to undefined.+ const parsedUrl = Either.try(() => new URL(repository));+ if (Either.isLeft(parsedUrl)) return undefined;+ const url = parsedUrl.right;+ const isCanonicalGitHubUrl =+ url.protocol === 'https:' &&+ url.hostname.toLowerCase() === 'github.com' &&+ url.port === '' &&+ url.username === '' &&+ url.password === '' &&+ url.search === '' &&+ url.hash === '';+ if (!isCanonicalGitHubUrl) return undefined;+ repository = url.pathname;}repository = repository.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '');@@ -245,29 +262,33 @@ const pluginState = (const commandText = (executable: string, args: ReadonlyArray<string>) =>[executable, ...args].join(' ');-const capture = (executable: string, args: ReadonlyArray<string>) =>+const capture = (+ adapter: SetupTargetAdapter,+ args: ReadonlyArray<string>,+ stage: Extract<SetupFailureStage, 'detect' | 'inspect'>+) =>Effect.gen(function* () {const runner = yield* CommandRunner;- return yield* runner.capture(Command.make(executable, ...args)).pipe(+ return yield* runner.capture(Command.make(adapter.executable, ...args)).pipe(Effect.timeoutFail({duration: SETUP_COMMAND_TIMEOUT,onTimeout: () =>- new Error(- `The \`${commandText(executable, args)}\` command timed out after ${SETUP_COMMAND_TIMEOUT}.`- ),+ setupProcessError({+ adapter,+ stage,+ message: `The \`${commandText(adapter.executable, args)}\` command timed out after ${SETUP_COMMAND_TIMEOUT}.`,+ }),}));});-const isCommandNotFound = (error: unknown): boolean => {- if (error === null || typeof error !== 'object') return false;- const record = error as Record<string, unknown>;- return record._tag === 'SystemError' && record.reason === 'NotFound';-};--const captureOptional = (executable: string, args: ReadonlyArray<string>) =>- capture(executable, args).pipe(- Effect.catchIf(isCommandNotFound, () => Effect.succeed<CommandResult | undefined>(undefined))+const captureOptional = (adapter: SetupTargetAdapter, args: ReadonlyArray<string>) =>+ capture(adapter, args, 'detect').pipe(+ Effect.catchIf(Schema.is(PlatformError.SystemError), error =>+ error.reason === 'NotFound'+ ? Effect.succeed<CommandResult | undefined>(undefined)+ : Effect.fail(error)+ ));const targetLabel = (target: AgentHost): string => (target === 'claude' ? 'Claude Code' : 'Codex');@@ -315,9 +336,14 @@ const supportsInspection = (adapter: SetupTargetAdapter, versionOutput?: string)for (const args of adapter.inspectionHelpArgs) {const command = commandText(adapter.executable, args);- const result = yield* capture(adapter.executable, args).pipe(- Effect.mapError(- error => new Error(capabilityCheckFailureMessage(adapter, command, errorMessage(error)))+ const result = yield* capture(adapter, args, 'detect').pipe(+ Effect.mapError(cause =>+ setupProcessError({+ adapter,+ stage: 'detect',+ message: capabilityCheckFailureMessage(adapter, command, errorMessage(cause)),+ cause,+ })));if (result.exitCode !== 0) {@@ -336,56 +362,60 @@ const supportsInspection = (adapter: SetupTargetAdapter, versionOutput?: string)const detectAdapter = (adapter: SetupTargetAdapter) =>Effect.gen(function* () {- const versionArgs = ['--version'] as const;+ const versionArgs = ['--version'];const versionCommand = commandText(adapter.executable, versionArgs);- const captureResult = yield* captureOptional(adapter.executable, versionArgs).pipe(- Effect.map(result => ({ result }) as const),- Effect.catchAll(error => Effect.succeed({ error } as const))- );- if ('error' in captureResult) {- return {- available: true,- supported: false,- unsupportedReason: capabilityCheckFailureMessage(- adapter,- versionCommand,- errorMessage(captureResult.error)- ),- };- }- const { result } = captureResult;- if (!result) return { available: false, supported: false };- if (result.exitCode === 127) return { available: false, supported: false };- if (result.exitCode !== 0) {- return {- available: true,- supported: false,- unsupportedReason: capabilityCheckFailureMessage(- adapter,- versionCommand,- commandResultDetail(result)- ),- };- }-- const version = result.stdout.trim() || result.stderr.trim();- const support = yield* supportsInspection(adapter, version).pipe(- Effect.catchAll(error =>- Effect.succeed({ supported: false, reason: errorMessage(error) } as const)- )+ return yield* captureOptional(adapter, versionArgs).pipe(+ Effect.matchEffect({+ onFailure: cause =>+ Effect.succeed({+ available: true,+ supported: false,+ unsupportedReason: capabilityCheckFailureMessage(+ adapter,+ versionCommand,+ errorMessage(cause)+ ),+ }),+ onSuccess: result => {+ if (!result || result.exitCode === 127) {+ return Effect.succeed({ available: false, supported: false });+ }+ if (result.exitCode !== 0) {+ return Effect.succeed({+ available: true,+ supported: false,+ unsupportedReason: capabilityCheckFailureMessage(+ adapter,+ versionCommand,+ commandResultDetail(result)+ ),+ });+ }++ const version = result.stdout.trim() || result.stderr.trim();+ return supportsInspection(adapter, version).pipe(+ Effect.match({+ onFailure: cause => ({ supported: false, reason: errorMessage(cause) }),+ onSuccess: support => support,+ }),+ Effect.map(support =>+ version+ ? {+ available: true,+ supported: support.supported,+ version,+ ...(support.supported ? {} : { unsupportedReason: support.reason }),+ }+ : {+ available: true,+ supported: support.supported,+ ...(support.supported ? {} : { unsupportedReason: support.reason }),+ }+ )+ );+ },+ }));- return version- ? {- available: true,- supported: support.supported,- version,- ...(support.supported ? {} : { unsupportedReason: support.reason }),- }- : {- available: true,- supported: support.supported,- ...(support.supported ? {} : { unsupportedReason: support.reason }),- };});const commandFailureSuffix = (result: CommandResult): string => {@@ -393,7 +423,7 @@ const commandFailureSuffix = (result: CommandResult): string => {};const errorMessage = (error: unknown): string => {- if (error instanceof Error) return error.message;+ if (Predicate.isError(error)) return error.message;return String(error);};@@ -411,12 +441,14 @@ const captureInspection = (operation: string,setupOperation: SetupOperation) =>- capture(adapter.executable, args).pipe(- Effect.mapError(- error =>- new Error(- `Failed to inspect ${targetLabel(adapter.target)} ${operation}: ${errorMessage(error)}. ${recoveryHint(adapter, setupOperation)}`- )+ capture(adapter, args, 'inspect').pipe(+ Effect.mapError(cause =>+ setupProcessError({+ adapter,+ stage: 'inspect',+ message: `Failed to inspect ${targetLabel(adapter.target)} ${operation}: ${errorMessage(cause)}. ${recoveryHint(adapter, setupOperation)}`,+ cause,+ })));@@ -428,19 +460,19 @@ const requireInspection = <T>(setupOperation: SetupOperation) => {if (result.exitCode !== 0) {- return Effect.fail(- new Error(- `Failed to inspect ${targetLabel(adapter.target)} ${operation}${commandFailureSuffix(result)}. ${recoveryHint(adapter, setupOperation)}`- )- );+ return setupProcessError({+ adapter,+ stage: 'inspect',+ message: `Failed to inspect ${targetLabel(adapter.target)} ${operation}${commandFailureSuffix(result)}. ${recoveryHint(adapter, setupOperation)}`,+ });}const inspected = parse(result.stdout);if (!inspected) {- return Effect.fail(- new Error(- `${targetLabel(adapter.target)} returned invalid JSON while inspecting ${operation}. ${recoveryHint(adapter, setupOperation)}`- )- );+ return setupProcessError({+ adapter,+ stage: 'inspect',+ message: `${targetLabel(adapter.target)} returned invalid JSON while inspecting ${operation}. ${recoveryHint(adapter, setupOperation)}`,+ });}return Effect.succeed(inspected);};@@ -470,7 +502,11 @@ const inspectAdapter = (}if (!detection.supported) {- return yield* Effect.fail(new Error(unsupportedInspectionMessage(adapter)));+ return yield* setupProcessError({+ adapter,+ stage: 'inspect',+ message: unsupportedInspectionMessage(adapter),+ });}const [marketplaces, plugins] = yield* Effect.all([@@ -551,42 +587,66 @@ const runRequired = (const result = yield* runner.capture(Command.make(adapter.executable, ...args)).pipe(Effect.timeoutFail({duration: SETUP_COMMAND_TIMEOUT,- onTimeout: () => new Error(`${operation} timed out after ${SETUP_COMMAND_TIMEOUT}.`),+ onTimeout: () =>+ setupProcessError({+ adapter,+ stage: 'mutate',+ message: `${operation} timed out after ${SETUP_COMMAND_TIMEOUT}.`,+ }),}),- Effect.mapError(- error =>- new Error(- `${operation} failed: ${errorMessage(error)}. ${recoveryHint(adapter, setupOperation)}`- )+ Effect.mapError(cause =>+ setupProcessError({+ adapter,+ stage: 'mutate',+ message: `${operation} failed: ${errorMessage(cause)}. ${recoveryHint(adapter, setupOperation)}`,+ cause,+ })));if (result.exitCode !== 0) {- return yield* Effect.fail(- new Error(- `${operation} failed${commandFailureSuffix(result)}. ${recoveryHint(adapter, setupOperation)}`- )- );+ return yield* setupProcessError({+ adapter,+ stage: 'mutate',+ message: `${operation} failed${commandFailureSuffix(result)}. ${recoveryHint(adapter, setupOperation)}`,+ });}});const validateInitialState = (adapter: SetupTargetAdapter, initial: InspectedSetupTarget) => {if (!initial.available) {- return Effect.fail(- new Error(- `${adapter.executable} is not installed or not available on PATH. Install it and rerun \`composio setup --target ${adapter.target}\`.`- )- );+ return setupProcessError({+ adapter,+ stage: 'validate',+ message: `${adapter.executable} is not installed or not available on PATH. Install it and rerun \`composio setup --target ${adapter.target}\`.`,+ });}if (initial.marketplace_conflict) {- return Effect.fail(- new Error(- `The ${adapter.target} marketplace named "composio" points to a different source. Run \`${adapter.marketplaceRemoveCommand}\`, then rerun \`composio setup --target ${adapter.target}\`.`- )- );+ return setupProcessError({+ adapter,+ stage: 'validate',+ message: `The ${adapter.target} marketplace named "composio" points to a different source. Run \`${adapter.marketplaceRemoveCommand}\`, then rerun \`composio setup --target ${adapter.target}\`.`,+ });}return Effect.void;};+const toSetupTargetResult = (params: {+ readonly adapter: SetupTargetAdapter;+ readonly final: InspectedSetupTarget;+ readonly pluginChanged: boolean;+ readonly skillChanged: boolean;+}): SetupTargetResult => ({+ target: params.adapter.target,+ available: params.final.available,+ marketplace_configured: params.final.marketplace_configured,+ plugin_installed: params.final.plugin_installed,+ plugin_enabled: params.final.plugin_enabled,+ cli_skill_ready: params.final.cli_skill_ready,+ changed: params.pluginChanged || params.skillChanged,+ plugin_changed: params.pluginChanged,+ skill_changed: params.skillChanged,+});+const installAdapter = (adapter: SetupTargetAdapter, initial: InspectedSetupTarget) =>Effect.gen(function* () {const steps: SetupStep[] = [];@@ -607,35 +667,27 @@ const installAdapter = (adapter: SetupTargetAdapter, initial: InspectedSetupTarglet skillChanged = false;if (adapter.skillSource === 'standalone' && !initial.cli_skill_ready) {skillChanged = yield* skillInstaller.ensureClaudeSkill.pipe(- Effect.mapError(- error =>- new Error(- `Installing the Claude Code CLI skill failed: ${errorMessage(error)}. ${recoveryHint(adapter, 'setup')}`- )+ Effect.mapError(cause =>+ setupProcessError({+ adapter,+ stage: 'skill',+ message: `Installing the Claude Code CLI skill failed: ${errorMessage(cause)}. ${recoveryHint(adapter, 'setup')}`,+ cause,+ })));}const final = yield* inspectAdapter(adapter);if (!isSetupReady(final)) {- return yield* Effect.fail(- new Error(- `Setup commands completed, but ${adapter.target} did not report the Composio plugin and CLI skill as ready. Rerun \`composio setup --target ${adapter.target}\` or inspect the native ${adapter.target} plugin configuration.`- )- );+ return yield* setupProcessError({+ adapter,+ stage: 'verify',+ message: `Setup commands completed, but ${adapter.target} did not report the Composio plugin and CLI skill as ready. Rerun \`composio setup --target ${adapter.target}\` or inspect the native ${adapter.target} plugin configuration.`,+ });}- return {- target: adapter.target,- available: final.available,- marketplace_configured: final.marketplace_configured,- plugin_installed: final.plugin_installed,- plugin_enabled: final.plugin_enabled,- cli_skill_ready: final.cli_skill_ready,- changed: pluginChanged || skillChanged,- plugin_changed: pluginChanged,- skill_changed: skillChanged,- } satisfies SetupTargetResult;+ return toSetupTargetResult({ adapter, final, pluginChanged, skillChanged });});const uninstallAdapter = (adapter: SetupTargetAdapter, initial: InspectedSetupTarget) =>@@ -655,35 +707,27 @@ const uninstallAdapter = (adapter: SetupTargetAdapter, initial: InspectedSetupTalet skillChanged = false;if (adapter.skillSource === 'standalone') {skillChanged = yield* skillInstaller.removeClaudeSkill.pipe(- Effect.mapError(- error =>- new Error(- `Removing the Claude Code CLI skill failed: ${errorMessage(error)}. ${recoveryHint(adapter, 'uninstall')}`- )+ Effect.mapError(cause =>+ setupProcessError({+ adapter,+ stage: 'skill',+ message: `Removing the Claude Code CLI skill failed: ${errorMessage(cause)}. ${recoveryHint(adapter, 'uninstall')}`,+ cause,+ })));}const final = yield* inspectAdapter(adapter, undefined, 'uninstall');if (final.plugin_installed) {- return yield* Effect.fail(- new Error(- `Uninstall commands completed, but ${adapter.target} still reports the Composio plugin as installed. Rerun \`composio setup --uninstall --target ${adapter.target}\` or inspect the native ${adapter.target} plugin configuration.`- )- );+ return yield* setupProcessError({+ adapter,+ stage: 'verify',+ message: `Uninstall commands completed, but ${adapter.target} still reports the Composio plugin as installed. Rerun \`composio setup --uninstall --target ${adapter.target}\` or inspect the native ${adapter.target} plugin configuration.`,+ });}- return {- target: adapter.target,- available: final.available,- marketplace_configured: final.marketplace_configured,- plugin_installed: final.plugin_installed,- plugin_enabled: final.plugin_enabled,- cli_skill_ready: final.cli_skill_ready,- changed: pluginChanged || skillChanged,- plugin_changed: pluginChanged,- skill_changed: skillChanged,- } satisfies SetupTargetResult;+ return toSetupTargetResult({ adapter, final, pluginChanged, skillChanged });});const FIXED_TARGETS: Readonly<Partial<Record<SetupTarget, ReadonlyArray<AgentHost>>>> = {@@ -733,17 +777,27 @@ export const inspectSetupTargets = (return inspected;});-export const installSetupTargets = (inspected: ReadonlyArray<InspectedSetupTarget>) =>+const runSetupTargets = <E, R>(+ inspected: ReadonlyArray<InspectedSetupTarget>,+ runAdapter: (+ adapter: SetupTargetAdapter,+ status: InspectedSetupTarget+ ) => Effect.Effect<SetupTargetResult, E, R>,+ verb: 'Setup' | 'Uninstall'+) =>Effect.gen(function* () {const completed: SetupTargetResult[] = [];for (const status of inspected) {- const result = yield* installAdapter(ADAPTERS[status.target], status).pipe(+ const result = yield* runAdapter(ADAPTERS[status.target], status).pipe(Effect.mapError(error => {if (completed.length === 0) return error;const targets = completed.map(item => item.target).join(', ');- return new Error(- `Setup completed for ${targets} before a later target failed: ${errorMessage(error)}`- );+ return setupProcessError({+ adapter: ADAPTERS[status.target],+ stage: 'mutate',+ message: `${verb} completed for ${targets} before a later target failed: ${errorMessage(error)}`,+ cause: error,+ });}));completed.push(result);@@ -751,20 +805,8 @@ export const installSetupTargets = (inspected: ReadonlyArray<InspectedSetupTargereturn completed;});+export const installSetupTargets = (inspected: ReadonlyArray<InspectedSetupTarget>) =>+ runSetupTargets(inspected, installAdapter, 'Setup');+export const uninstallSetupTargets = (inspected: ReadonlyArray<InspectedSetupTarget>) =>- Effect.gen(function* () {- const completed: SetupTargetResult[] = [];- for (const status of inspected) {- const result = yield* uninstallAdapter(ADAPTERS[status.target], status).pipe(- Effect.mapError(error => {- if (completed.length === 0) return error;- const targets = completed.map(item => item.target).join(', ');- return new Error(- `Uninstall completed for ${targets} before a later target failed: ${errorMessage(error)}`- );- })- );- completed.push(result);- }- return completed;- });+ runSetupTargets(inspected, uninstallAdapter, 'Uninstall');diff --git a/ts/packages/cli/src/services/tool-file-uploads.ts b/ts/packages/cli/src/services/tool-file-uploads.tsindex 6f5b743e7..cdc734be6 100644--- a/ts/packages/cli/src/services/tool-file-uploads.ts+++ b/ts/packages/cli/src/services/tool-file-uploads.ts@@ -1,25 +1,35 @@-// 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';+// This module's upload pipeline is plain async/await around the raw+// @composio/client promise API. The Effect caller resolves the platform+// FileSystem and Path services and passes the instances in as parameters;+// `readLocalFileBytes` below is the single point where a FileSystem effect+// is run to completion inside this promise pipeline.+import type { FileSystem, Path } from '@effect/platform';import type { Composio as RawComposioClient } from '@composio/client';import { assertSafeFileUploadPath } from '@composio/core';+import { Cause, Data, Effect, Exit, Predicate } from 'effect';import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';type JsonSchema = Record<string, unknown>;-const isRecord = (value: unknown): value is Record<string, unknown> =>- typeof value === 'object' && value !== null && !Array.isArray(value);+export class ToolFileUploadError extends Data.TaggedError('services/ToolFileUploadError')<{+ readonly cause?: unknown;+ readonly message: string;+ readonly reason: 'source-fetch' | 'source-read' | 'unsupported-source' | 'upload';+ readonly status?: number;+}> {}const isFileLike = (value: unknown): value is File =>typeof File !== 'undefined' && value instanceof File;-const isSchemaRecord = (value: unknown): value is JsonSchema => isRecord(value);+const isSchemaRecord = (value: unknown): value is JsonSchema => Predicate.isRecord(value);++const getSchemaVariant = (value: unknown): ReadonlyArray<JsonSchema> =>+ Array.isArray(value) ? value.filter(isSchemaRecord) : [];const getSchemaVariants = (schema: JsonSchema | undefined): ReadonlyArray<JsonSchema> => [- ...((Array.isArray(schema?.anyOf) ? schema.anyOf : []) as JsonSchema[]),- ...((Array.isArray(schema?.oneOf) ? schema.oneOf : []) as JsonSchema[]),- ...((Array.isArray(schema?.allOf) ? schema.allOf : []) as JsonSchema[]),+ ...getSchemaVariant(schema?.anyOf),+ ...getSchemaVariant(schema?.oneOf),+ ...getSchemaVariant(schema?.allOf),];const transformSchema = (schema: JsonSchema): JsonSchema => {@@ -132,10 +142,14 @@ export const findFileUploadablePaths = (});};-const readFileFromUrl = async (url: string) => {+const readFileFromUrl = async (path: Path.Path, url: string) => {const response = await fetch(url);if (!response.ok) {- throw new Error(`Failed to fetch file: ${response.statusText}`);+ throw new ToolFileUploadError({+ message: `Failed to fetch file: ${response.statusText}`,+ reason: 'source-fetch',+ status: response.status,+ });}const bytes = new Uint8Array(await response.arrayBuffer());@@ -149,7 +163,18 @@ const readFileFromUrl = async (url: string) => {};};-const readFileFromDisk = async (filePath: string) => {+// Runs the FileSystem read to completion for the plain-async pipeline above.+// A failed read rejects with the underlying platform error (not a FiberFailure+// wrapper), matching this module's throw-based error contract.+const readLocalFileBytes = (fs: FileSystem.FileSystem, filePath: string): Promise<Uint8Array> =>+ Effect.runPromiseExit(fs.readFile(filePath)).then(exit =>+ Exit.match(exit, {+ onFailure: cause => Promise.reject<Uint8Array>(Cause.squash(cause)),+ onSuccess: bytes => Promise.resolve(bytes),+ })+ );++const readFileFromDisk = async (fs: FileSystem.FileSystem, path: Path.Path, filePath: string) => {// Enforce the sensitive-path denylist at the lowest-level local read, so any// caller of this reader (not just `uploadToolInputFiles`) is protected. This// is the single canonical guard shared with `@composio/core`; without it the@@ -169,13 +194,19 @@ const readFileFromDisk = async (filePath: string) => {'pass the copy instead.',});return {- bytes: new Uint8Array(await fs.readFile(filePath)),+ // Copy into a fresh ArrayBuffer-backed view: `fetch` bodies reject the+ // wider ArrayBufferLike-backed Uint8Array that FileSystem returns.+ bytes: new Uint8Array(await readLocalFileBytes(fs, filePath)),fileName: path.basename(filePath),mimeType: 'application/octet-stream',};};-const readUploadSource = async (file: string | File) => {+const readUploadSource = async (+ fs: FileSystem.FileSystem,+ path: Path.Path,+ file: string | File+) => {if (isFileLike(file)) {return {bytes: new Uint8Array(await file.arrayBuffer()),@@ -185,23 +216,28 @@ const readUploadSource = async (file: string | File) => {}if (typeof file === 'string' && /^https?:\/\//i.test(file)) {- return readFileFromUrl(file);+ return readFileFromUrl(path, file);}if (typeof file === 'string') {- return readFileFromDisk(file);+ return readFileFromDisk(fs, path, file);}- throw new Error('Unsupported upload source');+ throw new ToolFileUploadError({+ message: 'Unsupported upload source',+ reason: 'unsupported-source',+ });};const uploadFile = async (params: {+ readonly fs: FileSystem.FileSystem;+ readonly path: Path.Path;readonly file: string | File;readonly toolSlug: string;readonly toolkitSlug: string;readonly client: RawComposioClient;}) => {- const fileData = await readUploadSource(params.file);+ const fileData = await readUploadSource(params.fs, params.path, params.file);const { createHash } = await import('node:crypto');const md5 = createHash('md5').update(fileData.bytes).digest('hex');const presigned = await params.client.files.createPresignedURL({@@ -222,7 +258,11 @@ const uploadFile = async (params: {});if (!uploadResponse.ok) {- throw new Error(`Failed to upload file to S3: ${uploadResponse.statusText}`);+ throw new ToolFileUploadError({+ message: `Failed to upload file to S3: ${uploadResponse.statusText}`,+ reason: 'upload',+ status: uploadResponse.status,+ });}return {@@ -236,6 +276,8 @@ const hydrateFileUploads = async (value: unknown,schema: JsonSchema | undefined,ctx: {+ readonly fs: FileSystem.FileSystem;+ readonly path: Path.Path;readonly toolSlug: string;readonly toolkitSlug: string;readonly client: RawComposioClient;@@ -247,6 +289,8 @@ const hydrateFileUploads = async (}return uploadFile({+ fs: ctx.fs,+ path: ctx.path,file: value,toolSlug: ctx.toolSlug,toolkitSlug: ctx.toolkitSlug,@@ -263,15 +307,14 @@ const hydrateFileUploads = async (return nextValue;}- if (isSchemaRecord(schema?.properties) && isRecord(value)) {+ if (isSchemaRecord(schema?.properties) && Predicate.isRecord(value)) {+ const properties = schema.properties;const entries = await Promise.all(Object.entries(value).map(async ([key, entryValue]) => [key,await hydrateFileUploads(entryValue,- isSchemaRecord((schema.properties as Record<string, unknown>)[key])- ? ((schema.properties as Record<string, unknown>)[key] as JsonSchema)- : undefined,+ isSchemaRecord(properties[key]) ? properties[key] : undefined,ctx),])@@ -293,6 +336,8 @@ const hydrateFileUploads = async (};export const uploadToolInputFiles = async (params: {+ readonly fs: FileSystem.FileSystem;+ readonly path: Path.Path;readonly toolSlug: string;readonly arguments_: Record<string, unknown>;readonly inputSchema: JsonSchema;@@ -304,10 +349,12 @@ export const uploadToolInputFiles = async (params: {}const hydrated = await hydrateFileUploads(params.arguments_, params.inputSchema, {+ fs: params.fs,+ path: params.path,toolSlug: params.toolSlug,toolkitSlug: params.toolkitSlug ?? toolkitFromToolSlug(params.toolSlug) ?? 'unknown',client: params.client,});- return isRecord(hydrated) ? hydrated : params.arguments_;+ return Predicate.isRecord(hydrated) ? hydrated : params.arguments_;};diff --git a/ts/packages/cli/src/services/tool-permissions.ts b/ts/packages/cli/src/services/tool-permissions.tsindex a404f8bce..5e6677496 100644--- a/ts/packages/cli/src/services/tool-permissions.ts+++ b/ts/packages/cli/src/services/tool-permissions.ts@@ -1,12 +1,11 @@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 { FileSystem, Path } from '@effect/platform';import open from 'open';import { detectCliPlatform } from '@composio/cli-local-tools';-import { Effect, Option, Schema } from 'effect';+import { Data, Effect, Option, Record as EffectRecord, Schema } from 'effect';+import { JsonRecordSchema } from 'src/effects/json';import { resolveCliConfigDirectorySync } from 'src/services/cli-user-config';+import { collectDecodedEntries } from 'src/utils/collect-decoded-entries';import {detectNativeUiCallerAgent,isInteractivePermissionUiDisabled,@@ -28,55 +27,52 @@ const ALLOW_FOR_DURATION_LABEL = '1 hr';const ALLOW_FOR_DURATION_MS = 60 * 60 * 1000;const NO_CONNECTED_ACCOUNT = '__none__';-export type PermissionDefaultMode = 'allow_all' | 'ask_every_call' | 'ask_once_per_session';-export type PermissionOverrideState = 'always_allow' | 'always_deny' | 'ask_once' | 'ask_always';export type PermissionDecision = 'allow_once' | 'allow_session' | 'deny';export type PermissionApprovalStatus ='always_approved' | 'cached_approved' | 'approved_once' | 'approved_for_session';export type PermissionGateResult ={ readonly approvalStatus: PermissionApprovalStatus } | undefined;-export interface ToolRouterPermissionsConfig {- readonly default: PermissionDefaultMode;- readonly overrides?: Readonly<Record<string, PermissionOverrideState>>;-}--export interface ConsumerPermissionSnapshot {- readonly orgId: string;- readonly projectId: string;- readonly consumerUserId: string;- readonly enhancedControlsEnabled: boolean;- readonly permissions?: ToolRouterPermissionsConfig;- readonly connectedAccountIds: ReadonlyArray<string>;- readonly fetchedAt: number;-}--interface CachedAllowDecision {- readonly expiresAt: number;-}--interface CacheFile {- readonly entries: Readonly<Record<string, ConsumerPermissionSnapshot>>;- readonly allowEntries?: Readonly<Record<string, CachedAllowDecision>>;-}--const PermissionDefaultModeSchema = Schema.Literal(+const PermissionDefaultModeLiteralSchema = Schema.Literal('allow_all','ask_every_call','ask_once_per_session');-const PermissionOverrideStateSchema = Schema.Literal(+const PermissionOverrideStateLiteralSchema = Schema.Literal('always_allow','always_deny','ask_once','ask_always');+const isPermissionDefaultMode = Schema.is(PermissionDefaultModeLiteralSchema);+const isPermissionOverrideState = Schema.is(PermissionOverrideStateLiteralSchema);++// The permissions API can add modes before every installed CLI has upgraded.+// Preserve validation without failing open during that version-skew window:+// unknown defaults and overrides decode to their interactive safe equivalents.+const PermissionDefaultModeSchema = Schema.String.pipe(+ Schema.transform(PermissionDefaultModeLiteralSchema, {+ decode: value => (isPermissionDefaultMode(value) ? value : 'ask_every_call'),+ encode: value => value,+ strict: true,+ })+);+const PermissionOverrideStateSchema = Schema.String.pipe(+ Schema.transform(PermissionOverrideStateLiteralSchema, {+ decode: value => (isPermissionOverrideState(value) ? value : 'ask_always'),+ encode: value => value,+ strict: true,+ })+);const ToolRouterPermissionsConfigSchema = Schema.Struct({default: PermissionDefaultModeSchema,overrides: Schema.optional(Schema.Record({ key: Schema.String, value: PermissionOverrideStateSchema })),});+export const decodeToolRouterPermissionsConfig = Schema.decodeUnknownOption(+ ToolRouterPermissionsConfigSchema+);const ConsumerPermissionSnapshotSchema = Schema.Struct({orgId: Schema.String,projectId: Schema.String,@@ -86,35 +82,40 @@ const ConsumerPermissionSnapshotSchema = Schema.Struct({connectedAccountIds: Schema.Array(Schema.String),fetchedAt: Schema.Number,});-const CachedAllowDecisionSchema = Schema.Struct({- expiresAt: Schema.Number,+const CachedAllowDecisionSchema = Schema.Struct({ expiresAt: Schema.Number });+const PermissionResolveResponseSchema = Schema.Struct({+ experimental: Schema.optional(+ Schema.Struct({ permissions: Schema.optional(ToolRouterPermissionsConfigSchema) })+ ),+});+const ConsumerConfigResponseSchema = Schema.Struct({+ enhanced_controls: Schema.optional(Schema.Boolean),+ enhancedControls: Schema.optional(Schema.Boolean),});-const UnknownRecordSchema = Schema.Record({ key: Schema.String, value: Schema.Unknown });+export type PermissionDefaultMode = typeof PermissionDefaultModeSchema.Type;+export type PermissionOverrideState = typeof PermissionOverrideStateSchema.Type;+export type ToolRouterPermissionsConfig = typeof ToolRouterPermissionsConfigSchema.Type;+export type ConsumerPermissionSnapshot = typeof ConsumerPermissionSnapshotSchema.Type;+type CachedAllowDecision = typeof CachedAllowDecisionSchema.Type;+// Decoding of the cache file is per-entry (decodeCacheShell + decodeSnapshotEntry /+// decodeAllowEntry below), so the file shape only needs a type, not a schema value.+type CacheFile = {+ readonly entries: Readonly<Record<string, ConsumerPermissionSnapshot>>;+ readonly allowEntries?: Readonly<Record<string, CachedAllowDecision>> | undefined;+};+type ConsumerConfigResponse = typeof ConsumerConfigResponseSchema.Type;const decodeCacheShell = Schema.decodeUnknownOption(Schema.parseJson(Schema.Struct({- entries: Schema.optional(UnknownRecordSchema),- allowEntries: Schema.optional(UnknownRecordSchema),+ entries: Schema.optional(JsonRecordSchema),+ allowEntries: Schema.optional(JsonRecordSchema),})));const decodeSnapshotEntry = Schema.decodeUnknownOption(ConsumerPermissionSnapshotSchema);const decodeAllowEntry = Schema.decodeUnknownOption(CachedAllowDecisionSchema);-const collectDecodedEntries = <A>(- entries: Readonly<Record<string, unknown>> | undefined,- decode: (value: unknown) => Option.Option<A>-): Record<string, A> =>- Object.fromEntries(- Object.entries(entries ?? {}).flatMap(([key, value]) =>- Option.match(decode(value), {- onNone: () => [],- onSome: entry => [[key, entry] as const],- })- )- );-// Per-entry decode: one stale or version-skewed entry drops only itself.// Discarding the whole file would also wipe all cached allow decisions and// be persisted back on the next write.@@ -127,16 +128,37 @@ export const decodeCacheFileTolerant = (raw: string): CacheFile =>}),});-interface PermissionResolveResponse {- readonly experimental?: {- readonly permissions?: ToolRouterPermissionsConfig;- };-}+export class ToolPermissionDeniedError extends Data.TaggedError(+ 'services/ToolPermissionDeniedError'+)<{+ readonly toolSlug: string;+ readonly deniedBy: 'permissions' | 'user';+ readonly message: string;+}> {}-interface ConsumerConfigResponse {- readonly enhanced_controls?: boolean;- readonly enhancedControls?: boolean;-}+export class ToolPermissionsRequestError extends Data.TaggedError(+ 'services/ToolPermissionsRequestError'+)<{+ readonly path: string;+ readonly message: string;+ readonly cause: unknown;+}> {}++export class ToolPermissionsCacheError extends Data.TaggedError(+ 'services/ToolPermissionsCacheError'+)<{+ readonly operation: 'read' | 'write';+ readonly message: string;+ readonly cause: unknown;+}> {}++export class ToolPermissionPromptError extends Data.TaggedError(+ 'services/ToolPermissionPromptError'+)<{+ readonly toolSlug: string;+ readonly message: string;+ readonly cause: unknown;+}> {}interface GateParams {readonly toolSlug: string;@@ -147,7 +169,7 @@ interface GateParams {const allowDecisionMemoryCache = new Map<string, number>();-const cachePath = () => path.join(resolveCliConfigDirectorySync(), CACHE_FILE_NAME);+const cachePath = (path: Path.Path) => path.join(resolveCliConfigDirectorySync(), CACHE_FILE_NAME);const cacheKey = (params: { orgId: string; projectId: string; consumerUserId: string }) =>[params.orgId, params.projectId, params.consumerUserId].join(':');const normalizeBaseUrl = (baseURL: string) => baseURL.replace(/\/$/, '');@@ -159,71 +181,73 @@ const uniq = (values: ReadonlyArray<string | undefined>) => [const pruneAllowEntries = (entries: Readonly<Record<string, CachedAllowDecision>> | undefined,now = Date.now()-): Record<string, CachedAllowDecision> => {- const freshEntries: Record<string, CachedAllowDecision> = {};- for (const [key, entry] of Object.entries(entries ?? {})) {- if (typeof entry.expiresAt === 'number' && entry.expiresAt > now) {- freshEntries[key] = entry;- }- }- return freshEntries;-};--const readCacheFile = async (): Promise<CacheFile> => {- try {- const raw = await fs.readFile(cachePath(), 'utf8');- const parsed = decodeCacheFileTolerant(raw);- return {- entries: parsed.entries,- allowEntries: pruneAllowEntries(parsed.allowEntries),- };- } catch {- return { entries: {} };- }-};--const writeCacheFile = async (cache: CacheFile): Promise<void> => {- const targetPath = cachePath();- await fs.mkdir(path.dirname(targetPath), { recursive: true });-- const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${crypto.randomUUID()}.tmp`;- try {- await fs.writeFile(- tempPath,- `${JSON.stringify(- {- entries: cache.entries,- allowEntries: pruneAllowEntries(cache.allowEntries),- } satisfies CacheFile,- null,- 2- )}\n`,- 'utf8'- );- await fs.rename(tempPath, targetPath);- } catch (error) {- await fs.rm(tempPath, { force: true }).catch(() => undefined);- throw error;- }-};+): Record<string, CachedAllowDecision> =>+ EffectRecord.filter(+ entries ?? {},+ entry => typeof entry.expiresAt === 'number' && entry.expiresAt > now+ );-let cacheWriteQueue: Promise<void> = Promise.resolve();+// A missing or unreadable cache file degrades to an empty cache.+const readCacheFile = (fs: FileSystem.FileSystem, path: Path.Path): Effect.Effect<CacheFile> =>+ fs.readFileString(cachePath(path)).pipe(+ Effect.map((raw): CacheFile => {+ const parsed = decodeCacheFileTolerant(raw);+ return {+ entries: parsed.entries,+ allowEntries: pruneAllowEntries(parsed.allowEntries),+ };+ }),+ Effect.orElseSucceed((): CacheFile => ({ entries: {} }))+ );-const updateCacheFile = async (- update: (current: CacheFile) => CacheFile | Promise<CacheFile>-): Promise<void> => {- const previous = cacheWriteQueue.catch(() => undefined);- const next = previous.then(async () => {- const current = await readCacheFile();- await writeCacheFile(await update(current));+const writeCacheFile = (fs: FileSystem.FileSystem, path: Path.Path, cache: CacheFile) =>+ Effect.gen(function* () {+ const targetPath = cachePath(path);+ yield* fs.makeDirectory(path.dirname(targetPath), { recursive: true });++ const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${crypto.randomUUID()}.tmp`;+ // Atomic write: on failure the temp file is dropped (best effort) and the+ // original error is surfaced.+ yield* fs+ .writeFileString(+ tempPath,+ `${JSON.stringify(+ {+ entries: cache.entries,+ allowEntries: pruneAllowEntries(cache.allowEntries),+ } satisfies CacheFile,+ null,+ 2+ )}\n`+ )+ .pipe(+ Effect.andThen(fs.rename(tempPath, targetPath)),+ Effect.onError(() => fs.remove(tempPath, { force: true }).pipe(Effect.ignore))+ );});- cacheWriteQueue = next.catch(() => undefined);- await next;-};+// Serializes the read-modify-write cycles on the cache file so concurrent+// writers cannot interleave (the same role the previous promise write queue+// played for the plain async helpers).+const cacheWriteSemaphore = Effect.unsafeMakeSemaphore(1);++const updateCacheFile = (+ fs: FileSystem.FileSystem,+ path: Path.Path,+ update: (current: CacheFile) => CacheFile+) =>+ cacheWriteSemaphore.withPermits(1)(+ readCacheFile(fs, path).pipe(+ Effect.flatMap(current => writeCacheFile(fs, path, update(current)))+ )+ );-const writeCacheEntry = async (entry: ConsumerPermissionSnapshot): Promise<void> =>- updateCacheFile(current => ({+const writeCacheEntry = (+ fs: FileSystem.FileSystem,+ path: Path.Path,+ entry: ConsumerPermissionSnapshot+) =>+ updateCacheFile(fs, path, current => ({entries: {...current.entries,[cacheKey(entry)]: entry,@@ -231,14 +255,16 @@ const writeCacheEntry = async (entry: ConsumerPermissionSnapshot): Promise<void>allowEntries: current.allowEntries,}));-const readCachedEntry = async (params: {- orgId: string;- projectId: string;- consumerUserId: string;-}): Promise<ConsumerPermissionSnapshot | undefined> => {- const cache = await readCacheFile();- return cache.entries[cacheKey(params)];-};+const readCachedEntry = (+ fs: FileSystem.FileSystem,+ path: Path.Path,+ params: {+ orgId: string;+ projectId: string;+ consumerUserId: string;+ }+): Effect.Effect<ConsumerPermissionSnapshot | undefined> =>+ readCacheFile(fs, path).pipe(Effect.map(cache => cache.entries[cacheKey(params)]));const isFreshForAccounts = (entry: ConsumerPermissionSnapshot | undefined,@@ -253,23 +279,26 @@ const isFreshForAccounts = (const readEnhancedControlsFlag = (payload: ConsumerConfigResponse): boolean =>payload.enhanced_controls === true || payload.enhancedControls === true;-const fetchJson = async <T>({- baseURL,- apiKey,- orgId,- projectId,- path,- method = 'GET',- body,-}: {- readonly baseURL: string;- readonly apiKey: string;- readonly orgId: string;- readonly projectId: string;- readonly path: string;- readonly method?: 'GET' | 'POST';- readonly body?: unknown;-}): Promise<T> => {+const fetchJson = async <A, I>(+ responseSchema: Schema.Schema<A, I, never>,+ {+ baseURL,+ apiKey,+ orgId,+ projectId,+ path,+ method = 'GET',+ body,+ }: {+ readonly baseURL: string;+ readonly apiKey: string;+ readonly orgId: string;+ readonly projectId: string;+ readonly path: string;+ readonly method?: 'GET' | 'POST';+ readonly body?: unknown;+ }+): Promise<A> => {const response = await fetch(`${normalizeBaseUrl(baseURL)}${path}`, {method,redirect: 'error',@@ -286,7 +315,8 @@ const fetchJson = async <T>({if (!response.ok) {throw new Error(`HTTP ${response.status} ${response.statusText}`);}- return (await response.json()) as T;+ const responseBody: unknown = await response.json();+ return Schema.decodeUnknownPromise(responseSchema)(responseBody);};export const refreshConsumerPermissionSnapshot = (params: {@@ -296,20 +326,29 @@ export const refreshConsumerPermissionSnapshot = (params: {readonly connectedAccountIds?: ReadonlyArray<string>;}) =>Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;const userContext = yield* ComposioUserContext;const apiKey = Option.getOrUndefined(userContext.data.apiKey);if (!apiKey) return undefined;const connectedAccountIds = uniq(params.connectedAccountIds ?? []);- const config = yield* Effect.tryPromise(() =>- fetchJson<ConsumerConfigResponse>({- baseURL: userContext.data.baseURL,- apiKey,- orgId: params.orgId,- projectId: params.projectId,- path: '/api/v3.1/org/consumer/config',- })- );+ const config = yield* Effect.tryPromise({+ try: () =>+ fetchJson(ConsumerConfigResponseSchema, {+ baseURL: userContext.data.baseURL,+ apiKey,+ orgId: params.orgId,+ projectId: params.projectId,+ path: '/api/v3.1/org/consumer/config',+ }),+ catch: cause =>+ new ToolPermissionsRequestError({+ path: '/api/v3.1/org/consumer/config',+ message: 'Failed to fetch the org consumer config.',+ cause,+ }),+ });const platformSupportsEnhancedControls = isEnhancedControlsPlatformSupported();const remoteEnhancedControlsEnabled = readEnhancedControlsFlag(config);if (remoteEnhancedControlsEnabled && !platformSupportsEnhancedControls) {@@ -321,20 +360,27 @@ export const refreshConsumerPermissionSnapshot = (params: {remoteEnhancedControlsEnabled && platformSupportsEnhancedControls;const resolved =enhancedControlsEnabled && connectedAccountIds.length > 0- ? yield* Effect.tryPromise(() =>- fetchJson<PermissionResolveResponse>({- baseURL: userContext.data.baseURL,- apiKey,- orgId: params.orgId,- projectId: params.projectId,- path: '/api/v3.1/consumer/permissions/resolve',- method: 'POST',- body: {- connected_account_ids: connectedAccountIds,- default: 'ask_every_call',- },- })- ).pipe(+ ? yield* Effect.tryPromise({+ try: () =>+ fetchJson(PermissionResolveResponseSchema, {+ baseURL: userContext.data.baseURL,+ apiKey,+ orgId: params.orgId,+ projectId: params.projectId,+ path: '/api/v3.1/consumer/permissions/resolve',+ method: 'POST',+ body: {+ connected_account_ids: connectedAccountIds,+ default: 'ask_every_call',+ },+ }),+ catch: cause =>+ new ToolPermissionsRequestError({+ path: '/api/v3.1/consumer/permissions/resolve',+ message: 'Failed to resolve consumer permissions.',+ cause,+ }),+ }).pipe(Effect.map(response => ({permissions: response.experimental?.permissions,resolveFailed: false,@@ -342,7 +388,7 @@ export const refreshConsumerPermissionSnapshot = (params: {// The org said enhanced controls are ON but the policy could not// be learned: fail closed to the interactive default instead of// silently allowing tools the policy may explicitly deny.- Effect.catchAll(error =>+ Effect.catchTag('services/ToolPermissionsRequestError', error =>Effect.logDebug('Failed to resolve consumer permissions; failing closed to ask_every_call',error@@ -368,15 +414,22 @@ export const refreshConsumerPermissionSnapshot = (params: {// A fail-closed snapshot is not persisted, so a healthy fetch replaces it// on the next command instead of pinning ask_every_call for the TTL.if (!resolved.resolveFailed) {- yield* Effect.tryPromise(() => writeCacheEntry(snapshot)).pipe(- Effect.catchAll(error =>- Effect.logDebug('Failed to write the tool permissions cache', error)+ yield* writeCacheEntry(fs, path, snapshot).pipe(+ Effect.catchAll(cause =>+ Effect.logDebug(+ 'Failed to write the tool permissions cache',+ new ToolPermissionsCacheError({+ operation: 'write',+ message: 'Failed to write the tool permissions cache.',+ cause,+ })+ )));}return snapshot;}).pipe(- Effect.catchAll(error =>+ Effect.catchTag('services/ToolPermissionsRequestError', error =>Effect.gen(function* () {yield* Effect.logDebug('Failed to refresh consumer permission cache', error);return undefined;@@ -391,10 +444,12 @@ export const getConsumerPermissionSnapshot = (params: {readonly connectedAccountIds?: ReadonlyArray<string>;}) =>Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;const connectedAccountIds = uniq(params.connectedAccountIds ?? []);- const cached = yield* Effect.tryPromise(() => readCachedEntry(params)).pipe(- Effect.catchAll(() => Effect.succeed(undefined))- );+ // Read failures are absorbed inside readCacheFile (empty cache), so an+ // unreadable cache file behaves exactly like a cache miss here.+ const cached = yield* readCachedEntry(fs, path, params);if (isFreshForAccounts(cached, connectedAccountIds)) {yield* refreshConsumerPermissionSnapshot({ ...params, connectedAccountIds }).pipe(@@ -422,15 +477,22 @@ export const getOrgEnhancedControlsStatus = (params: {const apiKey = Option.getOrUndefined(userContext.data.apiKey);if (!apiKey) return undefined;- const config = yield* Effect.tryPromise(() =>- fetchJson<ConsumerConfigResponse>({- baseURL: userContext.data.baseURL,- apiKey,- orgId: params.orgId,- projectId: params.projectId,- path: '/api/v3.1/org/consumer/config',- })- );+ const config = yield* Effect.tryPromise({+ try: () =>+ fetchJson(ConsumerConfigResponseSchema, {+ baseURL: userContext.data.baseURL,+ apiKey,+ orgId: params.orgId,+ projectId: params.projectId,+ path: '/api/v3.1/org/consumer/config',+ }),+ catch: cause =>+ new ToolPermissionsRequestError({+ path: '/api/v3.1/org/consumer/config',+ message: 'Failed to fetch the org consumer config.',+ cause,+ }),+ });const remoteEnabled = readEnhancedControlsFlag(config);const platformSupported = isEnhancedControlsPlatformSupported();return {@@ -439,7 +501,7 @@ export const getOrgEnhancedControlsStatus = (params: {platformSupported,};}).pipe(- Effect.catchAll(error =>+ Effect.catchTag('services/ToolPermissionsRequestError', error =>Effect.gen(function* () {yield* Effect.logDebug('Failed to read enhanced controls status', error);return undefined;@@ -493,29 +555,44 @@ const isAllowCachedInMemory = (cacheKey: string, now = Date.now()): boolean => {return true;};-const isAllowCached = async (cacheKey: string, now = Date.now()): Promise<boolean> => {- if (isAllowCachedInMemory(cacheKey, now)) return true;-- const cache = await readCacheFile();- const expiresAt = cache.allowEntries?.[cacheKey]?.expiresAt;- if (expiresAt === undefined || expiresAt <= now) return false;+const isAllowCached = (+ fs: FileSystem.FileSystem,+ path: Path.Path,+ cacheKey: string,+ now = Date.now()+): Effect.Effect<boolean> =>+ Effect.suspend(() => {+ if (isAllowCachedInMemory(cacheKey, now)) return Effect.succeed(true);- allowDecisionMemoryCache.set(cacheKey, expiresAt);- return true;-};+ return readCacheFile(fs, path).pipe(+ Effect.map(cache => {+ const expiresAt = cache.allowEntries?.[cacheKey]?.expiresAt;+ if (expiresAt === undefined || expiresAt <= now) return false;-const cacheAllowDecision = async (cacheKey: string, now = Date.now()): Promise<void> => {- const expiresAt = now + ALLOW_FOR_DURATION_MS;- allowDecisionMemoryCache.set(cacheKey, expiresAt);+ allowDecisionMemoryCache.set(cacheKey, expiresAt);+ return true;+ })+ );+ });- await updateCacheFile(current => ({- entries: current.entries,- allowEntries: {- ...current.allowEntries,- [cacheKey]: { expiresAt },- },- }));-};+const cacheAllowDecision = (+ fs: FileSystem.FileSystem,+ path: Path.Path,+ cacheKey: string,+ now = Date.now()+) =>+ Effect.suspend(() => {+ const expiresAt = now + ALLOW_FOR_DURATION_MS;+ allowDecisionMemoryCache.set(cacheKey, expiresAt);++ return updateCacheFile(fs, path, current => ({+ entries: current.entries,+ allowEntries: {+ ...current.allowEntries,+ [cacheKey]: { expiresAt },+ },+ }));+ });const escapeHtml = (value: string): string =>value.replace(/[&<>"']/g, char => {@@ -972,15 +1049,19 @@ export const gateToolExecution = (params: GateParams) =>return { approvalStatus: 'always_approved' } satisfies PermissionGateResult;}if (state === 'always_deny') {- return yield* Effect.fail(- new Error(`Tool execution denied by permissions: ${params.toolSlug}`)- );+ return yield* new ToolPermissionDeniedError({+ toolSlug: params.toolSlug,+ deniedBy: 'permissions',+ message: `Tool execution denied by permissions: ${params.toolSlug}`,+ });}+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;const cacheKey = allowCacheKey(params);- const hasCachedAllow = yield* Effect.tryPromise(() => isAllowCached(cacheKey)).pipe(- Effect.catchAll(() => Effect.succeed(false))- );+ // Read failures are absorbed inside readCacheFile (empty cache), so an+ // unreadable allow cache behaves exactly like "no cached allow decision".+ const hasCachedAllow = yield* isAllowCached(fs, path, cacheKey);if (hasCachedAllow) {return { approvalStatus: 'cached_approved' } satisfies PermissionGateResult;}@@ -988,28 +1069,46 @@ export const gateToolExecution = (params: GateParams) =>// Fail closed instead of spawning approval UI where nobody can answer it// (tests, CI). Cached allow decisions above still apply.if (yield* isInteractivePermissionUiDisabled) {- return yield* Effect.fail(- new Error(- `Tool execution requires interactive approval, but permission prompts are disabled in this environment (CI/VITEST, or COMPOSIO_DISABLE_PERMISSION_UI): ${params.toolSlug}`- )- );+ return yield* new ToolPermissionDeniedError({+ toolSlug: params.toolSlug,+ deniedBy: 'permissions',+ message: `Tool execution requires interactive approval, but permission prompts are disabled in this environment (CI/VITEST, or COMPOSIO_DISABLE_PERMISSION_UI): ${params.toolSlug}`,+ });}- const decision = yield* Effect.tryPromise(() =>- requestPermissionDecision({- toolSlug: params.toolSlug,- accountLabel: params.connectedAccountWordId,- })- );+ const decision = yield* Effect.tryPromise({+ try: () =>+ requestPermissionDecision({+ toolSlug: params.toolSlug,+ accountLabel: params.connectedAccountWordId,+ }),+ catch: cause =>+ new ToolPermissionPromptError({+ toolSlug: params.toolSlug,+ message: `Failed to collect a permission decision for: ${params.toolSlug}`,+ cause,+ }),+ });if (decision === 'deny') {- return yield* Effect.fail(new Error(`Tool execution denied by user: ${params.toolSlug}`));+ return yield* new ToolPermissionDeniedError({+ toolSlug: params.toolSlug,+ deniedBy: 'user',+ message: `Tool execution denied by user: ${params.toolSlug}`,+ });}const cachesAllowOnce = state === 'ask_once' || state === 'ask_once_per_session';if (decision === 'allow_session' || (cachesAllowOnce && decision === 'allow_once')) {- yield* Effect.tryPromise(() => cacheAllowDecision(cacheKey)).pipe(- Effect.catchAll(error =>- Effect.logDebug('Failed to cache tool permission allow decision', error)+ yield* cacheAllowDecision(fs, path, cacheKey).pipe(+ Effect.catchAll(cause =>+ Effect.logDebug(+ 'Failed to cache tool permission allow decision',+ new ToolPermissionsCacheError({+ operation: 'write',+ message: 'Failed to cache the tool permission allow decision.',+ cause,+ })+ )));}diff --git a/ts/packages/cli/src/services/tool-router-session-connections.ts b/ts/packages/cli/src/services/tool-router-session-connections.tsindex 15768ec49..c2d4041b5 100644--- a/ts/packages/cli/src/services/tool-router-session-connections.ts+++ b/ts/packages/cli/src/services/tool-router-session-connections.ts@@ -1,11 +1,20 @@-import { Effect } from 'effect';+import { Data, Effect, Schema } from 'effect';import type { Composio } from '@composio/client';+import { ConnectedAccountItem } from 'src/models/connected-accounts';import {+ compareNewestFirst,groupCachedConnectedAccountsByToolkit,resolveDefaultConnectedAccountsByToolkit,type SelectableConnectedAccount,} from 'src/services/connected-account-selection';+export class ToolRouterSessionConnectionsError extends Data.TaggedError(+ 'services/ToolRouterSessionConnectionsError'+)<{+ readonly message: string;+ readonly cause: unknown;+}> {}+type RawConnectedAccount = {readonly id: string;readonly alias?: string | null;@@ -40,41 +49,17 @@ export type ToolRouterSessionConnectionContext = {>;};-const parseTimestamp = (value?: string | null): number => {- if (!value) return 0;- const parsed = Date.parse(value);- return Number.isFinite(parsed) ? parsed : 0;-};+// Derived from the model schema so the known-status list can't drift from it.+const isKnownConnectedAccountStatus = Schema.is(ConnectedAccountItem.fields.status);const normalizeConnectedAccountStatus = (status?: string | null-): SelectableConnectedAccount['status'] => {- switch (status) {- case 'INITIALIZING':- case 'INITIATED':- case 'ACTIVE':- case 'FAILED':- case 'EXPIRED':- case 'INACTIVE':- case 'REVOKED':- return status;- default:- // Sentinel — `'INACTIVE'` would falsely tag the account as user-disabled.- return 'UNKNOWN';- }-};+): SelectableConnectedAccount['status'] =>+ // Sentinel — `'INACTIVE'` would falsely tag the account as user-disabled.+ status != null && isKnownConnectedAccountStatus(status) ? status : 'UNKNOWN';-const isNewerAccount = (candidate: RawConnectedAccount, current: RawConnectedAccount): boolean => {- const candidateTimestamp = Math.max(- parseTimestamp(candidate.updated_at),- parseTimestamp(candidate.created_at)- );- const currentTimestamp = Math.max(- parseTimestamp(current.updated_at),- parseTimestamp(current.created_at)- );- return candidateTimestamp > currentTimestamp;-};+const isNewerAccount = (candidate: RawConnectedAccount, current: RawConnectedAccount): boolean =>+ compareNewestFirst(candidate, current) < 0;export const resolveToolRouterSessionConnections = (client: Composio,@@ -83,15 +68,21 @@ export const resolveToolRouterSessionConnections = (readonly toolkits?: ReadonlyArray<string>;}) =>- Effect.tryPromise(() =>- client.connectedAccounts.list({- user_ids: [userId],- statuses: ['ACTIVE'],- toolkit_slugs:- options?.toolkits && options.toolkits.length > 0 ? [...options.toolkits] : undefined,- limit: 1000,- })- ).pipe(+ Effect.tryPromise({+ try: () =>+ client.connectedAccounts.list({+ user_ids: [userId],+ statuses: ['ACTIVE'],+ toolkit_slugs:+ options?.toolkits && options.toolkits.length > 0 ? [...options.toolkits] : undefined,+ limit: 1000,+ }),+ catch: cause =>+ new ToolRouterSessionConnectionsError({+ message: `Failed to list connected accounts for user "${userId}".`,+ cause,+ }),+ }).pipe(Effect.map(response => {const items = (response.items ?? []) as ReadonlyArray<RawConnectedAccount>;const unknownStatuses = new Set<string>();diff --git a/ts/packages/cli/src/services/tools-executor.ts b/ts/packages/cli/src/services/tools-executor.tsindex 8a6800561..06336560c 100644--- a/ts/packages/cli/src/services/tools-executor.ts+++ b/ts/packages/cli/src/services/tools-executor.ts@@ -1,5 +1,5 @@import { FileSystem, Path } from '@effect/platform';-import { Context, Effect, Layer } from 'effect';+import { Context, Data, Effect, Layer } from 'effect';import type { Composio } from '@composio/client';import { executeLocalToolBySlug, resolveLocalTool } from '@composio/cli-local-tools';import type {@@ -15,7 +15,8 @@ import {mapComposioError,} from 'src/services/composio-error-overrides';import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';-import { uploadToolInputFiles } from 'src/services/tool-file-uploads';+import { ToolFileUploadError, uploadToolInputFiles } from 'src/services/tool-file-uploads';+import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';import type { NodeOs } from 'src/services/node-os';import type { NodeProcess } from 'src/services/node-process';import type { ComposioUserContext } from 'src/services/user-context';@@ -70,6 +71,12 @@ export interface ToolsExecutor {export const ToolsExecutor = Context.GenericTag<ToolsExecutor>('services/ToolsExecutor');+export class LocalToolsDisabledError extends Data.TaggedError('services/LocalToolsDisabledError')<{+ readonly toolSlug: string;+ readonly feature: string;+ readonly message: string;+}> {}+/*** Meta tool slugs handled by `session.executeMeta` instead of `session.execute`.*@@ -77,7 +84,7 @@ export const ToolsExecutor = Context.GenericTag<ToolsExecutor>('services/ToolsEx* `SessionExecuteMetaParams['slug']` union — a compile error will surface if* a slug is misspelled or if the API adds/removes a meta tool.*/-const META_TOOL_SLUG_LIST = [+const META_TOOL_SLUG_LIST: ReadonlyArray<SessionExecuteMetaParams['slug']> = ['COMPOSIO_SEARCH_TOOLS','COMPOSIO_MULTI_EXECUTE_TOOL','COMPOSIO_MANAGE_CONNECTIONS',@@ -85,7 +92,7 @@ const META_TOOL_SLUG_LIST = ['COMPOSIO_REMOTE_WORKBENCH','COMPOSIO_REMOTE_BASH_TOOL','COMPOSIO_GET_TOOL_SCHEMAS',-] as const satisfies ReadonlyArray<SessionExecuteMetaParams['slug']>;+];const META_TOOL_SLUGS: ReadonlySet<string> = new Set(META_TOOL_SLUG_LIST);@@ -155,21 +162,22 @@ export const ToolsExecutorLive = Layer.effect(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS);if (localToolResolution && !localToolsEnabled) {- return yield* Effect.fail(- new Error(- `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${slug}.`- )- );+ return yield* new LocalToolsDisabledError({+ toolSlug: slug,+ feature: CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,+ message: `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${slug}.`,+ });}if (localToolResolution) {- const localResult = yield* Effect.tryPromise(() =>- executeLocalToolBySlug(slug, params.arguments)- );+ const localResult = yield* Effect.tryPromise({+ try: () => executeLocalToolBySlug(slug, params.arguments),+ catch: cause => cause,+ });if (localResult) {return {successful: true,- data: localResult as Record<string, unknown>,+ data: localResult,error: null,logId: '',} satisfies ToolExecuteResponse;@@ -190,7 +198,7 @@ export const ToolsExecutorLive = Layer.effect(connectedAccounts: params.connectedAccounts,cacheScope: params.cacheScope,});- const toolkitSlug = slug.split('_')[0]?.toLowerCase();+ const toolkitSlug = toolkitFromToolSlug(slug);const permissionGateResult = yield* gateToolExecution({toolSlug: slug,connectedAccountId: toolkitSlug ? connectedAccounts?.[toolkitSlug] : undefined,@@ -199,6 +207,8 @@ export const ToolsExecutorLive = Layer.effect(: undefined,snapshot: permissionSnapshot,});+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;const normalizedArguments = isMetaToolSlug(slug)? params.arguments: yield* getOrFetchToolInputDefinition(slug).pipe(@@ -208,42 +218,55 @@ export const ToolsExecutorLive = Layer.effect(return Effect.succeed(params.arguments);}- return Effect.tryPromise(() =>- uploadToolInputFiles({- toolSlug: slug,- arguments_: params.arguments,- inputSchema: definition.schema,- client: resolvedClient,- })- );+ return Effect.tryPromise({+ try: () =>+ uploadToolInputFiles({+ fs,+ path,+ toolSlug: slug,+ arguments_: params.arguments,+ inputSchema: definition.schema,+ client: resolvedClient,+ }),+ catch: cause =>+ cause instanceof ToolFileUploadError+ ? cause+ : new ToolFileUploadError({+ cause,+ message: cause instanceof Error ? cause.message : String(cause),+ reason: 'source-read',+ }),+ });}));const raw: SessionExecuteResponse | SessionExecuteMetaResponse = yield* Effect.tryPromise(- () => {- if (isMetaToolSlug(slug)) {- return resolvedClient.toolRouter.session.executeMeta(sessionId, {- slug,+ {+ try: () => {+ if (isMetaToolSlug(slug)) {+ return resolvedClient.toolRouter.session.executeMeta(sessionId, {+ slug,+ arguments: normalizedArguments,+ });+ }+ const executePayload = {+ tool_slug: slug,arguments: normalizedArguments,- });- }- const executePayload = {- tool_slug: slug,- arguments: normalizedArguments,- ...(localExperimentalPayload ? { experimental: localExperimentalPayload } : {}),- };- return resolvedClient.toolRouter.session.execute(sessionId, executePayload);+ ...(localExperimentalPayload ? { experimental: localExperimentalPayload } : {}),+ };+ return resolvedClient.toolRouter.session.execute(sessionId, executePayload);+ },+ catch: cause => cause,});return normalizeResponse(raw, permissionGateResult);}).pipe(- Effect.catchAll((error): Effect.Effect<never, unknown> => {+ Effect.mapError(error => {const mapped = mapComposioError({ error, toolSlug: slug });- if (mapped.normalized instanceof ComposioNoActiveConnectionError) {- return Effect.fail(mapped.normalized);- }- return Effect.fail(error);+ return mapped.normalized instanceof ComposioNoActiveConnectionError+ ? mapped.normalized+ : error;})),});diff --git a/ts/packages/cli/src/services/triggers-realtime.ts b/ts/packages/cli/src/services/triggers-realtime.tsindex 220bbcb8a..3b08555b1 100644--- a/ts/packages/cli/src/services/triggers-realtime.ts+++ b/ts/packages/cli/src/services/triggers-realtime.ts@@ -1,4 +1,5 @@-import { Data, Effect, Runtime } from 'effect';+import { Data, Effect, Either, Option, Runtime, Schema } from 'effect';+import { JsonRecordSchema } from 'src/effects/json';import {ComposioClientSingleton,ComposioSessionRepository,@@ -6,58 +7,17 @@ import {type CliRealtimeCredentialsResponse,} from 'src/services/composio-clients';-type RawRealtimeEvent = Record<string, unknown>;+const RawRealtimeEvent = JsonRecordSchema;+type RawRealtimeEvent = typeof RawRealtimeEvent.Type;+const decodeRawRealtimeEvent = Schema.decodeUnknownOption(RawRealtimeEvent);-type PusherAuthOptions = {- params?: {- channel_name?: string;- socket_id?: string;- channelName?: string;- socketId?: string;- };- channel_name?: string;- socket_id?: string;- channelName?: string;- socketId?: string;-};--type PusherAuthCallback = (error: unknown, data?: unknown) => void;--type PusherChannel = {- bind: (event: string, callback: (data: unknown) => void) => void;- bind_global?: (callback: (eventName: string, data: unknown) => void) => void;- unbind?: (event?: string, callback?: (data: unknown) => void) => void;- unbind_all?: () => void;-};--type PusherClient = {- subscribe: (channelName: string) => PusherChannel;- unsubscribe: (channelName: string) => void;- disconnect: () => void;- connection?: {- bind?: (event: string, callback: (data: unknown) => void) => void;- };-};--type PusherCtor = new (- key: string,- options: {- cluster: string;- channelAuthorization: {- customHandler: (- authOptions: PusherAuthOptions,- callback?: PusherAuthCallback- ) => Promise<unknown> | void;- };- }-) => PusherClient;--type ChunkedRealtimeEvent = {- id: string;- index: number;- chunk: string;- final: boolean;-};+const ChunkedRealtimeEvent = Schema.Struct({+ id: Schema.String,+ index: Schema.Int,+ chunk: Schema.String,+ final: Schema.Boolean,+});+const decodeChunkedRealtimeEvent = Schema.decodeUnknownOption(ChunkedRealtimeEvent);export class TriggerRealtimeSubscriptionError extends Data.TaggedError('services/TriggerRealtimeSubscriptionError'@@ -104,21 +64,16 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(catch: subscriptionError('Failed to load the realtime client'),});- const Pusher = pusherModule.default as unknown as PusherCtor;+ const Pusher = pusherModule.default;const pusher = new Pusher(creds.pusher_key, {cluster: creds.pusher_cluster,channelAuthorization: {- customHandler: (authOptions: PusherAuthOptions, callback?: PusherAuthCallback) => {- const authParams = authOptions.params ?? authOptions;- const channel_name = authParams.channel_name ?? authParams.channelName;- const socket_id = authParams.socket_id ?? authParams.socketId;+ customHandler: (authOptions, callback) => {+ const channel_name = authOptions.channelName;+ const socket_id = authOptions.socketId;const doAuth = async () => {- if (!channel_name || !socket_id) {- throw new Error('Missing channel_name or socket_id for realtime auth');- }-const response = await Runtime.runPromise(runtime)(params.authRealtimeChannel({channel_name,@@ -134,14 +89,11 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(return normalizedResponse;};- if (callback) {- void doAuth()- .then(data => callback(null, data))- .catch(error => callback(error));- return;- }-- return doAuth();+ void doAuth()+ .then(data => callback(null, data))+ .catch(cause =>+ callback(cause instanceof Error ? cause : new Error(String(cause)), null)+ );},},});@@ -186,15 +138,16 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(}}, CHUNK_TTL_MS);- channel.bind('trigger_to_client', eventData => {- params.onEvent((eventData ?? {}) as RawRealtimeEvent);+ channel.bind('trigger_to_client', (eventData: unknown) => {+ params.onEvent(Option.getOrElse(decodeRawRealtimeEvent(eventData), () => ({})));});- channel.bind('chunked-trigger_to_client', data => {- const typed = data as ChunkedRealtimeEvent;- if (!typed || typeof typed.id !== 'string' || typeof typed.index !== 'number') {+ channel.bind('chunked-trigger_to_client', (data: unknown) => {+ const decoded = decodeChunkedRealtimeEvent(data);+ if (Option.isNone(decoded)) {return;}+ const typed = decoded.value;// Reject non-integer or out-of-range indices to prevent a single// malformed event from creating a massive sparse array.@@ -221,7 +174,10 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(});}- const current = chunkedEvents.get(typed.id)!;+ const current = chunkedEvents.get(typed.id);+ if (!current) {+ return;+ }current.chunks[typed.index] = typed.chunk;if (typed.final) {current.receivedFinal = true;@@ -235,13 +191,16 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(current.receivedFinal &¤t.chunks.length === Object.keys(current.chunks).length) {- try {- const parsed = JSON.parse(current.chunks.join('')) as RawRealtimeEvent;- params.onEvent(parsed);- } catch {- // Silently discard events that fail to parse after chunk reassembly- } finally {- chunkedEvents.delete(typed.id);+ const reassembled = current.chunks.join('');+ chunkedEvents.delete(typed.id);+ // Silently discard events that fail to parse after chunk+ // reassembly; the buffer entry is already cleared either way.+ const parsed = Either.try((): unknown => JSON.parse(reassembled)).pipe(+ Either.getRight,+ Option.flatMap(decodeRawRealtimeEvent)+ );+ if (Option.isSome(parsed)) {+ params.onEvent(parsed.value);}}});diff --git a/ts/packages/cli/src/services/user-context.ts b/ts/packages/cli/src/services/user-context.tsindex 7827c77b2..c8e9d0491 100644--- a/ts/packages/cli/src/services/user-context.ts+++ b/ts/packages/cli/src/services/user-context.ts@@ -1,11 +1,12 @@import { FileSystem, Path } from '@effect/platform';-import { Effect, Context, Layer, Option } from 'effect';+import { Effect, Context, Layer, Option, Predicate, Schema } from 'effect';import {type UserDataWithDefaults,UserData,userDataFromJSON,userDataToJSON,} from 'src/models/user-data';+import { JsonRecordSchema } from 'src/effects/json';import { setupCacheDir } from 'src/effects/setup-cache-dir';import * as constants from 'src/constants';import type { PlatformError } from '@effect/platform/Error';@@ -25,6 +26,16 @@ import { ComposioCliUserConfig, ComposioCliUserConfigLive } from 'src/services/c*/const KEYRING_SERVICE = 'com.composio.cli';const KEYRING_USER = 'default';+const decodeUserDataJsonObject = Schema.decodeUnknown(Schema.parseJson(JsonRecordSchema));++const normalizeEncodedUserData = (encoded: string, omitApiKey: boolean) =>+ Effect.gen(function* () {+ const decoded = yield* decodeUserDataJsonObject(encoded);+ const parsed = { ...decoded };+ if (parsed.project_id === null) delete parsed.project_id;+ if (omitApiKey && parsed.api_key === null) delete parsed.api_key;+ return JSON.stringify(parsed);+ });// -----------------------------------------------------------------------------// Keyring helpers — extracted from the generator so it stays within@@ -58,7 +69,7 @@ const writeKeyring = (deps: KeyringDeps, password: string) =>} else {yield* Effect.logDebug('Unexpected keyring error while writing api_key, falling back to plaintext: ' +- (err instanceof Error ? err.message : String(err))+ (Predicate.isError(err) ? err.message : String(err)));}return false;@@ -92,7 +103,7 @@ const readKeyring = (deps: KeyringDeps) =>} else {yield* Effect.logDebug('Unexpected keyring error while reading api_key, falling back to plaintext: ' +- (err instanceof Error ? err.message : String(err))+ (Predicate.isError(err) ? err.message : String(err)));}return Option.none<string>();@@ -119,7 +130,7 @@ const deleteKeyring = (deps: KeyringDeps) =>yield* Effect.logDebug(`Keyring delete skipped: ${err.kind}`);} else {yield* Effect.logWarning(- 'Keyring delete failed: ' + (err instanceof Error ? err.message : String(err))+ 'Keyring delete failed: ' + (Predicate.isError(err) ? err.message : String(err)));}})@@ -183,14 +194,7 @@ export const rawComposioUserContextLive = Layer.effect(? snapshot: { ...snapshot, apiKey: Option.none() };const encoded = yield* userDataToJSON(onDisk);- const normalized = JSON.stringify(- (() => {- const parsed = JSON.parse(encoded) as Record<string, unknown>;- if (parsed.project_id === null) delete parsed.project_id;- if (!useLegacyStorage && parsed.api_key === null) delete parsed.api_key;- return parsed;- })()- );+ const normalized = yield* normalizeEncodedUserData(encoded, !useLegacyStorage);yield* Effect.logDebug('Saving user data:', normalized);yield* fs.writeFileString(jsonUserConfigPath, normalized);});@@ -233,13 +237,7 @@ export const rawComposioUserContextLive = Layer.effect(// process restarts. We bypass writeJson's strip logic by// temporarily writing with the legacy-storage codepath.const onDisk = yield* userDataToJSON(next);- const normalized = JSON.stringify(- (() => {- const parsed = JSON.parse(onDisk) as Record<string, unknown>;- if (parsed.project_id === null) delete parsed.project_id;- return parsed;- })()- );+ const normalized = yield* normalizeEncodedUserData(onDisk, false);yield* Effect.logDebug('Saving user data (keyring fallback):', normalized);yield* fs.writeFileString(jsonUserConfigPath, normalized);}diff --git a/ts/packages/cli/src/utils/api-error-extraction.ts b/ts/packages/cli/src/utils/api-error-extraction.tsindex d176948bb..0388c7039 100644--- a/ts/packages/cli/src/utils/api-error-extraction.ts+++ b/ts/packages/cli/src/utils/api-error-extraction.ts@@ -59,27 +59,27 @@ export const extractMessage = (value: unknown, seen?: Set<unknown>): string | un// stores the API response body in .error (which itself has .error.message).// We prefer the deepest message because outer wrappers often have generic// messages like "An unknown error occurred in Effect.tryPromise".- if (value && typeof value === 'object') {+ if (Predicate.isObject(value)) {const visited = seen ?? new Set<unknown>();if (visited.has(value)) return undefined;visited.add(value);// Try .cause chain first (Effect's UnknownException → real SDK error)- if ('cause' in value) {- const causeMsg = extractMessage((value as { cause?: unknown }).cause, visited);+ if (Predicate.hasProperty(value, 'cause')) {+ const causeMsg = extractMessage(value.cause, visited);if (causeMsg) return causeMsg;}// Try .error chain (SDK error → API response body → nested .error.message)- if ('error' in value) {- const inner = (value as { error?: unknown }).error;+ if (Predicate.hasProperty(value, 'error')) {+ const inner = value.error;const innerMsg = extractMessage(inner, visited);if (innerMsg) return innerMsg;}// Fall back to the wrapper's own message- if ('message' in value && typeof (value as { message?: unknown }).message === 'string') {- return (value as { message: string }).message;+ if (Predicate.hasProperty(value, 'message') && Predicate.isString(value.message)) {+ return value.message;}}@@ -95,20 +95,20 @@ export const extractSlug = (value: unknown): string | undefined => {let current: unknown = value;const seen = new Set<unknown>();- while (current && typeof current === 'object' && !seen.has(current)) {+ while (Predicate.isObject(current) && !seen.has(current)) {seen.add(current);- if ('slug' in current && typeof (current as { slug?: unknown }).slug === 'string') {- return (current as { slug: string }).slug;+ if (Predicate.hasProperty(current, 'slug') && Predicate.isString(current.slug)) {+ return current.slug;}- if ('error' in current) {- current = (current as { error?: unknown }).error;+ if (Predicate.hasProperty(current, 'error')) {+ current = current.error;continue;}- if ('cause' in current) {- current = (current as { cause?: unknown }).cause;+ if (Predicate.hasProperty(current, 'cause')) {+ current = current.cause;continue;}@@ -137,7 +137,7 @@ export const extractApiErrorDetails = (value: unknown): ApiErrorDetails | undefiwhile (head < queue.length) {const current = queue[head++];- if (!current || typeof current !== 'object' || seen.has(current)) {+ if (!Predicate.isObject(current) || seen.has(current)) {continue;}seen.add(current);@@ -154,12 +154,12 @@ export const extractApiErrorDetails = (value: unknown): ApiErrorDetails | undefi}}- if ('error' in current) {- queue.push((current as { error?: unknown }).error);+ if (Predicate.hasProperty(current, 'error')) {+ queue.push(current.error);}- if ('cause' in current) {- queue.push((current as { cause?: unknown }).cause);+ if (Predicate.hasProperty(current, 'cause')) {+ queue.push(current.cause);}}diff --git a/ts/packages/cli/src/utils/collect-decoded-entries.ts b/ts/packages/cli/src/utils/collect-decoded-entries.tsnew file mode 100644index 000000000..f139e288e--- /dev/null+++ b/ts/packages/cli/src/utils/collect-decoded-entries.ts@@ -0,0 +1,21 @@+import { Option } from 'effect';++/**+ * Decode a record's entries one by one, keeping only the entries that decode+ * successfully. Used for tolerant cache-file reads: one stale or+ * version-skewed entry drops only itself instead of discarding the whole+ * file (which would also be persisted back on the next write, permanently+ * destroying the good entries).+ */+export const collectDecodedEntries = <A>(+ entries: Readonly<Record<string, unknown>> | undefined,+ decode: (value: unknown) => Option.Option<A>+): Record<string, A> =>+ Object.fromEntries(+ Object.entries(entries ?? {}).flatMap(([key, value]) =>+ Option.match(decode(value), {+ onNone: () => [],+ onSome: entry => [[key, entry] as const],+ })+ )+ );diff --git a/ts/packages/cli/test/src/cli-main.test.ts b/ts/packages/cli/test/src/cli-main.test.tsnew file mode 100644index 000000000..4f260fdf9--- /dev/null+++ b/ts/packages/cli/test/src/cli-main.test.ts@@ -0,0 +1,54 @@+import fs from 'node:fs';+import path from 'node:path';+import { spawnSync } from 'node:child_process';+import { describe, expect, it } from 'vitest';+import * as tempy from 'tempy';++describe('CLI process error handling', () => {+ it('prints unreported ToolExecutionError failures and exits non-zero', () => {+ const configDirectory = tempy.temporaryDirectory();+ fs.writeFileSync(+ path.join(configDirectory, 'config.json'),+ JSON.stringify({ experimental_features: { local_tools: true } })+ );+ fs.writeFileSync(+ path.join(configDirectory, 'user_data.json'),+ JSON.stringify({+ api_key: null,+ base_url: 'https://backend.composio.dev',+ web_url: 'https://platform.composio.dev',+ org_id: null,+ test_user_id: null,+ })+ );++ const result = spawnSync(+ 'bun',+ [+ 'run',+ 'src/bin.ts',+ 'execute',+ 'LOCAL_PEEKABOO_VERSION',+ '--file',+ '/tmp/does-not-matter',+ '-d',+ '{}',+ ],+ {+ cwd: process.cwd(),+ encoding: 'utf8',+ env: {+ ...process.env,+ CI: '1',+ NO_COLOR: '1',+ COMPOSIO_CACHE_DIR: configDirectory,+ },+ }+ );++ expect(result.status).toBe(1);+ expect(`${result.stdout}\n${result.stderr}`).toContain(+ '--file is not supported for local tools yet.'+ );+ });+});diff --git a/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts b/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.tsindex 45e850c72..6f4f7ca07 100644--- a/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts@@ -1,5 +1,6 @@import { describe, expect, layer } from '@effect/vitest';import { ConfigProvider, Console, Effect } from 'effect';+import { HelpDoc, ValidationError } from '@effect/cli';import { extendConfigProvider } from 'src/services/config';import { cli, TestLive, MockConsole } from 'test/__utils__';import type { TestLiveInput } from 'test/__utils__/services/test-layer';@@ -45,6 +46,12 @@ const makeConnectedAccountsData = (...overrides,});+const connectedAccountWithCredentialFields = {+ ...makeConnectedAccount(),+ state: { access_token: 'must-not-leak' },+ data: { refresh_token: 'must-not-leak' },+};+const testConfigProvider = ConfigProvider.fromMap(new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])).pipe(extendConfigProvider);@@ -271,6 +278,52 @@ describe('CLI: composio dev connected-accounts link', () => {);});+ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ connectedAccountsData: makeConnectedAccountsData(),+ fixture: 'global-test-user-id',+ })+ )('[Given] a blank --alias [Then] fails with a CLI validation error', it => {+ it.scoped('reports the invalid option value before making a link request', () =>+ Effect.gen(function* () {+ const error = yield* cli(['link', 'gmail', '--alias', ' ']).pipe(Effect.flip);++ expect(ValidationError.isValidationError(error)).toBe(true);+ if (!ValidationError.isValidationError(error)) return;+ expect(ValidationError.isInvalidValue(error)).toBe(true);+ expect(HelpDoc.toAnsiText(error.error)).toContain('`--alias` cannot be empty.');+ expect(vi.mocked(open)).not.toHaveBeenCalled();+ })+ );+ });++ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ connectedAccountsData: {+ items: [connectedAccountWithCredentialFields],+ },+ fixture: 'global-test-user-id',+ })+ )('[Given] raw credential fields [Then] --list emits only schema-approved fields', it => {+ it.scoped('strips state and data at the response boundary', () =>+ Effect.gen(function* () {+ yield* cli(['link', 'gmail', '--list']);++ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');+ expect(output).not.toContain('must-not-leak');+ expect(output).not.toContain('access_token');+ expect(output).not.toContain('refresh_token');+ expect(extractJsonObject(output)).toStrictEqual({+ toolkit: 'gmail',+ total: 1,+ items: [makeConnectedAccount()],+ });+ })+ );+ });+layer(TestLive({baseConfigProvider: testConfigProvider,diff --git a/ts/packages/cli/test/src/commands/listen.cmd.test.ts b/ts/packages/cli/test/src/commands/listen.cmd.test.tsindex 268971f4d..2207d3faa 100644--- a/ts/packages/cli/test/src/commands/listen.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/listen.cmd.test.ts@@ -1,5 +1,7 @@+import { ValidationError } from '@effect/cli';import { describe, expect, layer } from '@effect/vitest';-import { ConfigProvider, Effect } from 'effect';+import { Cause, ConfigProvider, Effect, Exit } from 'effect';+import { ListenCommandError } from 'src/commands/listen.cmd';import { extendConfigProvider } from 'src/services/config';import { ComposioCliUserConfig } from 'src/services/cli-user-config';import { cli, MockConsole, TestLive } from 'test/__utils__';@@ -8,6 +10,16 @@ const testConfigProvider = ConfigProvider.fromMap(new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])).pipe(extendConfigProvider);+const enableListen = Effect.gen(function* () {+ const config = yield* ComposioCliUserConfig;+ yield* config.update({+ experimentalFeatures: {+ ...config.raw.experimentalFeatures,+ listen: true,+ },+ });+});+describe('CLI: composio listen', () => {layer(TestLive({@@ -35,13 +47,7 @@ describe('CLI: composio listen', () => {'[Then] listens to top-level composio.* events without creating a temporary trigger',() =>Effect.gen(function* () {- const config = yield* ComposioCliUserConfig;- yield* config.update({- experimentalFeatures: {- ...config.raw.experimentalFeatures,- listen: true,- },- });+ yield* enableListen;yield* cli(['listen', 'composio.connected_account.expired', '--max-events', '1']);const lines = yield* MockConsole.getLines({ stripAnsi: true });@@ -106,13 +112,7 @@ describe('CLI: composio listen', () => {)(it => {it.scoped('[Then] keeps the temporary-trigger flow for trigger slugs', () =>Effect.gen(function* () {- const config = yield* ComposioCliUserConfig;- yield* config.update({- experimentalFeatures: {- ...config.raw.experimentalFeatures,- listen: true,- },- });+ yield* enableListen;yield* cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE', '--max-events', '1']);const lines = yield* MockConsole.getLines({ stripAnsi: true });@@ -124,4 +124,64 @@ describe('CLI: composio listen', () => {}));});++ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ })+ )('listen validation and domain failures', it => {+ it.scoped('reports malformed trigger params as CLI input validation', () =>+ Effect.gen(function* () {+ yield* enableListen;+ const exit = yield* Effect.exit(+ cli(['listen', 'composio.connected_account.expired', '--params', '[]'])+ );++ expect(Exit.isFailure(exit)).toBe(true);+ if (Exit.isFailure(exit)) {+ const failure = Cause.squash(exit.cause);+ expect(+ ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)+ ).toBe(true);+ }+ })+ );++ it.scoped('reports malformed timeout values as CLI input validation', () =>+ Effect.gen(function* () {+ yield* enableListen;+ const exit = yield* Effect.exit(+ cli(['listen', 'composio.connected_account.expired', '--timeout', 'eventually'])+ );++ expect(Exit.isFailure(exit)).toBe(true);+ if (Exit.isFailure(exit)) {+ const failure = Cause.squash(exit.cause);+ expect(+ ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)+ ).toBe(true);+ }+ })+ );++ it.scoped('reports a missing active connection as a structured domain failure', () =>+ Effect.gen(function* () {+ yield* enableListen;+ const exit = yield* Effect.exit(cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE']));++ expect(Exit.isFailure(exit)).toBe(true);+ if (Exit.isFailure(exit)) {+ const failure = Cause.squash(exit.cause);+ expect(failure).toBeInstanceOf(ListenCommandError);+ if (failure instanceof ListenCommandError) {+ expect(failure).toMatchObject({+ reason: 'connected_account_not_found',+ toolkitSlug: 'gmail',+ });+ }+ }+ })+ );+ });});diff --git a/ts/packages/cli/test/src/commands/local-tools.cmd.test.ts b/ts/packages/cli/test/src/commands/local-tools.cmd.test.tsindex a3881e20e..e1b364d4e 100644--- a/ts/packages/cli/test/src/commands/local-tools.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/local-tools.cmd.test.ts@@ -1,8 +1,10 @@import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';+import { ValidationError } from '@effect/cli';import { describe, expect, layer } from '@effect/vitest';-import { Effect } from 'effect';+import { Cause, Effect, Exit } from 'effect';+import { LocalToolsDoctorError } from 'src/commands/local-tools/commands/local-tools.doctor.cmd';import { cli, MockConsole, TestLive } from 'test/__utils__';const withLocalToolsPath = <A, E, R>(effect: Effect.Effect<A, E, R>) =>@@ -64,6 +66,52 @@ describe('CLI: composio local-tools', () => {}));+ it.scoped('[Given] an unknown configure selector [Then] reports CLI input validation', () =>+ Effect.gen(function* () {+ const exit = yield* Effect.exit(+ cli(['local-tools', 'configure', 'NOT_A_LOCAL_TOOL', '--disable'])+ );++ expect(Exit.isFailure(exit)).toBe(true);+ if (Exit.isFailure(exit)) {+ const failure = Cause.squash(exit.cause);+ expect(+ ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)+ ).toBe(true);+ }+ })+ );++ it.scoped(+ '[Given] strict doctor finds a disabled tool [Then] reports structured readiness',+ () =>+ withLocalToolsPath(+ Effect.gen(function* () {+ yield* cli(['local-tools', 'configure', 'CHROME_DEVTOOLS', '--disable']);+ const exit = yield* Effect.exit(+ cli([+ 'local-tools',+ 'doctor',+ '--toolkits',+ 'CHROME_DEVTOOLS',+ '--all-platforms',+ '--strict',+ ])+ );++ expect(Exit.isFailure(exit)).toBe(true);+ if (Exit.isFailure(exit)) {+ const failure = Cause.squash(exit.cause);+ expect(failure).toBeInstanceOf(LocalToolsDoctorError);+ if (failure instanceof LocalToolsDoctorError) {+ expect(failure.operation).toBe('strict');+ expect(failure.notReadyTools.length).toBeGreaterThan(0);+ }+ }+ })+ )+ );+it.scoped('[Given] meta --init --json [Then] writes local metadata file', () =>withLocalToolsPath(Effect.gen(function* () {diff --git a/ts/packages/cli/test/src/commands/login.cmd.test.ts b/ts/packages/cli/test/src/commands/login.cmd.test.tsindex b1b7fc0cb..168c1e0a6 100644--- a/ts/packages/cli/test/src/commands/login.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/login.cmd.test.ts@@ -1,6 +1,7 @@import { describe, expect, layer } from '@effect/vitest';import { vi, afterEach } from 'vitest';import { Effect, Option } from 'effect';+import { HelpDoc, ValidationError } from '@effect/cli';import path from 'node:path';import { FileSystem } from '@effect/platform';import { cli, MockConsole, TestLive } from 'test/__utils__';@@ -61,6 +62,27 @@ describe('CLI: composio login', () => {});});+ layer(TestLive())(it => {+ it.scoped('[Given] conflicting login options [Then] fails with a CLI validation error', () =>+ Effect.gen(function* () {+ const error = yield* cli([+ 'login',+ '--key',+ 'cli_session_key',+ '--user-api-key',+ 'uak_direct_key',+ ]).pipe(Effect.flip);++ expect(ValidationError.isValidationError(error)).toBe(true);+ if (!ValidationError.isValidationError(error)) return;+ expect(ValidationError.isInvalidValue(error)).toBe(true);+ expect(HelpDoc.toAnsiText(error.error)).toContain(+ 'Use either `--key` or `--user-api-key`, not both.'+ );+ })+ );+ });+layer(TestLive())(it => {it.scoped('[When] stdin is non-interactive [Then] login prints agent instructions', () =>Effect.gen(function* () {diff --git a/ts/packages/cli/test/src/commands/logs-cmd/format.test.ts b/ts/packages/cli/test/src/commands/logs-cmd/format.test.tsindex c71596015..c955e642f 100644--- a/ts/packages/cli/test/src/commands/logs-cmd/format.test.ts+++ b/ts/packages/cli/test/src/commands/logs-cmd/format.test.ts@@ -6,18 +6,21 @@ import {formatToolLogsTable,formatTriggerLogsTable,} from 'src/commands/logs-cmd/format';+import {+ decodeTriggerLogRecord,+ type TriggerLogRecord,+} from 'src/commands/logs-cmd/trigger-log-record';import { green, red } from 'src/ui/colors';-type TriggerLog = Logs.TriggerListResponse.Data;type ToolLog = Logs.ToolListResponse.Data;type ToolLogDetailed = Logs.ToolRetrieveResponse;-const makeTriggerLog = (createdAt: TriggerLog['createdAt'] | number): TriggerLog =>- ({+const makeTriggerLog = (createdAt: string | number): TriggerLogRecord =>+ decodeTriggerLogRecord({id: 'trigger_log_1',clientId: 'client_1',type: 'trigger',- createdAt: createdAt as TriggerLog['createdAt'],+ createdAt,status: 'success',appName: 'gmail',meta: {@@ -27,7 +30,7 @@ const makeTriggerLog = (createdAt: TriggerLog['createdAt'] | number): TriggerLog},entityId: 'entity_123',connectionId: 'conn_123',- }) as unknown as TriggerLog;+ });const makeToolLog = (createdAt: ToolLog['createdAt'] | null,@@ -156,19 +159,21 @@ describe('formatToolLogInfo', () => {describe('formatTriggerLogInfo', () => {it('[Given] trigger detailed log [Then] it renders key fields', () => {- const output = formatTriggerLogInfo({- id: 'trigger_log_1',- createdAt: 0,- status: 'success',- appName: 'gmail',- meta: {- triggerId: 'trigger_123',- triggerNanoId: 'ti_123',- triggerName: 'NEW_GMAIL_MESSAGE',- },- entityId: 'user_123',- connectionId: 'conn_123',- });+ const output = formatTriggerLogInfo(+ decodeTriggerLogRecord({+ id: 'trigger_log_1',+ createdAt: 0,+ status: 'success',+ appName: 'gmail',+ meta: {+ triggerId: 'trigger_123',+ triggerNanoId: 'ti_123',+ triggerName: 'NEW_GMAIL_MESSAGE',+ },+ entityId: 'user_123',+ connectionId: 'conn_123',+ })+ );expect(output).toContain('logId:');expect(output).toContain('trigger_log_1');@@ -183,7 +188,7 @@ describe('formatTriggerLogInfo', () => {});it('[Given] missing fields [Then] it renders fallback dashes', () => {- const output = formatTriggerLogInfo({});+ const output = formatTriggerLogInfo(decodeTriggerLogRecord({}));const plain = output.replace(/\x1b\[[0-9;]*m/g, '');expect(plain).toContain('logId: -');expect(plain).toContain('triggerId: -');@@ -193,21 +198,23 @@ describe('formatTriggerLogInfo', () => {});it('[Given] retrieve response wrapped under log [Then] it unwraps and renders values', () => {- const output = formatTriggerLogInfo({- log: {- id: 'log_QNzKGStH-ruD',- status: 'info',- appName: 'gmail',- createdAt: '2026-02-25T22:01:22.865Z',- entityId: 'pg-test-37ee710c-d5be-4775-91f2-a8e06b937d9b',- connectionId: 'ca_zkX9njO68E8A',- meta: {- triggerId: '77ac1dbf-6db0-4039-8dbe-e903b3f2057e',- triggerNanoId: 'ti_-nGUzD9N6JNf',- triggerName: 'GMAIL_NEW_GMAIL_MESSAGE',+ const output = formatTriggerLogInfo(+ decodeTriggerLogRecord({+ log: {+ id: 'log_QNzKGStH-ruD',+ status: 'info',+ appName: 'gmail',+ createdAt: '2026-02-25T22:01:22.865Z',+ entityId: 'pg-test-37ee710c-d5be-4775-91f2-a8e06b937d9b',+ connectionId: 'ca_zkX9njO68E8A',+ meta: {+ triggerId: '77ac1dbf-6db0-4039-8dbe-e903b3f2057e',+ triggerNanoId: 'ti_-nGUzD9N6JNf',+ triggerName: 'GMAIL_NEW_GMAIL_MESSAGE',+ },},- },- });+ })+ );expect(output).toContain('log_QNzKGStH-ruD');expect(output).toContain('77ac1dbf-6db0-4039-8dbe-e903b3f2057e');diff --git a/ts/packages/cli/test/src/commands/logs-cmd/logs.triggers.cmd.test.ts b/ts/packages/cli/test/src/commands/logs-cmd/logs.triggers.cmd.test.tsdeleted file mode 100644index 8ac1faebd..000000000--- a/ts/packages/cli/test/src/commands/logs-cmd/logs.triggers.cmd.test.ts+++ /dev/null@@ -1,47 +0,0 @@-import { describe, expect, it } from 'vitest';-import {- getTriggerLogRecord,- getTriggerPayload,- getTriggerResponse,- parseMaybeJson,-} from 'src/commands/logs-cmd/commands/logs.triggers.cmd';--describe('logs triggers detail helpers', () => {- it('[Given] retrieve response wrapper [Then] unwraps nested log record', () => {- const wrapped = {- log: {- id: 'log_123',- meta: { triggerId: 'trigger_123' },- },- } as Record<string, unknown>;-- expect(getTriggerLogRecord(wrapped)).toEqual({- id: 'log_123',- meta: { triggerId: 'trigger_123' },- });- });-- it('[Given] trigger payload in meta JSON string [Then] parses it to object', () => {- const payload = getTriggerPayload({- meta: {- triggerProviderPayload: '{"foo":"bar","count":2}',- },- });-- expect(payload).toEqual({ foo: 'bar', count: 2 });- });-- it('[Given] trigger response in meta JSON string [Then] parses it to object', () => {- const response = getTriggerResponse({- meta: {- triggerClientResponse: '{"status":"CANCELED"}',- },- });-- expect(response).toEqual({ status: 'CANCELED' });- });-- it('[Given] non-JSON string [Then] parseMaybeJson returns original value', () => {- expect(parseMaybeJson('not-json')).toBe('not-json');- });-});diff --git a/ts/packages/cli/test/src/commands/logs-cmd/trigger-log-record.test.ts b/ts/packages/cli/test/src/commands/logs-cmd/trigger-log-record.test.tsnew file mode 100644index 000000000..776bedc78--- /dev/null+++ b/ts/packages/cli/test/src/commands/logs-cmd/trigger-log-record.test.ts@@ -0,0 +1,182 @@+import { describe, expect, it } from 'vitest';+import {+ decodeTriggerLogRecord,+ emptyTriggerLogRecord,+ parseMaybeJson,+} from 'src/commands/logs-cmd/trigger-log-record';++describe('decodeTriggerLogRecord', () => {+ it('[Given] camelCase-only payload [Then] resolves detail and table fields', () => {+ const record = decodeTriggerLogRecord({+ id: 'log_1',+ appName: 'gmail',+ status: 'success',+ createdAt: '2026-02-25T22:01:22.865Z',+ entityId: 'user_1',+ connectionId: 'conn_1',+ triggerId: 'trigger_1',+ triggerNanoId: 'ti_1',+ triggerName: 'NEW_GMAIL_MESSAGE',+ });++ expect(record.id).toBe('log_1');+ expect(record.appName).toBe('gmail');+ expect(record.detail.logId).toBe('log_1');+ expect(record.detail.triggerId).toBe('trigger_1');+ expect(record.detail.triggerNanoId).toBe('ti_1');+ expect(record.detail.triggerName).toBe('NEW_GMAIL_MESSAGE');+ expect(record.detail.status).toBe('success');+ expect(record.detail.toolkit).toBe('gmail');+ expect(record.detail.connectionId).toBe('conn_1');+ expect(record.detail.entityId).toBe('user_1');+ expect(record.detail.createdAt).toBe('2026-02-25T22:01:22.865Z');+ expect(record.table.triggerId).toBe('ti_1');+ expect(record.table.triggerName).toBe('NEW_GMAIL_MESSAGE');+ });++ it('[Given] snake_case-only payload [Then] resolves the same fields', () => {+ const record = decodeTriggerLogRecord({+ log_id: 'log_2',+ trigger_id: 'trigger_2',+ trigger_nano_id: 'ti_2',+ trigger_name: 'SLACK_NEW_MESSAGE',+ toolkit_key: 'slack',+ connection_id: 'conn_2',+ entity_id: 'user_2',+ created_at: 1750000000000,+ });++ expect(record.detail.logId).toBe('log_2');+ expect(record.detail.triggerId).toBe('trigger_2');+ expect(record.detail.triggerNanoId).toBe('ti_2');+ expect(record.detail.triggerName).toBe('SLACK_NEW_MESSAGE');+ expect(record.detail.toolkit).toBe('slack');+ expect(record.detail.connectionId).toBe('conn_2');+ expect(record.detail.entityId).toBe('user_2');+ expect(record.detail.createdAt).toBe(1750000000000);+ expect(record.table.triggerId).toBe('ti_2');+ expect(record.table.triggerName).toBe('SLACK_NEW_MESSAGE');+ });++ it('[Given] aliases at meta and top level [Then] detail prefers top level while table prefers meta', () => {+ const record = decodeTriggerLogRecord({+ triggerId: 'top_trigger',+ triggerName: 'TOP_NAME',+ meta: {+ triggerId: 'meta_trigger',+ triggerNanoId: 'ti_meta',+ triggerName: 'META_NAME',+ },+ });++ expect(record.detail.triggerId).toBe('top_trigger');+ expect(record.detail.triggerName).toBe('TOP_NAME');+ // Nano id under meta beats every plain trigger id in the table column.+ expect(record.table.triggerId).toBe('ti_meta');+ expect(record.table.triggerName).toBe('META_NAME');+ });++ it('[Given] meta-only aliases [Then] detail falls back to meta values', () => {+ const record = decodeTriggerLogRecord({+ meta: {+ id: 'meta_id',+ triggerId: 'meta_trigger',+ trigger_name: 'META_NAME',+ createdAt: '2026-01-01T00:00:00.000Z',+ },+ });++ expect(record.detail.logId).toBe('meta_id');+ expect(record.detail.triggerId).toBe('meta_trigger');+ expect(record.detail.triggerName).toBe('META_NAME');+ expect(record.detail.createdAt).toBe('2026-01-01T00:00:00.000Z');+ // Top-level table columns stay untouched by meta values.+ expect(record.id).toBeUndefined();+ });++ it('[Given] retrieve response wrapped under log [Then] unwraps the nested record', () => {+ const record = decodeTriggerLogRecord({+ log: {+ id: 'log_QNzKGStH-ruD',+ appName: 'gmail',+ meta: { triggerNanoId: 'ti_-nGUzD9N6JNf' },+ },+ });++ expect(record.detail.logId).toBe('log_QNzKGStH-ruD');+ expect(record.detail.toolkit).toBe('gmail');+ expect(record.table.triggerId).toBe('ti_-nGUzD9N6JNf');+ });++ it('[Given] payload JSON strings in meta [Then] parses provider payload first', () => {+ const record = decodeTriggerLogRecord({+ meta: {+ triggerProviderPayload: '{"foo":"bar","count":2}',+ triggerClientPayload: '{"ignored":true}',+ },+ });++ expect(record.payload).toEqual({ foo: 'bar', count: 2 });+ });++ it('[Given] response JSON string in meta [Then] parses client response first', () => {+ const record = decodeTriggerLogRecord({+ meta: {+ triggerClientResponse: '{"status":"CANCELED"}',+ triggerProviderResponse: '{"ignored":true}',+ },+ });++ expect(record.response).toEqual({ status: 'CANCELED' });+ });++ it('[Given] top-level payloadReceived [Then] uses it when meta has no payload', () => {+ const record = decodeTriggerLogRecord({+ payloadReceived: '{"a":1}',+ payload: '{"b":2}',+ });++ expect(record.payload).toEqual({ a: 1 });+ });++ it('[Given] non-JSON payload string [Then] keeps the original string', () => {+ const record = decodeTriggerLogRecord({+ meta: { triggerProviderPayload: 'not-json' },+ });++ expect(record.payload).toBe('not-json');+ });++ it('[Given] wrongly-typed fields [Then] treats them as absent instead of failing', () => {+ const record = decodeTriggerLogRecord({+ id: 42,+ triggerName: ['nope'],+ meta: { triggerName: 'META_NAME' },+ });++ expect(record.id).toBeUndefined();+ expect(record.detail.triggerName).toBe('META_NAME');+ });++ it('[Given] garbage payload [Then] falls back to the empty record', () => {+ expect(decodeTriggerLogRecord(null)).toEqual(emptyTriggerLogRecord);+ expect(decodeTriggerLogRecord('garbage')).toEqual(emptyTriggerLogRecord);+ expect(emptyTriggerLogRecord.detail.logId).toBeUndefined();+ expect(emptyTriggerLogRecord.payload).toBeNull();+ expect(emptyTriggerLogRecord.response).toBeNull();+ });+});++describe('parseMaybeJson', () => {+ it('[Given] non-JSON string [Then] returns the original value', () => {+ expect(parseMaybeJson('not-json')).toBe('not-json');+ });++ it('[Given] JSON object string [Then] parses it', () => {+ expect(parseMaybeJson('{"foo":"bar"}')).toEqual({ foo: 'bar' });+ });++ it('[Given] malformed JSON-looking string [Then] returns the original value', () => {+ expect(parseMaybeJson('{oops}')).toBe('{oops}');+ });+});diff --git a/ts/packages/cli/test/src/commands/proxy.cmd.test.ts b/ts/packages/cli/test/src/commands/proxy.cmd.test.tsindex e3b5edb35..9f850eb37 100644--- a/ts/packages/cli/test/src/commands/proxy.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/proxy.cmd.test.ts@@ -1,12 +1,17 @@-import { describe, expect, layer } from '@effect/vitest';-import { ConfigProvider, Effect, Option } from 'effect';-import { afterEach, it, vi } from 'vitest';+import { describe, expect, it, layer } from '@effect/vitest';+import { ConfigProvider, Effect, Exit, Option } from 'effect';+import { afterEach, vi } from 'vitest';import type {SessionCreateParams,SessionProxyExecuteParams,} from '@composio/client/resources/tool-router';import { extendConfigProvider } from 'src/services/config';-import { normalizeProxyMethod, parseProxyBody, parseProxyHeader } from 'src/commands/proxy.cmd';+import {+ normalizeProxyMethod,+ parseProxyBody,+ parseProxyHeader,+ ProxyCommandError,+} from 'src/commands/proxy.cmd';import * as consumerShortTermCache from 'src/services/consumer-short-term-cache';import { cli, MockConsole, TestLive } from 'test/__utils__';@@ -161,17 +166,19 @@ describe('CLI: composio proxy', () => {},});- yield* cli([+ const failure = yield* cli(['proxy','https://gmail.googleapis.com/gmail/v1/users/me/profile','--toolkit','gmail',- ]).pipe(- Effect.provide(live),- Effect.catchAll(() => Effect.void)- );+ ]).pipe(Effect.provide(live), Effect.flip);expect(createCalled).toBe(false);+ expect(failure).toBeInstanceOf(ProxyCommandError);+ if (failure instanceof ProxyCommandError) {+ expect(failure.reason).toBe('toolkit_not_connected');+ expect(failure.toolkit).toBe('gmail');+ }const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -214,7 +221,7 @@ describe('CLI: composio proxy', () => {'--skip-connection-check',]).pipe(Effect.provide(live), Effect.exit);- expect(exit._tag).toBe('Failure');+ expect(Exit.isFailure(exit)).toBe(true);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');diff --git a/ts/packages/cli/test/src/commands/py/py.generate.cmd.test.ts b/ts/packages/cli/test/src/commands/py/py.generate.cmd.test.tsindex 84b29c055..fc74d6d5b 100644--- a/ts/packages/cli/test/src/commands/py/py.generate.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/py/py.generate.cmd.test.ts@@ -1,4 +1,6 @@+import assert from 'node:assert';import path from 'node:path';+import { HelpDoc, ValidationError } from '@effect/cli';import { describe, expect, layer } from '@effect/vitest';import { Effect } from 'effect';import { FileSystem } from '@effect/platform';@@ -365,8 +367,9 @@ describe('CLI: composio generate py', () => {const args = ['generate', 'py', '--toolkits', 'nonexistent', '--output-dir', outputDir];const result = yield* cli(args).pipe(Effect.catchAll(e => Effect.succeed(e)));- expect(result).toBeInstanceOf(Error);- expect((result as Error).message).toContain('Invalid toolkit(s): nonexistent');+ assert.ok(ValidationError.isValidationError(result));+ assert.ok(ValidationError.isInvalidValue(result));+ expect(HelpDoc.toAnsiText(result.error)).toContain('Invalid toolkit(s): nonexistent');}));diff --git a/ts/packages/cli/test/src/commands/setup.cmd.test.ts b/ts/packages/cli/test/src/commands/setup.cmd.test.tsindex 284f05de2..f3f55e37f 100644--- a/ts/packages/cli/test/src/commands/setup.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/setup.cmd.test.ts@@ -2,7 +2,9 @@ import { Command, CommandExecutor } from '@effect/platform';import { describe, expect, layer } from '@effect/vitest';import { Cause, Effect, Exit, Fiber, TestClock } from 'effect';import { afterEach, vi } from 'vitest';+import { SkillInstallError } from 'src/effects/install-skill';import { CommandRunner } from 'src/services/command-runner';+import { SetupCommandError, SetupProcessError } from 'src/services/setup';import { SetupSkillInstaller } from 'src/services/setup-skill-installer';import { cli, MockConsole, TestLive } from 'test/__utils__';@@ -90,7 +92,14 @@ const makeRunner = (const makeSkillInstaller = (initiallyReady = false, failInstall = false) => {let ready = initiallyReady;const ensureClaudeSkill = () => {- if (failInstall) return Effect.fail(new Error('skill download failed'));+ if (failInstall) {+ return Effect.fail(+ new SkillInstallError({+ message: 'skill download failed',+ phase: 'download',+ })+ );+ }return Effect.sync(() => {const changed = !ready;ready = true;@@ -1169,10 +1178,21 @@ describe('CLI: composio setup', () => {{ failOn: 'plugin install' });layer(TestLive({ commandRunner: failedInstall.runner }))('native install failure', it => {- it.scoped('fails the command', () =>+ it.scoped('preserves the structured setup process failure as the command cause', () =>Effect.gen(function* () {const exit = yield* Effect.exit(cli(['setup', '--target', 'claude', '--yes']));expect(Exit.isFailure(exit)).toBe(true);+ if (Exit.isFailure(exit)) {+ const failure = Cause.squash(exit.cause);+ expect(failure).toBeInstanceOf(SetupCommandError);+ if (failure instanceof SetupCommandError) {+ expect(failure.operation).toBe('setup');+ expect(failure.cause).toBeInstanceOf(SetupProcessError);+ if (failure.cause instanceof SetupProcessError) {+ expect(failure.cause).toMatchObject({ target: 'claude', stage: 'mutate' });+ }+ }+ }}));});diff --git a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.tsindex ed7990dc8..900da6d61 100644--- a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts@@ -1,9 +1,10 @@import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';-import { describe, expect, layer } from '@effect/vitest';+import { HelpDoc, ValidationError } from '@effect/cli';+import { describe, expect, it, layer } from '@effect/vitest';import { vi, beforeEach, afterEach } from 'vitest';-import { ConfigProvider, Effect, Option } from 'effect';+import { Config, ConfigProvider, Effect, Option, Predicate } from 'effect';import { extendConfigProvider } from 'src/services/config';import { ComposioNoActiveConnectionError } from 'src/services/composio-error-overrides';import { setupCacheDir } from 'src/effects/setup-cache-dir';@@ -13,13 +14,26 @@ import * as composioClients from 'src/services/composio-clients';import * as redactModule from 'src/ui/redact';import { cli, TestLive, MockConsole } from 'test/__utils__';import type { TestLiveInput } from 'test/__utils__/services/test-layer';-import { showToolsExecuteInputHelp } from 'src/commands/tools/commands/tools.execute.cmd';+import {+ parseParallelExecuteArgs,+ showToolsExecuteInputHelp,+} from 'src/commands/tools/commands/tools.execute.cmd';import type { ToolkitDetailed } from 'src/models/toolkits';const testConfigProvider = ConfigProvider.fromMap(new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])).pipe(extendConfigProvider);+const expectInvalidValueMessage = (failure: unknown, message: string) => {+ expect(ValidationError.isValidationError(failure)).toBe(true);+ if (!ValidationError.isValidationError(failure)) return;++ expect(ValidationError.isInvalidValue(failure)).toBe(true);+ if (!ValidationError.isInvalidValue(failure)) return;++ expect(HelpDoc.toAnsiText(failure.error)).toContain(message);+};+const parseLastJson = (lines: ReadonlyArray<string>) => {for (let i = lines.length - 1; i >= 0; i -= 1) {const line = lines[i];@@ -39,6 +53,19 @@ const parseLastJson = (lines: ReadonlyArray<string>) => {};describe('CLI: composio execute', () => {+ it.effect('returns a CLI validation error for malformed parallel arguments', () =>+ Effect.gen(function* () {+ const failure = yield* parseParallelExecuteArgs(['--parallel', '--data', '{}'], {+ surface: 'root',+ projectMode: 'consumer',+ allowUserId: false,+ allowProjectName: false,+ }).pipe(Effect.flip);++ expectInvalidValueMessage(failure, 'Expected a tool slug before --data');+ })+ );+// Disable CI redaction so tests see raw values.// The explicit CI-redaction test overrides via vi.spyOn and is unaffected.let savedCI: string | undefined;@@ -379,6 +406,29 @@ describe('CLI: composio execute', () => {});}));++ it.scoped('applies a trailing account selector to the current parallel tool only', () =>+ Effect.gen(function* () {+ yield* cli([+ 'execute',+ '--parallel',+ '--skip-checks',+ 'GMAIL_SEND_EMAIL',+ '-d',+ '{"recipient":"[email protected]"}',+ '--account',+ 'forest',+ 'GMAIL_SEND_EMAIL',+ '-d',+ '{"recipient":"[email protected]"}',+ ]);++ expect(recordedSessionCreateParams).toHaveLength(2);+ expect(recordedSessionCreateParams.map(params => params.connected_accounts)).toEqual(+ expect.arrayContaining([{ gmail: 'con_gmail_secondary' }, { gmail: 'con_gmail_default' }])+ );+ })+ );});layer(@@ -937,7 +987,9 @@ describe('CLI: composio execute', () => {expect(output.tokenCount).toBeGreaterThan(10_000);// Session artifacts fall back to COMPOSIO_CACHE_DIR, which the shared// vitest setup pins to a per-test temp directory.+ const cacheDir = yield* ConfigProvider.fromEnv().load(Config.string('COMPOSIO_CACHE_DIR'));expect(output.outputFilePath).toMatch(/\/[^/]+\/GMAIL_SEND_EMAIL_OUTPUT_[^.]+\.json$/);+ expect(output.outputFilePath.startsWith(`${cacheDir}/`)).toBe(true);expect(fs.existsSync(output.outputFilePath)).toBe(true);const storedJson = fs.readFileSync(output.outputFilePath, 'utf8');expect(storedJson).toContain('token token token');@@ -1024,6 +1076,58 @@ describe('CLI: composio execute', () => {);});+ layer(+ TestLive({+ baseConfigProvider: testConfigProvider,+ fixture: 'global-test-user-id',+ stdin: { isTTY: true, data: '' },+ toolRouter: {+ execute: async (_sessionId, params) => {+ if (params.tool_slug === 'GMAIL_SEND_EMAIL') {+ throw new Error('gmail execution failed');+ }+ return {+ data: { tool_slug: params.tool_slug, arguments: params.arguments },+ error: null,+ log_id: 'log_parallel_success',+ };+ },+ },+ })+ )('[Given] one parallel execution fails [Then] sibling results are retained', it => {+ it.scoped('returns an aggregate result for every requested tool', () =>+ Effect.gen(function* () {+ yield* cli([+ 'execute',+ '--parallel',+ '--skip-checks',+ 'GMAIL_SEND_EMAIL',+ '-d',+ '{"recipient":"a"}',+ 'GITHUB_CREATE_ISSUE',+ '-d',+ '{"title":"Bug"}',+ ]).pipe(Effect.catchAll(() => Effect.void));++ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = parseLastJson(lines);+ const results =+ Predicate.hasProperty(output, 'results') && Array.isArray(output.results)+ ? output.results+ : [];++ expect(output.successful).toBe(false);+ expect(results).toHaveLength(2);+ expect(results).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ slug: 'GMAIL_SEND_EMAIL', successful: false }),+ expect.objectContaining({ slug: 'GITHUB_CREATE_ISSUE', successful: true }),+ ])+ );+ })+ );+ });+layer(TestLive({baseConfigProvider: testConfigProvider,@@ -2171,10 +2275,9 @@ describe('CLI: composio execute', () => {it.scoped('fails with invalid JSON error', () =>Effect.gen(function* () {const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', 'not-valid-json']).pipe(- Effect.flip,- Effect.map(error => (error instanceof Error ? error.message : String(error)))+ Effect.flip);- expect(failure).toContain('Invalid JSON input');+ expectInvalidValueMessage(failure, 'Invalid JSON input');}));});@@ -2189,10 +2292,9 @@ describe('CLI: composio execute', () => {it.scoped('fails with expected object error', () =>Effect.gen(function* () {const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '[1,2,3]']).pipe(- Effect.flip,- Effect.map(error => (error instanceof Error ? error.message : String(error)))+ Effect.flip);- expect(failure).toContain('Expected a JSON object');+ expectInvalidValueMessage(failure, 'Expected a JSON object');}));});@@ -2207,10 +2309,9 @@ describe('CLI: composio execute', () => {it.scoped('fails with expected object error for string', () =>Effect.gen(function* () {const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '"just a string"']).pipe(- Effect.flip,- Effect.map(error => (error instanceof Error ? error.message : String(error)))+ Effect.flip);- expect(failure).toContain('Expected a JSON object');+ expectInvalidValueMessage(failure, 'Expected a JSON object');}));});@@ -2251,11 +2352,8 @@ describe('CLI: composio execute', () => {)('[Given] empty piped stdin [Then] fails with parse error', it => {it.scoped('fails with error for empty stdin', () =>Effect.gen(function* () {- const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL']).pipe(- Effect.flip,- Effect.map(error => (error instanceof Error ? error.message : String(error)))- );- expect(failure).toContain('Invalid JSON input');+ const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL']).pipe(Effect.flip);+ expectInvalidValueMessage(failure, 'Invalid JSON input');}));});diff --git a/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.tsindex b7c3e5681..a96260329 100644--- a/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts@@ -8,6 +8,7 @@ import { extendConfigProvider } from 'src/services/config';import { cli, TestLive, MockConsole } from 'test/__utils__';import type { TestLiveInput } from 'test/__utils__/services/test-layer';import type { Tools } from 'src/models/tools';+import { ToolsSearchInputError } from 'src/commands/tools/commands/tools.search.cmd';const testTools: Tools = [{@@ -97,6 +98,19 @@ const extractFirstJsonObject = (output: string): Record<string, unknown> | null};describe('CLI: composio search', () => {+ layer(TestLive(testLiveOptions))('[Given] a blank query [Then] typed validation fails', it => {+ it.scoped('returns the structured missing-query error', () =>+ Effect.gen(function* () {+ const failure = yield* cli(['search', ' ']).pipe(Effect.flip);+ expect(failure).toBeInstanceOf(ToolsSearchInputError);+ if (failure instanceof ToolsSearchInputError) {+ expect(failure.reason).toBe('missing_query');+ expect(failure.message).toBe('At least one query is required.');+ }+ })+ );+ });+layer(TestLive(testLiveOptions))('[Given] query "send" [Then] returns JSON by default', it => {it.scoped('returns JSON payload by default', () =>Effect.gen(function* () {diff --git a/ts/packages/cli/test/src/commands/triggers/triggers.list.cmd.test.ts b/ts/packages/cli/test/src/commands/triggers/triggers.list.cmd.test.tsindex b9389dbe7..049168a76 100644--- a/ts/packages/cli/test/src/commands/triggers/triggers.list.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/triggers/triggers.list.cmd.test.ts@@ -1,5 +1,6 @@+import { ValidationError } from '@effect/cli';import { describe, expect, layer } from '@effect/vitest';-import { ConfigProvider, Effect } from 'effect';+import { Cause, ConfigProvider, Effect, Exit } from 'effect';import { extendConfigProvider } from 'src/services/config';import { cli, MockConsole, TestLive } from 'test/__utils__';import type { TriggerTypes } from 'src/models/trigger-types';@@ -76,7 +77,14 @@ describe('CLI: composio dev triggers list', () => {it => {it.scoped('uses root toolkit command in the no-results hint', () =>Effect.gen(function* () {- yield* cli(['triggers', 'list', 'nonexistent']).pipe(Effect.ignore);+ const exit = yield* Effect.exit(cli(['triggers', 'list', 'nonexistent']));+ expect(Exit.isFailure(exit)).toBe(true);+ if (Exit.isFailure(exit)) {+ const failure = Cause.squash(exit.cause);+ expect(+ ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)+ ).toBe(true);+ }const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');diff --git a/ts/packages/cli/test/src/commands/ts/ts.generate.cmd.test.ts b/ts/packages/cli/test/src/commands/ts/ts.generate.cmd.test.tsindex f9117e60f..587dabafc 100644--- a/ts/packages/cli/test/src/commands/ts/ts.generate.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/ts/ts.generate.cmd.test.ts@@ -1,4 +1,6 @@+import assert from 'node:assert';import path from 'node:path';+import { HelpDoc, ValidationError } from '@effect/cli';import { describe, expect, layer } from '@effect/vitest';import { Effect } from 'effect';import { FileSystem } from '@effect/platform';@@ -998,8 +1000,9 @@ describe('CLI: composio generate ts', () => {const args = ['generate', 'ts', '--toolkits', 'nonexistent', '--output-dir', outputDir];const result = yield* cli(args).pipe(Effect.catchAll(e => Effect.succeed(e)));- expect(result).toBeInstanceOf(Error);- expect((result as Error).message).toContain('Invalid toolkit(s): nonexistent');+ assert.ok(ValidationError.isValidationError(result));+ assert.ok(ValidationError.isInvalidValue(result));+ expect(HelpDoc.toAnsiText(result.error)).toContain('Invalid toolkit(s): nonexistent');}));diff --git a/ts/packages/cli/test/src/effect-errors/span-annotation.test.ts b/ts/packages/cli/test/src/effect-errors/span-annotation.test.tsnew file mode 100644index 000000000..ebc64a7e6--- /dev/null+++ b/ts/packages/cli/test/src/effect-errors/span-annotation.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from '@effect/vitest';+import { Cause, Data, Effect, Option } from 'effect';+import { extractSpanAnnotation } from 'src/effect-errors/logic/errors/span-annotation';++class CanaryError extends Data.TaggedError('CanaryError')<{+ readonly message: string;+}> {}++const failureOf = <E>(cause: Cause.Cause<E>): E =>+ Option.getOrThrowWith(Cause.failureOption(cause), () => new Error('expected a failure cause'));++describe('extractSpanAnnotation', () => {+ it.effect(+ 'recovers the ambient span from a runtime failure (canary for the effect/SpanAnnotation internal)',+ () =>+ Effect.gen(function* () {+ const cause = yield* Effect.fail(new CanaryError({ message: 'boom' })).pipe(+ Effect.withSpan('canary-span'),+ Effect.sandbox,+ Effect.flip+ );++ const span = extractSpanAnnotation(failureOf(cause));++ expect(span).toBeDefined();+ expect(span?.name).toBe('canary-span');+ })+ );++ it.effect('recovers the ambient span from a runtime defect', () =>+ Effect.gen(function* () {+ const cause = yield* Effect.die(new Error('defect boom')).pipe(+ Effect.withSpan('defect-span'),+ Effect.sandbox,+ Effect.flip+ );++ const defects = Cause.defects(cause);+ const span = extractSpanAnnotation([...defects][0]);++ expect(span?.name).toBe('defect-span');+ })+ );++ it('returns undefined when the error carries no span annotation', () => {+ expect(extractSpanAnnotation(new CanaryError({ message: 'boom' }))).toBeUndefined();+ expect(extractSpanAnnotation('plain string')).toBeUndefined();+ expect(extractSpanAnnotation(undefined)).toBeUndefined();+ });++ it('returns undefined when the annotation does not look like a span', () => {+ const spanSymbol = Symbol.for('effect/SpanAnnotation');+ const error = { [spanSymbol]: { name: 'not-a-span' } };++ expect(extractSpanAnnotation(error)).toBeUndefined();+ });+});diff --git a/ts/packages/cli/test/src/effects/install-skill.test.ts b/ts/packages/cli/test/src/effects/install-skill.test.tsindex 6cd0b53e5..d0ae240db 100644--- a/ts/packages/cli/test/src/effects/install-skill.test.ts+++ b/ts/packages/cli/test/src/effects/install-skill.test.ts@@ -13,6 +13,7 @@ import {resolveSkillReleaseTag,resolveTargetSkillPath,SKILL_RELEASE_TAG_FILENAME,+ SkillInstallError,type SkillReleaseChannel,} from 'src/effects/install-skill';import { GITHUB_CONFIG } from 'src/effects/github-config';@@ -277,11 +278,10 @@ describe('install-skill', () => {const home = tempy.temporaryDirectory();const error = yield* Effect.flip(makeInstallEffect(home, apiBaseUrl));- // The install pipeline still fails with a plain Error until the- // typed-error slice (PR 8 of this stack) introduces SkillInstallError.- expect(error).toBeInstanceOf(Error);- if (error instanceof Error) {- expect(error.message).toContain('Failed to download skill');+ expect(error).toBeInstanceOf(SkillInstallError);+ if (error instanceof SkillInstallError) {+ expect(error.phase).toBe('release');+ expect(error.cause).toBeDefined();}}));diff --git a/ts/packages/cli/test/src/services/agents.test.ts b/ts/packages/cli/test/src/services/agents.test.tsnew file mode 100644index 000000000..1d8f550ea--- /dev/null+++ b/ts/packages/cli/test/src/services/agents.test.ts@@ -0,0 +1,85 @@+import { afterEach, vi } from 'vitest';+import { describe, expect, it } from '@effect/vitest';+import { Effect } from 'effect';+import {+ AgentRequestError,+ AgentResponseDecodeError,+ fetchAgentInbox,+ normalizeAgentIdentity,+} from 'src/services/agents';++describe('agent service response boundaries', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('normalizes known keys while preserving forward-compatible fields', () => {+ const identity = normalizeAgentIdentity({+ agent_key: 'agent_test_key',+ status: 'READY',+ future_field: { enabled: true },+ composio: {+ user_api_key: 'uak_test',+ org_id: 'org_test',+ future_credential_metadata: 'preserved',+ },+ });++ expect(identity.composio_agent_key).toBe('agent_test_key');+ expect(identity.future_field).toEqual({ enabled: true });+ expect(identity.composio?.future_credential_metadata).toBe('preserved');+ });++ it.effect('decodes inbox responses instead of asserting their shape', () =>+ Effect.gen(function* () {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ new Response(+ JSON.stringify({+ count: 1,+ messages: [{ subject: 'Hello', future_field: 'preserved' }],+ next_cursor: 'cursor_test',+ }),+ { status: 200 }+ )+ );++ const inbox = yield* fetchAgentInbox({ agentKey: 'agent_test_key' });++ expect(inbox.count).toBe(1);+ expect(inbox.messages?.[0]?.subject).toBe('Hello');+ expect(inbox.messages?.[0]?.future_field).toBe('preserved');+ expect(inbox.next_cursor).toBe('cursor_test');+ })+ );++ it.effect('fails with structured context when an inbox response is invalid', () =>+ Effect.gen(function* () {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ new Response(JSON.stringify({ messages: [{ subject: 42 }] }), { status: 200 })+ );++ const error = yield* fetchAgentInbox({ agentKey: 'agent_test_key', limit: 5 }).pipe(+ Effect.flip+ );++ expect(error).toBeInstanceOf(AgentResponseDecodeError);+ expect(error.pathname).toBe('/api/mail?limit=5');+ })+ );++ it.effect('preserves an agent API error message and HTTP status', () =>+ Effect.gen(function* () {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ new Response(JSON.stringify({ message: 'Agent key expired' }), { status: 401 })+ );++ const error = yield* fetchAgentInbox({ agentKey: 'expired_key' }).pipe(Effect.flip);++ expect(error).toBeInstanceOf(AgentRequestError);+ if (!(error instanceof AgentRequestError)) return;+ expect(error.message).toBe('Agent key expired');+ expect(error.status).toBe(401);+ expect(error.pathname).toBe('/api/mail?limit=50');+ })+ );+});diff --git a/ts/packages/cli/test/src/services/command-hints.test.ts b/ts/packages/cli/test/src/services/command-hints.test.tsindex 77cf2e6b6..e00a6b97b 100644--- a/ts/packages/cli/test/src/services/command-hints.test.ts+++ b/ts/packages/cli/test/src/services/command-hints.test.ts@@ -1,15 +1,15 @@import { describe, expect, it } from 'vitest';+import { Record } from 'effect';import {COMMAND_HINTS,commandHintExample,commandHintLinks,renderCommandHintGraph,- type CommandHintId,} from 'src/services/command-hints';describe('command-hints', () => {it('has no dangling linked command ids', () => {- const ids = new Set(Object.keys(COMMAND_HINTS) as CommandHintId[]);+ const ids = new Set(Record.keys(COMMAND_HINTS));for (const id of ids) {for (const linkedId of commandHintLinks(id)) {diff --git a/ts/packages/cli/test/src/services/composio-error-overrides.test.ts b/ts/packages/cli/test/src/services/composio-error-overrides.test.tsindex 4ebf4c1ad..6aadf12b6 100644--- a/ts/packages/cli/test/src/services/composio-error-overrides.test.ts+++ b/ts/packages/cli/test/src/services/composio-error-overrides.test.ts@@ -52,6 +52,46 @@ describe('composio-error-overrides', () => {expect(result.message).toBe('Something else broke');});+ it('does not trust malformed API error fields but keeps the valid ones', () => {+ const error = {+ details: {+ code: '4302',+ slug: 4302,+ message: 'Malformed API error',+ },+ };++ const result = mapComposioError({ error });++ expect(result.normalized).toBe(error);+ expect(result.apiDetails?.message).toBe('Malformed API error');+ expect(result.apiDetails?.code).toBeUndefined();+ expect(result.apiDetails?.slug).toBeUndefined();+ expect(result.override).toBeNull();+ expect(result.message).toBe('Malformed API error');+ });++ it('skips UnknownException wrappers while decoding their causes', () => {+ const result = mapComposioError({+ toolkit: 'gmail',+ error: {+ _tag: 'UnknownException',+ cause: {+ code: 4302,+ slug: 'ToolRouterV2_NoActiveConnection',+ message: 'No active connection',+ },+ },+ });++ expect(result.normalized).toBeInstanceOf(ComposioNoActiveConnectionError);+ expect(result.apiDetails).toEqual({+ code: 4302,+ slug: 'ToolRouterV2_NoActiveConnection',+ message: 'No active connection',+ });+ });+it('preserves original generic errors for top-level CLI handling', () => {const error = {_tag: 'ToolExecutionError',diff --git a/ts/packages/cli/test/src/services/run-helpers-runtime.test.ts b/ts/packages/cli/test/src/services/run-helpers-runtime.test.tsnew file mode 100644index 000000000..ac0b72d6a--- /dev/null+++ b/ts/packages/cli/test/src/services/run-helpers-runtime.test.ts@@ -0,0 +1,64 @@+import { Predicate } from 'effect';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { installRunHelpers } from 'src/services/run-helpers-runtime';++const installedGlobalNames = [+ 'z',+ 'zod',+ 'search',+ 'execute',+ 'experimental_subAgent',+ 'invokeAgent',+ 'proxy',+ '__composioRunContext',+ '__composioConsumerContext',+];+const originalGlobalDescriptors = new Map(+ installedGlobalNames.map(name => [name, Object.getOwnPropertyDescriptor(globalThis, name)])+);++describe('run-helpers-runtime', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ for (const name of installedGlobalNames) {+ const descriptor = originalGlobalDescriptors.get(name);+ if (descriptor) {+ Object.defineProperty(globalThis, name, descriptor);+ } else {+ Reflect.deleteProperty(globalThis, name);+ }+ }+ });++ it('[Given] a malformed proxy session response [Then] it rejects the HTTP boundary payload', async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ session_id: 42 }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })+ );+ vi.stubGlobal('fetch', fetchMock);++ await installRunHelpers({+ cliPrefix: ['composio'],+ helperContext: {+ apiKey: 'test-key',+ orgId: 'test-org',+ consumerProjectId: 'test-project',+ consumerUserId: 'test-user',+ },+ });++ const installedGlobals: unknown = globalThis;+ expect(Predicate.hasProperty(installedGlobals, 'proxy')).toBe(true);+ if (+ !Predicate.hasProperty(installedGlobals, 'proxy') ||+ typeof installedGlobals.proxy !== 'function'+ ) {+ throw new Error('installRunHelpers() did not install proxy().');+ }++ await expect(installedGlobals.proxy('github')).rejects.toThrow(/session_id/);+ expect(fetchMock).toHaveBeenCalledOnce();+ });+});diff --git a/ts/packages/cli/test/src/services/run-subagent-acp.test.ts b/ts/packages/cli/test/src/services/run-subagent-acp.test.tsindex 5da6b6a09..77bf0ce2d 100644--- a/ts/packages/cli/test/src/services/run-subagent-acp.test.ts+++ b/ts/packages/cli/test/src/services/run-subagent-acp.test.ts@@ -1,7 +1,11 @@-import { afterEach, describe, expect, it, vi } from 'vitest';+import { Readable } from 'node:stream';+import { BunContext } from '@effect/platform-bun';+import { Effect } from 'effect';+import { afterEach, describe, expect, it, vi } from '@effect/vitest';import {BufferedChunkLogger,createStructuredOutputMcpContext,+ readableStreamFromNode,resolveAcpAdapterCommand,selectPermissionOutcome,} from 'src/services/run-subagent-acp';@@ -12,20 +16,47 @@ describe('run-subagent-acp', () => {vi.unstubAllGlobals();});- it('[Given] bundled adapter packages [Then] it resolves to the bundled path without npx', () => {- const result = resolveAcpAdapterCommand('claude');- expect(result.source).toBe('bundled');- expect(result.cmd[0]).toBe(process.execPath);- expect(result.cmd[1]).toMatch(/claude-code-acp/);- });+ it('pauses a Node producer while the Web Stream queue is full', async () => {+ const input = new Readable({ read: () => undefined });+ const stream = readableStreamFromNode(input);++ input.push(new TextEncoder().encode('first'));+ input.push(new TextEncoder().encode('second'));+ await new Promise<void>(resolve => setImmediate(resolve));++ expect(input.isPaused()).toBe(true);- it('[Given] bundled codex adapter [Then] it resolves to the bundled path', () => {- const result = resolveAcpAdapterCommand('codex');- expect(result.source).toBe('bundled');- expect(result.cmd[0]).toBe(process.execPath);- expect(result.cmd[1]).toMatch(/codex-acp/);+ const reader = stream.getReader();+ const first = await reader.read();+ const second = await reader.read();++ expect(new TextDecoder().decode(first.value)).toBe('first');+ expect(new TextDecoder().decode(second.value)).toBe('second');++ await reader.cancel();+ expect(input.destroyed).toBe(true);});+ it.effect(+ '[Given] bundled adapter packages [Then] it resolves to the bundled path without npx',+ () =>+ Effect.gen(function* () {+ const result = yield* resolveAcpAdapterCommand('claude');+ expect(result.source).toBe('bundled');+ expect(result.cmd[0]).toBe(process.execPath);+ expect(result.cmd[1]).toMatch(/claude-code-acp/);+ }).pipe(Effect.provide(BunContext.layer))+ );++ it.effect('[Given] bundled codex adapter [Then] it resolves to the bundled path', () =>+ Effect.gen(function* () {+ const result = yield* resolveAcpAdapterCommand('codex');+ expect(result.source).toBe('bundled');+ expect(result.cmd[0]).toBe(process.execPath);+ expect(result.cmd[1]).toMatch(/codex-acp/);+ }).pipe(Effect.provide(BunContext.layer))+ );+it('[Given] an ACP invoke error [Then] it is classified for fallback', () => {const error = new AcpInvokeError('initialize_failed', 'boom');expect(isAcpInvokeError(error)).toBe(true);@@ -42,6 +73,16 @@ describe('run-subagent-acp', () => {expect(isAcpInvokeError(error)).toBe(true);});+ it('[Given] an unknown ACP error code [Then] it is not admitted into the fallback union', () => {+ const error = {+ name: 'AcpInvokeError',+ code: 'unexpected_failure',+ message: 'boom',+ };++ expect(isAcpInvokeError(error)).toBe(false);+ });+it('[Given] a cancelled ACP prompt [Then] it remains fallback-eligible', () => {const error = new AcpInvokeError('prompt_failed', 'claude ACP prompt was cancelled.');@@ -203,43 +244,47 @@ describe('run-subagent-acp', () => {});});- it('[Given] a structured schema [Then] it creates a stdio MCP server context for output capture', () => {- const helperDebugLog = vi.fn();- const context = createStructuredOutputMcpContext({- options: {- structuredSchema: {- type: 'object',- properties: {- summary: { type: 'string' },+ it.effect(+ '[Given] a structured schema [Then] it creates a stdio MCP server context for output capture',+ () =>+ Effect.gen(function* () {+ const helperDebugLog = vi.fn();+ const context = yield* createStructuredOutputMcpContext({+ options: {+ structuredSchema: {+ type: 'object',+ properties: {+ summary: { type: 'string' },+ },+ required: ['summary'],+ },},- required: ['summary'],- },- },- helperDebugLog,- });+ helperDebugLog,+ });- expect(context).not.toBeNull();- expect(context?.mcpServer.command).toBe(process.execPath);- expect(context?.mcpServer.args).toEqual(- expect.arrayContaining([- expect.stringContaining('run-subagent-output-mcp'),- '--schema-file',- expect.stringContaining('schema.json'),- '--result-file',- expect.stringContaining('result.json'),- ])- );- expect(context?.mcpServer.env).toEqual(- expect.arrayContaining([{ name: 'BUN_BE_BUN', value: '1' }])- );- expect(context?.resultFilePath).toContain('result.json');- expect(helperDebugLog).toHaveBeenCalledWith(- 'subAgent.acp.structured_output_tool',- expect.objectContaining({- modulePath: expect.stringContaining('run-subagent-output-mcp'),- })- );+ expect(context).not.toBeNull();+ expect(context?.mcpServer.command).toBe(process.execPath);+ expect(context?.mcpServer.args).toEqual(+ expect.arrayContaining([+ expect.stringContaining('run-subagent-output-mcp'),+ '--schema-file',+ expect.stringContaining('schema.json'),+ '--result-file',+ expect.stringContaining('result.json'),+ ])+ );+ expect(context?.mcpServer.env).toEqual(+ expect.arrayContaining([{ name: 'BUN_BE_BUN', value: '1' }])+ );+ expect(context?.resultFilePath).toContain('result.json');+ expect(helperDebugLog).toHaveBeenCalledWith(+ 'subAgent.acp.structured_output_tool',+ expect.objectContaining({+ modulePath: expect.stringContaining('run-subagent-output-mcp'),+ })+ );- context?.cleanup();- });+ yield* context!.cleanup;+ }).pipe(Effect.provide(BunContext.layer))+ );});diff --git a/ts/packages/cli/test/src/services/run-subagent-output-mcp.test.ts b/ts/packages/cli/test/src/services/run-subagent-output-mcp.test.tsindex aafb10ec5..f463682a0 100644--- a/ts/packages/cli/test/src/services/run-subagent-output-mcp.test.ts+++ b/ts/packages/cli/test/src/services/run-subagent-output-mcp.test.ts@@ -1,8 +1,13 @@import * as fs from 'node:fs';import { fileURLToPath } from 'node:url';import { describe, expect, it } from 'vitest';+import { decodeStructuredSchemaJson } from 'src/services/run-subagent-shared';describe('run-subagent-output-mcp source', () => {+ it('[Given] a non-object schema file [Then] it rejects the malformed boundary payload', () => {+ expect(() => decodeStructuredSchemaJson('[]')).toThrow();+ });+it('[Given] the structured output helper source [Then] it statically imports the MCP SDK', () => {const sourcePath = fileURLToPath(new URL('../../../src/services/run-subagent-output-mcp.ts', import.meta.url)diff --git a/ts/packages/cli/test/src/services/run-subagent-shared.test.ts b/ts/packages/cli/test/src/services/run-subagent-shared.test.tsnew file mode 100644index 000000000..c7101a2e2--- /dev/null+++ b/ts/packages/cli/test/src/services/run-subagent-shared.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';+import { finalizeInvokeAgentText, parseJson } from 'src/services/run-subagent-shared';++describe('run-subagent-shared JSON probes', () => {+ describe('parseJson', () => {+ it('[Given] blank text [Then] returns undefined', () => {+ expect(parseJson(' ')).toBeUndefined();+ });++ it('[Given] valid JSON [Then] returns the parsed value', () => {+ expect(parseJson(' {"a": 1} ')).toEqual({ a: 1 });+ expect(parseJson('[1, 2, 3]')).toEqual([1, 2, 3]);+ expect(parseJson('null')).toBeNull();+ });++ it('[Given] non-JSON text [Then] returns the trimmed text verbatim', () => {+ expect(parseJson(' not json at all ')).toBe('not json at all');+ });+ });++ describe('finalizeInvokeAgentText structured extraction', () => {+ const options = { structuredSchema: { type: 'object' } as Record<string, unknown> };++ it('[Given] direct JSON output [Then] parses it as the structured output', () => {+ expect(finalizeInvokeAgentText('{"a": 1}', options)).toEqual({+ result: null,+ structuredOutput: { a: 1 },+ });+ });++ it('[Given] a status line before a fenced JSON block [Then] extracts the fenced payload', () => {+ const text = 'Analysis complete.\n```json\n{"b": 2}\n```';+ expect(finalizeInvokeAgentText(text, options)).toEqual({+ result: null,+ structuredOutput: { b: 2 },+ });+ });++ it('[Given] JSON embedded in prose [Then] extracts the balanced payload', () => {+ const text = 'The final answer is {"c": {"nested": true}} as requested.';+ expect(finalizeInvokeAgentText(text, options)).toEqual({+ result: null,+ structuredOutput: { c: { nested: true } },+ });+ });++ it('[Given] output without any JSON [Then] throws the structured output error', () => {+ expect(() => finalizeInvokeAgentText('no structured payload here', options)).toThrow(+ 'experimental_subAgent() expected valid JSON output for structured response.'+ );+ });++ it('[Given] no structured schema [Then] returns the trimmed text as the result', () => {+ expect(finalizeInvokeAgentText(' plain answer ', {})).toEqual({ result: 'plain answer' });+ });+ });+});diff --git a/ts/packages/cli/test/src/services/tool-file-uploads.test.ts b/ts/packages/cli/test/src/services/tool-file-uploads.test.tsindex 38ba73aed..5fe818509 100644--- a/ts/packages/cli/test/src/services/tool-file-uploads.test.ts+++ b/ts/packages/cli/test/src/services/tool-file-uploads.test.ts@@ -1,10 +1,13 @@-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from '@effect/vitest';import * as os from 'node:os';import * as path from 'node:path';import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { FileSystem, Path } from '@effect/platform';+import { BunFileSystem, BunPath } from '@effect/platform-bun';+import { Effect, Layer } from 'effect';import type { Composio as RawComposioClient } from '@composio/client';import { ComposioSensitiveFilePathBlockedError } from '@composio/core';-import { uploadToolInputFiles } from 'src/services/tool-file-uploads';+import { schemaHasFileUploadable, uploadToolInputFiles } from 'src/services/tool-file-uploads';// Schema with a single `file_uploadable` attachment field — mirrors tools like// GMAIL_SEND_EMAIL whose attachment is uploaded from a local path.@@ -24,89 +27,135 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {vi.restoreAllMocks();});- it('refuses to read/upload a path under a sensitive directory (~/.ssh/id_rsa)', async () => {- const createPresignedURL = vi.fn();- const client = makeClient(createPresignedURL);-- await expect(- uploadToolInputFiles({- toolSlug: 'GMAIL_SEND_EMAIL',- arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },- inputSchema,- client,+ it('ignores malformed composition branches without hiding valid schemas', () => {+ expect(+ schemaHasFileUploadable({+ anyOf: ['not-a-schema', null, { file_uploadable: true }],})- ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError);-- // The guard must fire BEFORE any network round-trip: no presigned URL, no upload.- expect(createPresignedURL).not.toHaveBeenCalled();+ ).toBe(true);+ expect(schemaHasFileUploadable({ anyOf: ['not-a-schema', null] })).toBe(false);});- it('surfaces CLI-appropriate remediation, not the SDK-only opt-out, in the block error', async () => {- const client = makeClient(vi.fn());-- // The CLI has no `sensitiveFileUploadProtection` opt-out (by design), so the- // error must not point users at that non-existent knob (issue #3763 review #2/#3).- await expect(- uploadToolInputFiles({- toolSlug: 'GMAIL_SEND_EMAIL',- arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },- inputSchema,- client,- })- ).rejects.toThrowError(/has no opt-out/i);-- await expect(- uploadToolInputFiles({- toolSlug: 'GMAIL_SEND_EMAIL',- arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },- inputSchema,- client,- })- ).rejects.not.toThrowError(/sensitiveFileUploadProtection/);- });+ it.effect('refuses to read/upload a path under a sensitive directory (~/.ssh/id_rsa)', () =>+ Effect.gen(function* () {+ const fsApi = yield* FileSystem.FileSystem;+ const pathApi = yield* Path.Path;+ const createPresignedURL = vi.fn();+ const client = makeClient(createPresignedURL);- it('refuses credential-like basenames (.env) even outside a sensitive directory', async () => {- const createPresignedURL = vi.fn();- const client = makeClient(createPresignedURL);+ yield* Effect.promise(() =>+ expect(+ uploadToolInputFiles({+ fs: fsApi,+ path: pathApi,+ toolSlug: 'GMAIL_SEND_EMAIL',+ arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },+ inputSchema,+ client,+ })+ ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError)+ );- await expect(- uploadToolInputFiles({- toolSlug: 'GMAIL_SEND_EMAIL',- arguments_: { attachment: path.join(os.tmpdir(), '.env') },- inputSchema,- client,- })- ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError);- expect(createPresignedURL).not.toHaveBeenCalled();- });+ // The guard must fire BEFORE any network round-trip: no presigned URL, no upload.+ expect(createPresignedURL).not.toHaveBeenCalled();+ }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))+ );- it('still uploads a normal (non-sensitive) local file', async () => {- const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));- try {- const file = path.join(root, 'document.pdf');- writeFileSync(file, 'hello');-- const createPresignedURL = vi.fn(async () => ({- new_presigned_url: 'https://s3.example.com/put',- key: 's3key-123',- }));+ it.effect(+ 'surfaces CLI-appropriate remediation, not the SDK-only opt-out, in the block error',+ () =>+ Effect.gen(function* () {+ const fsApi = yield* FileSystem.FileSystem;+ const pathApi = yield* Path.Path;+ const client = makeClient(vi.fn());++ // The CLI has no `sensitiveFileUploadProtection` opt-out (by design), so the+ // error must not point users at that non-existent knob (issue #3763 review #2/#3).+ yield* Effect.promise(() =>+ expect(+ uploadToolInputFiles({+ fs: fsApi,+ path: pathApi,+ toolSlug: 'GMAIL_SEND_EMAIL',+ arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },+ inputSchema,+ client,+ })+ ).rejects.toThrowError(/has no opt-out/i)+ );++ yield* Effect.promise(() =>+ expect(+ uploadToolInputFiles({+ fs: fsApi,+ path: pathApi,+ toolSlug: 'GMAIL_SEND_EMAIL',+ arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },+ inputSchema,+ client,+ })+ ).rejects.not.toThrowError(/sensitiveFileUploadProtection/)+ );+ }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))+ );++ it.effect('refuses credential-like basenames (.env) even outside a sensitive directory', () =>+ Effect.gen(function* () {+ const fsApi = yield* FileSystem.FileSystem;+ const pathApi = yield* Path.Path;+ const createPresignedURL = vi.fn();const client = makeClient(createPresignedURL);- vi.stubGlobal(- 'fetch',- vi.fn(async () => ({ ok: true, statusText: 'OK' }))++ yield* Effect.promise(() =>+ expect(+ uploadToolInputFiles({+ fs: fsApi,+ path: pathApi,+ toolSlug: 'GMAIL_SEND_EMAIL',+ arguments_: { attachment: path.join(os.tmpdir(), '.env') },+ inputSchema,+ client,+ })+ ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError));+ expect(createPresignedURL).not.toHaveBeenCalled();+ }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))+ );- const result = await uploadToolInputFiles({- toolSlug: 'GMAIL_SEND_EMAIL',- arguments_: { attachment: file },- inputSchema,- client,- });+ it.effect('still uploads a normal (non-sensitive) local file', () => {+ const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));+ const file = path.join(root, 'document.pdf');+ writeFileSync(file, 'hello');++ const createPresignedURL = vi.fn(async () => ({+ new_presigned_url: 'https://s3.example.com/put',+ key: 's3key-123',+ }));+ const client = makeClient(createPresignedURL);+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({ ok: true, statusText: 'OK' }))+ );++ return Effect.gen(function* () {+ const fsApi = yield* FileSystem.FileSystem;+ const pathApi = yield* Path.Path;+ const result = yield* Effect.promise(() =>+ uploadToolInputFiles({+ fs: fsApi,+ path: pathApi,+ toolSlug: 'GMAIL_SEND_EMAIL',+ arguments_: { attachment: file },+ inputSchema,+ client,+ })+ );expect(createPresignedURL).toHaveBeenCalledTimes(1);expect(result.attachment).toMatchObject({ s3key: 's3key-123', name: 'document.pdf' });- } finally {- rmSync(root, { recursive: true, force: true });- }+ }).pipe(+ Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)),+ Effect.ensuring(Effect.sync(() => rmSync(root, { recursive: true, force: true })))+ );});});diff --git a/ts/packages/cli/test/src/services/tool-permissions.test.ts b/ts/packages/cli/test/src/services/tool-permissions.test.tsindex cdc5c8aa0..252444b8e 100644--- a/ts/packages/cli/test/src/services/tool-permissions.test.ts+++ b/ts/packages/cli/test/src/services/tool-permissions.test.ts@@ -1,9 +1,13 @@+import { FileSystem, Path } from '@effect/platform';+import { BunFileSystem, BunPath } from '@effect/platform-bun';import { afterEach, beforeEach, describe, expect, it, vi } from '@effect/vitest';-import { Effect } from 'effect';+import { Config, ConfigProvider, Effect, Layer, Option } from 'effect';import {decodeCacheFileTolerant,+ decodeToolRouterPermissionsConfig,gateToolExecution,resolveGateState,+ ToolPermissionDeniedError,type ConsumerPermissionSnapshot,} from 'src/services/tool-permissions';@@ -36,7 +40,25 @@ describe('tool permissions', () => {afterEach(() => {vi.useRealTimers();- vi.unstubAllEnvs();+ });++ it('maps forward-version permission modes to interactive safe defaults', () => {+ const decoded = decodeToolRouterPermissionsConfig({+ default: 'future_default_mode',+ overrides: {+ 'GMAIL_SEND_EMAIL:__none__': 'future_override_mode',+ },+ });++ expect(Option.isSome(decoded)).toBe(true);+ if (Option.isSome(decoded)) {+ expect(decoded.value).toStrictEqual({+ default: 'ask_every_call',+ overrides: {+ 'GMAIL_SEND_EMAIL:__none__': 'ask_always',+ },+ });+ }});it('drops only corrupt cache entries, keeping valid snapshots and allow decisions', () => {@@ -111,7 +133,35 @@ describe('tool permissions', () => {const result = yield* gateToolExecution({ toolSlug: 'GMAIL_SEND_EMAIL' });expect(result).toBeUndefined();- })+ }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))+ );++ it.effect('preserves permission-policy denial identity', () =>+ Effect.gen(function* () {+ const failure = yield* gateToolExecution({+ toolSlug: 'GMAIL_SEND_EMAIL',+ snapshot: {+ orgId: 'org_test',+ projectId: 'project_test',+ consumerUserId: 'user_test',+ enhancedControlsEnabled: true,+ permissions: {+ default: 'allow_all',+ overrides: {+ 'GMAIL_SEND_EMAIL:__none__': 'always_deny',+ },+ },+ connectedAccountIds: [],+ fetchedAt: PINNED_NOW,+ },+ }).pipe(Effect.flip);++ expect(failure).toBeInstanceOf(ToolPermissionDeniedError);+ if (failure instanceof ToolPermissionDeniedError) {+ expect(failure.deniedBy).toBe('permissions');+ expect(failure.toolSlug).toBe('GMAIL_SEND_EMAIL');+ }+ }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer))));it.effect('fails closed when interactive approval is needed but permission UI is disabled', () =>@@ -123,10 +173,42 @@ describe('tool permissions', () => {snapshot: snapshotFixture({ permissions: { default: 'ask_every_call' } }),}).pipe(Effect.flip);- expect(failure).toBeInstanceOf(Error);- if (failure instanceof Error) {+ expect(failure).toBeInstanceOf(ToolPermissionDeniedError);+ if (failure instanceof ToolPermissionDeniedError) {+ expect(failure.deniedBy).toBe('permissions');expect(failure.message).toContain('permission prompts are disabled');}- })+ }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))+ );++ it.effect('honors cached allow decisions even when permission UI is disabled', () =>+ Effect.gen(function* () {+ vi.stubEnv('COMPOSIO_DISABLE_PERMISSION_UI', '1');++ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ // The shared vitest setup pins COMPOSIO_CACHE_DIR to a fresh temp directory.+ const cacheDir = yield* ConfigProvider.fromEnv().load(Config.string('COMPOSIO_CACHE_DIR'));+ // Key shape: `${orgId}:${projectId}:${consumerUserId}:${toolSlug}:${accountId}`.+ const allowKey = 'org_cached_allow:project_test:user_test:GMAIL_SEND_EMAIL:__none__';+ yield* fs.writeFileString(+ path.join(cacheDir, 'tool-permissions-cache.json'),+ JSON.stringify({+ entries: {},+ // Unexpired relative to the pinned clock the SUT's expiry check reads.+ allowEntries: { [allowKey]: { expiresAt: PINNED_NOW + 60_000 } },+ })+ );++ const result = yield* gateToolExecution({+ toolSlug: 'GMAIL_SEND_EMAIL',+ snapshot: snapshotFixture({+ orgId: 'org_cached_allow',+ permissions: { default: 'ask_every_call' },+ }),+ });++ expect(result).toStrictEqual({ approvalStatus: 'cached_approved' });+ }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer))));});