@devries-cameron20 / composio Mirror · read-only / commits / aaabe9922
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 18:30 UTC

refactor(cli): enforce typed Effect error boundaries and v4 readiness seams (#3884)

This PR: - converts every remaining thunk-form `Effect.tryPromise` in CLI source to a purpose-named `Data.TaggedError` preserving its cause — `UnknownException` no longer surfaces from `src/` — and switches best-effort recoveries from `catchAll` to `catchTag` - isolates the `Symbol.for('effect/SpanAnnotation')` internal read behind a shape-validating adapter, with a canary test that fails a real effect through the runtime so an `effect` upgrade that drops the mechanism breaks CI instead of silently losing span timelines - decodes trigger-log payloads once at the API boundary through a tolerant schema documenting camelCase/snake_case/meta-nested alias precedence - deduplicates the per-entry tolerant decoders into `utils/collect-decoded-entries.ts`, replaces locally re-declared record schemas with `JsonRecordSchema`, deletes the unused `EnvLangDetector` service, and removes the temporary sync bridge from the platform-imports slice - the largest PR of the stack by design: generic refactors land late so the fix and rule slices before it stay small; one commit per sub-theme keeps `git show` reviewable --- **Stack** (re-slice of https://github.com/ComposioHQ/composio/pull/3859; each PR targets its parent and auto-retargets to `next` as parents merge): 1. https://github.com/ComposioHQ/composio/pull/3877 — guidelines + inert rule groups 2. https://github.com/ComposioHQ/composio/pull/3878 — `new Function()` eval security fix 3. https://github.com/ComposioHQ/composio/pull/3879 — behavioral fix pack 4. https://github.com/ComposioHQ/composio/pull/3880 — platform-imports rule + migration 5. https://github.com/ComposioHQ/composio/pull/3881 — terminal-streams rule + TerminalUI boundary 6. https://github.com/ComposioHQ/composio/pull/3882 — descriptor seam + zod→Schema 7. https://github.com/ComposioHQ/composio/pull/3883 — test-tree lint + deterministic suites 8. https://github.com/ComposioHQ/composio/pull/3884 — typed error boundaries + v4 seams ← **this PR** 9. https://github.com/ComposioHQ/composio/pull/3885 — try/catch+env ban + boundary ratchet On stacked bases CI runs lint/build and the CLI Docker e2e job; unit tests and typecheck are verified locally per PR and re-verified by full CI when each PR is retargeted to `next`.

Alberto Schiabel committed Jul 21, 2026 at 11:36 UTC aaabe9922b07d0afadca6ac11a4653648c749e50
89 files changed +5575 -3689
ts/packages/cli/AGENTS.md
-1
@@ -67,7 +67,6 @@ Options use `Options.text()`, `Options.boolean()`, `Options.choice()`, `Options.
67 | `ComposioToolkitsRepository` | API client — fetches toolkits, tools, trigger types; validates versions |
68 | `ComposioToolkitsRepositoryCached` | Decorator over base repository with file-based caching and graceful fallback |
69 | `NodeOs` | OS abstraction (`homedir`, `platform`, `arch`) |
70 -| `EnvLangDetector` | Detects project language (TS/Python) from config / lock files |
70 | `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions |
71 | `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |
72
ts/packages/cli/scripts/build-all-binaries.ts
+6 -2
@@ -12,11 +12,11 @@
12 * Output: `dist/binaries/composio-*`
13 */
14
15 -import process from 'node:process';
15 import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLevel } from 'effect';
16 import { Command } from '@effect/platform';
17 import { BunContext, BunRuntime } from '@effect/platform-bun';
18 import { buildCompanionModules, copyLocalToolBinaryAssets, teardown } from './_shared';
19 +import { BinaryBuildError } from './build-error';
20
21 /**
22 * All cross-compilation targets and their artifact names.
@@ -69,7 +69,11 @@ function runBunBuild(target: string, outfile: string) {
69 );
70
71 if (exitCode !== 0) {
72 - return yield* Effect.fail(new Error(`Failed to build binary for ${target}`));
72 + return yield* new BinaryBuildError({
73 + message: `Failed to build binary for ${target}`,
74 + target,
75 + exitCode,
76 + });
77 }
78 });
79 }
ts/packages/cli/scripts/build-binary-cross.ts
+6 -1
@@ -19,6 +19,7 @@ import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLeve
19 import { Command } from '@effect/platform';
20 import { BunContext, BunRuntime } from '@effect/platform-bun';
21 import { buildCompanionModules, copyLocalToolBinaryAssets, teardown } from './_shared';
22 +import { BinaryBuildError } from './build-error';
23
24 /**
25 * Maps Bun cross-compilation targets to Composio artifact names.
@@ -103,7 +104,11 @@ export function buildBinaryCross() {
104 process.exitCode = exitCode;
105
106 if (exitCode !== 0) {
106 - return yield* Effect.fail(new Error(`Failed to cross-compile binary for ${target}`));
107 + return yield* new BinaryBuildError({
108 + message: `Failed to cross-compile binary for ${target}`,
109 + target,
110 + exitCode,
111 + });
112 }
113
114 const companionOutputDir = './dist/binaries/companions';
ts/packages/cli/scripts/build-binary.ts
+5 -1
@@ -3,6 +3,7 @@ import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLeve
3 import { Command } from '@effect/platform';
4 import { BunContext, BunRuntime } from '@effect/platform-bun';
5 import { buildCompanionModules, copyLocalToolBinaryAssets, teardown } from './_shared';
6 +import { BinaryBuildError } from './build-error';
7
8 /**
9 * Usage: `bun scripts/build-binary.ts`
@@ -68,7 +69,10 @@ export function buildBinary() {
69 process.exitCode = exitCode;
70
71 if (exitCode !== 0) {
71 - return yield* Effect.fail(new Error('Failed to build binary'));
72 + return yield* new BinaryBuildError({
73 + message: 'Failed to build binary',
74 + exitCode,
75 + });
76 }
77
78 yield* Effect.logDebug('', 'Binary built successfully');
ts/packages/cli/scripts/build-error.ts new
+7
@@ -0,0 +1,7 @@
1 +import { Data } from 'effect';
2 +
3 +export class BinaryBuildError extends Data.TaggedError('scripts/BinaryBuildError')<{
4 + readonly message: string;
5 + readonly target?: string;
6 + readonly exitCode: number;
7 +}> {}
ts/packages/cli/src/analytics/events.ts
+3
@@ -87,6 +87,9 @@ const TOOL_VALIDATION_CODES: ReadonlySet<number> = new Set([
87 1607, // Upstream_ValidationError
88 3702, // ComposioTools_ValidationError
89 ]);
90 +// A parent `composio run` process hands these values to child CLI invocations through the
91 +// environment at spawn time; the event builders below are plain synchronous functions that
92 +// run outside any Effect context, so effect/Config is not available here.
93 const getInvocationOrigin = (): string => process.env.COMPOSIO_CLI_INVOCATION_ORIGIN ?? 'cli';
94 const getParentRunId = (): string | undefined => process.env.COMPOSIO_CLI_PARENT_RUN_ID;
95
ts/packages/cli/src/cli-main.ts
+1 -1
@@ -236,7 +236,7 @@ showUpdateNotice.pipe(
236 stripCwd: true,
237 });
238 const filteredErrors = captured.errors.filter(
239 - error => error.errorType !== 'ToolExecutionError'
239 + error => error.errorType !== 'ReportedToolExecutionError'
240 );
241 if (captured.interrupted || filteredErrors.length > 0) {
242 const message = prettyPrintFromCapturedErrors(
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+150 -77
@@ -1,4 +1,4 @@
1 -import { Args, Command, Options } from '@effect/cli';
1 +import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';
2 import { Data, Effect, Option, Schedule } from 'effect';
3 import type { Composio as RawComposioClient } from '@composio/client';
4 import open from 'open';
@@ -27,6 +27,17 @@ import { ComposioCliUserConfig } from 'src/services/cli-user-config';
27 import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
28 import { decodeConnectedAccountItemsWithFallback } from 'src/effects/decode-connected-account-list';
29
30 +class ConnectionPollingError extends Data.TaggedError('commands/ConnectionPollingError')<{
31 + readonly message: string;
32 + readonly connectedAccountId: string;
33 + readonly status: string;
34 +}> {}
35 +
36 +class MissingLinkUserIdError extends Data.TaggedError('commands/MissingLinkUserIdError')<{
37 + readonly message: string;
38 + readonly flow: 'list' | 'legacy' | 'tool-router';
39 +}> {}
40 +
41 class ConnectedAccountsDecodeError extends Data.TaggedError(
42 'commands/ConnectedAccountsDecodeError'
43 )<{
@@ -34,6 +45,20 @@ class ConnectedAccountsDecodeError extends Data.TaggedError(
45 readonly cause: unknown;
46 }> {}
47
48 +class ConnectedAccountsRequestError extends Data.TaggedError(
49 + 'commands/ConnectedAccountsRequestError'
50 +)<{
51 + readonly message: string;
52 + readonly cause: unknown;
53 +}> {}
54 +
55 +class BrowserOpenError extends Data.TaggedError('commands/BrowserOpenError')<{
56 + readonly message: string;
57 + readonly cause: unknown;
58 +}> {}
59 +
60 +const invalidOptionValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));
61 +
62 const toolkit = Args.text({ name: 'toolkit' }).pipe(
63 Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),
64 Args.optional
@@ -105,20 +130,21 @@ const waitForActiveConnection = (
130 Effect.gen(function* () {
131 yield* showRedirectUrl(ui, redirectUrl, { manual: noBrowser });
132
108 - let urlSchemeValid = false;
109 - try {
110 - const parsed = new URL(redirectUrl);
111 - urlSchemeValid = parsed.protocol === 'https:' || parsed.protocol === 'http:';
112 - } catch {
113 - // ignore
114 - }
133 + const parsedUrl = Option.liftThrowable((value: string) => new URL(value))(redirectUrl);
134 + const urlSchemeValid = Option.exists(
135 + parsedUrl,
136 + parsed => parsed.protocol === 'https:' || parsed.protocol === 'http:'
137 + );
138
139 if (!urlSchemeValid) {
140 yield* ui.log.warn(`Redirect URL has an unexpected scheme: ${redirectUrl}`);
141 yield* ui.log.info('Open the URL manually if you trust the source.');
142 } else if (!noBrowser) {
120 - yield* Effect.tryPromise(() => open(redirectUrl, { wait: false })).pipe(
121 - Effect.catchAll(error =>
143 + yield* Effect.tryPromise({
144 + try: () => open(redirectUrl, { wait: false }),
145 + catch: cause => new BrowserOpenError({ message: 'Failed to open the browser.', cause }),
146 + }).pipe(
147 + Effect.catchTag('commands/BrowserOpenError', error =>
148 Effect.gen(function* () {
149 yield* Effect.logDebug('Failed to open browser:', error);
150 yield* ui.log.warn('Could not open the browser automatically.');
@@ -131,15 +157,22 @@ const waitForActiveConnection = (
157 yield* ui.useMakeSpinner('Waiting for authentication...', spinner =>
158 Effect.retry(
159 Effect.gen(function* () {
134 - const account = yield* Effect.tryPromise(() =>
135 - client.connectedAccounts.retrieve(connectedAccountId)
136 - );
160 + const account = yield* Effect.tryPromise({
161 + try: () => client.connectedAccounts.retrieve(connectedAccountId),
162 + catch: cause =>
163 + new ConnectedAccountsRequestError({
164 + message: `Failed to fetch connected account "${connectedAccountId}".`,
165 + cause,
166 + }),
167 + });
168 if (account.status === 'ACTIVE') {
169 return account;
170 }
140 - return yield* Effect.fail(
141 - new Error(`Connection status is still '${account.status}', waiting for 'ACTIVE'`)
142 - );
171 + return yield* new ConnectionPollingError({
172 + message: `Connection status is still '${account.status}', waiting for 'ACTIVE'`,
173 + connectedAccountId,
174 + status: account.status,
175 + });
176 }),
177 Schedule.exponential('0.3 seconds').pipe(
178 Schedule.intersect(Schedule.recurs(15)),
@@ -224,8 +257,13 @@ const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string, noBrowser: boo
257 );
258
259 if (!noBrowser) {
227 - yield* Effect.tryPromise(() => open(dashboardUrl, { wait: false })).pipe(
228 - Effect.catchAll(() => ui.log.warn('Could not open the browser automatically.'))
260 + yield* Effect.tryPromise({
261 + try: () => open(dashboardUrl, { wait: false }),
262 + catch: cause => new BrowserOpenError({ message: 'Failed to open the browser.', cause }),
263 + }).pipe(
264 + Effect.catchTag('commands/BrowserOpenError', () =>
265 + ui.log.warn('Could not open the browser automatically.')
266 + )
267 );
268 }
269
@@ -257,7 +295,7 @@ const resolveNormalizedAliasOption = (alias: Option.Option<string>) =>
295
296 const normalizedAlias = normalizeAlias(alias.value);
297 if (normalizedAlias.length === 0) {
260 - return yield* Effect.fail(new Error('`--alias` cannot be empty.'));
298 + return yield* Effect.fail(invalidOptionValue('`--alias` cannot be empty.'));
299 }
300
301 return Option.some(normalizedAlias);
@@ -269,15 +307,21 @@ const listActiveConnectedAccounts = (params: {
307 readonly toolkitSlug?: string;
308 readonly authConfigId?: string;
309 }) =>
272 - Effect.tryPromise(() =>
273 - params.client.connectedAccounts.list({
274 - user_ids: [params.userId],
275 - toolkit_slugs: params.toolkitSlug ? [params.toolkitSlug] : undefined,
276 - auth_config_ids: params.authConfigId ? [params.authConfigId] : undefined,
277 - statuses: ['ACTIVE'],
278 - limit: 100,
279 - })
280 - );
310 + Effect.tryPromise({
311 + try: () =>
312 + params.client.connectedAccounts.list({
313 + user_ids: [params.userId],
314 + toolkit_slugs: params.toolkitSlug ? [params.toolkitSlug] : undefined,
315 + auth_config_ids: params.authConfigId ? [params.authConfigId] : undefined,
316 + statuses: ['ACTIVE'],
317 + limit: 100,
318 + }),
319 + catch: cause =>
320 + new ConnectedAccountsRequestError({
321 + message: `Failed to list connected accounts for user "${params.userId}".`,
322 + cause,
323 + }),
324 + });
325
326 const formatExistingAccountLabels = (
327 items: ReadonlyArray<{
@@ -310,12 +354,12 @@ const ensureAliasForAdditionalAccount = (params: {
354 }) =>
355 Effect.gen(function* () {
356 if (Option.isSome(params.alias)) {
313 - return true as const;
357 + return true;
358 }
359
360 const existingIds = new Set(params.existingAccounts.items.map(item => item.id));
361 if (params.existingAccounts.items.length === 0 || existingIds.has(params.connectedAccountId)) {
318 - return true as const;
362 + return true;
363 }
364
365 yield* params.ui.log.error(
@@ -325,7 +369,7 @@ const ensureAliasForAdditionalAccount = (params: {
369 formatExistingAccountLabels(params.existingAccounts.items),
370 'Existing accounts'
371 );
328 - return false as const;
372 + return false;
373 });
374
375 const resolveLinkUserId = (params: {
@@ -348,7 +392,8 @@ const resolveLinkUserId = (params: {
392 }) =>
393 Effect.gen(function* () {
394 const resolvedProjectContext = yield* params.projectContext.resolve.pipe(
351 - Effect.catchAll(() => Effect.succeed(Option.none()))
395 + Effect.option,
396 + Effect.map(Option.flatten)
397 );
398 const localTestUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
399
@@ -421,21 +466,28 @@ const handleListConnectedAccounts = (params: {
466 });
467
468 if (Option.isNone(resolvedUserId)) {
424 - return yield* Effect.fail(
425 - new Error('Missing user id. Provide --user-id or run composio dev init/login first.')
426 - );
469 + return yield* new MissingLinkUserIdError({
470 + message: 'Missing user id. Provide --user-id or run composio dev init/login first.',
471 + flow: 'list',
472 + });
473 }
474
475 const accounts = yield* params.ui.withSpinner(
476 `Listing connected accounts for "${toolkitSlug}"...`,
431 - Effect.tryPromise(() =>
432 - client.connectedAccounts.list({
433 - toolkit_slugs: [toolkitSlug],
434 - user_ids: [resolvedUserId.value],
435 - statuses: ['ACTIVE'],
436 - limit: 100,
437 - })
438 - )
477 + Effect.tryPromise({
478 + try: () =>
479 + client.connectedAccounts.list({
480 + toolkit_slugs: [toolkitSlug],
481 + user_ids: [resolvedUserId.value],
482 + statuses: ['ACTIVE'],
483 + limit: 100,
484 + }),
485 + catch: cause =>
486 + new ConnectedAccountsRequestError({
487 + message: `Failed to list connected accounts for "${toolkitSlug}".`,
488 + cause,
489 + }),
490 + })
491 );
492 const connectedAccounts = yield* decodeConnectedAccountItemsWithFallback(accounts.items).pipe(
493 Effect.mapError(
@@ -456,7 +508,7 @@ const handleListConnectedAccounts = (params: {
508 connectedAccounts: resolveDefaultConnectedAccountsByToolkit(connectedAccounts),
509 availableConnectedAccounts: groupCachedConnectedAccountsByToolkit(connectedAccounts),
510 },
459 - }).pipe(Effect.catchAll(() => Effect.void));
511 + }).pipe(Effect.ignore);
512 }
513
514 if (connectedAccounts.length === 0) {
@@ -514,7 +566,8 @@ const handleLegacyAuthConfigLink = (params: {
566 }) =>
567 Effect.gen(function* () {
568 const resolvedProjectContext = yield* params.projectContext.resolve.pipe(
517 - Effect.catchAll(() => Effect.succeed(Option.none()))
569 + Effect.option,
570 + Effect.map(Option.flatten)
571 );
572 const localTestUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
573 const globalTestUserId = params.userContext.data.testUserId;
@@ -524,11 +577,10 @@ const handleLegacyAuthConfigLink = (params: {
577 });
578
579 if (Option.isNone(resolvedUserId)) {
527 - return yield* Effect.fail(
528 - new Error(
529 - 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.'
530 - )
531 - );
580 + return yield* new MissingLinkUserIdError({
581 + message: 'Missing user id. Provide --user-id or run composio dev init to set test_user_id.',
582 + flow: 'legacy',
583 + });
584 }
585 if (Option.isNone(params.projectName) && Option.isNone(resolvedProjectContext)) {
586 yield* params.ui.log.error(
@@ -555,17 +607,27 @@ const handleLegacyAuthConfigLink = (params: {
607 client,
608 userId: resolvedUserId.value,
609 authConfigId: params.authConfigId,
558 - }).pipe(Effect.catchAll(() => Effect.succeed({ items: [] })));
610 + }).pipe(
611 + // Auxiliary fetch powering the --alias hint only: a transient list
612 + // failure must not abort the link flow.
613 + Effect.catchAll(() => Effect.succeed({ items: [] }))
614 + );
615 const linkOpt = yield* params.ui
616 .withSpinner(
617 'Creating link session...',
562 - Effect.tryPromise(() =>
563 - client.link.create({
564 - auth_config_id: params.authConfigId,
565 - user_id: resolvedUserId.value,
566 - ...(Option.isSome(normalizedAlias) && { alias: normalizedAlias.value }),
567 - })
568 - )
618 + Effect.tryPromise({
619 + try: () =>
620 + client.link.create({
621 + auth_config_id: params.authConfigId,
622 + user_id: resolvedUserId.value,
623 + ...(Option.isSome(normalizedAlias) && { alias: normalizedAlias.value }),
624 + }),
625 + catch: cause =>
626 + new ConnectedAccountsRequestError({
627 + message: `Failed to create link for auth config "${params.authConfigId}".`,
628 + cause,
629 + }),
630 + })
631 )
632 .pipe(
633 Effect.asSome,
@@ -656,7 +718,7 @@ const runConnectedAccountsLink = (params: {
718 if (params.rootOnly) {
719 if (Option.isSome(params.authConfig)) {
720 return yield* Effect.fail(
659 - new Error(
721 + invalidOptionValue(
722 '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.'
723 )
724 );
@@ -714,7 +776,8 @@ const runConnectedAccountsLink = (params: {
776 return;
777 }
778
717 - const toolkitSlug = Option.getOrThrow(params.toolkit);
779 + if (Option.isNone(params.toolkit)) return;
780 + const toolkitSlug = params.toolkit.value;
781 const resolvedProject = yield* resolveCommandProject({
782 mode: 'consumer',
783 projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
@@ -727,11 +790,11 @@ const runConnectedAccountsLink = (params: {
790 onNone: () => userContext.data.testUserId,
791 });
792 if (Option.isNone(resolvedUserId)) {
730 - return yield* Effect.fail(
731 - new Error(
732 - 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
733 - )
734 - );
793 + return yield* new MissingLinkUserIdError({
794 + message:
795 + 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
796 + flow: 'tool-router',
797 + });
798 }
799 const client = yield* clientSingleton.getFor({
800 orgId: resolvedProject.orgId,
@@ -741,7 +804,11 @@ const runConnectedAccountsLink = (params: {
804 client,
805 userId: resolvedUserId.value,
806 toolkitSlug,
744 - }).pipe(Effect.catchAll(() => Effect.succeed({ items: [] })));
807 + }).pipe(
808 + // Auxiliary fetch powering the --alias hint only: a transient list
809 + // failure must not abort the link flow.
810 + Effect.catchAll(() => Effect.succeed({ items: [] }))
811 + );
812
813 const linkOpt = yield* ui
814 .withSpinner(
@@ -757,12 +824,20 @@ const runConnectedAccountsLink = (params: {
824 }
825 : undefined,
826 });
760 - return yield* Effect.tryPromise(() =>
761 - client.toolRouter.session.link(sessionId, {
762 - toolkit: toolkitSlug,
763 - ...(Option.isSome(normalizedAliasOption) && { alias: normalizedAliasOption.value }),
764 - })
765 - );
827 + return yield* Effect.tryPromise({
828 + try: () =>
829 + client.toolRouter.session.link(sessionId, {
830 + toolkit: toolkitSlug,
831 + ...(Option.isSome(normalizedAliasOption) && {
832 + alias: normalizedAliasOption.value,
833 + }),
834 + }),
835 + catch: cause =>
836 + new ConnectedAccountsRequestError({
837 + message: `Failed to create link for toolkit "${toolkitSlug}".`,
838 + cause,
839 + }),
840 + });
841 })
842 )
843 .pipe(
@@ -784,9 +859,7 @@ const runConnectedAccountsLink = (params: {
859 return Option.none();
860 })
861 ),
787 - Effect.tap(() =>
788 - invalidateConsumerConnectedToolkitsCache().pipe(Effect.catchAll(() => Effect.void))
789 - )
862 + Effect.tap(() => invalidateConsumerConnectedToolkitsCache().pipe(Effect.ignore))
863 );
864
865 if (Option.isNone(linkOpt)) return;
@@ -832,7 +905,7 @@ const runConnectedAccountsLink = (params: {
905 connectedAccountId: connAccountId,
906 redirectUrl,
907 },
835 - }).pipe(Effect.catchAll(() => Effect.void));
908 + }).pipe(Effect.ignore);
909 } else {
910 yield* waitForActiveConnection(ui, client, connAccountId, redirectUrl, params.noBrowser);
911 yield* appendCliSessionHistory({
@@ -846,7 +919,7 @@ const runConnectedAccountsLink = (params: {
919 connectedAccountId: connAccountId,
920 redirectUrl,
921 },
849 - }).pipe(Effect.catchAll(() => Effect.void));
922 + }).pipe(Effect.ignore);
923 }
924 });
925
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.list.cmd.ts
+26 -13
@@ -1,5 +1,5 @@
1 import { Command, Options } from '@effect/cli';
2 -import { Effect, Option } from 'effect';
2 +import { Data, Effect, Option } from 'effect';
3 import type { ConnectedAccountListParams } from '@composio/client/resources/connected-accounts';
4 import { ComposioClientSingleton } from 'src/services/composio-clients';
5 import { TerminalUI } from 'src/services/terminal-ui';
@@ -13,6 +13,13 @@ import {
13 } from 'src/services/command-project';
14 import { formatConnectedAccountsTable, formatConnectedAccountsJson } from '../format';
15
16 +class ConnectedAccountsListRequestError extends Data.TaggedError(
17 + 'commands/ConnectedAccountsListRequestError'
18 +)<{
19 + readonly message: string;
20 + readonly cause: unknown;
21 +}> {}
22 +
23 const toolkits = Options.text('toolkits').pipe(
24 Options.withDescription(
25 'Filter by toolkit slugs, comma-separated (e.g. "gmail" or "gmail,slack")'
@@ -73,18 +80,24 @@ export const connectedAccountsCmd$List = Command.make(
80
81 const rawResult = yield* ui.withSpinner(
82 'Fetching connected accounts...',
76 - Effect.tryPromise(() =>
77 - client.connectedAccounts.list({
78 - toolkit_slugs: toolkitSlugs,
79 - user_ids: Option.isSome(userId) ? [userId.value] : undefined,
80 - // Bypass the stale Stainless union (still missing 'REVOKED')
81 - // until @composio/client is regenerated.
82 - statuses: Option.isSome(status)
83 - ? ([status.value] as ConnectedAccountListParams['statuses'])
84 - : undefined,
85 - limit: clampLimit(limit),
86 - })
87 - )
83 + Effect.tryPromise({
84 + try: () =>
85 + client.connectedAccounts.list({
86 + toolkit_slugs: toolkitSlugs,
87 + user_ids: Option.isSome(userId) ? [userId.value] : undefined,
88 + // Bypass the stale Stainless union (still missing 'REVOKED')
89 + // until @composio/client is regenerated.
90 + statuses: Option.isSome(status)
91 + ? ([status.value] as ConnectedAccountListParams['statuses'])
92 + : undefined,
93 + limit: clampLimit(limit),
94 + }),
95 + catch: cause =>
96 + new ConnectedAccountsListRequestError({
97 + message: 'Failed to list connected accounts.',
98 + cause,
99 + }),
100 + })
101 );
102 const result = yield* decodeConnectedAccountListWithFallback(rawResult);
103
ts/packages/cli/src/commands/connections/commands/connections.list.cmd.ts
+29 -12
@@ -1,5 +1,5 @@
1 import { Command, Options } from '@effect/cli';
2 -import { Effect, Option } from 'effect';
2 +import { Data, Effect, Option } from 'effect';
3 import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
4 import { requireAuth } from 'src/effects/require-auth';
5 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
@@ -14,6 +14,17 @@ import {
14 getConsumerPermissionSnapshot,
15 } from 'src/services/tool-permissions';
16
17 +class MissingConnectionsConsumerUserIdError extends Data.TaggedError(
18 + 'commands/MissingConnectionsConsumerUserIdError'
19 +)<{
20 + readonly message: string;
21 +}> {}
22 +
23 +class ConnectionsListRequestError extends Data.TaggedError('commands/ConnectionsListRequestError')<{
24 + readonly message: string;
25 + readonly cause: unknown;
26 +}> {}
27 +
28 const toolkit = Options.text('toolkit').pipe(
29 Options.withDescription('Filter by toolkit slug (e.g. "gmail")'),
30 Options.optional
@@ -32,7 +43,7 @@ const formatConnectionsJson = (
43 Record<string, Array<{ status: string; alias?: string | null; word_id?: string | null }>>
44 >((acc, item) => {
45 const toolkit = item.toolkit.slug;
35 - const includeAlias = toolkitCounts.get(toolkit)! > 1;
46 + const includeAlias = (toolkitCounts.get(toolkit) ?? 0) > 1;
47 const entry = {
48 status: item.status,
49 ...(includeAlias ? { alias: item.alias ?? null } : {}),
@@ -63,22 +74,28 @@ export const connectionsCmd$List = Command.make('list', { toolkit }, ({ toolkit
74
75 const consumerUserId = resolvedProject.consumerUserId;
76 if (!consumerUserId) {
66 - return yield* Effect.fail(
67 - new Error('Missing consumer user id. Run `composio login` and try again.')
68 - );
77 + return yield* new MissingConnectionsConsumerUserIdError({
78 + message: 'Missing consumer user id. Run `composio login` and try again.',
79 + });
80 }
81
82 const client = yield* clientSingleton.getFor({
83 orgId: resolvedProject.orgId,
84 projectId: resolvedProject.projectId,
85 });
75 - const rawResult = yield* Effect.tryPromise(() =>
76 - client.connectedAccounts.list({
77 - toolkit_slugs: toolkitSlug ? [toolkitSlug] : undefined,
78 - user_ids: [consumerUserId],
79 - limit: 1000,
80 - })
81 - );
86 + const rawResult = yield* Effect.tryPromise({
87 + try: () =>
88 + client.connectedAccounts.list({
89 + toolkit_slugs: toolkitSlug ? [toolkitSlug] : undefined,
90 + user_ids: [consumerUserId],
91 + limit: 1000,
92 + }),
93 + catch: cause =>
94 + new ConnectionsListRequestError({
95 + message: 'Failed to list connections.',
96 + cause,
97 + }),
98 + });
99 const result = yield* decodeConnectedAccountListWithFallback(rawResult);
100 const permissionSnapshot = yield* getConsumerPermissionSnapshot({
101 orgId: resolvedProject.orgId,
ts/packages/cli/src/commands/connections/commands/connections.remove.cmd.ts
+43 -15
@@ -1,5 +1,5 @@
1 import { Args, Command } from '@effect/cli';
2 -import { Effect } from 'effect';
2 +import { Data, Effect } from 'effect';
3 import { decodeConnectedAccountListWithFallback } from 'src/effects/decode-connected-account-list';
4 import { requireAuth } from 'src/effects/require-auth';
5 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
@@ -12,6 +12,19 @@ import { TerminalUI } from 'src/services/terminal-ui';
12 import { bold } from 'src/ui/colors';
13 import { redact } from 'src/ui/redact';
14
15 +class MissingConnectionRemovalConsumerUserIdError extends Data.TaggedError(
16 + 'commands/MissingConnectionRemovalConsumerUserIdError'
17 +)<{
18 + readonly message: string;
19 +}> {}
20 +
21 +class ConnectionsRemovalRequestError extends Data.TaggedError(
22 + 'commands/ConnectionsRemovalRequestError'
23 +)<{
24 + readonly message: string;
25 + readonly cause: unknown;
26 +}> {}
27 +
28 const account = Args.text({ name: 'account' }).pipe(
29 Args.withDescription('Connection selector: toolkit slug, alias, word_id, or connected account ID')
30 );
@@ -60,12 +73,14 @@ const resolveAccount = (params: {
73 const idMatches = matches.filter(
74 item => normalizeSelector(item.id) === normalizeSelector(params.selector)
75 );
63 - if (idMatches.length === 1) {
64 - return idMatches[0]!;
76 + const idMatch = idMatches[0];
77 + if (idMatch && idMatches.length === 1) {
78 + return idMatch;
79 }
80
67 - if (matches.length === 1) {
68 - return matches[0]!;
81 + const match = matches[0];
82 + if (match && matches.length === 1) {
83 + return match;
84 }
85
86 return {
@@ -89,9 +104,9 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ acco
104
105 const consumerUserId = resolvedProject.consumerUserId;
106 if (!consumerUserId) {
92 - return yield* Effect.fail(
93 - new Error('Missing consumer user id. Run `composio login` and try again.')
94 - );
107 + return yield* new MissingConnectionRemovalConsumerUserIdError({
108 + message: 'Missing consumer user id. Run `composio login` and try again.',
109 + });
110 }
111
112 const client = yield* clientSingleton.getFor({
@@ -100,12 +115,18 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ acco
115 });
116 const rawResult = yield* ui.withSpinner(
117 'Fetching connections...',
103 - Effect.tryPromise(() =>
104 - client.connectedAccounts.list({
105 - user_ids: [consumerUserId],
106 - limit: 1000,
107 - })
108 - )
118 + Effect.tryPromise({
119 + try: () =>
120 + client.connectedAccounts.list({
121 + user_ids: [consumerUserId],
122 + limit: 1000,
123 + }),
124 + catch: cause =>
125 + new ConnectionsRemovalRequestError({
126 + message: 'Failed to list connections.',
127 + cause,
128 + }),
129 + })
130 );
131 const result = yield* decodeConnectedAccountListWithFallback(rawResult);
132 const resolved = resolveAccount({ accounts: result.items, selector: account });
@@ -130,7 +151,14 @@ export const connectionsCmd$Remove = Command.make('remove', { account }, ({ acco
151
152 yield* ui.withSpinner(
153 `Removing ${resolved.toolkit.slug} connection...`,
133 - Effect.tryPromise(() => client.connectedAccounts.delete(resolved.id)),
154 + Effect.tryPromise({
155 + try: () => client.connectedAccounts.delete(resolved.id),
156 + catch: cause =>
157 + new ConnectionsRemovalRequestError({
158 + message: `Failed to remove connected account "${resolved.id}".`,
159 + cause,
160 + }),
161 + }),
162 {
163 successMessage: `Removed ${resolved.toolkit.slug} connection.`,
164 errorMessage: `Failed to remove ${resolved.toolkit.slug} connection.`,
ts/packages/cli/src/commands/dev.cmd.ts
+5 -3
@@ -10,7 +10,7 @@ import { connectedAccountsCmd } from './connected-accounts/connected-accounts.cm
10 import { triggersCmd } from './triggers/triggers.cmd';
11 import { projectsCmd } from './projects/projects.cmd';
12 import { devNativeUiCmd } from './dev/dev.native-ui.cmd';
13 -import { ComposioCliUserConfig, resolveCliConfigPathSync } from 'src/services/cli-user-config';
13 +import { ComposioCliUserConfig, resolveCliConfigPath } from 'src/services/cli-user-config';
14 import { Stdin } from 'src/services/stdin';
15 import { TerminalUI } from 'src/services/terminal-ui';
16 import type { CommandVisibility } from './feature-tags';
@@ -51,9 +51,10 @@ const applyDeveloperModeChange = (enabled: boolean) =>
51
52 if (enabled) {
53 if (!stdin.isTTY()) {
54 + const configPath = yield* resolveCliConfigPath;
55 yield* ui.log.error('Enabling developer mode requires an interactive terminal.');
56 yield* ui.log.step(
56 - `Set "developer.enabled": true manually in ${resolveCliConfigPathSync()} if you really want to enable it outside an interactive session.`
57 + `Set "developer.enabled": true manually in ${configPath} if you really want to enable it outside an interactive session.`
58 );
59 return;
60 }
@@ -85,7 +86,8 @@ const applyDeveloperModeChange = (enabled: boolean) =>
86 ? 'Developer mode enabled.'
87 : 'Developer mode disabled. Only `composio dev --mode on|off` remains available.'
88 );
88 - yield* ui.log.step(`Config updated: ${resolveCliConfigPathSync()}`);
89 + const configPath = yield* resolveCliConfigPath;
90 + yield* ui.log.step(`Config updated: ${configPath}`);
91 });
92
93 const promptForDeveloperMode = () =>
ts/packages/cli/src/commands/listen.cmd.ts
+184 -117
@@ -1,7 +1,7 @@
1 -import { Args, Command, Options } from '@effect/cli';
1 +import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';
2 import { FileSystem, Path } from '@effect/platform';
3 import type { Composio as RawComposioClient } from '@composio/client';
4 -import { Deferred, Effect, Either, Option, Runtime } from 'effect';
4 +import { Data, Deferred, Effect, Either, Option, Predicate, Runtime } from 'effect';
5 import { requireAuth } from 'src/effects/require-auth';
6 import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
7 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -25,6 +25,29 @@ import { ComposioCliUserConfig } from 'src/services/cli-user-config';
25 import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
26 import { matchesTriggerListenFilters } from './triggers/filter';
27 import { parseTriggerListenEvent } from './triggers/parse';
28 +import { decodeConnectedAccountItemsWithFallback } from 'src/effects/decode-connected-account-list';
29 +
30 +type TriggerCreateParams = NonNullable<
31 + Parameters<RawComposioClient['triggerInstances']['upsert']>[1]
32 +>;
33 +
34 +export class ListenCommandError extends Data.TaggedError('commands/ListenCommandError')<{
35 + readonly reason:
36 + | 'project_context'
37 + | 'connected_accounts'
38 + | 'connected_account_not_found'
39 + | 'create_trigger'
40 + | 'disable_trigger';
41 + readonly message: string;
42 + readonly slug?: string;
43 + readonly toolkitSlug?: string;
44 + readonly cause?: unknown;
45 +}> {}
46 +
47 +const invalidOptionValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));
48 +
49 +const errorMessage = (error: unknown): string =>
50 + Predicate.isError(error) ? error.message : String(error);
51
52 const slug = Args.text({ name: 'slug' }).pipe(
53 Args.withDescription(
@@ -73,6 +96,27 @@ const debug = Options.boolean('debug').pipe(
96 const sanitizePathPart = (value: string): string =>
97 value.replace(/[^A-Z0-9._-]+/gi, '-').replace(/^-+|-+$/g, '') || 'unknown';
98
99 +const disableTemporaryTrigger = (params: {
100 + client: RawComposioClient;
101 + ui: TerminalUI;
102 + slug: string;
103 + triggerId: string;
104 +}) =>
105 + Effect.tryPromise({
106 + try: () =>
107 + params.client.triggerInstances.manage.update(params.triggerId, { status: 'disable' }),
108 + catch: cause =>
109 + new ListenCommandError({
110 + reason: 'disable_trigger',
111 + message: `Failed to disable temporary trigger "${params.triggerId}": ${String(cause)}`,
112 + slug: params.slug,
113 + cause,
114 + }),
115 + }).pipe(
116 + Effect.tapError(error => params.ui.log.warn(error.message)),
117 + Effect.ignore
118 + );
119 +
120 const isProjectEventType = (value: string): boolean => value.startsWith('composio.');
121
122 const resolveParamsInput = (input: Option.Option<string>) =>
@@ -80,13 +124,12 @@ const resolveParamsInput = (input: Option.Option<string>) =>
124
125 const parseCreateParams = (raw: string) =>
126 parseJsonRecord(raw).pipe(
83 - Either.mapLeft(
84 - error =>
85 - new Error(
86 - error.reason === 'not-a-record'
87 - ? "Expected --params to be an object, e.g. -p '{ trigger_config: { ... } }'."
88 - : "Invalid --params input. Provide JSON or a JS-style object literal, e.g. -p '{ trigger_config: { ... } }'."
89 - )
127 + Either.mapLeft(error =>
128 + invalidOptionValue(
129 + error.reason === 'not-a-record'
130 + ? "Expected --params to be an object, e.g. -p '{ trigger_config: { ... } }'."
131 + : "Invalid --params input. Provide JSON or a JS-style object literal, e.g. -p '{ trigger_config: { ... } }'."
132 + )
133 )
134 );
135
@@ -97,7 +140,7 @@ const assertSupportedListenParams = (params: {
140 }) =>
141 params.listeningToProjectEvent && Object.keys(params.createParamsInput).length > 0
142 ? Effect.fail(
100 - new Error(
143 + invalidOptionValue(
144 `--params is only supported for trigger slugs. "${params.slug}" is a project-level composio.* event type and does not create a temporary trigger.`
145 )
146 )
@@ -113,7 +156,7 @@ const resolveConnectedAccountIdForTrigger = (params: {
156 const toolkitSlug = toolkitFromToolSlug(params.slug);
157 if (!toolkitSlug) {
158 return yield* Effect.fail(
116 - new Error(
159 + invalidOptionValue(
160 `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".`
161 )
162 );
@@ -127,31 +170,50 @@ const resolveConnectedAccountIdForTrigger = (params: {
170 statuses: ['ACTIVE'],
171 limit: 100,
172 }),
130 - catch: error =>
131 - new Error(`Failed to list connected accounts for "${toolkitSlug}": ${String(error)}`),
173 + catch: cause =>
174 + new ListenCommandError({
175 + reason: 'connected_accounts',
176 + message: `Failed to list connected accounts for "${toolkitSlug}": ${String(cause)}`,
177 + slug: params.slug,
178 + toolkitSlug,
179 + cause,
180 + }),
181 });
182 + const selectableAccounts = yield* decodeConnectedAccountItemsWithFallback(
183 + connectedAccounts.items
184 + ).pipe(
185 + Effect.mapError(
186 + cause =>
187 + new ListenCommandError({
188 + reason: 'connected_accounts',
189 + message: `Connected accounts for toolkit "${toolkitSlug}" did not match the expected response shape.`,
190 + slug: params.slug,
191 + toolkitSlug,
192 + cause,
193 + })
194 + )
195 + );
196 const selectedAccount = resolveConnectedAccountSelection(
134 - connectedAccounts.items as Parameters<typeof resolveConnectedAccountSelection>[0],
197 + selectableAccounts,
198 Option.getOrUndefined(params.account)
199 );
200 if (selectedAccount?.id) {
201 return selectedAccount.id;
202 }
203
141 - const choices = formatConnectedAccountChoices(
142 - connectedAccounts.items as Parameters<typeof formatConnectedAccountChoices>[0]
143 - );
204 + const choices = formatConnectedAccountChoices(selectableAccounts);
205 const suffix =
206 Option.isSome(params.account) && choices.length > 0
207 ? ` Available accounts: ${choices.join(', ')}.`
208 : '';
148 - return yield* Effect.fail(
149 - new Error(
150 - Option.isSome(params.account)
151 - ? `No connected account matched "${params.account.value}" for toolkit "${toolkitSlug}" and consumer user "${params.consumerUserId}".${suffix}`
152 - : `No active connected account found for toolkit "${toolkitSlug}" and consumer user "${params.consumerUserId}". Run \`composio link ${toolkitSlug}\` first.`
153 - )
154 - );
209 + return yield* new ListenCommandError({
210 + reason: 'connected_account_not_found',
211 + message: Option.isSome(params.account)
212 + ? `No connected account matched "${params.account.value}" for toolkit "${toolkitSlug}" and consumer user "${params.consumerUserId}".${suffix}`
213 + : `No active connected account found for toolkit "${toolkitSlug}" and consumer user "${params.consumerUserId}". Run \`composio link ${toolkitSlug}\` first.`,
214 + slug: params.slug,
215 + toolkitSlug,
216 + });
217 });
218 const emitStreamLine = (line: string, ui: TerminalUI) =>
219 Effect.gen(function* () {
@@ -163,13 +225,8 @@ const eventTypeOf = (eventData: Record<string, unknown>): string | undefined =>
225 typeof eventData.type === 'string' && eventData.type.length > 0 ? eventData.type : undefined;
226
227 const extractEventFileId = (eventData: Record<string, unknown>): string => {
166 - const candidates = [
167 - eventData.id,
168 - eventData.log_id,
169 - typeof eventData.metadata === 'object' && eventData.metadata !== null
170 - ? (eventData.metadata as Record<string, unknown>).id
171 - : undefined,
172 - ];
228 + const metadata = Predicate.isRecord(eventData.metadata) ? eventData.metadata : undefined;
229 + const candidates = [eventData.id, eventData.log_id, metadata?.id];
230
231 for (const candidate of candidates) {
232 if (typeof candidate === 'string' && candidate.length > 0) {
@@ -180,36 +237,43 @@ const extractEventFileId = (eventData: Record<string, unknown>): string => {
237 return `${Date.now()}-${crypto.randomUUID().slice(0, 8)}`;
238 };
239
183 -const parseStreamPath = (expression: string): ReadonlyArray<string | number> => {
184 - const trimmed = expression.trim();
185 - if (!trimmed.startsWith('.')) {
186 - throw new Error('Expected --stream to contain a jq-like path starting with "."');
187 - }
188 -
189 - const pathTokens: Array<string | number> = [];
190 - const tokenPattern = /(?:\.([A-Za-z0-9_-]+))|(?:\[(\d+)\])/g;
191 - let lastIndex = 0;
192 -
193 - for (const match of trimmed.matchAll(tokenPattern)) {
194 - if ((match.index ?? -1) !== lastIndex) {
195 - throw new Error(
196 - 'Unsupported --stream expression. Use a jq-like path such as ".foo.bar" or ".items[0].id".'
240 +const parseStreamPath = (expression: string) =>
241 + Effect.gen(function* () {
242 + const trimmed = expression.trim();
243 + if (!trimmed.startsWith('.')) {
244 + return yield* Effect.fail(
245 + invalidOptionValue('Expected --stream to contain a jq-like path starting with "."')
246 );
247 }
248
200 - if (match[1]) pathTokens.push(match[1]);
201 - if (match[2]) pathTokens.push(Number(match[2]));
202 - lastIndex += match[0].length;
203 - }
249 + const pathTokens: Array<string | number> = [];
250 + const tokenPattern = /(?:\.([A-Za-z0-9_-]+))|(?:\[(\d+)\])/g;
251 + let lastIndex = 0;
252 +
253 + for (const match of trimmed.matchAll(tokenPattern)) {
254 + if ((match.index ?? -1) !== lastIndex) {
255 + return yield* Effect.fail(
256 + invalidOptionValue(
257 + 'Unsupported --stream expression. Use a jq-like path such as ".foo.bar" or ".items[0].id".'
258 + )
259 + );
260 + }
261
205 - if (lastIndex !== trimmed.length) {
206 - throw new Error(
207 - 'Unsupported --stream expression. Use a jq-like path such as ".foo.bar" or ".items[0].id".'
208 - );
209 - }
262 + if (match[1]) pathTokens.push(match[1]);
263 + if (match[2]) pathTokens.push(Number(match[2]));
264 + lastIndex += match[0].length;
265 + }
266
211 - return pathTokens;
212 -};
267 + if (lastIndex !== trimmed.length) {
268 + return yield* Effect.fail(
269 + invalidOptionValue(
270 + 'Unsupported --stream expression. Use a jq-like path such as ".foo.bar" or ".items[0].id".'
271 + )
272 + );
273 + }
274 +
275 + return pathTokens;
276 + });
277
278 const applyStreamPath = (value: unknown, pathTokens: ReadonlyArray<string | number>): unknown => {
279 let current = value;
@@ -222,11 +286,11 @@ const applyStreamPath = (value: unknown, pathTokens: ReadonlyArray<string | numb
286 continue;
287 }
288
225 - if (typeof current !== 'object' || current === null || Array.isArray(current)) {
289 + if (!Predicate.isRecord(current)) {
290 return undefined;
291 }
292
229 - current = (current as Record<string, unknown>)[token];
293 + current = current[token];
294 }
295
296 return current;
@@ -279,25 +343,23 @@ const TIMEOUT_UNITS_MS: Record<string, number> = {
343 days: 86_400_000,
344 };
345
282 -const parseTimeoutMs = (value: string): number => {
283 - const trimmed = value.trim().toLowerCase();
284 - const match = /^(\d+(?:\.\d+)?)\s*([a-z]+)$/.exec(trimmed);
285 - if (!match) {
286 - throw new Error(
287 - 'Invalid --timeout value. Use a duration such as "30s", "5m", "1hr", or "1day".'
288 - );
289 - }
290 -
291 - const amount = Number(match[1]);
292 - const unitMs = TIMEOUT_UNITS_MS[match[2]];
293 - if (!Number.isFinite(amount) || amount <= 0 || unitMs === undefined) {
294 - throw new Error(
295 - 'Invalid --timeout value. Use a duration such as "30s", "5m", "1hr", or "1day".'
296 - );
297 - }
346 +const parseTimeoutMs = (value: string) =>
347 + Effect.gen(function* () {
348 + const trimmed = value.trim().toLowerCase();
349 + const match = /^(\d+(?:\.\d+)?)\s*([a-z]+)$/.exec(trimmed);
350 + const amount = Number(match?.[1]);
351 + const unit = match?.[2];
352 + const unitMs = unit === undefined ? undefined : TIMEOUT_UNITS_MS[unit];
353 + if (!match || !Number.isFinite(amount) || amount <= 0 || unitMs === undefined) {
354 + return yield* Effect.fail(
355 + invalidOptionValue(
356 + 'Invalid --timeout value. Use a duration such as "30s", "5m", "1hr", or "1day".'
357 + )
358 + );
359 + }
360
299 - return Math.round(amount * unitMs);
300 -};
361 + return Math.round(amount * unitMs);
362 + });
363
364 const resolveListenSetup = (params: {
365 readonly slug: string;
@@ -314,10 +376,13 @@ const resolveListenSetup = (params: {
376 };
377 }) =>
378 Effect.gen(function* () {
317 - if (!params.resolvedProject.consumerUserId) {
318 - return yield* Effect.fail(
319 - new Error('No consumer user is available in the current project context.')
320 - );
379 + const consumerUserId = params.resolvedProject.consumerUserId;
380 + if (!consumerUserId) {
381 + return yield* new ListenCommandError({
382 + reason: 'project_context',
383 + message: 'No consumer user is available in the current project context.',
384 + slug: params.slug,
385 + });
386 }
387
388 const listeningToProjectEvent = isProjectEventType(params.slug);
@@ -336,34 +401,34 @@ const resolveListenSetup = (params: {
401 : yield* resolveConnectedAccountIdForTrigger({
402 client: params.client,
403 slug: params.slug,
339 - consumerUserId: params.resolvedProject.consumerUserId,
404 + consumerUserId,
405 account: params.account,
406 });
407
343 - const createParams = listeningToProjectEvent
408 + const createParams: TriggerCreateParams | undefined = listeningToProjectEvent
409 ? undefined
345 - : ({
410 + : {
411 ...createParamsInput,
412 connected_account_id: resolvedConnectedAccountId,
348 - } as Parameters<typeof params.client.triggerInstances.upsert>[1]);
413 + };
414 +
415 + const timeoutMs = Option.isSome(params.timeout)
416 + ? yield* parseTimeoutMs(params.timeout.value)
417 + : undefined;
418 + const streamPath = Option.isSome(params.stream)
419 + ? params.stream.value.trim().length === 0
420 + ? []
421 + : yield* parseStreamPath(params.stream.value)
422 + : undefined;
423
424 return {
425 listeningToProjectEvent,
426 createParams,
353 - timeoutMs: Option.match(params.timeout, {
354 - onNone: () => undefined,
355 - onSome: value => parseTimeoutMs(value),
356 - }),
357 - streamPath: Option.match(params.stream, {
358 - onNone: () => undefined,
359 - onSome: value => {
360 - const trimmed = value.trim();
361 - return trimmed.length === 0 ? [] : parseStreamPath(trimmed);
362 - },
363 - }),
427 + timeoutMs,
428 + streamPath,
429 shouldStream: Option.isSome(params.stream),
430 maxEventsLimit: Option.getOrUndefined(params.maxEvents),
366 - consumerUserId: params.resolvedProject.consumerUserId,
431 + consumerUserId,
432 };
433 });
434
@@ -382,7 +447,15 @@ export const listenCmd = Command.make(
447 const realtime = yield* TriggersRealtime;
448
449 const resolvedProject = yield* resolveCommandProject({ mode: 'consumer' }).pipe(
385 - Effect.mapError(formatResolveCommandProjectError)
450 + Effect.mapError(cause => {
451 + const formatted = formatResolveCommandProjectError(cause);
452 + return new ListenCommandError({
453 + reason: 'project_context',
454 + message: formatted.message,
455 + slug,
456 + cause,
457 + });
458 + })
459 );
460
461 const client = yield* clientSingleton.getFor({
@@ -440,8 +513,13 @@ export const listenCmd = Command.make(
513 ? Effect.succeed<null | { trigger_id: string }>(null)
514 : Effect.tryPromise({
515 try: () => client.triggerInstances.upsert(slug, createParams),
443 - catch: error =>
444 - new Error(`Failed to create temporary trigger "${slug}": ${String(error)}`),
516 + catch: cause =>
517 + new ListenCommandError({
518 + reason: 'create_trigger',
519 + message: `Failed to create temporary trigger "${slug}": ${String(cause)}`,
520 + slug,
521 + cause,
522 + }),
523 }),
524 createdTrigger =>
525 Effect.gen(function* () {
@@ -478,15 +556,16 @@ export const listenCmd = Command.make(
556 const filterResult =
557 createdTrigger === null
558 ? eventTypeOf(eventData) === slug
481 - : matchesTriggerListenFilters(
559 + : parsedTriggerEvent !== undefined &&
560 + matchesTriggerListenFilters(
561 { triggerId: createdTrigger.trigger_id },
483 - parsedTriggerEvent!
562 + parsedTriggerEvent
563 );
564 if (debug) {
565 yield* emitStreamLine(
566 createdTrigger === null
567 ? `[debug] event.type=${eventTypeOf(eventData) ?? '<missing>'} match=${filterResult}`
489 - : `[debug] parsed.id=${parsedTriggerEvent!.id} triggerSlug=${parsedTriggerEvent!.triggerSlug} trigger_id=${createdTrigger.trigger_id} match=${filterResult}`,
568 + : `[debug] parsed.id=${parsedTriggerEvent?.id ?? '<missing>'} triggerSlug=${parsedTriggerEvent?.triggerSlug ?? '<missing>'} trigger_id=${createdTrigger.trigger_id} match=${filterResult}`,
569 ui
570 );
571 }
@@ -533,9 +612,8 @@ export const listenCmd = Command.make(
612 yield* Deferred.succeed(stopWhenDone, 'max-events').pipe(Effect.ignore);
613 }
614 }).pipe(
536 - Effect.catchAll(error =>
537 - ui.log.warn(error instanceof Error ? error.message : String(error))
538 - )
615 + Effect.tapError(error => ui.log.warn(errorMessage(error))),
616 + Effect.ignore
617 )
618 );
619 };
@@ -589,18 +667,7 @@ export const listenCmd = Command.make(
667 created =>
668 created === null
669 ? Effect.void
592 - : Effect.tryPromise({
593 - try: () =>
594 - client.triggerInstances.manage.update(created.trigger_id, { status: 'disable' }),
595 - catch: error =>
596 - new Error(
597 - `Failed to disable temporary trigger "${created.trigger_id}": ${String(error)}`
598 - ),
599 - }).pipe(
600 - Effect.catchAll(error =>
601 - ui.log.warn(error instanceof Error ? error.message : String(error))
602 - )
603 - )
670 + : disableTemporaryTrigger({ client, ui, slug, triggerId: created.trigger_id })
671 ).pipe(
672 Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>
673 Effect.gen(function* () {
ts/packages/cli/src/commands/local-tools/commands/local-tools.configure.cmd.ts
+35 -10
@@ -1,4 +1,4 @@
1 -import { Args, Command, Options } from '@effect/cli';
1 +import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';
2 import {
3 getLocalToolsMetaPath,
4 isLocalToolkitSlug,
@@ -7,7 +7,7 @@ import {
7 updateLocalToolMeta,
8 type LocalToolMetaEntry,
9 } from '@composio/cli-local-tools';
10 -import { Effect, Option } from 'effect';
10 +import { Data, Effect, Option, Predicate } from 'effect';
11 import { TerminalUI } from 'src/services/terminal-ui';
12 import { bold, gray } from 'src/ui/colors';
13
@@ -58,6 +58,19 @@ type ConfigureTarget =
58 readonly toolkitSlug: string;
59 };
60
61 +export class LocalToolsConfigureError extends Data.TaggedError(
62 + 'commands/local-tools/LocalToolsConfigureError'
63 +)<{
64 + readonly message: string;
65 + readonly target: ConfigureTarget;
66 + readonly cause: unknown;
67 +}> {}
68 +
69 +const errorMessage = (error: unknown): string =>
70 + Predicate.isError(error) ? error.message : String(error);
71 +
72 +const invalidValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));
73 +
74 const resolveTarget = (value: string): ConfigureTarget | null => {
75 const localTool = resolveLocalTool(value, { includeUnsupported: true });
76 if (localTool) {
@@ -137,7 +150,7 @@ export const localToolsCmd$Configure = Command.make(
150 const target = resolveTarget(selector);
151 if (!target) {
152 return yield* Effect.fail(
140 - new Error(
153 + invalidValue(
154 `Unknown local toolkit/tool "${selector}". Run \`composio local-tools list --all-platforms\` to inspect valid selectors.`
155 )
156 );
@@ -145,16 +158,28 @@ export const localToolsCmd$Configure = Command.make(
158
159 const patch = buildPatch({ command, disable, enable, authenticated, unauthenticated });
160 if ('error' in patch) {
148 - return yield* Effect.fail(new Error(patch.error));
161 + return yield* Effect.fail(invalidValue(patch.error));
162 }
163
151 - const metadata = yield* Effect.tryPromise(() =>
152 - target.kind === 'toolkit'
153 - ? updateLocalToolkitMeta(target.key, patch)
154 - : updateLocalToolMeta(target.key, patch)
155 - );
164 + const metadata = yield* Effect.tryPromise({
165 + try: () =>
166 + target.kind === 'toolkit'
167 + ? updateLocalToolkitMeta(target.key, patch)
168 + : updateLocalToolMeta(target.key, patch),
169 + catch: cause =>
170 + new LocalToolsConfigureError({
171 + message: errorMessage(cause),
172 + target,
173 + cause,
174 + }),
175 + });
176 const entry =
157 - target.kind === 'toolkit' ? metadata.toolkits[target.key]! : metadata.tools[target.key]!;
177 + target.kind === 'toolkit' ? metadata.toolkits[target.key] : metadata.tools[target.key];
178 + if (!entry) {
179 + return yield* Effect.dieMessage(
180 + `Local tools metadata invariant violated: ${target.kind} ${target.key} was not updated`
181 + );
182 + }
183 const metadataPath = getLocalToolsMetaPath();
184 const payload = { metadataPath, target, entry };
185
ts/packages/cli/src/commands/local-tools/commands/local-tools.doctor.cmd.ts
+41 -14
@@ -6,7 +6,7 @@ import {
6 type LocalReadinessStatus,
7 type LocalToolsReadinessReport,
8 } from '@composio/cli-local-tools';
9 -import { Effect, Option } from 'effect';
9 +import { Data, Effect, Option, Predicate } from 'effect';
10 import { TerminalUI } from 'src/services/terminal-ui';
11 import { bold, gray, green, red } from 'src/ui/colors';
12 import { truncate } from 'src/ui/truncate';
@@ -31,6 +31,18 @@ const toolkits = Options.text('toolkits').pipe(
31 Options.withDescription('Filter by local toolkit slugs, comma-separated')
32 );
33
34 +export class LocalToolsDoctorError extends Data.TaggedError(
35 + 'commands/local-tools/LocalToolsDoctorError'
36 +)<{
37 + readonly message: string;
38 + readonly operation: 'check' | 'strict';
39 + readonly notReadyTools: ReadonlyArray<string>;
40 + readonly cause?: unknown;
41 +}> {}
42 +
43 +const errorMessage = (error: unknown): string =>
44 + Predicate.isError(error) ? error.message : String(error);
45 +
46 const parseToolkitFilter = (value: Option.Option<string>): ReadonlyArray<string> | undefined => {
47 const raw = Option.getOrUndefined(value);
48 if (!raw?.trim()) return undefined;
@@ -59,9 +71,11 @@ const statusLabel = (status: LocalReadinessStatus): string => {
71 return red(status);
72 };
73
62 -const hasProblems = (report: LocalToolsReadinessReport): boolean =>
63 - report.toolkits.some(toolkit =>
64 - toolkit.tools.some(tool => tool.status !== 'ready' && tool.status !== 'unsupported')
74 +const notReadyTools = (report: LocalToolsReadinessReport): ReadonlyArray<string> =>
75 + report.toolkits.flatMap(toolkit =>
76 + toolkit.tools
77 + .filter(tool => tool.status !== 'ready' && tool.status !== 'unsupported')
78 + .map(tool => tool.finalSlug)
79 );
80
81 const formatDoctorReport = (report: LocalToolsReadinessReport, metadataPath: string): string => {
@@ -115,12 +129,20 @@ export const localToolsCmd$Doctor = Command.make(
129 const ui = yield* TerminalUI;
130 const toolkitFilter = parseToolkitFilter(toolkits);
131 const metadataPath = getLocalToolsMetaPath();
118 - const report = yield* Effect.tryPromise(() =>
119 - checkLocalToolkitsReadiness({
120 - includeUnsupported: allPlatforms,
121 - toolkits: toolkitFilter,
122 - })
123 - );
132 + const report = yield* Effect.tryPromise({
133 + try: () =>
134 + checkLocalToolkitsReadiness({
135 + includeUnsupported: allPlatforms,
136 + toolkits: toolkitFilter,
137 + }),
138 + catch: cause =>
139 + new LocalToolsDoctorError({
140 + message: errorMessage(cause),
141 + operation: 'check',
142 + notReadyTools: [],
143 + cause,
144 + }),
145 + });
146
147 if (json) {
148 yield* ui.output(JSON.stringify({ metadataPath, ...report }, null, 2), { force: true });
@@ -128,10 +150,15 @@ export const localToolsCmd$Doctor = Command.make(
150 yield* ui.log.message(formatDoctorReport(report, metadataPath));
151 }
152
131 - if (strict && hasProblems(report)) {
132 - return yield* Effect.fail(
133 - new Error('One or more local tools are not ready. Run without --strict for setup hints.')
134 - );
153 + if (strict) {
154 + const problems = notReadyTools(report);
155 + if (problems.length > 0) {
156 + return yield* new LocalToolsDoctorError({
157 + message: 'One or more local tools are not ready. Run without --strict for setup hints.',
158 + operation: 'strict',
159 + notReadyTools: problems,
160 + });
161 + }
162 }
163 })
164 ).pipe(
ts/packages/cli/src/commands/local-tools/commands/local-tools.meta.cmd.ts
+30 -10
@@ -5,10 +5,15 @@ import {
5 readLocalToolsMeta,
6 writeLocalToolsMeta,
7 } from '@composio/cli-local-tools';
8 -import { Effect } from 'effect';
8 +import { Data, Effect } from 'effect';
9 import { TerminalUI } from 'src/services/terminal-ui';
10 import { bold, gray } from 'src/ui/colors';
11
12 +class LocalToolsMetaError extends Data.TaggedError('commands/LocalToolsMetaError')<{
13 + readonly message: string;
14 + readonly cause: unknown;
15 +}> {}
16 +
17 const json = Options.boolean('json').pipe(
18 Options.withDefault(false),
19 Options.withDescription('Print the metadata file contents as JSON')
@@ -24,16 +29,31 @@ export const localToolsCmd$Meta = Command.make('meta', { json, init }, ({ json,
29 const ui = yield* TerminalUI;
30 const metadataPath = getLocalToolsMetaPath();
31 const meta = init
27 - ? yield* Effect.tryPromise(async () => {
28 - const existing = await readLocalToolsMeta();
29 - const next =
30 - Object.keys(existing.tools).length === 0 && Object.keys(existing.toolkits).length === 0
31 - ? createEmptyLocalToolsMeta()
32 - : existing;
33 - await writeLocalToolsMeta(next);
34 - return next;
32 + ? yield* Effect.tryPromise({
33 + try: async () => {
34 + const existing = await readLocalToolsMeta();
35 + const next =
36 + Object.keys(existing.tools).length === 0 &&
37 + Object.keys(existing.toolkits).length === 0
38 + ? createEmptyLocalToolsMeta()
39 + : existing;
40 + await writeLocalToolsMeta(next);
41 + return next;
42 + },
43 + catch: cause =>
44 + new LocalToolsMetaError({
45 + message: `Failed to initialize the local tools metadata file at ${metadataPath}.`,
46 + cause,
47 + }),
48 })
36 - : yield* Effect.tryPromise(() => readLocalToolsMeta());
49 + : yield* Effect.tryPromise({
50 + try: () => readLocalToolsMeta(),
51 + catch: cause =>
52 + new LocalToolsMetaError({
53 + message: `Failed to read the local tools metadata file at ${metadataPath}.`,
54 + cause,
55 + }),
56 + });
57
58 const payload = {
59 metadataPath,
ts/packages/cli/src/commands/login.cmd.ts
+102 -72
@@ -1,8 +1,6 @@
1 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
2 -import path from 'node:path';
3 -import { Command, Options } from '@effect/cli';
4 -import { FileSystem } from '@effect/platform';
5 -import { DateTime, Effect, Option, Schedule } from 'effect';
1 +import { Command, HelpDoc, Options, ValidationError } from '@effect/cli';
2 +import { FileSystem, Path } from '@effect/platform';
3 +import { Data, DateTime, Effect, Option, Schedule, Schema } from 'effect';
4 import open from 'open';
5 import {
6 ComposioSessionRepository,
@@ -82,40 +80,45 @@ const LOGIN_POLL_INTERVAL_SECONDS = 5;
80 const LOGIN_POLL_TIMEOUT_SECONDS = 10 * 60;
81 const LOGIN_POLL_RETRIES = Math.ceil(LOGIN_POLL_TIMEOUT_SECONDS / LOGIN_POLL_INTERVAL_SECONDS);
82
85 -type PendingLoginSession = {
86 - readonly key: string;
87 - readonly loginUrl: string;
88 - readonly expiresAt: string;
89 - readonly cachedAt: string;
90 -};
83 +const PendingLoginSession = Schema.Struct({
84 + key: Schema.String,
85 + loginUrl: Schema.String,
86 + expiresAt: Schema.String,
87 + cachedAt: Schema.String,
88 +});
89 +type PendingLoginSession = Schema.Schema.Type<typeof PendingLoginSession>;
90 +
91 +class PendingLoginError extends Data.TaggedError('commands/PendingLoginError')<{
92 + readonly message: string;
93 + readonly reason: 'invalid' | 'missing' | 'expired';
94 + readonly cause?: unknown;
95 +}> {}
96 +
97 +class LoginSessionError extends Data.TaggedError('commands/LoginSessionError')<{
98 + readonly message: string;
99 + readonly operation: 'load' | 'poll';
100 + readonly status?: string;
101 + readonly cause?: unknown;
102 +}> {}
103 +
104 +class LoginBrowserOpenError extends Data.TaggedError('commands/LoginBrowserOpenError')<{
105 + readonly message: string;
106 + readonly cause: unknown;
107 +}> {}
108 +
109 +class InvalidOrganizationError extends Data.TaggedError('commands/InvalidOrganizationError')<{
110 + readonly message: string;
111 + readonly requestedOrg: string;
112 +}> {}
113 +
114 +const invalidOptionValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));
115
116 const pendingLoginPath = Effect.gen(function* () {
117 + const path = yield* Path.Path;
118 const cacheDir = yield* setupCacheDir;
119 return path.join(cacheDir, PENDING_LOGIN_FILE_NAME);
120 });
121
97 -const isRecord = (value: unknown): value is Record<string, unknown> =>
98 - typeof value === 'object' && value !== null;
99 -
100 -const parsePendingLoginSession = (raw: string): PendingLoginSession => {
101 - const parsed: unknown = JSON.parse(raw);
102 - if (
103 - !isRecord(parsed) ||
104 - typeof parsed.key !== 'string' ||
105 - typeof parsed.loginUrl !== 'string' ||
106 - typeof parsed.expiresAt !== 'string' ||
107 - typeof parsed.cachedAt !== 'string'
108 - ) {
109 - throw new Error('Pending login cache is invalid');
110 - }
111 - return {
112 - key: parsed.key,
113 - loginUrl: parsed.loginUrl,
114 - expiresAt: parsed.expiresAt,
115 - cachedAt: parsed.cachedAt,
116 - };
117 -};
118 -
122 const writePendingLoginSession = (session: Omit<PendingLoginSession, 'cachedAt'>) =>
123 Effect.gen(function* () {
124 const fs = yield* FileSystem.FileSystem;
@@ -130,7 +133,7 @@ const writePendingLoginSession = (session: Omit<PendingLoginSession, 'cachedAt'>
133 const clearPendingLoginSession = Effect.gen(function* () {
134 const fs = yield* FileSystem.FileSystem;
135 const filePath = yield* pendingLoginPath;
133 - yield* fs.remove(filePath).pipe(Effect.catchAll(() => Effect.void));
136 + yield* fs.remove(filePath).pipe(Effect.ignore);
137 });
138
139 const readPendingLoginSession = Effect.gen(function* () {
@@ -138,20 +141,30 @@ const readPendingLoginSession = Effect.gen(function* () {
141 const filePath = yield* pendingLoginPath;
142 const exists = yield* fs.exists(filePath);
143 if (!exists) {
141 - return yield* Effect.fail(
142 - new Error('No pending login found. Run `composio login < /dev/null` first.')
143 - );
144 + return yield* new PendingLoginError({
145 + message: 'No pending login found. Run `composio login < /dev/null` first.',
146 + reason: 'missing',
147 + });
148 }
149
146 - const session = yield* fs
147 - .readFileString(filePath, 'utf8')
148 - .pipe(Effect.map(parsePendingLoginSession));
150 + const session = yield* fs.readFileString(filePath, 'utf8').pipe(
151 + Effect.flatMap(Schema.decodeUnknown(Schema.parseJson(PendingLoginSession))),
152 + Effect.mapError(
153 + cause =>
154 + new PendingLoginError({
155 + message: 'Pending login cache is invalid',
156 + reason: 'invalid',
157 + cause,
158 + })
159 + )
160 + );
161 const cachedAt = Date.parse(session.cachedAt);
162 if (!Number.isFinite(cachedAt) || Date.now() - cachedAt > PENDING_LOGIN_TTL_MS) {
163 yield* clearPendingLoginSession;
152 - return yield* Effect.fail(
153 - new Error('Pending login expired. Run `composio login < /dev/null` again.')
154 - );
164 + return yield* new PendingLoginError({
165 + message: 'Pending login expired. Run `composio login < /dev/null` again.',
166 + reason: 'expired',
167 + });
168 }
169
170 return session;
@@ -293,9 +306,10 @@ const resolveDirectLoginOrganization = (params: {
306
307 if (!match) {
308 yield* ui.log.error(`Organization "${requestedOrg}" was not found for this API key.`);
296 - return yield* Effect.fail(
297 - new Error('Invalid organization. Run `composio orgs list` to inspect available orgs.')
298 - );
309 + return yield* new InvalidOrganizationError({
310 + message: 'Invalid organization. Run `composio orgs list` to inspect available orgs.',
311 + requestedOrg,
312 + });
313 }
314
315 return match;
@@ -436,17 +450,17 @@ const loginWithKey = (params: {
450 const ctx = yield* ComposioUserContext;
451 const client = yield* ComposioSessionRepository;
452
439 - const getSessionEffect = client
440 - .getSession({ id: params.key })
441 - .pipe(
442 - Effect.catchAll(() =>
443 - Effect.fail(
444 - new Error(
445 - 'Session not found or expired. Run `composio login --no-wait` to get a new session.'
446 - )
447 - )
448 - )
449 - );
453 + const getSessionEffect = client.getSession({ id: params.key }).pipe(
454 + Effect.mapError(
455 + cause =>
456 + new LoginSessionError({
457 + message:
458 + 'Session not found or expired. Run `composio login --no-wait` to get a new session.',
459 + operation: 'load',
460 + cause,
461 + })
462 + )
463 + );
464
465 let linkedSession;
466 if (params.noWait) {
@@ -454,7 +468,11 @@ const loginWithKey = (params: {
468 if (session.status !== 'linked') {
469 yield* ui.log.error('Login not complete. Open the URL and finish authentication.');
470 yield* ui.log.info('Then run `composio login --key <key>` again.');
457 - return yield* Effect.fail(new Error('Session not yet linked'));
471 + return yield* new LoginSessionError({
472 + message: 'Session not yet linked',
473 + operation: 'poll',
474 + status: session.status,
475 + });
476 }
477 linkedSession = session;
478 } else {
@@ -465,9 +483,11 @@ const loginWithKey = (params: {
483 if (currentSession.status === 'linked') {
484 return currentSession;
485 }
468 - return yield* Effect.fail(
469 - new Error(`Session status is still '${currentSession.status}', waiting for 'linked'`)
470 - );
486 + return yield* new LoginSessionError({
487 + message: `Session status is still '${currentSession.status}', waiting for 'linked'`,
488 + operation: 'poll',
489 + status: currentSession.status,
490 + });
491 }),
492 Schedule.exponential('0.3 seconds').pipe(
493 Schedule.intersect(Schedule.recurs(params.pollRetries ?? 15)),
@@ -495,7 +515,7 @@ const loginWithKey = (params: {
515 Effect.catchAll(error =>
516 Effect.gen(function* () {
517 yield* Effect.logDebug('Failed to list organizations after login:', error);
498 - return [] as ReadonlyArray<OrganizationSummary>;
518 + return [];
519 })
520 )
521 )
@@ -642,8 +662,12 @@ export const browserLogin = (params: {
662 yield* ui.output(url);
663
664 if (!effectiveNoBrowser) {
645 - yield* Effect.tryPromise(() => open(url, { wait: false })).pipe(
646 - Effect.catchAll(error =>
665 + yield* Effect.tryPromise({
666 + try: () => open(url, { wait: false }),
667 + catch: cause =>
668 + new LoginBrowserOpenError({ message: 'Failed to open the browser.', cause }),
669 + }).pipe(
670 + Effect.catchTag('commands/LoginBrowserOpenError', error =>
671 Effect.gen(function* () {
672 yield* Effect.logDebug('Failed to open browser:', error);
673 yield* ui.log.warn('Could not open the browser automatically.');
@@ -662,9 +686,11 @@ export const browserLogin = (params: {
686 if (currentSession.status === 'linked') {
687 return currentSession;
688 }
665 - return yield* Effect.fail(
666 - new Error(`Session status is still '${currentSession.status}', waiting for 'linked'`)
667 - );
689 + return yield* new LoginSessionError({
690 + message: `Session status is still '${currentSession.status}', waiting for 'linked'`,
691 + operation: 'poll',
692 + status: currentSession.status,
693 + });
694 }),
695 Schedule.exponential('0.3 seconds').pipe(
696 Schedule.intersect(Schedule.recurs(15)),
@@ -788,7 +814,9 @@ export const loginCmd = Command.make(
814 }
815
816 if (Option.isSome(key) && Option.isSome(userApiKey)) {
791 - return yield* Effect.fail(new Error('Use either `--key` or `--user-api-key`, not both.'));
817 + return yield* Effect.fail(
818 + invalidOptionValue('Use either `--key` or `--user-api-key`, not both.')
819 + );
820 }
821
822 if (
@@ -796,7 +824,7 @@ export const loginCmd = Command.make(
824 (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey) || agent)
825 ) {
826 return yield* Effect.fail(
799 - new Error(
827 + invalidOptionValue(
828 '`--poll` cannot be combined with browser, session, direct-login, or agent flags.'
829 )
830 );
@@ -804,17 +832,19 @@ export const loginCmd = Command.make(
832
833 if (agent && (noBrowser || noWait || Option.isSome(key) || Option.isSome(userApiKey))) {
834 return yield* Effect.fail(
807 - new Error('`--agent` cannot be combined with browser, session, or direct-login flags.')
835 + invalidOptionValue(
836 + '`--agent` cannot be combined with browser, session, or direct-login flags.'
837 + )
838 );
839 }
840
841 if (Option.isSome(org) && Option.isNone(userApiKey)) {
812 - return yield* Effect.fail(new Error('`--org` requires `--user-api-key`.'));
842 + return yield* Effect.fail(invalidOptionValue('`--org` requires `--user-api-key`.'));
843 }
844
845 if (Option.isSome(userApiKey) && (noBrowser || noWait || Option.isSome(key))) {
846 return yield* Effect.fail(
817 - new Error(
847 + invalidOptionValue(
848 '`--user-api-key` is a direct login path and cannot be combined with browser or session flags.'
849 )
850 );
ts/packages/cli/src/commands/logs-cmd/commands/logs.tools.cmd.ts
+30 -12
@@ -1,5 +1,5 @@
1 import { Args, Command, Options } from '@effect/cli';
2 -import { Effect, Option } from 'effect';
2 +import { Data, Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { ComposioClientSingleton } from 'src/services/composio-clients';
@@ -9,6 +9,11 @@ import { formatToolLogInfo, formatToolLogsTable } from '../format';
9 import { commandHintStep } from 'src/services/command-hints';
10 import { toSearchParam } from '../utils';
11
12 +class ToolLogsRequestError extends Data.TaggedError('commands/ToolLogsRequestError')<{
13 + readonly message: string;
14 + readonly cause: unknown;
15 +}> {}
16 +
17 type ToolLogFilterInput = {
18 tool?: string;
19 toolkit?: string;
@@ -185,7 +190,14 @@ export const logsCmd$Tools = Command.make(
190 if (toolLogId) {
191 const toolLog = yield* ui.withSpinner(
192 `Fetching tool log "${toolLogId}"...`,
188 - Effect.tryPromise(() => client.logs.tools.retrieve(toolLogId))
193 + Effect.tryPromise({
194 + try: () => client.logs.tools.retrieve(toolLogId),
195 + catch: cause =>
196 + new ToolLogsRequestError({
197 + message: `Failed to fetch tool log "${toolLogId}".`,
198 + cause,
199 + }),
200 + })
201 );
202
203 yield* ui.log.info(
@@ -197,16 +209,22 @@ export const logsCmd$Tools = Command.make(
209
210 const response = yield* ui.withSpinner(
211 'Fetching tool logs...',
200 - Effect.tryPromise(() =>
201 - client.logs.tools.list({
202 - cursor: Option.getOrUndefined(cursor) ?? null,
203 - from: Option.getOrUndefined(from),
204 - to: Option.getOrUndefined(to),
205 - limit: clampedLimit,
206 - case_sensitive: caseSensitive,
207 - search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,
208 - })
209 - )
212 + Effect.tryPromise({
213 + try: () =>
214 + client.logs.tools.list({
215 + cursor: Option.getOrUndefined(cursor) ?? null,
216 + from: Option.getOrUndefined(from),
217 + to: Option.getOrUndefined(to),
218 + limit: clampedLimit,
219 + case_sensitive: caseSensitive,
220 + search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,
221 + }),
222 + catch: cause =>
223 + new ToolLogsRequestError({
224 + message: 'Failed to fetch tool logs.',
225 + cause,
226 + }),
227 + })
228 );
229
230 const logs = response.data ?? [];
ts/packages/cli/src/commands/logs-cmd/commands/logs.triggers.cmd.ts
+37 -67
@@ -1,14 +1,20 @@
1 import { Args, Command, Options } from '@effect/cli';
2 -import { Effect, Option } from 'effect';
2 +import { Data, Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { ComposioClientSingleton } from 'src/services/composio-clients';
6 import { clampLimit } from 'src/ui/clamp-limit';
7 import { parseCsv } from 'src/commands/triggers/parse-csv';
8 import { formatTriggerLogInfo, formatTriggerLogsTable } from '../format';
9 +import { decodeTriggerLogRecord } from '../trigger-log-record';
10 import { commandHintStep } from 'src/services/command-hints';
11 import { toSearchParam } from '../utils';
12
13 +class TriggerLogsRequestError extends Data.TaggedError('commands/TriggerLogsRequestError')<{
14 + readonly message: string;
15 + readonly cause: unknown;
16 +}> {}
17 +
18 const cursor = Options.text('cursor').pipe(
19 Options.withDescription('Cursor for pagination'),
20 Options.optional
@@ -149,34 +155,45 @@ export const logsCmd$Triggers = Command.make(
155 if (triggerLogId) {
156 const triggerLog = yield* ui.withSpinner(
157 `Fetching trigger log "${triggerLogId}"...`,
152 - Effect.tryPromise(() => client.logs.triggers.retrieve(triggerLogId))
158 + Effect.tryPromise({
159 + try: () => client.logs.triggers.retrieve(triggerLogId),
160 + catch: cause =>
161 + new TriggerLogsRequestError({
162 + message: `Failed to fetch trigger log "${triggerLogId}".`,
163 + cause,
164 + }),
165 + })
166 );
154 - const triggerLogData = triggerLog as unknown as Record<string, unknown>;
155 - const normalizedLogData = getTriggerLogRecord(triggerLogData);
156 - const payload = getTriggerPayload(normalizedLogData);
157 - const response = getTriggerResponse(normalizedLogData);
167 + const record = decodeTriggerLogRecord(triggerLog);
168
169 yield* ui.log.info(
160 - `${formatTriggerLogInfo(triggerLog)}\n\nPayload:\n${JSON.stringify(payload, null, 2)}\n\nResponse:\n${JSON.stringify(response, null, 2)}`
170 + `${formatTriggerLogInfo(record)}\n\nPayload:\n${JSON.stringify(record.payload, null, 2)}\n\nResponse:\n${JSON.stringify(record.response, null, 2)}`
171 );
172 + // Raw API payload for scripts; only human-readable formatting uses the decoded record.
173 yield* ui.output(JSON.stringify(triggerLog, null, 2));
174 return;
175 }
176
177 const response = yield* ui.withSpinner(
178 'Fetching trigger logs...',
168 - Effect.tryPromise(() =>
169 - client.logs.triggers.list({
170 - cursor: Option.getOrUndefined(cursor),
171 - from: Option.getOrUndefined(from),
172 - to: Option.getOrUndefined(to),
173 - limit: clampedLimit,
174 - time: Option.getOrUndefined(time),
175 - search: Option.getOrUndefined(search),
176 - include_payload: includePayload,
177 - search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,
178 - })
179 - )
179 + Effect.tryPromise({
180 + try: () =>
181 + client.logs.triggers.list({
182 + cursor: Option.getOrUndefined(cursor),
183 + from: Option.getOrUndefined(from),
184 + to: Option.getOrUndefined(to),
185 + limit: clampedLimit,
186 + time: Option.getOrUndefined(time),
187 + search: Option.getOrUndefined(search),
188 + include_payload: includePayload,
189 + search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,
190 + }),
191 + catch: cause =>
192 + new TriggerLogsRequestError({
193 + message: 'Failed to fetch trigger logs.',
194 + cause,
195 + }),
196 + })
197 );
198
199 const logs = response.data ?? [];
@@ -188,7 +205,7 @@ export const logsCmd$Triggers = Command.make(
205 }
206
207 yield* ui.log.info(
191 - `Listing ${logs.length} trigger log${logs.length === 1 ? '' : 's'}\n\n${formatTriggerLogsTable(logs)}`
208 + `Listing ${logs.length} trigger log${logs.length === 1 ? '' : 's'}\n\n${formatTriggerLogsTable(logs.map(decodeTriggerLogRecord))}`
209 );
210
211 const firstLogId = logs[0]?.id;
@@ -207,50 +224,3 @@ export const logsCmd$Triggers = Command.make(
224 yield* ui.output(JSON.stringify(response, null, 2));
225 })
226 ).pipe(Command.withDescription('List trigger logs.'));
210 -
211 -export const getTriggerLogRecord = (record: Record<string, unknown>): Record<string, unknown> => {
212 - const log = record.log;
213 - if (log && typeof log === 'object') return log as Record<string, unknown>;
214 - return record;
215 -};
216 -
217 -export const getTriggerPayload = (record: Record<string, unknown>): unknown => {
218 - const meta = record.meta;
219 - const metaRecord = meta && typeof meta === 'object' ? (meta as Record<string, unknown>) : {};
220 - const rawPayload =
221 - metaRecord.triggerProviderPayload ??
222 - metaRecord.triggerClientPayload ??
223 - record.payloadReceived ??
224 - record.payload ??
225 - null;
226 -
227 - return parseMaybeJson(rawPayload);
228 -};
229 -
230 -export const getTriggerResponse = (record: Record<string, unknown>): unknown => {
231 - const meta = record.meta;
232 - const metaRecord = meta && typeof meta === 'object' ? (meta as Record<string, unknown>) : {};
233 - const rawResponse =
234 - metaRecord.triggerClientResponse ??
235 - metaRecord.triggerProviderResponse ??
236 - record.response ??
237 - null;
238 -
239 - return parseMaybeJson(rawResponse);
240 -};
241 -
242 -export const parseMaybeJson = (value: unknown): unknown => {
243 - if (typeof value !== 'string') return value;
244 - const trimmed = value.trim();
245 - if (
246 - (trimmed.startsWith('{') && trimmed.endsWith('}')) ||
247 - (trimmed.startsWith('[') && trimmed.endsWith(']'))
248 - ) {
249 - try {
250 - return JSON.parse(trimmed);
251 - } catch {
252 - return value;
253 - }
254 - }
255 - return value;
256 -};
ts/packages/cli/src/commands/logs-cmd/format.ts
+19 -121
@@ -1,8 +1,8 @@
1 import type { Logs } from '@composio/client/resources/logs/logs';
2 +import type { TriggerLogRecord } from 'src/commands/logs-cmd/trigger-log-record';
3 import { bold, gray, green, red } from 'src/ui/colors';
4 import { truncate } from 'src/ui/truncate';
5
5 -type TriggerLog = Logs.TriggerListResponse.Data;
6 type ToolLog = Logs.ToolListResponse.Data;
7 type ToolLogDetailed = Logs.ToolRetrieveResponse;
8
@@ -26,7 +26,7 @@ const TOOL_LOG_TABLE = {
26 connectedAccountId: 20,
27 } as const;
28
29 -export const formatTriggerLogsTable = (logs: ReadonlyArray<TriggerLog>): string => {
29 +export const formatTriggerLogsTable = (logs: ReadonlyArray<TriggerLogRecord>): string => {
30 const header = [
31 bold('Created At'.padEnd(TRIGGER_LOG_TABLE.createdAt)),
32 bold('Log Id'.padEnd(TRIGGER_LOG_TABLE.id)),
@@ -44,13 +44,15 @@ export const formatTriggerLogsTable = (logs: ReadonlyArray<TriggerLog>): string
44 )
45 );
46 const id = (log.id ?? '-').padEnd(TRIGGER_LOG_TABLE.id);
47 - const triggerId = truncate(getTriggerId(log), TRIGGER_LOG_TABLE.triggerId).padEnd(
47 + const triggerId = truncate(
48 + valueOrDash(log.table.triggerId),
49 TRIGGER_LOG_TABLE.triggerId
49 - );
50 + ).padEnd(TRIGGER_LOG_TABLE.triggerId);
51 const app = truncate(log.appName ?? '-', TRIGGER_LOG_TABLE.app).padEnd(TRIGGER_LOG_TABLE.app);
51 - const triggerName = truncate(getTriggerName(log), TRIGGER_LOG_TABLE.triggerName).padEnd(
52 + const triggerName = truncate(
53 + valueOrDash(log.table.triggerName),
54 TRIGGER_LOG_TABLE.triggerName
53 - );
55 + ).padEnd(TRIGGER_LOG_TABLE.triggerName);
56 const triggerUserId = truncate(log.entityId ?? '-', TRIGGER_LOG_TABLE.triggerUserId).padEnd(
57 TRIGGER_LOG_TABLE.triggerUserId
58 );
@@ -118,46 +120,6 @@ const valueOrDash = (value: string | null | undefined): string => {
120 return normalizedValue.length > 0 ? normalizedValue : '-';
121 };
122
121 -const getTriggerId = (log: TriggerLog): string => {
122 - const dynamicLog = log as unknown as Record<string, unknown>;
123 - const dynamicMeta = (dynamicLog.meta ?? {}) as Record<string, unknown>;
124 - const triggerId =
125 - typeof dynamicMeta.triggerNanoId === 'string'
126 - ? dynamicMeta.triggerNanoId
127 - : typeof dynamicMeta.trigger_nano_id === 'string'
128 - ? dynamicMeta.trigger_nano_id
129 - : typeof dynamicMeta.triggerId === 'string'
130 - ? dynamicMeta.triggerId
131 - : typeof dynamicMeta.trigger_id === 'string'
132 - ? dynamicMeta.trigger_id
133 - : typeof dynamicLog.triggerNanoId === 'string'
134 - ? dynamicLog.triggerNanoId
135 - : typeof dynamicLog.trigger_nano_id === 'string'
136 - ? dynamicLog.trigger_nano_id
137 - : typeof dynamicLog.triggerId === 'string'
138 - ? dynamicLog.triggerId
139 - : typeof dynamicLog.trigger_id === 'string'
140 - ? dynamicLog.trigger_id
141 - : null;
142 - return valueOrDash(triggerId);
143 -};
144 -
145 -const getTriggerName = (log: TriggerLog): string => {
146 - const dynamicLog = log as unknown as Record<string, unknown>;
147 - const dynamicMeta = (dynamicLog.meta ?? {}) as Record<string, unknown>;
148 - const triggerName =
149 - typeof dynamicMeta.triggerName === 'string'
150 - ? dynamicMeta.triggerName
151 - : typeof dynamicMeta.trigger_name === 'string'
152 - ? dynamicMeta.trigger_name
153 - : typeof dynamicLog.triggerName === 'string'
154 - ? dynamicLog.triggerName
155 - : typeof dynamicLog.trigger_name === 'string'
156 - ? dynamicLog.trigger_name
157 - : null;
158 - return valueOrDash(triggerName);
159 -};
160 -
123 const formatEpoch = (value: number): string => {
124 const date = new Date(value);
125 if (Number.isNaN(date.getTime())) return '-';
@@ -186,83 +148,19 @@ export const formatToolLogInfo = (toolLog: ToolLogDetailed): string => {
148 return lines.join('\n');
149 };
150
189 -export const formatTriggerLogInfo = (triggerLog: unknown): string => {
190 - const rawLog = triggerLog as Record<string, unknown>;
191 - const logCandidate = rawLog.log;
192 - const log =
193 - logCandidate && typeof logCandidate === 'object'
194 - ? (logCandidate as Record<string, unknown>)
195 - : rawLog;
151 +export const formatTriggerLogInfo = (triggerLog: TriggerLogRecord): string => {
152 + const { detail } = triggerLog;
153 const lines: string[] = [];
154
198 - lines.push(`${bold('logId:')} ${valueOrDash(getRecordString(log, ['id', 'logId', 'log_id']))}`);
199 - lines.push(
200 - `${bold('triggerId:')} ${valueOrDash(getRecordString(log, ['triggerId', 'trigger_id']))}`
201 - );
202 - lines.push(
203 - `${bold('triggerNanoId:')} ${valueOrDash(
204 - getRecordString(log, ['triggerNanoId', 'trigger_nano_id'])
205 - )}`
206 - );
207 - lines.push(
208 - `${bold('trigger:')} ${valueOrDash(getRecordString(log, ['triggerName', 'trigger_name']))}`
209 - );
210 - lines.push(`${bold('Status:')} ${valueOrDash(getRecordString(log, ['status']))}`);
211 - lines.push(
212 - `${bold('toolkit:')} ${valueOrDash(getRecordString(log, ['appName', 'toolkit', 'toolkit_key']))}`
213 - );
214 - lines.push(
215 - `${bold('Connection ID:')} ${valueOrDash(
216 - getRecordString(log, ['connectionId', 'connection_id', 'connectedAccountId'])
217 - )}`
218 - );
219 - lines.push(
220 - `${bold('Entity:')} ${valueOrDash(getRecordString(log, ['entityId', 'entity_id', 'userId']))}`
221 - );
222 - lines.push(
223 - `${bold('Created At:')} ${formatCreatedAt(
224 - getRecordNumberOrString(log, ['createdAt', 'created_at'])
225 - )}`
226 - );
155 + lines.push(`${bold('logId:')} ${valueOrDash(detail.logId)}`);
156 + lines.push(`${bold('triggerId:')} ${valueOrDash(detail.triggerId)}`);
157 + lines.push(`${bold('triggerNanoId:')} ${valueOrDash(detail.triggerNanoId)}`);
158 + lines.push(`${bold('trigger:')} ${valueOrDash(detail.triggerName)}`);
159 + lines.push(`${bold('Status:')} ${valueOrDash(detail.status)}`);
160 + lines.push(`${bold('toolkit:')} ${valueOrDash(detail.toolkit)}`);
161 + lines.push(`${bold('Connection ID:')} ${valueOrDash(detail.connectionId)}`);
162 + lines.push(`${bold('Entity:')} ${valueOrDash(detail.entityId)}`);
163 + lines.push(`${bold('Created At:')} ${formatCreatedAt(detail.createdAt)}`);
164
165 return lines.join('\n');
166 };
230 -
231 -const getRecordString = (record: Record<string, unknown>, keys: ReadonlyArray<string>) => {
232 - for (const key of keys) {
233 - const value = record[key];
234 - if (typeof value === 'string') return value;
235 - }
236 -
237 - const meta = record.meta;
238 - if (meta && typeof meta === 'object') {
239 - const metaRecord = meta as Record<string, unknown>;
240 - for (const key of keys) {
241 - const value = metaRecord[key];
242 - if (typeof value === 'string') return value;
243 - }
244 - }
245 -
246 - return null;
247 -};
248 -
249 -const getRecordNumberOrString = (
250 - record: Record<string, unknown>,
251 - keys: ReadonlyArray<string>
252 -): number | string | null => {
253 - for (const key of keys) {
254 - const value = record[key];
255 - if (typeof value === 'number' || typeof value === 'string') return value;
256 - }
257 -
258 - const meta = record.meta;
259 - if (meta && typeof meta === 'object') {
260 - const metaRecord = meta as Record<string, unknown>;
261 - for (const key of keys) {
262 - const value = metaRecord[key];
263 - if (typeof value === 'number' || typeof value === 'string') return value;
264 - }
265 - }
266 -
267 - return null;
268 -};
ts/packages/cli/src/commands/logs-cmd/trigger-log-record.ts new
+295
@@ -0,0 +1,295 @@
1 +import { Option, Schema } from 'effect';
2 +
3 +/**
4 + * Tolerant normalization of trigger-log API payloads.
5 + *
6 + * The `@composio/client` type (`Logs.TriggerListResponse.Data`) declares
7 + * trigger metadata under `meta` in camelCase, but the API has historically
8 + * served camelCase and snake_case variants at both the top level and under
9 + * `meta`. Instead of mining those aliases with `as ... as Record` casts at
10 + * every call site, payloads are decoded once at the API boundary into the
11 + * canonical {@link TriggerLogRecord} shape.
12 + *
13 + * Decoding is deliberately lenient: wrongly-typed fields behave as absent and
14 + * a completely garbage payload decodes to an empty record, so formatting
15 + * falls back to `'-'` placeholders instead of failing the command.
16 + */
17 +
18 +/** Decodes to the string value when present, treating any other type as absent. */
19 +const LenientString = Schema.transform(Schema.Unknown, Schema.UndefinedOr(Schema.String), {
20 + strict: true,
21 + decode: value => (typeof value === 'string' ? value : undefined),
22 + encode: value => value,
23 +});
24 +
25 +/** Decodes to the string or number value when present, treating any other type as absent. */
26 +const LenientTimestamp = Schema.transform(
27 + Schema.Unknown,
28 + Schema.UndefinedOr(Schema.Union(Schema.String, Schema.Number)),
29 + {
30 + strict: true,
31 + decode: value => (typeof value === 'string' || typeof value === 'number' ? value : undefined),
32 + encode: value => value,
33 + }
34 +);
35 +
36 +/**
37 + * Every alias the CLI has ever mined from trigger logs. The same aliases can
38 + * appear at the top level of a record and under its `meta` object.
39 + */
40 +const aliasFields = {
41 + id: Schema.optional(LenientString),
42 + logId: Schema.optional(LenientString),
43 + log_id: Schema.optional(LenientString),
44 + triggerId: Schema.optional(LenientString),
45 + trigger_id: Schema.optional(LenientString),
46 + triggerNanoId: Schema.optional(LenientString),
47 + trigger_nano_id: Schema.optional(LenientString),
48 + triggerName: Schema.optional(LenientString),
49 + trigger_name: Schema.optional(LenientString),
50 + status: Schema.optional(LenientString),
51 + appName: Schema.optional(LenientString),
52 + toolkit: Schema.optional(LenientString),
53 + toolkit_key: Schema.optional(LenientString),
54 + connectionId: Schema.optional(LenientString),
55 + connection_id: Schema.optional(LenientString),
56 + connectedAccountId: Schema.optional(LenientString),
57 + entityId: Schema.optional(LenientString),
58 + entity_id: Schema.optional(LenientString),
59 + userId: Schema.optional(LenientString),
60 + createdAt: Schema.optional(LenientTimestamp),
61 + created_at: Schema.optional(LenientTimestamp),
62 +};
63 +
64 +const RawTriggerLogMeta = Schema.Struct({
65 + ...aliasFields,
66 + triggerProviderPayload: Schema.optional(Schema.Unknown),
67 + triggerClientPayload: Schema.optional(Schema.Unknown),
68 + triggerClientResponse: Schema.optional(Schema.Unknown),
69 + triggerProviderResponse: Schema.optional(Schema.Unknown),
70 +});
71 +type RawTriggerLogMeta = typeof RawTriggerLogMeta.Type;
72 +
73 +const decodeMetaOption = Schema.decodeUnknownOption(RawTriggerLogMeta);
74 +
75 +/** Any non-record `meta` behaves like an absent one. */
76 +const LenientMeta = Schema.transform(
77 + Schema.Unknown,
78 + Schema.UndefinedOr(Schema.typeSchema(RawTriggerLogMeta)),
79 + {
80 + strict: true,
81 + decode: value => Option.getOrUndefined(decodeMetaOption(value)),
82 + encode: value => value,
83 + }
84 +);
85 +
86 +const rawLevelFields = {
87 + ...aliasFields,
88 + payloadReceived: Schema.optional(Schema.Unknown),
89 + payload: Schema.optional(Schema.Unknown),
90 + response: Schema.optional(Schema.Unknown),
91 + meta: Schema.optional(LenientMeta),
92 +};
93 +
94 +const RawTriggerLogLevel = Schema.Struct(rawLevelFields);
95 +type RawTriggerLogLevel = typeof RawTriggerLogLevel.Type;
96 +
97 +const decodeLevelOption = Schema.decodeUnknownOption(RawTriggerLogLevel);
98 +
99 +/**
100 + * `logs.triggers.retrieve` responses wrap the record under `log`. Any object
101 + * there is used as the record (even one that yields no fields); everything
102 + * else falls back to the top level.
103 + */
104 +const LenientNestedLog = Schema.transform(
105 + Schema.Unknown,
106 + Schema.UndefinedOr(Schema.typeSchema(RawTriggerLogLevel)),
107 + {
108 + strict: true,
109 + decode: value =>
110 + typeof value === 'object' && value !== null
111 + ? Option.getOrElse(decodeLevelOption(value), (): RawTriggerLogLevel => ({}))
112 + : undefined,
113 + encode: value => value,
114 + }
115 +);
116 +
117 +const RawTriggerLog = Schema.Struct({
118 + ...rawLevelFields,
119 + log: Schema.optional(LenientNestedLog),
120 +});
121 +
122 +/**
123 + * Canonical trigger-log shape consumed by the `logs triggers` formatting code.
124 + *
125 + * - Top-level fields hold the values exactly as the client type declares them
126 + * (the plain list-table columns).
127 + * - `detail` holds alias-resolved fields for the info block. Precedence: the
128 + * listed aliases at the top level of the record first, then the same
129 + * aliases under `meta`.
130 + * - `table` holds the trigger columns of the list table, which historically
131 + * resolved `meta` aliases first (nano id preferred over plain id) and only
132 + * then the top level.
133 + */
134 +export const TriggerLogRecord = Schema.Struct({
135 + id: Schema.optional(Schema.String),
136 + appName: Schema.optional(Schema.String),
137 + entityId: Schema.optional(Schema.String),
138 + connectionId: Schema.optional(Schema.String),
139 + createdAt: Schema.optional(Schema.Union(Schema.String, Schema.Number)),
140 + detail: Schema.Struct({
141 + /** `id` → `logId` → `log_id`, top level then `meta`. */
142 + logId: Schema.optional(Schema.String),
143 + /** `triggerId` → `trigger_id`, top level then `meta`. */
144 + triggerId: Schema.optional(Schema.String),
145 + /** `triggerNanoId` → `trigger_nano_id`, top level then `meta`. */
146 + triggerNanoId: Schema.optional(Schema.String),
147 + /** `triggerName` → `trigger_name`, top level then `meta`. */
148 + triggerName: Schema.optional(Schema.String),
149 + /** `status`, top level then `meta`. */
150 + status: Schema.optional(Schema.String),
151 + /** `appName` → `toolkit` → `toolkit_key`, top level then `meta`. */
152 + toolkit: Schema.optional(Schema.String),
153 + /** `connectionId` → `connection_id` → `connectedAccountId`, top level then `meta`. */
154 + connectionId: Schema.optional(Schema.String),
155 + /** `entityId` → `entity_id` → `userId`, top level then `meta`. */
156 + entityId: Schema.optional(Schema.String),
157 + /** `createdAt` → `created_at`, top level then `meta`. */
158 + createdAt: Schema.optional(Schema.Union(Schema.String, Schema.Number)),
159 + }),
160 + table: Schema.Struct({
161 + /** Nano id preferred over plain id; `meta` aliases before top-level ones. */
162 + triggerId: Schema.optional(Schema.String),
163 + /** `triggerName` → `trigger_name`, `meta` then top level. */
164 + triggerName: Schema.optional(Schema.String),
165 + }),
166 + /**
167 + * `meta.triggerProviderPayload` → `meta.triggerClientPayload` →
168 + * `payloadReceived` → `payload` → `null`, JSON-parsed when it looks like JSON.
169 + */
170 + payload: Schema.Unknown,
171 + /**
172 + * `meta.triggerClientResponse` → `meta.triggerProviderResponse` →
173 + * `response` → `null`, JSON-parsed when it looks like JSON.
174 + */
175 + response: Schema.Unknown,
176 +});
177 +export type TriggerLogRecord = typeof TriggerLogRecord.Type;
178 +
179 +/** Parses strings that look like JSON objects/arrays, passing everything else through. */
180 +export const parseMaybeJson = (value: unknown): unknown => {
181 + if (typeof value !== 'string') return value;
182 + const trimmed = value.trim();
183 + if (
184 + (trimmed.startsWith('{') && trimmed.endsWith('}')) ||
185 + (trimmed.startsWith('[') && trimmed.endsWith(']'))
186 + ) {
187 + return Option.getOrElse(
188 + Option.liftThrowable((input: string): unknown => JSON.parse(input))(trimmed),
189 + () => value
190 + );
191 + }
192 + return value;
193 +};
194 +
195 +const normalizeLevel = (level: RawTriggerLogLevel): TriggerLogRecord => {
196 + const meta = level.meta;
197 +
198 + return {
199 + id: level.id,
200 + appName: level.appName,
201 + entityId: level.entityId,
202 + connectionId: level.connectionId,
203 + createdAt: level.createdAt,
204 + detail: {
205 + logId: level.id ?? level.logId ?? level.log_id ?? meta?.id ?? meta?.logId ?? meta?.log_id,
206 + triggerId: level.triggerId ?? level.trigger_id ?? meta?.triggerId ?? meta?.trigger_id,
207 + triggerNanoId:
208 + level.triggerNanoId ??
209 + level.trigger_nano_id ??
210 + meta?.triggerNanoId ??
211 + meta?.trigger_nano_id,
212 + triggerName:
213 + level.triggerName ?? level.trigger_name ?? meta?.triggerName ?? meta?.trigger_name,
214 + status: level.status ?? meta?.status,
215 + toolkit:
216 + level.appName ??
217 + level.toolkit ??
218 + level.toolkit_key ??
219 + meta?.appName ??
220 + meta?.toolkit ??
221 + meta?.toolkit_key,
222 + connectionId:
223 + level.connectionId ??
224 + level.connection_id ??
225 + level.connectedAccountId ??
226 + meta?.connectionId ??
227 + meta?.connection_id ??
228 + meta?.connectedAccountId,
229 + entityId:
230 + level.entityId ??
231 + level.entity_id ??
232 + level.userId ??
233 + meta?.entityId ??
234 + meta?.entity_id ??
235 + meta?.userId,
236 + createdAt: level.createdAt ?? level.created_at ?? meta?.createdAt ?? meta?.created_at,
237 + },
238 + table: {
239 + triggerId:
240 + meta?.triggerNanoId ??
241 + meta?.trigger_nano_id ??
242 + meta?.triggerId ??
243 + meta?.trigger_id ??
244 + level.triggerNanoId ??
245 + level.trigger_nano_id ??
246 + level.triggerId ??
247 + level.trigger_id,
248 + triggerName:
249 + meta?.triggerName ?? meta?.trigger_name ?? level.triggerName ?? level.trigger_name,
250 + },
251 + payload: parseMaybeJson(
252 + meta?.triggerProviderPayload ??
253 + meta?.triggerClientPayload ??
254 + level.payloadReceived ??
255 + level.payload ??
256 + null
257 + ),
258 + response: parseMaybeJson(
259 + meta?.triggerClientResponse ?? meta?.triggerProviderResponse ?? level.response ?? null
260 + ),
261 + };
262 +};
263 +
264 +const TriggerLogRecordFromRaw = Schema.transform(RawTriggerLog, TriggerLogRecord, {
265 + strict: true,
266 + decode: raw => normalizeLevel(raw.log ?? raw),
267 + encode: record => ({
268 + id: record.id,
269 + appName: record.appName,
270 + entityId: record.entityId,
271 + connectionId: record.connectionId,
272 + createdAt: record.createdAt,
273 + logId: record.detail.logId,
274 + triggerId: record.detail.triggerId,
275 + triggerNanoId: record.detail.triggerNanoId,
276 + triggerName: record.detail.triggerName,
277 + status: record.detail.status,
278 + toolkit: record.detail.toolkit,
279 + payload: record.payload,
280 + response: record.response,
281 + }),
282 +});
283 +
284 +const decodeTriggerLogRecordOption = Schema.decodeUnknownOption(TriggerLogRecordFromRaw);
285 +
286 +/** Canonical record produced when a payload cannot be decoded at all. */
287 +export const emptyTriggerLogRecord: TriggerLogRecord = normalizeLevel({});
288 +
289 +/**
290 + * Decodes an unknown trigger-log payload into the canonical
291 + * {@link TriggerLogRecord}, falling back to {@link emptyTriggerLogRecord}
292 + * (which formats as `'-'` placeholders) when the payload is not an object.
293 + */
294 +export const decodeTriggerLogRecord = (input: unknown): TriggerLogRecord =>
295 + Option.getOrElse(decodeTriggerLogRecordOption(input), () => emptyTriggerLogRecord);
ts/packages/cli/src/commands/proxy.cmd.ts
+65 -46
@@ -1,5 +1,5 @@
1 import { Args, Command, Options } from '@effect/cli';
2 -import { Effect, Either, Option } from 'effect';
2 +import { Data, Effect, Either, Option } from 'effect';
3 import type {
4 SessionProxyExecuteParams,
5 SessionProxyExecuteResponse,
@@ -62,20 +62,33 @@ type ProxyMethod = Extract<
62 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
63 >;
64
65 -const SUPPORTED_PROXY_METHODS = [
65 +const SUPPORTED_PROXY_METHODS: ReadonlyArray<ProxyMethod> = [
66 'GET',
67 'POST',
68 'PUT',
69 'DELETE',
70 'PATCH',
71 -] as const satisfies ReadonlyArray<ProxyMethod>;
71 +];
72 +
73 +export class ProxyCommandError extends Data.TaggedError('commands/ProxyCommandError')<{
74 + readonly reason: 'missing_consumer_user' | 'toolkit_not_connected';
75 + readonly message: string;
76 + readonly toolkit?: string;
77 + readonly endpoint?: string;
78 +}> {}
79 +
80 +class ProxyRequestError extends Data.TaggedError('commands/ProxyRequestError')<{
81 + readonly message: string;
82 + readonly cause: unknown;
83 +}> {}
84
85 export const normalizeProxyMethod = (value: string): ProxyMethod => {
86 const normalized = value.trim().toUpperCase();
75 - if (!SUPPORTED_PROXY_METHODS.includes(normalized as ProxyMethod)) {
87 + const supported = SUPPORTED_PROXY_METHODS.find(method => method === normalized);
88 + if (!supported) {
89 throw new Error('Unsupported method. Use one of GET, POST, PUT, DELETE, PATCH.');
90 }
78 - return normalized as ProxyMethod;
91 + return supported;
92 };
93
94 export const parseProxyHeader = (value: string): { name: string; value: string } => {
@@ -162,17 +175,9 @@ const handleProxyExecutionError = (params: {
175 ].join('\n'),
176 'Tips'
177 );
165 - const output = formatProxyErrorOutput({
166 - error: mapped.message,
167 - toolkit: params.toolkit,
168 - endpoint: params.endpoint,
169 - slug: mapped.slugValue,
170 - });
171 - yield* params.ui.output(output);
172 - return yield* Effect.fail(mapped.normalized);
178 + } else {
179 + yield* params.ui.log.error(mapped.message);
180 }
174 -
175 - yield* params.ui.log.error(mapped.message);
181 const output = formatProxyErrorOutput({
182 error: mapped.message,
183 toolkit: params.toolkit,
@@ -234,7 +239,12 @@ const runProxyConnectedToolkitFailFast = (params: {
239 2
240 )
241 );
237 - return yield* Effect.fail(new Error(message));
242 + return yield* new ProxyCommandError({
243 + reason: 'toolkit_not_connected',
244 + message,
245 + toolkit: params.toolkit,
246 + endpoint: params.endpoint,
247 + });
248 }
249 });
250
@@ -272,9 +282,10 @@ export const proxyCmd = Command.make('proxy', {
282 );
283
284 if (resolvedProject.projectType !== 'CONSUMER' || !resolvedProject.consumerUserId) {
275 - return yield* Effect.fail(
276 - new Error('No consumer project user is available for proxy execution in this context.')
277 - );
285 + return yield* new ProxyCommandError({
286 + reason: 'missing_consumer_user',
287 + message: 'No consumer project user is available for proxy execution in this context.',
288 + });
289 }
290 const consumerUserId = resolvedProject.consumerUserId;
291 const normalizedToolkit = toolkit.toLowerCase();
@@ -289,14 +300,16 @@ export const proxyCmd = Command.make('proxy', {
300 });
301
302 const normalizedMethod = normalizeProxyMethod(method);
292 - const headerParameters = headers.map(header => {
293 - const parsed = parseProxyHeader(header);
294 - return {
295 - name: parsed.name,
296 - type: 'header' as const,
297 - value: parsed.value,
298 - };
299 - });
303 + const headerParameters: NonNullable<SessionProxyExecuteParams['parameters']> = headers.map(
304 + header => {
305 + const parsed = parseProxyHeader(header);
306 + return {
307 + name: parsed.name,
308 + type: 'header',
309 + value: parsed.value,
310 + };
311 + }
312 + );
313 const rawBody = yield* resolveBodyInput(data);
314 const parsedBody = rawBody === undefined ? undefined : parseProxyBody(rawBody);
315
@@ -316,26 +329,32 @@ export const proxyCmd = Command.make('proxy', {
329 },
330 });
331
319 - const resultEither = yield* Effect.tryPromise(() =>
320 - client.toolRouter.session.proxyExecute(sessionId, {
321 - toolkit_slug: normalizedToolkit,
322 - endpoint,
323 - method: normalizedMethod,
324 - ...(parsedBody !== undefined ? { body: parsedBody } : {}),
325 - ...(headerParameters.length > 0 ? { parameters: headerParameters } : {}),
332 + return yield* Effect.tryPromise({
333 + try: () =>
334 + client.toolRouter.session.proxyExecute(sessionId, {
335 + toolkit_slug: normalizedToolkit,
336 + endpoint,
337 + method: normalizedMethod,
338 + ...(parsedBody !== undefined ? { body: parsedBody } : {}),
339 + ...(headerParameters.length > 0 ? { parameters: headerParameters } : {}),
340 + }),
341 + catch: cause =>
342 + new ProxyRequestError({
343 + message: `Failed to proxy ${normalizedMethod} ${endpoint} via "${normalizedToolkit}".`,
344 + cause,
345 + }),
346 + }).pipe(
347 + Effect.matchEffect({
348 + onFailure: error =>
349 + handleProxyExecutionError({
350 + ui,
351 + error,
352 + toolkit: normalizedToolkit,
353 + endpoint,
354 + }),
355 + onSuccess: Effect.succeed,
356 })
327 - ).pipe(Effect.either);
328 -
329 - if (resultEither._tag === 'Left') {
330 - return yield* handleProxyExecutionError({
331 - ui,
332 - error: resultEither.left,
333 - toolkit: normalizedToolkit,
334 - endpoint,
335 - });
336 - }
337 -
338 - return resultEither.right;
357 + );
358 })
359 );
360
ts/packages/cli/src/commands/py/commands/py.generate.cmd.ts
+29 -15
@@ -1,8 +1,6 @@
1 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
2 -import path from 'node:path';
3 -import { Command, Options } from '@effect/cli';
4 -import { pipe, Effect, Option, Array } from 'effect';
5 -import { FileSystem } from '@effect/platform';
1 +import { Command, HelpDoc, Options, ValidationError } from '@effect/cli';
2 +import { Array, Data, Effect, Option, pipe, String } from 'effect';
3 +import { FileSystem, Path } from '@effect/platform';
4 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
5 import { logMetrics } from 'src/effects/log-metrics';
6 import type { GetCmdParams } from 'src/type-utils';
@@ -18,6 +16,16 @@ import {
16 import { validateToolkitVersionOverrides } from 'src/effects/validate-toolkit-versions';
17 import { TerminalUI } from 'src/services/terminal-ui';
18
19 +export class PythonGenerationWriteError extends Data.TaggedError(
20 + 'commands/PythonGenerationWriteError'
21 +)<{
22 + readonly cause: unknown;
23 + readonly filePath: string;
24 + readonly message: string;
25 +}> {}
26 +
27 +const invalidGenerateValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));
28 +
29 export const outputOpt = Options.optional(
30 Options.directory('output-dir', {
31 exists: 'either',
@@ -54,6 +62,7 @@ export function generatePythonTypeStubs({
62 const process = yield* NodeProcess;
63 const cwd = process.cwd;
64 const fs = yield* FileSystem.FileSystem;
65 + const path = yield* Path.Path;
66 const client = yield* ComposioToolkitsRepository;
67
68 yield* ui.intro('composio generate py');
@@ -69,7 +78,7 @@ export function generatePythonTypeStubs({
78 const normalizedPath = path.normalize(outputDir);
79 if (normalizedPath.includes('node_modules')) {
80 return Effect.fail(
72 - new Error(
81 + invalidGenerateValue(
82 'Output directory cannot be inside node_modules. Please specify a different directory.'
83 )
84 );
@@ -106,7 +115,7 @@ export function generatePythonTypeStubs({
115 .pipe(
116 Effect.catchTag('services/InvalidToolkitsError', error =>
117 Effect.fail(
109 - new Error(
118 + invalidGenerateValue(
119 `Invalid toolkit(s): ${error.invalidToolkits.join(', ')}. ` +
120 `Available toolkits: ${error.availableToolkits.slice(0, 10).join(', ')}${error.availableToolkits.length > 10 ? '...' : ''}`
121 )
@@ -144,9 +153,10 @@ export function generatePythonTypeStubs({
153 // Build version map for toolkits being generated (using validated overrides)
154 const versionMap: ToolkitVersionOverrides = new Map();
155 for (const toolkit of toolkits) {
147 - const version = validatedOverrides.get(toolkit.slug.toLowerCase() as Lowercase<string>);
156 + const normalizedSlug = String.toLowerCase(toolkit.slug);
157 + const version = validatedOverrides.get(normalizedSlug);
158 if (version && version !== 'latest') {
149 - versionMap.set(toolkit.slug.toLowerCase() as Lowercase<string>, version);
159 + versionMap.set(normalizedSlug, version);
160 }
161 }
162
@@ -167,15 +177,19 @@ export function generatePythonTypeStubs({
177 yield* pipe(
178 Effect.all(
179 sources.map(([filePath, content]) =>
170 - fs
171 - .writeFileString(filePath, content)
172 - .pipe(
173 - Effect.mapError(error => new Error(`Failed to write file ${filePath}: ${error}`))
180 + fs.writeFileString(filePath, content).pipe(
181 + Effect.mapError(
182 + cause =>
183 + new PythonGenerationWriteError({
184 + cause,
185 + filePath,
186 + message: `Failed to write file ${filePath}`,
187 + })
188 )
189 + )
190 ),
191 { concurrency: 1 }
177 - ),
178 - Effect.mapError(error => new Error(`Failed to write generated files: ${error}`))
192 + )
193 );
194
195 yield* spinner.stop('Type stubs generated successfully');
ts/packages/cli/src/commands/setup.cmd.ts
+41 -31
@@ -1,5 +1,5 @@
1 import { Command, Options } from '@effect/cli';
2 -import { Effect } from 'effect';
2 +import { Effect, Predicate } from 'effect';
3 import {
4 detectSetupTargets,
5 inspectSetupTargets,
@@ -10,13 +10,12 @@ import {
10 SetupCommandError,
11 uninstallSetupTargets,
12 type AgentHost,
13 - type SetupTarget,
13 } from 'src/services/setup';
14 import { TerminalUI } from 'src/services/terminal-ui';
15 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
16
17 const target = Options.choice('target', SETUP_TARGETS).pipe(
19 - Options.withDefault('auto' as SetupTarget),
18 + Options.withDefault('auto'),
19 Options.withDescription('Agent host to configure: auto, claude, codex, or all')
20 );
21
@@ -45,7 +44,14 @@ const formatTargets = (targets: ReadonlyArray<AgentHost>): string =>
44 targets.map(target => TARGET_LABELS[target]).join(' and ');
45
46 const errorMessage = (error: unknown): string =>
48 - error instanceof Error ? error.message : String(error);
47 + Predicate.isError(error) ? error.message : String(error);
48 +
49 +const setupCommandError = (message: string, operation: 'setup' | 'uninstall', cause?: unknown) =>
50 + new SetupCommandError({
51 + message,
52 + operation,
53 + ...(cause === undefined ? {} : { cause }),
54 + });
55
56 const setupBaseCmd = Command.make(
57 'setup',
@@ -53,6 +59,8 @@ const setupBaseCmd = Command.make(
59 ({ target, yes, ifPresent, uninstall }) =>
60 Effect.gen(function* () {
61 const ui = yield* TerminalUI;
62 + const terminal = yield* ui.capabilities;
63 + const operation = uninstall ? 'uninstall' : 'setup';
64 yield* ui.intro(uninstall ? 'composio setup --uninstall' : 'composio setup');
65
66 const detections = yield* detectSetupTargets(target);
@@ -70,10 +78,9 @@ const setupBaseCmd = Command.make(
78 yield* ui.log.info(`${formatTargets(notDetected)} not detected.`);
79 }
80 if (target === 'all' && notDetected.length > 0) {
73 - return yield* Effect.fail(
74 - new Error(
75 - `\`--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.`
76 - )
81 + return yield* setupCommandError(
82 + `\`--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.`,
83 + operation
84 );
85 }
86 if (unsupported.length > 0) {
@@ -82,7 +89,7 @@ const setupBaseCmd = Command.make(
89 .filter((message): message is string => Boolean(message))
90 .join(' ');
91 if (target !== 'auto') {
85 - return yield* Effect.fail(new Error(reason));
92 + return yield* setupCommandError(reason, operation);
93 }
94 yield* ui.log.warn(
95 `${formatTargets(unsupported.map(result => result.target))} plugin setup skipped. ${reason}`
@@ -94,22 +101,20 @@ const setupBaseCmd = Command.make(
101 );
102 return;
103 }
97 - return yield* Effect.fail(new Error(reason));
104 + return yield* setupCommandError(reason, operation);
105 }
106 }
107 if (detected.length === 0) {
108 if (target === 'claude' || target === 'codex') {
102 - return yield* Effect.fail(
103 - new Error(
104 - `${target} is not installed or not available on PATH. Install it and rerun \`composio setup${uninstall ? ' --uninstall' : ''} --target ${target}\`.`
105 - )
109 + return yield* setupCommandError(
110 + `${target} is not installed or not available on PATH. Install it and rerun \`composio setup${uninstall ? ' --uninstall' : ''} --target ${target}\`.`,
111 + operation
112 );
113 }
114 if (!ifPresent || target !== 'auto') {
109 - return yield* Effect.fail(
110 - new Error(
111 - `No supported agent host was detected. Install Claude Code or Codex, then rerun \`composio setup${uninstall ? ' --uninstall' : ''}\`.`
112 - )
115 + return yield* setupCommandError(
116 + `No supported agent host was detected. Install Claude Code or Codex, then rerun \`composio setup${uninstall ? ' --uninstall' : ''}\`.`,
117 + operation
118 );
119 }
120 yield* ui.outro(
@@ -145,9 +150,10 @@ const setupBaseCmd = Command.make(
150 }
151
152 if (!yes && removable.length > 0) {
148 - if (!(yield* ui.capabilities).isInteractive) {
149 - return yield* Effect.fail(
150 - new Error('Non-interactive uninstall requires `--yes` to approve local changes.')
153 + if (!terminal.isInteractive) {
154 + return yield* setupCommandError(
155 + 'Non-interactive uninstall requires `--yes` to approve local changes.',
156 + operation
157 );
158 }
159 const confirmed = yield* ui.confirm(
@@ -185,9 +191,10 @@ const setupBaseCmd = Command.make(
191
192 const pendingPlugins = pending.filter(status => !isSetupPluginReady(status));
193 if (!yes) {
188 - if (!(yield* ui.capabilities).isInteractive) {
189 - return yield* Effect.fail(
190 - new Error('Non-interactive setup requires `--yes` to approve local changes.')
194 + if (!terminal.isInteractive) {
195 + return yield* setupCommandError(
196 + 'Non-interactive setup requires `--yes` to approve local changes.',
197 + operation
198 );
199 }
200
@@ -206,7 +213,12 @@ const setupBaseCmd = Command.make(
213 for (const result of results) {
214 if (!result.plugin_changed) continue;
215
209 - const initial = pending.find(status => status.target === result.target)!;
216 + const initial = pending.find(status => status.target === result.target);
217 + if (!initial) {
218 + return yield* Effect.dieMessage(
219 + `Setup invariant violated: missing initial state for ${result.target}`
220 + );
221 + }
222 let action = 'configured and enabled';
223 if (!initial.plugin_installed) action = 'installed and enabled';
224 else if (!initial.plugin_enabled) action = 'enabled';
@@ -217,12 +229,10 @@ const setupBaseCmd = Command.make(
229
230 yield* ui.outro('Composio setup complete.');
231 }).pipe(
220 - Effect.mapError(
221 - error =>
222 - new SetupCommandError({
223 - message: errorMessage(error),
224 - operation: uninstall ? 'uninstall' : 'setup',
225 - })
232 + Effect.mapError(error =>
233 + error instanceof SetupCommandError
234 + ? error
235 + : setupCommandError(errorMessage(error), uninstall ? 'uninstall' : 'setup', error)
236 )
237 )
238 );
ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts
+15 -7
@@ -1,5 +1,5 @@
1 import { Args, Command, Options } from '@effect/cli';
2 -import { Effect, Option } from 'effect';
2 +import { Data, Effect, Option } from 'effect';
3 import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
@@ -9,6 +9,11 @@ import { ProjectContext } from 'src/services/project-context';
9 import { ComposioUserContext } from 'src/services/user-context';
10 import { formatToolkitInfo, formatToolkitInfoJson } from '../format';
11
12 +class ToolkitsInfoRequestError extends Data.TaggedError('commands/ToolkitsInfoRequestError')<{
13 + readonly message: string;
14 + readonly cause: unknown;
15 +}> {}
16 +
17 const slug = Args.text({ name: 'slug' }).pipe(
18 Args.withDescription('Toolkit slug (e.g. "gmail")'),
19 Args.optional
@@ -88,9 +93,14 @@ export const toolkitsCmd$Info = Command.make(
93 if (Option.isSome(resolvedUserId)) {
94 const client = yield* clientSingleton.get();
95 const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value);
91 - const sessionToolkits = yield* Effect.tryPromise(() =>
92 - client.toolRouter.session.toolkits(sessionId, { toolkits: [slugValue] })
93 - );
96 + const sessionToolkits = yield* Effect.tryPromise({
97 + try: () => client.toolRouter.session.toolkits(sessionId, { toolkits: [slugValue] }),
98 + catch: cause =>
99 + new ToolkitsInfoRequestError({
100 + message: `Failed to fetch toolkit "${slugValue}".`,
101 + cause,
102 + }),
103 + });
104 return { toolkit: sessionToolkits.items[0], detailedToolkitOpt };
105 }
106
@@ -162,9 +172,7 @@ export const toolkitsCmd$Info = Command.make(
172 );
173
174 // Next step hint
165 - yield* ui.log.step(
166 - `To list tools in this toolkit:\n> composio tools list "${toolkit.slug}"`
167 - );
175 + yield* ui.log.step(`To list tools in this toolkit:\n> composio tools list "${toolkit.slug}"`);
176
177 yield* ui.output(formatToolkitInfoJson(toolkit, detailedToolkit, allDetails));
178 })
ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts
+20 -9
@@ -1,6 +1,6 @@
1 import process from 'node:process';
2 import { Command, Options } from '@effect/cli';
3 -import { Effect, Option } from 'effect';
3 +import { Data, Effect, Option } from 'effect';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
6 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
@@ -11,6 +11,11 @@ import { clampLimit } from 'src/ui/clamp-limit';
11 import { extractMessage } from 'src/utils/api-error-extraction';
12 import { mergeToolkitData, formatToolkitsJson, formatToolkitsTable } from '../format';
13
14 +class ToolkitsListRequestError extends Data.TaggedError('commands/ToolkitsListRequestError')<{
15 + readonly message: string;
16 + readonly cause: unknown;
17 +}> {}
18 +
19 const query = Options.text('query').pipe(
20 Options.withDescription('Text search by name, slug, or description'),
21 Options.optional
@@ -126,15 +131,21 @@ export const toolkitsCmd$List = Command.make(
131 let sessionFailed = false;
132 if (sessionContext) {
133 const { client, sessionId } = sessionContext;
129 - sessionItems = yield* Effect.tryPromise(() =>
130 - client.toolRouter.session.toolkits(sessionId, {
131 - search: Option.getOrUndefined(query),
132 - limit: clampedLimit,
133 - is_connected: Option.getOrUndefined(connected),
134 - })
135 - ).pipe(
134 + sessionItems = yield* Effect.tryPromise({
135 + try: () =>
136 + client.toolRouter.session.toolkits(sessionId, {
137 + search: Option.getOrUndefined(query),
138 + limit: clampedLimit,
139 + is_connected: Option.getOrUndefined(connected),
140 + }),
141 + catch: cause =>
142 + new ToolkitsListRequestError({
143 + message: 'Failed to fetch session toolkits.',
144 + cause,
145 + }),
146 + }).pipe(
147 Effect.map(r => r.items),
137 - Effect.catchAll(error =>
148 + Effect.catchTag('commands/ToolkitsListRequestError', error =>
149 Effect.logDebug('Failed to fetch session toolkits:', error).pipe(
150 Effect.as(
151 [] as ReadonlyArray<
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+483 -439
@@ -1,8 +1,8 @@
1 -import { Args, Command, Options } from '@effect/cli';
1 +import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';
2 import type { Composio } from '@composio/client';
3 import { isLocalToolSlug } from '@composio/cli-local-tools';
4 import util from 'node:util';
5 -import { Effect, Option, Either, Exit, Fiber, Cause, HashSet } from 'effect';
5 +import { Cause, Data, Effect, Either, Exit, Fiber, HashSet, Option, Predicate } from 'effect';
6 import { encodingForModel } from 'js-tiktoken';
7 import { redact } from 'src/ui/redact';
8 import { parseJsonRecord } from 'src/utils/parse-json';
@@ -19,7 +19,12 @@ import {
19 validateToolInputArgumentsWithDefinition,
20 } from 'src/services/tool-input-validation';
21 import { TerminalUI } from 'src/services/terminal-ui';
22 -import { ToolsExecutor, detectInBandWarning } from 'src/services/tools-executor';
22 +import { logToolDebug, makePerfDebugLogger } from 'src/services/runtime-debug-logger';
23 +import {
24 + LocalToolsDisabledError,
25 + ToolsExecutor,
26 + detectInBandWarning,
27 +} from 'src/services/tools-executor';
28 import type { ToolExecuteParams, ToolExecuteResponse } from 'src/services/tools-executor';
29 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
30 import { ComposioUserContext } from 'src/services/user-context';
@@ -40,7 +45,6 @@ import {
45 formatResolveCommandProjectError,
46 } from 'src/services/command-project';
47 import { commandHintStep } from 'src/services/command-hints';
43 -import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';
48 import {
49 getFreshConsumerConnectedToolkitsFromCache,
50 refreshConsumerConnectedToolkitsCache,
@@ -63,6 +67,7 @@ import {
67 import * as constants from 'src/constants';
68 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
69 import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
70 +import { decodeConnectedAccountItemsWithFallback } from 'src/effects/decode-connected-account-list';
71
72 const slug = Args.text({ name: 'slug' }).pipe(
73 Args.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')
@@ -130,15 +135,39 @@ const resolveInput = (input: Option.Option<string>) =>
135 missingValue: '{}',
136 });
137
138 +const invalidArguments = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));
139 +
140 +type ToolExecutionErrorFields = {
141 + readonly reason:
142 + | 'invalid_arguments'
143 + | 'file_input'
144 + | 'connected_account'
145 + | 'missing_user_id'
146 + | 'unsupported_local_file'
147 + | 'connection_check'
148 + | 'execution_failed'
149 + | 'parallel_failed';
150 + readonly message: string;
151 + readonly toolSlug?: string;
152 + readonly cause?: unknown;
153 +};
154 +
155 +export class ToolExecutionError extends Data.TaggedError(
156 + 'ToolExecutionError'
157 +)<ToolExecutionErrorFields> {}
158 +
159 +class ReportedToolExecutionError extends Data.TaggedError(
160 + 'ReportedToolExecutionError'
161 +)<ToolExecutionErrorFields> {}
162 +
163 const parseArguments = (raw: string) =>
164 parseJsonRecord(raw).pipe(
135 - Either.mapLeft(
136 - error =>
137 - new Error(
138 - error.reason === 'not-a-record'
139 - ? 'Expected a JSON object for tool arguments, e.g. -d \'{ "key": "value" }\''
140 - : 'Invalid JSON input. Provide JSON or a JS-style object literal, e.g. -d \'{ "key": "value" }\''
141 - )
165 + Either.mapLeft(error =>
166 + invalidArguments(
167 + error.reason === 'not-a-record'
168 + ? 'Expected a JSON object for tool arguments, e.g. -d \'{ "key": "value" }\''
169 + : 'Invalid JSON input. Provide JSON or a JS-style object literal, e.g. -d \'{ "key": "value" }\''
170 + )
171 )
172 );
173
@@ -148,13 +177,13 @@ const hasNestedKey = (
177 ): boolean => {
178 let current: unknown = record;
179 for (const key of pathParts) {
151 - if (typeof current !== 'object' || current === null || Array.isArray(current)) {
180 + if (!Predicate.isRecord(current)) {
181 return false;
182 }
154 - if (!(key in (current as Record<string, unknown>))) {
183 + if (!(key in current)) {
184 return false;
185 }
157 - current = (current as Record<string, unknown>)[key];
186 + current = current[key];
187 }
188 return true;
189 };
@@ -176,10 +205,7 @@ const setNestedKey = (
205 }
206
207 const next = current[key];
179 - const nextObject =
180 - typeof next === 'object' && next !== null && !Array.isArray(next)
181 - ? { ...(next as Record<string, unknown>) }
182 - : {};
208 + const nextObject = Predicate.isRecord(next) ? { ...next } : {};
209 current[key] = nextObject;
210 current = nextObject;
211 }
@@ -197,28 +223,28 @@ const injectSingleFileArgument = (params: {
223 const uploadablePaths = findFileUploadablePaths(params.schema);
224
225 if (uploadablePaths.length === 0) {
200 - return yield* Effect.fail(
201 - new Error(
202 - `Tool "${params.slug}" has no file_uploadable input. Remove --file or pass JSON via -d.`
203 - )
204 - );
226 + return yield* new ToolExecutionError({
227 + reason: 'file_input',
228 + toolSlug: params.slug,
229 + message: `Tool "${params.slug}" has no file_uploadable input. Remove --file or pass JSON via -d.`,
230 + });
231 }
232
233 if (uploadablePaths.length > 1) {
208 - return yield* Effect.fail(
209 - new Error(
210 - `Tool "${params.slug}" has multiple file_uploadable inputs (${uploadablePaths.map(parts => parts.join('.')).join(', ')}). Pass the target field explicitly with -d instead of --file.`
211 - )
212 - );
234 + return yield* new ToolExecutionError({
235 + reason: 'file_input',
236 + toolSlug: params.slug,
237 + 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.`,
238 + });
239 }
240
241 const targetPath = uploadablePaths[0] ?? [];
242 if (hasNestedKey(params.args, targetPath)) {
217 - return yield* Effect.fail(
218 - new Error(
219 - `Cannot use --file because "${targetPath.join('.')}" is already set in -d. Remove that field or omit --file.`
220 - )
221 - );
243 + return yield* new ToolExecutionError({
244 + reason: 'file_input',
245 + toolSlug: params.slug,
246 + message: `Cannot use --file because "${targetPath.join('.')}" is already set in -d. Remove that field or omit --file.`,
247 + });
248 }
249
250 return setNestedKey(params.args, targetPath, params.filePath);
@@ -256,25 +282,26 @@ const ciRedactReplacer = (_key: string, value: unknown): unknown => {
282 return value;
283 };
284
259 -const formatUnknownObject = (value: object): string => {
260 - try {
261 - return JSON.stringify(value, null, 2);
262 - } catch {
263 - return util.inspect(value, { depth: 5, breakLength: 120 });
264 - }
265 -};
285 +// JSON.stringify throws synchronously on circular or BigInt-bearing API
286 +// payloads; fall back to util.inspect so the formatter stays a plain string
287 +// function for its callers.
288 +const formatUnknownObject = (value: object): string =>
289 + Either.getOrElse(
290 + Either.try(() => JSON.stringify(value, null, 2)),
291 + () => util.inspect(value, { depth: 5, breakLength: 120 })
292 + );
293
294 const redactRequestId = (value: object): object => {
295 if (!value || typeof value !== 'object' || Array.isArray(value)) {
296 return value;
297 }
271 - const record = value as Record<string, unknown>;
272 - const requestId = record.request_id;
298 + if (!Predicate.isRecord(value)) return value;
299 + const requestId = value.request_id;
300 if (typeof requestId !== 'string') {
301 return value;
302 }
303 return {
277 - ...record,
304 + ...value,
305 request_id: redact({ value: requestId }),
306 };
307 };
@@ -300,6 +327,10 @@ type StoredExecuteOutputSummary = {
327 readonly outputFilePath: string;
328 };
329
330 +type PreparedExecuteOutput =
331 + | { readonly kind: 'inline'; readonly json: string }
332 + | { readonly kind: 'file'; readonly summary: StoredExecuteOutputSummary };
333 +
334 const serializeExecuteOutput = (result: unknown): string =>
335 JSON.stringify(result, ciRedactReplacer, 2);
336
@@ -348,24 +379,7 @@ const persistLargeExecuteOutput = (toolSlug: string, json: string, sharedDirecto
379 } satisfies StoredExecuteOutputSummary;
380 });
381
351 -const perfDebugEpoch = Date.now();
352 -const perfDebugLog = (label: string, details: Record<string, unknown> = {}) => {
353 - if (!isPerfDebugEnabled()) return;
354 - // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)
355 - process.stderr.write(
356 - `[perf] ${JSON.stringify({
357 - phase: 'event',
358 - label,
359 - elapsedMs: Date.now() - perfDebugEpoch,
360 - ...details,
361 - })}\n`
362 - );
363 -};
364 -const toolDebugLog = (label: string, details: Record<string, unknown> = {}) => {
365 - if (!isToolDebugEnabled()) return;
366 - // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)
367 - process.stderr.write(`[tool-debug] ${JSON.stringify({ label, ...details })}\n`);
368 -};
382 +const perfDebugLog = makePerfDebugLogger();
383
384 const prepareExecuteOutput = (
385 toolSlug: string,
@@ -377,18 +391,18 @@ const prepareExecuteOutput = (
391 const tokenCount = getExecuteOutputEncoder().encode(json).length;
392 if (tokenCount <= EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD || !shouldStoreLargeExecuteOutput()) {
393 return {
380 - kind: 'inline' as const,
394 + kind: 'inline',
395 json,
382 - };
396 + } satisfies PreparedExecuteOutput;
397 }
398
399 return {
386 - kind: 'file' as const,
400 + kind: 'file',
401 summary: {
402 ...(yield* persistLargeExecuteOutput(toolSlug, json, sharedDirectory)),
403 logId: result.logId,
404 } satisfies StoredExecuteOutputSummary,
391 - };
405 + } satisfies PreparedExecuteOutput;
406 });
407
408 const emitExecuteFailureTelemetry = (params: {
@@ -403,10 +417,10 @@ const emitExecuteFailureTelemetry = (params: {
417 }) =>
418 Effect.gen(function* () {
419 const normalized = params.mappedError?.normalized ?? normalizeCliError(params.error);
406 - const failureOrigin =
420 + const failureOrigin: 'fast_fail' | 'main_endpoint' =
421 normalized instanceof ToolInputValidationError || params.stage !== 'execution'
408 - ? ('fast_fail' as const)
409 - : ('main_endpoint' as const);
422 + ? 'fast_fail'
423 + : 'main_endpoint';
424
425 if (normalized instanceof ToolInputValidationError) {
426 yield* trackCliEventEffect(
@@ -706,14 +720,6 @@ const handleExecutionError = (
720 return { error: mapped.message, slug: slugValue };
721 });
722
709 -class ToolExecutionError extends Error {
710 - readonly _tag = 'ToolExecutionError';
711 - constructor(readonly message: string) {
712 - super(message);
713 - this.name = 'ToolExecutionError';
714 - }
715 -}
716 -
723 type CachedValidationDecision =
724 { readonly status: 'valid' | 'stale' } | { readonly status: 'fail'; readonly error: unknown };
725
@@ -754,12 +760,12 @@ const spawnBackgroundValidationGuard = (params: {
760 };
761 }) =>
762 Effect.gen(function* () {
757 - perfDebugLog('execute.validation.background_spawn', { slug: params.slug });
763 + yield* perfDebugLog('execute.validation.background_spawn', { slug: params.slug });
764 const validationFiber = yield* validateToolInputArguments(params.slug, params.args, {
765 orgId: params.resolvedProject.orgId,
766 projectId: params.resolvedProject.projectId,
767 }).pipe(Effect.forkDaemon);
762 - perfDebugLog('execute.validation.background_spawned', { slug: params.slug });
768 + yield* perfDebugLog('execute.validation.background_spawned', { slug: params.slug });
769 return validationGuardFromFiber(validationFiber);
770 });
771
@@ -774,7 +780,7 @@ const initializeValidationState = (params: {
780 }) =>
781 Effect.gen(function* () {
782 if (!params.cachedDefinition) {
777 - perfDebugLog('execute.validation.cache_miss', { slug: params.slug });
783 + yield* perfDebugLog('execute.validation.cache_miss', { slug: params.slug });
784 return {
785 cacheHit: false,
786 validationGuard: Effect.never,
@@ -783,7 +789,7 @@ const initializeValidationState = (params: {
789 }
790 const cachedDefinition = params.cachedDefinition;
791
786 - perfDebugLog('execute.validation.cache_hit', {
792 + yield* perfDebugLog('execute.validation.cache_hit', {
793 slug: params.slug,
794 cachedVersion: cachedDefinition.version,
795 });
@@ -796,46 +802,47 @@ const initializeValidationState = (params: {
802 }
803 ).pipe(
804 Effect.tap(result =>
799 - Effect.sync(() =>
800 - perfDebugLog('execute.validation.version_check_done', {
801 - slug: params.slug,
802 - cachedVersion: cachedDefinition.version,
803 - latestVersion: result.latestVersion,
804 - isStale: result.isStale,
805 - })
806 - )
805 + perfDebugLog('execute.validation.version_check_done', {
806 + slug: params.slug,
807 + cachedVersion: cachedDefinition.version,
808 + latestVersion: result.latestVersion,
809 + isStale: result.isStale,
810 + })
811 ),
808 - Effect.either,
812 + Effect.option,
813 Effect.forkDaemon
814 );
815 const cachedValidationDecisionFiber = yield* Effect.gen(function* () {
812 - perfDebugLog('execute.validation.cached_start', { slug: params.slug });
813 - const result = yield* validateToolInputArgumentsWithDefinition(
816 + yield* perfDebugLog('execute.validation.cached_start', { slug: params.slug });
817 + const validationDecision = yield* validateToolInputArgumentsWithDefinition(
818 params.slug,
819 params.args,
820 cachedDefinition
817 - ).pipe(Effect.either);
818 - perfDebugLog('execute.validation.cached_end', {
821 + ).pipe(
822 + Effect.match({
823 + onFailure: error => ({ status: 'fail', error }) satisfies CachedValidationDecision,
824 + onSuccess: () => ({ status: 'valid' }) satisfies CachedValidationDecision,
825 + })
826 + );
827 + yield* perfDebugLog('execute.validation.cached_end', {
828 slug: params.slug,
820 - successful: Either.isRight(result),
829 + successful: validationDecision.status === 'valid',
830 });
822 - if (Either.isRight(result)) {
823 - return { status: 'valid' as const };
831 + if (validationDecision.status === 'valid') {
832 + return validationDecision;
833 }
834
826 - const freshnessEither = yield* Fiber.join(versionCheckFiber);
827 - const isStale = Either.isRight(freshnessEither) && freshnessEither.right.isStale;
828 - perfDebugLog('execute.validation.cached_failed', {
835 + const freshnessResult = yield* Fiber.join(versionCheckFiber);
836 + const isStale = Option.isSome(freshnessResult) && freshnessResult.value.isStale;
837 + yield* perfDebugLog('execute.validation.cached_failed', {
838 slug: params.slug,
839 cacheStillCurrent: !isStale,
840 });
841 return isStale
833 - ? { status: 'stale' as const }
834 - : { status: 'fail' as const, error: result.left };
842 + ? ({ status: 'stale' } satisfies CachedValidationDecision)
843 + : validationDecision;
844 }).pipe(Effect.forkDaemon);
836 - const awaitCachedValidationDecision = Fiber.join(
837 - cachedValidationDecisionFiber
838 - ) as Effect.Effect<CachedValidationDecision, never>;
845 + const awaitCachedValidationDecision = Fiber.join(cachedValidationDecisionFiber);
846
847 return {
848 cacheHit: true,
@@ -964,7 +971,7 @@ const resolveExplicitConnectedAccount = (params: {
971 readonly toolkitSlug?: string;
972 readonly userId: string;
973 readonly selector: Option.Option<string>;
967 -}): Effect.Effect<string | undefined, Error> =>
974 +}) =>
975 Effect.gen(function* () {
976 if (!params.toolkitSlug) return undefined;
977 const toolkitSlug = params.toolkitSlug;
@@ -977,14 +984,28 @@ const resolveExplicitConnectedAccount = (params: {
984 statuses: ['ACTIVE'],
985 limit: 100,
986 }),
980 - catch: error =>
981 - new Error(
982 - `Failed to load connected accounts for toolkit "${toolkitSlug}": ${String(error)}`
983 - ),
987 + catch: cause =>
988 + new ToolExecutionError({
989 + reason: 'connected_account',
990 + toolSlug: params.toolkitSlug,
991 + message: `Failed to load connected accounts for toolkit "${toolkitSlug}": ${String(cause)}`,
992 + cause,
993 + }),
994 });
995 + const selectableAccounts = yield* decodeConnectedAccountItemsWithFallback(accounts.items).pipe(
996 + Effect.mapError(
997 + cause =>
998 + new ToolExecutionError({
999 + reason: 'connected_account',
1000 + toolSlug: toolkitSlug,
1001 + message: `Connected accounts for toolkit "${toolkitSlug}" did not match the expected response shape.`,
1002 + cause,
1003 + })
1004 + )
1005 + );
1006
1007 const selected = resolveConnectedAccountSelection(
987 - accounts.items as Parameters<typeof resolveConnectedAccountSelection>[0],
1008 + selectableAccounts,
1009 Option.getOrUndefined(params.selector)
1010 );
1011
@@ -996,18 +1017,16 @@ const resolveExplicitConnectedAccount = (params: {
1017 return undefined;
1018 }
1019
999 - const choices = formatConnectedAccountChoices(
1000 - accounts.items as Parameters<typeof formatConnectedAccountChoices>[0]
1001 - );
1020 + const choices = formatConnectedAccountChoices(selectableAccounts);
1021 const hint =
1022 choices.length > 0
1023 ? ` Available accounts: ${choices.join(', ')}.`
1024 : ' No active connected accounts were found for that toolkit.';
1006 - return yield* Effect.fail(
1007 - new Error(
1008 - `No connected account matched "${params.selector.value}" for toolkit "${toolkitSlug}".${hint}`
1009 - )
1010 - );
1025 + return yield* new ToolExecutionError({
1026 + reason: 'connected_account',
1027 + toolSlug: toolkitSlug,
1028 + message: `No connected account matched "${params.selector.value}" for toolkit "${toolkitSlug}".${hint}`,
1029 + });
1030 });
1031
1032 const resolveExecuteContext = (params: RunToolsExecuteParams) =>
@@ -1022,16 +1041,20 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
1041 isLocalToolSlug(params.slug) &&
1042 !cliConfig.isExperimentalFeatureEnabled(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS)
1043 ) {
1025 - return yield* Effect.fail(
1026 - new Error(
1027 - `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${params.slug}.`
1028 - )
1029 - );
1044 + return yield* new LocalToolsDisabledError({
1045 + toolSlug: params.slug,
1046 + feature: CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,
1047 + message: `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${params.slug}.`,
1048 + });
1049 }
1050
1051 if (isLocalToolSlug(params.slug)) {
1052 if (Option.isSome(params.file)) {
1034 - return yield* Effect.fail(new Error('--file is not supported for local tools yet.'));
1053 + return yield* new ToolExecutionError({
1054 + reason: 'unsupported_local_file',
1055 + toolSlug: params.slug,
1056 + message: '--file is not supported for local tools yet.',
1057 + });
1058 }
1059 return {
1060 ui,
@@ -1074,13 +1097,14 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
1097 });
1098
1099 if (Option.isNone(resolvedUserId)) {
1077 - return yield* Effect.fail(
1078 - new Error(
1100 + return yield* new ToolExecutionError({
1101 + reason: 'missing_user_id',
1102 + toolSlug: params.slug,
1103 + message:
1104 params.projectMode === 'developer'
1105 ? 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.'
1081 - : 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
1082 - )
1083 - );
1106 + : 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
1107 + });
1108 }
1109
1110 const client = yield* clientSingleton.getFor({
@@ -1180,7 +1204,7 @@ const runConnectedToolkitFailFast = (params: {
1204 }) =>
1205 Effect.gen(function* () {
1206 if (params.skipConnectionCheck || params.skipChecks) {
1183 - perfDebugLog('execute.connected_toolkits.skipped', {
1207 + yield* perfDebugLog('execute.connected_toolkits.skipped', {
1208 slug: params.slug,
1209 reason: params.skipChecks ? 'skip-checks' : 'skip-connection-check',
1210 });
@@ -1189,7 +1213,7 @@ const runConnectedToolkitFailFast = (params: {
1213 if (params.resolvedProject.projectType !== 'CONSUMER') return;
1214 if (isLocalToolSlug(params.slug)) return;
1215
1192 - perfDebugLog('execute.connected_toolkits.refresh_start', {
1216 + yield* perfDebugLog('execute.connected_toolkits.refresh_start', {
1217 slug: params.slug,
1218 orgId: params.resolvedProject.orgId,
1219 consumerUserId: params.resolvedUserId,
@@ -1199,24 +1223,20 @@ const runConnectedToolkitFailFast = (params: {
1223 consumerUserId: params.resolvedUserId,
1224 }).pipe(
1225 Effect.tap(() =>
1202 - Effect.sync(() =>
1203 - perfDebugLog('execute.connected_toolkits.refresh_end', {
1204 - slug: params.slug,
1205 - orgId: params.resolvedProject.orgId,
1206 - consumerUserId: params.resolvedUserId,
1207 - successful: true,
1208 - })
1209 - )
1226 + perfDebugLog('execute.connected_toolkits.refresh_end', {
1227 + slug: params.slug,
1228 + orgId: params.resolvedProject.orgId,
1229 + consumerUserId: params.resolvedUserId,
1230 + successful: true,
1231 + })
1232 ),
1233 Effect.catchAll(() =>
1212 - Effect.sync(() =>
1213 - perfDebugLog('execute.connected_toolkits.refresh_end', {
1214 - slug: params.slug,
1215 - orgId: params.resolvedProject.orgId,
1216 - consumerUserId: params.resolvedUserId,
1217 - successful: false,
1218 - })
1219 - )
1234 + perfDebugLog('execute.connected_toolkits.refresh_end', {
1235 + slug: params.slug,
1236 + orgId: params.resolvedProject.orgId,
1237 + consumerUserId: params.resolvedUserId,
1238 + successful: false,
1239 + })
1240 ),
1241 Effect.forkDaemon,
1242 Effect.asVoid
@@ -1229,7 +1249,7 @@ const runConnectedToolkitFailFast = (params: {
1249 orgId: params.resolvedProject.orgId,
1250 consumerUserId: params.resolvedUserId,
1251 });
1232 - perfDebugLog(
1252 + yield* perfDebugLog(
1253 Option.isSome(cachedToolkits)
1254 ? 'execute.connected_toolkits.cache_hit'
1255 : 'execute.connected_toolkits.cache_miss',
@@ -1243,7 +1263,7 @@ const runConnectedToolkitFailFast = (params: {
1263 );
1264
1265 if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(toolkit)) {
1246 - perfDebugLog('execute.connected_toolkits.fail_fast', {
1266 + yield* perfDebugLog('execute.connected_toolkits.fail_fast', {
1267 slug: params.slug,
1268 toolkit,
1269 orgId: params.resolvedProject.orgId,
@@ -1264,11 +1284,22 @@ const runConnectedToolkitFailFast = (params: {
1284 2
1285 )
1286 );
1267 - return yield* Effect.fail(new ToolExecutionError(message));
1287 + return yield* new ToolExecutionError({
1288 + reason: 'connection_check',
1289 + toolSlug: params.slug,
1290 + message,
1291 + });
1292 }
1293 });
1294
1271 -// eslint-disable-next-line max-lines-per-function
1295 +const executeSessionHistoryScope = (resolvedProject: ResolvedExecuteContext['resolvedProject']) =>
1296 + resolvedProject.projectType === 'CONSUMER'
1297 + ? {
1298 + orgId: resolvedProject.orgId,
1299 + consumerUserId: resolvedProject.consumerUserId,
1300 + }
1301 + : {};
1302 +
1303 const runExecuteWithSpinner = (params: {
1304 readonly slug: string;
1305 readonly surface: 'root' | 'dev';
@@ -1290,7 +1321,7 @@ const runExecuteWithSpinner = (params: {
1321 const cachedDefinition = verificationDisabled
1322 ? null
1323 : yield* getCachedToolInputDefinition(params.slug);
1293 - const validationState = verificationDisabled
1324 + const validationState: ValidationState = verificationDisabled
1325 ? ({
1326 cacheHit: false,
1327 validationGuard: Effect.never,
@@ -1368,14 +1399,7 @@ const runExecuteWithSpinner = (params: {
1399 );
1400 yield* writeExecuteStdout(params.ui, JSON.stringify(summary, ciRedactReplacer, 2));
1401 yield* appendCliSessionHistory({
1371 - orgId:
1372 - params.resolvedProject.projectType === 'CONSUMER'
1373 - ? params.resolvedProject.orgId
1374 - : undefined,
1375 - consumerUserId:
1376 - params.resolvedProject.projectType === 'CONSUMER'
1377 - ? params.resolvedProject.consumerUserId
1378 - : undefined,
1402 + ...executeSessionHistoryScope(params.resolvedProject),
1403 entry: {
1404 command: 'execute',
1405 status: 'dry-run',
@@ -1386,61 +1410,63 @@ const runExecuteWithSpinner = (params: {
1410 return;
1411 }
1412
1389 - perfDebugLog('execute.tool_call.start', { slug: params.slug });
1390 - const resultEither = yield* params.executor
1391 - .execute(params.slug, params.executeParams)
1392 - .pipe(Effect.raceFirst(validationGuard))
1393 - .pipe(Effect.either);
1394 - toolDebugLog('execute_result', {
1395 - slug: params.slug,
1396 - result: Either.isRight(resultEither) ? resultEither.right : resultEither.left,
1397 - });
1398 - perfDebugLog('execute.tool_call.end', {
1399 - slug: params.slug,
1400 - successful: Either.isRight(resultEither),
1401 - });
1402 -
1403 - if (Either.isLeft(resultEither)) {
1404 - yield* invalidateToolInputDefinition(params.slug).pipe(
1405 - Effect.catchAll(() => Effect.void)
1406 - );
1407 - yield* spinner.error();
1408 - const summary = yield* handleExecutionError(params.ui, resultEither.left, {
1409 - toolSlug: params.slug,
1410 - args: params.args,
1411 - surface: params.surface,
1412 - projectMode: params.projectMode,
1413 - stage: 'execution',
1414 - });
1415 - yield* writeExecuteStdout(
1416 - params.ui,
1417 - JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)
1418 - );
1419 - yield* appendCliSessionHistory({
1420 - orgId:
1421 - params.resolvedProject.projectType === 'CONSUMER'
1422 - ? params.resolvedProject.orgId
1423 - : undefined,
1424 - consumerUserId:
1425 - params.resolvedProject.projectType === 'CONSUMER'
1426 - ? params.resolvedProject.consumerUserId
1427 - : undefined,
1428 - entry: {
1429 - command: 'execute',
1430 - status: 'error',
1431 - slug: params.slug,
1432 - arguments: params.args,
1433 - error: summary.error,
1434 - },
1435 - }).pipe(Effect.catchAll(() => Effect.void));
1436 - return yield* Effect.fail(new ToolExecutionError(summary.error));
1437 - }
1438 -
1439 - const result = resultEither.right;
1413 + yield* perfDebugLog('execute.tool_call.start', { slug: params.slug });
1414 + const result = yield* params.executor.execute(params.slug, params.executeParams).pipe(
1415 + Effect.raceFirst(validationGuard),
1416 + Effect.matchEffect({
1417 + onFailure: error =>
1418 + Effect.gen(function* () {
1419 + yield* logToolDebug('execute_result', { slug: params.slug, result: error });
1420 + yield* perfDebugLog('execute.tool_call.end', {
1421 + slug: params.slug,
1422 + successful: false,
1423 + });
1424 + yield* invalidateToolInputDefinition(params.slug).pipe(
1425 + Effect.catchAll(() => Effect.void)
1426 + );
1427 + yield* spinner.error();
1428 + const summary = yield* handleExecutionError(params.ui, error, {
1429 + toolSlug: params.slug,
1430 + args: params.args,
1431 + surface: params.surface,
1432 + projectMode: params.projectMode,
1433 + stage: 'execution',
1434 + });
1435 + yield* writeExecuteStdout(
1436 + params.ui,
1437 + JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)
1438 + );
1439 + yield* appendCliSessionHistory({
1440 + ...executeSessionHistoryScope(params.resolvedProject),
1441 + entry: {
1442 + command: 'execute',
1443 + status: 'error',
1444 + slug: params.slug,
1445 + arguments: params.args,
1446 + error: summary.error,
1447 + },
1448 + }).pipe(Effect.catchAll(() => Effect.void));
1449 + return yield* new ReportedToolExecutionError({
1450 + reason: 'execution_failed',
1451 + toolSlug: params.slug,
1452 + message: summary.error,
1453 + });
1454 + }),
1455 + onSuccess: result =>
1456 + Effect.gen(function* () {
1457 + yield* logToolDebug('execute_result', { slug: params.slug, result });
1458 + yield* perfDebugLog('execute.tool_call.end', {
1459 + slug: params.slug,
1460 + successful: true,
1461 + });
1462 + return result;
1463 + }),
1464 + })
1465 + );
1466 if (validationState.awaitCachedValidationDecision) {
1467 const decision = yield* validationState.awaitCachedValidationDecision;
1468 if (decision.status === 'fail') {
1443 - perfDebugLog('execute.validation.post_success_failure_ignored', {
1469 + yield* perfDebugLog('execute.validation.post_success_failure_ignored', {
1470 slug: params.slug,
1471 });
1472 }
@@ -1464,7 +1490,11 @@ const runExecuteWithSpinner = (params: {
1490 logId: result.logId,
1491 });
1492 yield* writeExecuteStdout(params.ui, JSON.stringify(result, ciRedactReplacer, 2));
1467 - return yield* Effect.fail(new ToolExecutionError(summary.error));
1493 + return yield* new ReportedToolExecutionError({
1494 + reason: 'execution_failed',
1495 + toolSlug: params.slug,
1496 + message: summary.error,
1497 + });
1498 }
1499
1500 yield* spinner.stop(`Execution successful${executionSuccessSuffix(result)}`);
@@ -1481,14 +1511,7 @@ const runExecuteWithSpinner = (params: {
1511 );
1512 yield* writeExecuteStdout(params.ui, JSON.stringify(output.summary, ciRedactReplacer, 2));
1513 yield* appendCliSessionHistory({
1484 - orgId:
1485 - params.resolvedProject.projectType === 'CONSUMER'
1486 - ? params.resolvedProject.orgId
1487 - : undefined,
1488 - consumerUserId:
1489 - params.resolvedProject.projectType === 'CONSUMER'
1490 - ? params.resolvedProject.consumerUserId
1491 - : undefined,
1514 + ...executeSessionHistoryScope(params.resolvedProject),
1515 entry: {
1516 command: 'execute',
1517 status: 'success',
@@ -1505,14 +1528,7 @@ const runExecuteWithSpinner = (params: {
1528
1529 yield* writeExecuteStdout(params.ui, output.json);
1530 yield* appendCliSessionHistory({
1508 - orgId:
1509 - params.resolvedProject.projectType === 'CONSUMER'
1510 - ? params.resolvedProject.orgId
1511 - : undefined,
1512 - consumerUserId:
1513 - params.resolvedProject.projectType === 'CONSUMER'
1514 - ? params.resolvedProject.consumerUserId
1515 - : undefined,
1531 + ...executeSessionHistoryScope(params.resolvedProject),
1532 entry: {
1533 command: 'execute',
1534 status: 'success',
@@ -1535,11 +1551,11 @@ const runToolsExecute = (params: RunToolsExecuteParams) =>
1551 isLocalToolSlug(params.slug) &&
1552 !cliConfig.isExperimentalFeatureEnabled(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS)
1553 ) {
1538 - return yield* Effect.fail(
1539 - new Error(
1540 - `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${params.slug}.`
1541 - )
1542 - );
1554 + return yield* new LocalToolsDisabledError({
1555 + toolSlug: params.slug,
1556 + feature: CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,
1557 + message: `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${params.slug}.`,
1558 + });
1559 }
1560
1561 if (params.getSchema) {
@@ -1574,7 +1590,7 @@ const runToolsExecute = (params: RunToolsExecuteParams) =>
1590 skipConnectionCheck: params.skipConnectionCheck,
1591 skipChecks: params.skipChecks,
1592 });
1577 - toolDebugLog('execute_params', {
1593 + yield* logToolDebug('execute_params', {
1594 slug: params.slug,
1595 userId: context.resolvedUserId,
1596 connectedAccountId: context.selectedConnectedAccountId,
@@ -1582,7 +1598,7 @@ const runToolsExecute = (params: RunToolsExecuteParams) =>
1598 projectId: context.resolvedProject.projectId,
1599 orgId: context.resolvedProject.orgId,
1600 });
1585 - perfDebugLog('execute.prepare', {
1601 + yield* perfDebugLog('execute.prepare', {
1602 slug: params.slug,
1603 surface: params.surface,
1604 projectMode: params.projectMode,
@@ -1603,7 +1619,7 @@ const runToolsExecute = (params: RunToolsExecuteParams) =>
1619 });
1620 });
1621
1606 -const parseParallelExecuteArgs = (
1622 +export const parseParallelExecuteArgs = (
1623 args: ReadonlyArray<string>,
1624 config: {
1625 readonly surface: 'root' | 'dev';
@@ -1611,153 +1627,181 @@ const parseParallelExecuteArgs = (
1627 readonly allowUserId: boolean;
1628 readonly allowProjectName: boolean;
1629 }
1614 -): ParsedParallelExecuteArgs => {
1615 - let getSchema = false;
1616 - let dryRun = false;
1617 - let skipConnectionCheck = false;
1618 - let skipToolParamsCheck = false;
1619 - let skipChecks = false;
1620 - let account = Option.none<string>();
1621 - let userId = Option.none<string>();
1622 - let projectName = Option.none<string>();
1623 - const specs: ParallelExecuteSpec[] = [];
1624 - let currentSpec: ParallelExecuteSpec | null = null;
1625 -
1626 - const pushCurrentSpec = () => {
1627 - if (!currentSpec) return;
1628 - specs.push(currentSpec);
1629 - currentSpec = null;
1630 - };
1630 +) =>
1631 + Effect.gen(function* () {
1632 + let getSchema = false;
1633 + let dryRun = false;
1634 + let skipConnectionCheck = false;
1635 + let skipToolParamsCheck = false;
1636 + let skipChecks = false;
1637 + let account = Option.none<string>();
1638 + let userId = Option.none<string>();
1639 + let projectName = Option.none<string>();
1640 + const specs: ParallelExecuteSpec[] = [];
1641 + let currentSpec: ParallelExecuteSpec | null = null;
1642 +
1643 + const pushCurrentSpec = () => {
1644 + if (!currentSpec) return;
1645 + specs.push(currentSpec);
1646 + currentSpec = null;
1647 + };
1648
1632 - const readValue = (token: string, index: number) => {
1633 - if (token.includes('=')) {
1634 - return {
1635 - value: token.slice(token.indexOf('=') + 1),
1636 - nextIndex: index,
1637 - };
1638 - }
1649 + const readValue = (token: string, index: number) => {
1650 + if (token.includes('=')) {
1651 + return Effect.succeed({
1652 + value: token.slice(token.indexOf('=') + 1),
1653 + nextIndex: index,
1654 + });
1655 + }
1656
1640 - const next = args[index + 1];
1641 - if (!next) {
1642 - throw new Error(`Missing value for ${token}.`);
1643 - }
1644 - return { value: next, nextIndex: index + 1 };
1645 - };
1657 + const next = args[index + 1];
1658 + if (!next) {
1659 + return Effect.fail(invalidArguments(`Missing value for ${token}.`));
1660 + }
1661 + return Effect.succeed({ value: next, nextIndex: index + 1 });
1662 + };
1663
1647 - for (let i = 0; i < args.length; i += 1) {
1648 - const token = args[i];
1649 - if (!token) continue;
1664 + for (let i = 0; i < args.length; i += 1) {
1665 + const token = args[i];
1666 + if (!token) continue;
1667
1651 - if (token === '--parallel' || token === '-p') {
1652 - continue;
1653 - }
1654 - if (token === '--get-schema') {
1655 - getSchema = true;
1656 - continue;
1657 - }
1658 - if (token === '--dry-run') {
1659 - dryRun = true;
1660 - continue;
1661 - }
1662 - if (token === '--skip-connection-check') {
1663 - skipConnectionCheck = true;
1664 - continue;
1665 - }
1666 - if (token === '--skip-tool-params-check') {
1667 - skipToolParamsCheck = true;
1668 - continue;
1669 - }
1670 - if (token === '--skip-checks') {
1671 - skipChecks = true;
1672 - continue;
1673 - }
1674 - if (token === '--account' || token.startsWith('--account=')) {
1675 - const parsed = readValue(token, i);
1676 - account = Option.some(parsed.value);
1677 - i = parsed.nextIndex;
1678 - continue;
1679 - }
1680 - if (token === '--user-id' || token.startsWith('--user-id=')) {
1681 - if (!config.allowUserId) {
1682 - throw new Error(`${token} is not supported for this execute command.`);
1668 + if (token === '--parallel' || token === '-p') {
1669 + continue;
1670 }
1684 - const parsed = readValue(token, i);
1685 - userId = Option.some(parsed.value);
1686 - i = parsed.nextIndex;
1687 - continue;
1688 - }
1689 - if (token === '--project-name' || token.startsWith('--project-name=')) {
1690 - if (!config.allowProjectName) {
1691 - throw new Error(`${token} is not supported for this execute command.`);
1671 + if (token === '--get-schema') {
1672 + getSchema = true;
1673 + continue;
1674 }
1693 - const parsed = readValue(token, i);
1694 - projectName = Option.some(parsed.value);
1695 - i = parsed.nextIndex;
1696 - continue;
1697 - }
1698 - if (
1699 - token === '--data' ||
1700 - token === '-d' ||
1701 - token.startsWith('--data=') ||
1702 - token.startsWith('-d=')
1703 - ) {
1704 - if (!currentSpec) {
1705 - throw new Error(
1706 - `Expected a tool slug before ${token}. Use: composio execute --parallel TOOL_SLUG -d '{}' TOOL_SLUG_2 -d '{}'.`
1675 + if (token === '--dry-run') {
1676 + dryRun = true;
1677 + continue;
1678 + }
1679 + if (token === '--skip-connection-check') {
1680 + skipConnectionCheck = true;
1681 + continue;
1682 + }
1683 + if (token === '--skip-tool-params-check') {
1684 + skipToolParamsCheck = true;
1685 + continue;
1686 + }
1687 + if (token === '--skip-checks') {
1688 + skipChecks = true;
1689 + continue;
1690 + }
1691 + if (token === '--account' || token.startsWith('--account=')) {
1692 + const parsed = yield* readValue(token, i);
1693 + if (currentSpec) {
1694 + currentSpec = {
1695 + slug: currentSpec.slug,
1696 + data: currentSpec.data,
1697 + account: Option.some(parsed.value),
1698 + };
1699 + } else {
1700 + account = Option.some(parsed.value);
1701 + }
1702 + i = parsed.nextIndex;
1703 + continue;
1704 + }
1705 + if (token === '--user-id' || token.startsWith('--user-id=')) {
1706 + if (!config.allowUserId) {
1707 + return yield* Effect.fail(
1708 + invalidArguments(`${token} is not supported for this execute command.`)
1709 + );
1710 + }
1711 + const parsed = yield* readValue(token, i);
1712 + userId = Option.some(parsed.value);
1713 + i = parsed.nextIndex;
1714 + continue;
1715 + }
1716 + if (token === '--project-name' || token.startsWith('--project-name=')) {
1717 + if (!config.allowProjectName) {
1718 + return yield* Effect.fail(
1719 + invalidArguments(`${token} is not supported for this execute command.`)
1720 + );
1721 + }
1722 + const parsed = yield* readValue(token, i);
1723 + projectName = Option.some(parsed.value);
1724 + i = parsed.nextIndex;
1725 + continue;
1726 + }
1727 + if (
1728 + token === '--data' ||
1729 + token === '-d' ||
1730 + token.startsWith('--data=') ||
1731 + token.startsWith('-d=')
1732 + ) {
1733 + if (!currentSpec) {
1734 + return yield* Effect.fail(
1735 + invalidArguments(
1736 + `Expected a tool slug before ${token}. Use: composio execute --parallel TOOL_SLUG -d '{}' TOOL_SLUG_2 -d '{}'.`
1737 + )
1738 + );
1739 + }
1740 + const parsed = yield* readValue(token, i);
1741 + currentSpec = {
1742 + slug: currentSpec.slug,
1743 + data: Option.some(parsed.value),
1744 + account: currentSpec.account,
1745 + };
1746 + i = parsed.nextIndex;
1747 + continue;
1748 + }
1749 + if (token.startsWith('-')) {
1750 + return yield* Effect.fail(
1751 + invalidArguments(`Unknown option for parallel execute: ${token}`)
1752 );
1753 }
1709 - const parsed = readValue(token, i);
1754 +
1755 + pushCurrentSpec();
1756 currentSpec = {
1711 - slug: currentSpec.slug,
1712 - data: Option.some(parsed.value),
1713 - account: currentSpec.account,
1757 + slug: token,
1758 + data: Option.none(),
1759 + account,
1760 };
1715 - i = parsed.nextIndex;
1716 - continue;
1717 - }
1718 - if (token.startsWith('-')) {
1719 - throw new Error(`Unknown option for parallel execute: ${token}`);
1761 }
1762
1763 pushCurrentSpec();
1723 - currentSpec = {
1724 - slug: token,
1725 - data: Option.none(),
1726 - account,
1727 - };
1728 - }
1764
1730 - pushCurrentSpec();
1765 + if (specs.length === 0) {
1766 + return yield* Effect.fail(
1767 + invalidArguments(
1768 + "No tool slugs were provided. Use: composio execute --parallel TOOL_SLUG -d '{}' TOOL_SLUG_2 -d '{}'."
1769 + )
1770 + );
1771 + }
1772
1732 - if (specs.length === 0) {
1733 - throw new Error(
1734 - "No tool slugs were provided. Use: composio execute --parallel TOOL_SLUG -d '{}' TOOL_SLUG_2 -d '{}'."
1735 - );
1736 - }
1773 + return {
1774 + specs,
1775 + userId,
1776 + projectName,
1777 + surface: config.surface,
1778 + projectMode: config.projectMode,
1779 + getSchema,
1780 + dryRun,
1781 + skipConnectionCheck,
1782 + skipToolParamsCheck,
1783 + skipChecks,
1784 + account,
1785 + } satisfies ParsedParallelExecuteArgs;
1786 + });
1787
1738 - return {
1739 - specs,
1740 - userId,
1741 - projectName,
1742 - surface: config.surface,
1743 - projectMode: config.projectMode,
1744 - getSchema,
1745 - dryRun,
1746 - skipConnectionCheck,
1747 - skipToolParamsCheck,
1748 - skipChecks,
1749 - account,
1750 - };
1788 +type ParallelExecuteCommand = {
1789 + readonly matched: boolean;
1790 + readonly tail: ReadonlyArray<string>;
1791 + readonly surface: 'root' | 'dev';
1792 + readonly projectMode: 'consumer' | 'developer';
1793 + readonly allowUserId: boolean;
1794 + readonly allowProjectName: boolean;
1795 };
1796
1753 -const isParallelExecuteCommand = (argv: ReadonlyArray<string>) => {
1797 +const isParallelExecuteCommand = (argv: ReadonlyArray<string>): ParallelExecuteCommand | null => {
1798 const args = argv.slice(2);
1799 if (args[0] === 'execute') {
1800 return {
1801 matched: args.includes('--parallel') || args.includes('-p'),
1802 tail: args.slice(1),
1759 - surface: 'root' as const,
1760 - projectMode: 'consumer' as const,
1803 + surface: 'root',
1804 + projectMode: 'consumer',
1805 allowUserId: false,
1806 allowProjectName: false,
1807 };
@@ -1766,8 +1810,8 @@ const isParallelExecuteCommand = (argv: ReadonlyArray<string>) => {
1810 return {
1811 matched: args.includes('--parallel') || args.includes('-p'),
1812 tail: args.slice(2),
1769 - surface: 'dev' as const,
1770 - projectMode: 'developer' as const,
1813 + surface: 'dev',
1814 + projectMode: 'developer',
1815 allowUserId: true,
1816 allowProjectName: true,
1817 };
@@ -1805,9 +1849,11 @@ const checkConnectedToolkitOrFail = (params: {
1849 });
1850
1851 if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(toolkit)) {
1808 - throw new ToolExecutionError(
1809 - `Toolkit "${toolkit}" is not connected for this user (cached within the last 5 minutes). If you just connected the account, use --skip-connection-check.`
1810 - );
1852 + return yield* new ToolExecutionError({
1853 + reason: 'connection_check',
1854 + toolSlug: params.slug,
1855 + 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.`,
1856 + });
1857 }
1858 });
1859
@@ -1894,9 +1940,10 @@ const runParallelSchemaFetchFromParsed = (params: ParsedParallelExecuteArgs) =>
1940 )
1941 );
1942 if (!successful) {
1897 - return yield* Effect.fail(
1898 - new ToolExecutionError('One or more parallel tool executions failed.')
1899 - );
1943 + return yield* new ReportedToolExecutionError({
1944 + reason: 'parallel_failed',
1945 + message: 'One or more parallel tool executions failed.',
1946 + });
1947 }
1948 }
1949 });
@@ -1941,76 +1988,76 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
1988 Effect.gen(function* () {
1989 const toolSlug = spec.slug;
1990
1944 - try {
1945 - yield* checkConnectedToolkitOrFail({
1946 - slug: toolSlug,
1947 - resolvedProject: context.resolvedProject,
1948 - resolvedUserId: context.resolvedUserId,
1949 - skipConnectionCheck: params.skipConnectionCheck,
1950 - skipChecks: params.skipChecks,
1951 - });
1952 -
1953 - if (params.dryRun) {
1954 - const verificationDisabled = params.skipChecks || params.skipToolParamsCheck;
1955 - const definition = verificationDisabled
1956 - ? null
1957 - : yield* getOrFetchToolInputDefinition(toolSlug, {
1958 - orgId: context.resolvedProject.orgId,
1959 - projectId: context.resolvedProject.projectId,
1960 - });
1961 - if (definition) {
1962 - yield* validateToolInputArgumentsWithDefinition(toolSlug, context.args, definition);
1963 - }
1964 - return {
1965 - successful: true,
1966 - dryRun: true,
1967 - slug: toolSlug,
1968 - arguments: context.args,
1969 - userId: context.resolvedUserId,
1970 - schemaPath: definition?.schemaPath,
1971 - schemaVersion: definition?.version,
1972 - } satisfies DryRunSummary;
1973 - }
1991 + yield* checkConnectedToolkitOrFail({
1992 + slug: toolSlug,
1993 + resolvedProject: context.resolvedProject,
1994 + resolvedUserId: context.resolvedUserId,
1995 + skipConnectionCheck: params.skipConnectionCheck,
1996 + skipChecks: params.skipChecks,
1997 + });
1998
1975 - if (!params.skipChecks && !params.skipToolParamsCheck) {
1976 - const definition = yield* getOrFetchToolInputDefinition(toolSlug, {
1977 - orgId: context.resolvedProject.orgId,
1978 - projectId: context.resolvedProject.projectId,
1979 - });
1999 + if (params.dryRun) {
2000 + const verificationDisabled = params.skipChecks || params.skipToolParamsCheck;
2001 + const definition = verificationDisabled
2002 + ? null
2003 + : yield* getOrFetchToolInputDefinition(toolSlug, {
2004 + orgId: context.resolvedProject.orgId,
2005 + projectId: context.resolvedProject.projectId,
2006 + });
2007 + if (definition) {
2008 yield* validateToolInputArgumentsWithDefinition(toolSlug, context.args, definition);
2009 }
2010 + return {
2011 + successful: true,
2012 + dryRun: true,
2013 + slug: toolSlug,
2014 + arguments: context.args,
2015 + userId: context.resolvedUserId,
2016 + schemaPath: definition?.schemaPath,
2017 + schemaVersion: definition?.version,
2018 + } satisfies DryRunSummary;
2019 + }
2020
1983 - const result = yield* context.executor.execute(toolSlug, context.executeParams);
1984 - if (!result.successful) {
1985 - return {
1986 - slug: toolSlug,
1987 - successful: false,
1988 - error: result.error ?? 'Execution failed.',
1989 - logId: result.logId,
1990 - };
1991 - }
1992 -
1993 - const output = yield* prepareExecuteOutput(toolSlug, result, context.executeOutputDir);
1994 - if (output.kind === 'file') {
1995 - return {
1996 - slug: toolSlug,
1997 - ...output.summary,
1998 - };
1999 - }
2021 + if (!params.skipChecks && !params.skipToolParamsCheck) {
2022 + const definition = yield* getOrFetchToolInputDefinition(toolSlug, {
2023 + orgId: context.resolvedProject.orgId,
2024 + projectId: context.resolvedProject.projectId,
2025 + });
2026 + yield* validateToolInputArgumentsWithDefinition(toolSlug, context.args, definition);
2027 + }
2028
2029 + const result = yield* context.executor.execute(toolSlug, context.executeParams);
2030 + if (!result.successful) {
2031 return {
2032 slug: toolSlug,
2003 - ...result,
2033 + successful: false,
2034 + error: result.error ?? 'Execution failed.',
2035 + logId: result.logId,
2036 };
2005 - } catch (error) {
2006 - const mapped = mapComposioError({ error, toolSlug });
2037 + }
2038 +
2039 + const output = yield* prepareExecuteOutput(toolSlug, result, context.executeOutputDir);
2040 + if (output.kind === 'file') {
2041 return {
2042 slug: toolSlug,
2009 - successful: false,
2010 - error: mapped.message,
2043 + ...output.summary,
2044 };
2045 }
2013 - }),
2046 +
2047 + return {
2048 + slug: toolSlug,
2049 + ...result,
2050 + };
2051 + }).pipe(
2052 + Effect.catchAll(error => {
2053 + const mapped = mapComposioError({ error, toolSlug: spec.slug });
2054 + return Effect.succeed({
2055 + slug: spec.slug,
2056 + successful: false,
2057 + error: mapped.message,
2058 + } satisfies ParallelExecuteResult);
2059 + })
2060 + ),
2061 { concurrency: 'unbounded' }
2062 );
2063
@@ -2071,9 +2118,10 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
2118 }
2119
2120 if (!successful) {
2074 - return yield* Effect.fail(
2075 - new ToolExecutionError('One or more parallel tool executions failed.')
2076 - );
2121 + return yield* new ReportedToolExecutionError({
2122 + reason: 'parallel_failed',
2123 + message: 'One or more parallel tool executions failed.',
2124 + });
2125 }
2126 });
2127
@@ -2083,15 +2131,11 @@ export const runParallelToolsExecuteFromArgv = (argv: ReadonlyArray<string>) =>
2131 return null;
2132 }
2133
2086 - return Effect.try({
2087 - try: () =>
2088 - parseParallelExecuteArgs(command.tail, {
2089 - surface: command.surface,
2090 - projectMode: command.projectMode,
2091 - allowUserId: command.allowUserId,
2092 - allowProjectName: command.allowProjectName,
2093 - }),
2094 - catch: error => (error instanceof Error ? error : new Error(String(error))),
2134 + return parseParallelExecuteArgs(command.tail, {
2135 + surface: command.surface,
2136 + projectMode: command.projectMode,
2137 + allowUserId: command.allowUserId,
2138 + allowProjectName: command.allowProjectName,
2139 }).pipe(Effect.flatMap(runParallelToolsExecuteFromParsed));
2140 };
2141
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+42 -45
@@ -1,6 +1,7 @@
1 import { Args, Command, Options } from '@effect/cli';
2 import { isLocalToolkitSlug } from '@composio/cli-local-tools';
3 -import { Effect, Option } from 'effect';
3 +import type { SessionSearchResponse } from '@composio/client/resources/tool-router';
4 +import { Data, Effect, Option } from 'effect';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 import { requireAuth } from 'src/effects/require-auth';
7 import { setupCacheDir } from 'src/effects/setup-cache-dir';
@@ -59,35 +60,22 @@ const human = Options.boolean('human').pipe(
60 Options.withDescription('Show formatted human-readable search output')
61 );
62
62 -type SearchToolSchema = {
63 - tool_slug: string;
64 - toolkit: string;
65 - description?: string;
66 - input_schema?: Record<string, unknown>;
67 - output_schema?: Record<string, unknown>;
68 -};
63 +type SearchToolSchema = SessionSearchResponse.ToolSchemas;
64 +type SearchResultRecord = SessionSearchResponse.Result;
65 +type SearchResponseRecord = Pick<
66 + SessionSearchResponse,
67 + 'results' | 'toolkit_connection_statuses' | 'tool_schemas' | 'next_steps_guidance' | 'error'
68 +>;
69
70 -type SearchResultRecord = {
71 - use_case: string;
72 - primary_tool_slugs: string[];
73 - related_tool_slugs: string[];
74 - recommended_plan_steps?: string[];
75 - reference_workbench_snippets?: unknown;
76 - plan_id?: string;
77 -};
70 +export class ToolsSearchInputError extends Data.TaggedError('commands/ToolsSearchInputError')<{
71 + readonly reason: 'missing_query' | 'missing_user_id';
72 + readonly message: string;
73 +}> {}
74
79 -type ToolkitConnectionStatusRecord = {
80 - toolkit: string;
81 - has_active_connection: boolean;
82 -};
83 -
84 -type SearchResponseRecord = {
85 - results: SearchResultRecord[];
86 - toolkit_connection_statuses: ToolkitConnectionStatusRecord[];
87 - tool_schemas: Record<string, SearchToolSchema>;
88 - next_steps_guidance: string[];
89 - error: string | null;
90 -};
75 +class ToolsSearchRequestError extends Data.TaggedError('commands/ToolsSearchRequestError')<{
76 + readonly message: string;
77 + readonly cause: unknown;
78 +}> {}
79
80 const stripSearchResultMetadata = <
81 T extends { reference_workbench_snippets?: unknown; plan_id?: unknown },
@@ -137,9 +125,9 @@ const collectToolsForResult = (params: {
125 description: schema.description ?? '',
126 tags: [],
127 available_versions: [],
140 - input_parameters: (schema.input_schema ?? {}) as Record<string, unknown>,
141 - output_parameters: (schema.output_schema ?? {}) as Record<string, unknown>,
142 - } as Tool);
128 + input_parameters: schema.input_schema ?? {},
129 + output_parameters: schema.output_schema ?? {},
130 + });
131
132 if (toolsList.length >= params.limit) break;
133 }
@@ -195,7 +183,10 @@ const buildSearchJsonPayload = (params: {
183 yield* Effect.forEach(primaryToolSlugs, slug =>
184 Effect.gen(function* () {
185 const definition = yield* getOrFetchToolInputDefinition(slug, params.projectScope);
198 - return [slug, toHomeRelativePath(cacheDir, definition.schemaPath)] as const;
186 + return [slug, toHomeRelativePath(cacheDir, definition.schemaPath)] satisfies readonly [
187 + string,
188 + string,
189 + ];
190 })
191 )
192 );
@@ -228,7 +219,7 @@ const buildSearchJsonPayload = (params: {
219 'You can directly proceed with these steps without waiting for the user to ask. Link accounts first if needed, then execute tools.',
220 steps: params.nextSteps,
221 },
231 - } as const;
222 + };
223 });
224
225 const emitHumanSearchOutput = (params: {
@@ -313,7 +304,10 @@ const runToolsSearch = (params: {
304 const emitJson = params.json || !emitHuman;
305 const queries = params.query.map(q => q.trim()).filter(Boolean);
306 if (queries.length === 0) {
316 - return yield* Effect.fail(new Error('At least one query is required.'));
307 + return yield* new ToolsSearchInputError({
308 + reason: 'missing_query',
309 + message: 'At least one query is required.',
310 + });
311 }
312 const toolkitFilter = Option.getOrUndefined(params.toolkits);
313 const toolkitList =
@@ -337,11 +331,11 @@ const runToolsSearch = (params: {
331 onNone: () => userContext.data.testUserId,
332 });
333 if (Option.isNone(resolvedUserId)) {
340 - return yield* Effect.fail(
341 - new Error(
342 - 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
343 - )
344 - );
334 + return yield* new ToolsSearchInputError({
335 + reason: 'missing_user_id',
336 + message:
337 + 'Missing user id. Provide --user-id or run composio login to set global test_user_id.',
338 + });
339 }
340 const clientSingleton = yield* ComposioClientSingleton;
341 const client = yield* clientSingleton.getFor({
@@ -373,9 +367,14 @@ const runToolsSearch = (params: {
367 queries: queries.map(query => ({ use_case: query })),
368 ...(localExperimentalPayload ? { experimental: localExperimentalPayload } : {}),
369 };
376 - const searchResponse = yield* Effect.tryPromise(() =>
377 - client.toolRouter.session.search(sessionId, searchPayload)
378 - );
370 + const searchResponse = yield* Effect.tryPromise({
371 + try: () => client.toolRouter.session.search(sessionId, searchPayload),
372 + catch: cause =>
373 + new ToolsSearchRequestError({
374 + message: 'Failed to search tools.',
375 + cause,
376 + }),
377 + });
378 return {
379 searchResponse,
380 projectScope: {
@@ -435,9 +434,7 @@ const runToolsSearch = (params: {
434 ? searchResponse.tool_schemas[firstSlug]
435 : undefined;
436 const firstToolkit = firstSchema?.toolkit;
438 - const firstPayload = buildMinimalPayloadFromSchema(
439 - (firstSchema?.input_schema ?? {}) as Record<string, unknown>
440 - );
437 + const firstPayload = buildMinimalPayloadFromSchema(firstSchema?.input_schema ?? {});
438 const firstPayloadJson = JSON.stringify(firstPayload);
439 const firstDataArg =
440 Object.keys(firstPayload).length === 0 ? '-d "{}"' : `-d '${firstPayloadJson}'`;
ts/packages/cli/src/commands/triggers/commands/triggers.list.cmd.ts
+6 -4
@@ -1,7 +1,7 @@
1 -import { Args, Command, Options } from '@effect/cli';
1 +import { Args, Command, HelpDoc, Options, ValidationError } from '@effect/cli';
2 import { Effect } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 -import { ComposioToolkitsRepository, InvalidToolkitsError } from 'src/services/composio-clients';
4 +import { ComposioToolkitsRepository } from 'src/services/composio-clients';
5 import { TerminalUI } from 'src/services/terminal-ui';
6 import { clampLimit } from 'src/ui/clamp-limit';
7 import { formatTriggerTypesJson, formatTriggerTypesTable } from '../format';
@@ -39,7 +39,7 @@ const makeTriggersListCommand = ({ noResultsCommand, infoCommand }: TriggersList
39 const clampedLimit = clampLimit(limit);
40
41 yield* repo.validateToolkits([toolkit]).pipe(
42 - Effect.catchTag('services/InvalidToolkitsError', (error: InvalidToolkitsError) =>
42 + Effect.catchTag('services/InvalidToolkitsError', error =>
43 Effect.gen(function* () {
44 const availableExample = error.availableToolkits.slice(0, 8).join(', ');
45 yield* ui.log.error(
@@ -47,7 +47,9 @@ const makeTriggersListCommand = ({ noResultsCommand, infoCommand }: TriggersList
47 );
48 yield* ui.log.step(`List valid toolkits with:\n> ${noResultsCommand}`);
49 return yield* Effect.fail(
50 - new Error(`Invalid toolkit slug "${toolkit}" for trigger listing.`)
50 + ValidationError.invalidValue(
51 + HelpDoc.p(`Invalid toolkit slug "${toolkit}" for trigger listing.`)
52 + )
53 );
54 })
55 )
ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts
+31 -16
@@ -15,12 +15,10 @@
15 * and stored along with the generated TypeScript files. CJS is not supported.
16 */
17
18 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
19 -import path from 'node:path';
20 -import { Command, Options } from '@effect/cli';
21 -import { Effect, Option, pipe, Array } from 'effect';
18 +import { Command, HelpDoc, Options, ValidationError } from '@effect/cli';
19 +import { Array, Data, Effect, Option, pipe } from 'effect';
20 import { Match } from 'effect';
23 -import { FileSystem } from '@effect/platform';
21 +import { FileSystem, Path } from '@effect/platform';
22 import { ComposioToolkitsRepository } from 'src/services/composio-clients';
23 import { logMetrics } from 'src/effects/log-metrics';
24 import { NodeProcess } from 'src/services/node-process';
@@ -42,6 +40,16 @@ import {
40 import { validateToolkitVersionOverrides } from 'src/effects/validate-toolkit-versions';
41 import { TerminalUI, type SpinnerHandle } from 'src/services/terminal-ui';
42
43 +export class TypeScriptGenerationWriteError extends Data.TaggedError(
44 + 'commands/TypeScriptGenerationWriteError'
45 +)<{
46 + readonly cause: unknown;
47 + readonly filePath: string;
48 + readonly message: string;
49 +}> {}
50 +
51 +const invalidGenerateValue = (message: string) => ValidationError.invalidValue(HelpDoc.p(message));
52 +
53 export const outputOpt = Options.optional(
54 Options.directory('output-dir', {
55 exists: 'either',
@@ -112,7 +120,7 @@ function fetchFilteredData(
120 typeTools: boolean,
121 versionOverrides: ToolkitVersionOverrides,
122 spinner: SpinnerHandle
115 -): Effect.Effect<FetchResult, Error, never> {
123 +): Effect.Effect<FetchResult, Error | ValidationError.ValidationError, never> {
124 return Effect.gen(function* () {
125 yield* spinner.message(`Fetching data for ${slugs.length} toolkit(s): ${slugs.join(', ')}...`);
126
@@ -132,7 +140,7 @@ function fetchFilteredData(
140 .pipe(
141 Effect.catchTag('services/InvalidToolkitsError', error =>
142 Effect.fail(
135 - new Error(
143 + invalidGenerateValue(
144 `Invalid toolkit(s): ${error.invalidToolkits.join(', ')}. Toolkit not found.`
145 )
146 )
@@ -227,7 +235,7 @@ function fetchAllDataFastPath(
235 toolkits: allToolkits,
236 triggerTypes: allTriggerTypes,
237 typeableTools: allTypeableTools,
230 - versionMap: new Map() as ToolkitVersionOverrides,
238 + versionMap: new Map<Lowercase<string>, string>(),
239 };
240 });
241 }
@@ -316,13 +324,16 @@ function fetchAllData(
324 /**
325 * Validates that the output directory is not inside node_modules
326 */
319 -function validateOutputDir(outputDir: string): Effect.Effect<string, Error, FileSystem.FileSystem> {
327 +function validateOutputDir(
328 + outputDir: string
329 +): Effect.Effect<string, ValidationError.ValidationError, Path.Path> {
330 return Effect.gen(function* () {
331 + const path = yield* Path.Path;
332 const normalizedPath = path.normalize(outputDir);
333
334 if (normalizedPath.includes('node_modules')) {
335 return yield* Effect.fail(
325 - new Error(
336 + invalidGenerateValue(
337 'Output directory cannot be inside node_modules. Please specify a different directory.'
338 )
339 );
@@ -419,15 +430,19 @@ export function generateTypescriptTypeStubs({
430 yield* pipe(
431 Effect.all(
432 sources.map(([filePath, content]) =>
422 - fs
423 - .writeFileString(filePath, content)
424 - .pipe(
425 - Effect.mapError(error => new Error(`Failed to write file ${filePath}: ${error}`))
433 + fs.writeFileString(filePath, content).pipe(
434 + Effect.mapError(
435 + cause =>
436 + new TypeScriptGenerationWriteError({
437 + cause,
438 + filePath,
439 + message: `Failed to write file ${filePath}`,
440 + })
441 )
442 + )
443 ),
444 { concurrency: 'unbounded' }
429 - ),
430 - Effect.mapError(error => new Error(`Failed to write generated files: ${error}`))
445 + )
446 );
447
448 // Compile TypeScript to JavaScript if needed
ts/packages/cli/src/effect-errors/logic/errors/index.ts
+1
@@ -1,2 +1,3 @@
1 export * from './capture-errors-from-cause';
2 export * from './parse-error';
3 +export * from './span-annotation';
ts/packages/cli/src/effect-errors/logic/errors/parse-error.ts
+2 -6
@@ -1,14 +1,10 @@
1 -import { hasProperty } from 'effect/Predicate';
2 -import type { Span } from 'effect/Tracer';
3 -
1 import { PrettyError } from 'effect-errors/types';
2
3 import { extractErrorDetails } from './extract-error-details';
7 -
8 -const spanSymbol = Symbol.for('effect/SpanAnnotation');
4 +import { extractSpanAnnotation } from './span-annotation';
5
6 export const parseError = (error: unknown): PrettyError => {
11 - const maybeSpan = hasProperty(error, spanSymbol) ? (error[spanSymbol] as Span) : undefined;
7 + const maybeSpan = extractSpanAnnotation(error);
8 const { message, type, isPlainString } = extractErrorDetails(error);
9
10 if (error instanceof Error) {
ts/packages/cli/src/effect-errors/logic/errors/span-annotation.ts new
+27
@@ -0,0 +1,27 @@
1 +import { hasProperty, isString, isTagged } from 'effect/Predicate';
2 +import type { Span } from 'effect/Tracer';
3 +
4 +// Effect v3 internal: `Effect.fail`/`Effect.die` proxy object errors so the
5 +// fiber's current span is readable under this global registry symbol. There is
6 +// no public API for it, and `Symbol.for` succeeds even on Effect versions that
7 +// stop setting it, so keep every read behind this adapter — the canary test in
8 +// test/src/effect-errors/span-annotation.test.ts breaks loudly when an
9 +// `effect` upgrade drops the mechanism.
10 +const spanSymbol = Symbol.for('effect/SpanAnnotation');
11 +
12 +const looksLikeSpan = (value: unknown): value is Span =>
13 + isTagged(value, 'Span') &&
14 + hasProperty(value, 'name') &&
15 + isString(value.name) &&
16 + hasProperty(value, 'status') &&
17 + hasProperty(value, 'attributes') &&
18 + hasProperty(value, 'parent');
19 +
20 +export const extractSpanAnnotation = (error: unknown): Span | undefined => {
21 + if (!hasProperty(error, spanSymbol)) {
22 + return undefined;
23 + }
24 +
25 + const value = error[spanSymbol];
26 + return looksLikeSpan(value) ? value : undefined;
27 +};
ts/packages/cli/src/effects/create-tool-router-session.ts
+43 -21
@@ -1,4 +1,4 @@
1 -import { Effect, Option } from 'effect';
1 +import { Data, Effect, Option } from 'effect';
2 import type { Composio } from '@composio/client';
3 import {
4 createLocalToolRouterExperimentalPayload,
@@ -57,6 +57,20 @@ export interface CreatedToolRouterSession {
57 readonly connectedAccountWordIds?: Record<string, string>;
58 }
59
60 +export class LocalToolRouterDisabledError extends Data.TaggedError(
61 + 'effects/LocalToolRouterDisabledError'
62 +)<{
63 + readonly message: string;
64 + readonly requestedToolkits: ReadonlyArray<string>;
65 +}> {}
66 +
67 +export class ToolRouterSessionCreateError extends Data.TaggedError(
68 + 'effects/ToolRouterSessionCreateError'
69 +)<{
70 + readonly message: string;
71 + readonly cause: unknown;
72 +}> {}
73 +
74 /**
75 * Create an ephemeral Tool Router session for the given user ID.
76 * Returns the session id plus any local-tool custom payload bound to the session.
@@ -91,9 +105,10 @@ export const createToolRouterSessionContext = (
105 requestedToolkits.length === 0 || requestedLocalToolkits.length > 0;
106 if (!localToolsEnabled && requestedLocalToolkits.length > 0) {
107 return yield* Effect.fail(
94 - new Error(
95 - `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before using toolkit filter(s): ${requestedLocalToolkits.join(', ')}.`
96 - )
108 + new LocalToolRouterDisabledError({
109 + message: `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before using toolkit filter(s): ${requestedLocalToolkits.join(', ')}.`,
110 + requestedToolkits: requestedLocalToolkits,
111 + })
112 );
113 }
114 const localExperimentalPayload =
@@ -204,23 +219,30 @@ export const createToolRouterSessionContext = (
219 : {}),
220 };
221
207 - return yield* Effect.tryPromise(() =>
208 - client.toolRouter.session.create({
209 - user_id: userId,
210 - auth_configs: connectionContext.authConfigs,
211 - connected_accounts: connectionContext.connectedAccounts,
212 - manage_connections: { enable: options?.manageConnections ?? false },
213 - multi_account: options?.multiAccount
214 - ? {
215 - enable: options.multiAccount.enable,
216 - max_accounts_per_toolkit: options.multiAccount.maxAccountsPerToolkit,
217 - require_explicit_selection: options.multiAccount.requireExplicitSelection,
218 - }
219 - : undefined,
220 - toolkits: remoteToolkits.length > 0 ? { enable: [...remoteToolkits] } : undefined,
221 - experimental: Object.keys(experimentalPayload).length > 0 ? experimentalPayload : undefined,
222 - })
223 - ).pipe(
222 + return yield* Effect.tryPromise({
223 + try: () =>
224 + client.toolRouter.session.create({
225 + user_id: userId,
226 + auth_configs: connectionContext.authConfigs,
227 + connected_accounts: connectionContext.connectedAccounts,
228 + manage_connections: { enable: options?.manageConnections ?? false },
229 + multi_account: options?.multiAccount
230 + ? {
231 + enable: options.multiAccount.enable,
232 + max_accounts_per_toolkit: options.multiAccount.maxAccountsPerToolkit,
233 + require_explicit_selection: options.multiAccount.requireExplicitSelection,
234 + }
235 + : undefined,
236 + toolkits: remoteToolkits.length > 0 ? { enable: [...remoteToolkits] } : undefined,
237 + experimental:
238 + Object.keys(experimentalPayload).length > 0 ? experimentalPayload : undefined,
239 + }),
240 + catch: cause =>
241 + new ToolRouterSessionCreateError({
242 + message: 'Failed to create a Tool Router session.',
243 + cause,
244 + }),
245 + }).pipe(
246 Effect.map((session): CreatedToolRouterSession => ({
247 sessionId: session.session_id,
248 localExperimentalPayload,
ts/packages/cli/src/effects/from-lazy-json.ts
+2 -1
@@ -11,6 +11,7 @@ import {
11 ConfigProvider,
12 ConfigProviderPathPatch,
13 HashSet,
14 + Predicate,
15 } from 'effect';
16 import { JSONParse, JSONParseError } from 'src/effects/json';
17
@@ -106,7 +107,7 @@ export const configProviderFromLazyJson = (filePath: string) =>
107
108 const pathNotFoundError = ConfigError.MissingData([], `Path ${filePath} not found`);
109 const handlePlatformError = (error: PlatformError.PlatformError) =>
109 - error._tag === 'SystemError' && error.reason === 'NotFound'
110 + Predicate.isTagged(error, 'SystemError') && error.reason === 'NotFound'
111 ? Effect.fail(pathNotFoundError)
112 : Effect.fail(sourceError(error));
113
ts/packages/cli/src/effects/install-skill.ts
+59 -26
@@ -1,4 +1,4 @@
1 -import { Effect, Config, Option } from 'effect';
1 +import { Config, Data, Effect, Option } from 'effect';
2 import { FileSystem, HttpClient, Path } from '@effect/platform';
3 import { NodeOs } from 'src/services/node-os';
4 import { TerminalUI } from 'src/services/terminal-ui';
@@ -6,6 +6,7 @@ import { GITHUB_CONFIG } from 'src/effects/github-config';
6 import { APP_VERSION, type CliReleaseChannel } from 'src/constants';
7 import {
8 fetchLatestCliRelease,
9 + fetchCliReleaseByTag,
10 type GitHubRelease,
11 type GitHubRepoConfig,
12 } from 'src/effects/resolve-cli-release';
@@ -36,6 +37,13 @@ type GitHubConfig = GitHubRepoConfig & {
37 ACCESS_TOKEN: Option.Option<string>;
38 };
39
40 +export class SkillInstallError extends Data.TaggedError('effects/SkillInstallError')<{
41 + readonly cause?: unknown;
42 + readonly message: string;
43 + readonly phase: 'release' | 'download' | 'extract';
44 + readonly status?: number;
45 +}> {}
46 +
47 const hasSkillAsset = (release: GitHubRelease) =>
48 release.assets.some(asset => asset.name === SKILL_ASSET_NAME);
49
@@ -142,44 +150,59 @@ export const installSkill = (options?: {
150 releaseTag: options?.releaseTag,
151 });
152
145 - // Find the skill asset URL from the release
146 - const releaseUrl = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases/tags/${encodeURIComponent(tag)}`;
147 - const releaseResponse = yield* httpClient
148 - .get(releaseUrl)
149 - .pipe(
150 - Effect.catchAll(error => Effect.fail(new Error(`Failed to fetch release ${tag}: ${error}`)))
151 - );
152 -
153 - if (releaseResponse.status < 200 || releaseResponse.status >= 300) {
154 - return yield* Effect.fail(
155 - new Error(`Release ${tag} not found (HTTP ${releaseResponse.status})`)
156 - );
157 - }
158 -
159 - const release = (yield* releaseResponse.json.pipe(
160 - Effect.catchAll(() => Effect.fail(new Error('Failed to parse release JSON')))
161 - )) as { assets: Array<{ name: string; browser_download_url: string }> };
153 + const release = yield* fetchCliReleaseByTag({ githubConfig, httpClient, tag }).pipe(
154 + Effect.mapError(
155 + error =>
156 + new SkillInstallError({
157 + cause: error,
158 + message: error.message,
159 + phase: 'release',
160 + status: error.status,
161 + })
162 + )
163 + );
164
165 const skillAsset = release.assets.find(a => a.name === SKILL_ASSET_NAME);
166 if (!skillAsset) {
167 return yield* Effect.fail(
166 - new Error(`Skill asset ${SKILL_ASSET_NAME} not found in release ${tag}`)
168 + new SkillInstallError({
169 + message: `Skill asset ${SKILL_ASSET_NAME} not found in release ${tag}`,
170 + phase: 'release',
171 + })
172 );
173 }
174
175 // Download the skill zip
171 - const downloadResponse = yield* httpClient
172 - .get(skillAsset.browser_download_url)
173 - .pipe(Effect.catchAll(error => Effect.fail(new Error(`Failed to download skill: ${error}`))));
176 + const downloadResponse = yield* httpClient.get(skillAsset.browser_download_url).pipe(
177 + Effect.mapError(
178 + cause =>
179 + new SkillInstallError({
180 + cause,
181 + message: 'Failed to download skill',
182 + phase: 'download',
183 + })
184 + )
185 + );
186
187 if (downloadResponse.status < 200 || downloadResponse.status >= 300) {
188 return yield* Effect.fail(
177 - new Error(`Failed to download skill (HTTP ${downloadResponse.status})`)
189 + new SkillInstallError({
190 + message: `Failed to download skill (HTTP ${downloadResponse.status})`,
191 + phase: 'download',
192 + status: downloadResponse.status,
193 + })
194 );
195 }
196
197 const zipData = yield* downloadResponse.arrayBuffer.pipe(
182 - Effect.catchAll(() => Effect.fail(new Error('Failed to read skill zip data')))
198 + Effect.mapError(
199 + cause =>
200 + new SkillInstallError({
201 + cause,
202 + message: 'Failed to read skill zip data',
203 + phase: 'download',
204 + })
205 + )
206 );
207
208 // Extract to a temp dir, then move into place
@@ -192,13 +215,23 @@ export const installSkill = (options?: {
215
216 yield* Effect.tryPromise({
217 try: () => extractZip(zipPath, { dir: tmpDir }),
195 - catch: error => new Error(`Failed to extract skill zip: ${error}`),
218 + catch: cause =>
219 + new SkillInstallError({
220 + cause,
221 + message: 'Failed to extract skill zip',
222 + phase: 'extract',
223 + }),
224 });
225
226 // The zip contains composio-cli/ directory
227 const extractedDir = path.join(tmpDir, SKILL_NAME);
228 if (!(yield* fs.exists(extractedDir))) {
201 - return yield* Effect.fail(new Error('Extracted skill directory not found'));
229 + return yield* Effect.fail(
230 + new SkillInstallError({
231 + message: 'Extracted skill directory not found',
232 + phase: 'extract',
233 + })
234 + );
235 }
236
237 yield* Effect.gen(function* () {
ts/packages/cli/src/effects/resolve-optional-text-input.ts
+4 -1
@@ -1,3 +1,4 @@
1 +import { HelpDoc, ValidationError } from '@effect/cli';
2 import { FileSystem } from '@effect/platform';
3 import { Effect, Option } from 'effect';
4
@@ -22,7 +23,9 @@ export const resolveOptionalTextInput = (
23 if (value.startsWith('@')) {
24 const filePath = value.slice(1).trim();
25 if (!filePath) {
25 - return yield* Effect.fail(new Error('Missing file path after "@" in --data'));
26 + return yield* Effect.fail(
27 + ValidationError.invalidValue(HelpDoc.p('Missing file path after "@" in --data'))
28 + );
29 }
30 return yield* fs.readFileString(filePath, 'utf-8');
31 }
ts/packages/cli/src/effects/validate-toolkit-versions.ts
+51 -15
@@ -1,4 +1,4 @@
1 -import { Effect } from 'effect';
1 +import { Data, Effect } from 'effect';
2 import colors from 'picocolors';
3 import { S_BAR, unicodeOr } from '@clack/prompts';
4 import { TerminalUI } from 'src/services/terminal-ui';
@@ -12,13 +12,17 @@ import type { ToolkitVersionOverrides } from './toolkit-version-overrides';
12 * Custom error class for invalid toolkit versions that preserves structured data.
13 * This allows consumers to access both the human-readable message and the machine-readable data.
14 */
15 -export class InvalidToolkitVersionsValidationError extends Error {
15 +export class InvalidToolkitVersionsValidationError extends Data.TaggedError(
16 + 'effects/InvalidToolkitVersionsValidationError'
17 +)<{
18 readonly invalidVersions: ReadonlyArray<InvalidVersionDetail>;
17 -
19 + readonly message: string;
20 +}> {
21 constructor(invalidVersions: ReadonlyArray<InvalidVersionDetail>) {
19 - super(formatInvalidVersionsError(invalidVersions));
20 - this.name = 'InvalidToolkitVersionsValidationError';
21 - this.invalidVersions = invalidVersions;
22 + super({
23 + invalidVersions,
24 + message: formatInvalidVersionsError(invalidVersions),
25 + });
26 }
27
28 /**
@@ -26,12 +30,20 @@ export class InvalidToolkitVersionsValidationError extends Error {
30 */
31 toJSON(): { error: string; invalidVersions: ReadonlyArray<InvalidVersionDetail> } {
32 return {
29 - error: this.name,
33 + error: 'InvalidToolkitVersionsValidationError',
34 invalidVersions: this.invalidVersions,
35 };
36 }
37 }
38
39 +export class ToolkitVersionValidationError extends Data.TaggedError(
40 + 'effects/ToolkitVersionValidationError'
41 +)<{
42 + readonly cause?: unknown;
43 + readonly message: string;
44 + readonly reason: 'invalid-toolkit' | 'request' | 'decode' | 'client-unavailable';
45 +}> {}
46 +
47 const MAX_VERSIONS_TO_SHOW = 5;
48 const S_CORNER_BOTTOM_LEFT = unicodeOr('╰', '+');
49 const S_STEP_ERROR = unicodeOr('▲', 'x');
@@ -141,7 +153,11 @@ export const validateToolkitVersionOverrides = ({
153 versionOverrides,
154 toolkitSlugsFilter,
155 client,
144 -}: ValidateVersionsOptions): Effect.Effect<ValidateVersionsResult, Error, TerminalUI> =>
156 +}: ValidateVersionsOptions): Effect.Effect<
157 + ValidateVersionsResult,
158 + InvalidToolkitVersionsValidationError | ToolkitVersionValidationError,
159 + TerminalUI
160 +> =>
161 Effect.gen(function* () {
162 const ui = yield* TerminalUI;
163
@@ -164,20 +180,40 @@ export const validateToolkitVersionOverrides = ({
180 ),
181 Effect.catchTag('services/InvalidToolkitsError', error =>
182 Effect.fail(
167 - new Error(
168 - `Invalid toolkit(s) in version overrides: ${error.invalidToolkits.join(', ')}. ` +
169 - `Check that the toolkit slug is correct (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL, not COMPOSIO_TOOLKIT_VERSION_GMAL).`
170 - )
183 + new ToolkitVersionValidationError({
184 + cause: error,
185 + message:
186 + `Invalid toolkit(s) in version overrides: ${error.invalidToolkits.join(', ')}. ` +
187 + `Check that the toolkit slug is correct (e.g., COMPOSIO_TOOLKIT_VERSION_GMAIL, not COMPOSIO_TOOLKIT_VERSION_GMAL).`,
188 + reason: 'invalid-toolkit',
189 + })
190 )
191 ),
192 Effect.catchTag('services/HttpServerError', error =>
174 - Effect.fail(new Error(`Failed to validate toolkit versions: ${error.cause}`))
193 + Effect.fail(
194 + new ToolkitVersionValidationError({
195 + cause: error,
196 + message: 'Failed to validate toolkit versions',
197 + reason: 'request',
198 + })
199 + )
200 ),
201 Effect.catchTag('services/HttpDecodingError', error =>
177 - Effect.fail(new Error(`Failed to decode toolkit response: ${error.cause}`))
202 + Effect.fail(
203 + new ToolkitVersionValidationError({
204 + cause: error,
205 + message: 'Failed to decode toolkit response',
206 + reason: 'decode',
207 + })
208 + )
209 ),
210 Effect.catchTag('NoSuchElementException', () =>
180 - Effect.fail(new Error('API client not initialized'))
211 + Effect.fail(
212 + new ToolkitVersionValidationError({
213 + message: 'API client not initialized',
214 + reason: 'client-unavailable',
215 + })
216 + )
217 )
218 );
219
ts/packages/cli/src/models/cli-user-config.ts
+1 -1
@@ -76,7 +76,7 @@ export const CliUserConfig = Schema.Struct({
76 * no behavior change on upgrade).
77 */
78 security: Schema.optionalWith(SecurityBackend, {
79 - default: () => 'auto' as const,
79 + default: (): SecurityBackend => 'auto',
80 }),
81 }).annotations({
82 identifier: 'CliUserConfig',
ts/packages/cli/src/models/utils/json-transform-schema.ts
+6 -3
@@ -1,4 +1,7 @@
1 -import { Schema, ParseResult } from 'effect';
1 +import { ParseResult, Predicate, Schema } from 'effect';
2 +
3 +const errorMessage = (error: unknown): string =>
4 + Predicate.isError(error) ? error.message : String(error);
5
6 export function JSONTransformSchema<To extends Schema.Schema.Any>(to: To) {
7 return Schema.transformOrFail(Schema.String, to, {
@@ -6,12 +9,12 @@ export function JSONTransformSchema<To extends Schema.Schema.Any>(to: To) {
9 encode: (obj, _options, ast) =>
10 ParseResult.try({
11 try: () => JSON.stringify(obj),
9 - catch: e => new ParseResult.Type(ast, obj, (e as Error).message),
12 + catch: error => new ParseResult.Type(ast, obj, errorMessage(error)),
13 }),
14 decode: (str, _options, ast) =>
15 ParseResult.try({
16 try: () => JSON.parse(str),
14 - catch: e => new ParseResult.Type(ast, str, (e as Error).message),
17 + catch: error => new ParseResult.Type(ast, str, errorMessage(error)),
18 }),
19 });
20 }
ts/packages/cli/src/services/cli-user-config.ts
+43 -43
@@ -1,11 +1,10 @@
1 -import { FileSystem } from '@effect/platform';
1 +import { FileSystem, Path } from '@effect/platform';
2 import type { PlatformError } from '@effect/platform/Error';
3 -import { Context, Effect, Layer, Option } from 'effect';
3 +import { Context, Effect, Layer, Option, Predicate, Schema } from 'effect';
4 import type { ParseError } from 'effect/ParseResult';
5 // eslint-disable-next-line no-restricted-imports -- os.homedir feeds resolveCliConfigDirectorySync, which runs from synchronous non-Effect call sites (dev.cmd messages, run-helpers-runtime readFileSync) where the NodeOs service is unavailable
6 import os from 'node:os';
7 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
8 -import path from 'node:path';
7 +import { JsonRecordSchema } from 'src/effects/json';
8 import { setupCacheDir } from 'src/effects/setup-cache-dir';
9 import { getVersion } from 'src/effects/version';
10 import {
@@ -36,11 +35,41 @@ export type CliUserConfigResolved = {
35 const detectReleaseChannel = (version: string): CliReleaseChannel =>
36 /-[0-9A-Za-z.-]+$/.test(version) ? 'beta' : 'stable';
37
38 +const DEFAULT_CLI_USER_CONFIG = CliUserConfig.make({
39 + developer: {
40 + enabled: true,
41 + destructiveActions: false,
42 + },
43 + experimentalFeatures: {},
44 + artifactDirectory: Option.none(),
45 + experimentalSubagent: Option.none(),
46 + security: 'auto',
47 +});
48 +
49 +const decodeConfigJson = Schema.decodeUnknown(Schema.parseJson(JsonRecordSchema));
50 +
51 +// The sync resolvers below run from non-Effect call sites (the
52 +// run-helpers-runtime child process), so the Path service is materialized once
53 +// from its pure default layer instead of being yielded from context.
54 +const syncPath = Effect.runSync(Path.Path.pipe(Effect.provide(Path.layer)));
55 +
56 export const resolveCliConfigDirectorySync = (): string =>
40 - process.env.COMPOSIO_CACHE_DIR?.trim() || path.join(os.homedir(), constants.USER_COMPOSIO_DIR);
57 + process.env.COMPOSIO_CACHE_DIR?.trim() ||
58 + syncPath.join(os.homedir(), constants.USER_COMPOSIO_DIR);
59
60 export const resolveCliConfigPathSync = (): string =>
43 - path.join(resolveCliConfigDirectorySync(), constants.CLI_CONFIG_FILE_NAME);
61 + syncPath.join(resolveCliConfigDirectorySync(), constants.CLI_CONFIG_FILE_NAME);
62 +
63 +/**
64 + * Effect-based resolver for the CLI config file path. Prefer this over
65 + * `resolveCliConfigPathSync` inside Effect-hosted code: it honors the
66 + * COMPOSIO_CACHE_DIR override via `effect/Config` and the NodeOs service.
67 + */
68 +export const resolveCliConfigPath = Effect.gen(function* () {
69 + const path = yield* Path.Path;
70 + const configDir = yield* setupCacheDir;
71 + return path.join(configDir, constants.CLI_CONFIG_FILE_NAME);
72 +});
73
74 export class ComposioCliUserConfig extends Context.Tag('ComposioCliUserConfig')<
75 ComposioCliUserConfig,
@@ -76,30 +105,17 @@ export const ComposioCliUserConfigLive = Layer.effect(
105 const fs = yield* FileSystem.FileSystem;
106 const version = yield* getVersion;
107 const channel = detectReleaseChannel(version);
79 - const configDir = yield* setupCacheDir;
80 - const jsonConfigPath = path.join(configDir, constants.CLI_CONFIG_FILE_NAME);
108 + const jsonConfigPath = yield* resolveCliConfigPath;
109
82 - let rawConfig = CliUserConfig.make({
83 - developer: {
84 - enabled: true,
85 - destructiveActions: false,
86 - },
87 - experimentalFeatures: {},
88 - artifactDirectory: Option.none(),
89 - experimentalSubagent: Option.none(),
90 - security: 'auto',
91 - });
110 + let rawConfig = DEFAULT_CLI_USER_CONFIG;
111
112 const normalizeRawConfigJson = (value: unknown): unknown => {
94 - if (!value || typeof value !== 'object' || Array.isArray(value)) {
113 + if (!Predicate.isRecord(value)) {
114 return value;
115 }
116
98 - const record = { ...(value as Record<string, unknown>) };
99 - const existingDeveloper =
100 - record.developer && typeof record.developer === 'object' && !Array.isArray(record.developer)
101 - ? { ...(record.developer as Record<string, unknown>) }
102 - : {};
117 + const record = { ...value };
118 + const existingDeveloper = Predicate.isRecord(record.developer) ? { ...record.developer } : {};
119
120 if (!('enabled' in existingDeveloper) && 'developer_mode_enabled' in record) {
121 existingDeveloper.enabled = record.developer_mode_enabled;
@@ -137,29 +153,13 @@ export const ComposioCliUserConfigLive = Layer.effect(
153
154 const load = Effect.gen(function* () {
155 const configJson = yield* fs.readFileString(jsonConfigPath, 'utf8');
140 - rawConfig = yield* cliUserConfigFromJSON(
141 - JSON.stringify(normalizeRawConfigJson(JSON.parse(configJson)))
142 - );
156 + const parsed = yield* decodeConfigJson(configJson);
157 + rawConfig = yield* cliUserConfigFromJSON(JSON.stringify(normalizeRawConfigJson(parsed)));
158 return rawConfig;
159 });
160
161 if (yield* fs.exists(jsonConfigPath)) {
147 - yield* load.pipe(
148 - Effect.catchAll(() =>
149 - persist(
150 - CliUserConfig.make({
151 - developer: {
152 - enabled: true,
153 - destructiveActions: false,
154 - },
155 - experimentalFeatures: {},
156 - artifactDirectory: Option.none(),
157 - experimentalSubagent: Option.none(),
158 - security: 'auto',
159 - })
160 - )
161 - )
162 - );
162 + yield* load.pipe(Effect.catchAll(() => persist(DEFAULT_CLI_USER_CONFIG)));
163 } else {
164 yield* persist(rawConfig);
165 }
ts/packages/cli/src/services/command-hints.ts
+7 -3
@@ -1,7 +1,11 @@
1 +import { Record as EffectRecord } from 'effect';
2 +
3 type HintParams = Readonly<Record<string, string | undefined>>;
4
3 -const getParam = (params: HintParams | undefined, key: string, fallback: string) =>
4 - params?.[key]?.trim() ? params[key]! : fallback;
5 +const getParam = (params: HintParams | undefined, key: string, fallback: string) => {
6 + const value = params?.[key];
7 + return value?.trim() ? value : fallback;
8 +};
9
10 export type CommandHintId =
11 | 'root.search'
@@ -120,7 +124,7 @@ export const commandHintLinks = (id: CommandHintId): ReadonlyArray<CommandHintId
124 COMMAND_HINTS[id].links ?? [];
125
126 export const renderCommandHintGraph = () => ({
123 - nodes: (Object.keys(COMMAND_HINTS) as CommandHintId[]).map(id => ({
127 + nodes: EffectRecord.toEntries(COMMAND_HINTS).map(([id]) => ({
128 id,
129 example: commandHintExample(id),
130 links: [...commandHintLinks(id)],
ts/packages/cli/src/services/command-project.ts
+11 -25
@@ -1,4 +1,4 @@
1 -import { Data, Effect, Option } from 'effect';
1 +import { Data, Effect, Option, Predicate } from 'effect';
2 import { ProjectContext } from './project-context';
3 import { ComposioUserContext } from './user-context';
4 import {
@@ -6,8 +6,6 @@ import {
6 findDeveloperProjectByName,
7 DeveloperProjectNotFoundError,
8 AmbiguousDeveloperProjectNameError,
9 - type HttpDecodingError,
10 - type HttpServerError,
9 } from './composio-clients';
10
11 export type ProjectMode = 'consumer' | 'developer';
@@ -15,10 +13,7 @@ export type ProjectMode = 'consumer' | 'developer';
13 export type CliProjectType = 'CONSUMER' | 'DEVELOPER';
14
15 export type CliProjectResolutionSource =
18 - | 'consumer-default'
19 - | 'developer-project-name'
20 - | 'developer-local-config'
21 - | 'developer-explicit';
16 + 'consumer-default' | 'developer-project-name' | 'developer-local-config' | 'developer-explicit';
17
18 export interface ResolvedCommandProject {
19 readonly orgId: string;
@@ -29,13 +24,11 @@ export interface ResolvedCommandProject {
24 readonly source: CliProjectResolutionSource;
25 }
26
32 -export class MissingDefaultOrgError extends Data.TaggedError(
33 - 'services/MissingDefaultOrgError'
34 -)<{}> {}
27 +export class MissingDefaultOrgError extends Data.TaggedError('services/MissingDefaultOrgError') {}
28
29 export class MissingDeveloperProjectError extends Data.TaggedError(
30 'services/MissingDeveloperProjectError'
38 -)<{}> {}
31 +) {}
32
33 const requireDefaultOrg = (orgId: Option.Option<string>) =>
34 Option.match(orgId, {
@@ -117,15 +110,7 @@ export const resolveCommandProject = (params: { mode: ProjectMode; projectName?:
110 projectType: 'DEVELOPER',
111 source: 'developer-local-config',
112 } satisfies ResolvedCommandProject;
120 - }) as Effect.Effect<
121 - ResolvedCommandProject,
122 - | MissingDefaultOrgError
123 - | MissingDeveloperProjectError
124 - | DeveloperProjectNotFoundError
125 - | AmbiguousDeveloperProjectNameError
126 - | HttpServerError
127 - | HttpDecodingError
128 - >;
113 + });
114
115 export const formatResolveCommandProjectError = (error: unknown): Error => {
116 if (error instanceof MissingDefaultOrgError) {
@@ -148,11 +133,12 @@ export const formatResolveCommandProjectError = (error: unknown): Error => {
133 `Developer project name "${error.projectName}" is ambiguous in org "${error.orgId}". Use an exact unique project name.`
134 );
135 }
151 - if (typeof error === 'object' && error && 'details' in error) {
152 - const details = (error as { details?: { message?: string } }).details;
153 - if (details?.message) {
154 - return new Error(details.message);
155 - }
136 + if (
137 + Predicate.hasProperty(error, 'details') &&
138 + Predicate.hasProperty(error.details, 'message') &&
139 + Predicate.isString(error.details.message)
140 + ) {
141 + return new Error(error.details.message);
142 }
143 if (error instanceof Error) {
144 return error;
ts/packages/cli/src/services/composio-clients.ts
+30 -58
@@ -32,15 +32,16 @@ import {
32 type ToolkitVersionSpec,
33 type ToolkitVersionOverrides,
34 } from 'src/effects/toolkit-version-overrides';
35 +import { JsonRecordSchema } from 'src/effects/json';
36 import { Session, RetrievedSession } from 'src/models/session';
37 import { TriggerType, TriggerTypes, TriggerTypesAsEnums } from 'src/models/trigger-types';
38 import * as constants from 'src/constants';
39 import { getCurrentCwdSessionId } from 'src/analytics/dispatch';
40 import { ComposioUserContext, ComposioUserContextLive } from './user-context';
40 -import { NodeOs } from './node-os';
41 import { ProjectContext } from './project-context';
42 import type { NoSuchElementException } from 'effect/Cause';
43 import { renderPrettyError } from './utils/pretty-error';
44 +import { NodeOs } from './node-os';
45
46 /**
47 * Error types
@@ -99,6 +100,16 @@ export class HttpDecodingError extends Data.TaggedError('services/HttpDecodingEr
100
101 export type HttpError = HttpServerError | HttpDecodingError;
102
103 +// Sort items by slug.
104 +// TODO: make sure this happens on the server-side.
105 +const sortBySlug = <T extends { readonly slug: string }>(
106 + items: ReadonlyArray<T>
107 +): ReadonlyArray<T> =>
108 + Array.sort(
109 + items,
110 + Order.mapInput(Order.string, (item: T) => item.slug)
111 + );
112 +
113 const validateToolkitVersionsImpl = (
114 client: {
115 toolkits: {
@@ -293,8 +304,8 @@ export const ToolDetailedResponse = Schema.Struct({
304 description: Schema.String,
305 tags: Schema.Array(Schema.String),
306 available_versions: Schema.Array(Schema.String),
296 - input_parameters: Schema.Record({ key: Schema.String, value: Schema.Unknown }),
297 - output_parameters: Schema.Record({ key: Schema.String, value: Schema.Unknown }),
307 + input_parameters: JsonRecordSchema,
308 + output_parameters: JsonRecordSchema,
309 no_auth: Schema.optionalWith(Schema.Boolean, { default: () => false }),
310 toolkit: Schema.optionalWith(
311 Schema.Struct({
@@ -1365,8 +1376,7 @@ const buildDefaultHeaders = (params: {
1376 };
1377
1378 // Utility function for calling the Composio API and decoding its response.
1368 -// eslint-disable-next-line @typescript-eslint/no-explicit-any
1369 -const callClient = <T, S extends Schema.Schema<any, any>>(
1379 +const callClient = <T, S extends Schema.Schema.AnyNoContext>(
1380 clientSingleton: ComposioClientSingleton,
1381 apiCall: (client: _RawComposioClient) => APIPromise<T>,
1382 responseSchema: S
@@ -1407,17 +1417,16 @@ const callClient = <T, S extends Schema.Schema<any, any>>(
1417 return { metrics, data: typedJson };
1418 });
1419
1410 -// Schema constraint for paginated responses
1411 -type PaginatedSchema = Schema.Schema<
1412 - {
1413 - // eslint-disable-next-line @typescript-eslint/no-explicit-any
1414 - items: ReadonlyArray<any>;
1415 - next_cursor: string | null;
1416 - total_pages: number;
1417 - },
1418 - // eslint-disable-next-line @typescript-eslint/no-explicit-any
1419 - any
1420 ->;
1420 +// Schema constraint for paginated responses: the decoded page must expose the
1421 +// pagination envelope, expressed through the schema's `Type` phantom property so
1422 +// concrete item types stay free of `any`.
1423 +type PaginatedSchema = Schema.Schema.AnyNoContext & {
1424 + readonly Type: {
1425 + readonly items: ReadonlyArray<unknown>;
1426 + readonly next_cursor: string | null;
1427 + readonly total_pages: number;
1428 + };
1429 +};
1430
1431 // Maximum items per page allowed by the server
1432 const MAX_PAGE_SIZE = 1000;
@@ -2071,14 +2080,7 @@ export class ComposioToolkitsRepository extends Effect.Service<ComposioToolkitsR
2080 const getToolkits = () =>
2081 client.toolkits.list().pipe(
2082 Effect.map(response => response.items),
2074 - Effect.flatMap(
2075 - Effect.fn(function* (toolkits) {
2076 - // Sort apps by slug.
2077 - // TODO: make sure this happens on the server-side.
2078 - const orderBySlug = Order.mapInput(Order.string, (app: Toolkit) => app.slug);
2079 - return Array.sort(toolkits, orderBySlug) as ReadonlyArray<Toolkit>;
2080 - })
2081 - )
2083 + Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>)
2084 );
2085
2086 /**
@@ -2107,16 +2109,7 @@ export class ComposioToolkitsRepository extends Effect.Service<ComposioToolkitsR
2109 )
2110 ),
2111 { concurrency: MAX_CONCURRENT_REQUESTS_PER_ENDPOINT }
2110 - ).pipe(
2111 - Effect.flatMap(
2112 - Effect.fn(function* (toolkits) {
2113 - // Sort apps by slug.
2114 - // TODO: make sure this happens on the server-side.
2115 - const orderBySlug = Order.mapInput(Order.string, (app: Toolkit) => app.slug);
2116 - return Array.sort(toolkits, orderBySlug) as ReadonlyArray<Toolkit>;
2117 - })
2118 - )
2119 - );
2112 + ).pipe(Effect.map(items => sortBySlug(items) as ReadonlyArray<Toolkit>));
2113
2114 return {
2115 getToolkits,
@@ -2131,14 +2124,7 @@ export class ComposioToolkitsRepository extends Effect.Service<ComposioToolkitsR
2124 getTools: (toolkitSlugs?: ReadonlyArray<string>) =>
2125 client.tools.list(toolkitSlugs ?? []).pipe(
2126 Effect.map(response => response.items),
2134 - Effect.flatMap(
2135 - Effect.fn(function* (tools) {
2136 - // Sort apps by slug.
2137 - // TODO: make sure this happens on the server-side.
2138 - const orderBySlug = Order.mapInput(Order.string, (app: Tool) => app.slug);
2139 - return Array.sort(tools, orderBySlug) as ReadonlyArray<Tool>;
2140 - })
2141 - )
2127 + Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)
2128 ),
2129 /**
2130 * Fetches tools with per-toolkit version support.
@@ -2148,14 +2134,7 @@ export class ComposioToolkitsRepository extends Effect.Service<ComposioToolkitsR
2134 getToolsByVersionSpecs: (specs: ReadonlyArray<ToolkitVersionSpec>) =>
2135 client.tools.listByVersionSpecs(specs).pipe(
2136 Effect.map(response => response.items),
2151 - Effect.flatMap(
2152 - Effect.fn(function* (tools) {
2153 - // Sort apps by slug.
2154 - // TODO: make sure this happens on the server-side.
2155 - const orderBySlug = Order.mapInput(Order.string, (app: Tool) => app.slug);
2156 - return Array.sort(tools, orderBySlug) as ReadonlyArray<Tool>;
2157 - })
2158 - )
2137 + Effect.map(items => sortBySlug(items) as ReadonlyArray<Tool>)
2138 ),
2139 getTriggerTypesAsEnums: () => client.triggersTypes.retrieveEnum(),
2140 /**
@@ -2171,14 +2150,7 @@ export class ComposioToolkitsRepository extends Effect.Service<ComposioToolkitsR
2150 getTriggerTypes: (toolkitSlugs?: ReadonlyArray<string>) =>
2151 client.triggersTypes.list(toolkitSlugs).pipe(
2152 Effect.map(response => response.items),
2174 - Effect.flatMap(
2175 - Effect.fn(function* (triggerTypes) {
2176 - // Sort apps by slug.
2177 - // TODO: make sure this happens on the server-side.
2178 - const orderBySlug = Order.mapInput(Order.string, (app: TriggerType) => app.slug);
2179 - return Array.sort(triggerTypes, orderBySlug) as ReadonlyArray<TriggerType>;
2180 - })
2181 - )
2153 + Effect.map(items => sortBySlug(items) as ReadonlyArray<TriggerType>)
2154 ),
2155 /**
2156 * Validates that the given toolkit slugs are valid by comparing them against the list
ts/packages/cli/src/services/composio-error-overrides.ts
+18 -16
@@ -1,9 +1,11 @@
1 +import { Predicate } from 'effect';
2 import {
3 extractApiErrorDetails,
4 extractMessage,
5 extractSlug,
6 type ApiErrorDetails,
7 } from 'src/utils/api-error-extraction';
8 +import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
9
10 const NO_CONNECTION_SLUGS: ReadonlySet<string> = new Set([
11 'ActionExecute_ConnectedAccountNotFound',
@@ -14,22 +16,22 @@ const extractNestedDetails = (value: unknown): unknown => {
16 let current: unknown = value;
17 const seen = new Set<unknown>();
18
17 - while (current && typeof current === 'object' && !seen.has(current)) {
19 + while (Predicate.isObject(current) && !seen.has(current)) {
20 seen.add(current);
21
20 - if ('details' in current) {
21 - const details = (current as { details?: unknown }).details;
22 + if (Predicate.hasProperty(current, 'details')) {
23 + const details = current.details;
24 if (details !== undefined) {
25 return details;
26 }
27 }
28
27 - if ('error' in current) {
28 - current = (current as { error?: unknown }).error;
29 + if (Predicate.hasProperty(current, 'error')) {
30 + current = current.error;
31 continue;
32 }
31 - if ('cause' in current) {
32 - current = (current as { cause?: unknown }).cause;
33 + if (Predicate.hasProperty(current, 'cause')) {
34 + current = current.cause;
35 continue;
36 }
37 break;
@@ -42,19 +44,19 @@ export const normalizeCliError = (error: unknown): unknown => {
44 let current: unknown = error;
45 const seen = new Set<unknown>();
46
45 - while (current && typeof current === 'object' && !seen.has(current)) {
47 + while (Predicate.isObject(current) && !seen.has(current)) {
48 seen.add(current);
49
50 if (current instanceof Error) {
51 return current;
52 }
53
52 - if ('error' in current) {
53 - current = (current as { error?: unknown }).error;
54 + if (Predicate.hasProperty(current, 'error')) {
55 + current = current.error;
56 continue;
57 }
56 - if ('cause' in current) {
57 - current = (current as { cause?: unknown }).cause;
58 + if (Predicate.hasProperty(current, 'cause')) {
59 + current = current.cause;
60 continue;
61 }
62 break;
@@ -78,10 +80,10 @@ export const buildNoActiveConnectionMessage = (params: {
80 return `No active connection found for toolkit "${params.toolkit}". Run \`composio link ${params.toolkit}\`, then retry.`;
81 }
82 if (params.toolSlug) {
81 - const idx = params.toolSlug.indexOf('_');
82 - const toolkit =
83 - idx <= 0 ? params.toolSlug.toLowerCase() : params.toolSlug.slice(0, idx).toLowerCase();
84 - if (toolkit !== 'composio') {
83 + // `toolkitFromToolSlug` returns the whole slug lowercased when there is no
84 + // underscore, so keep the explicit 'composio' guard for the bare-slug case.
85 + const toolkit = toolkitFromToolSlug(params.toolSlug);
86 + if (toolkit && toolkit !== 'composio') {
87 return `No active connection found for toolkit "${toolkit}". Run \`composio link ${toolkit}\`, then retry.`;
88 }
89 }
ts/packages/cli/src/services/connected-account-selection.ts
+4 -4
@@ -20,15 +20,15 @@ export type CachedConnectedAccountSummary = typeof CachedConnectedAccountSummary
20
21 const normalizeSelector = (value: string): string => value.trim().toLowerCase();
22
23 -const parseTimestamp = (value: string | undefined): number => {
23 +const parseTimestamp = (value: string | null | undefined): number => {
24 if (!value) return 0;
25 const parsed = Date.parse(value);
26 return Number.isFinite(parsed) ? parsed : 0;
27 };
28
29 -const compareNewestFirst = (
30 - left: Pick<ConnectedAccountItem, 'updated_at' | 'created_at'>,
31 - right: Pick<ConnectedAccountItem, 'updated_at' | 'created_at'>
29 +export const compareNewestFirst = (
30 + left: { readonly updated_at?: string | null; readonly created_at?: string | null },
31 + right: { readonly updated_at?: string | null; readonly created_at?: string | null }
32 ): number =>
33 Math.max(parseTimestamp(right.updated_at), parseTimestamp(right.created_at)) -
34 Math.max(parseTimestamp(left.updated_at), parseTimestamp(left.created_at));
ts/packages/cli/src/services/consumer-short-term-cache.ts
+42 -69
@@ -1,6 +1,7 @@
1 import { FileSystem, Path } from '@effect/platform';
2 import { Effect, Option, Record as EffectRecord, Schema } from 'effect';
3 import { APP_CONFIG } from 'src/effects/app-config';
4 +import { JsonRecordSchema } from 'src/effects/json';
5 import { setupCacheDir } from 'src/effects/setup-cache-dir';
6 import { NodeProcess } from 'src/services/node-process';
7 import {
@@ -10,6 +11,8 @@ import {
11 resolveConsumerProject,
12 } from 'src/services/composio-clients';
13 import { resolveCommandProject } from 'src/services/command-project';
14 +import { collectDecodedEntries } from 'src/utils/collect-decoded-entries';
15 +import { djb2Hash } from 'src/utils/djb2';
16 import { resolveToolRouterSessionConnections } from 'src/services/tool-router-session-connections';
17 import { ComposioUserContext } from 'src/services/user-context';
18 import {
@@ -45,15 +48,14 @@ const CacheEntrySchema = Schema.Struct({
48 })
49 ),
50 });
51 +
52 export type ConsumerToolRouterAuthConfigMappings =
53 typeof ConsumerToolRouterAuthConfigMappingsSchema.Type;
54 export type ConsumerToolRouterConnectedAccountMappings =
55 typeof ConsumerToolRouterConnectedAccountMappingsSchema.Type;
56 type CacheEntry = typeof CacheEntrySchema.Type;
57 type CacheState = { readonly [key: string]: CacheEntry };
54 -const decodeCacheShell = Schema.decodeUnknownOption(
55 - Schema.parseJson(Schema.Record({ key: Schema.String, value: Schema.Unknown }))
56 -);
58 +const decodeCacheShell = Schema.decodeUnknownOption(Schema.parseJson(JsonRecordSchema));
59 const decodeCacheEntry = Schema.decodeUnknownOption(CacheEntrySchema);
60
61 // Per-entry decode: one stale or version-skewed entry (e.g. written by a
@@ -62,15 +64,7 @@ const decodeCacheEntry = Schema.decodeUnknownOption(CacheEntrySchema);
64 export const decodeCacheStateTolerant = (raw: string): CacheState =>
65 Option.match(decodeCacheShell(raw), {
66 onNone: (): CacheState => ({}),
65 - onSome: shell =>
66 - Object.fromEntries(
67 - Object.entries(shell).flatMap(([key, value]) =>
68 - Option.match(decodeCacheEntry(value), {
69 - onNone: () => [],
70 - onSome: entry => [[key, entry] as const],
71 - })
72 - )
73 - ),
67 + onSome: shell => collectDecodedEntries(shell, decodeCacheEntry),
68 });
69
70 const cacheKey = (orgId: string, consumerUserId: string) => `${orgId}:${consumerUserId}`;
@@ -81,13 +75,7 @@ const cachePath = Effect.gen(function* () {
75 return path.join(cacheDir, CACHE_FILE);
76 });
77
84 -const cwdHash = (cwd: string): string => {
85 - let hash = 5381;
86 - for (let i = 0; i < cwd.length; i += 1) {
87 - hash = (hash * 33) ^ cwd.charCodeAt(i);
88 - }
89 - return Math.abs(hash >>> 0).toString(36);
90 -};
78 +const cwdHash = (cwd: string): string => djb2Hash(cwd).toString(36);
79
80 const createProbablyMyCliSessionId = (cwd: string): string => {
81 const random = crypto.randomUUID().replace(/-/g, '').slice(0, 10);
@@ -146,9 +134,10 @@ const writeCache = (state: CacheState) =>
134 Effect.gen(function* () {
135 const fs = yield* FileSystem.FileSystem;
136 const cacheDir = yield* setupCacheDir;
137 + const filePath = yield* cachePath;
138 yield* fs.makeDirectory(cacheDir, { recursive: true }).pipe(Effect.catchAll(() => Effect.void));
139 yield* fs
151 - .writeFileString(yield* cachePath, JSON.stringify(state, null, 2))
140 + .writeFileString(filePath, JSON.stringify(state, null, 2))
141 .pipe(Effect.catchAll(() => Effect.void));
142 });
143
@@ -268,48 +257,43 @@ const mergeConnectedAccountMappings = (params: {
257 });
258 };
259
271 -export const getFreshConsumerConnectedToolkitsFromCache = (params: {
272 - orgId: string;
273 - consumerUserId: string;
274 -}) =>
260 +// Shared prefix of every getFresh*FromCache accessor: bail to Option.none()
261 +// when the cache is disabled, the entry is missing, or its TTL has passed.
262 +const getFreshCacheEntry = (params: { orgId: string; consumerUserId: string }) =>
263 Effect.gen(function* () {
264 const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;
265 if (disabled) {
278 - return Option.none<ReadonlyArray<string>>();
266 + return Option.none<CacheEntry>();
267 }
268 const state = yield* readCache();
269 const entry = state[cacheKey(params.orgId, params.consumerUserId)];
270 if (!entry) {
283 - return Option.none<ReadonlyArray<string>>();
271 + return Option.none<CacheEntry>();
272 }
273 const expiresAtMs = Date.parse(entry.expiresAt);
274 if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) {
287 - return Option.none<ReadonlyArray<string>>();
275 + return Option.none<CacheEntry>();
276 }
289 - return Option.some(entry.toolkits);
277 + return Option.some(entry);
278 });
279
280 +export const getFreshConsumerConnectedToolkitsFromCache = (params: {
281 + orgId: string;
282 + consumerUserId: string;
283 +}) => getFreshCacheEntry(params).pipe(Effect.map(Option.map(entry => entry.toolkits)));
284 +
285 export const getFreshConsumerToolRouterAuthConfigsFromCache = (params: {
286 orgId: string;
287 consumerUserId: string;
288 toolkits?: ReadonlyArray<string>;
289 }) =>
290 Effect.gen(function* () {
298 - const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;
299 - if (disabled) {
300 - return Option.none<ConsumerToolRouterAuthConfigMappings>();
301 - }
302 - const state = yield* readCache();
303 - const entry = state[cacheKey(params.orgId, params.consumerUserId)];
304 - if (!entry) {
305 - return Option.none<ConsumerToolRouterAuthConfigMappings>();
306 - }
307 - const expiresAtMs = Date.parse(entry.expiresAt);
308 - if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) {
291 + const entry = yield* getFreshCacheEntry(params);
292 + if (Option.isNone(entry)) {
293 return Option.none<ConsumerToolRouterAuthConfigMappings>();
294 }
295
312 - const mappings = normalizeAuthConfigMappings(entry.toolRouterAuthConfigs);
296 + const mappings = normalizeAuthConfigMappings(entry.value.toolRouterAuthConfigs);
297 if (!mappings) {
298 return Option.none<ConsumerToolRouterAuthConfigMappings>();
299 }
@@ -339,21 +323,12 @@ export const getFreshConsumerToolRouterConnectedAccountsFromCache = (params: {
323 toolkits?: ReadonlyArray<string>;
324 }) =>
325 Effect.gen(function* () {
342 - const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;
343 - if (disabled) {
344 - return Option.none<ConsumerToolRouterConnectedAccountMappings>();
345 - }
346 - const state = yield* readCache();
347 - const entry = state[cacheKey(params.orgId, params.consumerUserId)];
348 - if (!entry) {
349 - return Option.none<ConsumerToolRouterConnectedAccountMappings>();
350 - }
351 - const expiresAtMs = Date.parse(entry.expiresAt);
352 - if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) {
326 + const entry = yield* getFreshCacheEntry(params);
327 + if (Option.isNone(entry)) {
328 return Option.none<ConsumerToolRouterConnectedAccountMappings>();
329 }
330
356 - const mappings = normalizeConnectedAccountMappings(entry.toolRouterConnectedAccounts);
331 + const mappings = normalizeConnectedAccountMappings(entry.value.toolRouterConnectedAccounts);
332 if (!mappings) {
333 return Option.none<ConsumerToolRouterConnectedAccountMappings>();
334 }
@@ -363,25 +338,23 @@ export const getFreshConsumerToolRouterConnectedAccountsFromCache = (params: {
338 }
339
340 const requestedToolkits = params.toolkits.map(toolkit => toolkit.toLowerCase());
366 - const filteredConnectedAccounts = requestedToolkits.reduce<Record<string, string>>(
367 - (acc, toolkit) => {
341 + const filteredConnectedAccounts = EffectRecord.fromEntries(
342 + requestedToolkits.flatMap(toolkit => {
343 const connectedAccountId = mappings.connectedAccounts?.[toolkit];
369 - if (typeof connectedAccountId === 'string') {
370 - acc[toolkit] = connectedAccountId;
371 - }
372 - return acc;
373 - },
374 - {}
344 + return typeof connectedAccountId === 'string'
345 + ? [[toolkit, connectedAccountId] as const]
346 + : [];
347 + })
348 + );
349 + const filteredAvailableConnectedAccounts: Record<
350 + string,
351 + ReadonlyArray<CachedConnectedAccountSummary>
352 + > = EffectRecord.fromEntries(
353 + requestedToolkits.flatMap(toolkit => {
354 + const accounts = mappings.availableConnectedAccounts?.[toolkit];
355 + return Array.isArray(accounts) && accounts.length > 0 ? [[toolkit, accounts] as const] : [];
356 + })
357 );
376 - const filteredAvailableConnectedAccounts = requestedToolkits.reduce<
377 - Record<string, ReadonlyArray<CachedConnectedAccountSummary>>
378 - >((acc, toolkit) => {
379 - const accounts = mappings.availableConnectedAccounts?.[toolkit];
380 - if (Array.isArray(accounts) && accounts.length > 0) {
381 - acc[toolkit] = accounts;
382 - }
383 - return acc;
384 - }, {});
358 const filtered = normalizeConnectedAccountMappings({
359 connectedAccounts: filteredConnectedAccounts,
360 availableConnectedAccounts: filteredAvailableConnectedAccounts,
ts/packages/cli/src/services/env-lang-detector.ts deleted
-213
@@ -1,213 +0,0 @@
1 -import { BunFileSystem } from '@effect/platform-bun';
2 -import { pipe, Data, Effect } from 'effect';
3 -import { FileSystem } from '@effect/platform';
4 -
5 -export class EnvLangDetectorError extends Data.TaggedError('services/DetectEnvLangError')<{
6 - readonly cause: Error;
7 - readonly message: string;
8 -}> {}
9 -
10 -// Service that attempts to detect the language of the project in the current working directory.
11 -export class EnvLangDetector extends Effect.Service<EnvLangDetector>()('services/EnvLangDetector', {
12 - effect: Effect.gen(function* () {
13 - const fs = yield* FileSystem.FileSystem;
14 -
15 - return {
16 - detectEnvLanguage: (
17 - cwd: string
18 - ): Effect.Effect<'TypeScript' | 'Python', EnvLangDetectorError, never> =>
19 - Effect.gen(function* () {
20 - const files = yield* pipe(
21 - fs.readDirectory(cwd),
22 - Effect.catchAll(e =>
23 - Effect.fail(
24 - new EnvLangDetectorError({ cause: e, message: `Failed to read directory ${cwd}` })
25 - )
26 - )
27 - );
28 -
29 - // Convert to lowercase for case-insensitive comparison
30 - const fileNames = files.map(f => f.toLowerCase());
31 - yield* Effect.logDebug(`Files in directory ${cwd}:\n${fileNames.join('\n')}`);
32 -
33 - // TypeScript project indicators (in order of precedence)
34 - const typescriptIndicators = [
35 - 'tsconfig.json',
36 - 'package.json',
37 - 'yarn.lock',
38 - 'package-lock.json',
39 - 'pnpm-lock.yaml',
40 - 'bun.lockb',
41 - 'deno.json',
42 - 'deno.jsonc',
43 - ];
44 -
45 - // Python project indicators (in order of precedence)
46 - const pythonIndicators = [
47 - 'pyproject.toml',
48 - 'setup.py',
49 - 'requirements.txt',
50 - 'pipfile',
51 - 'pipfile.lock',
52 - 'poetry.lock',
53 - 'conda.yaml',
54 - 'environment.yml',
55 - 'setup.cfg',
56 - 'tox.ini',
57 - 'pytest.ini',
58 - '__pycache__',
59 - ];
60 -
61 - // Check for TypeScript indicators first
62 - const hasTypescriptIndicator = typescriptIndicators.some(indicator =>
63 - fileNames.includes(indicator)
64 - );
65 -
66 - // Check for Python indicators
67 - const hasPythonIndicator = pythonIndicators.some(indicator =>
68 - fileNames.includes(indicator)
69 - );
70 -
71 - yield* Effect.logDebug(`TypeScript indicators found: ${hasTypescriptIndicator}`);
72 - yield* Effect.logDebug(`Python indicators found: ${hasPythonIndicator}`);
73 -
74 - // Additional checks for file extensions if no clear indicators found
75 - if (!hasTypescriptIndicator && !hasPythonIndicator) {
76 - // Get actual file names (not lowercase) for extension checking
77 - const hasTypeScriptFiles = files.some(
78 - file => file.endsWith('.ts') || file.endsWith('.tsx') || file.endsWith('.mts')
79 - );
80 -
81 - const hasPythonFiles = files.some(
82 - file =>
83 - file.endsWith('.py') ||
84 - file.endsWith('.pyw') ||
85 - file.endsWith('.pyi') ||
86 - file.endsWith('.pyx')
87 - );
88 -
89 - if (hasTypeScriptFiles && !hasPythonFiles) {
90 - return 'TypeScript' as const;
91 - }
92 -
93 - if (hasPythonFiles && !hasTypeScriptFiles) {
94 - return 'Python' as const;
95 - }
96 -
97 - // If both or neither are found, check for more files by reading subdirectories
98 - // This is a more exhaustive check
99 - const allFiles: string[] = [];
100 -
101 - // Don't recurse into common directories that might contain false positives
102 - const skipDirs = [
103 - '.composio',
104 - 'node_modules',
105 - '.git',
106 - '__pycache__',
107 - '.venv',
108 - 'venv',
109 - 'env',
110 - 'dist',
111 - 'build',
112 - ];
113 -
114 - // Recursively collect files from immediate subdirectories
115 - yield* Effect.logInfo('Checking subdirectories for more files...');
116 -
117 - for (const item of files) {
118 - const itemPath = `${cwd}/${item}`;
119 - const stat = yield* pipe(
120 - fs.stat(cwd),
121 - Effect.catchAll(e =>
122 - Effect.fail(
123 - new EnvLangDetectorError({
124 - cause: e,
125 - message: `Failed to read file ${itemPath}`,
126 - })
127 - )
128 - )
129 - );
130 -
131 - if (stat.type === 'Directory') {
132 - if (!skipDirs.includes(item.toLowerCase())) {
133 - const subFiles = yield* pipe(
134 - fs.readDirectory(item),
135 - Effect.catchAll(e =>
136 - Effect.fail(
137 - new EnvLangDetectorError({
138 - cause: e,
139 - message: `Failed to read directory ${item}`,
140 - })
141 - )
142 - )
143 - );
144 - allFiles.push(...subFiles);
145 - }
146 - }
147 - }
148 -
149 - const allFileNames = [...files, ...allFiles];
150 -
151 - const deepTsFiles = allFileNames.filter(
152 - file => file.endsWith('.ts') || file.endsWith('.tsx') || file.endsWith('.mts')
153 - ).length;
154 -
155 - const deepPyFiles = allFileNames.filter(
156 - file =>
157 - file.endsWith('.py') ||
158 - file.endsWith('.pyw') ||
159 - file.endsWith('.pyi') ||
160 - file.endsWith('.pyx')
161 - ).length;
162 -
163 - // Decide based on which has more files
164 - if (deepTsFiles > deepPyFiles && deepTsFiles > 0) {
165 - return 'TypeScript' as const;
166 - }
167 -
168 - if (deepPyFiles > deepTsFiles && deepPyFiles > 0) {
169 - return 'Python' as const;
170 - }
171 - }
172 -
173 - // Prioritize based on strength of indicators
174 - if (hasTypescriptIndicator && hasPythonIndicator) {
175 - // Both present - prioritize based on most definitive files
176 - const strongTsIndicators = ['tsconfig.json', 'package.json'];
177 - const strongPyIndicators = ['pyproject.toml', 'setup.py'];
178 -
179 - const hasStrongTs = strongTsIndicators.some(indicator => fileNames.includes(indicator));
180 - const hasStrongPy = strongPyIndicators.some(indicator => fileNames.includes(indicator));
181 -
182 - if (hasStrongTs && !hasStrongPy) {
183 - return 'TypeScript' as const;
184 - }
185 - if (hasStrongPy && !hasStrongTs) {
186 - return 'Python' as const;
187 - }
188 -
189 - // If both have strong indicators, default to TypeScript
190 - // (this is arbitrary but package.json is very common)
191 - return 'TypeScript' as const;
192 - }
193 -
194 - if (hasTypescriptIndicator) {
195 - return 'TypeScript' as const;
196 - }
197 -
198 - if (hasPythonIndicator) {
199 - return 'Python' as const;
200 - }
201 -
202 - // No clear indicators found
203 - return yield* Effect.fail(
204 - new EnvLangDetectorError({
205 - cause: new Error('Unable to detect project language'),
206 - message: `Could not determine if directory '${cwd}' contains a Python or TypeScript project. No recognizable project files or patterns found.`,
207 - })
208 - );
209 - }),
210 - };
211 - }),
212 - dependencies: [BunFileSystem.layer],
213 -}) {}
ts/packages/cli/src/services/run-companion-modules.ts
-92
@@ -645,95 +645,3 @@ export const resolveRunCompanionModulePath = ({
645 : path.resolve(currentDirectory, `${baseName}.mjs`)
646 );
647 });
648 -
649 -// ── Temporary sync bridges ──────────────────────────────────────────────
650 -//
651 -// The callers below still run outside the Effect runtime and are migrated
652 -// wholesale by the typed-error slice (PR 8 of this stack), which deletes this
653 -// whole section: update-check.ts and run-subagent-acp.ts. Do not add new
654 -// callers.
655 -
656 -// eslint-disable-next-line no-restricted-imports -- temporary sync bridge for pre-migration callers, removed with the typed-error slice (PR 8 of this stack)
657 -import * as fsSync from 'node:fs';
658 -// eslint-disable-next-line no-restricted-imports -- temporary sync bridge for pre-migration callers, removed with the typed-error slice (PR 8 of this stack)
659 -import * as pathSync from 'node:path';
660 -
661 -const readTextFileIfPresentSync = (filePath: string) => {
662 - if (!fsSync.existsSync(filePath)) {
663 - return undefined;
664 - }
665 -
666 - const value = fsSync.readFileSync(filePath, 'utf8').trim();
667 - return value.length > 0 ? value : undefined;
668 -};
669 -
670 -export const resolveInstalledCliVersionSync = (execPath: string, fallbackVersion: string): string =>
671 - normalizeCliReleaseVersion(
672 - readTextFileIfPresentSync(
673 - pathSync.join(pathSync.dirname(execPath), RUN_COMPANION_RELEASE_TAG_FILENAME)
674 - ) ?? fallbackVersion
675 - );
676 -
677 -export const resolveRunCompanionAssetPathSync = ({
678 - callerImportMetaUrl,
679 - execPath,
680 - relativePathFromRoot,
681 -}: {
682 - callerImportMetaUrl: string;
683 - execPath: string;
684 - relativePathFromRoot: string;
685 -}): string | null => {
686 - const currentFilePath = fileURLToPath(callerImportMetaUrl);
687 - const currentDirectory = pathSync.dirname(currentFilePath);
688 - const executableDirectory = pathSync.dirname(execPath);
689 -
690 - const candidates = [
691 - pathSync.resolve(currentDirectory, relativePathFromRoot),
692 - pathSync.resolve(currentDirectory, '..', relativePathFromRoot),
693 - pathSync.resolve(executableDirectory, relativePathFromRoot),
694 - ];
695 -
696 - for (const candidate of candidates) {
697 - if (fsSync.existsSync(candidate)) {
698 - return candidate;
699 - }
700 - }
701 -
702 - return null;
703 -};
704 -
705 -export const resolveRunCompanionModulePathSync = ({
706 - callerImportMetaUrl,
707 - execPath,
708 - relativeNoExtensionFromCaller,
709 -}: {
710 - callerImportMetaUrl: string;
711 - execPath: string;
712 - relativeNoExtensionFromCaller: string;
713 -}): string => {
714 - const currentFilePath = fileURLToPath(callerImportMetaUrl);
715 - const currentDirectory = pathSync.dirname(currentFilePath);
716 - const executableDirectory = pathSync.dirname(execPath);
717 - const baseName = pathSync.basename(relativeNoExtensionFromCaller);
718 -
719 - const candidates = [
720 - pathSync.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.ts`),
721 - pathSync.resolve(currentDirectory, `${relativeNoExtensionFromCaller}.js`),
722 - pathSync.resolve(currentDirectory, 'services', `${baseName}.mjs`),
723 - pathSync.resolve(currentDirectory, 'services', `${baseName}.js`),
724 - pathSync.resolve(currentDirectory, `${baseName}.mjs`),
725 - pathSync.resolve(currentDirectory, `${baseName}.js`),
726 - pathSync.resolve(executableDirectory, `${baseName}.mjs`),
727 - pathSync.resolve(executableDirectory, `${baseName}.js`),
728 - ];
729 -
730 - for (const candidate of candidates) {
731 - if (fsSync.existsSync(candidate)) {
732 - return candidate;
733 - }
734 - }
735 -
736 - return currentFilePath.startsWith('/$bunfs/')
737 - ? pathSync.resolve(executableDirectory, `${baseName}.mjs`)
738 - : pathSync.resolve(currentDirectory, `${baseName}.mjs`);
739 -};
ts/packages/cli/src/services/run-helpers-runtime.ts
+606 -524
@@ -1,16 +1,25 @@
1 +// This module is preloaded into the user's spawned child process, where no Effect
2 +// runtime or @effect/platform layers are provided, so it uses sync Node builtins.
3 // eslint-disable-next-line no-restricted-imports -- sync fs for run-log appends, run-file writes, and CLI config reads in the child process, outside the Effect runtime
4 import * as fs from 'node:fs';
5 // eslint-disable-next-line no-restricted-imports -- os.tmpdir() locates the fallback run-files directory in the child process, outside the Effect runtime
6 import * as os from 'node:os';
5 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
6 -import * as path from 'node:path';
7 import process from 'node:process';
8 +import { Path } from '@effect/platform';
9 +import { Effect, Predicate, Schema } from 'effect';
10 import { z } from 'zod';
11 +import { JsonRecordSchema } from 'src/effects/json';
12 import { resolveCliConfigPathSync } from 'src/services/cli-user-config';
10 -import type { MasterKind } from 'src/services/master-detector';
11 -import { isAcpInvokeError } from 'src/services/run-subagent-shared';
13 +import { detectMaster, type MasterKind } from 'src/services/master-detector';
14 +import {
15 + isAcpInvokeError,
16 + parseJson,
17 + type HelperDebugLog,
18 + type InvokeAgentNormalizedOptions,
19 +} from 'src/services/run-subagent-shared';
20 import { invokeAcpSubAgent } from 'src/services/run-subagent-acp';
21 import { invokeLegacySubAgent } from 'src/services/run-subagent-legacy';
22 +import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';
23
24 export type RunHelperContext = {
25 readonly apiKey?: string;
@@ -41,59 +50,25 @@ type RunHelpersInstallParams = {
50 readonly helperContext?: RunHelperContext;
51 };
52
44 -type RunCliResult =
45 - | undefined
46 - | string
47 - | number
48 - | boolean
49 - | {
50 - readonly successful?: boolean;
51 - readonly storedInFile?: boolean;
52 - readonly outputFilePath?: string | null;
53 - readonly tokenCount?: number | null;
54 - readonly error?: string | null;
55 - readonly data?: unknown;
56 - readonly [key: string]: unknown;
57 - };
53 +type RunCliResult = unknown;
54
59 -type PromptableResult = {
60 - readonly prompt?: () => string;
61 - readonly data?: unknown;
62 - readonly [key: string]: unknown;
63 -};
64 -
65 -type StructuredSchemaInput =
66 - | {
67 - readonly safeParse?: (value: unknown) => unknown;
68 - readonly _def?: unknown;
69 - }
70 - | Record<string, unknown>;
71 -
72 -type NormalizedInvokeAgentOptions = {
73 - readonly target?: string;
74 - readonly model?: string;
75 - readonly schema?: StructuredSchemaInput;
76 - readonly jsonSchema?: Record<string, unknown>;
77 - readonly structuredSchema?: Record<string, unknown>;
78 - readonly zodSchema?: StructuredSchemaInput;
79 -};
80 -
81 -type RunGlobalScope = typeof globalThis & {
82 - z: typeof z;
83 - zod: typeof z;
84 - search: (query: string, options?: Record<string, unknown>) => Promise<RunCliResult>;
85 - execute: (slug: string, data?: unknown, options?: { account?: string }) => Promise<RunCliResult>;
86 - experimental_subAgent: (prompt: string, options?: Record<string, unknown>) => Promise<unknown>;
87 - invokeAgent: (prompt: string, options?: Record<string, unknown>) => Promise<unknown>;
88 - proxy: (
89 - toolkit: string
90 - ) => Promise<(input: string | URL, init?: RequestInit) => Promise<Response>>;
91 - __composioRunContext: {
92 - readonly outputDir: string | null;
93 - readonly logFilePath: string | null;
94 - };
95 - __composioConsumerContext: RunHelperContext;
96 -};
55 +const JsonObject = JsonRecordSchema;
56 +const ExperimentalSubagentConfig = Schema.Struct({
57 + experimental_subagent: Schema.optional(
58 + Schema.Struct({ target: Schema.optional(Schema.Unknown) })
59 + ),
60 +});
61 +const decodeExperimentalSubagentConfig = Schema.decodeUnknownSync(
62 + Schema.parseJson(ExperimentalSubagentConfig)
63 +);
64 +const ProxySessionResponse = Schema.Struct({ session_id: Schema.NonEmptyString });
65 +const ProxyExecuteResponse = Schema.Struct({
66 + headers: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.String })),
67 + binary_data: Schema.optional(Schema.Struct({ url: Schema.optional(Schema.String) })),
68 + data: Schema.optional(Schema.Unknown),
69 + status: Schema.optional(Schema.Number),
70 +});
71 +type ProxyExecuteResponse = Schema.Schema.Type<typeof ProxyExecuteResponse>;
72
73 const experimentalSubAgentSchema = {
74 type: 'function',
@@ -135,7 +110,7 @@ const experimentalSubAgentSchema = {
110 logFilePath: { description: 'Path to the local run log file for helper execution details.' },
111 },
112 },
138 -} as const;
113 +};
114
115 const proxySchema = {
116 type: 'function',
@@ -165,9 +140,7 @@ const proxySchema = {
140 },
141 },
142 },
168 -} as const;
169 -
170 -const runGlobals = globalThis as RunGlobalScope;
143 +};
144
145 const encodeBase64 = (bytes: Uint8Array): string => {
146 let binary = '';
@@ -177,141 +150,337 @@ const encodeBase64 = (bytes: Uint8Array): string => {
150 return btoa(binary);
151 };
152
180 -// eslint-disable-next-line max-lines-per-function
181 -export const installRunHelpers = async ({
182 - cliPrefix,
183 - helperContext = {},
184 -}: RunHelpersInstallParams): Promise<void> => {
185 - runGlobals.z = z;
186 - runGlobals.zod = z;
153 +// ---------------------------------------------------------------------------
154 +// Pure helpers — no run-context captures, hoisted to module scope
155 +// ---------------------------------------------------------------------------
156
188 - const perfDebugEnabled =
189 - helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === '1';
190 - const toolDebugEnabled =
191 - helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === '1';
192 - const perfDebugStart = Date.now();
193 - let perfDebugSeq = 0;
194 - const executeId = () => crypto.randomUUID().slice(0, 8);
195 - const proxySessionCache = new Map<string, string>();
196 - const composioBaseURL = (helperContext.baseURL || 'https://backend.composio.dev').replace(
197 - /\/$/,
198 - ''
199 - );
200 - const sharedRunOutputDir =
201 - typeof helperContext.runOutputDir === 'string' && helperContext.runOutputDir.length > 0
202 - ? helperContext.runOutputDir
203 - : null;
204 - const sharedRunLogFilePath =
205 - typeof helperContext.runLogFilePath === 'string' && helperContext.runLogFilePath.length > 0
206 - ? helperContext.runLogFilePath
207 - : null;
157 +const executeId = () => crypto.randomUUID().slice(0, 8);
158
209 - const appendRunLogLine = (line: string) => {
210 - if (!sharedRunLogFilePath || line.length === 0) return;
211 - fs.appendFileSync(sharedRunLogFilePath, `${line}\n`, 'utf8');
212 - };
159 +const truncateDebugText = (value: unknown, max = 240) => {
160 + const text = typeof value === 'string' ? value : String(value ?? '');
161 + return text.length > max ? `${text.slice(0, max - 1)}…` : text;
162 +};
163
214 - const perfDebugLog = (phase: string, label: string, details: Record<string, unknown> = {}) => {
215 - if (!perfDebugEnabled) return;
216 - const elapsedMs = Date.now() - perfDebugStart;
217 - const payload = { phase, label, elapsedMs, ...details };
218 - // eslint-disable-next-line no-console
219 - console.error(`[perf] ${JSON.stringify(payload)}`);
164 +const previewDebugValue = (value: unknown): string => {
165 + if (value == null) return '';
166 + if (typeof value === 'string') return truncateDebugText(value.replace(/\s+/g, ' ').trim());
167 + if (typeof value === 'number' || typeof value === 'boolean') return String(value);
168 + if (Array.isArray(value)) return `array(${value.length})`;
169 + if (Predicate.isRecord(value)) {
170 + const preferred = ['message', 'error', 'title', 'summary', 'brief', 'status'];
171 + for (const key of preferred) {
172 + const candidate = value[key];
173 + if (typeof candidate === 'string' && candidate.trim().length > 0) {
174 + return truncateDebugText(candidate.trim());
175 + }
176 + }
177 + return `object{${Object.keys(value).slice(0, 4).join(', ')}}`;
178 + }
179 + return truncateDebugText(String(value));
180 +};
181 +
182 +const formatHelperDebugEvent = (step: string, details: Record<string, unknown> = {}) => {
183 + switch (step) {
184 + case 'subAgent.target':
185 + return `[experimental_subAgent] triggered with ${details.resolvedTarget}`;
186 + case 'subAgent.acp.resolve':
187 + return `[experimental_subAgent] ACP via ${details.source} (${details.target})`;
188 + case 'subAgent.acp.initialized':
189 + return `[experimental_subAgent] ACP initialized (${details.target})`;
190 + case 'subAgent.acp.session':
191 + return `[experimental_subAgent] session ready (${details.target})`;
192 + case 'subAgent.acp.model':
193 + return details.applied === true
194 + ? `[experimental_subAgent] model=${details.model}`
195 + : `[experimental_subAgent] model unchanged (${details.model})`;
196 + case 'subAgent.acp.message': {
197 + const text = previewDebugValue(details.text);
198 + return text ? `[experimental_subAgent] ${text}` : null;
199 + }
200 + case 'subAgent.acp.thought': {
201 + const text = previewDebugValue(details.text);
202 + return text ? `[experimental_subAgent:thinking] ${text}` : null;
203 + }
204 + case 'subAgent.acp.tool_call': {
205 + const locations = Array.isArray(details.locations) ? details.locations : [];
206 + const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';
207 + return `[experimental_subAgent:tool] ${details.status || 'pending'} ${
208 + details.title || details.kind || 'tool'
209 + }${where}`;
210 + }
211 + case 'subAgent.acp.tool_call_update': {
212 + const locations = Array.isArray(details.locations) ? details.locations : [];
213 + const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';
214 + const preview = previewDebugValue(details.rawOutput);
215 + return `[experimental_subAgent:tool] ${details.status || 'update'} ${
216 + details.title || details.toolCallId || details.kind || 'tool'
217 + }${where}${preview ? ` -> ${preview}` : ''}`;
218 + }
219 + case 'subAgent.acp.plan': {
220 + const entries = Array.isArray(details.entries)
221 + ? details.entries.filter(Predicate.isRecord)
222 + : [];
223 + if (entries.length === 0) return '[experimental_subAgent:plan] updated';
224 + const summary = entries
225 + .slice(0, 3)
226 + .map(entry => {
227 + const status = typeof entry.status === 'string' ? entry.status : 'pending';
228 + const content = typeof entry.content === 'string' ? entry.content : '';
229 + return `${status}:${truncateDebugText(content, 48)}`;
230 + })
231 + .join(' | ');
232 + return `[experimental_subAgent:plan] ${summary}`;
233 + }
234 + case 'subAgent.acp.fallback':
235 + return `[experimental_subAgent] ACP fallback (${details.code})`;
236 + case 'execute.prepare':
237 + return `[execute] ${details.slug}`;
238 + case 'search.prepare':
239 + return `[search] ${truncateDebugText(details.query || '', 96)}`;
240 + case 'proxy.request':
241 + return `[proxy] ${details.method} ${truncateDebugText(details.endpoint || '', 96)}`;
242 + case 'cli.result': {
243 + const command = typeof details.command === 'string' ? details.command : 'cli';
244 + const state = details.successful === false ? 'failed' : 'ok';
245 + const preview = previewDebugValue(details.preview);
246 + return `[${command}] ${state}${preview ? ` ${preview}` : ''}`;
247 + }
248 + case 'cli.error': {
249 + const command = typeof details.command === 'string' ? details.command : 'cli';
250 + const stderr = previewDebugValue(details.stderr);
251 + return `[${command}] failed${stderr ? ` ${stderr}` : ''}`;
252 + }
253 + default:
254 + return null;
255 + }
256 +};
257 +
258 +const stringifyForPrompt = (value: unknown): string => {
259 + if (value === undefined) return 'undefined';
260 + if (value === null) return 'null';
261 + if (typeof value === 'string') return value;
262 + if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
263 + return String(value);
264 + }
265 + try {
266 + return JSON.stringify(value, null, 2);
267 + } catch {
268 + return String(value);
269 + }
270 +};
271 +
272 +const attachPromptMethod = <T>(value: T): T => {
273 + if (!Predicate.isRecord(value)) return value;
274 + if (typeof value.prompt === 'function') return value;
275 + Object.defineProperty(value, 'prompt', {
276 + value: () => stringifyForPrompt('data' in value ? value.data : value),
277 + enumerable: false,
278 + });
279 + return value;
280 +};
281 +
282 +const isPlainObjectForExecute = Predicate.isRecord;
283 +
284 +const runFileExtensionFromMimeType = (mimeType: string | undefined): string => {
285 + if (typeof mimeType !== 'string' || mimeType.trim().length === 0) return 'bin';
286 + const normalized = mimeType.split(';')[0]?.trim().toLowerCase() ?? '';
287 + const explicit: Record<string, string> = {
288 + 'text/plain': 'txt',
289 + 'application/json': 'json',
290 + 'application/pdf': 'pdf',
291 + 'image/jpeg': 'jpg',
292 + 'image/png': 'png',
293 + 'image/webp': 'webp',
294 + 'image/gif': 'gif',
295 };
296 + if (explicit[normalized]) return explicit[normalized];
297 + const subtype = normalized.split('/')[1] || 'bin';
298 + return subtype.includes('+') ? (subtype.split('+').pop() ?? 'bin') : subtype;
299 +};
300
222 - const truncateDebugText = (value: unknown, max = 240) => {
223 - const text = typeof value === 'string' ? value : String(value ?? '');
224 - return text.length > max ? `${text.slice(0, max - 1)}…` : text;
301 +const describeDebugValue = (value: unknown) => {
302 + if (Array.isArray(value)) return { type: 'array', length: value.length };
303 + if (Predicate.isRecord(value)) {
304 + return { type: 'object', keys: Object.keys(value).slice(0, 20) };
305 + }
306 + return {
307 + type: typeof value,
308 + value: typeof value === 'string' ? value.slice(0, 200) : (value ?? null),
309 };
310 +};
311
227 - const previewDebugValue = (value: unknown): string => {
228 - if (value == null) return '';
229 - if (typeof value === 'string') return truncateDebugText(value.replace(/\s+/g, ' ').trim());
230 - if (typeof value === 'number' || typeof value === 'boolean') return String(value);
231 - if (Array.isArray(value)) return `array(${value.length})`;
232 - if (typeof value === 'object') {
233 - const record = value as Record<string, unknown>;
234 - const preferred = ['message', 'error', 'title', 'summary', 'brief', 'status'];
235 - for (const key of preferred) {
236 - if (typeof record[key] === 'string' && record[key].trim().length > 0) {
237 - return truncateDebugText(record[key].trim());
238 - }
312 +const summarizeCliResultPreview = (result: RunCliResult): unknown => {
313 + if (!Predicate.isRecord(result)) return result;
314 + if ('data' in result && result.data !== undefined) return result.data;
315 + if (typeof result.error === 'string' && result.error.trim().length > 0)
316 + return result.error.trim();
317 + return result;
318 +};
319 +
320 +const readConfiguredExperimentalSubagentTarget = (): 'auto' | 'claude' | 'codex' => {
321 + try {
322 + const raw = fs.readFileSync(resolveCliConfigPathSync(), 'utf8');
323 + const parsed = decodeExperimentalSubagentConfig(raw);
324 + const target = parsed.experimental_subagent?.target;
325 + return target === 'claude' || target === 'codex' || target === 'auto' ? target : 'auto';
326 + } catch {
327 + return 'auto';
328 + }
329 +};
330 +
331 +const normalizeInvokeAgentOptions = (
332 + options: Record<string, unknown> = {}
333 +): InvokeAgentNormalizedOptions => {
334 + if (options == null || typeof options !== 'object' || Array.isArray(options)) {
335 + throw new Error('experimental_subAgent() options must be an object when provided.');
336 + }
337 + if (options.schema !== undefined && options.jsonSchema !== undefined) {
338 + throw new Error(
339 + 'experimental_subAgent() accepts either options.schema or options.jsonSchema, not both.'
340 + );
341 + }
342 + const requestedTarget = options.target;
343 + if (
344 + requestedTarget !== undefined &&
345 + requestedTarget !== 'claude' &&
346 + requestedTarget !== 'codex' &&
347 + requestedTarget !== 'user'
348 + ) {
349 + throw new Error(
350 + 'experimental_subAgent() target must be "claude", "codex", or "user" when provided.'
351 + );
352 + }
353 + const inputSchema = options.schema ?? options.jsonSchema;
354 + let structuredSchema: Record<string, unknown> | undefined;
355 + let zodSchema: z.ZodType | undefined;
356 + if (inputSchema !== undefined) {
357 + if (inputSchema instanceof z.ZodType) {
358 + if (typeof z.toJSONSchema !== 'function') {
359 + throw new Error(
360 + 'experimental_subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.'
361 + );
362 }
240 - return `object{${Object.keys(record).slice(0, 4).join(', ')}}`;
363 + zodSchema = inputSchema;
364 + const generatedSchema = z.toJSONSchema(inputSchema);
365 + structuredSchema = Schema.decodeUnknownSync(JsonObject)(generatedSchema);
366 + } else if (Predicate.isRecord(inputSchema)) {
367 + structuredSchema = inputSchema;
368 + } else {
369 + throw new Error('experimental_subAgent() schema must be a Zod schema or JSON Schema object.');
370 }
242 - return truncateDebugText(String(value));
371 + }
372 + return {
373 + ...(requestedTarget === undefined ? {} : { target: requestedTarget }),
374 + ...(typeof options.model === 'string' ? { model: options.model } : {}),
375 + ...(options.schema === undefined ? {} : { schema: options.schema }),
376 + ...(options.jsonSchema === undefined ? {} : { jsonSchema: options.jsonSchema }),
377 + ...(structuredSchema === undefined ? {} : { structuredSchema }),
378 + ...(zodSchema === undefined ? {} : { zodSchema }),
379 };
380 +};
381
245 - const formatHelperDebugEvent = (step: string, details: Record<string, unknown> = {}) => {
246 - switch (step) {
247 - case 'subAgent.target':
248 - return `[experimental_subAgent] triggered with ${details.resolvedTarget}`;
249 - case 'subAgent.acp.resolve':
250 - return `[experimental_subAgent] ACP via ${details.source} (${details.target})`;
251 - case 'subAgent.acp.initialized':
252 - return `[experimental_subAgent] ACP initialized (${details.target})`;
253 - case 'subAgent.acp.session':
254 - return `[experimental_subAgent] session ready (${details.target})`;
255 - case 'subAgent.acp.model':
256 - return details.applied === true
257 - ? `[experimental_subAgent] model=${details.model}`
258 - : `[experimental_subAgent] model unchanged (${details.model})`;
259 - case 'subAgent.acp.message': {
260 - const text = previewDebugValue(details.text);
261 - return text ? `[experimental_subAgent] ${text}` : null;
262 - }
263 - case 'subAgent.acp.thought': {
264 - const text = previewDebugValue(details.text);
265 - return text ? `[experimental_subAgent:thinking] ${text}` : null;
266 - }
267 - case 'subAgent.acp.tool_call': {
268 - const locations = Array.isArray(details.locations) ? details.locations : [];
269 - const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';
270 - return `[experimental_subAgent:tool] ${details.status || 'pending'} ${
271 - details.title || details.kind || 'tool'
272 - }${where}`;
273 - }
274 - case 'subAgent.acp.tool_call_update': {
275 - const locations = Array.isArray(details.locations) ? details.locations : [];
276 - const where = locations.length > 0 ? ` ${locations.slice(0, 2).join(', ')}` : '';
277 - const preview = previewDebugValue(details.rawOutput);
278 - return `[experimental_subAgent:tool] ${details.status || 'update'} ${
279 - details.title || details.toolCallId || details.kind || 'tool'
280 - }${where}${preview ? ` -> ${preview}` : ''}`;
281 - }
282 - case 'subAgent.acp.plan': {
283 - const entries = Array.isArray(details.entries)
284 - ? (details.entries as Array<{ status?: string; content?: string }>)
285 - : [];
286 - if (entries.length === 0) return '[experimental_subAgent:plan] updated';
287 - const summary = entries
288 - .slice(0, 3)
289 - .map(entry => `${entry.status}:${truncateDebugText(entry.content || '', 48)}`)
290 - .join(' | ');
291 - return `[experimental_subAgent:plan] ${summary}`;
292 - }
293 - case 'subAgent.acp.fallback':
294 - return `[experimental_subAgent] ACP fallback (${details.code})`;
295 - case 'execute.prepare':
296 - return `[execute] ${details.slug}`;
297 - case 'search.prepare':
298 - return `[search] ${truncateDebugText(details.query || '', 96)}`;
299 - case 'proxy.request':
300 - return `[proxy] ${details.method} ${truncateDebugText(details.endpoint || '', 96)}`;
301 - case 'cli.result': {
302 - const command = typeof details.command === 'string' ? details.command : 'cli';
303 - const state = details.successful === false ? 'failed' : 'ok';
304 - const preview = previewDebugValue(details.preview);
305 - return `[${command}] ${state}${preview ? ` ${preview}` : ''}`;
306 - }
307 - case 'cli.error': {
308 - const command = typeof details.command === 'string' ? details.command : 'cli';
309 - const stderr = previewDebugValue(details.stderr);
310 - return `[${command}] failed${stderr ? ` ${stderr}` : ''}`;
311 - }
312 - default:
313 - return null;
314 - }
382 +const normalizeProxyToolkit = (toolkit: string) => {
383 + if (typeof toolkit !== 'string' || toolkit.trim().length === 0) {
384 + throw new Error('proxy() requires a non-empty toolkit string.');
385 + }
386 + return toolkit.trim();
387 +};
388 +
389 +const normalizeFetchHeaders = (headers: HeadersInit | undefined) => {
390 + if (!headers) return [];
391 + const normalized: Array<{ name: string; type: string; value: string }> = [];
392 + new Headers(headers).forEach((value, name) => {
393 + normalized.push({ name, type: 'header', value });
394 + });
395 + return normalized;
396 +};
397 +
398 +const normalizeFetchBody = async (body: unknown) => {
399 + if (body === undefined || body === null) return undefined;
400 + if (typeof body === 'string' || typeof body === 'number' || typeof body === 'boolean')
401 + return body;
402 + if (typeof Blob !== 'undefined' && body instanceof Blob) return await body.text();
403 + if (body instanceof ArrayBuffer) return encodeBase64(new Uint8Array(body));
404 + if (ArrayBuffer.isView(body)) {
405 + return encodeBase64(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
406 + }
407 + return body;
408 +};
409 +
410 +const normalizeFetchInput = async (input: unknown, init: RequestInit = {}) => {
411 + if (typeof Request !== 'undefined' && input instanceof Request) {
412 + throw new Error(
413 + 'proxy() does not support passing a Request instance yet. Pass a URL string and init instead.'
414 + );
415 + }
416 + const endpoint = input instanceof URL ? input.toString() : input;
417 + if (typeof endpoint !== 'string' || endpoint.trim().length === 0) {
418 + throw new Error('proxy fetch requires a non-empty URL string or URL object.');
419 + }
420 + const method = typeof init.method === 'string' ? init.method.toUpperCase() : 'GET';
421 + if (!['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].includes(method)) {
422 + throw new Error('proxy fetch only supports GET, POST, PUT, DELETE, PATCH.');
423 + }
424 + return {
425 + endpoint: endpoint.trim(),
426 + method,
427 + parameters: normalizeFetchHeaders(init.headers),
428 + body: await normalizeFetchBody(init.body),
429 + };
430 +};
431 +
432 +const toProxyResponse = async (result: ProxyExecuteResponse) => {
433 + const headers = new Headers(result?.headers || {});
434 + if (result?.binary_data?.url) {
435 + const binaryResponse = await fetch(result.binary_data.url);
436 + binaryResponse.headers.forEach((value, key) => {
437 + if (!headers.has(key)) headers.set(key, value);
438 + });
439 + return new Response(binaryResponse.body, {
440 + status: result.status ?? binaryResponse.status,
441 + headers,
442 + });
443 + }
444 + if (result?.data === undefined || result?.data === null) {
445 + return new Response(null, { status: result?.status ?? 200, headers });
446 + }
447 + if (typeof result.data === 'string') {
448 + if (!headers.has('content-type')) headers.set('content-type', 'text/plain; charset=utf-8');
449 + return new Response(result.data, { status: result.status ?? 200, headers });
450 + }
451 + if (!headers.has('content-type')) headers.set('content-type', 'application/json; charset=utf-8');
452 + return new Response(JSON.stringify(result.data), { status: result.status ?? 200, headers });
453 +};
454 +
455 +// ---------------------------------------------------------------------------
456 +// Helper factories — capture the per-run context passed by installRunHelpers
457 +// ---------------------------------------------------------------------------
458 +
459 +type RunHelperLoggers = {
460 + readonly perfDebugLog: (phase: string, label: string, details?: Record<string, unknown>) => void;
461 + readonly helperDebugLog: HelperDebugLog;
462 +};
463 +
464 +const createRunHelperLoggers = (params: {
465 + readonly helperContext: RunHelperContext;
466 + readonly writeError: (line: string) => void;
467 + readonly sharedRunLogFilePath: string | null;
468 + readonly perfDebugEnabled: boolean;
469 + readonly perfDebugStart: number;
470 +}): RunHelperLoggers => {
471 + const { helperContext, writeError, sharedRunLogFilePath, perfDebugEnabled, perfDebugStart } =
472 + params;
473 +
474 + const appendRunLogLine = (line: string) => {
475 + if (!sharedRunLogFilePath || line.length === 0) return;
476 + fs.appendFileSync(sharedRunLogFilePath, `${line}\n`, 'utf8');
477 + };
478 +
479 + const perfDebugLog = (phase: string, label: string, details: Record<string, unknown> = {}) => {
480 + if (!perfDebugEnabled) return;
481 + const elapsedMs = Date.now() - perfDebugStart;
482 + const payload = { phase, label, elapsedMs, ...details };
483 + writeError(`[perf] ${JSON.stringify(payload)}`);
484 };
485
486 const shouldStreamHelperLog = (step: string, formattedLine: string | null): boolean => {
@@ -320,71 +489,24 @@ export const installRunHelpers = async ({
489 return formattedLine !== null && (step.startsWith('subAgent.') || step.startsWith('agent.'));
490 };
491
323 - const helperDebugLog = (step: string, details: Record<string, unknown> = {}) => {
492 + const helperDebugLog: HelperDebugLog = (step, details = {}) => {
493 const formattedLine = formatHelperDebugEvent(step, details);
494 const elapsedMs = Date.now() - perfDebugStart;
495 const line = formattedLine ?? `[run:debug] ${JSON.stringify({ step, elapsedMs, ...details })}`;
496 appendRunLogLine(line);
497 if (shouldStreamHelperLog(step, formattedLine)) {
329 - // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)
330 - process.stderr.write(`${line}\n`);
331 - }
332 - };
333 -
334 - const parseJson = (text: string): unknown => {
335 - const value = text.trim();
336 - if (!value) return undefined;
337 - try {
338 - return JSON.parse(value);
339 - } catch {
340 - return value;
341 - }
342 - };
343 -
344 - const stringifyForPrompt = (value: unknown): string => {
345 - if (value === undefined) return 'undefined';
346 - if (value === null) return 'null';
347 - if (typeof value === 'string') return value;
348 - if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
349 - return String(value);
350 - }
351 - try {
352 - return JSON.stringify(value, null, 2);
353 - } catch {
354 - return String(value);
498 + writeError(line);
499 }
500 };
501
358 - const attachPromptMethod = <T>(value: T): T => {
359 - if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
360 - const promptable = value as PromptableResult;
361 - if (typeof promptable.prompt === 'function') return value;
362 - Object.defineProperty(promptable, 'prompt', {
363 - value: () => stringifyForPrompt('data' in promptable ? promptable.data : promptable),
364 - enumerable: false,
365 - });
366 - return value;
367 - };
502 + return { perfDebugLog, helperDebugLog };
503 +};
504
369 - const isPlainObjectForExecute = (value: unknown): value is Record<string, unknown> =>
370 - typeof value === 'object' && value !== null && !Array.isArray(value);
371 -
372 - const runFileExtensionFromMimeType = (mimeType: string | undefined): string => {
373 - if (typeof mimeType !== 'string' || mimeType.trim().length === 0) return 'bin';
374 - const normalized = mimeType.split(';')[0]?.trim().toLowerCase() ?? '';
375 - const explicit: Record<string, string> = {
376 - 'text/plain': 'txt',
377 - 'application/json': 'json',
378 - 'application/pdf': 'pdf',
379 - 'image/jpeg': 'jpg',
380 - 'image/png': 'png',
381 - 'image/webp': 'webp',
382 - 'image/gif': 'gif',
383 - };
384 - if (explicit[normalized]) return explicit[normalized];
385 - const subtype = normalized.split('/')[1] || 'bin';
386 - return subtype.includes('+') ? (subtype.split('+').pop() ?? 'bin') : subtype;
387 - };
505 +const createExecutePayloadMaterializer = (params: {
506 + readonly path: Path.Path;
507 + readonly sharedRunOutputDir: string | null;
508 +}): ((value: unknown) => Promise<unknown>) => {
509 + const { path, sharedRunOutputDir } = params;
510
511 const writeTempExecuteFile = async (value: unknown): Promise<unknown> => {
512 const outputDir = sharedRunOutputDir || path.join(os.tmpdir(), 'composio-run-files');
@@ -427,8 +549,24 @@ export const installRunHelpers = async ({
549 return value;
550 };
551
552 + return materializeExecutePayload;
553 +};
554 +
555 +const createCliRunner = (params: {
556 + readonly cliPrefix: ReadonlyArray<string>;
557 + readonly helperContext: RunHelperContext;
558 + readonly sharedRunOutputDir: string | null;
559 + readonly perfDebugEnabled: boolean;
560 + readonly toolDebugEnabled: boolean;
561 + readonly loggers: RunHelperLoggers;
562 +}): ((args: ReadonlyArray<string>) => Promise<RunCliResult>) => {
563 + const { cliPrefix, helperContext, sharedRunOutputDir, perfDebugEnabled, toolDebugEnabled } =
564 + params;
565 + const { perfDebugLog, helperDebugLog } = params.loggers;
566 + let perfDebugSeq = 0;
567 +
568 const maybeLoadStoredCliResult = (result: RunCliResult): RunCliResult => {
431 - if (!result || typeof result !== 'object' || result.storedInFile !== true) {
569 + if (!Predicate.isRecord(result) || result.storedInFile !== true) {
570 return attachPromptMethod(result);
571 }
572 helperDebugLog('cli.result.stored_in_file', {
@@ -445,31 +583,12 @@ export const installRunHelpers = async ({
583 });
584 };
585
448 - const describeDebugValue = (value: unknown) => {
449 - if (Array.isArray(value)) return { type: 'array', length: value.length };
450 - if (value && typeof value === 'object') {
451 - return { type: 'object', keys: Object.keys(value as Record<string, unknown>).slice(0, 20) };
452 - }
453 - return {
454 - type: typeof value,
455 - value: typeof value === 'string' ? value.slice(0, 200) : (value ?? null),
456 - };
457 - };
458 -
459 - const summarizeCliResultPreview = (result: RunCliResult): unknown => {
460 - if (result == null || typeof result !== 'object') return result;
461 - if ('data' in result && result.data !== undefined) return result.data;
462 - if (typeof result.error === 'string' && result.error.trim().length > 0)
463 - return result.error.trim();
464 - return result;
465 - };
466 -
586 const logCliResultPreview = (
587 requestId: string,
588 command: string | undefined,
589 result: RunCliResult
590 ) => {
472 - if (!result || typeof result !== 'object') {
591 + if (!Predicate.isRecord(result)) {
592 helperDebugLog('cli.result', {
593 requestId,
594 command,
@@ -491,211 +610,10 @@ export const installRunHelpers = async ({
610 });
611 };
612
494 - const detectInvokeAgentMaster = (): MasterKind | 'user' => {
495 - if (
496 - helperContext.master === 'claude' ||
497 - helperContext.master === 'codex' ||
498 - helperContext.master === 'user'
499 - ) {
500 - return helperContext.master;
501 - }
502 - const envKeys = Object.keys(process.env || {});
503 - if (envKeys.some(key => key.startsWith('CODEX_'))) return 'codex';
504 - if (envKeys.some(key => key.startsWith('CLAUDE_'))) return 'claude';
505 - return 'user';
506 - };
507 -
508 - const readConfiguredExperimentalSubagentTarget = (): 'auto' | 'claude' | 'codex' => {
509 - try {
510 - const raw = fs.readFileSync(resolveCliConfigPathSync(), 'utf8');
511 - const parsed = JSON.parse(raw) as {
512 - experimental_subagent?: { target?: unknown };
513 - };
514 - const target = parsed.experimental_subagent?.target;
515 - return target === 'claude' || target === 'codex' || target === 'auto' ? target : 'auto';
516 - } catch {
517 - return 'auto';
518 - }
519 - };
520 -
521 - const resolveInvokeAgentTarget = (requestedTarget?: string): 'claude' | 'codex' => {
522 - if (requestedTarget === 'claude' || requestedTarget === 'codex') return requestedTarget;
523 - const configuredTarget = readConfiguredExperimentalSubagentTarget();
524 - if (configuredTarget === 'claude' || configuredTarget === 'codex') return configuredTarget;
525 - const detected = requestedTarget === 'user' ? 'user' : detectInvokeAgentMaster();
526 - if (detected === 'codex' || detected === 'claude') return detected;
527 - if (typeof Bun.which === 'function' && Bun.which('codex')) return 'codex';
528 - if (typeof Bun.which === 'function' && Bun.which('claude')) return 'claude';
529 - throw new Error(
530 - 'experimental_subAgent() could not determine an agent CLI. Current master is user; install codex or claude, or pass { target: "codex" | "claude" }.'
531 - );
532 - };
533 -
534 - const normalizeInvokeAgentOptions = (
535 - options: Record<string, unknown> = {}
536 - ): NormalizedInvokeAgentOptions => {
537 - if (options == null || typeof options !== 'object' || Array.isArray(options)) {
538 - throw new Error('experimental_subAgent() options must be an object when provided.');
539 - }
540 - if (options.schema !== undefined && options.jsonSchema !== undefined) {
541 - throw new Error(
542 - 'experimental_subAgent() accepts either options.schema or options.jsonSchema, not both.'
543 - );
544 - }
545 - const inputSchema = (options.schema ?? options.jsonSchema) as StructuredSchemaInput | undefined;
546 - let structuredSchema: Record<string, unknown> | undefined;
547 - let zodSchema: StructuredSchemaInput | undefined;
548 - if (inputSchema !== undefined) {
549 - if (
550 - typeof inputSchema === 'object' &&
551 - inputSchema !== null &&
552 - 'safeParse' in inputSchema &&
553 - typeof inputSchema.safeParse === 'function' &&
554 - '_def' in inputSchema
555 - ) {
556 - if (typeof z.toJSONSchema !== 'function') {
557 - throw new Error(
558 - 'experimental_subAgent() requires Zod 4 with z.toJSONSchema() when using options.schema.'
559 - );
560 - }
561 - zodSchema = inputSchema;
562 - structuredSchema = z.toJSONSchema(inputSchema as never) as Record<string, unknown>;
563 - } else if (
564 - typeof inputSchema === 'object' &&
565 - inputSchema !== null &&
566 - !Array.isArray(inputSchema)
567 - ) {
568 - structuredSchema = inputSchema;
569 - } else {
570 - throw new Error(
571 - 'experimental_subAgent() schema must be a Zod schema or JSON Schema object.'
572 - );
573 - }
574 - }
575 - return { ...options, structuredSchema, zodSchema };
576 - };
577 -
578 - const requireConsumerProxyContext = () => {
579 - if (!helperContext.apiKey) {
580 - throw new Error('proxy() requires an authenticated Composio user session.');
581 - }
582 - if (!helperContext.orgId || !helperContext.consumerProjectId || !helperContext.consumerUserId) {
583 - throw new Error(
584 - 'proxy() requires a consumer project context so it can use the consumer project credentials.'
585 - );
586 - }
587 - return {
588 - apiKey: helperContext.apiKey,
589 - orgId: helperContext.orgId,
590 - projectId: helperContext.consumerProjectId,
591 - userId: helperContext.consumerUserId,
592 - };
593 - };
594 -
595 - const normalizeProxyToolkit = (toolkit: string) => {
596 - if (typeof toolkit !== 'string' || toolkit.trim().length === 0) {
597 - throw new Error('proxy() requires a non-empty toolkit string.');
598 - }
599 - return toolkit.trim();
600 - };
601 -
602 - const normalizeFetchHeaders = (headers: HeadersInit | undefined) => {
603 - if (!headers) return [];
604 - return [...(new Headers(headers) as unknown as Iterable<[string, string]>)].map(
605 - ([name, value]) => ({
606 - name,
607 - type: 'header',
608 - value,
609 - })
610 - );
611 - };
612 -
613 - const normalizeFetchBody = async (body: unknown) => {
614 - if (body === undefined || body === null) return undefined;
615 - if (typeof body === 'string' || typeof body === 'number' || typeof body === 'boolean')
616 - return body;
617 - if (typeof Blob !== 'undefined' && body instanceof Blob) return await body.text();
618 - if (body instanceof ArrayBuffer) return encodeBase64(new Uint8Array(body));
619 - if (ArrayBuffer.isView(body)) {
620 - return encodeBase64(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
621 - }
622 - return body;
623 - };
624 -
625 - const normalizeFetchInput = async (input: unknown, init: RequestInit = {}) => {
626 - if (typeof Request !== 'undefined' && input instanceof Request) {
627 - throw new Error(
628 - 'proxy() does not support passing a Request instance yet. Pass a URL string and init instead.'
629 - );
630 - }
631 - const endpoint = input instanceof URL ? input.toString() : input;
632 - if (typeof endpoint !== 'string' || endpoint.trim().length === 0) {
633 - throw new Error('proxy fetch requires a non-empty URL string or URL object.');
634 - }
635 - const method = typeof init.method === 'string' ? init.method.toUpperCase() : 'GET';
636 - if (!['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].includes(method)) {
637 - throw new Error('proxy fetch only supports GET, POST, PUT, DELETE, PATCH.');
638 - }
639 - return {
640 - endpoint: endpoint.trim(),
641 - method,
642 - parameters: normalizeFetchHeaders(init.headers),
643 - body: await normalizeFetchBody(init.body),
644 - };
645 - };
646 -
647 - const fetchComposioJson = async (pathname: string, body: Record<string, unknown>) => {
648 - const auth = requireConsumerProxyContext();
649 - const response = await fetch(`${composioBaseURL}${pathname}`, {
650 - method: 'POST',
651 - headers: {
652 - 'content-type': 'application/json',
653 - 'x-user-api-key': auth.apiKey,
654 - 'x-org-id': auth.orgId,
655 - 'x-project-id': auth.projectId,
656 - },
657 - body: JSON.stringify(body),
658 - });
659 - const raw = await response.text();
660 - const parsed = parseJson(raw);
661 - if (!response.ok) {
662 - const detail =
663 - typeof parsed === 'string'
664 - ? parsed
665 - : (((parsed as { message?: string; error?: string } | undefined)?.message ||
666 - (parsed as { message?: string; error?: string } | undefined)?.error ||
667 - raw.trim()) ??
668 - undefined);
669 - const error = new Error(
670 - `Composio proxy request failed with status ${response.status}${detail ? `: ${detail}` : ''}`
671 - );
672 - Object.assign(error, { status: response.status, response: parsed ?? raw });
673 - throw error;
674 - }
675 - return parsed;
676 - };
677 -
678 - const getProxySessionId = async (toolkit: string) => {
679 - const cached = proxySessionCache.get(toolkit);
680 - if (cached) return cached;
681 - const auth = requireConsumerProxyContext();
682 - const created = (await fetchComposioJson('/api/v3/tool_router/session', {
683 - user_id: auth.userId,
684 - manage_connections: { enable: false },
685 - toolkits: { enable: [toolkit] },
686 - })) as { session_id?: string };
687 - const sessionId = created?.session_id;
688 - if (typeof sessionId !== 'string' || sessionId.length === 0) {
689 - throw new Error('Composio proxy session creation returned no session_id.');
690 - }
691 - proxySessionCache.set(toolkit, sessionId);
692 - return sessionId;
693 - };
694 -
613 const runCliJson = async (args: ReadonlyArray<string>): Promise<RunCliResult> => {
614 const requestId = `${args[0] ?? 'cli'}#${++perfDebugSeq}`;
615 helperDebugLog('cli.start', { requestId, args });
698 - const env = {
616 + const env: Record<string, string | undefined> = {
617 ...process.env,
618 ...(helperContext.apiKey ? { COMPOSIO_USER_API_KEY: helperContext.apiKey } : {}),
619 ...(helperContext.baseURL ? { COMPOSIO_BASE_URL: helperContext.baseURL } : {}),
@@ -706,7 +624,7 @@ export const installRunHelpers = async ({
624 ...(perfDebugEnabled ? { COMPOSIO_PERF_DEBUG: '1' } : {}),
625 ...(toolDebugEnabled ? { COMPOSIO_TOOL_DEBUG: '1' } : {}),
626 };
709 - delete (env as Record<string, string | undefined>).BUN_BE_BUN;
627 + delete env.BUN_BE_BUN;
628 perfDebugLog('start', requestId, { cmd: args });
629 const child = Bun.spawn({
630 cmd: [...cliPrefix, ...args],
@@ -715,7 +633,7 @@ export const installRunHelpers = async ({
633 });
634 const stdout = child.stdout ? await new Response(child.stdout).text() : '';
635 const stderr = child.stderr ? await new Response(child.stderr).text() : '';
718 - const result = maybeLoadStoredCliResult(parseJson(stdout) as RunCliResult);
636 + const result = maybeLoadStoredCliResult(parseJson(stdout));
637 const exitCode = await child.exited;
638 if (exitCode !== 0) {
639 perfDebugLog('error', requestId, { exitCode, stderr: stderr.trim() || undefined });
@@ -754,7 +672,28 @@ export const installRunHelpers = async ({
672 return result;
673 };
674
757 - runGlobals.search = async (query, options = {}) => {
675 + return runCliJson;
676 +};
677 +
678 +const createSearchAndExecuteHelpers = (params: {
679 + readonly helperContext: RunHelperContext;
680 + readonly sharedRunOutputDir: string | null;
681 + readonly runCliJson: (args: ReadonlyArray<string>) => Promise<RunCliResult>;
682 + readonly materializeExecutePayload: (value: unknown) => Promise<unknown>;
683 + readonly helperDebugLog: HelperDebugLog;
684 +}) => {
685 + const {
686 + helperContext,
687 + sharedRunOutputDir,
688 + runCliJson,
689 + materializeExecutePayload,
690 + helperDebugLog,
691 + } = params;
692 +
693 + const search = async (
694 + query: string,
695 + options: Record<string, unknown> = {}
696 + ): Promise<RunCliResult> => {
697 helperDebugLog('search.prepare', { query, options });
698 const args = ['search', query];
699 if (Array.isArray(options.toolkits) && options.toolkits.length > 0) {
@@ -768,7 +707,11 @@ export const installRunHelpers = async ({
707 return runCliJson(args);
708 };
709
771 - runGlobals.execute = async (slug, data = {}, options = {}) => {
710 + const execute = async (
711 + slug: string,
712 + data: unknown = {},
713 + options: { account?: string } = {}
714 + ): Promise<RunCliResult> => {
715 helperDebugLog('execute.prepare', {
716 slug,
717 hasData: data !== undefined,
@@ -795,7 +738,7 @@ export const installRunHelpers = async ({
738 }
739 }
740 const result = await runCliJson(args);
798 - if (result && typeof result === 'object' && result.successful === false) {
741 + if (Predicate.isRecord(result) && result.successful === false) {
742 const message =
743 typeof result.error === 'string' && result.error.trim().length > 0
744 ? result.error.trim()
@@ -807,6 +750,39 @@ export const installRunHelpers = async ({
750 return result;
751 };
752
753 + return { search, execute };
754 +};
755 +
756 +const createExperimentalSubAgent = (params: {
757 + readonly helperContext: RunHelperContext;
758 + readonly helperDebugLog: HelperDebugLog;
759 +}) => {
760 + const { helperContext, helperDebugLog } = params;
761 +
762 + const detectInvokeAgentMaster = (): MasterKind | 'user' => {
763 + if (
764 + helperContext.master === 'claude' ||
765 + helperContext.master === 'codex' ||
766 + helperContext.master === 'user'
767 + ) {
768 + return helperContext.master;
769 + }
770 + return detectMaster();
771 + };
772 +
773 + const resolveInvokeAgentTarget = (requestedTarget?: string): 'claude' | 'codex' => {
774 + if (requestedTarget === 'claude' || requestedTarget === 'codex') return requestedTarget;
775 + const configuredTarget = readConfiguredExperimentalSubagentTarget();
776 + if (configuredTarget === 'claude' || configuredTarget === 'codex') return configuredTarget;
777 + const detected = requestedTarget === 'user' ? 'user' : detectInvokeAgentMaster();
778 + if (detected === 'codex' || detected === 'claude') return detected;
779 + if (typeof Bun.which === 'function' && Bun.which('codex')) return 'codex';
780 + if (typeof Bun.which === 'function' && Bun.which('claude')) return 'claude';
781 + throw new Error(
782 + 'experimental_subAgent() could not determine an agent CLI. Current master is user; install codex or claude, or pass { target: "codex" | "claude" }.'
783 + );
784 + };
785 +
786 const experimentalSubAgentImpl = async (
787 prompt: string,
788 options: Record<string, unknown> = {}
@@ -829,8 +805,7 @@ export const installRunHelpers = async ({
805 try {
806 const response = await invokeAcpSubAgent({
807 prompt: prompt.trim(),
832 - options:
833 - normalizedOptions as import('src/services/run-subagent-shared').InvokeAgentNormalizedOptions,
808 + options: normalizedOptions,
809 master,
810 target,
811 allowedReadRoots: Array.isArray(helperContext.readAccessRoots)
@@ -849,8 +824,7 @@ export const installRunHelpers = async ({
824 });
825 const response = await invokeLegacySubAgent({
826 prompt: prompt.trim(),
852 - options:
853 - normalizedOptions as import('src/services/run-subagent-shared').InvokeAgentNormalizedOptions,
827 + options: normalizedOptions,
828 master,
829 target,
830 helperDebugLog,
@@ -859,43 +833,86 @@ export const installRunHelpers = async ({
833 }
834 };
835
862 - runGlobals.experimental_subAgent = experimentalSubAgentImpl;
863 - Object.defineProperty(runGlobals.experimental_subAgent, 'schema', {
864 - value: experimentalSubAgentSchema,
865 - });
866 - runGlobals.invokeAgent = experimentalSubAgentImpl;
867 - Object.defineProperty(runGlobals.invokeAgent, 'schema', { value: experimentalSubAgentSchema });
868 -
869 - const toProxyResponse = async (result: {
870 - readonly headers?: Record<string, string>;
871 - readonly binary_data?: { readonly url?: string };
872 - readonly data?: unknown;
873 - readonly status?: number;
874 - }) => {
875 - const headers = new Headers(result?.headers || {});
876 - if (result?.binary_data?.url) {
877 - const binaryResponse = await fetch(result.binary_data.url);
878 - binaryResponse.headers.forEach((value, key) => {
879 - if (!headers.has(key)) headers.set(key, value);
880 - });
881 - return new Response(binaryResponse.body, {
882 - status: result.status ?? binaryResponse.status,
883 - headers,
884 - });
836 + Object.defineProperty(experimentalSubAgentImpl, 'schema', { value: experimentalSubAgentSchema });
837 + return experimentalSubAgentImpl;
838 +};
839 +
840 +const createProxyHelper = (params: {
841 + readonly helperContext: RunHelperContext;
842 + readonly composioBaseURL: string;
843 + readonly helperDebugLog: HelperDebugLog;
844 +}) => {
845 + const { helperContext, composioBaseURL, helperDebugLog } = params;
846 + const proxySessionCache = new Map<string, string>();
847 +
848 + const requireConsumerProxyContext = () => {
849 + if (!helperContext.apiKey) {
850 + throw new Error('proxy() requires an authenticated Composio user session.');
851 }
886 - if (result?.data === undefined || result?.data === null) {
887 - return new Response(null, { status: result?.status ?? 200, headers });
852 + if (!helperContext.orgId || !helperContext.consumerProjectId || !helperContext.consumerUserId) {
853 + throw new Error(
854 + 'proxy() requires a consumer project context so it can use the consumer project credentials.'
855 + );
856 }
889 - if (typeof result.data === 'string') {
890 - if (!headers.has('content-type')) headers.set('content-type', 'text/plain; charset=utf-8');
891 - return new Response(result.data, { status: result.status ?? 200, headers });
857 + return {
858 + apiKey: helperContext.apiKey,
859 + orgId: helperContext.orgId,
860 + projectId: helperContext.consumerProjectId,
861 + userId: helperContext.consumerUserId,
862 + };
863 + };
864 +
865 + const fetchComposioJson = async (pathname: string, body: Record<string, unknown>) => {
866 + const auth = requireConsumerProxyContext();
867 + const response = await fetch(`${composioBaseURL}${pathname}`, {
868 + method: 'POST',
869 + headers: {
870 + 'content-type': 'application/json',
871 + 'x-user-api-key': auth.apiKey,
872 + 'x-org-id': auth.orgId,
873 + 'x-project-id': auth.projectId,
874 + },
875 + body: JSON.stringify(body),
876 + });
877 + const raw = await response.text();
878 + const parsed = parseJson(raw);
879 + if (!response.ok) {
880 + const responseMessage = Predicate.isRecord(parsed) ? parsed.message : undefined;
881 + const responseError = Predicate.isRecord(parsed) ? parsed.error : undefined;
882 + const detail =
883 + typeof parsed === 'string'
884 + ? parsed
885 + : typeof responseMessage === 'string'
886 + ? responseMessage
887 + : typeof responseError === 'string'
888 + ? responseError
889 + : raw.trim() || undefined;
890 + const error = new Error(
891 + `Composio proxy request failed with status ${response.status}${detail ? `: ${detail}` : ''}`
892 + );
893 + Object.assign(error, { status: response.status, response: parsed ?? raw });
894 + throw error;
895 }
893 - if (!headers.has('content-type'))
894 - headers.set('content-type', 'application/json; charset=utf-8');
895 - return new Response(JSON.stringify(result.data), { status: result.status ?? 200, headers });
896 + return parsed;
897 + };
898 +
899 + const getProxySessionId = async (toolkit: string) => {
900 + const cached = proxySessionCache.get(toolkit);
901 + if (cached) return cached;
902 + const auth = requireConsumerProxyContext();
903 + const created = await Schema.decodeUnknownPromise(ProxySessionResponse)(
904 + await fetchComposioJson('/api/v3/tool_router/session', {
905 + user_id: auth.userId,
906 + manage_connections: { enable: false },
907 + toolkits: { enable: [toolkit] },
908 + })
909 + );
910 + const sessionId = created.session_id;
911 + proxySessionCache.set(toolkit, sessionId);
912 + return sessionId;
913 };
914
898 - runGlobals.proxy = async (toolkit: string) => {
915 + const proxy = async (toolkit: string) => {
916 const normalizedToolkit = normalizeProxyToolkit(toolkit);
917 helperDebugLog('proxy.session', {
918 toolkit: normalizedToolkit,
@@ -909,39 +926,104 @@ export const installRunHelpers = async ({
926 method: request.method,
927 endpoint: request.endpoint,
928 });
912 - const result = (await fetchComposioJson(
913 - `/api/v3/tool_router/session/${sessionId}/proxy_execute`,
914 - {
929 + const result = await Schema.decodeUnknownPromise(ProxyExecuteResponse)(
930 + await fetchComposioJson(`/api/v3/tool_router/session/${sessionId}/proxy_execute`, {
931 toolkit_slug: normalizedToolkit,
932 endpoint: request.endpoint,
933 method: request.method,
934 ...(request.body !== undefined ? { body: request.body } : {}),
935 ...(request.parameters.length > 0
936 ? {
921 - parameters: request.parameters.map(
922 - (parameter: { name: string; type: string; value: string }) => ({
923 - name: parameter.name,
924 - type: parameter.type,
925 - value: String(parameter.value),
926 - })
927 - ),
937 + parameters: request.parameters.map(parameter => ({
938 + name: parameter.name,
939 + type: parameter.type,
940 + value: String(parameter.value),
941 + })),
942 }
943 : {}),
930 - }
931 - )) as {
932 - readonly headers?: Record<string, string>;
933 - readonly binary_data?: { readonly url?: string };
934 - readonly data?: unknown;
935 - readonly status?: number;
936 - };
944 + })
945 + );
946 return toProxyResponse(result);
947 };
948 Object.defineProperty(proxyFetch, 'toolkit', { value: normalizedToolkit });
949 return proxyFetch;
950 };
942 - Object.defineProperty(runGlobals.proxy, 'schema', { value: proxySchema });
951
944 - Object.defineProperty(runGlobals, '__composioRunContext', {
952 + Object.defineProperty(proxy, 'schema', { value: proxySchema });
953 + return proxy;
954 +};
955 +
956 +export const installRunHelpers = async ({
957 + cliPrefix,
958 + helperContext = {},
959 +}: RunHelpersInstallParams): Promise<void> => {
960 + // This preload runs in the user's child process, outside the CLI runtime.
961 + // Resolve the live services once at that boundary and keep all writes centralized.
962 + const terminal = Effect.runSync(TerminalUI.pipe(Effect.provide(TerminalUILive)));
963 + const path = Effect.runSync(Path.Path.pipe(Effect.provide(Path.layer)));
964 + const writeError = (line: string) => Effect.runSync(terminal.error(line));
965 +
966 + Reflect.set(globalThis, 'z', z);
967 + Reflect.set(globalThis, 'zod', z);
968 +
969 + const perfDebugEnabled =
970 + helperContext.perfDebug === true || process.env.COMPOSIO_PERF_DEBUG === '1';
971 + const toolDebugEnabled =
972 + helperContext.toolDebug === true || process.env.COMPOSIO_TOOL_DEBUG === '1';
973 + const perfDebugStart = Date.now();
974 + const composioBaseURL = (helperContext.baseURL || 'https://backend.composio.dev').replace(
975 + /\/$/,
976 + ''
977 + );
978 + const sharedRunOutputDir =
979 + typeof helperContext.runOutputDir === 'string' && helperContext.runOutputDir.length > 0
980 + ? helperContext.runOutputDir
981 + : null;
982 + const sharedRunLogFilePath =
983 + typeof helperContext.runLogFilePath === 'string' && helperContext.runLogFilePath.length > 0
984 + ? helperContext.runLogFilePath
985 + : null;
986 +
987 + const loggers = createRunHelperLoggers({
988 + helperContext,
989 + writeError,
990 + sharedRunLogFilePath,
991 + perfDebugEnabled,
992 + perfDebugStart,
993 + });
994 + const { helperDebugLog } = loggers;
995 +
996 + const materializeExecutePayload = createExecutePayloadMaterializer({
997 + path,
998 + sharedRunOutputDir,
999 + });
1000 + const runCliJson = createCliRunner({
1001 + cliPrefix,
1002 + helperContext,
1003 + sharedRunOutputDir,
1004 + perfDebugEnabled,
1005 + toolDebugEnabled,
1006 + loggers,
1007 + });
1008 + const { search, execute } = createSearchAndExecuteHelpers({
1009 + helperContext,
1010 + sharedRunOutputDir,
1011 + runCliJson,
1012 + materializeExecutePayload,
1013 + helperDebugLog,
1014 + });
1015 +
1016 + const experimentalSubAgentImpl = createExperimentalSubAgent({ helperContext, helperDebugLog });
1017 + Reflect.set(globalThis, 'experimental_subAgent', experimentalSubAgentImpl);
1018 + Reflect.set(globalThis, 'invokeAgent', experimentalSubAgentImpl);
1019 +
1020 + const proxy = createProxyHelper({ helperContext, composioBaseURL, helperDebugLog });
1021 +
1022 + Reflect.set(globalThis, 'search', search);
1023 + Reflect.set(globalThis, 'execute', execute);
1024 + Reflect.set(globalThis, 'proxy', proxy);
1025 +
1026 + Object.defineProperty(globalThis, '__composioRunContext', {
1027 value: Object.freeze({
1028 outputDir: sharedRunOutputDir,
1029 logFilePath: sharedRunLogFilePath,
@@ -949,7 +1031,7 @@ export const installRunHelpers = async ({
1031 configurable: true,
1032 });
1033
952 - Object.defineProperty(runGlobals, '__composioConsumerContext', {
1034 + Object.defineProperty(globalThis, '__composioConsumerContext', {
1035 value: helperContext,
1036 configurable: true,
1037 });
ts/packages/cli/src/services/run-subagent-acp.ts
+518 -324
@@ -1,18 +1,14 @@
1 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
2 -import * as fs from 'node:fs';
3 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
4 -import { spawn } from 'node:child_process';
1 import { createRequire } from 'node:module';
6 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
7 -import * as os from 'node:os';
8 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
9 -import path from 'node:path';
10 -import { Readable, Writable } from 'node:stream';
2 +import type { Readable } from 'node:stream';
3 import * as acp from '@agentclientprotocol/sdk';
4 +import { Command, FileSystem, Path } from '@effect/platform';
5 +import { BunContext } from '@effect/platform-bun';
6 +import { Cause, Config, Effect, Exit, Layer, Option, Predicate, Queue, Stream } from 'effect';
7 import type { MasterKind } from 'src/services/master-detector';
8 +import { NodeOs } from 'src/services/node-os';
9 import {
14 - resolveRunCompanionAssetPathSync,
15 - resolveRunCompanionModulePathSync,
10 + resolveRunCompanionAssetPath,
11 + resolveRunCompanionModulePath,
12 RUN_CODEX_ACP_BINARY_TARGETS,
13 } from 'src/services/run-companion-modules';
14 import {
@@ -38,9 +34,82 @@ type LegacySetSessionModelConnection = {
34 }) => Promise<unknown>;
35 };
36
41 -const resolveShippedAdapterAsset = (target: InvokeAgentTarget): string | null => {
37 +type AcpAdapterCommand = {
38 + readonly cmd: readonly [string, ...ReadonlyArray<string>];
39 + readonly env?: Readonly<Record<string, string>>;
40 + readonly source: 'shipped' | 'bundled' | 'which' | 'npx';
41 +};
42 +
43 +// This module is bundled as a standalone `composio run` companion module, so it
44 +// provides its own platform layers instead of assuming the CLI runtime.
45 +const RunSubAgentAcpLive = Layer.mergeAll(BunContext.layer, NodeOs.Default);
46 +
47 +const getLegacySetSessionModel = (
48 + connection: unknown
49 +): LegacySetSessionModelConnection['unstable_setSessionModel'] => {
50 + if (!Predicate.hasProperty(connection, 'unstable_setSessionModel')) {
51 + return undefined;
52 + }
53 + const method = connection.unstable_setSessionModel;
54 + return Predicate.isFunction(method) ? async params => method.call(connection, params) : undefined;
55 +};
56 +
57 +export const readableStreamFromNode = (input: Readable): ReadableStream<Uint8Array> => {
58 + let cleanup = () => undefined;
59 +
60 + return new ReadableStream<Uint8Array>({
61 + start: controller => {
62 + const onData = (chunk: Buffer | string) => {
63 + controller.enqueue(
64 + typeof chunk === 'string' ? new TextEncoder().encode(chunk) : Uint8Array.from(chunk)
65 + );
66 + if ((controller.desiredSize ?? 1) <= 0) {
67 + input.pause();
68 + }
69 + };
70 + const onEnd = () => {
71 + cleanup();
72 + controller.close();
73 + };
74 + const onError = (error: Error) => {
75 + cleanup();
76 + controller.error(error);
77 + };
78 + cleanup = () => {
79 + input.off('data', onData);
80 + input.off('end', onEnd);
81 + input.off('error', onError);
82 + };
83 + input.on('data', onData);
84 + input.once('end', onEnd);
85 + input.once('error', onError);
86 + },
87 + pull: () => {
88 + input.resume();
89 + },
90 + cancel: reason => {
91 + cleanup();
92 + input.destroy(reason instanceof Error ? reason : undefined);
93 + },
94 + });
95 +};
96 +
97 +// Bridges the ACP connection's outgoing ndjson writes into an Effect Queue that
98 +// a forked fiber drains into the child's stdin Sink. A bounded queue keeps the
99 +// child's stdin backpressure visible to the ACP writer, and shutting the queue
100 +// down on close/abort ends the stdin stream (EOF) for the child.
101 +const writableStreamFromQueue = (queue: Queue.Queue<Uint8Array>): WritableStream<Uint8Array> =>
102 + new WritableStream<Uint8Array>({
103 + write: chunk => Effect.runPromise(Effect.asVoid(Queue.offer(queue, chunk))),
104 + close: () => Effect.runPromise(Queue.shutdown(queue)),
105 + abort: () => Effect.runPromise(Queue.shutdown(queue)),
106 + });
107 +
108 +const resolveShippedAdapterAsset = (
109 + target: InvokeAgentTarget
110 +): Effect.Effect<string | null, never, FileSystem.FileSystem | Path.Path> => {
111 if (target === 'claude') {
43 - return resolveRunCompanionAssetPathSync({
112 + return resolveRunCompanionAssetPath({
113 callerImportMetaUrl: import.meta.url,
114 execPath: process.execPath,
115 relativePathFromRoot: 'acp-adapters/claude-code-acp.mjs',
@@ -51,10 +120,10 @@ const resolveShippedAdapterAsset = (target: InvokeAgentTarget): string | null =>
120 candidate => candidate.platform === process.platform && candidate.arch === process.arch
121 );
122 if (!binaryTarget) {
54 - return null;
123 + return Effect.succeed(null);
124 }
125
57 - return resolveRunCompanionAssetPathSync({
126 + return resolveRunCompanionAssetPath({
127 callerImportMetaUrl: import.meta.url,
128 execPath: process.execPath,
129 relativePathFromRoot: binaryTarget.relativePath,
@@ -66,82 +135,81 @@ const resolveInstalledAdapter = (target: InvokeAgentTarget): string | null => {
135 target === 'claude'
136 ? '@zed-industries/claude-code-acp/dist/index.js'
137 : '@zed-industries/codex-acp/bin/codex-acp.js';
69 - try {
70 - const require = createRequire(import.meta.url);
71 - return require.resolve(specifier);
72 - } catch {
73 - return null;
74 - }
138 + const require = createRequire(import.meta.url);
139 + return Option.getOrNull(Option.liftThrowable(() => require.resolve(specifier))());
140 };
141
142 export const resolveAcpAdapterCommand = (
143 target: InvokeAgentTarget
79 -): {
80 - readonly cmd: ReadonlyArray<string>;
81 - readonly env?: Readonly<Record<string, string>>;
82 - readonly source: 'shipped' | 'bundled' | 'which' | 'npx';
83 -} => {
84 - const binary = target === 'claude' ? 'claude-code-acp' : 'codex-acp';
85 - const packageName =
86 - target === 'claude' ? '@zed-industries/claude-code-acp' : '@zed-industries/codex-acp';
87 -
88 - // 1. Prefer shipped companion assets next to the CLI binary / dist bundle.
89 - const shipped = resolveShippedAdapterAsset(target);
90 - if (shipped) {
91 - if (target === 'codex') {
144 +): Effect.Effect<AcpAdapterCommand, never, FileSystem.FileSystem | Path.Path> =>
145 + Effect.gen(function* () {
146 + const binary = target === 'claude' ? 'claude-code-acp' : 'codex-acp';
147 + const packageName =
148 + target === 'claude' ? '@zed-industries/claude-code-acp' : '@zed-industries/codex-acp';
149 +
150 + // 1. Prefer shipped companion assets next to the CLI binary / dist bundle.
151 + const shipped = yield* resolveShippedAdapterAsset(target);
152 + if (shipped) {
153 + if (target === 'codex') {
154 + return {
155 + cmd: [shipped],
156 + source: 'shipped',
157 + } satisfies AcpAdapterCommand;
158 + }
159 +
160 return {
93 - cmd: [shipped],
161 + cmd: [process.execPath, shipped],
162 + env: {
163 + BUN_BE_BUN: '1',
164 + },
165 source: 'shipped',
95 - };
166 + } satisfies AcpAdapterCommand;
167 }
168
98 - return {
99 - cmd: [process.execPath, shipped],
100 - env: {
101 - BUN_BE_BUN: '1',
102 - },
103 - source: 'shipped',
104 - };
105 - }
106 -
107 - // 2. Try the installed dependency bundle next (no npx overhead).
108 - const bundled = resolveInstalledAdapter(target);
109 - if (bundled) {
110 - return {
111 - cmd: [process.execPath, bundled],
112 - env: {
113 - BUN_BE_BUN: '1',
114 - },
115 - source: 'bundled',
116 - };
117 - }
118 -
119 - // 3. Check if the binary is on PATH.
120 - if (typeof Bun !== 'undefined' && typeof Bun.which === 'function') {
121 - const resolved = Bun.which(binary);
122 - if (resolved) {
169 + // 2. Try the installed dependency bundle next (no npx overhead).
170 + const bundled = resolveInstalledAdapter(target);
171 + if (bundled) {
172 return {
124 - cmd: [resolved],
125 - source: 'which',
126 - };
173 + cmd: [process.execPath, bundled],
174 + env: {
175 + BUN_BE_BUN: '1',
176 + },
177 + source: 'bundled',
178 + } satisfies AcpAdapterCommand;
179 }
128 - }
180
130 - // 4. Fall back to npx.
131 - return {
132 - cmd: [process.platform === 'win32' ? 'npx.cmd' : 'npx', '-y', packageName],
133 - source: 'npx',
134 - };
135 -};
181 + // 3. Check if the binary is on PATH.
182 + if (typeof Bun !== 'undefined' && typeof Bun.which === 'function') {
183 + const resolved = Bun.which(binary);
184 + if (resolved) {
185 + return {
186 + cmd: [resolved],
187 + source: 'which',
188 + } satisfies AcpAdapterCommand;
189 + }
190 + }
191 +
192 + // 4. Fall back to npx.
193 + return {
194 + cmd: [process.platform === 'win32' ? 'npx.cmd' : 'npx', '-y', packageName],
195 + source: 'npx',
196 + } satisfies AcpAdapterCommand;
197 + });
198
199 const chunkFlushPattern = /[\s,.;:!?)\]}"]$/;
138 -const structuredOutputMcpModulePath = resolveRunCompanionModulePathSync({
200 +const resolveStructuredOutputMcpModulePath = resolveRunCompanionModulePath({
201 callerImportMetaUrl: import.meta.url,
202 execPath: process.execPath,
203 relativeNoExtensionFromCaller: './run-subagent-output-mcp',
204 });
205
144 -const collectToolCallPaths = (value: unknown, results: Set<string>, parentKey?: string): void => {
206 +const collectToolCallPaths = (
207 + value: unknown,
208 + results: Set<string>,
209 + pathApi: Path.Path,
210 + homedir: string,
211 + parentKey?: string
212 +): void => {
213 if (typeof value === 'string') {
214 const key = parentKey?.toLowerCase() ?? '';
215 if (
@@ -153,7 +221,7 @@ const collectToolCallPaths = (value: unknown, results: Set<string>, parentKey?:
221 ) {
222 results.add(value);
223 } else if (key === 'command' || key === 'cmd') {
156 - for (const candidatePath of extractPathsFromCommandText(value)) {
224 + for (const candidatePath of extractPathsFromCommandText(value, pathApi, homedir)) {
225 results.add(candidatePath);
226 }
227 }
@@ -177,7 +245,7 @@ const collectToolCallPaths = (value: unknown, results: Set<string>, parentKey?:
245 }
246
247 for (const entry of value) {
180 - collectToolCallPaths(entry, results);
248 + collectToolCallPaths(entry, results, pathApi, homedir);
249 }
250 return;
251 }
@@ -187,11 +255,15 @@ const collectToolCallPaths = (value: unknown, results: Set<string>, parentKey?:
255 }
256
257 for (const [key, nestedValue] of Object.entries(value)) {
190 - collectToolCallPaths(nestedValue, results, key);
258 + collectToolCallPaths(nestedValue, results, pathApi, homedir, key);
259 }
260 };
261
194 -const extractPathsFromCommandText = (command: string): ReadonlyArray<string> => {
262 +const extractPathsFromCommandText = (
263 + command: string,
264 + pathApi: Path.Path,
265 + homedir: string
266 +): ReadonlyArray<string> => {
267 const results = new Set<string>();
268 const matches = command.matchAll(/(^|[\s"'`])((?:~\/|\/)[^\s"'`|&;<>]+)/g);
269 for (const match of matches) {
@@ -200,14 +272,16 @@ const extractPathsFromCommandText = (command: string): ReadonlyArray<string> =>
272 continue;
273 }
274
203 - results.add(rawPath.startsWith('~/') ? path.join(os.homedir(), rawPath.slice(2)) : rawPath);
275 + results.add(rawPath.startsWith('~/') ? pathApi.join(homedir, rawPath.slice(2)) : rawPath);
276 }
277
278 return [...results];
279 };
280
281 const extractToolCallPaths = (
210 - toolCall: Pick<acp.RequestPermissionRequest, 'toolCall'>['toolCall']
282 + toolCall: Pick<acp.RequestPermissionRequest, 'toolCall'>['toolCall'],
283 + pathApi: Path.Path,
284 + homedir: string
285 ): ReadonlyArray<string> => {
286 const paths = new Set<string>();
287 for (const location of toolCall.locations ?? []) {
@@ -216,9 +290,9 @@ const extractToolCallPaths = (
290 }
291 }
292
219 - collectToolCallPaths(toolCall.rawInput, paths);
293 + collectToolCallPaths(toolCall.rawInput, paths, pathApi, homedir);
294 if (typeof toolCall.title === 'string') {
221 - for (const candidatePath of extractPathsFromCommandText(toolCall.title)) {
295 + for (const candidatePath of extractPathsFromCommandText(toolCall.title, pathApi, homedir)) {
296 paths.add(candidatePath);
297 }
298 }
@@ -325,7 +399,9 @@ class RunSubAgentClient {
399
400 constructor(
401 private readonly helperDebugLog: HelperDebugLog,
328 - private readonly allowedReadRoots: ReadonlyArray<string>
402 + private readonly allowedReadRoots: ReadonlyArray<string>,
403 + private readonly pathApi: Path.Path,
404 + private readonly homedir: string
405 ) {
406 this.messageLogger = new BufferedChunkLogger('subAgent.acp.message', helperDebugLog);
407 this.thoughtLogger = new BufferedChunkLogger('subAgent.acp.thought', helperDebugLog);
@@ -334,7 +410,7 @@ class RunSubAgentClient {
410 async requestPermission(
411 params: acp.RequestPermissionRequest
412 ): Promise<acp.RequestPermissionResponse> {
337 - const requestedPaths = extractToolCallPaths(params.toolCall);
413 + const requestedPaths = extractToolCallPaths(params.toolCall, this.pathApi, this.homedir);
414 const decision = selectPermissionOutcome(params, this.allowedReadRoots);
415 this.helperDebugLog('subAgent.acp.permission', {
416 toolCallId: params.toolCall.toolCallId,
@@ -417,7 +493,7 @@ const createFallbackError = (
493 type StructuredOutputMcpContext = {
494 readonly mcpServer: acp.McpServerStdio;
495 readonly resultFilePath: string;
420 - readonly cleanup: () => void;
496 + readonly cleanup: Effect.Effect<void>;
497 };
498
499 export const createStructuredOutputMcpContext = ({
@@ -426,63 +502,79 @@ export const createStructuredOutputMcpContext = ({
502 }: {
503 options: InvokeAgentNormalizedOptions;
504 helperDebugLog: HelperDebugLog;
429 -}): StructuredOutputMcpContext | null => {
430 - if (!options.structuredSchema) {
431 - return null;
432 - }
505 +}): Effect.Effect<StructuredOutputMcpContext | null, never, FileSystem.FileSystem | Path.Path> =>
506 + Effect.gen(function* () {
507 + const structuredSchema = options.structuredSchema;
508 + if (!structuredSchema) {
509 + return null;
510 + }
511
434 - let tempDirectory: string | null = null;
435 - try {
436 - // Keep this on an OS temp dir for now. Repointing MCP schema/result files into
437 - // session artifacts needs a broader bundling + run-companion test pass so we
438 - // don't break structured sub-agent output in packaged CLI builds.
439 - tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-subagent-output-mcp-'));
440 - const schemaFilePath = path.join(tempDirectory, 'schema.json');
441 - const resultFilePath = path.join(tempDirectory, 'result.json');
442 - fs.writeFileSync(schemaFilePath, JSON.stringify(options.structuredSchema), 'utf8');
443 -
444 - helperDebugLog('subAgent.acp.structured_output_tool', {
445 - modulePath: structuredOutputMcpModulePath,
446 - schemaFilePath,
447 - resultFilePath,
448 - });
512 + const fs = yield* FileSystem.FileSystem;
513 + const pathApi = yield* Path.Path;
514 + const structuredOutputMcpModulePath = yield* resolveStructuredOutputMcpModulePath;
515
450 - return {
451 - mcpServer: {
452 - name: 'composio-structured-output',
453 - command: process.execPath,
454 - args: [
455 - structuredOutputMcpModulePath,
456 - '--schema-file',
457 - schemaFilePath,
458 - '--result-file',
459 - resultFilePath,
460 - ],
461 - env: [
462 - {
463 - name: 'BUN_BE_BUN',
464 - value: '1',
465 - },
466 - ],
467 - },
468 - resultFilePath,
469 - cleanup: () => {
470 - if (tempDirectory) {
471 - fs.rmSync(tempDirectory, { recursive: true, force: true });
472 - }
473 - },
474 - };
475 - } catch (error) {
476 - if (tempDirectory) {
477 - fs.rmSync(tempDirectory, { recursive: true, force: true });
478 - }
479 - helperDebugLog('subAgent.acp.structured_output_tool_failed', {
480 - error: error instanceof Error ? error.message : String(error),
481 - modulePath: structuredOutputMcpModulePath,
516 + const build = Effect.gen(function* () {
517 + // Keep this on an OS temp dir for now. Repointing MCP schema/result files into
518 + // session artifacts needs a broader bundling + run-companion test pass so we
519 + // don't break structured sub-agent output in packaged CLI builds.
520 + const tempDirectory = yield* fs.makeTempDirectory({
521 + prefix: 'composio-subagent-output-mcp-',
522 + });
523 + const removeTempDirectory = Effect.ignore(
524 + fs.remove(tempDirectory, { recursive: true, force: true })
525 + );
526 + const schemaFilePath = pathApi.join(tempDirectory, 'schema.json');
527 + const resultFilePath = pathApi.join(tempDirectory, 'result.json');
528 + yield* Effect.try({
529 + try: () => JSON.stringify(structuredSchema),
530 + catch: error => error,
531 + }).pipe(
532 + Effect.flatMap(schemaJson => fs.writeFileString(schemaFilePath, schemaJson)),
533 + Effect.tapError(() => removeTempDirectory)
534 + );
535 +
536 + helperDebugLog('subAgent.acp.structured_output_tool', {
537 + modulePath: structuredOutputMcpModulePath,
538 + schemaFilePath,
539 + resultFilePath,
540 + });
541 +
542 + const context: StructuredOutputMcpContext = {
543 + mcpServer: {
544 + name: 'composio-structured-output',
545 + command: process.execPath,
546 + args: [
547 + structuredOutputMcpModulePath,
548 + '--schema-file',
549 + schemaFilePath,
550 + '--result-file',
551 + resultFilePath,
552 + ],
553 + env: [
554 + {
555 + name: 'BUN_BE_BUN',
556 + value: '1',
557 + },
558 + ],
559 + },
560 + resultFilePath,
561 + cleanup: removeTempDirectory,
562 + };
563 + return context;
564 });
483 - return null;
484 - }
485 -};
565 +
566 + return yield* build.pipe(
567 + Effect.catchAll(error =>
568 + Effect.sync(() => {
569 + helperDebugLog('subAgent.acp.structured_output_tool_failed', {
570 + error: error instanceof Error ? error.message : String(error),
571 + modulePath: structuredOutputMcpModulePath,
572 + });
573 + return null;
574 + })
575 + )
576 + );
577 + });
578
579 const maybeReadStructuredOutputFromTool = ({
580 context,
@@ -492,124 +584,258 @@ const maybeReadStructuredOutputFromTool = ({
584 context: StructuredOutputMcpContext | null;
585 options: InvokeAgentNormalizedOptions;
586 helperDebugLog: HelperDebugLog;
495 -}): unknown | undefined => {
496 - if (!context || !options.structuredSchema || !fs.existsSync(context.resultFilePath)) {
497 - return undefined;
498 - }
587 +}): Effect.Effect<unknown, never, FileSystem.FileSystem> =>
588 + Effect.gen(function* () {
589 + const structuredSchema = options.structuredSchema;
590 + if (!context || !structuredSchema) {
591 + return undefined;
592 + }
593
500 - try {
501 - const rawPayload = JSON.parse(fs.readFileSync(context.resultFilePath, 'utf8')) as unknown;
502 - const parsed = unwrapStructuredOutputToolPayload(rawPayload, options.structuredSchema);
503 - helperDebugLog('subAgent.acp.structured_output_tool_result', {
504 - resultFilePath: context.resultFilePath,
505 - });
506 - return validateStructuredOutput(parsed, options);
507 - } catch (error) {
508 - helperDebugLog('subAgent.acp.structured_output_tool_result_failed', {
509 - resultFilePath: context.resultFilePath,
510 - error: error instanceof Error ? error.message : String(error),
511 - });
512 - return undefined;
513 - }
594 + const fs = yield* FileSystem.FileSystem;
595 + const resultFileExists = yield* fs
596 + .exists(context.resultFilePath)
597 + .pipe(Effect.orElseSucceed(() => false));
598 + if (!resultFileExists) {
599 + return undefined;
600 + }
601 +
602 + const read = fs.readFileString(context.resultFilePath).pipe(
603 + Effect.flatMap(rawText =>
604 + Effect.try({
605 + try: () => {
606 + const rawPayload: unknown = JSON.parse(rawText);
607 + const parsed = unwrapStructuredOutputToolPayload(rawPayload, structuredSchema);
608 + helperDebugLog('subAgent.acp.structured_output_tool_result', {
609 + resultFilePath: context.resultFilePath,
610 + });
611 + return validateStructuredOutput(parsed, options);
612 + },
613 + catch: error => error,
614 + })
615 + )
616 + );
617 +
618 + return yield* read.pipe(
619 + Effect.catchAll(error =>
620 + Effect.sync<unknown>(() => {
621 + helperDebugLog('subAgent.acp.structured_output_tool_result_failed', {
622 + resultFilePath: context.resultFilePath,
623 + error: error instanceof Error ? error.message : String(error),
624 + });
625 + return undefined;
626 + })
627 + )
628 + );
629 + });
630 +
631 +type InvokeAcpSubAgentParams = {
632 + prompt: string;
633 + options: InvokeAgentNormalizedOptions;
634 + master: MasterKind;
635 + target: InvokeAgentTarget;
636 + allowedReadRoots: ReadonlyArray<string>;
637 + helperDebugLog: HelperDebugLog;
638 };
639
516 -export const invokeAcpSubAgent = async ({
517 - prompt,
640 +// Turns the accumulated agent text into the final response, retrying once with
641 +// a structured-repair prompt when a structured schema was requested and the
642 +// first finalize attempt failed. Non-structured failures propagate unchanged.
643 +const finalizeWithStructuredRepair = ({
644 + client,
645 options,
646 master,
647 target,
521 - allowedReadRoots,
648 + structuredOutputMcp,
649 helperDebugLog,
650 + runPrompt,
651 + stderrSuffix,
652 }: {
524 - prompt: string;
653 + client: RunSubAgentClient;
654 options: InvokeAgentNormalizedOptions;
655 master: MasterKind;
656 target: InvokeAgentTarget;
528 - allowedReadRoots: ReadonlyArray<string>;
657 + structuredOutputMcp: StructuredOutputMcpContext | null;
658 helperDebugLog: HelperDebugLog;
530 -}): Promise<InvokeAgentResponse> => {
531 - const structuredOutputMcp = createStructuredOutputMcpContext({
532 - options,
533 - helperDebugLog,
534 - });
535 - const resolved = resolveAcpAdapterCommand(target);
536 - helperDebugLog('subAgent.acp.resolve', {
537 - target,
538 - source: resolved.source,
539 - command: resolved.cmd[0],
540 - args: resolved.cmd.slice(1),
659 + runPrompt: (text: string) => Effect.Effect<acp.PromptResponse, AcpInvokeError>;
660 + stderrSuffix: () => string;
661 +}): Effect.Effect<InvokeAgentResponse, unknown, FileSystem.FileSystem> => {
662 + const finalizeText = Effect.try({
663 + try: () => finalizeInvokeAgentText(client.getText(), options),
664 + catch: error => error,
665 });
666
543 - const { CLAUDECODE: _, ...childEnv } = process.env;
544 - const child = spawn(resolved.cmd[0]!, resolved.cmd.slice(1), {
545 - cwd: process.cwd(),
546 - env: resolved.env
547 - ? {
548 - ...childEnv,
549 - ...resolved.env,
667 + return finalizeText.pipe(
668 + Effect.map(payload => toInvokeAgentResponse(master, target, payload)),
669 + Effect.catchAll(error => {
670 + const structuredSchema = options.structuredSchema;
671 + if (!structuredSchema) {
672 + return Effect.fail(error);
673 + }
674 +
675 + return Effect.gen(function* () {
676 + helperDebugLog('subAgent.acp.structured_repair', {
677 + target,
678 + reason: error instanceof Error ? error.message : String(error),
679 + });
680 +
681 + const repairResponse = yield* runPrompt(
682 + buildStructuredRepairPrompt(
683 + structuredSchema,
684 + structuredOutputMcp ? ACP_STRUCTURED_OUTPUT_TOOL_NAME : undefined
685 + )
686 + );
687 +
688 + if (repairResponse.stopReason === 'cancelled') {
689 + return yield* Effect.fail(
690 + createFallbackError(
691 + 'prompt_failed',
692 + `${target} ACP repair prompt was cancelled${stderrSuffix()}`
693 + )
694 + );
695 }
551 - : childEnv,
552 - stdio: ['pipe', 'pipe', 'pipe'],
553 - });
696
555 - let stderr = '';
556 - child.stderr?.setEncoding('utf8');
557 - child.stderr?.on('data', chunk => {
558 - stderr += chunk;
559 - });
697 + const repairedStructuredOutput = yield* maybeReadStructuredOutputFromTool({
698 + context: structuredOutputMcp,
699 + options,
700 + helperDebugLog,
701 + });
702 + if (repairedStructuredOutput !== undefined) {
703 + return toInvokeAgentResponse(master, target, {
704 + result: null,
705 + structuredOutput: repairedStructuredOutput,
706 + });
707 + }
708
561 - const closePromise = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(
562 - (resolve, reject) => {
563 - child.once('error', reject);
564 - child.once('close', (code, signal) => resolve({ code, signal }));
565 - }
709 + const payload = yield* finalizeText;
710 + return toInvokeAgentResponse(master, target, payload);
711 + });
712 + })
713 );
714 +};
715
568 - if (!child.stdin || !child.stdout) {
569 - child.kill();
570 - throw createFallbackError('spawn_failed', `Failed to spawn ${target} ACP adapter.`);
571 - }
716 +const invokeAcpSubAgentEffect = ({
717 + prompt,
718 + options,
719 + master,
720 + target,
721 + allowedReadRoots,
722 + helperDebugLog,
723 +}: InvokeAcpSubAgentParams) =>
724 + Effect.gen(function* () {
725 + const pathApi = yield* Path.Path;
726 + const nodeOs = yield* NodeOs;
727
573 - const client = new RunSubAgentClient(helperDebugLog, [
574 - ...new Set(allowedReadRoots.map(root => path.resolve(root))),
575 - ]);
576 - const stream = acp.ndJsonStream(
577 - Writable.toWeb(child.stdin) as unknown as WritableStream<Uint8Array>,
578 - Readable.toWeb(child.stdout) as unknown as ReadableStream<Uint8Array>
579 - );
580 - const connection = new acp.ClientSideConnection(() => client, stream);
728 + const structuredOutputMcp = yield* createStructuredOutputMcpContext({
729 + options,
730 + helperDebugLog,
731 + });
732 + yield* Effect.addFinalizer(() =>
733 + structuredOutputMcp ? structuredOutputMcp.cleanup : Effect.void
734 + );
735
582 - try {
583 - const initialized = await connection
584 - .initialize({
585 - protocolVersion: acp.PROTOCOL_VERSION,
586 - clientCapabilities: {},
736 + const resolved = yield* resolveAcpAdapterCommand(target);
737 + helperDebugLog('subAgent.acp.resolve', {
738 + target,
739 + source: resolved.source,
740 + command: resolved.cmd[0],
741 + args: resolved.cmd.slice(1),
742 + });
743 +
744 + // The Claude Code CLI refuses to start when it inherits CLAUDECODE=1 (its
745 + // nested-session guard checks `process.env.CLAUDECODE === "1"`). The
746 + // platform Command executor always spreads process.env into the child, so
747 + // the variable cannot be dropped; mask it with an empty string instead —
748 + // falsy and distinct from the guarded "1" — only when the parent has it set.
749 + const claudeCode = yield* Config.option(Config.string('CLAUDECODE'));
750 + const childEnv: Record<string, string> = {
751 + ...(Option.isSome(claudeCode) ? { CLAUDECODE: '' } : {}),
752 + ...(resolved.env ?? {}),
753 + };
754 +
755 + const stdinQueue = yield* Queue.bounded<Uint8Array>(16);
756 + const [executable, ...commandArgs] = resolved.cmd;
757 + const command = Command.make(executable, ...commandArgs).pipe(Command.env(childEnv));
758 +
759 + const child = yield* Command.start(command).pipe(
760 + Effect.mapError(error =>
761 + createFallbackError('spawn_failed', `Failed to spawn ${target} ACP adapter.`, error)
762 + )
763 + );
764 +
765 + // Teardown parity with the previous finally block: SIGTERM the child, wait
766 + // for it to exit for at most 200ms, then SIGKILL it if it is still alive.
767 + // Registered after Command.start so it runs before the executor's own
768 + // scope finalizer (which would otherwise await a stubborn child forever).
769 + yield* Effect.addFinalizer(() =>
770 + Effect.gen(function* () {
771 + yield* Effect.interruptible(child.kill('SIGTERM')).pipe(
772 + Effect.timeout('200 millis'),
773 + Effect.ignore
774 + );
775 + const stillRunning = yield* child.isRunning.pipe(Effect.orElseSucceed(() => false));
776 + if (stillRunning) {
777 + yield* Effect.ignore(child.kill('SIGKILL'));
778 + }
779 })
588 - .catch(error => {
589 - throw createFallbackError(
780 + );
781 +
782 + let stderrText = '';
783 + yield* Stream.runForEach(Stream.decodeText(child.stderr), text =>
784 + Effect.sync(() => {
785 + stderrText += text;
786 + })
787 + ).pipe(Effect.ignore, Effect.forkScoped);
788 + const stderrSuffix = () => (stderrText.trim() ? `: ${stderrText.trim()}` : '');
789 +
790 + yield* Stream.run(Stream.fromQueue(stdinQueue), child.stdin).pipe(
791 + Effect.ignore,
792 + Effect.forkScoped
793 + );
794 +
795 + const client = new RunSubAgentClient(
796 + helperDebugLog,
797 + [...new Set(allowedReadRoots.map(root => pathApi.resolve(root)))],
798 + pathApi,
799 + nodeOs.homedir
800 + );
801 + const stream = acp.ndJsonStream(
802 + writableStreamFromQueue(stdinQueue),
803 + Stream.toReadableStream(child.stdout)
804 + );
805 + const connection = new acp.ClientSideConnection(() => client, stream);
806 +
807 + const initialized = yield* Effect.tryPromise({
808 + try: () =>
809 + connection.initialize({
810 + protocolVersion: acp.PROTOCOL_VERSION,
811 + clientCapabilities: {},
812 + }),
813 + catch: error =>
814 + createFallbackError(
815 'initialize_failed',
591 - `${target} ACP initialize failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,
816 + `${target} ACP initialize failed${stderrSuffix()}`,
817 error
593 - );
594 - });
818 + ),
819 + });
820
821 helperDebugLog('subAgent.acp.initialized', {
822 target,
823 protocolVersion: initialized.protocolVersion,
824 });
825
601 - const session = await connection
602 - .newSession({
603 - cwd: process.cwd(),
604 - mcpServers: structuredOutputMcp ? [structuredOutputMcp.mcpServer] : [],
605 - })
606 - .catch(error => {
607 - throw createFallbackError(
826 + const session = yield* Effect.tryPromise({
827 + try: () =>
828 + connection.newSession({
829 + cwd: process.cwd(),
830 + mcpServers: structuredOutputMcp ? [structuredOutputMcp.mcpServer] : [],
831 + }),
832 + catch: error =>
833 + createFallbackError(
834 'session_failed',
609 - `${target} ACP session creation failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,
835 + `${target} ACP session creation failed${stderrSuffix()}`,
836 error
611 - );
612 - });
837 + ),
838 + });
839
840 helperDebugLog('subAgent.acp.session', {
841 target,
@@ -617,30 +843,28 @@ export const invokeAcpSubAgent = async ({
843 });
844
845 if (typeof options.model === 'string' && options.model.trim().length > 0) {
620 - const setSessionModel = (connection as LegacySetSessionModelConnection)
621 - .unstable_setSessionModel;
622 - try {
623 - if (typeof setSessionModel !== 'function') {
624 - throw new Error('ACP session model selection is not supported by this connection');
625 - }
846 + const model = options.model.trim();
847 + const setSessionModel = getLegacySetSessionModel(connection);
848 + const modelFailure =
849 + setSessionModel === undefined
850 + ? 'ACP session model selection is not supported by this connection'
851 + : yield* Effect.tryPromise({
852 + try: () => setSessionModel({ sessionId: session.sessionId, modelId: model }),
853 + catch: error => (error instanceof Error ? error.message : String(error)),
854 + }).pipe(
855 + Effect.match({
856 + onSuccess: (): string | undefined => undefined,
857 + onFailure: message => message,
858 + })
859 + );
860
627 - await setSessionModel.call(connection, {
628 - sessionId: session.sessionId,
629 - modelId: options.model.trim(),
630 - });
631 - helperDebugLog('subAgent.acp.model', {
632 - target,
633 - model: options.model.trim(),
634 - applied: true,
635 - });
636 - } catch (error) {
637 - helperDebugLog('subAgent.acp.model', {
638 - target,
639 - model: options.model.trim(),
640 - applied: false,
641 - error: error instanceof Error ? error.message : String(error),
642 - });
643 - }
861 + helperDebugLog('subAgent.acp.model', {
862 + target,
863 + model,
864 + ...(modelFailure === undefined
865 + ? { applied: true }
866 + : { applied: false, error: modelFailure }),
867 + });
868 }
869
870 const promptText =
@@ -651,37 +875,36 @@ export const invokeAcpSubAgent = async ({
875 ACP_STRUCTURED_OUTPUT_TOOL_NAME
876 )
877 : buildStructuredPrompt(prompt, options.structuredSchema);
654 - const runPrompt = async (promptText: string) =>
655 - connection
656 - .prompt({
657 - sessionId: session.sessionId,
658 - prompt: [{ type: 'text', text: promptText }],
659 - })
660 - .catch(error => {
661 - if (connection.signal.aborted) {
662 - throw createFallbackError(
663 - 'connection_closed',
664 - `${target} ACP connection closed before prompt completion${stderr.trim() ? `: ${stderr.trim()}` : ''}`,
665 - error
666 - );
667 - }
668 - throw createFallbackError(
669 - 'prompt_failed',
670 - `${target} ACP prompt failed${stderr.trim() ? `: ${stderr.trim()}` : ''}`,
671 - error
672 - );
673 - });
878 + const runPrompt = (text: string) =>
879 + Effect.tryPromise({
880 + try: () =>
881 + connection.prompt({
882 + sessionId: session.sessionId,
883 + prompt: [{ type: 'text', text }],
884 + }),
885 + catch: error =>
886 + connection.signal.aborted
887 + ? createFallbackError(
888 + 'connection_closed',
889 + `${target} ACP connection closed before prompt completion${stderrSuffix()}`,
890 + error
891 + )
892 + : createFallbackError(
893 + 'prompt_failed',
894 + `${target} ACP prompt failed${stderrSuffix()}`,
895 + error
896 + ),
897 + });
898
675 - const response = await runPrompt(promptText);
899 + const response = yield* runPrompt(promptText);
900
901 if (response.stopReason === 'cancelled') {
678 - throw createFallbackError(
679 - 'prompt_failed',
680 - `${target} ACP prompt was cancelled${stderr.trim() ? `: ${stderr.trim()}` : ''}`
902 + return yield* Effect.fail(
903 + createFallbackError('prompt_failed', `${target} ACP prompt was cancelled${stderrSuffix()}`)
904 );
905 }
906
684 - const structuredOutput = maybeReadStructuredOutputFromTool({
907 + const structuredOutput = yield* maybeReadStructuredOutputFromTool({
908 context: structuredOutputMcp,
909 options,
910 helperDebugLog,
@@ -693,58 +916,29 @@ export const invokeAcpSubAgent = async ({
916 });
917 }
918
696 - let payload: Pick<InvokeAgentResponse, 'result' | 'structuredOutput'>;
697 - try {
698 - payload = finalizeInvokeAgentText(client.getText(), options);
699 - } catch (error) {
700 - if (!options.structuredSchema) {
701 - throw error;
702 - }
703 -
704 - helperDebugLog('subAgent.acp.structured_repair', {
705 - target,
706 - reason: error instanceof Error ? error.message : String(error),
707 - });
708 -
709 - const repairResponse = await runPrompt(
710 - buildStructuredRepairPrompt(
711 - options.structuredSchema,
712 - structuredOutputMcp ? ACP_STRUCTURED_OUTPUT_TOOL_NAME : undefined
713 - )
714 - );
715 -
716 - if (repairResponse.stopReason === 'cancelled') {
717 - throw createFallbackError(
718 - 'prompt_failed',
719 - `${target} ACP repair prompt was cancelled${stderr.trim() ? `: ${stderr.trim()}` : ''}`
720 - );
721 - }
722 -
723 - const repairedStructuredOutput = maybeReadStructuredOutputFromTool({
724 - context: structuredOutputMcp,
725 - options,
726 - helperDebugLog,
727 - });
728 - if (repairedStructuredOutput !== undefined) {
729 - return toInvokeAgentResponse(master, target, {
730 - result: null,
731 - structuredOutput: repairedStructuredOutput,
732 - });
733 - }
734 -
735 - payload = finalizeInvokeAgentText(client.getText(), options);
736 - }
919 + return yield* finalizeWithStructuredRepair({
920 + client,
921 + options,
922 + master,
923 + target,
924 + structuredOutputMcp,
925 + helperDebugLog,
926 + runPrompt,
927 + stderrSuffix,
928 + });
929 + });
930
738 - return toInvokeAgentResponse(master, target, payload);
739 - } finally {
740 - structuredOutputMcp?.cleanup();
741 - child.kill();
742 - await Promise.race([
743 - closePromise.catch(() => undefined),
744 - new Promise(resolve => setTimeout(resolve, 200)),
745 - ]);
746 - if (!child.killed) {
747 - child.kill('SIGKILL');
748 - }
931 +export const invokeAcpSubAgent = async (
932 + params: InvokeAcpSubAgentParams
933 +): Promise<InvokeAgentResponse> => {
934 + const exit = await Effect.runPromiseExit(
935 + invokeAcpSubAgentEffect(params).pipe(Effect.scoped, Effect.provide(RunSubAgentAcpLive))
936 + );
937 + if (Exit.isSuccess(exit)) {
938 + return exit.value;
939 }
940 +
941 + // Surface the original error instance (callers branch on AcpInvokeError and
942 + // its code), not a FiberFailure wrapper.
943 + throw Cause.squash(exit.cause);
944 };
ts/packages/cli/src/services/run-subagent-legacy.ts
+122 -108
@@ -1,11 +1,6 @@
1 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
2 -import * as fs from 'node:fs';
3 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
4 -import * as os from 'node:os';
5 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
6 -import * as path from 'node:path';
7 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
8 -import { spawn } from 'node:child_process';
1 +import { Command, FileSystem, Path } from '@effect/platform';
2 +import { BunContext } from '@effect/platform-bun';
3 +import { Cause, Data, Effect, Exit, Predicate, Stream } from 'effect';
4 import type { MasterKind } from 'src/services/master-detector';
5 import {
6 parseJson,
@@ -16,117 +11,131 @@ import {
11 type InvokeAgentTarget,
12 } from 'src/services/run-subagent-shared';
13
19 -const runExternalCommandText = async (
20 - cmd: ReadonlyArray<string>,
21 - helperDebugLog: HelperDebugLog
22 -) => {
23 - helperDebugLog('agent.spawn', { command: cmd[0], args: cmd.slice(1) });
24 -
25 - const child = spawn(cmd[0]!, cmd.slice(1), {
26 - cwd: process.cwd(),
27 - env: process.env,
28 - stdio: ['ignore', 'pipe', 'pipe'],
29 - });
30 -
31 - const stdoutChunks: string[] = [];
32 - const stderrChunks: string[] = [];
14 +class SubAgentCommandFailedError extends Data.TaggedError('SubAgentCommandFailedError')<{
15 + readonly command: string;
16 + readonly exitCode: number;
17 + readonly details: string;
18 +}> {
19 + override get message(): string {
20 + const suffix = this.details ? `: ${this.details}` : '';
21 + return `${this.command} failed with exit code ${this.exitCode}${suffix}`;
22 + }
23 +}
24
34 - child.stdout?.setEncoding('utf8');
35 - child.stdout?.on('data', chunk => stdoutChunks.push(chunk));
36 - child.stderr?.setEncoding('utf8');
37 - child.stderr?.on('data', chunk => stderrChunks.push(chunk));
25 +class SubAgentNonJsonOutputError extends Data.TaggedError('SubAgentNonJsonOutputError')<{
26 + readonly target: InvokeAgentTarget;
27 +}> {
28 + override get message(): string {
29 + return `${this.target} returned non-JSON output in experimental_subAgent().`;
30 + }
31 +}
32
39 - const exitCode = await new Promise<number>((resolve, reject) => {
40 - child.once('error', reject);
41 - child.once('close', code => resolve(code ?? 0));
42 - });
33 +const collectUtf8Text = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
34 + Stream.mkString(Stream.decodeText(stream));
35
44 - const stdout = stdoutChunks.join('');
45 - const stderr = stderrChunks.join('');
36 +const runExternalCommandText = (
37 + cmd: readonly [string, ...Array<string>],
38 + helperDebugLog: HelperDebugLog
39 +) =>
40 + Effect.gen(function* () {
41 + const [executable, ...commandArgs] = cmd;
42 + helperDebugLog('agent.spawn', { command: cmd[0], args: cmd.slice(1) });
43 +
44 + // The child never reads interactive input: hand it an immediately-closed
45 + // stdin pipe (EOF), matching the previous `stdio: ['ignore', ...]` spawn.
46 + const command = Command.make(executable, ...commandArgs).pipe(Command.stdin(Stream.empty));
47 +
48 + const [exitCode, stdout, stderr] = yield* Effect.scoped(
49 + Effect.flatMap(Command.start(command), child =>
50 + Effect.all([child.exitCode, collectUtf8Text(child.stdout), collectUtf8Text(child.stderr)], {
51 + concurrency: 3,
52 + })
53 + )
54 + );
55 +
56 + if (exitCode !== 0) {
57 + const details = stderr.trim() || stdout.trim();
58 + helperDebugLog('agent.error', {
59 + command: cmd[0],
60 + exitCode,
61 + stderr: stderr.trim() || undefined,
62 + });
63 + return yield* new SubAgentCommandFailedError({ command: executable, exitCode, details });
64 + }
65
47 - if (exitCode !== 0) {
48 - const details = stderr.trim() || stdout.trim();
49 - const suffix = details ? `: ${details}` : '';
50 - helperDebugLog('agent.error', {
66 + helperDebugLog('agent.done', {
67 command: cmd[0],
68 exitCode,
53 - stderr: stderr.trim() || undefined,
69 + stdoutBytes: stdout.length,
70 + stderrBytes: stderr.length,
71 });
55 - throw new Error(`${cmd[0]} failed with exit code ${exitCode}${suffix}`);
56 - }
57 -
58 - helperDebugLog('agent.done', {
59 - command: cmd[0],
60 - exitCode,
61 - stdoutBytes: stdout.length,
62 - stderrBytes: stderr.length,
72 + return { stdout, stderr, exitCode };
73 });
64 - return { stdout, stderr, exitCode };
65 -};
74
67 -const invokeClaudeLegacy = async (
75 +const invokeClaudeLegacy = (
76 prompt: string,
77 options: InvokeAgentNormalizedOptions,
78 master: MasterKind,
79 helperDebugLog: HelperDebugLog
72 -): Promise<InvokeAgentResponse> => {
73 - helperDebugLog('subAgent.prepare', {
74 - target: 'claude',
75 - transport: 'legacy',
76 - hasSchema: options.structuredSchema !== undefined,
77 - });
80 +) =>
81 + Effect.gen(function* () {
82 + helperDebugLog('subAgent.prepare', {
83 + target: 'claude',
84 + transport: 'legacy',
85 + hasSchema: options.structuredSchema !== undefined,
86 + });
87
79 - const args = ['claude', '--bare', '-p', '--output-format', 'json'];
80 - if (typeof options.model === 'string' && options.model.trim().length > 0) {
81 - args.push('--model', options.model.trim());
82 - }
83 - if (options.structuredSchema !== undefined) {
84 - args.push('--json-schema', JSON.stringify(options.structuredSchema));
85 - }
86 - args.push(prompt);
88 + const args: [string, ...Array<string>] = ['claude', '--bare', '-p', '--output-format', 'json'];
89 + if (typeof options.model === 'string' && options.model.trim().length > 0) {
90 + args.push('--model', options.model.trim());
91 + }
92 + if (options.structuredSchema !== undefined) {
93 + args.push('--json-schema', JSON.stringify(options.structuredSchema));
94 + }
95 + args.push(prompt);
96
88 - const result = await runExternalCommandText(args, helperDebugLog);
89 - const parsed = parseJson(result.stdout.trim());
90 - if (!parsed || typeof parsed !== 'object') {
91 - throw new Error('claude returned non-JSON output in experimental_subAgent().');
92 - }
97 + const result = yield* runExternalCommandText(args, helperDebugLog);
98 + const parsed = parseJson(result.stdout.trim());
99 + if (!Predicate.isRecord(parsed)) {
100 + return yield* new SubAgentNonJsonOutputError({ target: 'claude' });
101 + }
102
94 - const payload =
95 - options.structuredSchema !== undefined
96 - ? {
97 - result: null,
98 - structuredOutput: (parsed as { structured_output?: unknown }).structured_output ?? null,
99 - }
100 - : {
101 - result:
102 - typeof (parsed as { result?: unknown }).result === 'string'
103 - ? (parsed as { result: string }).result
104 - : null,
105 - structuredOutput: null,
106 - };
107 -
108 - return toInvokeAgentResponse(master, 'claude', payload);
109 -};
103 + const payload =
104 + options.structuredSchema !== undefined
105 + ? {
106 + result: null,
107 + structuredOutput: parsed.structured_output ?? null,
108 + }
109 + : {
110 + result: typeof parsed.result === 'string' ? parsed.result : null,
111 + structuredOutput: null,
112 + };
113 +
114 + return toInvokeAgentResponse(master, 'claude', payload);
115 + });
116
111 -const invokeCodexLegacy = async (
117 +const invokeCodexLegacy = (
118 prompt: string,
119 options: InvokeAgentNormalizedOptions,
120 master: MasterKind,
121 helperDebugLog: HelperDebugLog
116 -): Promise<InvokeAgentResponse> => {
117 - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-invoke-agent-'));
118 - const outputPath = path.join(tempDir, 'last-message.txt');
119 - const args = [
120 - 'codex',
121 - 'exec',
122 - '--skip-git-repo-check',
123 - '--sandbox',
124 - 'read-only',
125 - '-o',
126 - outputPath,
127 - ];
128 -
129 - try {
122 +) =>
123 + Effect.gen(function* () {
124 + const fs = yield* FileSystem.FileSystem;
125 + const path = yield* Path.Path;
126 +
127 + const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: 'composio-invoke-agent-' });
128 + const outputPath = path.join(tempDir, 'last-message.txt');
129 + const args: [string, ...Array<string>] = [
130 + 'codex',
131 + 'exec',
132 + '--skip-git-repo-check',
133 + '--sandbox',
134 + 'read-only',
135 + '-o',
136 + outputPath,
137 + ];
138 +
139 helperDebugLog('subAgent.prepare', {
140 target: 'codex',
141 transport: 'legacy',
@@ -139,14 +148,14 @@ const invokeCodexLegacy = async (
148
149 if (options.structuredSchema !== undefined) {
150 const schemaPath = path.join(tempDir, 'schema.json');
142 - fs.writeFileSync(schemaPath, JSON.stringify(options.structuredSchema), 'utf8');
151 + yield* fs.writeFileString(schemaPath, JSON.stringify(options.structuredSchema));
152 args.push('--output-schema', schemaPath);
153 }
154
155 args.push(prompt);
147 - await runExternalCommandText(args, helperDebugLog);
156 + yield* runExternalCommandText(args, helperDebugLog);
157
149 - const text = fs.readFileSync(outputPath, 'utf8').trim();
158 + const text = (yield* fs.readFileString(outputPath)).trim();
159 if (options.structuredSchema !== undefined) {
160 return toInvokeAgentResponse(master, 'codex', {
161 result: null,
@@ -158,10 +167,7 @@ const invokeCodexLegacy = async (
167 result: text,
168 structuredOutput: null,
169 });
161 - } finally {
162 - fs.rmSync(tempDir, { recursive: true, force: true });
163 - }
164 -};
170 + }).pipe(Effect.scoped);
171
172 export const invokeLegacySubAgent = async ({
173 prompt,
@@ -176,9 +182,17 @@ export const invokeLegacySubAgent = async ({
182 target: InvokeAgentTarget;
183 helperDebugLog: HelperDebugLog;
184 }): Promise<InvokeAgentResponse> => {
179 - if (target === 'claude') {
180 - return invokeClaudeLegacy(prompt, options, master, helperDebugLog);
185 + const program =
186 + target === 'claude'
187 + ? invokeClaudeLegacy(prompt, options, master, helperDebugLog)
188 + : invokeCodexLegacy(prompt, options, master, helperDebugLog);
189 +
190 + const exit = await Effect.runPromiseExit(Effect.provide(program, BunContext.layer));
191 + if (Exit.isSuccess(exit)) {
192 + return exit.value;
193 }
194
183 - return invokeCodexLegacy(prompt, options, master, helperDebugLog);
195 + // Surface the original error instance (same message callers matched on
196 + // before), not a FiberFailure wrapper.
197 + throw Cause.squash(exit.cause);
198 };
ts/packages/cli/src/services/run-subagent-output-mcp.ts
+8 -3
@@ -4,10 +4,13 @@ import process from 'node:process';
4 import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
5 import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
6 import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7 +import { Effect } from 'effect';
8 import {
9 ACP_STRUCTURED_OUTPUT_TOOL_NAME,
10 buildStructuredOutputToolSchema,
11 + decodeStructuredSchemaJson,
12 } from 'src/services/run-subagent-shared';
13 +import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';
14
15 const readFlag = (name: string): string => {
16 const index = process.argv.indexOf(name);
@@ -22,7 +25,7 @@ const main = async (): Promise<void> => {
25 const schemaFilePath = readFlag('--schema-file');
26 const resultFilePath = readFlag('--result-file');
27 const schemaText = fs.readFileSync(schemaFilePath, 'utf8');
25 - const structuredSchema = JSON.parse(schemaText) as Record<string, unknown>;
28 + const structuredSchema = decodeStructuredSchemaJson(schemaText);
29 const toolInputSchema = jsonSchemaToZod(buildStructuredOutputToolSchema(structuredSchema));
30
31 const server = new McpServer({
@@ -57,7 +60,9 @@ const main = async (): Promise<void> => {
60
61 void main().catch(error => {
62 const message = error instanceof Error ? (error.stack ?? error.message) : String(error);
60 - // eslint-disable-next-line no-restricted-syntax -- migrated with the typed-error slice (PR 8 of this stack)
61 - process.stderr.write(`${message}\n`);
63 + Effect.gen(function* () {
64 + const ui = yield* TerminalUI;
65 + yield* ui.error(message);
66 + }).pipe(Effect.provide(TerminalUILive), Effect.runSync);
67 process.exit(1);
68 });
ts/packages/cli/src/services/run-subagent-shared.ts
+71 -55
@@ -1,3 +1,5 @@
1 +import { Either, Predicate, Schema } from 'effect';
2 +import { JsonRecordSchema } from 'src/effects/json';
3 import type { MasterKind } from 'src/services/master-detector';
4
5 export type InvokeAgentTarget = 'claude' | 'codex';
@@ -46,12 +48,19 @@ export class AcpInvokeError extends Error {
48 }
49 }
50
51 +const isAcpInvokeFailure = (value: unknown): value is AcpInvokeFailure =>
52 + value === 'adapter_not_found' ||
53 + value === 'spawn_failed' ||
54 + value === 'initialize_failed' ||
55 + value === 'session_failed' ||
56 + value === 'prompt_failed' ||
57 + value === 'connection_closed';
58 +
59 export const isAcpInvokeError = (value: unknown): value is AcpInvokeError =>
50 - !!value &&
51 - typeof value === 'object' &&
52 - (value as { name?: unknown }).name === 'AcpInvokeError' &&
53 - typeof (value as { message?: unknown }).message === 'string' &&
54 - typeof (value as { code?: unknown }).code === 'string';
60 + Predicate.isRecord(value) &&
61 + value.name === 'AcpInvokeError' &&
62 + typeof value.message === 'string' &&
63 + isAcpInvokeFailure(value.code);
64
65 export const toInvokeAgentResponse = (
66 master: MasterKind,
@@ -69,26 +78,29 @@ export const toInvokeAgentResponse = (
78 : {}),
79 });
80
81 +/**
82 + * Sync JSON probe shared with the non-Effect child-process runtime; `Either`
83 + * is pure data from the already-bundled `effect` package, so it is safe there.
84 + */
85 +const parseJsonEither = (text: string): Either.Either<unknown, unknown> =>
86 + Either.try((): unknown => JSON.parse(text));
87 +
88 export const parseJson = (text: string): unknown => {
89 const value = text.trim();
90 if (!value) {
91 return undefined;
92 }
77 - try {
78 - return JSON.parse(value);
79 - } catch {
80 - return value;
81 - }
93 + // Non-JSON sub-agent stdout is returned verbatim by design.
94 + return Either.getOrElse(parseJsonEither(value), (): unknown => value);
95 };
96
97 +const decodeStructuredSchema = Schema.decodeUnknownSync(Schema.parseJson(JsonRecordSchema));
98 +
99 +export const decodeStructuredSchemaJson = (text: string): Record<string, unknown> =>
100 + decodeStructuredSchema(text);
101 +
102 const summarizeValidationError = (error: unknown): string => {
85 - const issues =
86 - error &&
87 - typeof error === 'object' &&
88 - 'issues' in error &&
89 - Array.isArray((error as { issues?: unknown[] }).issues)
90 - ? (error as { issues: Array<{ path?: unknown[]; message?: unknown }> }).issues
91 - : [];
103 + const issues = Predicate.isRecord(error) && Array.isArray(error.issues) ? error.issues : [];
104
105 if (issues.length === 0) {
106 return 'Invalid structured output.';
@@ -97,6 +109,9 @@ const summarizeValidationError = (error: unknown): string => {
109 return issues
110 .slice(0, 5)
111 .map(issue => {
112 + if (!Predicate.isRecord(issue)) {
113 + return '<root>: Invalid value';
114 + }
115 const path =
116 Array.isArray(issue.path) && issue.path.length > 0 ? issue.path.join('.') : '<root>';
117 const message = typeof issue.message === 'string' ? issue.message : 'Invalid value';
@@ -165,13 +180,8 @@ export const unwrapStructuredOutputToolPayload = (
180 return payload;
181 }
182
168 - if (
169 - payload &&
170 - typeof payload === 'object' &&
171 - !Array.isArray(payload) &&
172 - ACP_STRUCTURED_OUTPUT_WRAPPER_KEY in payload
173 - ) {
174 - return (payload as Record<string, unknown>)[ACP_STRUCTURED_OUTPUT_WRAPPER_KEY];
183 + if (Predicate.isRecord(payload) && ACP_STRUCTURED_OUTPUT_WRAPPER_KEY in payload) {
184 + return payload[ACP_STRUCTURED_OUTPUT_WRAPPER_KEY];
185 }
186
187 return payload;
@@ -239,11 +249,12 @@ const tryParseStructuredJson = (text: string): unknown | undefined => {
249 return undefined;
250 }
251
242 - try {
243 - return JSON.parse(trimmed);
244 - } catch {
245 - // Fall through to more permissive extraction for agents that emit a short
246 - // status line before the final JSON payload.
252 + // A parse failure here is the signal to fall through to more permissive
253 + // extraction for agents that emit a short status line before the final JSON
254 + // payload, not an error to surface.
255 + const direct = parseJsonEither(trimmed);
256 + if (Either.isRight(direct)) {
257 + return direct.right;
258 }
259
260 const fencedMatches = [...trimmed.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];
@@ -253,10 +264,11 @@ const tryParseStructuredJson = (text: string): unknown | undefined => {
264 continue;
265 }
266
256 - try {
257 - return JSON.parse(candidate);
258 - } catch {
259 - // Keep scanning for a valid fenced block.
267 + // Probes each fenced block for valid JSON; an invalid block just advances
268 + // the scan to the next one.
269 + const fenced = parseJsonEither(candidate);
270 + if (Either.isRight(fenced)) {
271 + return fenced.right;
272 }
273 }
274
@@ -333,29 +345,33 @@ const tryParseStructuredJson = (text: string): unknown | undefined => {
345 }
346
347 const candidate = trimmed.slice(start, end + 1);
336 - try {
337 - const parsed = JSON.parse(candidate);
338 - const nextCandidate = {
339 - length: candidate.length,
340 - start,
341 - isObject: !Array.isArray(parsed) && parsed !== null && typeof parsed === 'object',
342 - value: parsed,
343 - };
348 + // Probes each balanced {...}/[...] substring for valid JSON inside a
349 + // tight scanning loop; a failure just skips the candidate so the scan can
350 + // keep looking for a larger valid JSON payload.
351 + const parsedCandidate = parseJsonEither(candidate);
352 + if (Either.isLeft(parsedCandidate)) {
353 + continue;
354 + }
355
345 - if (
346 - !bestCandidate ||
347 - nextCandidate.length > bestCandidate.length ||
348 - (nextCandidate.length === bestCandidate.length &&
349 - nextCandidate.isObject &&
350 - !bestCandidate.isObject) ||
351 - (nextCandidate.length === bestCandidate.length &&
352 - nextCandidate.isObject === bestCandidate.isObject &&
353 - nextCandidate.start < bestCandidate.start)
354 - ) {
355 - bestCandidate = nextCandidate;
356 - }
357 - } catch {
358 - // Keep scanning for a larger valid JSON payload.
356 + const parsed = parsedCandidate.right;
357 + const nextCandidate = {
358 + length: candidate.length,
359 + start,
360 + isObject: !Array.isArray(parsed) && parsed !== null && typeof parsed === 'object',
361 + value: parsed,
362 + };
363 +
364 + if (
365 + !bestCandidate ||
366 + nextCandidate.length > bestCandidate.length ||
367 + (nextCandidate.length === bestCandidate.length &&
368 + nextCandidate.isObject &&
369 + !bestCandidate.isObject) ||
370 + (nextCandidate.length === bestCandidate.length &&
371 + nextCandidate.isObject === bestCandidate.isObject &&
372 + nextCandidate.start < bestCandidate.start)
373 + ) {
374 + bestCandidate = nextCandidate;
375 }
376 }
377
ts/packages/cli/src/services/setup.ts
+239 -197
@@ -1,5 +1,5 @@
1 -import { Command } from '@effect/platform';
2 -import { Data, Effect } from 'effect';
1 +import { Command, Error as PlatformError } from '@effect/platform';
2 +import { Data, Effect, Either, Option, Predicate, Schema } from 'effect';
3 import semver from 'semver';
4 import { CommandRunner, type CommandResult } from './command-runner';
5 import { SetupSkillInstaller } from './setup-skill-installer';
@@ -120,23 +120,40 @@ const MINIMUM_CODEX_SETUP_VERSION = '0.139.0';
120 export class SetupCommandError extends Data.TaggedError('services/SetupCommandError')<{
121 readonly message: string;
122 readonly operation: 'setup' | 'uninstall';
123 + readonly cause?: unknown;
124 }> {}
125
125 -const asRecord = (value: unknown): Record<string, unknown> | undefined => {
126 - if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined;
127 - return value as Record<string, unknown>;
128 -};
126 +type SetupFailureStage = 'detect' | 'inspect' | 'validate' | 'mutate' | 'verify' | 'skill';
127
130 -const isRecord = (value: unknown): value is Record<string, unknown> =>
131 - asRecord(value) !== undefined;
128 +export class SetupProcessError extends Data.TaggedError('services/SetupProcessError')<{
129 + readonly message: string;
130 + readonly target: AgentHost;
131 + readonly stage: SetupFailureStage;
132 + readonly cause?: unknown;
133 +}> {}
134
133 -const parseJson = (value: string): unknown => {
134 - try {
135 - return JSON.parse(value) as unknown;
136 - } catch {
137 - return undefined;
138 - }
139 -};
135 +const setupProcessError = (params: {
136 + readonly adapter: SetupTargetAdapter;
137 + readonly stage: SetupFailureStage;
138 + readonly message: string;
139 + readonly cause?: unknown;
140 +}) =>
141 + new SetupProcessError({
142 + message: params.message,
143 + target: params.adapter.target,
144 + stage: params.stage,
145 + ...(params.cause === undefined ? {} : { cause: params.cause }),
146 + });
147 +
148 +const asRecord = (value: unknown): Record<string, unknown> | undefined =>
149 + Predicate.isRecord(value) ? value : undefined;
150 +
151 +const decodeJsonOption = Schema.decodeUnknownOption(Schema.parseJson());
152 +
153 +const parseJson = (value: string): unknown | undefined =>
154 + Option.getOrUndefined(decodeJsonOption(value));
155 +
156 +const isRecord = Predicate.isRecord;
157
158 const recordsFrom = (
159 value: unknown,
@@ -174,21 +191,21 @@ const normalizeGitHubRepository = (value: string): string | undefined => {
191
192 let repository = trimmed;
193 if (/^[a-z][a-z0-9+.-]*:\/\//i.test(repository)) {
177 - try {
178 - const url = new URL(repository);
179 - const isCanonicalGitHubUrl =
180 - url.protocol === 'https:' &&
181 - url.hostname.toLowerCase() === 'github.com' &&
182 - url.port === '' &&
183 - url.username === '' &&
184 - url.password === '' &&
185 - url.search === '' &&
186 - url.hash === '';
187 - if (!isCanonicalGitHubUrl) return undefined;
188 - repository = url.pathname;
189 - } catch {
190 - return undefined;
191 - }
194 + // new URL() throws on malformed input; an unparseable repository string
195 + // simply normalizes to undefined.
196 + const parsedUrl = Either.try(() => new URL(repository));
197 + if (Either.isLeft(parsedUrl)) return undefined;
198 + const url = parsedUrl.right;
199 + const isCanonicalGitHubUrl =
200 + url.protocol === 'https:' &&
201 + url.hostname.toLowerCase() === 'github.com' &&
202 + url.port === '' &&
203 + url.username === '' &&
204 + url.password === '' &&
205 + url.search === '' &&
206 + url.hash === '';
207 + if (!isCanonicalGitHubUrl) return undefined;
208 + repository = url.pathname;
209 }
210
211 repository = repository.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '');
@@ -245,29 +262,33 @@ const pluginState = (
262 const commandText = (executable: string, args: ReadonlyArray<string>) =>
263 [executable, ...args].join(' ');
264
248 -const capture = (executable: string, args: ReadonlyArray<string>) =>
265 +const capture = (
266 + adapter: SetupTargetAdapter,
267 + args: ReadonlyArray<string>,
268 + stage: Extract<SetupFailureStage, 'detect' | 'inspect'>
269 +) =>
270 Effect.gen(function* () {
271 const runner = yield* CommandRunner;
251 - return yield* runner.capture(Command.make(executable, ...args)).pipe(
272 + return yield* runner.capture(Command.make(adapter.executable, ...args)).pipe(
273 Effect.timeoutFail({
274 duration: SETUP_COMMAND_TIMEOUT,
275 onTimeout: () =>
255 - new Error(
256 - `The \`${commandText(executable, args)}\` command timed out after ${SETUP_COMMAND_TIMEOUT}.`
257 - ),
276 + setupProcessError({
277 + adapter,
278 + stage,
279 + message: `The \`${commandText(adapter.executable, args)}\` command timed out after ${SETUP_COMMAND_TIMEOUT}.`,
280 + }),
281 })
282 );
283 });
284
262 -const isCommandNotFound = (error: unknown): boolean => {
263 - if (error === null || typeof error !== 'object') return false;
264 - const record = error as Record<string, unknown>;
265 - return record._tag === 'SystemError' && record.reason === 'NotFound';
266 -};
267 -
268 -const captureOptional = (executable: string, args: ReadonlyArray<string>) =>
269 - capture(executable, args).pipe(
270 - Effect.catchIf(isCommandNotFound, () => Effect.succeed<CommandResult | undefined>(undefined))
285 +const captureOptional = (adapter: SetupTargetAdapter, args: ReadonlyArray<string>) =>
286 + capture(adapter, args, 'detect').pipe(
287 + Effect.catchIf(Schema.is(PlatformError.SystemError), error =>
288 + error.reason === 'NotFound'
289 + ? Effect.succeed<CommandResult | undefined>(undefined)
290 + : Effect.fail(error)
291 + )
292 );
293
294 const targetLabel = (target: AgentHost): string => (target === 'claude' ? 'Claude Code' : 'Codex');
@@ -315,9 +336,14 @@ const supportsInspection = (adapter: SetupTargetAdapter, versionOutput?: string)
336
337 for (const args of adapter.inspectionHelpArgs) {
338 const command = commandText(adapter.executable, args);
318 - const result = yield* capture(adapter.executable, args).pipe(
319 - Effect.mapError(
320 - error => new Error(capabilityCheckFailureMessage(adapter, command, errorMessage(error)))
339 + const result = yield* capture(adapter, args, 'detect').pipe(
340 + Effect.mapError(cause =>
341 + setupProcessError({
342 + adapter,
343 + stage: 'detect',
344 + message: capabilityCheckFailureMessage(adapter, command, errorMessage(cause)),
345 + cause,
346 + })
347 )
348 );
349 if (result.exitCode !== 0) {
@@ -336,56 +362,60 @@ const supportsInspection = (adapter: SetupTargetAdapter, versionOutput?: string)
362
363 const detectAdapter = (adapter: SetupTargetAdapter) =>
364 Effect.gen(function* () {
339 - const versionArgs = ['--version'] as const;
365 + const versionArgs = ['--version'];
366 const versionCommand = commandText(adapter.executable, versionArgs);
341 - const captureResult = yield* captureOptional(adapter.executable, versionArgs).pipe(
342 - Effect.map(result => ({ result }) as const),
343 - Effect.catchAll(error => Effect.succeed({ error } as const))
344 - );
345 - if ('error' in captureResult) {
346 - return {
347 - available: true,
348 - supported: false,
349 - unsupportedReason: capabilityCheckFailureMessage(
350 - adapter,
351 - versionCommand,
352 - errorMessage(captureResult.error)
353 - ),
354 - };
355 - }
356 - const { result } = captureResult;
357 - if (!result) return { available: false, supported: false };
358 - if (result.exitCode === 127) return { available: false, supported: false };
359 - if (result.exitCode !== 0) {
360 - return {
361 - available: true,
362 - supported: false,
363 - unsupportedReason: capabilityCheckFailureMessage(
364 - adapter,
365 - versionCommand,
366 - commandResultDetail(result)
367 - ),
368 - };
369 - }
370 -
371 - const version = result.stdout.trim() || result.stderr.trim();
372 - const support = yield* supportsInspection(adapter, version).pipe(
373 - Effect.catchAll(error =>
374 - Effect.succeed({ supported: false, reason: errorMessage(error) } as const)
375 - )
367 + return yield* captureOptional(adapter, versionArgs).pipe(
368 + Effect.matchEffect({
369 + onFailure: cause =>
370 + Effect.succeed({
371 + available: true,
372 + supported: false,
373 + unsupportedReason: capabilityCheckFailureMessage(
374 + adapter,
375 + versionCommand,
376 + errorMessage(cause)
377 + ),
378 + }),
379 + onSuccess: result => {
380 + if (!result || result.exitCode === 127) {
381 + return Effect.succeed({ available: false, supported: false });
382 + }
383 + if (result.exitCode !== 0) {
384 + return Effect.succeed({
385 + available: true,
386 + supported: false,
387 + unsupportedReason: capabilityCheckFailureMessage(
388 + adapter,
389 + versionCommand,
390 + commandResultDetail(result)
391 + ),
392 + });
393 + }
394 +
395 + const version = result.stdout.trim() || result.stderr.trim();
396 + return supportsInspection(adapter, version).pipe(
397 + Effect.match({
398 + onFailure: cause => ({ supported: false, reason: errorMessage(cause) }),
399 + onSuccess: support => support,
400 + }),
401 + Effect.map(support =>
402 + version
403 + ? {
404 + available: true,
405 + supported: support.supported,
406 + version,
407 + ...(support.supported ? {} : { unsupportedReason: support.reason }),
408 + }
409 + : {
410 + available: true,
411 + supported: support.supported,
412 + ...(support.supported ? {} : { unsupportedReason: support.reason }),
413 + }
414 + )
415 + );
416 + },
417 + })
418 );
377 - return version
378 - ? {
379 - available: true,
380 - supported: support.supported,
381 - version,
382 - ...(support.supported ? {} : { unsupportedReason: support.reason }),
383 - }
384 - : {
385 - available: true,
386 - supported: support.supported,
387 - ...(support.supported ? {} : { unsupportedReason: support.reason }),
388 - };
419 });
420
421 const commandFailureSuffix = (result: CommandResult): string => {
@@ -393,7 +423,7 @@ const commandFailureSuffix = (result: CommandResult): string => {
423 };
424
425 const errorMessage = (error: unknown): string => {
396 - if (error instanceof Error) return error.message;
426 + if (Predicate.isError(error)) return error.message;
427 return String(error);
428 };
429
@@ -411,12 +441,14 @@ const captureInspection = (
441 operation: string,
442 setupOperation: SetupOperation
443 ) =>
414 - capture(adapter.executable, args).pipe(
415 - Effect.mapError(
416 - error =>
417 - new Error(
418 - `Failed to inspect ${targetLabel(adapter.target)} ${operation}: ${errorMessage(error)}. ${recoveryHint(adapter, setupOperation)}`
419 - )
444 + capture(adapter, args, 'inspect').pipe(
445 + Effect.mapError(cause =>
446 + setupProcessError({
447 + adapter,
448 + stage: 'inspect',
449 + message: `Failed to inspect ${targetLabel(adapter.target)} ${operation}: ${errorMessage(cause)}. ${recoveryHint(adapter, setupOperation)}`,
450 + cause,
451 + })
452 )
453 );
454
@@ -428,19 +460,19 @@ const requireInspection = <T>(
460 setupOperation: SetupOperation
461 ) => {
462 if (result.exitCode !== 0) {
431 - return Effect.fail(
432 - new Error(
433 - `Failed to inspect ${targetLabel(adapter.target)} ${operation}${commandFailureSuffix(result)}. ${recoveryHint(adapter, setupOperation)}`
434 - )
435 - );
463 + return setupProcessError({
464 + adapter,
465 + stage: 'inspect',
466 + message: `Failed to inspect ${targetLabel(adapter.target)} ${operation}${commandFailureSuffix(result)}. ${recoveryHint(adapter, setupOperation)}`,
467 + });
468 }
469 const inspected = parse(result.stdout);
470 if (!inspected) {
439 - return Effect.fail(
440 - new Error(
441 - `${targetLabel(adapter.target)} returned invalid JSON while inspecting ${operation}. ${recoveryHint(adapter, setupOperation)}`
442 - )
443 - );
471 + return setupProcessError({
472 + adapter,
473 + stage: 'inspect',
474 + message: `${targetLabel(adapter.target)} returned invalid JSON while inspecting ${operation}. ${recoveryHint(adapter, setupOperation)}`,
475 + });
476 }
477 return Effect.succeed(inspected);
478 };
@@ -470,7 +502,11 @@ const inspectAdapter = (
502 }
503
504 if (!detection.supported) {
473 - return yield* Effect.fail(new Error(unsupportedInspectionMessage(adapter)));
505 + return yield* setupProcessError({
506 + adapter,
507 + stage: 'inspect',
508 + message: unsupportedInspectionMessage(adapter),
509 + });
510 }
511
512 const [marketplaces, plugins] = yield* Effect.all([
@@ -551,42 +587,66 @@ const runRequired = (
587 const result = yield* runner.capture(Command.make(adapter.executable, ...args)).pipe(
588 Effect.timeoutFail({
589 duration: SETUP_COMMAND_TIMEOUT,
554 - onTimeout: () => new Error(`${operation} timed out after ${SETUP_COMMAND_TIMEOUT}.`),
590 + onTimeout: () =>
591 + setupProcessError({
592 + adapter,
593 + stage: 'mutate',
594 + message: `${operation} timed out after ${SETUP_COMMAND_TIMEOUT}.`,
595 + }),
596 }),
556 - Effect.mapError(
557 - error =>
558 - new Error(
559 - `${operation} failed: ${errorMessage(error)}. ${recoveryHint(adapter, setupOperation)}`
560 - )
597 + Effect.mapError(cause =>
598 + setupProcessError({
599 + adapter,
600 + stage: 'mutate',
601 + message: `${operation} failed: ${errorMessage(cause)}. ${recoveryHint(adapter, setupOperation)}`,
602 + cause,
603 + })
604 )
605 );
606 if (result.exitCode !== 0) {
564 - return yield* Effect.fail(
565 - new Error(
566 - `${operation} failed${commandFailureSuffix(result)}. ${recoveryHint(adapter, setupOperation)}`
567 - )
568 - );
607 + return yield* setupProcessError({
608 + adapter,
609 + stage: 'mutate',
610 + message: `${operation} failed${commandFailureSuffix(result)}. ${recoveryHint(adapter, setupOperation)}`,
611 + });
612 }
613 });
614
615 const validateInitialState = (adapter: SetupTargetAdapter, initial: InspectedSetupTarget) => {
616 if (!initial.available) {
574 - return Effect.fail(
575 - new Error(
576 - `${adapter.executable} is not installed or not available on PATH. Install it and rerun \`composio setup --target ${adapter.target}\`.`
577 - )
578 - );
617 + return setupProcessError({
618 + adapter,
619 + stage: 'validate',
620 + message: `${adapter.executable} is not installed or not available on PATH. Install it and rerun \`composio setup --target ${adapter.target}\`.`,
621 + });
622 }
623 if (initial.marketplace_conflict) {
581 - return Effect.fail(
582 - new Error(
583 - `The ${adapter.target} marketplace named "composio" points to a different source. Run \`${adapter.marketplaceRemoveCommand}\`, then rerun \`composio setup --target ${adapter.target}\`.`
584 - )
585 - );
624 + return setupProcessError({
625 + adapter,
626 + stage: 'validate',
627 + message: `The ${adapter.target} marketplace named "composio" points to a different source. Run \`${adapter.marketplaceRemoveCommand}\`, then rerun \`composio setup --target ${adapter.target}\`.`,
628 + });
629 }
630 return Effect.void;
631 };
632
633 +const toSetupTargetResult = (params: {
634 + readonly adapter: SetupTargetAdapter;
635 + readonly final: InspectedSetupTarget;
636 + readonly pluginChanged: boolean;
637 + readonly skillChanged: boolean;
638 +}): SetupTargetResult => ({
639 + target: params.adapter.target,
640 + available: params.final.available,
641 + marketplace_configured: params.final.marketplace_configured,
642 + plugin_installed: params.final.plugin_installed,
643 + plugin_enabled: params.final.plugin_enabled,
644 + cli_skill_ready: params.final.cli_skill_ready,
645 + changed: params.pluginChanged || params.skillChanged,
646 + plugin_changed: params.pluginChanged,
647 + skill_changed: params.skillChanged,
648 +});
649 +
650 const installAdapter = (adapter: SetupTargetAdapter, initial: InspectedSetupTarget) =>
651 Effect.gen(function* () {
652 const steps: SetupStep[] = [];
@@ -607,35 +667,27 @@ const installAdapter = (adapter: SetupTargetAdapter, initial: InspectedSetupTarg
667 let skillChanged = false;
668 if (adapter.skillSource === 'standalone' && !initial.cli_skill_ready) {
669 skillChanged = yield* skillInstaller.ensureClaudeSkill.pipe(
610 - Effect.mapError(
611 - error =>
612 - new Error(
613 - `Installing the Claude Code CLI skill failed: ${errorMessage(error)}. ${recoveryHint(adapter, 'setup')}`
614 - )
670 + Effect.mapError(cause =>
671 + setupProcessError({
672 + adapter,
673 + stage: 'skill',
674 + message: `Installing the Claude Code CLI skill failed: ${errorMessage(cause)}. ${recoveryHint(adapter, 'setup')}`,
675 + cause,
676 + })
677 )
678 );
679 }
680
681 const final = yield* inspectAdapter(adapter);
682 if (!isSetupReady(final)) {
621 - return yield* Effect.fail(
622 - new Error(
623 - `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.`
624 - )
625 - );
683 + return yield* setupProcessError({
684 + adapter,
685 + stage: 'verify',
686 + 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.`,
687 + });
688 }
689
628 - return {
629 - target: adapter.target,
630 - available: final.available,
631 - marketplace_configured: final.marketplace_configured,
632 - plugin_installed: final.plugin_installed,
633 - plugin_enabled: final.plugin_enabled,
634 - cli_skill_ready: final.cli_skill_ready,
635 - changed: pluginChanged || skillChanged,
636 - plugin_changed: pluginChanged,
637 - skill_changed: skillChanged,
638 - } satisfies SetupTargetResult;
690 + return toSetupTargetResult({ adapter, final, pluginChanged, skillChanged });
691 });
692
693 const uninstallAdapter = (adapter: SetupTargetAdapter, initial: InspectedSetupTarget) =>
@@ -655,35 +707,27 @@ const uninstallAdapter = (adapter: SetupTargetAdapter, initial: InspectedSetupTa
707 let skillChanged = false;
708 if (adapter.skillSource === 'standalone') {
709 skillChanged = yield* skillInstaller.removeClaudeSkill.pipe(
658 - Effect.mapError(
659 - error =>
660 - new Error(
661 - `Removing the Claude Code CLI skill failed: ${errorMessage(error)}. ${recoveryHint(adapter, 'uninstall')}`
662 - )
710 + Effect.mapError(cause =>
711 + setupProcessError({
712 + adapter,
713 + stage: 'skill',
714 + message: `Removing the Claude Code CLI skill failed: ${errorMessage(cause)}. ${recoveryHint(adapter, 'uninstall')}`,
715 + cause,
716 + })
717 )
718 );
719 }
720
721 const final = yield* inspectAdapter(adapter, undefined, 'uninstall');
722 if (final.plugin_installed) {
669 - return yield* Effect.fail(
670 - new Error(
671 - `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.`
672 - )
673 - );
723 + return yield* setupProcessError({
724 + adapter,
725 + stage: 'verify',
726 + 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.`,
727 + });
728 }
729
676 - return {
677 - target: adapter.target,
678 - available: final.available,
679 - marketplace_configured: final.marketplace_configured,
680 - plugin_installed: final.plugin_installed,
681 - plugin_enabled: final.plugin_enabled,
682 - cli_skill_ready: final.cli_skill_ready,
683 - changed: pluginChanged || skillChanged,
684 - plugin_changed: pluginChanged,
685 - skill_changed: skillChanged,
686 - } satisfies SetupTargetResult;
730 + return toSetupTargetResult({ adapter, final, pluginChanged, skillChanged });
731 });
732
733 const FIXED_TARGETS: Readonly<Partial<Record<SetupTarget, ReadonlyArray<AgentHost>>>> = {
@@ -733,17 +777,27 @@ export const inspectSetupTargets = (
777 return inspected;
778 });
779
736 -export const installSetupTargets = (inspected: ReadonlyArray<InspectedSetupTarget>) =>
780 +const runSetupTargets = <E, R>(
781 + inspected: ReadonlyArray<InspectedSetupTarget>,
782 + runAdapter: (
783 + adapter: SetupTargetAdapter,
784 + status: InspectedSetupTarget
785 + ) => Effect.Effect<SetupTargetResult, E, R>,
786 + verb: 'Setup' | 'Uninstall'
787 +) =>
788 Effect.gen(function* () {
789 const completed: SetupTargetResult[] = [];
790 for (const status of inspected) {
740 - const result = yield* installAdapter(ADAPTERS[status.target], status).pipe(
791 + const result = yield* runAdapter(ADAPTERS[status.target], status).pipe(
792 Effect.mapError(error => {
793 if (completed.length === 0) return error;
794 const targets = completed.map(item => item.target).join(', ');
744 - return new Error(
745 - `Setup completed for ${targets} before a later target failed: ${errorMessage(error)}`
746 - );
795 + return setupProcessError({
796 + adapter: ADAPTERS[status.target],
797 + stage: 'mutate',
798 + message: `${verb} completed for ${targets} before a later target failed: ${errorMessage(error)}`,
799 + cause: error,
800 + });
801 })
802 );
803 completed.push(result);
@@ -751,20 +805,8 @@ export const installSetupTargets = (inspected: ReadonlyArray<InspectedSetupTarge
805 return completed;
806 });
807
808 +export const installSetupTargets = (inspected: ReadonlyArray<InspectedSetupTarget>) =>
809 + runSetupTargets(inspected, installAdapter, 'Setup');
810 +
811 export const uninstallSetupTargets = (inspected: ReadonlyArray<InspectedSetupTarget>) =>
755 - Effect.gen(function* () {
756 - const completed: SetupTargetResult[] = [];
757 - for (const status of inspected) {
758 - const result = yield* uninstallAdapter(ADAPTERS[status.target], status).pipe(
759 - Effect.mapError(error => {
760 - if (completed.length === 0) return error;
761 - const targets = completed.map(item => item.target).join(', ');
762 - return new Error(
763 - `Uninstall completed for ${targets} before a later target failed: ${errorMessage(error)}`
764 - );
765 - })
766 - );
767 - completed.push(result);
768 - }
769 - return completed;
770 - });
812 + runSetupTargets(inspected, uninstallAdapter, 'Uninstall');
ts/packages/cli/src/services/tool-file-uploads.ts
+72 -25
@@ -1,25 +1,35 @@
1 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
2 -import fs from 'node:fs/promises';
3 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
4 -import path from 'node:path';
1 +// This module's upload pipeline is plain async/await around the raw
2 +// @composio/client promise API. The Effect caller resolves the platform
3 +// FileSystem and Path services and passes the instances in as parameters;
4 +// `readLocalFileBytes` below is the single point where a FileSystem effect
5 +// is run to completion inside this promise pipeline.
6 +import type { FileSystem, Path } from '@effect/platform';
7 import type { Composio as RawComposioClient } from '@composio/client';
8 import { assertSafeFileUploadPath } from '@composio/core';
9 +import { Cause, Data, Effect, Exit, Predicate } from 'effect';
10 import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
11
12 type JsonSchema = Record<string, unknown>;
13
11 -const isRecord = (value: unknown): value is Record<string, unknown> =>
12 - typeof value === 'object' && value !== null && !Array.isArray(value);
14 +export class ToolFileUploadError extends Data.TaggedError('services/ToolFileUploadError')<{
15 + readonly cause?: unknown;
16 + readonly message: string;
17 + readonly reason: 'source-fetch' | 'source-read' | 'unsupported-source' | 'upload';
18 + readonly status?: number;
19 +}> {}
20
21 const isFileLike = (value: unknown): value is File =>
22 typeof File !== 'undefined' && value instanceof File;
23
17 -const isSchemaRecord = (value: unknown): value is JsonSchema => isRecord(value);
24 +const isSchemaRecord = (value: unknown): value is JsonSchema => Predicate.isRecord(value);
25 +
26 +const getSchemaVariant = (value: unknown): ReadonlyArray<JsonSchema> =>
27 + Array.isArray(value) ? value.filter(isSchemaRecord) : [];
28
29 const getSchemaVariants = (schema: JsonSchema | undefined): ReadonlyArray<JsonSchema> => [
20 - ...((Array.isArray(schema?.anyOf) ? schema.anyOf : []) as JsonSchema[]),
21 - ...((Array.isArray(schema?.oneOf) ? schema.oneOf : []) as JsonSchema[]),
22 - ...((Array.isArray(schema?.allOf) ? schema.allOf : []) as JsonSchema[]),
30 + ...getSchemaVariant(schema?.anyOf),
31 + ...getSchemaVariant(schema?.oneOf),
32 + ...getSchemaVariant(schema?.allOf),
33 ];
34
35 const transformSchema = (schema: JsonSchema): JsonSchema => {
@@ -132,10 +142,14 @@ export const findFileUploadablePaths = (
142 });
143 };
144
135 -const readFileFromUrl = async (url: string) => {
145 +const readFileFromUrl = async (path: Path.Path, url: string) => {
146 const response = await fetch(url);
147 if (!response.ok) {
138 - throw new Error(`Failed to fetch file: ${response.statusText}`);
148 + throw new ToolFileUploadError({
149 + message: `Failed to fetch file: ${response.statusText}`,
150 + reason: 'source-fetch',
151 + status: response.status,
152 + });
153 }
154
155 const bytes = new Uint8Array(await response.arrayBuffer());
@@ -149,7 +163,18 @@ const readFileFromUrl = async (url: string) => {
163 };
164 };
165
152 -const readFileFromDisk = async (filePath: string) => {
166 +// Runs the FileSystem read to completion for the plain-async pipeline above.
167 +// A failed read rejects with the underlying platform error (not a FiberFailure
168 +// wrapper), matching this module's throw-based error contract.
169 +const readLocalFileBytes = (fs: FileSystem.FileSystem, filePath: string): Promise<Uint8Array> =>
170 + Effect.runPromiseExit(fs.readFile(filePath)).then(exit =>
171 + Exit.match(exit, {
172 + onFailure: cause => Promise.reject<Uint8Array>(Cause.squash(cause)),
173 + onSuccess: bytes => Promise.resolve(bytes),
174 + })
175 + );
176 +
177 +const readFileFromDisk = async (fs: FileSystem.FileSystem, path: Path.Path, filePath: string) => {
178 // Enforce the sensitive-path denylist at the lowest-level local read, so any
179 // caller of this reader (not just `uploadToolInputFiles`) is protected. This
180 // is the single canonical guard shared with `@composio/core`; without it the
@@ -169,13 +194,19 @@ const readFileFromDisk = async (filePath: string) => {
194 'pass the copy instead.',
195 });
196 return {
172 - bytes: new Uint8Array(await fs.readFile(filePath)),
197 + // Copy into a fresh ArrayBuffer-backed view: `fetch` bodies reject the
198 + // wider ArrayBufferLike-backed Uint8Array that FileSystem returns.
199 + bytes: new Uint8Array(await readLocalFileBytes(fs, filePath)),
200 fileName: path.basename(filePath),
201 mimeType: 'application/octet-stream',
202 };
203 };
204
178 -const readUploadSource = async (file: string | File) => {
205 +const readUploadSource = async (
206 + fs: FileSystem.FileSystem,
207 + path: Path.Path,
208 + file: string | File
209 +) => {
210 if (isFileLike(file)) {
211 return {
212 bytes: new Uint8Array(await file.arrayBuffer()),
@@ -185,23 +216,28 @@ const readUploadSource = async (file: string | File) => {
216 }
217
218 if (typeof file === 'string' && /^https?:\/\//i.test(file)) {
188 - return readFileFromUrl(file);
219 + return readFileFromUrl(path, file);
220 }
221
222 if (typeof file === 'string') {
192 - return readFileFromDisk(file);
223 + return readFileFromDisk(fs, path, file);
224 }
225
195 - throw new Error('Unsupported upload source');
226 + throw new ToolFileUploadError({
227 + message: 'Unsupported upload source',
228 + reason: 'unsupported-source',
229 + });
230 };
231
232 const uploadFile = async (params: {
233 + readonly fs: FileSystem.FileSystem;
234 + readonly path: Path.Path;
235 readonly file: string | File;
236 readonly toolSlug: string;
237 readonly toolkitSlug: string;
238 readonly client: RawComposioClient;
239 }) => {
204 - const fileData = await readUploadSource(params.file);
240 + const fileData = await readUploadSource(params.fs, params.path, params.file);
241 const { createHash } = await import('node:crypto');
242 const md5 = createHash('md5').update(fileData.bytes).digest('hex');
243 const presigned = await params.client.files.createPresignedURL({
@@ -222,7 +258,11 @@ const uploadFile = async (params: {
258 });
259
260 if (!uploadResponse.ok) {
225 - throw new Error(`Failed to upload file to S3: ${uploadResponse.statusText}`);
261 + throw new ToolFileUploadError({
262 + message: `Failed to upload file to S3: ${uploadResponse.statusText}`,
263 + reason: 'upload',
264 + status: uploadResponse.status,
265 + });
266 }
267
268 return {
@@ -236,6 +276,8 @@ const hydrateFileUploads = async (
276 value: unknown,
277 schema: JsonSchema | undefined,
278 ctx: {
279 + readonly fs: FileSystem.FileSystem;
280 + readonly path: Path.Path;
281 readonly toolSlug: string;
282 readonly toolkitSlug: string;
283 readonly client: RawComposioClient;
@@ -247,6 +289,8 @@ const hydrateFileUploads = async (
289 }
290
291 return uploadFile({
292 + fs: ctx.fs,
293 + path: ctx.path,
294 file: value,
295 toolSlug: ctx.toolSlug,
296 toolkitSlug: ctx.toolkitSlug,
@@ -263,15 +307,14 @@ const hydrateFileUploads = async (
307 return nextValue;
308 }
309
266 - if (isSchemaRecord(schema?.properties) && isRecord(value)) {
310 + if (isSchemaRecord(schema?.properties) && Predicate.isRecord(value)) {
311 + const properties = schema.properties;
312 const entries = await Promise.all(
313 Object.entries(value).map(async ([key, entryValue]) => [
314 key,
315 await hydrateFileUploads(
316 entryValue,
272 - isSchemaRecord((schema.properties as Record<string, unknown>)[key])
273 - ? ((schema.properties as Record<string, unknown>)[key] as JsonSchema)
274 - : undefined,
317 + isSchemaRecord(properties[key]) ? properties[key] : undefined,
318 ctx
319 ),
320 ])
@@ -293,6 +336,8 @@ const hydrateFileUploads = async (
336 };
337
338 export const uploadToolInputFiles = async (params: {
339 + readonly fs: FileSystem.FileSystem;
340 + readonly path: Path.Path;
341 readonly toolSlug: string;
342 readonly arguments_: Record<string, unknown>;
343 readonly inputSchema: JsonSchema;
@@ -304,10 +349,12 @@ export const uploadToolInputFiles = async (params: {
349 }
350
351 const hydrated = await hydrateFileUploads(params.arguments_, params.inputSchema, {
352 + fs: params.fs,
353 + path: params.path,
354 toolSlug: params.toolSlug,
355 toolkitSlug: params.toolkitSlug ?? toolkitFromToolSlug(params.toolSlug) ?? 'unknown',
356 client: params.client,
357 });
358
312 - return isRecord(hydrated) ? hydrated : params.arguments_;
359 + return Predicate.isRecord(hydrated) ? hydrated : params.arguments_;
360 };
ts/packages/cli/src/services/tool-permissions.ts
+328 -229
@@ -1,12 +1,11 @@
1 import http from 'node:http';
2 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
3 -import fs from 'node:fs/promises';
4 -// eslint-disable-next-line no-restricted-imports -- migrated with the typed-error slice (PR 8 of this stack)
5 -import path from 'node:path';
2 +import { FileSystem, Path } from '@effect/platform';
3 import open from 'open';
4 import { detectCliPlatform } from '@composio/cli-local-tools';
8 -import { Effect, Option, Schema } from 'effect';
5 +import { Data, Effect, Option, Record as EffectRecord, Schema } from 'effect';
6 +import { JsonRecordSchema } from 'src/effects/json';
7 import { resolveCliConfigDirectorySync } from 'src/services/cli-user-config';
8 +import { collectDecodedEntries } from 'src/utils/collect-decoded-entries';
9 import {
10 detectNativeUiCallerAgent,
11 isInteractivePermissionUiDisabled,
@@ -28,55 +27,52 @@ const ALLOW_FOR_DURATION_LABEL = '1 hr';
27 const ALLOW_FOR_DURATION_MS = 60 * 60 * 1000;
28 const NO_CONNECTED_ACCOUNT = '__none__';
29
31 -export type PermissionDefaultMode = 'allow_all' | 'ask_every_call' | 'ask_once_per_session';
32 -export type PermissionOverrideState = 'always_allow' | 'always_deny' | 'ask_once' | 'ask_always';
30 export type PermissionDecision = 'allow_once' | 'allow_session' | 'deny';
31 export type PermissionApprovalStatus =
32 'always_approved' | 'cached_approved' | 'approved_once' | 'approved_for_session';
33 export type PermissionGateResult =
34 { readonly approvalStatus: PermissionApprovalStatus } | undefined;
35
39 -export interface ToolRouterPermissionsConfig {
40 - readonly default: PermissionDefaultMode;
41 - readonly overrides?: Readonly<Record<string, PermissionOverrideState>>;
42 -}
43 -
44 -export interface ConsumerPermissionSnapshot {
45 - readonly orgId: string;
46 - readonly projectId: string;
47 - readonly consumerUserId: string;
48 - readonly enhancedControlsEnabled: boolean;
49 - readonly permissions?: ToolRouterPermissionsConfig;
50 - readonly connectedAccountIds: ReadonlyArray<string>;
51 - readonly fetchedAt: number;
52 -}
53 -
54 -interface CachedAllowDecision {
55 - readonly expiresAt: number;
56 -}
57 -
58 -interface CacheFile {
59 - readonly entries: Readonly<Record<string, ConsumerPermissionSnapshot>>;
60 - readonly allowEntries?: Readonly<Record<string, CachedAllowDecision>>;
61 -}
62 -
63 -const PermissionDefaultModeSchema = Schema.Literal(
36 +const PermissionDefaultModeLiteralSchema = Schema.Literal(
37 'allow_all',
38 'ask_every_call',
39 'ask_once_per_session'
40 );
68 -const PermissionOverrideStateSchema = Schema.Literal(
41 +const PermissionOverrideStateLiteralSchema = Schema.Literal(
42 'always_allow',
43 'always_deny',
44 'ask_once',
45 'ask_always'
46 );
47 +const isPermissionDefaultMode = Schema.is(PermissionDefaultModeLiteralSchema);
48 +const isPermissionOverrideState = Schema.is(PermissionOverrideStateLiteralSchema);
49 +
50 +// The permissions API can add modes before every installed CLI has upgraded.
51 +// Preserve validation without failing open during that version-skew window:
52 +// unknown defaults and overrides decode to their interactive safe equivalents.
53 +const PermissionDefaultModeSchema = Schema.String.pipe(
54 + Schema.transform(PermissionDefaultModeLiteralSchema, {
55 + decode: value => (isPermissionDefaultMode(value) ? value : 'ask_every_call'),
56 + encode: value => value,
57 + strict: true,
58 + })
59 +);
60 +const PermissionOverrideStateSchema = Schema.String.pipe(
61 + Schema.transform(PermissionOverrideStateLiteralSchema, {
62 + decode: value => (isPermissionOverrideState(value) ? value : 'ask_always'),
63 + encode: value => value,
64 + strict: true,
65 + })
66 +);
67 const ToolRouterPermissionsConfigSchema = Schema.Struct({
68 default: PermissionDefaultModeSchema,
69 overrides: Schema.optional(
70 Schema.Record({ key: Schema.String, value: PermissionOverrideStateSchema })
71 ),
72 });
73 +export const decodeToolRouterPermissionsConfig = Schema.decodeUnknownOption(
74 + ToolRouterPermissionsConfigSchema
75 +);
76 const ConsumerPermissionSnapshotSchema = Schema.Struct({
77 orgId: Schema.String,
78 projectId: Schema.String,
@@ -86,35 +82,40 @@ const ConsumerPermissionSnapshotSchema = Schema.Struct({
82 connectedAccountIds: Schema.Array(Schema.String),
83 fetchedAt: Schema.Number,
84 });
89 -const CachedAllowDecisionSchema = Schema.Struct({
90 - expiresAt: Schema.Number,
85 +const CachedAllowDecisionSchema = Schema.Struct({ expiresAt: Schema.Number });
86 +const PermissionResolveResponseSchema = Schema.Struct({
87 + experimental: Schema.optional(
88 + Schema.Struct({ permissions: Schema.optional(ToolRouterPermissionsConfigSchema) })
89 + ),
90 +});
91 +const ConsumerConfigResponseSchema = Schema.Struct({
92 + enhanced_controls: Schema.optional(Schema.Boolean),
93 + enhancedControls: Schema.optional(Schema.Boolean),
94 });
95
93 -const UnknownRecordSchema = Schema.Record({ key: Schema.String, value: Schema.Unknown });
96 +export type PermissionDefaultMode = typeof PermissionDefaultModeSchema.Type;
97 +export type PermissionOverrideState = typeof PermissionOverrideStateSchema.Type;
98 +export type ToolRouterPermissionsConfig = typeof ToolRouterPermissionsConfigSchema.Type;
99 +export type ConsumerPermissionSnapshot = typeof ConsumerPermissionSnapshotSchema.Type;
100 +type CachedAllowDecision = typeof CachedAllowDecisionSchema.Type;
101 +// Decoding of the cache file is per-entry (decodeCacheShell + decodeSnapshotEntry /
102 +// decodeAllowEntry below), so the file shape only needs a type, not a schema value.
103 +type CacheFile = {
104 + readonly entries: Readonly<Record<string, ConsumerPermissionSnapshot>>;
105 + readonly allowEntries?: Readonly<Record<string, CachedAllowDecision>> | undefined;
106 +};
107 +type ConsumerConfigResponse = typeof ConsumerConfigResponseSchema.Type;
108 const decodeCacheShell = Schema.decodeUnknownOption(
109 Schema.parseJson(
110 Schema.Struct({
97 - entries: Schema.optional(UnknownRecordSchema),
98 - allowEntries: Schema.optional(UnknownRecordSchema),
111 + entries: Schema.optional(JsonRecordSchema),
112 + allowEntries: Schema.optional(JsonRecordSchema),
113 })
114 )
115 );
116 const decodeSnapshotEntry = Schema.decodeUnknownOption(ConsumerPermissionSnapshotSchema);
117 const decodeAllowEntry = Schema.decodeUnknownOption(CachedAllowDecisionSchema);
118
105 -const collectDecodedEntries = <A>(
106 - entries: Readonly<Record<string, unknown>> | undefined,
107 - decode: (value: unknown) => Option.Option<A>
108 -): Record<string, A> =>
109 - Object.fromEntries(
110 - Object.entries(entries ?? {}).flatMap(([key, value]) =>
111 - Option.match(decode(value), {
112 - onNone: () => [],
113 - onSome: entry => [[key, entry] as const],
114 - })
115 - )
116 - );
117 -
119 // Per-entry decode: one stale or version-skewed entry drops only itself.
120 // Discarding the whole file would also wipe all cached allow decisions and
121 // be persisted back on the next write.
@@ -127,16 +128,37 @@ export const decodeCacheFileTolerant = (raw: string): CacheFile =>
128 }),
129 });
130
130 -interface PermissionResolveResponse {
131 - readonly experimental?: {
132 - readonly permissions?: ToolRouterPermissionsConfig;
133 - };
134 -}
131 +export class ToolPermissionDeniedError extends Data.TaggedError(
132 + 'services/ToolPermissionDeniedError'
133 +)<{
134 + readonly toolSlug: string;
135 + readonly deniedBy: 'permissions' | 'user';
136 + readonly message: string;
137 +}> {}
138
136 -interface ConsumerConfigResponse {
137 - readonly enhanced_controls?: boolean;
138 - readonly enhancedControls?: boolean;
139 -}
139 +export class ToolPermissionsRequestError extends Data.TaggedError(
140 + 'services/ToolPermissionsRequestError'
141 +)<{
142 + readonly path: string;
143 + readonly message: string;
144 + readonly cause: unknown;
145 +}> {}
146 +
147 +export class ToolPermissionsCacheError extends Data.TaggedError(
148 + 'services/ToolPermissionsCacheError'
149 +)<{
150 + readonly operation: 'read' | 'write';
151 + readonly message: string;
152 + readonly cause: unknown;
153 +}> {}
154 +
155 +export class ToolPermissionPromptError extends Data.TaggedError(
156 + 'services/ToolPermissionPromptError'
157 +)<{
158 + readonly toolSlug: string;
159 + readonly message: string;
160 + readonly cause: unknown;
161 +}> {}
162
163 interface GateParams {
164 readonly toolSlug: string;
@@ -147,7 +169,7 @@ interface GateParams {
169
170 const allowDecisionMemoryCache = new Map<string, number>();
171
150 -const cachePath = () => path.join(resolveCliConfigDirectorySync(), CACHE_FILE_NAME);
172 +const cachePath = (path: Path.Path) => path.join(resolveCliConfigDirectorySync(), CACHE_FILE_NAME);
173 const cacheKey = (params: { orgId: string; projectId: string; consumerUserId: string }) =>
174 [params.orgId, params.projectId, params.consumerUserId].join(':');
175 const normalizeBaseUrl = (baseURL: string) => baseURL.replace(/\/$/, '');
@@ -159,71 +181,73 @@ const uniq = (values: ReadonlyArray<string | undefined>) => [
181 const pruneAllowEntries = (
182 entries: Readonly<Record<string, CachedAllowDecision>> | undefined,
183 now = Date.now()
162 -): Record<string, CachedAllowDecision> => {
163 - const freshEntries: Record<string, CachedAllowDecision> = {};
164 - for (const [key, entry] of Object.entries(entries ?? {})) {
165 - if (typeof entry.expiresAt === 'number' && entry.expiresAt > now) {
166 - freshEntries[key] = entry;
167 - }
168 - }
169 - return freshEntries;
170 -};
171 -
172 -const readCacheFile = async (): Promise<CacheFile> => {
173 - try {
174 - const raw = await fs.readFile(cachePath(), 'utf8');
175 - const parsed = decodeCacheFileTolerant(raw);
176 - return {
177 - entries: parsed.entries,
178 - allowEntries: pruneAllowEntries(parsed.allowEntries),
179 - };
180 - } catch {
181 - return { entries: {} };
182 - }
183 -};
184 -
185 -const writeCacheFile = async (cache: CacheFile): Promise<void> => {
186 - const targetPath = cachePath();
187 - await fs.mkdir(path.dirname(targetPath), { recursive: true });
188 -
189 - const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${crypto.randomUUID()}.tmp`;
190 - try {
191 - await fs.writeFile(
192 - tempPath,
193 - `${JSON.stringify(
194 - {
195 - entries: cache.entries,
196 - allowEntries: pruneAllowEntries(cache.allowEntries),
197 - } satisfies CacheFile,
198 - null,
199 - 2
200 - )}\n`,
201 - 'utf8'
202 - );
203 - await fs.rename(tempPath, targetPath);
204 - } catch (error) {
205 - await fs.rm(tempPath, { force: true }).catch(() => undefined);
206 - throw error;
207 - }
208 -};
184 +): Record<string, CachedAllowDecision> =>
185 + EffectRecord.filter(
186 + entries ?? {},
187 + entry => typeof entry.expiresAt === 'number' && entry.expiresAt > now
188 + );
189
210 -let cacheWriteQueue: Promise<void> = Promise.resolve();
190 +// A missing or unreadable cache file degrades to an empty cache.
191 +const readCacheFile = (fs: FileSystem.FileSystem, path: Path.Path): Effect.Effect<CacheFile> =>
192 + fs.readFileString(cachePath(path)).pipe(
193 + Effect.map((raw): CacheFile => {
194 + const parsed = decodeCacheFileTolerant(raw);
195 + return {
196 + entries: parsed.entries,
197 + allowEntries: pruneAllowEntries(parsed.allowEntries),
198 + };
199 + }),
200 + Effect.orElseSucceed((): CacheFile => ({ entries: {} }))
201 + );
202
212 -const updateCacheFile = async (
213 - update: (current: CacheFile) => CacheFile | Promise<CacheFile>
214 -): Promise<void> => {
215 - const previous = cacheWriteQueue.catch(() => undefined);
216 - const next = previous.then(async () => {
217 - const current = await readCacheFile();
218 - await writeCacheFile(await update(current));
203 +const writeCacheFile = (fs: FileSystem.FileSystem, path: Path.Path, cache: CacheFile) =>
204 + Effect.gen(function* () {
205 + const targetPath = cachePath(path);
206 + yield* fs.makeDirectory(path.dirname(targetPath), { recursive: true });
207 +
208 + const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${crypto.randomUUID()}.tmp`;
209 + // Atomic write: on failure the temp file is dropped (best effort) and the
210 + // original error is surfaced.
211 + yield* fs
212 + .writeFileString(
213 + tempPath,
214 + `${JSON.stringify(
215 + {
216 + entries: cache.entries,
217 + allowEntries: pruneAllowEntries(cache.allowEntries),
218 + } satisfies CacheFile,
219 + null,
220 + 2
221 + )}\n`
222 + )
223 + .pipe(
224 + Effect.andThen(fs.rename(tempPath, targetPath)),
225 + Effect.onError(() => fs.remove(tempPath, { force: true }).pipe(Effect.ignore))
226 + );
227 });
228
221 - cacheWriteQueue = next.catch(() => undefined);
222 - await next;
223 -};
229 +// Serializes the read-modify-write cycles on the cache file so concurrent
230 +// writers cannot interleave (the same role the previous promise write queue
231 +// played for the plain async helpers).
232 +const cacheWriteSemaphore = Effect.unsafeMakeSemaphore(1);
233 +
234 +const updateCacheFile = (
235 + fs: FileSystem.FileSystem,
236 + path: Path.Path,
237 + update: (current: CacheFile) => CacheFile
238 +) =>
239 + cacheWriteSemaphore.withPermits(1)(
240 + readCacheFile(fs, path).pipe(
241 + Effect.flatMap(current => writeCacheFile(fs, path, update(current)))
242 + )
243 + );
244
225 -const writeCacheEntry = async (entry: ConsumerPermissionSnapshot): Promise<void> =>
226 - updateCacheFile(current => ({
245 +const writeCacheEntry = (
246 + fs: FileSystem.FileSystem,
247 + path: Path.Path,
248 + entry: ConsumerPermissionSnapshot
249 +) =>
250 + updateCacheFile(fs, path, current => ({
251 entries: {
252 ...current.entries,
253 [cacheKey(entry)]: entry,
@@ -231,14 +255,16 @@ const writeCacheEntry = async (entry: ConsumerPermissionSnapshot): Promise<void>
255 allowEntries: current.allowEntries,
256 }));
257
234 -const readCachedEntry = async (params: {
235 - orgId: string;
236 - projectId: string;
237 - consumerUserId: string;
238 -}): Promise<ConsumerPermissionSnapshot | undefined> => {
239 - const cache = await readCacheFile();
240 - return cache.entries[cacheKey(params)];
241 -};
258 +const readCachedEntry = (
259 + fs: FileSystem.FileSystem,
260 + path: Path.Path,
261 + params: {
262 + orgId: string;
263 + projectId: string;
264 + consumerUserId: string;
265 + }
266 +): Effect.Effect<ConsumerPermissionSnapshot | undefined> =>
267 + readCacheFile(fs, path).pipe(Effect.map(cache => cache.entries[cacheKey(params)]));
268
269 const isFreshForAccounts = (
270 entry: ConsumerPermissionSnapshot | undefined,
@@ -253,23 +279,26 @@ const isFreshForAccounts = (
279 const readEnhancedControlsFlag = (payload: ConsumerConfigResponse): boolean =>
280 payload.enhanced_controls === true || payload.enhancedControls === true;
281
256 -const fetchJson = async <T>({
257 - baseURL,
258 - apiKey,
259 - orgId,
260 - projectId,
261 - path,
262 - method = 'GET',
263 - body,
264 -}: {
265 - readonly baseURL: string;
266 - readonly apiKey: string;
267 - readonly orgId: string;
268 - readonly projectId: string;
269 - readonly path: string;
270 - readonly method?: 'GET' | 'POST';
271 - readonly body?: unknown;
272 -}): Promise<T> => {
282 +const fetchJson = async <A, I>(
283 + responseSchema: Schema.Schema<A, I, never>,
284 + {
285 + baseURL,
286 + apiKey,
287 + orgId,
288 + projectId,
289 + path,
290 + method = 'GET',
291 + body,
292 + }: {
293 + readonly baseURL: string;
294 + readonly apiKey: string;
295 + readonly orgId: string;
296 + readonly projectId: string;
297 + readonly path: string;
298 + readonly method?: 'GET' | 'POST';
299 + readonly body?: unknown;
300 + }
301 +): Promise<A> => {
302 const response = await fetch(`${normalizeBaseUrl(baseURL)}${path}`, {
303 method,
304 redirect: 'error',
@@ -286,7 +315,8 @@ const fetchJson = async <T>({
315 if (!response.ok) {
316 throw new Error(`HTTP ${response.status} ${response.statusText}`);
317 }
289 - return (await response.json()) as T;
318 + const responseBody: unknown = await response.json();
319 + return Schema.decodeUnknownPromise(responseSchema)(responseBody);
320 };
321
322 export const refreshConsumerPermissionSnapshot = (params: {
@@ -296,20 +326,29 @@ export const refreshConsumerPermissionSnapshot = (params: {
326 readonly connectedAccountIds?: ReadonlyArray<string>;
327 }) =>
328 Effect.gen(function* () {
329 + const fs = yield* FileSystem.FileSystem;
330 + const path = yield* Path.Path;
331 const userContext = yield* ComposioUserContext;
332 const apiKey = Option.getOrUndefined(userContext.data.apiKey);
333 if (!apiKey) return undefined;
334
335 const connectedAccountIds = uniq(params.connectedAccountIds ?? []);
304 - const config = yield* Effect.tryPromise(() =>
305 - fetchJson<ConsumerConfigResponse>({
306 - baseURL: userContext.data.baseURL,
307 - apiKey,
308 - orgId: params.orgId,
309 - projectId: params.projectId,
310 - path: '/api/v3.1/org/consumer/config',
311 - })
312 - );
336 + const config = yield* Effect.tryPromise({
337 + try: () =>
338 + fetchJson(ConsumerConfigResponseSchema, {
339 + baseURL: userContext.data.baseURL,
340 + apiKey,
341 + orgId: params.orgId,
342 + projectId: params.projectId,
343 + path: '/api/v3.1/org/consumer/config',
344 + }),
345 + catch: cause =>
346 + new ToolPermissionsRequestError({
347 + path: '/api/v3.1/org/consumer/config',
348 + message: 'Failed to fetch the org consumer config.',
349 + cause,
350 + }),
351 + });
352 const platformSupportsEnhancedControls = isEnhancedControlsPlatformSupported();
353 const remoteEnhancedControlsEnabled = readEnhancedControlsFlag(config);
354 if (remoteEnhancedControlsEnabled && !platformSupportsEnhancedControls) {
@@ -321,20 +360,27 @@ export const refreshConsumerPermissionSnapshot = (params: {
360 remoteEnhancedControlsEnabled && platformSupportsEnhancedControls;
361 const resolved =
362 enhancedControlsEnabled && connectedAccountIds.length > 0
324 - ? yield* Effect.tryPromise(() =>
325 - fetchJson<PermissionResolveResponse>({
326 - baseURL: userContext.data.baseURL,
327 - apiKey,
328 - orgId: params.orgId,
329 - projectId: params.projectId,
330 - path: '/api/v3.1/consumer/permissions/resolve',
331 - method: 'POST',
332 - body: {
333 - connected_account_ids: connectedAccountIds,
334 - default: 'ask_every_call',
335 - },
336 - })
337 - ).pipe(
363 + ? yield* Effect.tryPromise({
364 + try: () =>
365 + fetchJson(PermissionResolveResponseSchema, {
366 + baseURL: userContext.data.baseURL,
367 + apiKey,
368 + orgId: params.orgId,
369 + projectId: params.projectId,
370 + path: '/api/v3.1/consumer/permissions/resolve',
371 + method: 'POST',
372 + body: {
373 + connected_account_ids: connectedAccountIds,
374 + default: 'ask_every_call',
375 + },
376 + }),
377 + catch: cause =>
378 + new ToolPermissionsRequestError({
379 + path: '/api/v3.1/consumer/permissions/resolve',
380 + message: 'Failed to resolve consumer permissions.',
381 + cause,
382 + }),
383 + }).pipe(
384 Effect.map(response => ({
385 permissions: response.experimental?.permissions,
386 resolveFailed: false,
@@ -342,7 +388,7 @@ export const refreshConsumerPermissionSnapshot = (params: {
388 // The org said enhanced controls are ON but the policy could not
389 // be learned: fail closed to the interactive default instead of
390 // silently allowing tools the policy may explicitly deny.
345 - Effect.catchAll(error =>
391 + Effect.catchTag('services/ToolPermissionsRequestError', error =>
392 Effect.logDebug(
393 'Failed to resolve consumer permissions; failing closed to ask_every_call',
394 error
@@ -368,15 +414,22 @@ export const refreshConsumerPermissionSnapshot = (params: {
414 // A fail-closed snapshot is not persisted, so a healthy fetch replaces it
415 // on the next command instead of pinning ask_every_call for the TTL.
416 if (!resolved.resolveFailed) {
371 - yield* Effect.tryPromise(() => writeCacheEntry(snapshot)).pipe(
372 - Effect.catchAll(error =>
373 - Effect.logDebug('Failed to write the tool permissions cache', error)
417 + yield* writeCacheEntry(fs, path, snapshot).pipe(
418 + Effect.catchAll(cause =>
419 + Effect.logDebug(
420 + 'Failed to write the tool permissions cache',
421 + new ToolPermissionsCacheError({
422 + operation: 'write',
423 + message: 'Failed to write the tool permissions cache.',
424 + cause,
425 + })
426 + )
427 )
428 );
429 }
430 return snapshot;
431 }).pipe(
379 - Effect.catchAll(error =>
432 + Effect.catchTag('services/ToolPermissionsRequestError', error =>
433 Effect.gen(function* () {
434 yield* Effect.logDebug('Failed to refresh consumer permission cache', error);
435 return undefined;
@@ -391,10 +444,12 @@ export const getConsumerPermissionSnapshot = (params: {
444 readonly connectedAccountIds?: ReadonlyArray<string>;
445 }) =>
446 Effect.gen(function* () {
447 + const fs = yield* FileSystem.FileSystem;
448 + const path = yield* Path.Path;
449 const connectedAccountIds = uniq(params.connectedAccountIds ?? []);
395 - const cached = yield* Effect.tryPromise(() => readCachedEntry(params)).pipe(
396 - Effect.catchAll(() => Effect.succeed(undefined))
397 - );
450 + // Read failures are absorbed inside readCacheFile (empty cache), so an
451 + // unreadable cache file behaves exactly like a cache miss here.
452 + const cached = yield* readCachedEntry(fs, path, params);
453
454 if (isFreshForAccounts(cached, connectedAccountIds)) {
455 yield* refreshConsumerPermissionSnapshot({ ...params, connectedAccountIds }).pipe(
@@ -422,15 +477,22 @@ export const getOrgEnhancedControlsStatus = (params: {
477 const apiKey = Option.getOrUndefined(userContext.data.apiKey);
478 if (!apiKey) return undefined;
479
425 - const config = yield* Effect.tryPromise(() =>
426 - fetchJson<ConsumerConfigResponse>({
427 - baseURL: userContext.data.baseURL,
428 - apiKey,
429 - orgId: params.orgId,
430 - projectId: params.projectId,
431 - path: '/api/v3.1/org/consumer/config',
432 - })
433 - );
480 + const config = yield* Effect.tryPromise({
481 + try: () =>
482 + fetchJson(ConsumerConfigResponseSchema, {
483 + baseURL: userContext.data.baseURL,
484 + apiKey,
485 + orgId: params.orgId,
486 + projectId: params.projectId,
487 + path: '/api/v3.1/org/consumer/config',
488 + }),
489 + catch: cause =>
490 + new ToolPermissionsRequestError({
491 + path: '/api/v3.1/org/consumer/config',
492 + message: 'Failed to fetch the org consumer config.',
493 + cause,
494 + }),
495 + });
496 const remoteEnabled = readEnhancedControlsFlag(config);
497 const platformSupported = isEnhancedControlsPlatformSupported();
498 return {
@@ -439,7 +501,7 @@ export const getOrgEnhancedControlsStatus = (params: {
501 platformSupported,
502 };
503 }).pipe(
442 - Effect.catchAll(error =>
504 + Effect.catchTag('services/ToolPermissionsRequestError', error =>
505 Effect.gen(function* () {
506 yield* Effect.logDebug('Failed to read enhanced controls status', error);
507 return undefined;
@@ -493,29 +555,44 @@ const isAllowCachedInMemory = (cacheKey: string, now = Date.now()): boolean => {
555 return true;
556 };
557
496 -const isAllowCached = async (cacheKey: string, now = Date.now()): Promise<boolean> => {
497 - if (isAllowCachedInMemory(cacheKey, now)) return true;
498 -
499 - const cache = await readCacheFile();
500 - const expiresAt = cache.allowEntries?.[cacheKey]?.expiresAt;
501 - if (expiresAt === undefined || expiresAt <= now) return false;
558 +const isAllowCached = (
559 + fs: FileSystem.FileSystem,
560 + path: Path.Path,
561 + cacheKey: string,
562 + now = Date.now()
563 +): Effect.Effect<boolean> =>
564 + Effect.suspend(() => {
565 + if (isAllowCachedInMemory(cacheKey, now)) return Effect.succeed(true);
566
503 - allowDecisionMemoryCache.set(cacheKey, expiresAt);
504 - return true;
505 -};
567 + return readCacheFile(fs, path).pipe(
568 + Effect.map(cache => {
569 + const expiresAt = cache.allowEntries?.[cacheKey]?.expiresAt;
570 + if (expiresAt === undefined || expiresAt <= now) return false;
571
507 -const cacheAllowDecision = async (cacheKey: string, now = Date.now()): Promise<void> => {
508 - const expiresAt = now + ALLOW_FOR_DURATION_MS;
509 - allowDecisionMemoryCache.set(cacheKey, expiresAt);
572 + allowDecisionMemoryCache.set(cacheKey, expiresAt);
573 + return true;
574 + })
575 + );
576 + });
577
511 - await updateCacheFile(current => ({
512 - entries: current.entries,
513 - allowEntries: {
514 - ...current.allowEntries,
515 - [cacheKey]: { expiresAt },
516 - },
517 - }));
518 -};
578 +const cacheAllowDecision = (
579 + fs: FileSystem.FileSystem,
580 + path: Path.Path,
581 + cacheKey: string,
582 + now = Date.now()
583 +) =>
584 + Effect.suspend(() => {
585 + const expiresAt = now + ALLOW_FOR_DURATION_MS;
586 + allowDecisionMemoryCache.set(cacheKey, expiresAt);
587 +
588 + return updateCacheFile(fs, path, current => ({
589 + entries: current.entries,
590 + allowEntries: {
591 + ...current.allowEntries,
592 + [cacheKey]: { expiresAt },
593 + },
594 + }));
595 + });
596
597 const escapeHtml = (value: string): string =>
598 value.replace(/[&<>"']/g, char => {
@@ -972,15 +1049,19 @@ export const gateToolExecution = (params: GateParams) =>
1049 return { approvalStatus: 'always_approved' } satisfies PermissionGateResult;
1050 }
1051 if (state === 'always_deny') {
975 - return yield* Effect.fail(
976 - new Error(`Tool execution denied by permissions: ${params.toolSlug}`)
977 - );
1052 + return yield* new ToolPermissionDeniedError({
1053 + toolSlug: params.toolSlug,
1054 + deniedBy: 'permissions',
1055 + message: `Tool execution denied by permissions: ${params.toolSlug}`,
1056 + });
1057 }
1058
1059 + const fs = yield* FileSystem.FileSystem;
1060 + const path = yield* Path.Path;
1061 const cacheKey = allowCacheKey(params);
981 - const hasCachedAllow = yield* Effect.tryPromise(() => isAllowCached(cacheKey)).pipe(
982 - Effect.catchAll(() => Effect.succeed(false))
983 - );
1062 + // Read failures are absorbed inside readCacheFile (empty cache), so an
1063 + // unreadable allow cache behaves exactly like "no cached allow decision".
1064 + const hasCachedAllow = yield* isAllowCached(fs, path, cacheKey);
1065 if (hasCachedAllow) {
1066 return { approvalStatus: 'cached_approved' } satisfies PermissionGateResult;
1067 }
@@ -988,28 +1069,46 @@ export const gateToolExecution = (params: GateParams) =>
1069 // Fail closed instead of spawning approval UI where nobody can answer it
1070 // (tests, CI). Cached allow decisions above still apply.
1071 if (yield* isInteractivePermissionUiDisabled) {
991 - return yield* Effect.fail(
992 - new Error(
993 - `Tool execution requires interactive approval, but permission prompts are disabled in this environment (CI/VITEST, or COMPOSIO_DISABLE_PERMISSION_UI): ${params.toolSlug}`
994 - )
995 - );
1072 + return yield* new ToolPermissionDeniedError({
1073 + toolSlug: params.toolSlug,
1074 + deniedBy: 'permissions',
1075 + message: `Tool execution requires interactive approval, but permission prompts are disabled in this environment (CI/VITEST, or COMPOSIO_DISABLE_PERMISSION_UI): ${params.toolSlug}`,
1076 + });
1077 }
1078
998 - const decision = yield* Effect.tryPromise(() =>
999 - requestPermissionDecision({
1000 - toolSlug: params.toolSlug,
1001 - accountLabel: params.connectedAccountWordId,
1002 - })
1003 - );
1079 + const decision = yield* Effect.tryPromise({
1080 + try: () =>
1081 + requestPermissionDecision({
1082 + toolSlug: params.toolSlug,
1083 + accountLabel: params.connectedAccountWordId,
1084 + }),
1085 + catch: cause =>
1086 + new ToolPermissionPromptError({
1087 + toolSlug: params.toolSlug,
1088 + message: `Failed to collect a permission decision for: ${params.toolSlug}`,
1089 + cause,
1090 + }),
1091 + });
1092
1093 if (decision === 'deny') {
1006 - return yield* Effect.fail(new Error(`Tool execution denied by user: ${params.toolSlug}`));
1094 + return yield* new ToolPermissionDeniedError({
1095 + toolSlug: params.toolSlug,
1096 + deniedBy: 'user',
1097 + message: `Tool execution denied by user: ${params.toolSlug}`,
1098 + });
1099 }
1100 const cachesAllowOnce = state === 'ask_once' || state === 'ask_once_per_session';
1101 if (decision === 'allow_session' || (cachesAllowOnce && decision === 'allow_once')) {
1010 - yield* Effect.tryPromise(() => cacheAllowDecision(cacheKey)).pipe(
1011 - Effect.catchAll(error =>
1012 - Effect.logDebug('Failed to cache tool permission allow decision', error)
1102 + yield* cacheAllowDecision(fs, path, cacheKey).pipe(
1103 + Effect.catchAll(cause =>
1104 + Effect.logDebug(
1105 + 'Failed to cache tool permission allow decision',
1106 + new ToolPermissionsCacheError({
1107 + operation: 'write',
1108 + message: 'Failed to cache the tool permission allow decision.',
1109 + cause,
1110 + })
1111 + )
1112 )
1113 );
1114 }
ts/packages/cli/src/services/tool-router-session-connections.ts
+32 -41
@@ -1,11 +1,20 @@
1 -import { Effect } from 'effect';
1 +import { Data, Effect, Schema } from 'effect';
2 import type { Composio } from '@composio/client';
3 +import { ConnectedAccountItem } from 'src/models/connected-accounts';
4 import {
5 + compareNewestFirst,
6 groupCachedConnectedAccountsByToolkit,
7 resolveDefaultConnectedAccountsByToolkit,
8 type SelectableConnectedAccount,
9 } from 'src/services/connected-account-selection';
10
11 +export class ToolRouterSessionConnectionsError extends Data.TaggedError(
12 + 'services/ToolRouterSessionConnectionsError'
13 +)<{
14 + readonly message: string;
15 + readonly cause: unknown;
16 +}> {}
17 +
18 type RawConnectedAccount = {
19 readonly id: string;
20 readonly alias?: string | null;
@@ -40,41 +49,17 @@ export type ToolRouterSessionConnectionContext = {
49 >;
50 };
51
43 -const parseTimestamp = (value?: string | null): number => {
44 - if (!value) return 0;
45 - const parsed = Date.parse(value);
46 - return Number.isFinite(parsed) ? parsed : 0;
47 -};
52 +// Derived from the model schema so the known-status list can't drift from it.
53 +const isKnownConnectedAccountStatus = Schema.is(ConnectedAccountItem.fields.status);
54
55 const normalizeConnectedAccountStatus = (
56 status?: string | null
51 -): SelectableConnectedAccount['status'] => {
52 - switch (status) {
53 - case 'INITIALIZING':
54 - case 'INITIATED':
55 - case 'ACTIVE':
56 - case 'FAILED':
57 - case 'EXPIRED':
58 - case 'INACTIVE':
59 - case 'REVOKED':
60 - return status;
61 - default:
62 - // Sentinel — `'INACTIVE'` would falsely tag the account as user-disabled.
63 - return 'UNKNOWN';
64 - }
65 -};
57 +): SelectableConnectedAccount['status'] =>
58 + // Sentinel — `'INACTIVE'` would falsely tag the account as user-disabled.
59 + status != null && isKnownConnectedAccountStatus(status) ? status : 'UNKNOWN';
60
67 -const isNewerAccount = (candidate: RawConnectedAccount, current: RawConnectedAccount): boolean => {
68 - const candidateTimestamp = Math.max(
69 - parseTimestamp(candidate.updated_at),
70 - parseTimestamp(candidate.created_at)
71 - );
72 - const currentTimestamp = Math.max(
73 - parseTimestamp(current.updated_at),
74 - parseTimestamp(current.created_at)
75 - );
76 - return candidateTimestamp > currentTimestamp;
77 -};
61 +const isNewerAccount = (candidate: RawConnectedAccount, current: RawConnectedAccount): boolean =>
62 + compareNewestFirst(candidate, current) < 0;
63
64 export const resolveToolRouterSessionConnections = (
65 client: Composio,
@@ -83,15 +68,21 @@ export const resolveToolRouterSessionConnections = (
68 readonly toolkits?: ReadonlyArray<string>;
69 }
70 ) =>
86 - Effect.tryPromise(() =>
87 - client.connectedAccounts.list({
88 - user_ids: [userId],
89 - statuses: ['ACTIVE'],
90 - toolkit_slugs:
91 - options?.toolkits && options.toolkits.length > 0 ? [...options.toolkits] : undefined,
92 - limit: 1000,
93 - })
94 - ).pipe(
71 + Effect.tryPromise({
72 + try: () =>
73 + client.connectedAccounts.list({
74 + user_ids: [userId],
75 + statuses: ['ACTIVE'],
76 + toolkit_slugs:
77 + options?.toolkits && options.toolkits.length > 0 ? [...options.toolkits] : undefined,
78 + limit: 1000,
79 + }),
80 + catch: cause =>
81 + new ToolRouterSessionConnectionsError({
82 + message: `Failed to list connected accounts for user "${userId}".`,
83 + cause,
84 + }),
85 + }).pipe(
86 Effect.map(response => {
87 const items = (response.items ?? []) as ReadonlyArray<RawConnectedAccount>;
88 const unknownStatuses = new Set<string>();
ts/packages/cli/src/services/tools-executor.ts
+62 -39
@@ -1,5 +1,5 @@
1 import { FileSystem, Path } from '@effect/platform';
2 -import { Context, Effect, Layer } from 'effect';
2 +import { Context, Data, Effect, Layer } from 'effect';
3 import type { Composio } from '@composio/client';
4 import { executeLocalToolBySlug, resolveLocalTool } from '@composio/cli-local-tools';
5 import type {
@@ -15,7 +15,8 @@ import {
15 mapComposioError,
16 } from 'src/services/composio-error-overrides';
17 import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
18 -import { uploadToolInputFiles } from 'src/services/tool-file-uploads';
18 +import { ToolFileUploadError, uploadToolInputFiles } from 'src/services/tool-file-uploads';
19 +import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
20 import type { NodeOs } from 'src/services/node-os';
21 import type { NodeProcess } from 'src/services/node-process';
22 import type { ComposioUserContext } from 'src/services/user-context';
@@ -70,6 +71,12 @@ export interface ToolsExecutor {
71
72 export const ToolsExecutor = Context.GenericTag<ToolsExecutor>('services/ToolsExecutor');
73
74 +export class LocalToolsDisabledError extends Data.TaggedError('services/LocalToolsDisabledError')<{
75 + readonly toolSlug: string;
76 + readonly feature: string;
77 + readonly message: string;
78 +}> {}
79 +
80 /**
81 * Meta tool slugs handled by `session.executeMeta` instead of `session.execute`.
82 *
@@ -77,7 +84,7 @@ export const ToolsExecutor = Context.GenericTag<ToolsExecutor>('services/ToolsEx
84 * `SessionExecuteMetaParams['slug']` union — a compile error will surface if
85 * a slug is misspelled or if the API adds/removes a meta tool.
86 */
80 -const META_TOOL_SLUG_LIST = [
87 +const META_TOOL_SLUG_LIST: ReadonlyArray<SessionExecuteMetaParams['slug']> = [
88 'COMPOSIO_SEARCH_TOOLS',
89 'COMPOSIO_MULTI_EXECUTE_TOOL',
90 'COMPOSIO_MANAGE_CONNECTIONS',
@@ -85,7 +92,7 @@ const META_TOOL_SLUG_LIST = [
92 'COMPOSIO_REMOTE_WORKBENCH',
93 'COMPOSIO_REMOTE_BASH_TOOL',
94 'COMPOSIO_GET_TOOL_SCHEMAS',
88 -] as const satisfies ReadonlyArray<SessionExecuteMetaParams['slug']>;
95 +];
96
97 const META_TOOL_SLUGS: ReadonlySet<string> = new Set(META_TOOL_SLUG_LIST);
98
@@ -155,21 +162,22 @@ export const ToolsExecutorLive = Layer.effect(
162 CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS
163 );
164 if (localToolResolution && !localToolsEnabled) {
158 - return yield* Effect.fail(
159 - new Error(
160 - `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${slug}.`
161 - )
162 - );
165 + return yield* new LocalToolsDisabledError({
166 + toolSlug: slug,
167 + feature: CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,
168 + message: `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${slug}.`,
169 + });
170 }
171
172 if (localToolResolution) {
166 - const localResult = yield* Effect.tryPromise(() =>
167 - executeLocalToolBySlug(slug, params.arguments)
168 - );
173 + const localResult = yield* Effect.tryPromise({
174 + try: () => executeLocalToolBySlug(slug, params.arguments),
175 + catch: cause => cause,
176 + });
177 if (localResult) {
178 return {
179 successful: true,
172 - data: localResult as Record<string, unknown>,
180 + data: localResult,
181 error: null,
182 logId: '',
183 } satisfies ToolExecuteResponse;
@@ -190,7 +198,7 @@ export const ToolsExecutorLive = Layer.effect(
198 connectedAccounts: params.connectedAccounts,
199 cacheScope: params.cacheScope,
200 });
193 - const toolkitSlug = slug.split('_')[0]?.toLowerCase();
201 + const toolkitSlug = toolkitFromToolSlug(slug);
202 const permissionGateResult = yield* gateToolExecution({
203 toolSlug: slug,
204 connectedAccountId: toolkitSlug ? connectedAccounts?.[toolkitSlug] : undefined,
@@ -199,6 +207,8 @@ export const ToolsExecutorLive = Layer.effect(
207 : undefined,
208 snapshot: permissionSnapshot,
209 });
210 + const fs = yield* FileSystem.FileSystem;
211 + const path = yield* Path.Path;
212 const normalizedArguments = isMetaToolSlug(slug)
213 ? params.arguments
214 : yield* getOrFetchToolInputDefinition(slug).pipe(
@@ -208,42 +218,55 @@ export const ToolsExecutorLive = Layer.effect(
218 return Effect.succeed(params.arguments);
219 }
220
211 - return Effect.tryPromise(() =>
212 - uploadToolInputFiles({
213 - toolSlug: slug,
214 - arguments_: params.arguments,
215 - inputSchema: definition.schema,
216 - client: resolvedClient,
217 - })
218 - );
221 + return Effect.tryPromise({
222 + try: () =>
223 + uploadToolInputFiles({
224 + fs,
225 + path,
226 + toolSlug: slug,
227 + arguments_: params.arguments,
228 + inputSchema: definition.schema,
229 + client: resolvedClient,
230 + }),
231 + catch: cause =>
232 + cause instanceof ToolFileUploadError
233 + ? cause
234 + : new ToolFileUploadError({
235 + cause,
236 + message: cause instanceof Error ? cause.message : String(cause),
237 + reason: 'source-read',
238 + }),
239 + });
240 })
241 );
242
243 const raw: SessionExecuteResponse | SessionExecuteMetaResponse = yield* Effect.tryPromise(
223 - () => {
224 - if (isMetaToolSlug(slug)) {
225 - return resolvedClient.toolRouter.session.executeMeta(sessionId, {
226 - slug,
244 + {
245 + try: () => {
246 + if (isMetaToolSlug(slug)) {
247 + return resolvedClient.toolRouter.session.executeMeta(sessionId, {
248 + slug,
249 + arguments: normalizedArguments,
250 + });
251 + }
252 + const executePayload = {
253 + tool_slug: slug,
254 arguments: normalizedArguments,
228 - });
229 - }
230 - const executePayload = {
231 - tool_slug: slug,
232 - arguments: normalizedArguments,
233 - ...(localExperimentalPayload ? { experimental: localExperimentalPayload } : {}),
234 - };
235 - return resolvedClient.toolRouter.session.execute(sessionId, executePayload);
255 + ...(localExperimentalPayload ? { experimental: localExperimentalPayload } : {}),
256 + };
257 + return resolvedClient.toolRouter.session.execute(sessionId, executePayload);
258 + },
259 + catch: cause => cause,
260 }
261 );
262
263 return normalizeResponse(raw, permissionGateResult);
264 }).pipe(
241 - Effect.catchAll((error): Effect.Effect<never, unknown> => {
265 + Effect.mapError(error => {
266 const mapped = mapComposioError({ error, toolSlug: slug });
243 - if (mapped.normalized instanceof ComposioNoActiveConnectionError) {
244 - return Effect.fail(mapped.normalized);
245 - }
246 - return Effect.fail(error);
267 + return mapped.normalized instanceof ComposioNoActiveConnectionError
268 + ? mapped.normalized
269 + : error;
270 })
271 ),
272 });
ts/packages/cli/src/services/triggers-realtime.ts
+41 -82
@@ -1,4 +1,5 @@
1 -import { Data, Effect, Runtime } from 'effect';
1 +import { Data, Effect, Either, Option, Runtime, Schema } from 'effect';
2 +import { JsonRecordSchema } from 'src/effects/json';
3 import {
4 ComposioClientSingleton,
5 ComposioSessionRepository,
@@ -6,58 +7,17 @@ import {
7 type CliRealtimeCredentialsResponse,
8 } from 'src/services/composio-clients';
9
9 -type RawRealtimeEvent = Record<string, unknown>;
10 +const RawRealtimeEvent = JsonRecordSchema;
11 +type RawRealtimeEvent = typeof RawRealtimeEvent.Type;
12 +const decodeRawRealtimeEvent = Schema.decodeUnknownOption(RawRealtimeEvent);
13
11 -type PusherAuthOptions = {
12 - params?: {
13 - channel_name?: string;
14 - socket_id?: string;
15 - channelName?: string;
16 - socketId?: string;
17 - };
18 - channel_name?: string;
19 - socket_id?: string;
20 - channelName?: string;
21 - socketId?: string;
22 -};
23 -
24 -type PusherAuthCallback = (error: unknown, data?: unknown) => void;
25 -
26 -type PusherChannel = {
27 - bind: (event: string, callback: (data: unknown) => void) => void;
28 - bind_global?: (callback: (eventName: string, data: unknown) => void) => void;
29 - unbind?: (event?: string, callback?: (data: unknown) => void) => void;
30 - unbind_all?: () => void;
31 -};
32 -
33 -type PusherClient = {
34 - subscribe: (channelName: string) => PusherChannel;
35 - unsubscribe: (channelName: string) => void;
36 - disconnect: () => void;
37 - connection?: {
38 - bind?: (event: string, callback: (data: unknown) => void) => void;
39 - };
40 -};
41 -
42 -type PusherCtor = new (
43 - key: string,
44 - options: {
45 - cluster: string;
46 - channelAuthorization: {
47 - customHandler: (
48 - authOptions: PusherAuthOptions,
49 - callback?: PusherAuthCallback
50 - ) => Promise<unknown> | void;
51 - };
52 - }
53 -) => PusherClient;
54 -
55 -type ChunkedRealtimeEvent = {
56 - id: string;
57 - index: number;
58 - chunk: string;
59 - final: boolean;
60 -};
14 +const ChunkedRealtimeEvent = Schema.Struct({
15 + id: Schema.String,
16 + index: Schema.Int,
17 + chunk: Schema.String,
18 + final: Schema.Boolean,
19 +});
20 +const decodeChunkedRealtimeEvent = Schema.decodeUnknownOption(ChunkedRealtimeEvent);
21
22 export class TriggerRealtimeSubscriptionError extends Data.TaggedError(
23 'services/TriggerRealtimeSubscriptionError'
@@ -104,21 +64,16 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
64 catch: subscriptionError('Failed to load the realtime client'),
65 });
66
107 - const Pusher = pusherModule.default as unknown as PusherCtor;
67 + const Pusher = pusherModule.default;
68
69 const pusher = new Pusher(creds.pusher_key, {
70 cluster: creds.pusher_cluster,
71 channelAuthorization: {
112 - customHandler: (authOptions: PusherAuthOptions, callback?: PusherAuthCallback) => {
113 - const authParams = authOptions.params ?? authOptions;
114 - const channel_name = authParams.channel_name ?? authParams.channelName;
115 - const socket_id = authParams.socket_id ?? authParams.socketId;
72 + customHandler: (authOptions, callback) => {
73 + const channel_name = authOptions.channelName;
74 + const socket_id = authOptions.socketId;
75
76 const doAuth = async () => {
118 - if (!channel_name || !socket_id) {
119 - throw new Error('Missing channel_name or socket_id for realtime auth');
120 - }
121 -
77 const response = await Runtime.runPromise(runtime)(
78 params.authRealtimeChannel({
79 channel_name,
@@ -134,14 +89,11 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
89 return normalizedResponse;
90 };
91
137 - if (callback) {
138 - void doAuth()
139 - .then(data => callback(null, data))
140 - .catch(error => callback(error));
141 - return;
142 - }
143 -
144 - return doAuth();
92 + void doAuth()
93 + .then(data => callback(null, data))
94 + .catch(cause =>
95 + callback(cause instanceof Error ? cause : new Error(String(cause)), null)
96 + );
97 },
98 },
99 });
@@ -186,15 +138,16 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
138 }
139 }, CHUNK_TTL_MS);
140
189 - channel.bind('trigger_to_client', eventData => {
190 - params.onEvent((eventData ?? {}) as RawRealtimeEvent);
141 + channel.bind('trigger_to_client', (eventData: unknown) => {
142 + params.onEvent(Option.getOrElse(decodeRawRealtimeEvent(eventData), () => ({})));
143 });
144
193 - channel.bind('chunked-trigger_to_client', data => {
194 - const typed = data as ChunkedRealtimeEvent;
195 - if (!typed || typeof typed.id !== 'string' || typeof typed.index !== 'number') {
145 + channel.bind('chunked-trigger_to_client', (data: unknown) => {
146 + const decoded = decodeChunkedRealtimeEvent(data);
147 + if (Option.isNone(decoded)) {
148 return;
149 }
150 + const typed = decoded.value;
151
152 // Reject non-integer or out-of-range indices to prevent a single
153 // malformed event from creating a massive sparse array.
@@ -221,7 +174,10 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
174 });
175 }
176
224 - const current = chunkedEvents.get(typed.id)!;
177 + const current = chunkedEvents.get(typed.id);
178 + if (!current) {
179 + return;
180 + }
181 current.chunks[typed.index] = typed.chunk;
182 if (typed.final) {
183 current.receivedFinal = true;
@@ -235,13 +191,16 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
191 current.receivedFinal &&
192 current.chunks.length === Object.keys(current.chunks).length
193 ) {
238 - try {
239 - const parsed = JSON.parse(current.chunks.join('')) as RawRealtimeEvent;
240 - params.onEvent(parsed);
241 - } catch {
242 - // Silently discard events that fail to parse after chunk reassembly
243 - } finally {
244 - chunkedEvents.delete(typed.id);
194 + const reassembled = current.chunks.join('');
195 + chunkedEvents.delete(typed.id);
196 + // Silently discard events that fail to parse after chunk
197 + // reassembly; the buffer entry is already cleared either way.
198 + const parsed = Either.try((): unknown => JSON.parse(reassembled)).pipe(
199 + Either.getRight,
200 + Option.flatMap(decodeRawRealtimeEvent)
201 + );
202 + if (Option.isSome(parsed)) {
203 + params.onEvent(parsed.value);
204 }
205 }
206 });
ts/packages/cli/src/services/user-context.ts
+17 -19
@@ -1,11 +1,12 @@
1 import { FileSystem, Path } from '@effect/platform';
2 -import { Effect, Context, Layer, Option } from 'effect';
2 +import { Effect, Context, Layer, Option, Predicate, Schema } from 'effect';
3 import {
4 type UserDataWithDefaults,
5 UserData,
6 userDataFromJSON,
7 userDataToJSON,
8 } from 'src/models/user-data';
9 +import { JsonRecordSchema } from 'src/effects/json';
10 import { setupCacheDir } from 'src/effects/setup-cache-dir';
11 import * as constants from 'src/constants';
12 import type { PlatformError } from '@effect/platform/Error';
@@ -25,6 +26,16 @@ import { ComposioCliUserConfig, ComposioCliUserConfigLive } from 'src/services/c
26 */
27 const KEYRING_SERVICE = 'com.composio.cli';
28 const KEYRING_USER = 'default';
29 +const decodeUserDataJsonObject = Schema.decodeUnknown(Schema.parseJson(JsonRecordSchema));
30 +
31 +const normalizeEncodedUserData = (encoded: string, omitApiKey: boolean) =>
32 + Effect.gen(function* () {
33 + const decoded = yield* decodeUserDataJsonObject(encoded);
34 + const parsed = { ...decoded };
35 + if (parsed.project_id === null) delete parsed.project_id;
36 + if (omitApiKey && parsed.api_key === null) delete parsed.api_key;
37 + return JSON.stringify(parsed);
38 + });
39
40 // -----------------------------------------------------------------------------
41 // Keyring helpers — extracted from the generator so it stays within
@@ -58,7 +69,7 @@ const writeKeyring = (deps: KeyringDeps, password: string) =>
69 } else {
70 yield* Effect.logDebug(
71 'Unexpected keyring error while writing api_key, falling back to plaintext: ' +
61 - (err instanceof Error ? err.message : String(err))
72 + (Predicate.isError(err) ? err.message : String(err))
73 );
74 }
75 return false;
@@ -92,7 +103,7 @@ const readKeyring = (deps: KeyringDeps) =>
103 } else {
104 yield* Effect.logDebug(
105 'Unexpected keyring error while reading api_key, falling back to plaintext: ' +
95 - (err instanceof Error ? err.message : String(err))
106 + (Predicate.isError(err) ? err.message : String(err))
107 );
108 }
109 return Option.none<string>();
@@ -119,7 +130,7 @@ const deleteKeyring = (deps: KeyringDeps) =>
130 yield* Effect.logDebug(`Keyring delete skipped: ${err.kind}`);
131 } else {
132 yield* Effect.logWarning(
122 - 'Keyring delete failed: ' + (err instanceof Error ? err.message : String(err))
133 + 'Keyring delete failed: ' + (Predicate.isError(err) ? err.message : String(err))
134 );
135 }
136 })
@@ -183,14 +194,7 @@ export const rawComposioUserContextLive = Layer.effect(
194 ? snapshot
195 : { ...snapshot, apiKey: Option.none() };
196 const encoded = yield* userDataToJSON(onDisk);
186 - const normalized = JSON.stringify(
187 - (() => {
188 - const parsed = JSON.parse(encoded) as Record<string, unknown>;
189 - if (parsed.project_id === null) delete parsed.project_id;
190 - if (!useLegacyStorage && parsed.api_key === null) delete parsed.api_key;
191 - return parsed;
192 - })()
193 - );
197 + const normalized = yield* normalizeEncodedUserData(encoded, !useLegacyStorage);
198 yield* Effect.logDebug('Saving user data:', normalized);
199 yield* fs.writeFileString(jsonUserConfigPath, normalized);
200 });
@@ -233,13 +237,7 @@ export const rawComposioUserContextLive = Layer.effect(
237 // process restarts. We bypass writeJson's strip logic by
238 // temporarily writing with the legacy-storage codepath.
239 const onDisk = yield* userDataToJSON(next);
236 - const normalized = JSON.stringify(
237 - (() => {
238 - const parsed = JSON.parse(onDisk) as Record<string, unknown>;
239 - if (parsed.project_id === null) delete parsed.project_id;
240 - return parsed;
241 - })()
242 - );
240 + const normalized = yield* normalizeEncodedUserData(onDisk, false);
241 yield* Effect.logDebug('Saving user data (keyring fallback):', normalized);
242 yield* fs.writeFileString(jsonUserConfigPath, normalized);
243 }
ts/packages/cli/src/utils/api-error-extraction.ts
+19 -19
@@ -59,27 +59,27 @@ export const extractMessage = (value: unknown, seen?: Set<unknown>): string | un
59 // stores the API response body in .error (which itself has .error.message).
60 // We prefer the deepest message because outer wrappers often have generic
61 // messages like "An unknown error occurred in Effect.tryPromise".
62 - if (value && typeof value === 'object') {
62 + if (Predicate.isObject(value)) {
63 const visited = seen ?? new Set<unknown>();
64 if (visited.has(value)) return undefined;
65 visited.add(value);
66
67 // Try .cause chain first (Effect's UnknownException → real SDK error)
68 - if ('cause' in value) {
69 - const causeMsg = extractMessage((value as { cause?: unknown }).cause, visited);
68 + if (Predicate.hasProperty(value, 'cause')) {
69 + const causeMsg = extractMessage(value.cause, visited);
70 if (causeMsg) return causeMsg;
71 }
72
73 // Try .error chain (SDK error → API response body → nested .error.message)
74 - if ('error' in value) {
75 - const inner = (value as { error?: unknown }).error;
74 + if (Predicate.hasProperty(value, 'error')) {
75 + const inner = value.error;
76 const innerMsg = extractMessage(inner, visited);
77 if (innerMsg) return innerMsg;
78 }
79
80 // Fall back to the wrapper's own message
81 - if ('message' in value && typeof (value as { message?: unknown }).message === 'string') {
82 - return (value as { message: string }).message;
81 + if (Predicate.hasProperty(value, 'message') && Predicate.isString(value.message)) {
82 + return value.message;
83 }
84 }
85
@@ -95,20 +95,20 @@ export const extractSlug = (value: unknown): string | undefined => {
95 let current: unknown = value;
96 const seen = new Set<unknown>();
97
98 - while (current && typeof current === 'object' && !seen.has(current)) {
98 + while (Predicate.isObject(current) && !seen.has(current)) {
99 seen.add(current);
100
101 - if ('slug' in current && typeof (current as { slug?: unknown }).slug === 'string') {
102 - return (current as { slug: string }).slug;
101 + if (Predicate.hasProperty(current, 'slug') && Predicate.isString(current.slug)) {
102 + return current.slug;
103 }
104
105 - if ('error' in current) {
106 - current = (current as { error?: unknown }).error;
105 + if (Predicate.hasProperty(current, 'error')) {
106 + current = current.error;
107 continue;
108 }
109
110 - if ('cause' in current) {
111 - current = (current as { cause?: unknown }).cause;
110 + if (Predicate.hasProperty(current, 'cause')) {
111 + current = current.cause;
112 continue;
113 }
114
@@ -137,7 +137,7 @@ export const extractApiErrorDetails = (value: unknown): ApiErrorDetails | undefi
137
138 while (head < queue.length) {
139 const current = queue[head++];
140 - if (!current || typeof current !== 'object' || seen.has(current)) {
140 + if (!Predicate.isObject(current) || seen.has(current)) {
141 continue;
142 }
143 seen.add(current);
@@ -154,12 +154,12 @@ export const extractApiErrorDetails = (value: unknown): ApiErrorDetails | undefi
154 }
155 }
156
157 - if ('error' in current) {
158 - queue.push((current as { error?: unknown }).error);
157 + if (Predicate.hasProperty(current, 'error')) {
158 + queue.push(current.error);
159 }
160
161 - if ('cause' in current) {
162 - queue.push((current as { cause?: unknown }).cause);
161 + if (Predicate.hasProperty(current, 'cause')) {
162 + queue.push(current.cause);
163 }
164 }
165
ts/packages/cli/src/utils/collect-decoded-entries.ts new
+21
@@ -0,0 +1,21 @@
1 +import { Option } from 'effect';
2 +
3 +/**
4 + * Decode a record's entries one by one, keeping only the entries that decode
5 + * successfully. Used for tolerant cache-file reads: one stale or
6 + * version-skewed entry drops only itself instead of discarding the whole
7 + * file (which would also be persisted back on the next write, permanently
8 + * destroying the good entries).
9 + */
10 +export const collectDecodedEntries = <A>(
11 + entries: Readonly<Record<string, unknown>> | undefined,
12 + decode: (value: unknown) => Option.Option<A>
13 +): Record<string, A> =>
14 + Object.fromEntries(
15 + Object.entries(entries ?? {}).flatMap(([key, value]) =>
16 + Option.match(decode(value), {
17 + onNone: () => [],
18 + onSome: entry => [[key, entry] as const],
19 + })
20 + )
21 + );
ts/packages/cli/test/src/cli-main.test.ts new
+54
@@ -0,0 +1,54 @@
1 +import fs from 'node:fs';
2 +import path from 'node:path';
3 +import { spawnSync } from 'node:child_process';
4 +import { describe, expect, it } from 'vitest';
5 +import * as tempy from 'tempy';
6 +
7 +describe('CLI process error handling', () => {
8 + it('prints unreported ToolExecutionError failures and exits non-zero', () => {
9 + const configDirectory = tempy.temporaryDirectory();
10 + fs.writeFileSync(
11 + path.join(configDirectory, 'config.json'),
12 + JSON.stringify({ experimental_features: { local_tools: true } })
13 + );
14 + fs.writeFileSync(
15 + path.join(configDirectory, 'user_data.json'),
16 + JSON.stringify({
17 + api_key: null,
18 + base_url: 'https://backend.composio.dev',
19 + web_url: 'https://platform.composio.dev',
20 + org_id: null,
21 + test_user_id: null,
22 + })
23 + );
24 +
25 + const result = spawnSync(
26 + 'bun',
27 + [
28 + 'run',
29 + 'src/bin.ts',
30 + 'execute',
31 + 'LOCAL_PEEKABOO_VERSION',
32 + '--file',
33 + '/tmp/does-not-matter',
34 + '-d',
35 + '{}',
36 + ],
37 + {
38 + cwd: process.cwd(),
39 + encoding: 'utf8',
40 + env: {
41 + ...process.env,
42 + CI: '1',
43 + NO_COLOR: '1',
44 + COMPOSIO_CACHE_DIR: configDirectory,
45 + },
46 + }
47 + );
48 +
49 + expect(result.status).toBe(1);
50 + expect(`${result.stdout}\n${result.stderr}`).toContain(
51 + '--file is not supported for local tools yet.'
52 + );
53 + });
54 +});
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+53
@@ -1,5 +1,6 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Console, Effect } from 'effect';
3 +import { HelpDoc, ValidationError } from '@effect/cli';
4 import { extendConfigProvider } from 'src/services/config';
5 import { cli, TestLive, MockConsole } from 'test/__utils__';
6 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -45,6 +46,12 @@ const makeConnectedAccountsData = (
46 ...overrides,
47 });
48
49 +const connectedAccountWithCredentialFields = {
50 + ...makeConnectedAccount(),
51 + state: { access_token: 'must-not-leak' },
52 + data: { refresh_token: 'must-not-leak' },
53 +};
54 +
55 const testConfigProvider = ConfigProvider.fromMap(
56 new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
57 ).pipe(extendConfigProvider);
@@ -271,6 +278,52 @@ describe('CLI: composio dev connected-accounts link', () => {
278 );
279 });
280
281 + layer(
282 + TestLive({
283 + baseConfigProvider: testConfigProvider,
284 + connectedAccountsData: makeConnectedAccountsData(),
285 + fixture: 'global-test-user-id',
286 + })
287 + )('[Given] a blank --alias [Then] fails with a CLI validation error', it => {
288 + it.scoped('reports the invalid option value before making a link request', () =>
289 + Effect.gen(function* () {
290 + const error = yield* cli(['link', 'gmail', '--alias', ' ']).pipe(Effect.flip);
291 +
292 + expect(ValidationError.isValidationError(error)).toBe(true);
293 + if (!ValidationError.isValidationError(error)) return;
294 + expect(ValidationError.isInvalidValue(error)).toBe(true);
295 + expect(HelpDoc.toAnsiText(error.error)).toContain('`--alias` cannot be empty.');
296 + expect(vi.mocked(open)).not.toHaveBeenCalled();
297 + })
298 + );
299 + });
300 +
301 + layer(
302 + TestLive({
303 + baseConfigProvider: testConfigProvider,
304 + connectedAccountsData: {
305 + items: [connectedAccountWithCredentialFields],
306 + },
307 + fixture: 'global-test-user-id',
308 + })
309 + )('[Given] raw credential fields [Then] --list emits only schema-approved fields', it => {
310 + it.scoped('strips state and data at the response boundary', () =>
311 + Effect.gen(function* () {
312 + yield* cli(['link', 'gmail', '--list']);
313 +
314 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
315 + expect(output).not.toContain('must-not-leak');
316 + expect(output).not.toContain('access_token');
317 + expect(output).not.toContain('refresh_token');
318 + expect(extractJsonObject(output)).toStrictEqual({
319 + toolkit: 'gmail',
320 + total: 1,
321 + items: [makeConnectedAccount()],
322 + });
323 + })
324 + );
325 + });
326 +
327 layer(
328 TestLive({
329 baseConfigProvider: testConfigProvider,
ts/packages/cli/test/src/commands/listen.cmd.test.ts
+75 -15
@@ -1,5 +1,7 @@
1 +import { ValidationError } from '@effect/cli';
2 import { describe, expect, layer } from '@effect/vitest';
2 -import { ConfigProvider, Effect } from 'effect';
3 +import { Cause, ConfigProvider, Effect, Exit } from 'effect';
4 +import { ListenCommandError } from 'src/commands/listen.cmd';
5 import { extendConfigProvider } from 'src/services/config';
6 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
7 import { cli, MockConsole, TestLive } from 'test/__utils__';
@@ -8,6 +10,16 @@ const testConfigProvider = ConfigProvider.fromMap(
10 new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
11 ).pipe(extendConfigProvider);
12
13 +const enableListen = Effect.gen(function* () {
14 + const config = yield* ComposioCliUserConfig;
15 + yield* config.update({
16 + experimentalFeatures: {
17 + ...config.raw.experimentalFeatures,
18 + listen: true,
19 + },
20 + });
21 +});
22 +
23 describe('CLI: composio listen', () => {
24 layer(
25 TestLive({
@@ -35,13 +47,7 @@ describe('CLI: composio listen', () => {
47 '[Then] listens to top-level composio.* events without creating a temporary trigger',
48 () =>
49 Effect.gen(function* () {
38 - const config = yield* ComposioCliUserConfig;
39 - yield* config.update({
40 - experimentalFeatures: {
41 - ...config.raw.experimentalFeatures,
42 - listen: true,
43 - },
44 - });
50 + yield* enableListen;
51 yield* cli(['listen', 'composio.connected_account.expired', '--max-events', '1']);
52
53 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -106,13 +112,7 @@ describe('CLI: composio listen', () => {
112 )(it => {
113 it.scoped('[Then] keeps the temporary-trigger flow for trigger slugs', () =>
114 Effect.gen(function* () {
109 - const config = yield* ComposioCliUserConfig;
110 - yield* config.update({
111 - experimentalFeatures: {
112 - ...config.raw.experimentalFeatures,
113 - listen: true,
114 - },
115 - });
115 + yield* enableListen;
116 yield* cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE', '--max-events', '1']);
117
118 const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -124,4 +124,64 @@ describe('CLI: composio listen', () => {
124 })
125 );
126 });
127 +
128 + layer(
129 + TestLive({
130 + baseConfigProvider: testConfigProvider,
131 + fixture: 'global-test-user-id',
132 + })
133 + )('listen validation and domain failures', it => {
134 + it.scoped('reports malformed trigger params as CLI input validation', () =>
135 + Effect.gen(function* () {
136 + yield* enableListen;
137 + const exit = yield* Effect.exit(
138 + cli(['listen', 'composio.connected_account.expired', '--params', '[]'])
139 + );
140 +
141 + expect(Exit.isFailure(exit)).toBe(true);
142 + if (Exit.isFailure(exit)) {
143 + const failure = Cause.squash(exit.cause);
144 + expect(
145 + ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)
146 + ).toBe(true);
147 + }
148 + })
149 + );
150 +
151 + it.scoped('reports malformed timeout values as CLI input validation', () =>
152 + Effect.gen(function* () {
153 + yield* enableListen;
154 + const exit = yield* Effect.exit(
155 + cli(['listen', 'composio.connected_account.expired', '--timeout', 'eventually'])
156 + );
157 +
158 + expect(Exit.isFailure(exit)).toBe(true);
159 + if (Exit.isFailure(exit)) {
160 + const failure = Cause.squash(exit.cause);
161 + expect(
162 + ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)
163 + ).toBe(true);
164 + }
165 + })
166 + );
167 +
168 + it.scoped('reports a missing active connection as a structured domain failure', () =>
169 + Effect.gen(function* () {
170 + yield* enableListen;
171 + const exit = yield* Effect.exit(cli(['listen', 'GMAIL_NEW_GMAIL_MESSAGE']));
172 +
173 + expect(Exit.isFailure(exit)).toBe(true);
174 + if (Exit.isFailure(exit)) {
175 + const failure = Cause.squash(exit.cause);
176 + expect(failure).toBeInstanceOf(ListenCommandError);
177 + if (failure instanceof ListenCommandError) {
178 + expect(failure).toMatchObject({
179 + reason: 'connected_account_not_found',
180 + toolkitSlug: 'gmail',
181 + });
182 + }
183 + }
184 + })
185 + );
186 + });
187 });
ts/packages/cli/test/src/commands/local-tools.cmd.test.ts
+49 -1
@@ -1,8 +1,10 @@
1 import fs from 'node:fs/promises';
2 import os from 'node:os';
3 import path from 'node:path';
4 +import { ValidationError } from '@effect/cli';
5 import { describe, expect, layer } from '@effect/vitest';
5 -import { Effect } from 'effect';
6 +import { Cause, Effect, Exit } from 'effect';
7 +import { LocalToolsDoctorError } from 'src/commands/local-tools/commands/local-tools.doctor.cmd';
8 import { cli, MockConsole, TestLive } from 'test/__utils__';
9
10 const withLocalToolsPath = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
@@ -64,6 +66,52 @@ describe('CLI: composio local-tools', () => {
66 })
67 );
68
69 + it.scoped('[Given] an unknown configure selector [Then] reports CLI input validation', () =>
70 + Effect.gen(function* () {
71 + const exit = yield* Effect.exit(
72 + cli(['local-tools', 'configure', 'NOT_A_LOCAL_TOOL', '--disable'])
73 + );
74 +
75 + expect(Exit.isFailure(exit)).toBe(true);
76 + if (Exit.isFailure(exit)) {
77 + const failure = Cause.squash(exit.cause);
78 + expect(
79 + ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)
80 + ).toBe(true);
81 + }
82 + })
83 + );
84 +
85 + it.scoped(
86 + '[Given] strict doctor finds a disabled tool [Then] reports structured readiness',
87 + () =>
88 + withLocalToolsPath(
89 + Effect.gen(function* () {
90 + yield* cli(['local-tools', 'configure', 'CHROME_DEVTOOLS', '--disable']);
91 + const exit = yield* Effect.exit(
92 + cli([
93 + 'local-tools',
94 + 'doctor',
95 + '--toolkits',
96 + 'CHROME_DEVTOOLS',
97 + '--all-platforms',
98 + '--strict',
99 + ])
100 + );
101 +
102 + expect(Exit.isFailure(exit)).toBe(true);
103 + if (Exit.isFailure(exit)) {
104 + const failure = Cause.squash(exit.cause);
105 + expect(failure).toBeInstanceOf(LocalToolsDoctorError);
106 + if (failure instanceof LocalToolsDoctorError) {
107 + expect(failure.operation).toBe('strict');
108 + expect(failure.notReadyTools.length).toBeGreaterThan(0);
109 + }
110 + }
111 + })
112 + )
113 + );
114 +
115 it.scoped('[Given] meta --init --json [Then] writes local metadata file', () =>
116 withLocalToolsPath(
117 Effect.gen(function* () {
ts/packages/cli/test/src/commands/login.cmd.test.ts
+22
@@ -1,6 +1,7 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { vi, afterEach } from 'vitest';
3 import { Effect, Option } from 'effect';
4 +import { HelpDoc, ValidationError } from '@effect/cli';
5 import path from 'node:path';
6 import { FileSystem } from '@effect/platform';
7 import { cli, MockConsole, TestLive } from 'test/__utils__';
@@ -61,6 +62,27 @@ describe('CLI: composio login', () => {
62 });
63 });
64
65 + layer(TestLive())(it => {
66 + it.scoped('[Given] conflicting login options [Then] fails with a CLI validation error', () =>
67 + Effect.gen(function* () {
68 + const error = yield* cli([
69 + 'login',
70 + '--key',
71 + 'cli_session_key',
72 + '--user-api-key',
73 + 'uak_direct_key',
74 + ]).pipe(Effect.flip);
75 +
76 + expect(ValidationError.isValidationError(error)).toBe(true);
77 + if (!ValidationError.isValidationError(error)) return;
78 + expect(ValidationError.isInvalidValue(error)).toBe(true);
79 + expect(HelpDoc.toAnsiText(error.error)).toContain(
80 + 'Use either `--key` or `--user-api-key`, not both.'
81 + );
82 + })
83 + );
84 + });
85 +
86 layer(TestLive())(it => {
87 it.scoped('[When] stdin is non-interactive [Then] login prints agent instructions', () =>
88 Effect.gen(function* () {
ts/packages/cli/test/src/commands/logs-cmd/format.test.ts
+40 -33
@@ -6,18 +6,21 @@ import {
6 formatToolLogsTable,
7 formatTriggerLogsTable,
8 } from 'src/commands/logs-cmd/format';
9 +import {
10 + decodeTriggerLogRecord,
11 + type TriggerLogRecord,
12 +} from 'src/commands/logs-cmd/trigger-log-record';
13 import { green, red } from 'src/ui/colors';
14
11 -type TriggerLog = Logs.TriggerListResponse.Data;
15 type ToolLog = Logs.ToolListResponse.Data;
16 type ToolLogDetailed = Logs.ToolRetrieveResponse;
17
15 -const makeTriggerLog = (createdAt: TriggerLog['createdAt'] | number): TriggerLog =>
16 - ({
18 +const makeTriggerLog = (createdAt: string | number): TriggerLogRecord =>
19 + decodeTriggerLogRecord({
20 id: 'trigger_log_1',
21 clientId: 'client_1',
22 type: 'trigger',
20 - createdAt: createdAt as TriggerLog['createdAt'],
23 + createdAt,
24 status: 'success',
25 appName: 'gmail',
26 meta: {
@@ -27,7 +30,7 @@ const makeTriggerLog = (createdAt: TriggerLog['createdAt'] | number): TriggerLog
30 },
31 entityId: 'entity_123',
32 connectionId: 'conn_123',
30 - }) as unknown as TriggerLog;
33 + });
34
35 const makeToolLog = (
36 createdAt: ToolLog['createdAt'] | null,
@@ -156,19 +159,21 @@ describe('formatToolLogInfo', () => {
159
160 describe('formatTriggerLogInfo', () => {
161 it('[Given] trigger detailed log [Then] it renders key fields', () => {
159 - const output = formatTriggerLogInfo({
160 - id: 'trigger_log_1',
161 - createdAt: 0,
162 - status: 'success',
163 - appName: 'gmail',
164 - meta: {
165 - triggerId: 'trigger_123',
166 - triggerNanoId: 'ti_123',
167 - triggerName: 'NEW_GMAIL_MESSAGE',
168 - },
169 - entityId: 'user_123',
170 - connectionId: 'conn_123',
171 - });
162 + const output = formatTriggerLogInfo(
163 + decodeTriggerLogRecord({
164 + id: 'trigger_log_1',
165 + createdAt: 0,
166 + status: 'success',
167 + appName: 'gmail',
168 + meta: {
169 + triggerId: 'trigger_123',
170 + triggerNanoId: 'ti_123',
171 + triggerName: 'NEW_GMAIL_MESSAGE',
172 + },
173 + entityId: 'user_123',
174 + connectionId: 'conn_123',
175 + })
176 + );
177
178 expect(output).toContain('logId:');
179 expect(output).toContain('trigger_log_1');
@@ -183,7 +188,7 @@ describe('formatTriggerLogInfo', () => {
188 });
189
190 it('[Given] missing fields [Then] it renders fallback dashes', () => {
186 - const output = formatTriggerLogInfo({});
191 + const output = formatTriggerLogInfo(decodeTriggerLogRecord({}));
192 const plain = output.replace(/\x1b\[[0-9;]*m/g, '');
193 expect(plain).toContain('logId: -');
194 expect(plain).toContain('triggerId: -');
@@ -193,21 +198,23 @@ describe('formatTriggerLogInfo', () => {
198 });
199
200 it('[Given] retrieve response wrapped under log [Then] it unwraps and renders values', () => {
196 - const output = formatTriggerLogInfo({
197 - log: {
198 - id: 'log_QNzKGStH-ruD',
199 - status: 'info',
200 - appName: 'gmail',
201 - createdAt: '2026-02-25T22:01:22.865Z',
202 - entityId: 'pg-test-37ee710c-d5be-4775-91f2-a8e06b937d9b',
203 - connectionId: 'ca_zkX9njO68E8A',
204 - meta: {
205 - triggerId: '77ac1dbf-6db0-4039-8dbe-e903b3f2057e',
206 - triggerNanoId: 'ti_-nGUzD9N6JNf',
207 - triggerName: 'GMAIL_NEW_GMAIL_MESSAGE',
201 + const output = formatTriggerLogInfo(
202 + decodeTriggerLogRecord({
203 + log: {
204 + id: 'log_QNzKGStH-ruD',
205 + status: 'info',
206 + appName: 'gmail',
207 + createdAt: '2026-02-25T22:01:22.865Z',
208 + entityId: 'pg-test-37ee710c-d5be-4775-91f2-a8e06b937d9b',
209 + connectionId: 'ca_zkX9njO68E8A',
210 + meta: {
211 + triggerId: '77ac1dbf-6db0-4039-8dbe-e903b3f2057e',
212 + triggerNanoId: 'ti_-nGUzD9N6JNf',
213 + triggerName: 'GMAIL_NEW_GMAIL_MESSAGE',
214 + },
215 },
209 - },
210 - });
216 + })
217 + );
218
219 expect(output).toContain('log_QNzKGStH-ruD');
220 expect(output).toContain('77ac1dbf-6db0-4039-8dbe-e903b3f2057e');
ts/packages/cli/test/src/commands/logs-cmd/logs.triggers.cmd.test.ts deleted
-47
@@ -1,47 +0,0 @@
1 -import { describe, expect, it } from 'vitest';
2 -import {
3 - getTriggerLogRecord,
4 - getTriggerPayload,
5 - getTriggerResponse,
6 - parseMaybeJson,
7 -} from 'src/commands/logs-cmd/commands/logs.triggers.cmd';
8 -
9 -describe('logs triggers detail helpers', () => {
10 - it('[Given] retrieve response wrapper [Then] unwraps nested log record', () => {
11 - const wrapped = {
12 - log: {
13 - id: 'log_123',
14 - meta: { triggerId: 'trigger_123' },
15 - },
16 - } as Record<string, unknown>;
17 -
18 - expect(getTriggerLogRecord(wrapped)).toEqual({
19 - id: 'log_123',
20 - meta: { triggerId: 'trigger_123' },
21 - });
22 - });
23 -
24 - it('[Given] trigger payload in meta JSON string [Then] parses it to object', () => {
25 - const payload = getTriggerPayload({
26 - meta: {
27 - triggerProviderPayload: '{"foo":"bar","count":2}',
28 - },
29 - });
30 -
31 - expect(payload).toEqual({ foo: 'bar', count: 2 });
32 - });
33 -
34 - it('[Given] trigger response in meta JSON string [Then] parses it to object', () => {
35 - const response = getTriggerResponse({
36 - meta: {
37 - triggerClientResponse: '{"status":"CANCELED"}',
38 - },
39 - });
40 -
41 - expect(response).toEqual({ status: 'CANCELED' });
42 - });
43 -
44 - it('[Given] non-JSON string [Then] parseMaybeJson returns original value', () => {
45 - expect(parseMaybeJson('not-json')).toBe('not-json');
46 - });
47 -});
ts/packages/cli/test/src/commands/logs-cmd/trigger-log-record.test.ts new
+182
@@ -0,0 +1,182 @@
1 +import { describe, expect, it } from 'vitest';
2 +import {
3 + decodeTriggerLogRecord,
4 + emptyTriggerLogRecord,
5 + parseMaybeJson,
6 +} from 'src/commands/logs-cmd/trigger-log-record';
7 +
8 +describe('decodeTriggerLogRecord', () => {
9 + it('[Given] camelCase-only payload [Then] resolves detail and table fields', () => {
10 + const record = decodeTriggerLogRecord({
11 + id: 'log_1',
12 + appName: 'gmail',
13 + status: 'success',
14 + createdAt: '2026-02-25T22:01:22.865Z',
15 + entityId: 'user_1',
16 + connectionId: 'conn_1',
17 + triggerId: 'trigger_1',
18 + triggerNanoId: 'ti_1',
19 + triggerName: 'NEW_GMAIL_MESSAGE',
20 + });
21 +
22 + expect(record.id).toBe('log_1');
23 + expect(record.appName).toBe('gmail');
24 + expect(record.detail.logId).toBe('log_1');
25 + expect(record.detail.triggerId).toBe('trigger_1');
26 + expect(record.detail.triggerNanoId).toBe('ti_1');
27 + expect(record.detail.triggerName).toBe('NEW_GMAIL_MESSAGE');
28 + expect(record.detail.status).toBe('success');
29 + expect(record.detail.toolkit).toBe('gmail');
30 + expect(record.detail.connectionId).toBe('conn_1');
31 + expect(record.detail.entityId).toBe('user_1');
32 + expect(record.detail.createdAt).toBe('2026-02-25T22:01:22.865Z');
33 + expect(record.table.triggerId).toBe('ti_1');
34 + expect(record.table.triggerName).toBe('NEW_GMAIL_MESSAGE');
35 + });
36 +
37 + it('[Given] snake_case-only payload [Then] resolves the same fields', () => {
38 + const record = decodeTriggerLogRecord({
39 + log_id: 'log_2',
40 + trigger_id: 'trigger_2',
41 + trigger_nano_id: 'ti_2',
42 + trigger_name: 'SLACK_NEW_MESSAGE',
43 + toolkit_key: 'slack',
44 + connection_id: 'conn_2',
45 + entity_id: 'user_2',
46 + created_at: 1750000000000,
47 + });
48 +
49 + expect(record.detail.logId).toBe('log_2');
50 + expect(record.detail.triggerId).toBe('trigger_2');
51 + expect(record.detail.triggerNanoId).toBe('ti_2');
52 + expect(record.detail.triggerName).toBe('SLACK_NEW_MESSAGE');
53 + expect(record.detail.toolkit).toBe('slack');
54 + expect(record.detail.connectionId).toBe('conn_2');
55 + expect(record.detail.entityId).toBe('user_2');
56 + expect(record.detail.createdAt).toBe(1750000000000);
57 + expect(record.table.triggerId).toBe('ti_2');
58 + expect(record.table.triggerName).toBe('SLACK_NEW_MESSAGE');
59 + });
60 +
61 + it('[Given] aliases at meta and top level [Then] detail prefers top level while table prefers meta', () => {
62 + const record = decodeTriggerLogRecord({
63 + triggerId: 'top_trigger',
64 + triggerName: 'TOP_NAME',
65 + meta: {
66 + triggerId: 'meta_trigger',
67 + triggerNanoId: 'ti_meta',
68 + triggerName: 'META_NAME',
69 + },
70 + });
71 +
72 + expect(record.detail.triggerId).toBe('top_trigger');
73 + expect(record.detail.triggerName).toBe('TOP_NAME');
74 + // Nano id under meta beats every plain trigger id in the table column.
75 + expect(record.table.triggerId).toBe('ti_meta');
76 + expect(record.table.triggerName).toBe('META_NAME');
77 + });
78 +
79 + it('[Given] meta-only aliases [Then] detail falls back to meta values', () => {
80 + const record = decodeTriggerLogRecord({
81 + meta: {
82 + id: 'meta_id',
83 + triggerId: 'meta_trigger',
84 + trigger_name: 'META_NAME',
85 + createdAt: '2026-01-01T00:00:00.000Z',
86 + },
87 + });
88 +
89 + expect(record.detail.logId).toBe('meta_id');
90 + expect(record.detail.triggerId).toBe('meta_trigger');
91 + expect(record.detail.triggerName).toBe('META_NAME');
92 + expect(record.detail.createdAt).toBe('2026-01-01T00:00:00.000Z');
93 + // Top-level table columns stay untouched by meta values.
94 + expect(record.id).toBeUndefined();
95 + });
96 +
97 + it('[Given] retrieve response wrapped under log [Then] unwraps the nested record', () => {
98 + const record = decodeTriggerLogRecord({
99 + log: {
100 + id: 'log_QNzKGStH-ruD',
101 + appName: 'gmail',
102 + meta: { triggerNanoId: 'ti_-nGUzD9N6JNf' },
103 + },
104 + });
105 +
106 + expect(record.detail.logId).toBe('log_QNzKGStH-ruD');
107 + expect(record.detail.toolkit).toBe('gmail');
108 + expect(record.table.triggerId).toBe('ti_-nGUzD9N6JNf');
109 + });
110 +
111 + it('[Given] payload JSON strings in meta [Then] parses provider payload first', () => {
112 + const record = decodeTriggerLogRecord({
113 + meta: {
114 + triggerProviderPayload: '{"foo":"bar","count":2}',
115 + triggerClientPayload: '{"ignored":true}',
116 + },
117 + });
118 +
119 + expect(record.payload).toEqual({ foo: 'bar', count: 2 });
120 + });
121 +
122 + it('[Given] response JSON string in meta [Then] parses client response first', () => {
123 + const record = decodeTriggerLogRecord({
124 + meta: {
125 + triggerClientResponse: '{"status":"CANCELED"}',
126 + triggerProviderResponse: '{"ignored":true}',
127 + },
128 + });
129 +
130 + expect(record.response).toEqual({ status: 'CANCELED' });
131 + });
132 +
133 + it('[Given] top-level payloadReceived [Then] uses it when meta has no payload', () => {
134 + const record = decodeTriggerLogRecord({
135 + payloadReceived: '{"a":1}',
136 + payload: '{"b":2}',
137 + });
138 +
139 + expect(record.payload).toEqual({ a: 1 });
140 + });
141 +
142 + it('[Given] non-JSON payload string [Then] keeps the original string', () => {
143 + const record = decodeTriggerLogRecord({
144 + meta: { triggerProviderPayload: 'not-json' },
145 + });
146 +
147 + expect(record.payload).toBe('not-json');
148 + });
149 +
150 + it('[Given] wrongly-typed fields [Then] treats them as absent instead of failing', () => {
151 + const record = decodeTriggerLogRecord({
152 + id: 42,
153 + triggerName: ['nope'],
154 + meta: { triggerName: 'META_NAME' },
155 + });
156 +
157 + expect(record.id).toBeUndefined();
158 + expect(record.detail.triggerName).toBe('META_NAME');
159 + });
160 +
161 + it('[Given] garbage payload [Then] falls back to the empty record', () => {
162 + expect(decodeTriggerLogRecord(null)).toEqual(emptyTriggerLogRecord);
163 + expect(decodeTriggerLogRecord('garbage')).toEqual(emptyTriggerLogRecord);
164 + expect(emptyTriggerLogRecord.detail.logId).toBeUndefined();
165 + expect(emptyTriggerLogRecord.payload).toBeNull();
166 + expect(emptyTriggerLogRecord.response).toBeNull();
167 + });
168 +});
169 +
170 +describe('parseMaybeJson', () => {
171 + it('[Given] non-JSON string [Then] returns the original value', () => {
172 + expect(parseMaybeJson('not-json')).toBe('not-json');
173 + });
174 +
175 + it('[Given] JSON object string [Then] parses it', () => {
176 + expect(parseMaybeJson('{"foo":"bar"}')).toEqual({ foo: 'bar' });
177 + });
178 +
179 + it('[Given] malformed JSON-looking string [Then] returns the original value', () => {
180 + expect(parseMaybeJson('{oops}')).toBe('{oops}');
181 + });
182 +});
ts/packages/cli/test/src/commands/proxy.cmd.test.ts
+17 -10
@@ -1,12 +1,17 @@
1 -import { describe, expect, layer } from '@effect/vitest';
2 -import { ConfigProvider, Effect, Option } from 'effect';
3 -import { afterEach, it, vi } from 'vitest';
1 +import { describe, expect, it, layer } from '@effect/vitest';
2 +import { ConfigProvider, Effect, Exit, Option } from 'effect';
3 +import { afterEach, vi } from 'vitest';
4 import type {
5 SessionCreateParams,
6 SessionProxyExecuteParams,
7 } from '@composio/client/resources/tool-router';
8 import { extendConfigProvider } from 'src/services/config';
9 -import { normalizeProxyMethod, parseProxyBody, parseProxyHeader } from 'src/commands/proxy.cmd';
9 +import {
10 + normalizeProxyMethod,
11 + parseProxyBody,
12 + parseProxyHeader,
13 + ProxyCommandError,
14 +} from 'src/commands/proxy.cmd';
15 import * as consumerShortTermCache from 'src/services/consumer-short-term-cache';
16 import { cli, MockConsole, TestLive } from 'test/__utils__';
17
@@ -161,17 +166,19 @@ describe('CLI: composio proxy', () => {
166 },
167 });
168
164 - yield* cli([
169 + const failure = yield* cli([
170 'proxy',
171 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
172 '--toolkit',
173 'gmail',
169 - ]).pipe(
170 - Effect.provide(live),
171 - Effect.catchAll(() => Effect.void)
172 - );
174 + ]).pipe(Effect.provide(live), Effect.flip);
175
176 expect(createCalled).toBe(false);
177 + expect(failure).toBeInstanceOf(ProxyCommandError);
178 + if (failure instanceof ProxyCommandError) {
179 + expect(failure.reason).toBe('toolkit_not_connected');
180 + expect(failure.toolkit).toBe('gmail');
181 + }
182
183 const lines = yield* MockConsole.getLines({ stripAnsi: true });
184 const output = lines.join('\n');
@@ -214,7 +221,7 @@ describe('CLI: composio proxy', () => {
221 '--skip-connection-check',
222 ]).pipe(Effect.provide(live), Effect.exit);
223
217 - expect(exit._tag).toBe('Failure');
224 + expect(Exit.isFailure(exit)).toBe(true);
225
226 const lines = yield* MockConsole.getLines({ stripAnsi: true });
227 const output = lines.join('\n');
ts/packages/cli/test/src/commands/py/py.generate.cmd.test.ts
+5 -2
@@ -1,4 +1,6 @@
1 +import assert from 'node:assert';
2 import path from 'node:path';
3 +import { HelpDoc, ValidationError } from '@effect/cli';
4 import { describe, expect, layer } from '@effect/vitest';
5 import { Effect } from 'effect';
6 import { FileSystem } from '@effect/platform';
@@ -365,8 +367,9 @@ describe('CLI: composio generate py', () => {
367 const args = ['generate', 'py', '--toolkits', 'nonexistent', '--output-dir', outputDir];
368 const result = yield* cli(args).pipe(Effect.catchAll(e => Effect.succeed(e)));
369
368 - expect(result).toBeInstanceOf(Error);
369 - expect((result as Error).message).toContain('Invalid toolkit(s): nonexistent');
370 + assert.ok(ValidationError.isValidationError(result));
371 + assert.ok(ValidationError.isInvalidValue(result));
372 + expect(HelpDoc.toAnsiText(result.error)).toContain('Invalid toolkit(s): nonexistent');
373 })
374 );
375
ts/packages/cli/test/src/commands/setup.cmd.test.ts
+22 -2
@@ -2,7 +2,9 @@ import { Command, CommandExecutor } from '@effect/platform';
2 import { describe, expect, layer } from '@effect/vitest';
3 import { Cause, Effect, Exit, Fiber, TestClock } from 'effect';
4 import { afterEach, vi } from 'vitest';
5 +import { SkillInstallError } from 'src/effects/install-skill';
6 import { CommandRunner } from 'src/services/command-runner';
7 +import { SetupCommandError, SetupProcessError } from 'src/services/setup';
8 import { SetupSkillInstaller } from 'src/services/setup-skill-installer';
9 import { cli, MockConsole, TestLive } from 'test/__utils__';
10
@@ -90,7 +92,14 @@ const makeRunner = (
92 const makeSkillInstaller = (initiallyReady = false, failInstall = false) => {
93 let ready = initiallyReady;
94 const ensureClaudeSkill = () => {
93 - if (failInstall) return Effect.fail(new Error('skill download failed'));
95 + if (failInstall) {
96 + return Effect.fail(
97 + new SkillInstallError({
98 + message: 'skill download failed',
99 + phase: 'download',
100 + })
101 + );
102 + }
103 return Effect.sync(() => {
104 const changed = !ready;
105 ready = true;
@@ -1169,10 +1178,21 @@ describe('CLI: composio setup', () => {
1178 { failOn: 'plugin install' }
1179 );
1180 layer(TestLive({ commandRunner: failedInstall.runner }))('native install failure', it => {
1172 - it.scoped('fails the command', () =>
1181 + it.scoped('preserves the structured setup process failure as the command cause', () =>
1182 Effect.gen(function* () {
1183 const exit = yield* Effect.exit(cli(['setup', '--target', 'claude', '--yes']));
1184 expect(Exit.isFailure(exit)).toBe(true);
1185 + if (Exit.isFailure(exit)) {
1186 + const failure = Cause.squash(exit.cause);
1187 + expect(failure).toBeInstanceOf(SetupCommandError);
1188 + if (failure instanceof SetupCommandError) {
1189 + expect(failure.operation).toBe('setup');
1190 + expect(failure.cause).toBeInstanceOf(SetupProcessError);
1191 + if (failure.cause instanceof SetupProcessError) {
1192 + expect(failure.cause).toMatchObject({ target: 'claude', stage: 'mutate' });
1193 + }
1194 + }
1195 + }
1196 })
1197 );
1198 });
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+115 -17
@@ -1,9 +1,10 @@
1 import * as fs from 'node:fs';
2 import * as os from 'node:os';
3 import * as path from 'node:path';
4 -import { describe, expect, layer } from '@effect/vitest';
4 +import { HelpDoc, ValidationError } from '@effect/cli';
5 +import { describe, expect, it, layer } from '@effect/vitest';
6 import { vi, beforeEach, afterEach } from 'vitest';
6 -import { ConfigProvider, Effect, Option } from 'effect';
7 +import { Config, ConfigProvider, Effect, Option, Predicate } from 'effect';
8 import { extendConfigProvider } from 'src/services/config';
9 import { ComposioNoActiveConnectionError } from 'src/services/composio-error-overrides';
10 import { setupCacheDir } from 'src/effects/setup-cache-dir';
@@ -13,13 +14,26 @@ import * as composioClients from 'src/services/composio-clients';
14 import * as redactModule from 'src/ui/redact';
15 import { cli, TestLive, MockConsole } from 'test/__utils__';
16 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
16 -import { showToolsExecuteInputHelp } from 'src/commands/tools/commands/tools.execute.cmd';
17 +import {
18 + parseParallelExecuteArgs,
19 + showToolsExecuteInputHelp,
20 +} from 'src/commands/tools/commands/tools.execute.cmd';
21 import type { ToolkitDetailed } from 'src/models/toolkits';
22
23 const testConfigProvider = ConfigProvider.fromMap(
24 new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
25 ).pipe(extendConfigProvider);
26
27 +const expectInvalidValueMessage = (failure: unknown, message: string) => {
28 + expect(ValidationError.isValidationError(failure)).toBe(true);
29 + if (!ValidationError.isValidationError(failure)) return;
30 +
31 + expect(ValidationError.isInvalidValue(failure)).toBe(true);
32 + if (!ValidationError.isInvalidValue(failure)) return;
33 +
34 + expect(HelpDoc.toAnsiText(failure.error)).toContain(message);
35 +};
36 +
37 const parseLastJson = (lines: ReadonlyArray<string>) => {
38 for (let i = lines.length - 1; i >= 0; i -= 1) {
39 const line = lines[i];
@@ -39,6 +53,19 @@ const parseLastJson = (lines: ReadonlyArray<string>) => {
53 };
54
55 describe('CLI: composio execute', () => {
56 + it.effect('returns a CLI validation error for malformed parallel arguments', () =>
57 + Effect.gen(function* () {
58 + const failure = yield* parseParallelExecuteArgs(['--parallel', '--data', '{}'], {
59 + surface: 'root',
60 + projectMode: 'consumer',
61 + allowUserId: false,
62 + allowProjectName: false,
63 + }).pipe(Effect.flip);
64 +
65 + expectInvalidValueMessage(failure, 'Expected a tool slug before --data');
66 + })
67 + );
68 +
69 // Disable CI redaction so tests see raw values.
70 // The explicit CI-redaction test overrides via vi.spyOn and is unaffected.
71 let savedCI: string | undefined;
@@ -379,6 +406,29 @@ describe('CLI: composio execute', () => {
406 });
407 })
408 );
409 +
410 + it.scoped('applies a trailing account selector to the current parallel tool only', () =>
411 + Effect.gen(function* () {
412 + yield* cli([
413 + 'execute',
414 + '--parallel',
415 + '--skip-checks',
416 + 'GMAIL_SEND_EMAIL',
417 + '-d',
418 + '{"recipient":"work@example.com"}',
419 + '--account',
420 + 'forest',
421 + 'GMAIL_SEND_EMAIL',
422 + '-d',
423 + '{"recipient":"default@example.com"}',
424 + ]);
425 +
426 + expect(recordedSessionCreateParams).toHaveLength(2);
427 + expect(recordedSessionCreateParams.map(params => params.connected_accounts)).toEqual(
428 + expect.arrayContaining([{ gmail: 'con_gmail_secondary' }, { gmail: 'con_gmail_default' }])
429 + );
430 + })
431 + );
432 });
433
434 layer(
@@ -937,7 +987,9 @@ describe('CLI: composio execute', () => {
987 expect(output.tokenCount).toBeGreaterThan(10_000);
988 // Session artifacts fall back to COMPOSIO_CACHE_DIR, which the shared
989 // vitest setup pins to a per-test temp directory.
990 + const cacheDir = yield* ConfigProvider.fromEnv().load(Config.string('COMPOSIO_CACHE_DIR'));
991 expect(output.outputFilePath).toMatch(/\/[^/]+\/GMAIL_SEND_EMAIL_OUTPUT_[^.]+\.json$/);
992 + expect(output.outputFilePath.startsWith(`${cacheDir}/`)).toBe(true);
993 expect(fs.existsSync(output.outputFilePath)).toBe(true);
994 const storedJson = fs.readFileSync(output.outputFilePath, 'utf8');
995 expect(storedJson).toContain('token token token');
@@ -1024,6 +1076,58 @@ describe('CLI: composio execute', () => {
1076 );
1077 });
1078
1079 + layer(
1080 + TestLive({
1081 + baseConfigProvider: testConfigProvider,
1082 + fixture: 'global-test-user-id',
1083 + stdin: { isTTY: true, data: '' },
1084 + toolRouter: {
1085 + execute: async (_sessionId, params) => {
1086 + if (params.tool_slug === 'GMAIL_SEND_EMAIL') {
1087 + throw new Error('gmail execution failed');
1088 + }
1089 + return {
1090 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
1091 + error: null,
1092 + log_id: 'log_parallel_success',
1093 + };
1094 + },
1095 + },
1096 + })
1097 + )('[Given] one parallel execution fails [Then] sibling results are retained', it => {
1098 + it.scoped('returns an aggregate result for every requested tool', () =>
1099 + Effect.gen(function* () {
1100 + yield* cli([
1101 + 'execute',
1102 + '--parallel',
1103 + '--skip-checks',
1104 + 'GMAIL_SEND_EMAIL',
1105 + '-d',
1106 + '{"recipient":"a"}',
1107 + 'GITHUB_CREATE_ISSUE',
1108 + '-d',
1109 + '{"title":"Bug"}',
1110 + ]).pipe(Effect.catchAll(() => Effect.void));
1111 +
1112 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
1113 + const output = parseLastJson(lines);
1114 + const results =
1115 + Predicate.hasProperty(output, 'results') && Array.isArray(output.results)
1116 + ? output.results
1117 + : [];
1118 +
1119 + expect(output.successful).toBe(false);
1120 + expect(results).toHaveLength(2);
1121 + expect(results).toEqual(
1122 + expect.arrayContaining([
1123 + expect.objectContaining({ slug: 'GMAIL_SEND_EMAIL', successful: false }),
1124 + expect.objectContaining({ slug: 'GITHUB_CREATE_ISSUE', successful: true }),
1125 + ])
1126 + );
1127 + })
1128 + );
1129 + });
1130 +
1131 layer(
1132 TestLive({
1133 baseConfigProvider: testConfigProvider,
@@ -2171,10 +2275,9 @@ describe('CLI: composio execute', () => {
2275 it.scoped('fails with invalid JSON error', () =>
2276 Effect.gen(function* () {
2277 const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', 'not-valid-json']).pipe(
2174 - Effect.flip,
2175 - Effect.map(error => (error instanceof Error ? error.message : String(error)))
2278 + Effect.flip
2279 );
2177 - expect(failure).toContain('Invalid JSON input');
2280 + expectInvalidValueMessage(failure, 'Invalid JSON input');
2281 })
2282 );
2283 });
@@ -2189,10 +2292,9 @@ describe('CLI: composio execute', () => {
2292 it.scoped('fails with expected object error', () =>
2293 Effect.gen(function* () {
2294 const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '[1,2,3]']).pipe(
2192 - Effect.flip,
2193 - Effect.map(error => (error instanceof Error ? error.message : String(error)))
2295 + Effect.flip
2296 );
2195 - expect(failure).toContain('Expected a JSON object');
2297 + expectInvalidValueMessage(failure, 'Expected a JSON object');
2298 })
2299 );
2300 });
@@ -2207,10 +2309,9 @@ describe('CLI: composio execute', () => {
2309 it.scoped('fails with expected object error for string', () =>
2310 Effect.gen(function* () {
2311 const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL', '-d', '"just a string"']).pipe(
2210 - Effect.flip,
2211 - Effect.map(error => (error instanceof Error ? error.message : String(error)))
2312 + Effect.flip
2313 );
2213 - expect(failure).toContain('Expected a JSON object');
2314 + expectInvalidValueMessage(failure, 'Expected a JSON object');
2315 })
2316 );
2317 });
@@ -2251,11 +2352,8 @@ describe('CLI: composio execute', () => {
2352 )('[Given] empty piped stdin [Then] fails with parse error', it => {
2353 it.scoped('fails with error for empty stdin', () =>
2354 Effect.gen(function* () {
2254 - const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL']).pipe(
2255 - Effect.flip,
2256 - Effect.map(error => (error instanceof Error ? error.message : String(error)))
2257 - );
2258 - expect(failure).toContain('Invalid JSON input');
2355 + const failure = yield* cli(['execute', 'GMAIL_SEND_EMAIL']).pipe(Effect.flip);
2356 + expectInvalidValueMessage(failure, 'Invalid JSON input');
2357 })
2358 );
2359 });
ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
+14
@@ -8,6 +8,7 @@ import { extendConfigProvider } from 'src/services/config';
8 import { cli, TestLive, MockConsole } from 'test/__utils__';
9 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
10 import type { Tools } from 'src/models/tools';
11 +import { ToolsSearchInputError } from 'src/commands/tools/commands/tools.search.cmd';
12
13 const testTools: Tools = [
14 {
@@ -97,6 +98,19 @@ const extractFirstJsonObject = (output: string): Record<string, unknown> | null
98 };
99
100 describe('CLI: composio search', () => {
101 + layer(TestLive(testLiveOptions))('[Given] a blank query [Then] typed validation fails', it => {
102 + it.scoped('returns the structured missing-query error', () =>
103 + Effect.gen(function* () {
104 + const failure = yield* cli(['search', ' ']).pipe(Effect.flip);
105 + expect(failure).toBeInstanceOf(ToolsSearchInputError);
106 + if (failure instanceof ToolsSearchInputError) {
107 + expect(failure.reason).toBe('missing_query');
108 + expect(failure.message).toBe('At least one query is required.');
109 + }
110 + })
111 + );
112 + });
113 +
114 layer(TestLive(testLiveOptions))('[Given] query "send" [Then] returns JSON by default', it => {
115 it.scoped('returns JSON payload by default', () =>
116 Effect.gen(function* () {
ts/packages/cli/test/src/commands/triggers/triggers.list.cmd.test.ts
+10 -2
@@ -1,5 +1,6 @@
1 +import { ValidationError } from '@effect/cli';
2 import { describe, expect, layer } from '@effect/vitest';
2 -import { ConfigProvider, Effect } from 'effect';
3 +import { Cause, ConfigProvider, Effect, Exit } from 'effect';
4 import { extendConfigProvider } from 'src/services/config';
5 import { cli, MockConsole, TestLive } from 'test/__utils__';
6 import type { TriggerTypes } from 'src/models/trigger-types';
@@ -76,7 +77,14 @@ describe('CLI: composio dev triggers list', () => {
77 it => {
78 it.scoped('uses root toolkit command in the no-results hint', () =>
79 Effect.gen(function* () {
79 - yield* cli(['triggers', 'list', 'nonexistent']).pipe(Effect.ignore);
80 + const exit = yield* Effect.exit(cli(['triggers', 'list', 'nonexistent']));
81 + expect(Exit.isFailure(exit)).toBe(true);
82 + if (Exit.isFailure(exit)) {
83 + const failure = Cause.squash(exit.cause);
84 + expect(
85 + ValidationError.isValidationError(failure) && ValidationError.isInvalidValue(failure)
86 + ).toBe(true);
87 + }
88 const lines = yield* MockConsole.getLines({ stripAnsi: true });
89 const output = lines.join('\n');
90
ts/packages/cli/test/src/commands/ts/ts.generate.cmd.test.ts
+5 -2
@@ -1,4 +1,6 @@
1 +import assert from 'node:assert';
2 import path from 'node:path';
3 +import { HelpDoc, ValidationError } from '@effect/cli';
4 import { describe, expect, layer } from '@effect/vitest';
5 import { Effect } from 'effect';
6 import { FileSystem } from '@effect/platform';
@@ -998,8 +1000,9 @@ describe('CLI: composio generate ts', () => {
1000 const args = ['generate', 'ts', '--toolkits', 'nonexistent', '--output-dir', outputDir];
1001 const result = yield* cli(args).pipe(Effect.catchAll(e => Effect.succeed(e)));
1002
1001 - expect(result).toBeInstanceOf(Error);
1002 - expect((result as Error).message).toContain('Invalid toolkit(s): nonexistent');
1003 + assert.ok(ValidationError.isValidationError(result));
1004 + assert.ok(ValidationError.isInvalidValue(result));
1005 + expect(HelpDoc.toAnsiText(result.error)).toContain('Invalid toolkit(s): nonexistent');
1006 })
1007 );
1008
ts/packages/cli/test/src/effect-errors/span-annotation.test.ts new
+57
@@ -0,0 +1,57 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Cause, Data, Effect, Option } from 'effect';
3 +import { extractSpanAnnotation } from 'src/effect-errors/logic/errors/span-annotation';
4 +
5 +class CanaryError extends Data.TaggedError('CanaryError')<{
6 + readonly message: string;
7 +}> {}
8 +
9 +const failureOf = <E>(cause: Cause.Cause<E>): E =>
10 + Option.getOrThrowWith(Cause.failureOption(cause), () => new Error('expected a failure cause'));
11 +
12 +describe('extractSpanAnnotation', () => {
13 + it.effect(
14 + 'recovers the ambient span from a runtime failure (canary for the effect/SpanAnnotation internal)',
15 + () =>
16 + Effect.gen(function* () {
17 + const cause = yield* Effect.fail(new CanaryError({ message: 'boom' })).pipe(
18 + Effect.withSpan('canary-span'),
19 + Effect.sandbox,
20 + Effect.flip
21 + );
22 +
23 + const span = extractSpanAnnotation(failureOf(cause));
24 +
25 + expect(span).toBeDefined();
26 + expect(span?.name).toBe('canary-span');
27 + })
28 + );
29 +
30 + it.effect('recovers the ambient span from a runtime defect', () =>
31 + Effect.gen(function* () {
32 + const cause = yield* Effect.die(new Error('defect boom')).pipe(
33 + Effect.withSpan('defect-span'),
34 + Effect.sandbox,
35 + Effect.flip
36 + );
37 +
38 + const defects = Cause.defects(cause);
39 + const span = extractSpanAnnotation([...defects][0]);
40 +
41 + expect(span?.name).toBe('defect-span');
42 + })
43 + );
44 +
45 + it('returns undefined when the error carries no span annotation', () => {
46 + expect(extractSpanAnnotation(new CanaryError({ message: 'boom' }))).toBeUndefined();
47 + expect(extractSpanAnnotation('plain string')).toBeUndefined();
48 + expect(extractSpanAnnotation(undefined)).toBeUndefined();
49 + });
50 +
51 + it('returns undefined when the annotation does not look like a span', () => {
52 + const spanSymbol = Symbol.for('effect/SpanAnnotation');
53 + const error = { [spanSymbol]: { name: 'not-a-span' } };
54 +
55 + expect(extractSpanAnnotation(error)).toBeUndefined();
56 + });
57 +});
ts/packages/cli/test/src/effects/install-skill.test.ts
+5 -5
@@ -13,6 +13,7 @@ import {
13 resolveSkillReleaseTag,
14 resolveTargetSkillPath,
15 SKILL_RELEASE_TAG_FILENAME,
16 + SkillInstallError,
17 type SkillReleaseChannel,
18 } from 'src/effects/install-skill';
19 import { GITHUB_CONFIG } from 'src/effects/github-config';
@@ -277,11 +278,10 @@ describe('install-skill', () => {
278 const home = tempy.temporaryDirectory();
279 const error = yield* Effect.flip(makeInstallEffect(home, apiBaseUrl));
280
280 - // The install pipeline still fails with a plain Error until the
281 - // typed-error slice (PR 8 of this stack) introduces SkillInstallError.
282 - expect(error).toBeInstanceOf(Error);
283 - if (error instanceof Error) {
284 - expect(error.message).toContain('Failed to download skill');
281 + expect(error).toBeInstanceOf(SkillInstallError);
282 + if (error instanceof SkillInstallError) {
283 + expect(error.phase).toBe('release');
284 + expect(error.cause).toBeDefined();
285 }
286 })
287 );
ts/packages/cli/test/src/services/agents.test.ts new
+85
@@ -0,0 +1,85 @@
1 +import { afterEach, vi } from 'vitest';
2 +import { describe, expect, it } from '@effect/vitest';
3 +import { Effect } from 'effect';
4 +import {
5 + AgentRequestError,
6 + AgentResponseDecodeError,
7 + fetchAgentInbox,
8 + normalizeAgentIdentity,
9 +} from 'src/services/agents';
10 +
11 +describe('agent service response boundaries', () => {
12 + afterEach(() => {
13 + vi.restoreAllMocks();
14 + });
15 +
16 + it('normalizes known keys while preserving forward-compatible fields', () => {
17 + const identity = normalizeAgentIdentity({
18 + agent_key: 'agent_test_key',
19 + status: 'READY',
20 + future_field: { enabled: true },
21 + composio: {
22 + user_api_key: 'uak_test',
23 + org_id: 'org_test',
24 + future_credential_metadata: 'preserved',
25 + },
26 + });
27 +
28 + expect(identity.composio_agent_key).toBe('agent_test_key');
29 + expect(identity.future_field).toEqual({ enabled: true });
30 + expect(identity.composio?.future_credential_metadata).toBe('preserved');
31 + });
32 +
33 + it.effect('decodes inbox responses instead of asserting their shape', () =>
34 + Effect.gen(function* () {
35 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
36 + new Response(
37 + JSON.stringify({
38 + count: 1,
39 + messages: [{ subject: 'Hello', future_field: 'preserved' }],
40 + next_cursor: 'cursor_test',
41 + }),
42 + { status: 200 }
43 + )
44 + );
45 +
46 + const inbox = yield* fetchAgentInbox({ agentKey: 'agent_test_key' });
47 +
48 + expect(inbox.count).toBe(1);
49 + expect(inbox.messages?.[0]?.subject).toBe('Hello');
50 + expect(inbox.messages?.[0]?.future_field).toBe('preserved');
51 + expect(inbox.next_cursor).toBe('cursor_test');
52 + })
53 + );
54 +
55 + it.effect('fails with structured context when an inbox response is invalid', () =>
56 + Effect.gen(function* () {
57 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
58 + new Response(JSON.stringify({ messages: [{ subject: 42 }] }), { status: 200 })
59 + );
60 +
61 + const error = yield* fetchAgentInbox({ agentKey: 'agent_test_key', limit: 5 }).pipe(
62 + Effect.flip
63 + );
64 +
65 + expect(error).toBeInstanceOf(AgentResponseDecodeError);
66 + expect(error.pathname).toBe('/api/mail?limit=5');
67 + })
68 + );
69 +
70 + it.effect('preserves an agent API error message and HTTP status', () =>
71 + Effect.gen(function* () {
72 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
73 + new Response(JSON.stringify({ message: 'Agent key expired' }), { status: 401 })
74 + );
75 +
76 + const error = yield* fetchAgentInbox({ agentKey: 'expired_key' }).pipe(Effect.flip);
77 +
78 + expect(error).toBeInstanceOf(AgentRequestError);
79 + if (!(error instanceof AgentRequestError)) return;
80 + expect(error.message).toBe('Agent key expired');
81 + expect(error.status).toBe(401);
82 + expect(error.pathname).toBe('/api/mail?limit=50');
83 + })
84 + );
85 +});
ts/packages/cli/test/src/services/command-hints.test.ts
+2 -2
@@ -1,15 +1,15 @@
1 import { describe, expect, it } from 'vitest';
2 +import { Record } from 'effect';
3 import {
4 COMMAND_HINTS,
5 commandHintExample,
6 commandHintLinks,
7 renderCommandHintGraph,
7 - type CommandHintId,
8 } from 'src/services/command-hints';
9
10 describe('command-hints', () => {
11 it('has no dangling linked command ids', () => {
12 - const ids = new Set(Object.keys(COMMAND_HINTS) as CommandHintId[]);
12 + const ids = new Set(Record.keys(COMMAND_HINTS));
13
14 for (const id of ids) {
15 for (const linkedId of commandHintLinks(id)) {
ts/packages/cli/test/src/services/composio-error-overrides.test.ts
+40
@@ -52,6 +52,46 @@ describe('composio-error-overrides', () => {
52 expect(result.message).toBe('Something else broke');
53 });
54
55 + it('does not trust malformed API error fields but keeps the valid ones', () => {
56 + const error = {
57 + details: {
58 + code: '4302',
59 + slug: 4302,
60 + message: 'Malformed API error',
61 + },
62 + };
63 +
64 + const result = mapComposioError({ error });
65 +
66 + expect(result.normalized).toBe(error);
67 + expect(result.apiDetails?.message).toBe('Malformed API error');
68 + expect(result.apiDetails?.code).toBeUndefined();
69 + expect(result.apiDetails?.slug).toBeUndefined();
70 + expect(result.override).toBeNull();
71 + expect(result.message).toBe('Malformed API error');
72 + });
73 +
74 + it('skips UnknownException wrappers while decoding their causes', () => {
75 + const result = mapComposioError({
76 + toolkit: 'gmail',
77 + error: {
78 + _tag: 'UnknownException',
79 + cause: {
80 + code: 4302,
81 + slug: 'ToolRouterV2_NoActiveConnection',
82 + message: 'No active connection',
83 + },
84 + },
85 + });
86 +
87 + expect(result.normalized).toBeInstanceOf(ComposioNoActiveConnectionError);
88 + expect(result.apiDetails).toEqual({
89 + code: 4302,
90 + slug: 'ToolRouterV2_NoActiveConnection',
91 + message: 'No active connection',
92 + });
93 + });
94 +
95 it('preserves original generic errors for top-level CLI handling', () => {
96 const error = {
97 _tag: 'ToolExecutionError',
ts/packages/cli/test/src/services/run-helpers-runtime.test.ts new
+64
@@ -0,0 +1,64 @@
1 +import { Predicate } from 'effect';
2 +import { afterEach, describe, expect, it, vi } from 'vitest';
3 +import { installRunHelpers } from 'src/services/run-helpers-runtime';
4 +
5 +const installedGlobalNames = [
6 + 'z',
7 + 'zod',
8 + 'search',
9 + 'execute',
10 + 'experimental_subAgent',
11 + 'invokeAgent',
12 + 'proxy',
13 + '__composioRunContext',
14 + '__composioConsumerContext',
15 +];
16 +const originalGlobalDescriptors = new Map(
17 + installedGlobalNames.map(name => [name, Object.getOwnPropertyDescriptor(globalThis, name)])
18 +);
19 +
20 +describe('run-helpers-runtime', () => {
21 + afterEach(() => {
22 + vi.unstubAllGlobals();
23 + for (const name of installedGlobalNames) {
24 + const descriptor = originalGlobalDescriptors.get(name);
25 + if (descriptor) {
26 + Object.defineProperty(globalThis, name, descriptor);
27 + } else {
28 + Reflect.deleteProperty(globalThis, name);
29 + }
30 + }
31 + });
32 +
33 + it('[Given] a malformed proxy session response [Then] it rejects the HTTP boundary payload', async () => {
34 + const fetchMock = vi.fn().mockResolvedValue(
35 + new Response(JSON.stringify({ session_id: 42 }), {
36 + status: 200,
37 + headers: { 'content-type': 'application/json' },
38 + })
39 + );
40 + vi.stubGlobal('fetch', fetchMock);
41 +
42 + await installRunHelpers({
43 + cliPrefix: ['composio'],
44 + helperContext: {
45 + apiKey: 'test-key',
46 + orgId: 'test-org',
47 + consumerProjectId: 'test-project',
48 + consumerUserId: 'test-user',
49 + },
50 + });
51 +
52 + const installedGlobals: unknown = globalThis;
53 + expect(Predicate.hasProperty(installedGlobals, 'proxy')).toBe(true);
54 + if (
55 + !Predicate.hasProperty(installedGlobals, 'proxy') ||
56 + typeof installedGlobals.proxy !== 'function'
57 + ) {
58 + throw new Error('installRunHelpers() did not install proxy().');
59 + }
60 +
61 + await expect(installedGlobals.proxy('github')).rejects.toThrow(/session_id/);
62 + expect(fetchMock).toHaveBeenCalledOnce();
63 + });
64 +});
ts/packages/cli/test/src/services/run-subagent-acp.test.ts
+93 -48
@@ -1,7 +1,11 @@
1 -import { afterEach, describe, expect, it, vi } from 'vitest';
1 +import { Readable } from 'node:stream';
2 +import { BunContext } from '@effect/platform-bun';
3 +import { Effect } from 'effect';
4 +import { afterEach, describe, expect, it, vi } from '@effect/vitest';
5 import {
6 BufferedChunkLogger,
7 createStructuredOutputMcpContext,
8 + readableStreamFromNode,
9 resolveAcpAdapterCommand,
10 selectPermissionOutcome,
11 } from 'src/services/run-subagent-acp';
@@ -12,20 +16,47 @@ describe('run-subagent-acp', () => {
16 vi.unstubAllGlobals();
17 });
18
15 - it('[Given] bundled adapter packages [Then] it resolves to the bundled path without npx', () => {
16 - const result = resolveAcpAdapterCommand('claude');
17 - expect(result.source).toBe('bundled');
18 - expect(result.cmd[0]).toBe(process.execPath);
19 - expect(result.cmd[1]).toMatch(/claude-code-acp/);
20 - });
19 + it('pauses a Node producer while the Web Stream queue is full', async () => {
20 + const input = new Readable({ read: () => undefined });
21 + const stream = readableStreamFromNode(input);
22 +
23 + input.push(new TextEncoder().encode('first'));
24 + input.push(new TextEncoder().encode('second'));
25 + await new Promise<void>(resolve => setImmediate(resolve));
26 +
27 + expect(input.isPaused()).toBe(true);
28
22 - it('[Given] bundled codex adapter [Then] it resolves to the bundled path', () => {
23 - const result = resolveAcpAdapterCommand('codex');
24 - expect(result.source).toBe('bundled');
25 - expect(result.cmd[0]).toBe(process.execPath);
26 - expect(result.cmd[1]).toMatch(/codex-acp/);
29 + const reader = stream.getReader();
30 + const first = await reader.read();
31 + const second = await reader.read();
32 +
33 + expect(new TextDecoder().decode(first.value)).toBe('first');
34 + expect(new TextDecoder().decode(second.value)).toBe('second');
35 +
36 + await reader.cancel();
37 + expect(input.destroyed).toBe(true);
38 });
39
40 + it.effect(
41 + '[Given] bundled adapter packages [Then] it resolves to the bundled path without npx',
42 + () =>
43 + Effect.gen(function* () {
44 + const result = yield* resolveAcpAdapterCommand('claude');
45 + expect(result.source).toBe('bundled');
46 + expect(result.cmd[0]).toBe(process.execPath);
47 + expect(result.cmd[1]).toMatch(/claude-code-acp/);
48 + }).pipe(Effect.provide(BunContext.layer))
49 + );
50 +
51 + it.effect('[Given] bundled codex adapter [Then] it resolves to the bundled path', () =>
52 + Effect.gen(function* () {
53 + const result = yield* resolveAcpAdapterCommand('codex');
54 + expect(result.source).toBe('bundled');
55 + expect(result.cmd[0]).toBe(process.execPath);
56 + expect(result.cmd[1]).toMatch(/codex-acp/);
57 + }).pipe(Effect.provide(BunContext.layer))
58 + );
59 +
60 it('[Given] an ACP invoke error [Then] it is classified for fallback', () => {
61 const error = new AcpInvokeError('initialize_failed', 'boom');
62 expect(isAcpInvokeError(error)).toBe(true);
@@ -42,6 +73,16 @@ describe('run-subagent-acp', () => {
73 expect(isAcpInvokeError(error)).toBe(true);
74 });
75
76 + it('[Given] an unknown ACP error code [Then] it is not admitted into the fallback union', () => {
77 + const error = {
78 + name: 'AcpInvokeError',
79 + code: 'unexpected_failure',
80 + message: 'boom',
81 + };
82 +
83 + expect(isAcpInvokeError(error)).toBe(false);
84 + });
85 +
86 it('[Given] a cancelled ACP prompt [Then] it remains fallback-eligible', () => {
87 const error = new AcpInvokeError('prompt_failed', 'claude ACP prompt was cancelled.');
88
@@ -203,43 +244,47 @@ describe('run-subagent-acp', () => {
244 });
245 });
246
206 - it('[Given] a structured schema [Then] it creates a stdio MCP server context for output capture', () => {
207 - const helperDebugLog = vi.fn();
208 - const context = createStructuredOutputMcpContext({
209 - options: {
210 - structuredSchema: {
211 - type: 'object',
212 - properties: {
213 - summary: { type: 'string' },
247 + it.effect(
248 + '[Given] a structured schema [Then] it creates a stdio MCP server context for output capture',
249 + () =>
250 + Effect.gen(function* () {
251 + const helperDebugLog = vi.fn();
252 + const context = yield* createStructuredOutputMcpContext({
253 + options: {
254 + structuredSchema: {
255 + type: 'object',
256 + properties: {
257 + summary: { type: 'string' },
258 + },
259 + required: ['summary'],
260 + },
261 },
215 - required: ['summary'],
216 - },
217 - },
218 - helperDebugLog,
219 - });
262 + helperDebugLog,
263 + });
264
221 - expect(context).not.toBeNull();
222 - expect(context?.mcpServer.command).toBe(process.execPath);
223 - expect(context?.mcpServer.args).toEqual(
224 - expect.arrayContaining([
225 - expect.stringContaining('run-subagent-output-mcp'),
226 - '--schema-file',
227 - expect.stringContaining('schema.json'),
228 - '--result-file',
229 - expect.stringContaining('result.json'),
230 - ])
231 - );
232 - expect(context?.mcpServer.env).toEqual(
233 - expect.arrayContaining([{ name: 'BUN_BE_BUN', value: '1' }])
234 - );
235 - expect(context?.resultFilePath).toContain('result.json');
236 - expect(helperDebugLog).toHaveBeenCalledWith(
237 - 'subAgent.acp.structured_output_tool',
238 - expect.objectContaining({
239 - modulePath: expect.stringContaining('run-subagent-output-mcp'),
240 - })
241 - );
265 + expect(context).not.toBeNull();
266 + expect(context?.mcpServer.command).toBe(process.execPath);
267 + expect(context?.mcpServer.args).toEqual(
268 + expect.arrayContaining([
269 + expect.stringContaining('run-subagent-output-mcp'),
270 + '--schema-file',
271 + expect.stringContaining('schema.json'),
272 + '--result-file',
273 + expect.stringContaining('result.json'),
274 + ])
275 + );
276 + expect(context?.mcpServer.env).toEqual(
277 + expect.arrayContaining([{ name: 'BUN_BE_BUN', value: '1' }])
278 + );
279 + expect(context?.resultFilePath).toContain('result.json');
280 + expect(helperDebugLog).toHaveBeenCalledWith(
281 + 'subAgent.acp.structured_output_tool',
282 + expect.objectContaining({
283 + modulePath: expect.stringContaining('run-subagent-output-mcp'),
284 + })
285 + );
286
243 - context?.cleanup();
244 - });
287 + yield* context!.cleanup;
288 + }).pipe(Effect.provide(BunContext.layer))
289 + );
290 });
ts/packages/cli/test/src/services/run-subagent-output-mcp.test.ts
+5
@@ -1,8 +1,13 @@
1 import * as fs from 'node:fs';
2 import { fileURLToPath } from 'node:url';
3 import { describe, expect, it } from 'vitest';
4 +import { decodeStructuredSchemaJson } from 'src/services/run-subagent-shared';
5
6 describe('run-subagent-output-mcp source', () => {
7 + it('[Given] a non-object schema file [Then] it rejects the malformed boundary payload', () => {
8 + expect(() => decodeStructuredSchemaJson('[]')).toThrow();
9 + });
10 +
11 it('[Given] the structured output helper source [Then] it statically imports the MCP SDK', () => {
12 const sourcePath = fileURLToPath(
13 new URL('../../../src/services/run-subagent-output-mcp.ts', import.meta.url)
ts/packages/cli/test/src/services/run-subagent-shared.test.ts new
+57
@@ -0,0 +1,57 @@
1 +import { describe, expect, it } from 'vitest';
2 +import { finalizeInvokeAgentText, parseJson } from 'src/services/run-subagent-shared';
3 +
4 +describe('run-subagent-shared JSON probes', () => {
5 + describe('parseJson', () => {
6 + it('[Given] blank text [Then] returns undefined', () => {
7 + expect(parseJson(' ')).toBeUndefined();
8 + });
9 +
10 + it('[Given] valid JSON [Then] returns the parsed value', () => {
11 + expect(parseJson(' {"a": 1} ')).toEqual({ a: 1 });
12 + expect(parseJson('[1, 2, 3]')).toEqual([1, 2, 3]);
13 + expect(parseJson('null')).toBeNull();
14 + });
15 +
16 + it('[Given] non-JSON text [Then] returns the trimmed text verbatim', () => {
17 + expect(parseJson(' not json at all ')).toBe('not json at all');
18 + });
19 + });
20 +
21 + describe('finalizeInvokeAgentText structured extraction', () => {
22 + const options = { structuredSchema: { type: 'object' } as Record<string, unknown> };
23 +
24 + it('[Given] direct JSON output [Then] parses it as the structured output', () => {
25 + expect(finalizeInvokeAgentText('{"a": 1}', options)).toEqual({
26 + result: null,
27 + structuredOutput: { a: 1 },
28 + });
29 + });
30 +
31 + it('[Given] a status line before a fenced JSON block [Then] extracts the fenced payload', () => {
32 + const text = 'Analysis complete.\n```json\n{"b": 2}\n```';
33 + expect(finalizeInvokeAgentText(text, options)).toEqual({
34 + result: null,
35 + structuredOutput: { b: 2 },
36 + });
37 + });
38 +
39 + it('[Given] JSON embedded in prose [Then] extracts the balanced payload', () => {
40 + const text = 'The final answer is {"c": {"nested": true}} as requested.';
41 + expect(finalizeInvokeAgentText(text, options)).toEqual({
42 + result: null,
43 + structuredOutput: { c: { nested: true } },
44 + });
45 + });
46 +
47 + it('[Given] output without any JSON [Then] throws the structured output error', () => {
48 + expect(() => finalizeInvokeAgentText('no structured payload here', options)).toThrow(
49 + 'experimental_subAgent() expected valid JSON output for structured response.'
50 + );
51 + });
52 +
53 + it('[Given] no structured schema [Then] returns the trimmed text as the result', () => {
54 + expect(finalizeInvokeAgentText(' plain answer ', {})).toEqual({ result: 'plain answer' });
55 + });
56 + });
57 +});
ts/packages/cli/test/src/services/tool-file-uploads.test.ts
+123 -74
@@ -1,10 +1,13 @@
1 -import { afterEach, describe, expect, it, vi } from 'vitest';
1 +import { afterEach, describe, expect, it, vi } from '@effect/vitest';
2 import * as os from 'node:os';
3 import * as path from 'node:path';
4 import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
5 +import { FileSystem, Path } from '@effect/platform';
6 +import { BunFileSystem, BunPath } from '@effect/platform-bun';
7 +import { Effect, Layer } from 'effect';
8 import type { Composio as RawComposioClient } from '@composio/client';
9 import { ComposioSensitiveFilePathBlockedError } from '@composio/core';
7 -import { uploadToolInputFiles } from 'src/services/tool-file-uploads';
10 +import { schemaHasFileUploadable, uploadToolInputFiles } from 'src/services/tool-file-uploads';
11
12 // Schema with a single `file_uploadable` attachment field — mirrors tools like
13 // GMAIL_SEND_EMAIL whose attachment is uploaded from a local path.
@@ -24,89 +27,135 @@ describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
27 vi.restoreAllMocks();
28 });
29
27 - it('refuses to read/upload a path under a sensitive directory (~/.ssh/id_rsa)', async () => {
28 - const createPresignedURL = vi.fn();
29 - const client = makeClient(createPresignedURL);
30 -
31 - await expect(
32 - uploadToolInputFiles({
33 - toolSlug: 'GMAIL_SEND_EMAIL',
34 - arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
35 - inputSchema,
36 - client,
30 + it('ignores malformed composition branches without hiding valid schemas', () => {
31 + expect(
32 + schemaHasFileUploadable({
33 + anyOf: ['not-a-schema', null, { file_uploadable: true }],
34 })
38 - ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError);
39 -
40 - // The guard must fire BEFORE any network round-trip: no presigned URL, no upload.
41 - expect(createPresignedURL).not.toHaveBeenCalled();
35 + ).toBe(true);
36 + expect(schemaHasFileUploadable({ anyOf: ['not-a-schema', null] })).toBe(false);
37 });
38
44 - it('surfaces CLI-appropriate remediation, not the SDK-only opt-out, in the block error', async () => {
45 - const client = makeClient(vi.fn());
46 -
47 - // The CLI has no `sensitiveFileUploadProtection` opt-out (by design), so the
48 - // error must not point users at that non-existent knob (issue #3763 review #2/#3).
49 - await expect(
50 - uploadToolInputFiles({
51 - toolSlug: 'GMAIL_SEND_EMAIL',
52 - arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
53 - inputSchema,
54 - client,
55 - })
56 - ).rejects.toThrowError(/has no opt-out/i);
57 -
58 - await expect(
59 - uploadToolInputFiles({
60 - toolSlug: 'GMAIL_SEND_EMAIL',
61 - arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
62 - inputSchema,
63 - client,
64 - })
65 - ).rejects.not.toThrowError(/sensitiveFileUploadProtection/);
66 - });
39 + it.effect('refuses to read/upload a path under a sensitive directory (~/.ssh/id_rsa)', () =>
40 + Effect.gen(function* () {
41 + const fsApi = yield* FileSystem.FileSystem;
42 + const pathApi = yield* Path.Path;
43 + const createPresignedURL = vi.fn();
44 + const client = makeClient(createPresignedURL);
45
68 - it('refuses credential-like basenames (.env) even outside a sensitive directory', async () => {
69 - const createPresignedURL = vi.fn();
70 - const client = makeClient(createPresignedURL);
46 + yield* Effect.promise(() =>
47 + expect(
48 + uploadToolInputFiles({
49 + fs: fsApi,
50 + path: pathApi,
51 + toolSlug: 'GMAIL_SEND_EMAIL',
52 + arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
53 + inputSchema,
54 + client,
55 + })
56 + ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError)
57 + );
58
72 - await expect(
73 - uploadToolInputFiles({
74 - toolSlug: 'GMAIL_SEND_EMAIL',
75 - arguments_: { attachment: path.join(os.tmpdir(), '.env') },
76 - inputSchema,
77 - client,
78 - })
79 - ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError);
80 - expect(createPresignedURL).not.toHaveBeenCalled();
81 - });
59 + // The guard must fire BEFORE any network round-trip: no presigned URL, no upload.
60 + expect(createPresignedURL).not.toHaveBeenCalled();
61 + }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
62 + );
63
83 - it('still uploads a normal (non-sensitive) local file', async () => {
84 - const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));
85 - try {
86 - const file = path.join(root, 'document.pdf');
87 - writeFileSync(file, 'hello');
88 -
89 - const createPresignedURL = vi.fn(async () => ({
90 - new_presigned_url: 'https://s3.example.com/put',
91 - key: 's3key-123',
92 - }));
64 + it.effect(
65 + 'surfaces CLI-appropriate remediation, not the SDK-only opt-out, in the block error',
66 + () =>
67 + Effect.gen(function* () {
68 + const fsApi = yield* FileSystem.FileSystem;
69 + const pathApi = yield* Path.Path;
70 + const client = makeClient(vi.fn());
71 +
72 + // The CLI has no `sensitiveFileUploadProtection` opt-out (by design), so the
73 + // error must not point users at that non-existent knob (issue #3763 review #2/#3).
74 + yield* Effect.promise(() =>
75 + expect(
76 + uploadToolInputFiles({
77 + fs: fsApi,
78 + path: pathApi,
79 + toolSlug: 'GMAIL_SEND_EMAIL',
80 + arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
81 + inputSchema,
82 + client,
83 + })
84 + ).rejects.toThrowError(/has no opt-out/i)
85 + );
86 +
87 + yield* Effect.promise(() =>
88 + expect(
89 + uploadToolInputFiles({
90 + fs: fsApi,
91 + path: pathApi,
92 + toolSlug: 'GMAIL_SEND_EMAIL',
93 + arguments_: { attachment: path.join(os.homedir(), '.ssh', 'id_rsa') },
94 + inputSchema,
95 + client,
96 + })
97 + ).rejects.not.toThrowError(/sensitiveFileUploadProtection/)
98 + );
99 + }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
100 + );
101 +
102 + it.effect('refuses credential-like basenames (.env) even outside a sensitive directory', () =>
103 + Effect.gen(function* () {
104 + const fsApi = yield* FileSystem.FileSystem;
105 + const pathApi = yield* Path.Path;
106 + const createPresignedURL = vi.fn();
107 const client = makeClient(createPresignedURL);
94 - vi.stubGlobal(
95 - 'fetch',
96 - vi.fn(async () => ({ ok: true, statusText: 'OK' }))
108 +
109 + yield* Effect.promise(() =>
110 + expect(
111 + uploadToolInputFiles({
112 + fs: fsApi,
113 + path: pathApi,
114 + toolSlug: 'GMAIL_SEND_EMAIL',
115 + arguments_: { attachment: path.join(os.tmpdir(), '.env') },
116 + inputSchema,
117 + client,
118 + })
119 + ).rejects.toBeInstanceOf(ComposioSensitiveFilePathBlockedError)
120 );
121 + expect(createPresignedURL).not.toHaveBeenCalled();
122 + }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
123 + );
124
99 - const result = await uploadToolInputFiles({
100 - toolSlug: 'GMAIL_SEND_EMAIL',
101 - arguments_: { attachment: file },
102 - inputSchema,
103 - client,
104 - });
125 + it.effect('still uploads a normal (non-sensitive) local file', () => {
126 + const root = mkdtempSync(path.join(os.tmpdir(), 'composio-upload-'));
127 + const file = path.join(root, 'document.pdf');
128 + writeFileSync(file, 'hello');
129 +
130 + const createPresignedURL = vi.fn(async () => ({
131 + new_presigned_url: 'https://s3.example.com/put',
132 + key: 's3key-123',
133 + }));
134 + const client = makeClient(createPresignedURL);
135 + vi.stubGlobal(
136 + 'fetch',
137 + vi.fn(async () => ({ ok: true, statusText: 'OK' }))
138 + );
139 +
140 + return Effect.gen(function* () {
141 + const fsApi = yield* FileSystem.FileSystem;
142 + const pathApi = yield* Path.Path;
143 + const result = yield* Effect.promise(() =>
144 + uploadToolInputFiles({
145 + fs: fsApi,
146 + path: pathApi,
147 + toolSlug: 'GMAIL_SEND_EMAIL',
148 + arguments_: { attachment: file },
149 + inputSchema,
150 + client,
151 + })
152 + );
153
154 expect(createPresignedURL).toHaveBeenCalledTimes(1);
155 expect(result.attachment).toMatchObject({ s3key: 's3key-123', name: 'document.pdf' });
108 - } finally {
109 - rmSync(root, { recursive: true, force: true });
110 - }
156 + }).pipe(
157 + Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)),
158 + Effect.ensuring(Effect.sync(() => rmSync(root, { recursive: true, force: true })))
159 + );
160 });
161 });
ts/packages/cli/test/src/services/tool-permissions.test.ts
+88 -6
@@ -1,9 +1,13 @@
1 +import { FileSystem, Path } from '@effect/platform';
2 +import { BunFileSystem, BunPath } from '@effect/platform-bun';
3 import { afterEach, beforeEach, describe, expect, it, vi } from '@effect/vitest';
2 -import { Effect } from 'effect';
4 +import { Config, ConfigProvider, Effect, Layer, Option } from 'effect';
5 import {
6 decodeCacheFileTolerant,
7 + decodeToolRouterPermissionsConfig,
8 gateToolExecution,
9 resolveGateState,
10 + ToolPermissionDeniedError,
11 type ConsumerPermissionSnapshot,
12 } from 'src/services/tool-permissions';
13
@@ -36,7 +40,25 @@ describe('tool permissions', () => {
40
41 afterEach(() => {
42 vi.useRealTimers();
39 - vi.unstubAllEnvs();
43 + });
44 +
45 + it('maps forward-version permission modes to interactive safe defaults', () => {
46 + const decoded = decodeToolRouterPermissionsConfig({
47 + default: 'future_default_mode',
48 + overrides: {
49 + 'GMAIL_SEND_EMAIL:__none__': 'future_override_mode',
50 + },
51 + });
52 +
53 + expect(Option.isSome(decoded)).toBe(true);
54 + if (Option.isSome(decoded)) {
55 + expect(decoded.value).toStrictEqual({
56 + default: 'ask_every_call',
57 + overrides: {
58 + 'GMAIL_SEND_EMAIL:__none__': 'ask_always',
59 + },
60 + });
61 + }
62 });
63
64 it('drops only corrupt cache entries, keeping valid snapshots and allow decisions', () => {
@@ -111,7 +133,35 @@ describe('tool permissions', () => {
133 const result = yield* gateToolExecution({ toolSlug: 'GMAIL_SEND_EMAIL' });
134
135 expect(result).toBeUndefined();
114 - })
136 + }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
137 + );
138 +
139 + it.effect('preserves permission-policy denial identity', () =>
140 + Effect.gen(function* () {
141 + const failure = yield* gateToolExecution({
142 + toolSlug: 'GMAIL_SEND_EMAIL',
143 + snapshot: {
144 + orgId: 'org_test',
145 + projectId: 'project_test',
146 + consumerUserId: 'user_test',
147 + enhancedControlsEnabled: true,
148 + permissions: {
149 + default: 'allow_all',
150 + overrides: {
151 + 'GMAIL_SEND_EMAIL:__none__': 'always_deny',
152 + },
153 + },
154 + connectedAccountIds: [],
155 + fetchedAt: PINNED_NOW,
156 + },
157 + }).pipe(Effect.flip);
158 +
159 + expect(failure).toBeInstanceOf(ToolPermissionDeniedError);
160 + if (failure instanceof ToolPermissionDeniedError) {
161 + expect(failure.deniedBy).toBe('permissions');
162 + expect(failure.toolSlug).toBe('GMAIL_SEND_EMAIL');
163 + }
164 + }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
165 );
166
167 it.effect('fails closed when interactive approval is needed but permission UI is disabled', () =>
@@ -123,10 +173,42 @@ describe('tool permissions', () => {
173 snapshot: snapshotFixture({ permissions: { default: 'ask_every_call' } }),
174 }).pipe(Effect.flip);
175
126 - expect(failure).toBeInstanceOf(Error);
127 - if (failure instanceof Error) {
176 + expect(failure).toBeInstanceOf(ToolPermissionDeniedError);
177 + if (failure instanceof ToolPermissionDeniedError) {
178 + expect(failure.deniedBy).toBe('permissions');
179 expect(failure.message).toContain('permission prompts are disabled');
180 }
130 - })
181 + }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
182 + );
183 +
184 + it.effect('honors cached allow decisions even when permission UI is disabled', () =>
185 + Effect.gen(function* () {
186 + vi.stubEnv('COMPOSIO_DISABLE_PERMISSION_UI', '1');
187 +
188 + const fs = yield* FileSystem.FileSystem;
189 + const path = yield* Path.Path;
190 + // The shared vitest setup pins COMPOSIO_CACHE_DIR to a fresh temp directory.
191 + const cacheDir = yield* ConfigProvider.fromEnv().load(Config.string('COMPOSIO_CACHE_DIR'));
192 + // Key shape: `${orgId}:${projectId}:${consumerUserId}:${toolSlug}:${accountId}`.
193 + const allowKey = 'org_cached_allow:project_test:user_test:GMAIL_SEND_EMAIL:__none__';
194 + yield* fs.writeFileString(
195 + path.join(cacheDir, 'tool-permissions-cache.json'),
196 + JSON.stringify({
197 + entries: {},
198 + // Unexpired relative to the pinned clock the SUT's expiry check reads.
199 + allowEntries: { [allowKey]: { expiresAt: PINNED_NOW + 60_000 } },
200 + })
201 + );
202 +
203 + const result = yield* gateToolExecution({
204 + toolSlug: 'GMAIL_SEND_EMAIL',
205 + snapshot: snapshotFixture({
206 + orgId: 'org_cached_allow',
207 + permissions: { default: 'ask_every_call' },
208 + }),
209 + });
210 +
211 + expect(result).toStrictEqual({ approvalStatus: 'cached_approved' });
212 + }).pipe(Effect.provide(Layer.mergeAll(BunFileSystem.layer, BunPath.layer)))
213 );
214 });