@devries-cameron20 / composio Mirror · read-only / commits / 377de9729
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

fix(cli): fail closed on permission gaps and tolerate skewed payloads (#3879)

This PR: - lands ten behavioral fixes as one commit each, so `git show` reviews standalone - fails the tool-permission gate closed: an unknown snapshot state or a failed policy resolve on a controls-enabled org now synthesizes an `ask_every_call` snapshot (never persisted) instead of silently skipping the gate, and interactive approval UI never spawns where nobody can answer it (CI/Vitest) - surfaces realtime subscription failures as typed errors: `composio listen` prints one actionable line mentioning `composio login`, cleans up temporary triggers, and exits 1 instead of dumping a captured defect - tolerates newer connected-account payloads with a fallback decode whose field allowlist keeps credential-bearing fields (`state`, `data`) out of `link --list` output - decodes persisted caches and GitHub release listings per entry, so one corrupt or version-skewed entry drops only itself - extracts API error details field by field, renders the deepest cause in pretty errors, and accepts `null` optional strings in agent API responses --- **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 ← **this PR** 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 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:15 UTC 377de97293a8a3dfee1cea0d2d72c54b498a1edf
23 files changed +1333 -331
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+25 -16
@@ -1,5 +1,5 @@
1 import { Args, Command, Options } from '@effect/cli';
2 -import { Effect, Option, Schedule } from 'effect';
2 +import { Data, Effect, Option, Schedule } from 'effect';
3 import type { Composio as RawComposioClient } from '@composio/client';
4 import open from 'open';
5 import { ComposioUserContext } from 'src/services/user-context';
@@ -25,6 +25,14 @@ import {
25 } from 'src/services/connected-account-selection';
26 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 ConnectedAccountsDecodeError extends Data.TaggedError(
31 + 'commands/ConnectedAccountsDecodeError'
32 +)<{
33 + readonly message: string;
34 + readonly cause: unknown;
35 +}> {}
36
37 const toolkit = Args.text({ name: 'toolkit' }).pipe(
38 Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),
@@ -53,9 +61,7 @@ const noWait = Options.boolean('no-wait').pipe(
61
62 const noBrowser = Options.boolean('no-browser').pipe(
63 Options.withDefault(false),
56 - Options.withDescription(
57 - 'Do not open the browser automatically; print the URL to open manually'
58 - )
64 + Options.withDescription('Do not open the browser automatically; print the URL to open manually')
65 );
66
67 const alias = Options.text('alias').pipe(
@@ -431,6 +437,15 @@ const handleListConnectedAccounts = (params: {
437 })
438 )
439 );
440 + const connectedAccounts = yield* decodeConnectedAccountItemsWithFallback(accounts.items).pipe(
441 + Effect.mapError(
442 + cause =>
443 + new ConnectedAccountsDecodeError({
444 + message: 'The API returned invalid connected account data.',
445 + cause,
446 + })
447 + )
448 + );
449
450 if (resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId) {
451 yield* writeConsumerConnectedToolkitsCache({
@@ -438,17 +453,13 @@ const handleListConnectedAccounts = (params: {
453 consumerUserId: resolvedProject.consumerUserId,
454 toolkits: [toolkitSlug],
455 toolRouterConnectedAccounts: {
441 - connectedAccounts: resolveDefaultConnectedAccountsByToolkit(
442 - accounts.items as Parameters<typeof resolveDefaultConnectedAccountsByToolkit>[0]
443 - ),
444 - availableConnectedAccounts: groupCachedConnectedAccountsByToolkit(
445 - accounts.items as Parameters<typeof groupCachedConnectedAccountsByToolkit>[0]
446 - ),
456 + connectedAccounts: resolveDefaultConnectedAccountsByToolkit(connectedAccounts),
457 + availableConnectedAccounts: groupCachedConnectedAccountsByToolkit(connectedAccounts),
458 },
459 }).pipe(Effect.catchAll(() => Effect.void));
460 }
461
451 - if (accounts.items.length === 0) {
462 + if (connectedAccounts.length === 0) {
463 yield* params.ui.log.warn(`No active connected accounts found for "${toolkitSlug}".`);
464 yield* params.ui.output(
465 JSON.stringify({ toolkit: toolkitSlug, items: [], total: 0 }, null, 2),
@@ -458,17 +469,15 @@ const handleListConnectedAccounts = (params: {
469 }
470
471 yield* params.ui.note(
461 - formatConnectedAccountsTable(
462 - accounts.items as Parameters<typeof formatConnectedAccountsTable>[0]
463 - ),
472 + formatConnectedAccountsTable(connectedAccounts),
473 `${toolkitSlug}: connected accounts`
474 );
475 yield* params.ui.output(
476 JSON.stringify(
477 {
478 toolkit: toolkitSlug,
470 - total: accounts.items.length,
471 - items: accounts.items,
479 + total: connectedAccounts.length,
480 + items: connectedAccounts,
481 },
482 null,
483 2
ts/packages/cli/src/commands/listen.cmd.ts
+9
@@ -604,6 +604,15 @@ export const listenCmd = Command.make(
604 ui.log.warn(error instanceof Error ? error.message : String(error))
605 )
606 )
607 + ).pipe(
608 + Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>
609 + Effect.gen(function* () {
610 + yield* ui.log.error(
611 + `Could not subscribe to realtime trigger events: ${error.message}. Check your network connection or run \`composio login\`.`
612 + );
613 + process.exitCode = 1;
614 + })
615 + )
616 );
617 })
618 ).pipe(
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+17 -6
@@ -332,13 +332,24 @@ export const triggersCmd$Listen = Command.make(
332 Effect.onInterrupt(() => ui.log.info('Stopped listening for realtime trigger events.'))
333 );
334
335 - if (maxEventsLimit === undefined) {
336 - yield* listenEffect;
337 - return;
338 - }
335 + yield* Effect.gen(function* () {
336 + if (maxEventsLimit === undefined) {
337 + yield* listenEffect;
338 + return;
339 + }
340
340 - yield* Effect.raceFirst(listenEffect, Deferred.await(stopWhenDone));
341 - yield* ui.outro(`Stopped after receiving ${matchingEvents} matching events.`);
341 + yield* Effect.raceFirst(listenEffect, Deferred.await(stopWhenDone));
342 + yield* ui.outro(`Stopped after receiving ${matchingEvents} matching events.`);
343 + }).pipe(
344 + Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>
345 + Effect.gen(function* () {
346 + yield* ui.log.error(
347 + `Could not subscribe to realtime trigger events: ${error.message}. Check your network connection or run \`composio login\`.`
348 + );
349 + process.exitCode = 1;
350 + })
351 + )
352 + );
353 })
354 ).pipe(
355 Command.withDescription(
ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.test.ts
+4 -4
@@ -11,7 +11,7 @@ describe('extractErrorDetails function', () => {
11 expect(result).toStrictEqual({ isPlainString: true, message: error });
12 });
13
14 - it('should handle errors with cause', () => {
14 + it('should preserve the actionable message for tagged errors with a cause', () => {
15 const _tag = 'MyError';
16 const message = 'Oh no!';
17 const cause = 'Some cause';
@@ -29,8 +29,8 @@ describe('extractErrorDetails function', () => {
29
30 expect(result).toStrictEqual({
31 isPlainString: false,
32 - message: cause,
33 - type: _tag,
32 + message: `${message}\nCaused by: ${cause}`,
33 + type: 'Error',
34 });
35 });
36
@@ -65,7 +65,7 @@ describe('extractErrorDetails function', () => {
65 expect(result).toStrictEqual({
66 isPlainString: false,
67 message: error.message,
68 - type: error._tag,
68 + type: error['_tag'],
69 });
70 });
71
ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.ts
+49 -10
@@ -7,6 +7,41 @@ interface ErrorDetails {
7 message: unknown;
8 }
9
10 +// Wrappers like UpgradeBinaryError carry the actionable specifics (a
11 +// ParseError path, an HTTP body) in `cause`; surface the deepest message so
12 +// the rendered error is debuggable, not just the wrapper's summary line.
13 +const causeDetail = (cause: unknown): string | undefined => {
14 + const seen = new Set<unknown>();
15 + let current: unknown = cause;
16 + let detail: string | undefined;
17 +
18 + while (current !== undefined && current !== null) {
19 + if (typeof current === 'object') {
20 + if (seen.has(current)) break;
21 + seen.add(current);
22 + }
23 +
24 + if (typeof current === 'string' && current.length > 0) {
25 + detail = current;
26 + } else if (
27 + hasProperty(current, 'message') &&
28 + typeof current.message === 'string' &&
29 + current.message.length > 0
30 + ) {
31 + detail = current.message;
32 + }
33 +
34 + current = hasProperty(current, 'cause') ? current.cause : undefined;
35 + }
36 +
37 + return detail;
38 +};
39 +
40 +const withCauseDetail = (message: string, cause: unknown): string => {
41 + const detail = causeDetail(cause);
42 + return detail !== undefined && detail !== message ? `${message}\nCaused by: ${detail}` : message;
43 +};
44 +
45 export const extractErrorDetails = (error: unknown): ErrorDetails => {
46 if (typeof error === 'string') {
47 return {
@@ -20,8 +55,8 @@ export const extractErrorDetails = (error: unknown): ErrorDetails => {
55 if (isTaggedErrorWithCause) {
56 return {
57 isPlainString: false,
23 - type: error._tag,
24 - message: error.cause,
58 + type: error.name,
59 + message: withCauseDetail(error.message, error.cause),
60 };
61 }
62
@@ -39,18 +74,22 @@ export const extractErrorDetails = (error: unknown): ErrorDetails => {
74 if (isPlainObjectsWithTagAttribute) {
75 return {
76 isPlainString: false,
42 - type: error._tag,
77 + type: error['_tag'],
78 message: error.message,
79 };
80 }
81
47 - const isPlainObjectsWithToStringImpl =
48 - hasProperty(error, 'toString') &&
49 - isFunction(error.toString) &&
50 - error.toString !== Object.prototype.toString &&
51 - error.toString !== Array.prototype.toString;
52 - if (isPlainObjectsWithToStringImpl) {
53 - const message = (error as { toString: () => string }).toString();
82 + if (hasProperty(error, 'toString')) {
83 + const toString = error.toString;
84 + const isPlainObjectsWithToStringImpl =
85 + isFunction(toString) &&
86 + toString !== Object.prototype.toString &&
87 + toString !== Array.prototype.toString;
88 + if (!isPlainObjectsWithToStringImpl) {
89 + return { message: `Error: ${JSON.stringify(error)}`, isPlainString: false };
90 + }
91 +
92 + const message = String(toString.call(error));
93 const maybeWithUnderlyingType = message.split(': ');
94
95 if (maybeWithUnderlyingType.length > 1) {
ts/packages/cli/src/effects/create-tool-router-session.ts
+10 -12
@@ -221,18 +221,16 @@ export const createToolRouterSessionContext = (
221 experimental: Object.keys(experimentalPayload).length > 0 ? experimentalPayload : undefined,
222 })
223 ).pipe(
224 - Effect.map(
225 - (session): CreatedToolRouterSession => ({
226 - sessionId: session.session_id,
227 - localExperimentalPayload,
228 - permissionSnapshot,
229 - connectedAccounts: connectionContext.connectedAccounts,
230 - connectedAccountWordIds: resolveConnectedAccountWordIds(
231 - connectionContext.connectedAccounts,
232 - connectionContext.availableConnectedAccounts
233 - ),
234 - })
235 - )
224 + Effect.map((session): CreatedToolRouterSession => ({
225 + sessionId: session.session_id,
226 + localExperimentalPayload,
227 + permissionSnapshot,
228 + connectedAccounts: connectionContext.connectedAccounts,
229 + connectedAccountWordIds: resolveConnectedAccountWordIds(
230 + connectionContext.connectedAccounts,
231 + connectionContext.availableConnectedAccounts
232 + ),
233 + }))
234 );
235 });
236
ts/packages/cli/src/effects/decode-connected-account-list.ts
+40
@@ -1,4 +1,9 @@
1 import { Effect, Schema } from 'effect';
2 +import type { ParseResult } from 'effect';
3 +import {
4 + ConnectedAccountItems,
5 + ConnectedAccountItemsPermissive,
6 +} from 'src/models/connected-accounts';
7 import {
8 ConnectedAccountListResponse,
9 type ConnectedAccountListResponse as ConnectedAccountListResponseType,
@@ -37,3 +42,38 @@ export const decodeConnectedAccountListWithFallback = (
42 )
43 );
44 });
45 +
46 +/**
47 + * Item-level variant of {@link decodeConnectedAccountListWithFallback} for
48 + * call sites that decode `response.items` rather than the whole list
49 + * response. Same forward-compat contract: on `ParseError` (e.g. a status
50 + * value newer than this CLI's closed `Schema.Literal(...)`) warn via
51 + * `ui.log.warn` and retry with `status` widened to `Schema.String`.
52 + *
53 + * Unlike the list-response helper above, this one must NOT fall back to the
54 + * raw payload: `link --list` JSON-dumps the decoded items to stdout, so the
55 + * schema's field allowlist is what keeps credential-bearing fields (`state`,
56 + * `data`, ...) out of pipeable output. The permissive re-decode preserves
57 + * that allowlist; truly malformed data still fails with `ParseError`.
58 + */
59 +export const decodeConnectedAccountItemsWithFallback = (
60 + rawItems: unknown
61 +): Effect.Effect<ConnectedAccountItems, ParseResult.ParseError, TerminalUI> =>
62 + Effect.gen(function* () {
63 + const ui = yield* TerminalUI;
64 + return yield* Schema.decodeUnknown(ConnectedAccountItems)(rawItems).pipe(
65 + Effect.catchTag('ParseError', error =>
66 + Effect.gen(function* () {
67 + yield* ui.log.warn(
68 + `Server returned a connection field this CLI does not recognize ` +
69 + `(likely a newly-added status). Run "composio upgrade" to pick up ` +
70 + `the latest schema. Continuing with a permissive schema.\n\n` +
71 + `Decode error: ${error.message}`
72 + );
73 + const permissive = yield* Schema.decodeUnknown(ConnectedAccountItemsPermissive)(rawItems);
74 + // Identical shape modulo the widened `status`; callers render it as text.
75 + return permissive as ConnectedAccountItems;
76 + })
77 + )
78 + );
79 + });
ts/packages/cli/src/effects/resolve-cli-release.ts
+128 -38
@@ -1,19 +1,37 @@
1 -import { Effect } from 'effect';
2 -import { HttpClient } from '@effect/platform';
1 +import { Data, Effect, Option, Schema } from 'effect';
2 +import { HttpClient, HttpClientResponse } from '@effect/platform';
3 import { semverComparator } from 'src/effects/compare-semver';
4 import type { CliReleaseChannel } from 'src/constants';
5
6 -export type GitHubReleaseAsset = {
7 - name: string;
8 - browser_download_url: string;
9 -};
6 +export const GitHubReleaseAsset = Schema.Struct({
7 + name: Schema.NonEmptyString,
8 + browser_download_url: Schema.NonEmptyString,
9 +});
10 +export type GitHubReleaseAsset = typeof GitHubReleaseAsset.Type;
11 +export const GitHubReleaseAssets = Schema.Array(GitHubReleaseAsset);
12
11 -export type GitHubRelease = {
12 - tag_name: string;
13 - prerelease?: boolean;
14 - draft?: boolean;
15 - assets: Array<GitHubReleaseAsset>;
16 -};
13 +export const GitHubRelease = Schema.Struct({
14 + tag_name: Schema.NonEmptyString,
15 + prerelease: Schema.optional(Schema.Boolean),
16 + draft: Schema.optional(Schema.Boolean),
17 + assets: GitHubReleaseAssets,
18 +});
19 +export type GitHubRelease = typeof GitHubRelease.Type;
20 +
21 +// Decoded per element: the endpoint returns up to 100 releases spanning the
22 +// whole repo, and one deviant entry (a draft mid-upload with a null asset
23 +// URL) must not fail resolution for the well-formed CLI releases.
24 +const RawGitHubReleases = Schema.Array(Schema.Unknown);
25 +const decodeGitHubRelease = Schema.decodeUnknownOption(GitHubRelease);
26 +
27 +export class CliReleaseResolutionError extends Data.TaggedError(
28 + 'effects/CliReleaseResolutionError'
29 +)<{
30 + readonly cause?: unknown;
31 + readonly message: string;
32 + readonly reason: 'request' | 'http-status' | 'decode' | 'not-found' | 'compare';
33 + readonly status?: number;
34 +}> {}
35
36 export type GitHubRepoConfig = {
37 API_BASE_URL: string;
@@ -23,6 +41,50 @@ export type GitHubRepoConfig = {
41
42 export const CLI_RELEASE_TAG_PATTERN = /^@composio\/cli@\d+\.\d+\.\d+.*$/;
43
44 +const GitHubReleaseByTag = Schema.Struct({ assets: GitHubReleaseAssets });
45 +
46 +export const fetchCliReleaseByTag = ({
47 + githubConfig,
48 + httpClient,
49 + tag,
50 +}: {
51 + githubConfig: GitHubRepoConfig;
52 + httpClient: HttpClient.HttpClient;
53 + tag: string;
54 +}) =>
55 + Effect.gen(function* () {
56 + const releaseUrl = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases/tags/${encodeURIComponent(tag)}`;
57 + const releaseResponse = yield* httpClient.get(releaseUrl).pipe(
58 + Effect.mapError(
59 + cause =>
60 + new CliReleaseResolutionError({
61 + cause,
62 + message: `Failed to fetch release ${tag}`,
63 + reason: 'request',
64 + })
65 + )
66 + );
67 +
68 + if (releaseResponse.status < 200 || releaseResponse.status >= 300) {
69 + return yield* new CliReleaseResolutionError({
70 + message: `Release ${tag} not found (HTTP ${releaseResponse.status})`,
71 + reason: 'http-status',
72 + status: releaseResponse.status,
73 + });
74 + }
75 +
76 + return yield* HttpClientResponse.schemaBodyJson(GitHubReleaseByTag)(releaseResponse).pipe(
77 + Effect.mapError(
78 + cause =>
79 + new CliReleaseResolutionError({
80 + cause,
81 + message: `Failed to decode release ${tag}`,
82 + reason: 'decode',
83 + })
84 + )
85 + );
86 + });
87 +
88 export const fetchLatestCliRelease = ({
89 assetDescription,
90 channel,
@@ -38,54 +100,82 @@ export const fetchLatestCliRelease = ({
100 }) =>
101 Effect.gen(function* () {
102 const releaseUrl = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases?per_page=100`;
41 - const releaseResponse = yield* httpClient
42 - .get(releaseUrl)
43 - .pipe(
44 - Effect.catchAll(error =>
45 - Effect.fail(new Error(`Failed to fetch ${channel} releases from GitHub: ${error}`))
46 - )
47 - );
103 + const releaseResponse = yield* httpClient.get(releaseUrl).pipe(
104 + Effect.mapError(
105 + cause =>
106 + new CliReleaseResolutionError({
107 + cause,
108 + message: `Failed to fetch ${channel} releases from GitHub`,
109 + reason: 'request',
110 + })
111 + )
112 + );
113
114 if (releaseResponse.status < 200 || releaseResponse.status >= 300) {
115 return yield* Effect.fail(
51 - new Error(
52 - `Failed to fetch ${channel} releases from GitHub (HTTP ${releaseResponse.status})`
53 - )
116 + new CliReleaseResolutionError({
117 + message: `Failed to fetch ${channel} releases from GitHub (HTTP ${releaseResponse.status})`,
118 + reason: 'http-status',
119 + status: releaseResponse.status,
120 + })
121 );
122 }
123
57 - const releases = (yield* releaseResponse.json.pipe(
58 - Effect.catchAll(() => Effect.fail(new Error('Failed to parse GitHub releases JSON')))
59 - )) as unknown;
60 -
61 - if (!Array.isArray(releases)) {
62 - return yield* Effect.fail(new Error('GitHub releases response was not an array'));
124 + const rawReleases = yield* HttpClientResponse.schemaBodyJson(RawGitHubReleases)(
125 + releaseResponse
126 + ).pipe(
127 + Effect.mapError(
128 + cause =>
129 + new CliReleaseResolutionError({
130 + cause,
131 + message: 'Failed to decode GitHub releases response',
132 + reason: 'decode',
133 + })
134 + )
135 + );
136 + const releases = rawReleases.flatMap(entry =>
137 + Option.match(decodeGitHubRelease(entry), {
138 + onNone: () => [],
139 + onSome: release => [release],
140 + })
141 + );
142 + if (releases.length < rawReleases.length) {
143 + yield* Effect.logDebug(
144 + `Skipped ${rawReleases.length - releases.length} malformed GitHub release entries.`
145 + );
146 }
147
148 const prerelease = channel === 'beta';
149 const matchingReleases = releases.filter(
67 - (release): release is GitHubRelease =>
68 - typeof release === 'object' &&
69 - release !== null &&
70 - 'tag_name' in release &&
71 - typeof release.tag_name === 'string' &&
72 - ('prerelease' in release ? release.prerelease === prerelease : prerelease === false) &&
73 - ('draft' in release ? release.draft === false : true) &&
150 + release =>
151 + (release.prerelease === undefined
152 + ? prerelease === false
153 + : release.prerelease === prerelease) &&
154 + release.draft !== true &&
155 CLI_RELEASE_TAG_PATTERN.test(release.tag_name) &&
75 - Array.isArray(release.assets) &&
156 hasRequiredAsset(release)
157 );
158
159 if (matchingReleases.length === 0) {
160 return yield* Effect.fail(
81 - new Error(`No ${channel} CLI releases found with ${assetDescription}`)
161 + new CliReleaseResolutionError({
162 + message: `No ${channel} CLI releases found with ${assetDescription}`,
163 + reason: 'not-found',
164 + })
165 );
166 }
167
168 let latest = matchingReleases[0];
169 for (const release of matchingReleases.slice(1)) {
170 const comparison = yield* semverComparator(latest.tag_name, release.tag_name).pipe(
88 - Effect.mapError(error => new Error(`Failed to compare release versions: ${error}`))
171 + Effect.mapError(
172 + cause =>
173 + new CliReleaseResolutionError({
174 + cause,
175 + message: `Failed to compare release versions: ${latest.tag_name} and ${release.tag_name}`,
176 + reason: 'compare',
177 + })
178 + )
179 );
180
181 if (comparison < 0) {
ts/packages/cli/src/models/connected-accounts.ts
+12
@@ -42,3 +42,15 @@ export type ConnectedAccountItem = Schema.Schema.Type<typeof ConnectedAccountIte
42
43 export const ConnectedAccountItems = Schema.Array(ConnectedAccountItem);
44 export type ConnectedAccountItems = Schema.Schema.Type<typeof ConnectedAccountItems>;
45 +
46 +/**
47 + * Forward-compatible variant of {@link ConnectedAccountItem}: identical field
48 + * allowlist (same credential-stripping guarantee as above) with `status`
49 + * widened to accept values newer than this CLI build's closed literal union.
50 + */
51 +export const ConnectedAccountItemPermissive = Schema.Struct({
52 + ...ConnectedAccountItem.fields,
53 + status: Schema.String,
54 +}).annotations({ identifier: 'ConnectedAccountItemPermissive' });
55 +
56 +export const ConnectedAccountItemsPermissive = Schema.Array(ConnectedAccountItemPermissive);
ts/packages/cli/src/services/agents.ts
+209 -136
@@ -1,5 +1,5 @@
1 import { FileSystem } from '@effect/platform';
2 -import { Data, Effect, Option } from 'effect';
2 +import { Data, Effect, Option, Predicate, Schema } from 'effect';
3 import path from 'node:path';
4 import { setupCacheDir } from 'src/effects/setup-cache-dir';
5 import { ComposioUserContext } from 'src/services/user-context';
@@ -10,68 +10,93 @@ export const DEFAULT_AGENTS_BASE_URL = 'https://agents.composio.dev';
10
11 export type AgentStatus = 'READY' | 'PENDING' | 'UNKNOWN';
12
13 -export interface AgentComposioCredentials {
14 - readonly member_id?: string;
15 - readonly org_id?: string;
16 - readonly project_id?: string;
17 - readonly api_key?: string;
18 - readonly user_api_key?: string;
19 -}
20 -
21 -export interface AgentIdentity {
22 - readonly status?: string;
23 - readonly request_id?: string;
24 - readonly slug?: string;
25 - readonly email?: string;
26 - readonly agent_key?: string;
27 - readonly composio_agent_key?: string;
28 - readonly claimed_by?: string | null;
29 - readonly claimed_at?: string | null;
30 - readonly composio?: AgentComposioCredentials;
31 - readonly [key: string]: unknown;
32 -}
33 -
34 -export interface AgentMailMessage {
35 - readonly id?: string;
36 - readonly thread_id?: string;
37 - readonly from?: string;
38 - readonly to?: string;
39 - readonly subject?: string;
40 - readonly preview?: string;
41 - readonly received_at?: string;
42 - readonly [key: string]: unknown;
43 -}
44 -
45 -export interface AgentMailResponse {
46 - readonly count?: number;
47 - readonly messages?: ReadonlyArray<AgentMailMessage>;
48 - readonly [key: string]: unknown;
49 -}
50 -
51 -export interface AgentClaimResponse {
52 - readonly status?: string;
53 - readonly email?: string;
54 - readonly org_id?: string;
55 - readonly invite_code?: string;
56 - readonly [key: string]: unknown;
57 -}
13 +const UnknownFields = Schema.Record({ key: Schema.String, value: Schema.Unknown });
14 +
15 +const AgentComposioCredentials = Schema.Struct({
16 + member_id: Schema.optional(Schema.NullOr(Schema.String)),
17 + org_id: Schema.optional(Schema.NullOr(Schema.String)),
18 + project_id: Schema.optional(Schema.NullOr(Schema.String)),
19 + api_key: Schema.optional(Schema.NullOr(Schema.String)),
20 + user_api_key: Schema.optional(Schema.NullOr(Schema.String)),
21 +}).pipe(Schema.extend(UnknownFields));
22 +export type AgentComposioCredentials = Schema.Schema.Type<typeof AgentComposioCredentials>;
23 +
24 +const AgentIdentity = Schema.Struct({
25 + status: Schema.optional(Schema.NullOr(Schema.String)),
26 + request_id: Schema.optional(Schema.NullOr(Schema.String)),
27 + slug: Schema.optional(Schema.NullOr(Schema.String)),
28 + email: Schema.optional(Schema.NullOr(Schema.String)),
29 + agent_key: Schema.optional(Schema.NullOr(Schema.String)),
30 + composio_agent_key: Schema.optional(Schema.NullOr(Schema.String)),
31 + claimed_by: Schema.optional(Schema.NullOr(Schema.String)),
32 + claimed_at: Schema.optional(Schema.NullOr(Schema.String)),
33 + composio: Schema.optional(AgentComposioCredentials),
34 +}).pipe(Schema.extend(UnknownFields));
35 +export type AgentIdentity = Schema.Schema.Type<typeof AgentIdentity>;
36 +
37 +const AgentMailMessage = Schema.Struct({
38 + id: Schema.optional(Schema.NullOr(Schema.String)),
39 + thread_id: Schema.optional(Schema.NullOr(Schema.String)),
40 + from: Schema.optional(Schema.NullOr(Schema.String)),
41 + to: Schema.optional(Schema.NullOr(Schema.String)),
42 + subject: Schema.optional(Schema.NullOr(Schema.String)),
43 + preview: Schema.optional(Schema.NullOr(Schema.String)),
44 + received_at: Schema.optional(Schema.NullOr(Schema.String)),
45 +}).pipe(Schema.extend(UnknownFields));
46 +export type AgentMailMessage = Schema.Schema.Type<typeof AgentMailMessage>;
47 +
48 +const AgentMailResponse = Schema.Struct({
49 + count: Schema.optional(Schema.Number),
50 + messages: Schema.optional(Schema.Array(AgentMailMessage)),
51 +}).pipe(Schema.extend(UnknownFields));
52 +export type AgentMailResponse = Schema.Schema.Type<typeof AgentMailResponse>;
53 +
54 +const AgentClaimResponse = Schema.Struct({
55 + status: Schema.optional(Schema.NullOr(Schema.String)),
56 + email: Schema.optional(Schema.NullOr(Schema.String)),
57 + org_id: Schema.optional(Schema.NullOr(Schema.String)),
58 + invite_code: Schema.optional(Schema.NullOr(Schema.String)),
59 +}).pipe(Schema.extend(UnknownFields));
60 +export type AgentClaimResponse = Schema.Schema.Type<typeof AgentClaimResponse>;
61
62 export class AgentAuthError extends Data.TaggedError('services/AgentAuthError')<{
63 readonly message: string;
64 readonly nextSteps: ReadonlyArray<string>;
65 }> {}
66
67 +export class AgentRequestError extends Data.TaggedError('services/AgentRequestError')<{
68 + readonly message: string;
69 + readonly pathname: string;
70 + readonly status?: number;
71 + readonly cause?: unknown;
72 +}> {}
73 +
74 +export class AgentResponseDecodeError extends Data.TaggedError(
75 + 'services/AgentResponseDecodeError'
76 +)<{
77 + readonly message: string;
78 + readonly pathname: string;
79 + readonly cause: unknown;
80 +}> {}
81 +
82 const agentsBaseURL = (): string =>
83 (process.env.COMPOSIO_AGENTS_BASE_URL ?? DEFAULT_AGENTS_BASE_URL).replace(/\/+$/, '');
84
67 -const asRecord = (value: unknown): Record<string, unknown> =>
68 - value && typeof value === 'object' && !Array.isArray(value)
69 - ? (value as Record<string, unknown>)
70 - : {};
71 -
72 -const readJson = (value: string): unknown => JSON.parse(value) as unknown;
85 +const decodeAgentResponse =
86 + <A, I>(pathname: string, schema: Schema.Schema<A, I>) =>
87 + (payload: unknown) =>
88 + Schema.decodeUnknown(schema)(payload).pipe(
89 + Effect.mapError(
90 + cause =>
91 + new AgentResponseDecodeError({
92 + message: `agents.composio.dev returned an invalid response for ${pathname}`,
93 + pathname,
94 + cause,
95 + })
96 + )
97 + );
98
74 -export const normalizeAgentStatus = (status: string | undefined): AgentStatus => {
99 +export const normalizeAgentStatus = (status: string | null | undefined): AgentStatus => {
100 const normalized = status?.trim().toUpperCase();
101 if (normalized === 'READY') return 'READY';
102 if (normalized === 'PENDING') return 'PENDING';
@@ -87,27 +112,40 @@ export const getAgentKey = (identity: AgentIdentity): string | undefined => {
112 export const isAgentIdentityForApiKey = (identity: AgentIdentity, apiKey: string): boolean =>
113 Boolean(getAgentKey(identity) && identity.composio?.user_api_key === apiKey);
114
115 +const normalizeDecodedAgentIdentity = (
116 + identity: AgentIdentity,
117 + fallbackAgentKey?: string
118 +): AgentIdentity => {
119 + const agentKey = identity.composio_agent_key ?? identity.agent_key ?? fallbackAgentKey;
120 +
121 + return agentKey ? { ...identity, agent_key: agentKey, composio_agent_key: agentKey } : identity;
122 +};
123 +
124 export const normalizeAgentIdentity = (
125 payload: unknown,
126 fallbackAgentKey?: string
93 -): AgentIdentity => {
94 - const record = asRecord(payload);
95 - const agentKey =
96 - (typeof record.composio_agent_key === 'string' ? record.composio_agent_key : undefined) ??
97 - (typeof record.agent_key === 'string' ? record.agent_key : undefined) ??
98 - fallbackAgentKey;
99 -
100 - const normalized: Record<string, unknown> = { ...record };
101 - if (agentKey) {
102 - normalized.agent_key = agentKey;
103 - normalized.composio_agent_key = agentKey;
104 - }
127 +): AgentIdentity =>
128 + normalizeDecodedAgentIdentity(
129 + Schema.decodeUnknownOption(AgentIdentity)(payload).pipe(
130 + Option.getOrElse((): AgentIdentity => ({}))
131 + ),
132 + fallbackAgentKey
133 + );
134
106 - return normalized as AgentIdentity;
135 +type SafeAgentSummary = {
136 + readonly account_type: 'agent';
137 + readonly status: AgentStatus;
138 + readonly slug: string | null;
139 + readonly email: string | null;
140 + readonly org_id: string | null;
141 + readonly project_id: string | null;
142 + readonly member_id: string | null;
143 + readonly claimed_by: string | null;
144 + readonly claimed_at: string | null;
145 };
146
109 -export const safeAgentSummary = (identity: AgentIdentity) => ({
110 - account_type: 'agent' as const,
147 +export const safeAgentSummary = (identity: AgentIdentity): SafeAgentSummary => ({
148 + account_type: 'agent',
149 status: normalizeAgentStatus(identity.status),
150 slug: identity.slug ?? null,
151 email: identity.email ?? null,
@@ -131,13 +169,10 @@ export const readStoredAgentIdentity = Effect.gen(function* () {
169 if (!exists) return Option.none<AgentIdentity>();
170
171 return yield* fs.readFileString(configPath, 'utf8').pipe(
134 - Effect.map(raw => Option.some(normalizeAgentIdentity(readJson(raw)))),
135 - Effect.catchAll(error =>
136 - Effect.gen(function* () {
137 - yield* Effect.logDebug('Failed to read agent identity:', error);
138 - return Option.none<AgentIdentity>();
139 - })
140 - )
172 + Effect.flatMap(Schema.decodeUnknown(Schema.parseJson(AgentIdentity))),
173 + Effect.map(normalizeDecodedAgentIdentity),
174 + Effect.tapError(error => Effect.logDebug('Failed to read agent identity:', error)),
175 + Effect.option
176 );
177 });
178
@@ -145,7 +180,7 @@ export const writeStoredAgentIdentity = (identity: AgentIdentity) =>
180 Effect.gen(function* () {
181 const fs = yield* FileSystem.FileSystem;
182 const configPath = yield* agentConfigPath;
148 - const normalized = normalizeAgentIdentity(identity);
183 + const normalized = normalizeDecodedAgentIdentity(identity);
184 yield* fs.writeFileString(configPath, `${JSON.stringify(normalized, null, 2)}\n`);
185 return normalized;
186 });
@@ -153,34 +188,66 @@ export const writeStoredAgentIdentity = (identity: AgentIdentity) =>
188 export const removeStoredAgentIdentity = Effect.gen(function* () {
189 const fs = yield* FileSystem.FileSystem;
190 const configPath = yield* agentConfigPath;
156 - yield* fs.remove(configPath).pipe(Effect.catchAll(() => Effect.void));
191 + yield* fs.remove(configPath).pipe(Effect.ignore);
192 });
193
194 const fetchAgentJson = (pathname: string, init: RequestInit = {}) =>
160 - Effect.tryPromise({
161 - try: async () => {
162 - const response = await fetch(`${agentsBaseURL()}${pathname}`, {
163 - redirect: 'error',
164 - ...init,
165 - headers: {
166 - Accept: 'application/json',
167 - ...(init.body ? { 'Content-Type': 'application/json' } : {}),
168 - ...(init.headers ?? {}),
169 - },
195 + Effect.gen(function* () {
196 + const response = yield* Effect.tryPromise({
197 + try: () =>
198 + fetch(`${agentsBaseURL()}${pathname}`, {
199 + redirect: 'error',
200 + ...init,
201 + headers: {
202 + Accept: 'application/json',
203 + ...(init.body ? { 'Content-Type': 'application/json' } : {}),
204 + ...(init.headers ?? {}),
205 + },
206 + }),
207 + catch: cause =>
208 + new AgentRequestError({
209 + message: `agents.composio.dev request failed for ${pathname}`,
210 + pathname,
211 + cause,
212 + }),
213 + });
214 +
215 + const text = yield* Effect.tryPromise({
216 + try: () => response.text(),
217 + catch: cause =>
218 + new AgentRequestError({
219 + message: `Failed to read agents.composio.dev response for ${pathname}`,
220 + pathname,
221 + status: response.status,
222 + cause,
223 + }),
224 + });
225 + const payload = text
226 + ? yield* Schema.decodeUnknown(Schema.parseJson(Schema.Unknown))(text).pipe(
227 + Effect.mapError(
228 + cause =>
229 + new AgentResponseDecodeError({
230 + message: `agents.composio.dev returned invalid JSON for ${pathname}`,
231 + pathname,
232 + cause,
233 + })
234 + )
235 + )
236 + : {};
237 +
238 + if (!response.ok) {
239 + const message =
240 + Predicate.isRecord(payload) && typeof payload.message === 'string'
241 + ? payload.message
242 + : `agents.composio.dev request failed with HTTP ${response.status}`;
243 + return yield* new AgentRequestError({
244 + message,
245 + pathname,
246 + status: response.status,
247 });
248 + }
249
172 - const text = await response.text();
173 - const payload = text ? (JSON.parse(text) as unknown) : {};
174 - if (!response.ok) {
175 - const message =
176 - typeof asRecord(payload).message === 'string'
177 - ? (asRecord(payload).message as string)
178 - : `agents.composio.dev request failed with HTTP ${response.status}`;
179 - throw new Error(message);
180 - }
181 - return payload;
182 - },
183 - catch: error => (error instanceof Error ? error : new Error(String(error))),
250 + return payload;
251 });
252
253 export const signupAgent = (params: { wait?: boolean } = {}) =>
@@ -190,7 +257,8 @@ export const signupAgent = (params: { wait?: boolean } = {}) =>
257 method: 'POST',
258 body: JSON.stringify({}),
259 });
193 - return yield* writeStoredAgentIdentity(normalizeAgentIdentity(payload));
260 + const identity = yield* decodeAgentResponse('/api/signup', AgentIdentity)(payload);
261 + return yield* writeStoredAgentIdentity(identity);
262 });
263
264 export const fetchAgentWhoami = (agentKey: string) =>
@@ -199,21 +267,30 @@ export const fetchAgentWhoami = (agentKey: string) =>
267 method: 'GET',
268 headers: { Authorization: `Bearer ${agentKey}` },
269 });
202 - return normalizeAgentIdentity(payload, agentKey);
270 + const identity = yield* decodeAgentResponse('/api/whoami', AgentIdentity)(payload);
271 + return normalizeDecodedAgentIdentity(identity, agentKey);
272 });
273
274 export const fetchAgentInbox = (params: { agentKey: string; limit?: number }) =>
206 - fetchAgentJson(`/api/mail?limit=${encodeURIComponent(String(params.limit ?? 50))}`, {
207 - method: 'GET',
208 - headers: { Authorization: `Bearer ${params.agentKey}` },
209 - }).pipe(Effect.map(payload => payload as AgentMailResponse));
275 + Effect.gen(function* () {
276 + const pathname = `/api/mail?limit=${encodeURIComponent(String(params.limit ?? 50))}`;
277 + const payload = yield* fetchAgentJson(pathname, {
278 + method: 'GET',
279 + headers: { Authorization: `Bearer ${params.agentKey}` },
280 + });
281 + return yield* decodeAgentResponse(pathname, AgentMailResponse)(payload);
282 + });
283
284 export const claimAgent = (params: { agentKey: string; email: string }) =>
212 - fetchAgentJson('/api/claim', {
213 - method: 'POST',
214 - headers: { Authorization: `Bearer ${params.agentKey}` },
215 - body: JSON.stringify({ email: params.email }),
216 - }).pipe(Effect.map(payload => payload as AgentClaimResponse));
285 + Effect.gen(function* () {
286 + const pathname = '/api/claim';
287 + const payload = yield* fetchAgentJson(pathname, {
288 + method: 'POST',
289 + headers: { Authorization: `Bearer ${params.agentKey}` },
290 + body: JSON.stringify({ email: params.email }),
291 + });
292 + return yield* decodeAgentResponse(pathname, AgentClaimResponse)(payload);
293 + });
294
295 const humanLoginError = () =>
296 new AgentAuthError({
@@ -232,7 +309,7 @@ export const ensureAgentSignupAllowed = Effect.gen(function* () {
309 const stored = yield* readStoredAgentIdentity;
310 if (Option.isSome(stored) && isAgentIdentityForApiKey(stored.value, apiKey.value)) return;
311
235 - return yield* Effect.fail(humanLoginError());
312 + return yield* humanLoginError();
313 });
314
315 export const getCurrentLoggedInAgent = Effect.gen(function* () {
@@ -255,35 +332,32 @@ export const resolveStoredAgentKey = Effect.gen(function* () {
332
333 if (Option.isSome(currentApiKey)) {
334 if (Option.isSome(stored) && isAgentIdentityForApiKey(stored.value, currentApiKey.value)) {
258 - return getAgentKey(stored.value) as string;
335 + const agentKey = getAgentKey(stored.value);
336 + if (agentKey) return agentKey;
337 }
338
261 - return yield* Effect.fail(humanLoginError());
339 + return yield* humanLoginError();
340 }
341
342 if (Option.isNone(stored)) {
265 - return yield* Effect.fail(
266 - new AgentAuthError({
267 - message: 'No Composio agent identity is saved on this machine.',
268 - nextSteps: [
269 - 'To create a new agent: run `composio signup` or `composio agent signup`.',
270 - 'To restore an existing agent: run `composio agent login <composio_agent_key>`.',
271 - ],
272 - })
273 - );
343 + return yield* new AgentAuthError({
344 + message: 'No Composio agent identity is saved on this machine.',
345 + nextSteps: [
346 + 'To create a new agent: run `composio signup` or `composio agent signup`.',
347 + 'To restore an existing agent: run `composio agent login <composio_agent_key>`.',
348 + ],
349 + });
350 }
351
352 const agentKey = getAgentKey(stored.value);
353 if (!agentKey) {
278 - return yield* Effect.fail(
279 - new AgentAuthError({
280 - message: 'The saved Composio agent identity is missing its composio_agent_key.',
281 - nextSteps: [
282 - 'If you saved the key, run `composio agent login <composio_agent_key>`.',
283 - 'Otherwise create a new agent with `composio signup`.',
284 - ],
285 - })
286 - );
354 + return yield* new AgentAuthError({
355 + message: 'The saved Composio agent identity is missing its composio_agent_key.',
356 + nextSteps: [
357 + 'If you saved the key, run `composio agent login <composio_agent_key>`.',
358 + 'Otherwise create a new agent with `composio signup`.',
359 + ],
360 + });
361 }
362
363 return agentKey;
@@ -315,11 +389,10 @@ export const loginWithAgentIdentity = (identity: AgentIdentity) =>
389 const orgId = identity.composio?.org_id;
390
391 if (!userApiKey || !orgId) {
318 - return yield* Effect.fail(
319 - new Error(
320 - 'Agent identity is not ready yet. Run `composio agent whoami` and try again once status is READY.'
321 - )
322 - );
392 + return yield* new AgentAuthError({
393 + message: 'Agent identity is not ready yet.',
394 + nextSteps: ['Run `composio agent whoami` and try again once status is READY.'],
395 + });
396 }
397
398 yield* ctx.login(userApiKey, orgId);
ts/packages/cli/src/services/connected-account-selection.ts
+9 -7
@@ -1,4 +1,5 @@
1 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
2 +import { Schema } from 'effect';
3
4 // `ConnectedAccountItem` widened with an `'UNKNOWN'` sentinel for statuses
5 // the closed schema doesn't yet know about. Selection only picks `'ACTIVE'`,
@@ -8,13 +9,14 @@ export type SelectableConnectedAccount = Omit<ConnectedAccountItem, 'status'> &
9 readonly status: ConnectedAccountItem['status'] | 'UNKNOWN';
10 };
11
11 -export type CachedConnectedAccountSummary = {
12 - readonly id: string;
13 - readonly alias: string | null;
14 - readonly wordId: string | null;
15 - readonly updatedAt: string;
16 - readonly createdAt: string;
17 -};
12 +export const CachedConnectedAccountSummarySchema = Schema.Struct({
13 + id: Schema.String,
14 + alias: Schema.NullOr(Schema.String),
15 + wordId: Schema.NullOr(Schema.String),
16 + updatedAt: Schema.String,
17 + createdAt: Schema.String,
18 +});
19 +export type CachedConnectedAccountSummary = typeof CachedConnectedAccountSummarySchema.Type;
20
21 const normalizeSelector = (value: string): string => value.trim().toLowerCase();
22
ts/packages/cli/src/services/consumer-short-term-cache.ts
+76 -51
@@ -1,6 +1,6 @@
1 import path from 'node:path';
2 import { FileSystem } from '@effect/platform';
3 -import { Effect, Option } from 'effect';
3 +import { Effect, Option, Record as EffectRecord, Schema } from 'effect';
4 import { APP_CONFIG } from 'src/effects/app-config';
5 import { setupCacheDir } from 'src/effects/setup-cache-dir';
6 import { NodeProcess } from 'src/services/node-process';
@@ -10,42 +10,69 @@ import {
10 getConsumerConnectedToolkits,
11 resolveConsumerProject,
12 } from 'src/services/composio-clients';
13 -import type { CachedConnectedAccountSummary } from 'src/services/connected-account-selection';
13 import { resolveCommandProject } from 'src/services/command-project';
14 import { resolveToolRouterSessionConnections } from 'src/services/tool-router-session-connections';
15 import { ComposioUserContext } from 'src/services/user-context';
16 +import {
17 + CachedConnectedAccountSummarySchema,
18 + type CachedConnectedAccountSummary,
19 +} from 'src/services/connected-account-selection';
20
21 const CACHE_FILE = 'consumer-short-term-cache.json';
22 const CACHE_TTL_MS = 15 * 60 * 1000;
23 const SEARCH_SESSION_EXTENSION_MS = 5 * 60 * 1000;
24
22 -export type ConsumerToolRouterAuthConfigMappings = {
23 - readonly authConfigs?: Record<string, string>;
24 -};
25 -
26 -export type ConsumerToolRouterConnectedAccountMappings = {
27 - readonly connectedAccounts?: Record<string, string>;
28 - readonly availableConnectedAccounts?: Record<
29 - string,
30 - ReadonlyArray<CachedConnectedAccountSummary>
31 - >;
32 -};
33 -
34 -type CacheEntry = {
35 - readonly toolkits: ReadonlyArray<string>;
36 - readonly expiresAt: string;
37 - readonly toolRouterAuthConfigs?: ConsumerToolRouterAuthConfigMappings;
38 - readonly toolRouterConnectedAccounts?: ConsumerToolRouterConnectedAccountMappings;
39 - readonly probablyMyCliSessionsByCwdHash?: Record<
40 - string,
41 - {
42 - readonly id: string;
43 - readonly expiresAt: string;
44 - }
45 - >;
46 -};
47 -
48 -type CacheState = Record<string, CacheEntry>;
25 +const StringMappingsSchema = Schema.Record({ key: Schema.String, value: Schema.String });
26 +const AvailableConnectedAccountsSchema = Schema.Record({
27 + key: Schema.String,
28 + value: Schema.Array(CachedConnectedAccountSummarySchema),
29 +});
30 +const ConsumerToolRouterAuthConfigMappingsSchema = Schema.Struct({
31 + authConfigs: Schema.optional(StringMappingsSchema),
32 +});
33 +const ConsumerToolRouterConnectedAccountMappingsSchema = Schema.Struct({
34 + connectedAccounts: Schema.optional(StringMappingsSchema),
35 + availableConnectedAccounts: Schema.optional(AvailableConnectedAccountsSchema),
36 +});
37 +const CacheEntrySchema = Schema.Struct({
38 + toolkits: Schema.Array(Schema.String),
39 + expiresAt: Schema.String,
40 + toolRouterAuthConfigs: Schema.optional(ConsumerToolRouterAuthConfigMappingsSchema),
41 + toolRouterConnectedAccounts: Schema.optional(ConsumerToolRouterConnectedAccountMappingsSchema),
42 + probablyMyCliSessionsByCwdHash: Schema.optional(
43 + Schema.Record({
44 + key: Schema.String,
45 + value: Schema.Struct({ id: Schema.String, expiresAt: Schema.String }),
46 + })
47 + ),
48 +});
49 +export type ConsumerToolRouterAuthConfigMappings =
50 + typeof ConsumerToolRouterAuthConfigMappingsSchema.Type;
51 +export type ConsumerToolRouterConnectedAccountMappings =
52 + typeof ConsumerToolRouterConnectedAccountMappingsSchema.Type;
53 +type CacheEntry = typeof CacheEntrySchema.Type;
54 +type CacheState = { readonly [key: string]: CacheEntry };
55 +const decodeCacheShell = Schema.decodeUnknownOption(
56 + Schema.parseJson(Schema.Record({ key: Schema.String, value: Schema.Unknown }))
57 +);
58 +const decodeCacheEntry = Schema.decodeUnknownOption(CacheEntrySchema);
59 +
60 +// Per-entry decode: one stale or version-skewed entry (e.g. written by a
61 +// newer CLI) drops only itself; discarding the whole cache would also be
62 +// persisted back on the next write, permanently destroying the good entries.
63 +export const decodeCacheStateTolerant = (raw: string): CacheState =>
64 + Option.match(decodeCacheShell(raw), {
65 + onNone: (): CacheState => ({}),
66 + onSome: shell =>
67 + Object.fromEntries(
68 + Object.entries(shell).flatMap(([key, value]) =>
69 + Option.match(decodeCacheEntry(value), {
70 + onNone: () => [],
71 + onSome: entry => [[key, entry] as const],
72 + })
73 + )
74 + ),
75 + });
76
77 const cacheKey = (orgId: string, consumerUserId: string) => `${orgId}:${consumerUserId}`;
78
@@ -74,8 +101,8 @@ const resolveSearchSessionMetadata = (params: {
101 ...(params.currentEntry?.probablyMyCliSessionsByCwdHash ?? {}),
102 };
103
77 - const probablyMyCliSessionsByCwdHash = Object.fromEntries(
78 - Object.entries(previousMap).filter(([, session]) => {
104 + const probablyMyCliSessionsByCwdHash = EffectRecord.fromEntries(
105 + EffectRecord.toEntries(previousMap).filter(([, session]) => {
106 const expiresAtMs = Date.parse(session.expiresAt);
107 return Number.isFinite(expiresAtMs) && expiresAtMs > now;
108 })
@@ -110,9 +137,7 @@ const readCache = () =>
137 return {} satisfies CacheState;
138 }
139 const raw = yield* fs.readFileString(filePath, 'utf8');
113 - return yield* Effect.sync(() => JSON.parse(raw) as CacheState).pipe(
114 - Effect.catchAll(() => Effect.succeed({} satisfies CacheState))
115 - );
140 + return decodeCacheStateTolerant(raw);
141 });
142
143 const writeCache = (state: CacheState) =>
@@ -148,7 +173,7 @@ const normalizeAuthConfigMappings = (
173 .map(([toolkit, authConfigId]) => [toolkit.toLowerCase(), authConfigId])
174 .filter(([, authConfigId]) => typeof authConfigId === 'string' && authConfigId.length > 0)
175 );
151 - if (Object.keys(authConfigs).length === 0) {
176 + if (EffectRecord.isEmptyRecord(authConfigs)) {
177 return undefined;
178 }
179
@@ -204,16 +229,19 @@ const normalizeConnectedAccountMappings = (
229 );
230
231 if (
207 - Object.keys(connectedAccounts).length === 0 &&
208 - Object.keys(availableConnectedAccounts).length === 0
232 + EffectRecord.isEmptyRecord(connectedAccounts) &&
233 + EffectRecord.isEmptyRecord(availableConnectedAccounts)
234 ) {
235 return undefined;
236 }
237
238 return {
214 - connectedAccounts: Object.keys(connectedAccounts).length > 0 ? connectedAccounts : undefined,
215 - availableConnectedAccounts:
216 - Object.keys(availableConnectedAccounts).length > 0 ? availableConnectedAccounts : undefined,
239 + connectedAccounts: EffectRecord.isEmptyRecord(connectedAccounts)
240 + ? undefined
241 + : connectedAccounts,
242 + availableConnectedAccounts: EffectRecord.isEmptyRecord(availableConnectedAccounts)
243 + ? undefined
244 + : availableConnectedAccounts,
245 };
246 };
247
@@ -289,19 +317,16 @@ export const getFreshConsumerToolRouterAuthConfigsFromCache = (params: {
317 }
318
319 const requestedToolkits = params.toolkits.map(toolkit => toolkit.toLowerCase());
292 - const requestedAuthConfigs = requestedToolkits.map(
293 - toolkit => [toolkit, mappings.authConfigs?.[toolkit]] as const
294 - );
295 -
296 - if (requestedAuthConfigs.some(([, authConfigId]) => typeof authConfigId !== 'string')) {
297 - return Option.none<ConsumerToolRouterAuthConfigMappings>();
320 + const requestedAuthConfigs: Record<string, string> = {};
321 + for (const toolkit of requestedToolkits) {
322 + const authConfigId = mappings.authConfigs?.[toolkit];
323 + if (typeof authConfigId !== 'string') {
324 + return Option.none<ConsumerToolRouterAuthConfigMappings>();
325 + }
326 + requestedAuthConfigs[toolkit] = authConfigId;
327 }
328
300 - const filtered = normalizeAuthConfigMappings({
301 - authConfigs: Object.fromEntries(
302 - requestedAuthConfigs.map(([toolkit, authConfigId]) => [toolkit, authConfigId as string])
303 - ),
304 - });
329 + const filtered = normalizeAuthConfigMappings({ authConfigs: requestedAuthConfigs });
330
331 return filtered ? Option.some(filtered) : Option.none<ConsumerToolRouterAuthConfigMappings>();
332 });
ts/packages/cli/src/services/native-ui-sidecar.ts
+56 -1
@@ -3,6 +3,7 @@ import fsSync from 'node:fs';
3 import fs from 'node:fs/promises';
4 import os from 'node:os';
5 import path from 'node:path';
6 +import { Config, ConfigProvider, Effect, Option, Predicate, Schema } from 'effect';
7 import {
8 detectCliPlatform,
9 ensureBundledBinaryExecutable,
@@ -36,6 +37,58 @@ interface NativeUiDecisionPayload {
37 const hasEnvPrefix = (env: NodeJS.ProcessEnv, prefix: string): boolean =>
38 Object.keys(env).some(key => key.startsWith(prefix));
39
40 +const FALSY_ENV_FLAG_VALUES: ReadonlyArray<string> = ['0', 'false', 'no', 'off'];
41 +
42 +// Any other non-empty value counts as set (`CI=woohoo` still disables the UI)
43 +// rather than failing config decoding the way `Config.boolean` would.
44 +const EnvFlagFromString = Schema.transform(
45 + Schema.compose(Schema.Trim, Schema.Lowercase),
46 + Schema.Boolean,
47 + {
48 + decode: value => !FALSY_ENV_FLAG_VALUES.includes(value),
49 + encode: enabled => (enabled ? '1' : '0'),
50 + strict: true,
51 + }
52 +);
53 +const decodeEnvFlag = Schema.decodeOption(EnvFlagFromString);
54 +
55 +// None when the variable is unset or blank, so callers can distinguish
56 +// "not configured" from an explicit true/false.
57 +const envFlag = (name: string): Config.Config<Option.Option<boolean>> =>
58 + Config.string(name).pipe(
59 + Config.map(value => value.trim()),
60 + Config.option,
61 + Config.map(Option.filter(value => value.length > 0)),
62 + Config.map(Option.flatMap(decodeEnvFlag))
63 + );
64 +
65 +/**
66 + * Interactive permission UI (the native sidecar dialog and the browser
67 + * approval page) must never spawn from automated environments. The explicit
68 + * COMPOSIO_DISABLE_PERMISSION_UI knob wins in both directions; without it,
69 + * CI and Vitest runs disable the UI.
70 + */
71 +export const interactivePermissionUiDisabledConfig: Config.Config<boolean> = Config.all({
72 + explicit: envFlag('COMPOSIO_DISABLE_PERMISSION_UI'),
73 + ci: envFlag('CI'),
74 + vitest: envFlag('VITEST'),
75 +}).pipe(
76 + Config.map(({ explicit, ci, vitest }) =>
77 + Option.getOrElse(
78 + explicit,
79 + () => Option.getOrElse(ci, () => false) || Option.getOrElse(vitest, () => false)
80 + )
81 + )
82 +);
83 +
84 +// CI / VITEST / COMPOSIO_DISABLE_PERMISSION_UI are read verbatim, so load them
85 +// through a raw env provider rather than the CLI's COMPOSIO_-prefixed one.
86 +const environmentProvider = ConfigProvider.fromEnv();
87 +
88 +export const isInteractivePermissionUiDisabled: Effect.Effect<boolean> = environmentProvider
89 + .load(interactivePermissionUiDisabledConfig)
90 + .pipe(Effect.orDie);
91 +
92 const normalizeCallerAgent = (value?: string): NativeUiCallerAgent | undefined => {
93 const normalized = value?.toLowerCase().replace(/[^a-z]/g, '');
94 if (normalized === 'claude' || normalized === 'codex' || normalized === 'openclaw') {
@@ -128,8 +181,10 @@ export const requestNativeUiPermissionDecision = async (params: {
181 readonly accountLabel?: string;
182 readonly timeoutSeconds?: number;
183 }): Promise<NativeUiPermissionDecision | undefined> => {
184 + if (await Effect.runPromise(isInteractivePermissionUiDisabled)) return undefined;
185 +
186 const resolved = resolveNativeUiBinary();
132 - if (resolved._tag !== 'found') return undefined;
187 + if (!Predicate.isTagged(resolved, 'found')) return undefined;
188
189 await ensureBundledBinaryExecutable(resolved.binaryPath);
190
ts/packages/cli/src/services/tool-permissions.ts
+139 -20
@@ -3,10 +3,11 @@ import fs from 'node:fs/promises';
3 import path from 'node:path';
4 import open from 'open';
5 import { detectCliPlatform } from '@composio/cli-local-tools';
6 -import { Effect, Option } from 'effect';
6 +import { Effect, Option, Schema } from 'effect';
7 import { resolveCliConfigDirectorySync } from 'src/services/cli-user-config';
8 import {
9 detectNativeUiCallerAgent,
10 + isInteractivePermissionUiDisabled,
11 requestNativeUiPermissionDecision,
12 type NativeUiCallerAgent,
13 } from 'src/services/native-ui-sidecar';
@@ -29,13 +30,9 @@ export type PermissionDefaultMode = 'allow_all' | 'ask_every_call' | 'ask_once_p
30 export type PermissionOverrideState = 'always_allow' | 'always_deny' | 'ask_once' | 'ask_always';
31 export type PermissionDecision = 'allow_once' | 'allow_session' | 'deny';
32 export type PermissionApprovalStatus =
32 - | 'always_approved'
33 - | 'cached_approved'
34 - | 'approved_once'
35 - | 'approved_for_session';
33 + 'always_approved' | 'cached_approved' | 'approved_once' | 'approved_for_session';
34 export type PermissionGateResult =
37 - | { readonly approvalStatus: PermissionApprovalStatus }
38 - | undefined;
35 + { readonly approvalStatus: PermissionApprovalStatus } | undefined;
36
37 export interface ToolRouterPermissionsConfig {
38 readonly default: PermissionDefaultMode;
@@ -61,6 +58,73 @@ interface CacheFile {
58 readonly allowEntries?: Readonly<Record<string, CachedAllowDecision>>;
59 }
60
61 +const PermissionDefaultModeSchema = Schema.Literal(
62 + 'allow_all',
63 + 'ask_every_call',
64 + 'ask_once_per_session'
65 +);
66 +const PermissionOverrideStateSchema = Schema.Literal(
67 + 'always_allow',
68 + 'always_deny',
69 + 'ask_once',
70 + 'ask_always'
71 +);
72 +const ToolRouterPermissionsConfigSchema = Schema.Struct({
73 + default: PermissionDefaultModeSchema,
74 + overrides: Schema.optional(
75 + Schema.Record({ key: Schema.String, value: PermissionOverrideStateSchema })
76 + ),
77 +});
78 +const ConsumerPermissionSnapshotSchema = Schema.Struct({
79 + orgId: Schema.String,
80 + projectId: Schema.String,
81 + consumerUserId: Schema.String,
82 + enhancedControlsEnabled: Schema.Boolean,
83 + permissions: Schema.optional(ToolRouterPermissionsConfigSchema),
84 + connectedAccountIds: Schema.Array(Schema.String),
85 + fetchedAt: Schema.Number,
86 +});
87 +const CachedAllowDecisionSchema = Schema.Struct({
88 + expiresAt: Schema.Number,
89 +});
90 +
91 +const UnknownRecordSchema = Schema.Record({ key: Schema.String, value: Schema.Unknown });
92 +const decodeCacheShell = Schema.decodeUnknownOption(
93 + Schema.parseJson(
94 + Schema.Struct({
95 + entries: Schema.optional(UnknownRecordSchema),
96 + allowEntries: Schema.optional(UnknownRecordSchema),
97 + })
98 + )
99 +);
100 +const decodeSnapshotEntry = Schema.decodeUnknownOption(ConsumerPermissionSnapshotSchema);
101 +const decodeAllowEntry = Schema.decodeUnknownOption(CachedAllowDecisionSchema);
102 +
103 +const collectDecodedEntries = <A>(
104 + entries: Readonly<Record<string, unknown>> | undefined,
105 + decode: (value: unknown) => Option.Option<A>
106 +): Record<string, A> =>
107 + Object.fromEntries(
108 + Object.entries(entries ?? {}).flatMap(([key, value]) =>
109 + Option.match(decode(value), {
110 + onNone: () => [],
111 + onSome: entry => [[key, entry] as const],
112 + })
113 + )
114 + );
115 +
116 +// Per-entry decode: one stale or version-skewed entry drops only itself.
117 +// Discarding the whole file would also wipe all cached allow decisions and
118 +// be persisted back on the next write.
119 +export const decodeCacheFileTolerant = (raw: string): CacheFile =>
120 + Option.match(decodeCacheShell(raw), {
121 + onNone: (): CacheFile => ({ entries: {} }),
122 + onSome: shell => ({
123 + entries: collectDecodedEntries(shell.entries, decodeSnapshotEntry),
124 + allowEntries: collectDecodedEntries(shell.allowEntries, decodeAllowEntry),
125 + }),
126 + });
127 +
128 interface PermissionResolveResponse {
129 readonly experimental?: {
130 readonly permissions?: ToolRouterPermissionsConfig;
@@ -106,10 +170,11 @@ const pruneAllowEntries = (
170 const readCacheFile = async (): Promise<CacheFile> => {
171 try {
172 const raw = await fs.readFile(cachePath(), 'utf8');
109 - const parsed = JSON.parse(raw) as CacheFile;
110 - return parsed && typeof parsed === 'object' && parsed.entries
111 - ? { entries: parsed.entries, allowEntries: pruneAllowEntries(parsed.allowEntries) }
112 - : { entries: {} };
173 + const parsed = decodeCacheFileTolerant(raw);
174 + return {
175 + entries: parsed.entries,
176 + allowEntries: pruneAllowEntries(parsed.allowEntries),
177 + };
178 } catch {
179 return { entries: {} };
180 }
@@ -252,7 +317,7 @@ export const refreshConsumerPermissionSnapshot = (params: {
317 }
318 const enhancedControlsEnabled =
319 remoteEnhancedControlsEnabled && platformSupportsEnhancedControls;
255 - const permissions =
320 + const resolved =
321 enhancedControlsEnabled && connectedAccountIds.length > 0
322 ? yield* Effect.tryPromise(() =>
323 fetchJson<PermissionResolveResponse>({
@@ -267,19 +332,46 @@ export const refreshConsumerPermissionSnapshot = (params: {
332 default: 'ask_every_call',
333 },
334 })
270 - ).pipe(Effect.map(response => response.experimental?.permissions))
271 - : undefined;
335 + ).pipe(
336 + Effect.map(response => ({
337 + permissions: response.experimental?.permissions,
338 + resolveFailed: false,
339 + })),
340 + // The org said enhanced controls are ON but the policy could not
341 + // be learned: fail closed to the interactive default instead of
342 + // silently allowing tools the policy may explicitly deny.
343 + Effect.catchAll(error =>
344 + Effect.logDebug(
345 + 'Failed to resolve consumer permissions; failing closed to ask_every_call',
346 + error
347 + ).pipe(
348 + Effect.as({
349 + permissions: { default: 'ask_every_call' } as ToolRouterPermissionsConfig,
350 + resolveFailed: true,
351 + })
352 + )
353 + )
354 + )
355 + : { permissions: undefined, resolveFailed: false };
356
357 const snapshot: ConsumerPermissionSnapshot = {
358 orgId: params.orgId,
359 projectId: params.projectId,
360 consumerUserId: params.consumerUserId,
361 enhancedControlsEnabled,
278 - permissions,
362 + permissions: resolved.permissions,
363 connectedAccountIds,
364 fetchedAt: Date.now(),
365 };
282 - yield* Effect.tryPromise(() => writeCacheEntry(snapshot));
366 + // A fail-closed snapshot is not persisted, so a healthy fetch replaces it
367 + // on the next command instead of pinning ask_every_call for the TTL.
368 + if (!resolved.resolveFailed) {
369 + yield* Effect.tryPromise(() => writeCacheEntry(snapshot)).pipe(
370 + Effect.catchAll(error =>
371 + Effect.logDebug('Failed to write the tool permissions cache', error)
372 + )
373 + );
374 + }
375 return snapshot;
376 }).pipe(
377 Effect.catchAll(error =>
@@ -366,15 +458,26 @@ export const getConnectedAccountPermissionGroup = (params: {
458 };
459
460 const resolvePermissionState = (
369 - params: GateParams
461 + params: GateParams & { readonly snapshot: ConsumerPermissionSnapshot }
462 ): PermissionOverrideState | PermissionDefaultMode => {
371 - const permissions = params.snapshot?.permissions;
463 + const permissions = params.snapshot.permissions;
464 const override =
465 permissions?.overrides?.[permissionField(params.toolSlug, params.connectedAccountId)] ??
466 permissions?.overrides?.[accountPermissionField(params.connectedAccountId)];
467 return override ?? permissions?.default ?? 'allow_all';
468 };
469
470 +// The gate's decision table: 'skip' means gating does not apply (developer
471 +// mode, or controls known disabled). A snapshot synthesized from a failed
472 +// permission resolve carries default: 'ask_every_call' and therefore prompts.
473 +export const resolveGateState = (
474 + params: GateParams
475 +): PermissionOverrideState | PermissionDefaultMode | 'skip' => {
476 + if (params.snapshot === undefined) return 'skip';
477 + if (!params.snapshot.enhancedControlsEnabled || !params.snapshot.permissions) return 'skip';
478 + return resolvePermissionState({ ...params, snapshot: params.snapshot });
479 +};
480 +
481 const allowCacheKey = (params: GateParams) =>
482 `${params.snapshot?.orgId ?? 'unknown'}:${params.snapshot?.projectId ?? 'unknown'}:${params.snapshot?.consumerUserId ?? 'unknown'}:${permissionField(params.toolSlug, params.connectedAccountId)}`;
483
@@ -843,6 +946,12 @@ const requestPermissionDecision = async (params: {
946 readonly toolSlug: string;
947 readonly accountLabel?: string;
948 }): Promise<PermissionDecision> => {
949 + if (await Effect.runPromise(isInteractivePermissionUiDisabled)) {
950 + throw new Error(
951 + `Interactive permission prompts are disabled in this environment (CI/VITEST, or COMPOSIO_DISABLE_PERMISSION_UI); cannot collect an approval for ${params.toolSlug}.`
952 + );
953 + }
954 +
955 // Prefer the bundled macOS native sidecar when it is available. The browser
956 // prompt remains the cross-platform fallback and is only opened when the
957 // native sidecar is missing or fails before returning a decision.
@@ -854,9 +963,9 @@ const requestPermissionDecision = async (params: {
963
964 export const gateToolExecution = (params: GateParams) =>
965 Effect.gen(function* () {
857 - if (!params.snapshot?.enhancedControlsEnabled || !params.snapshot.permissions) return;
966 + const state = resolveGateState(params);
967 + if (state === 'skip') return;
968
859 - const state = resolvePermissionState(params);
969 if (state === 'allow_all' || state === 'always_allow') {
970 return { approvalStatus: 'always_approved' } satisfies PermissionGateResult;
971 }
@@ -874,6 +983,16 @@ export const gateToolExecution = (params: GateParams) =>
983 return { approvalStatus: 'cached_approved' } satisfies PermissionGateResult;
984 }
985
986 + // Fail closed instead of spawning approval UI where nobody can answer it
987 + // (tests, CI). Cached allow decisions above still apply.
988 + if (yield* isInteractivePermissionUiDisabled) {
989 + return yield* Effect.fail(
990 + new Error(
991 + `Tool execution requires interactive approval, but permission prompts are disabled in this environment (CI/VITEST, or COMPOSIO_DISABLE_PERMISSION_UI): ${params.toolSlug}`
992 + )
993 + );
994 + }
995 +
996 const decision = yield* Effect.tryPromise(() =>
997 requestPermissionDecision({
998 toolSlug: params.toolSlug,
ts/packages/cli/src/services/triggers-realtime.ts
+23 -10
@@ -62,9 +62,13 @@ type ChunkedRealtimeEvent = {
62 export class TriggerRealtimeSubscriptionError extends Data.TaggedError(
63 'services/TriggerRealtimeSubscriptionError'
64 )<{
65 + readonly message: string;
66 readonly cause?: unknown;
67 }> {}
68
69 +const subscriptionError = (message: string) => (cause: unknown) =>
70 + new TriggerRealtimeSubscriptionError({ message, cause });
71 +
72 /**
73 * Service for listening to trigger events over Composio CLI realtime channels.
74 * Uses:
@@ -80,11 +84,14 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
84 const runtime = yield* Effect.runtime<never>();
85
86 const listenWith = (params: {
83 - getRealtimeCredentials: () => Effect.Effect<CliRealtimeCredentialsResponse>;
87 + getRealtimeCredentials: () => Effect.Effect<
88 + CliRealtimeCredentialsResponse,
89 + TriggerRealtimeSubscriptionError
90 + >;
91 authRealtimeChannel: (params: {
92 channel_name: string;
93 socket_id: string;
87 - }) => Effect.Effect<CliRealtimeAuthResponse>;
94 + }) => Effect.Effect<CliRealtimeAuthResponse, TriggerRealtimeSubscriptionError>;
95 onEvent: (data: RawRealtimeEvent) => void;
96 }) =>
97 Effect.acquireUseRelease(
@@ -94,7 +101,7 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
101
102 const pusherModule = yield* Effect.tryPromise({
103 try: () => import('pusher-js'),
97 - catch: cause => new TriggerRealtimeSubscriptionError({ cause }),
104 + catch: subscriptionError('Failed to load the realtime client'),
105 });
106
107 const Pusher = pusherModule.default as unknown as PusherCtor;
@@ -252,14 +259,20 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
259 resource =>
260 Effect.tryPromise({
261 try: () => resource.shutdown(),
255 - catch: cause => new TriggerRealtimeSubscriptionError({ cause }),
262 + catch: subscriptionError('Failed to shut down the realtime subscription'),
263 }).pipe(Effect.catchAll(() => Effect.void))
264 );
265
266 const listen = (onEvent: (data: RawRealtimeEvent) => void) =>
267 listenWith({
261 - getRealtimeCredentials: () => sessionRepo.getRealtimeCredentials().pipe(Effect.orDie),
262 - authRealtimeChannel: params => sessionRepo.authRealtimeChannel(params).pipe(Effect.orDie),
268 + getRealtimeCredentials: () =>
269 + sessionRepo
270 + .getRealtimeCredentials()
271 + .pipe(Effect.mapError(subscriptionError('Failed to fetch realtime credentials'))),
272 + authRealtimeChannel: params =>
273 + sessionRepo
274 + .authRealtimeChannel(params)
275 + .pipe(Effect.mapError(subscriptionError('Failed to authorize the realtime channel'))),
276 onEvent,
277 });
278
@@ -277,13 +290,13 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(
290 getRealtimeCredentials: () =>
291 Effect.tryPromise({
292 try: () => client.cli.realtime.credentials(),
280 - catch: cause => new TriggerRealtimeSubscriptionError({ cause }),
281 - }).pipe(Effect.orDie),
293 + catch: subscriptionError('Failed to fetch realtime credentials'),
294 + }),
295 authRealtimeChannel: params =>
296 Effect.tryPromise({
297 try: () => client.cli.realtime.auth(params),
285 - catch: cause => new TriggerRealtimeSubscriptionError({ cause }),
286 - }).pipe(Effect.orDie),
298 + catch: subscriptionError('Failed to authorize the realtime channel'),
299 + }),
300 onEvent,
301 });
302 });
ts/packages/cli/src/utils/api-error-extraction.ts
+39 -20
@@ -9,13 +9,42 @@
9 * `tools execute` command (for error display).
10 */
11
12 -export type ApiErrorDetails = {
13 - message?: string;
14 - code?: number;
15 - slug?: string;
16 - status?: number;
17 - request_id?: string;
18 - suggested_fix?: string;
12 +import { Predicate } from 'effect';
13 +
14 +export interface ApiErrorDetails {
15 + readonly message?: string;
16 + readonly code?: number;
17 + readonly slug?: string;
18 + readonly status?: number;
19 + readonly request_id?: string;
20 + readonly suggested_fix?: string;
21 +}
22 +
23 +const pickString = (value: object, key: string): string | undefined =>
24 + Predicate.hasProperty(value, key) && Predicate.isString(value[key]) ? value[key] : undefined;
25 +
26 +const pickNumber = (value: object, key: string): number | undefined =>
27 + Predicate.hasProperty(value, key) && Predicate.isNumber(value[key]) ? value[key] : undefined;
28 +
29 +// Field-by-field extraction: a present-but-mistyped field (e.g. a numeric
30 +// `message`) drops only that field, not the node's other perfectly good
31 +// details like `slug` and `request_id`.
32 +const extractCandidate = (value: object): ApiErrorDetails | undefined => {
33 + const candidate: ApiErrorDetails = {
34 + message: pickString(value, 'message'),
35 + code: pickNumber(value, 'code'),
36 + slug: pickString(value, 'slug'),
37 + status: pickNumber(value, 'status'),
38 + request_id: pickString(value, 'request_id'),
39 + suggested_fix: pickString(value, 'suggested_fix'),
40 + };
41 + const hasAnyApiField =
42 + candidate.message !== undefined ||
43 + candidate.code !== undefined ||
44 + candidate.slug !== undefined ||
45 + candidate.status !== undefined ||
46 + candidate.request_id !== undefined;
47 + return hasAnyApiField ? candidate : undefined;
48 };
49
50 /**
@@ -98,16 +127,6 @@ export const extractSlug = (value: unknown): string | undefined => {
127 * Skips Error instances and Effect's UnknownException wrappers.
128 */
129 export const extractApiErrorDetails = (value: unknown): ApiErrorDetails | undefined => {
101 - const isUnknownException = (candidate: object): boolean =>
102 - '_tag' in candidate && (candidate as { _tag?: unknown })._tag === 'UnknownException';
103 -
104 - const hasApiFields = (candidate: ApiErrorDetails): boolean =>
105 - 'message' in candidate ||
106 - 'code' in candidate ||
107 - 'slug' in candidate ||
108 - 'status' in candidate ||
109 - 'request_id' in candidate;
110 -
130 const hasStrongApiFields = (candidate: ApiErrorDetails): boolean =>
131 typeof candidate.slug === 'string' || typeof candidate.request_id === 'string';
132
@@ -123,10 +142,10 @@ export const extractApiErrorDetails = (value: unknown): ApiErrorDetails | undefi
142 }
143 seen.add(current);
144
126 - const candidate = current as ApiErrorDetails;
127 - const isWrapper = current instanceof Error || isUnknownException(current as object);
145 + const candidate = extractCandidate(current);
146 + const isWrapper = current instanceof Error || Predicate.isTagged(current, 'UnknownException');
147
129 - if (hasApiFields(candidate) && !isWrapper) {
148 + if (candidate !== undefined && !isWrapper) {
149 if (hasStrongApiFields(candidate)) {
150 return candidate;
151 }
ts/packages/cli/test/src/effect-errors/extract-error-details.test.ts new
+64
@@ -0,0 +1,64 @@
1 +import { describe, expect, it } from 'vitest';
2 +import { Data } from 'effect';
3 +import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
4 +
5 +class RequestError extends Data.TaggedError('RequestError')<{
6 + readonly message: string;
7 + readonly cause: unknown;
8 +}> {}
9 +
10 +describe('extractErrorDetails', () => {
11 + it('preserves a tagged error message and appends the cause detail', () => {
12 + const error = new RequestError({
13 + message: 'The request failed for /api/signup.',
14 + cause: new TypeError('fetch failed'),
15 + });
16 +
17 + expect(extractErrorDetails(error)).toStrictEqual({
18 + isPlainString: false,
19 + type: 'RequestError',
20 + message: 'The request failed for /api/signup.\nCaused by: fetch failed',
21 + });
22 + });
23 +
24 + it('surfaces the deepest cause message in a nested chain', () => {
25 + const deepest = new Error('expected NonEmptyString, got null');
26 + const middle = new Error('Failed to parse GitHub release JSON response', { cause: deepest });
27 + const error = new RequestError({
28 + message: 'Upgrade failed.',
29 + cause: middle,
30 + });
31 +
32 + expect(extractErrorDetails(error)).toStrictEqual({
33 + isPlainString: false,
34 + type: 'RequestError',
35 + message: 'Upgrade failed.\nCaused by: expected NonEmptyString, got null',
36 + });
37 + });
38 +
39 + it('leaves the message untouched when the cause carries no detail', () => {
40 + const error = new RequestError({
41 + message: 'The request failed.',
42 + cause: undefined,
43 + });
44 +
45 + expect(extractErrorDetails(error)).toStrictEqual({
46 + isPlainString: false,
47 + type: 'RequestError',
48 + message: 'The request failed.',
49 + });
50 + });
51 +
52 + it('does not repeat a cause message identical to the wrapper message', () => {
53 + const error = new RequestError({
54 + message: 'boom',
55 + cause: new Error('boom'),
56 + });
57 +
58 + expect(extractErrorDetails(error)).toStrictEqual({
59 + isPlainString: false,
60 + type: 'RequestError',
61 + message: 'boom',
62 + });
63 + });
64 +});
ts/packages/cli/test/src/effects/decode-connected-account-list.test.ts new
+81
@@ -0,0 +1,81 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { Console, Effect, Layer, ParseResult } from 'effect';
3 +import { decodeConnectedAccountItemsWithFallback } from 'src/effects/decode-connected-account-list';
4 +import type { ConnectedAccountItem } from 'src/models/connected-accounts';
5 +import { MockConsole } from 'test/__utils__';
6 +import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
7 +
8 +const TestLayer = Layer.unwrapEffect(
9 + Effect.map(MockConsole.make, _console =>
10 + Layer.mergeAll(Console.setConsole(_console), TerminalUITest)
11 + )
12 +);
13 +
14 +const makeItem = (overrides?: Record<string, unknown>) => ({
15 + id: 'con_decode_test',
16 + alias: 'default',
17 + word_id: 'castle',
18 + status: 'ACTIVE',
19 + status_reason: null,
20 + is_disabled: false,
21 + user_id: 'user_test',
22 + toolkit: { slug: 'gmail' },
23 + auth_config: {
24 + id: 'ac_gmail_oauth',
25 + auth_scheme: 'OAUTH2',
26 + is_composio_managed: true,
27 + is_disabled: false,
28 + },
29 + created_at: '2026-01-01T00:00:00Z',
30 + updated_at: '2026-01-15T00:00:00Z',
31 + test_request_endpoint: '',
32 + ...overrides,
33 +});
34 +
35 +describe('decodeConnectedAccountItemsWithFallback', () => {
36 + layer(TestLayer)('[Given] items matching the strict schema', it => {
37 + it.effect('decodes without warning', () =>
38 + Effect.gen(function* () {
39 + const items = yield* decodeConnectedAccountItemsWithFallback([makeItem()]);
40 +
41 + expect(items).toStrictEqual([makeItem()]);
42 + expect(yield* MockConsole.getLines()).toStrictEqual([]);
43 + })
44 + );
45 + });
46 +
47 + layer(TestLayer)('[Given] a status newer than this CLI build', it => {
48 + it.effect('warns, keeps the unknown status, and still strips credential fields', () =>
49 + Effect.gen(function* () {
50 + const raw = makeItem({
51 + status: 'QUANTUM_LINKED',
52 + state: { access_token: 'must-not-leak' },
53 + data: { refresh_token: 'must-not-leak' },
54 + });
55 +
56 + const items = yield* decodeConnectedAccountItemsWithFallback([raw]);
57 +
58 + expect(items).toStrictEqual([
59 + makeItem({ status: 'QUANTUM_LINKED' }) as unknown as ConnectedAccountItem,
60 + ]);
61 + expect(JSON.stringify(items)).not.toContain('must-not-leak');
62 +
63 + const output = (yield* MockConsole.getLines()).join('\n');
64 + expect(output).toContain('does not recognize');
65 + expect(output).toContain('composio upgrade');
66 + })
67 + );
68 + });
69 +
70 + layer(TestLayer)('[Given] a payload the permissive schema cannot decode', it => {
71 + it.effect('fails with ParseError instead of leaking the raw payload', () =>
72 + Effect.gen(function* () {
73 + const error = yield* Effect.flip(
74 + decodeConnectedAccountItemsWithFallback([{ definitely: 'not-an-account' }])
75 + );
76 +
77 + expect(ParseResult.isParseError(error)).toBe(true);
78 + })
79 + );
80 + });
81 +});
ts/packages/cli/test/src/effects/resolve-cli-release.test.ts new
+84
@@ -0,0 +1,84 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import { HttpClient, HttpClientResponse } from '@effect/platform';
4 +import { fetchLatestCliRelease, type GitHubRelease } from 'src/effects/resolve-cli-release';
5 +
6 +const githubConfig = {
7 + API_BASE_URL: 'https://api.github.test',
8 + OWNER: 'ComposioHQ',
9 + REPO: 'composio',
10 +};
11 +
12 +const stubHttpClient = (body: unknown) =>
13 + HttpClient.make(request =>
14 + Effect.succeed(
15 + HttpClientResponse.fromWeb(
16 + request,
17 + new Response(JSON.stringify(body), {
18 + status: 200,
19 + headers: { 'Content-Type': 'application/json' },
20 + })
21 + )
22 + )
23 + );
24 +
25 +const hasRequiredAsset = (release: GitHubRelease) =>
26 + release.assets.some(asset => asset.name === 'composio-darwin-arm64');
27 +
28 +describe('fetchLatestCliRelease', () => {
29 + it.effect('skips malformed release entries instead of failing resolution', () =>
30 + Effect.gen(function* () {
31 + const malformedDraft = {
32 + tag_name: '@composio/cli@0.3.0',
33 + draft: true,
34 + assets: [{ name: 'composio-darwin-arm64', browser_download_url: null }],
35 + };
36 + const wellFormed = {
37 + tag_name: '@composio/cli@0.2.9',
38 + prerelease: false,
39 + assets: [
40 + { name: 'composio-darwin-arm64', browser_download_url: 'https://example.test/cli' },
41 + ],
42 + };
43 + const unrelated = { something: 'else entirely' };
44 +
45 + const latest = yield* fetchLatestCliRelease({
46 + assetDescription: 'darwin-arm64 binary',
47 + channel: 'stable',
48 + githubConfig,
49 + hasRequiredAsset,
50 + httpClient: stubHttpClient([malformedDraft, unrelated, wellFormed]),
51 + });
52 +
53 + expect(latest.tag_name).toBe('@composio/cli@0.2.9');
54 + })
55 + );
56 +
57 + it.effect('still fails with a decode error when the body is not an array', () =>
58 + Effect.gen(function* () {
59 + const failure = yield* fetchLatestCliRelease({
60 + assetDescription: 'darwin-arm64 binary',
61 + channel: 'stable',
62 + githubConfig,
63 + hasRequiredAsset,
64 + httpClient: stubHttpClient({ message: 'rate limited' }),
65 + }).pipe(Effect.flip);
66 +
67 + expect(failure.reason).toBe('decode');
68 + })
69 + );
70 +
71 + it.effect('reports not-found when every entry is malformed', () =>
72 + Effect.gen(function* () {
73 + const failure = yield* fetchLatestCliRelease({
74 + assetDescription: 'darwin-arm64 binary',
75 + channel: 'stable',
76 + githubConfig,
77 + hasRequiredAsset,
78 + httpClient: stubHttpClient([{ tag_name: '' }, { assets: 'nope' }]),
79 + }).pipe(Effect.flip);
80 +
81 + expect(failure.reason).toBe('not-found');
82 + })
83 + );
84 +});
ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts
+33
@@ -1,6 +1,9 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { vi, afterEach } from 'vitest';
3 +import { FileSystem } from '@effect/platform';
4 import { ConfigProvider, Effect, Option } from 'effect';
5 +import path from 'node:path';
6 +import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 import { extendConfigProvider } from 'src/services/config';
8 import * as composioClients from 'src/services/composio-clients';
9 import {
@@ -178,6 +181,36 @@ describe('consumer short-term cache', () => {
181 );
182 });
183
184 + layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(
185 + '[Given] one corrupt entry among valid ones [Then] only the corrupt entry is dropped',
186 + it => {
187 + it.scoped('keeps valid cache entries when a sibling entry is corrupt', () =>
188 + Effect.gen(function* () {
189 + const fs = yield* FileSystem.FileSystem;
190 + const cacheDir = yield* setupCacheDir;
191 + yield* fs.writeFileString(
192 + path.join(cacheDir, 'consumer-short-term-cache.json'),
193 + JSON.stringify({
194 + 'org_bad:consumer-user-bad': { toolkits: 'not-an-array', expiresAt: 42 },
195 + 'org_test:consumer-user-test': {
196 + toolkits: ['github'],
197 + expiresAt: new Date(Date.now() + 60_000).toISOString(),
198 + },
199 + })
200 + );
201 +
202 + const cached = yield* getFreshConsumerConnectedToolkitsFromCache({
203 + orgId: 'org_test',
204 + consumerUserId: 'consumer-user-test',
205 + });
206 +
207 + const toolkits = Option.getOrElse(cached, (): ReadonlyArray<string> => []);
208 + expect(toolkits).toContain('github');
209 + })
210 + );
211 + }
212 + );
213 +
214 layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(
215 '[Given] a full auth-config cache hit [Then] cache reads are toolkit-complete',
216 it => {
ts/packages/cli/test/src/services/native-ui-sidecar.test.ts new
+31
@@ -0,0 +1,31 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { ConfigProvider, Effect } from 'effect';
3 +import { interactivePermissionUiDisabledConfig } from 'src/services/native-ui-sidecar';
4 +
5 +const loadFlag = (entries: Record<string, string>): boolean =>
6 + Effect.runSync(
7 + ConfigProvider.fromMap(new Map(Object.entries(entries))).load(
8 + interactivePermissionUiDisabledConfig
9 + )
10 + );
11 +
12 +describe('native UI sidecar', () => {
13 + it('disables interactive permission UI in CI and Vitest environments', () => {
14 + expect(loadFlag({})).toBe(false);
15 + expect(loadFlag({ CI: 'true' })).toBe(true);
16 + expect(loadFlag({ CI: '1' })).toBe(true);
17 + expect(loadFlag({ CI: 'woohoo' })).toBe(true);
18 + expect(loadFlag({ CI: 'false' })).toBe(false);
19 + expect(loadFlag({ CI: '' })).toBe(false);
20 + expect(loadFlag({ VITEST: 'true' })).toBe(true);
21 + });
22 +
23 + it('lets COMPOSIO_DISABLE_PERMISSION_UI override environment detection in both directions', () => {
24 + expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '1' })).toBe(true);
25 + expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: 'true' })).toBe(true);
26 + expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '0', CI: 'true', VITEST: 'true' })).toBe(
27 + false
28 + );
29 + expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '', CI: 'true' })).toBe(true);
30 + });
31 +});
ts/packages/cli/test/src/services/tool-permissions.test.ts new
+132
@@ -0,0 +1,132 @@
1 +import { afterEach, beforeEach, describe, expect, it, vi } from '@effect/vitest';
2 +import { Effect } from 'effect';
3 +import {
4 + decodeCacheFileTolerant,
5 + gateToolExecution,
6 + resolveGateState,
7 + type ConsumerPermissionSnapshot,
8 +} from 'src/services/tool-permissions';
9 +
10 +// Pinned wall clock for deterministic fixtures. The SUT reads the real
11 +// `Date.now()` (snapshot TTL, allow-decision expiry), so every timestamp
12 +// below is expressed relative to this instant.
13 +const PINNED_TIME = new Date('2026-01-01T00:00:00.000Z');
14 +const PINNED_NOW = PINNED_TIME.getTime();
15 +
16 +const snapshotFixture = (
17 + overrides: Partial<ConsumerPermissionSnapshot> = {}
18 +): ConsumerPermissionSnapshot => ({
19 + orgId: 'org_test',
20 + projectId: 'project_test',
21 + consumerUserId: 'user_test',
22 + enhancedControlsEnabled: true,
23 + permissions: { default: 'allow_all', overrides: {} },
24 + connectedAccountIds: [],
25 + fetchedAt: PINNED_NOW,
26 + ...overrides,
27 +});
28 +
29 +describe('tool permissions', () => {
30 + beforeEach(() => {
31 + // Fake ONLY `Date`: the SUT's cache reads/writes run on the live Effect
32 + // runtime, so real timers and microtasks must keep running.
33 + vi.useFakeTimers({ toFake: ['Date'] });
34 + vi.setSystemTime(PINNED_TIME);
35 + });
36 +
37 + afterEach(() => {
38 + vi.useRealTimers();
39 + vi.unstubAllEnvs();
40 + });
41 +
42 + it('drops only corrupt cache entries, keeping valid snapshots and allow decisions', () => {
43 + const good = snapshotFixture();
44 + const raw = JSON.stringify({
45 + entries: {
46 + good: good,
47 + skewed: { ...good, fetchedAt: 'not-a-number' },
48 + },
49 + allowEntries: {
50 + kept: { expiresAt: PINNED_NOW + 60_000 },
51 + broken: { expiresAt: 'soon' },
52 + },
53 + });
54 +
55 + const decoded = decodeCacheFileTolerant(raw);
56 +
57 + expect(Object.keys(decoded.entries)).toStrictEqual(['good']);
58 + expect(Object.keys(decoded.allowEntries ?? {})).toStrictEqual(['kept']);
59 + });
60 +
61 + it('returns an empty cache for unparseable cache files', () => {
62 + expect(decodeCacheFileTolerant('not json')).toStrictEqual({ entries: {} });
63 + });
64 +
65 + it('skips gating when no snapshot applies (developer mode)', () => {
66 + expect(resolveGateState({ toolSlug: 'GMAIL_SEND_EMAIL' })).toBe('skip');
67 + });
68 +
69 + it('skips gating when enhanced controls are known disabled', () => {
70 + expect(
71 + resolveGateState({
72 + toolSlug: 'GMAIL_SEND_EMAIL',
73 + snapshot: snapshotFixture({ enhancedControlsEnabled: false }),
74 + })
75 + ).toBe('skip');
76 + expect(
77 + resolveGateState({
78 + toolSlug: 'GMAIL_SEND_EMAIL',
79 + snapshot: snapshotFixture({ permissions: undefined }),
80 + })
81 + ).toBe('skip');
82 + });
83 +
84 + it('fails closed via the synthesized ask-every-call snapshot when policy resolution failed', () => {
85 + // Shape produced by refreshConsumerPermissionSnapshot when the org
86 + // reports enhanced controls enabled but the permissions resolve fails.
87 + expect(
88 + resolveGateState({
89 + toolSlug: 'GMAIL_SEND_EMAIL',
90 + snapshot: snapshotFixture({ permissions: { default: 'ask_every_call' } }),
91 + })
92 + ).toBe('ask_every_call');
93 + });
94 +
95 + it('resolves overrides ahead of the default mode', () => {
96 + expect(
97 + resolveGateState({
98 + toolSlug: 'GMAIL_SEND_EMAIL',
99 + snapshot: snapshotFixture({
100 + permissions: {
101 + default: 'allow_all',
102 + overrides: { 'GMAIL_SEND_EMAIL:__none__': 'always_deny' },
103 + },
104 + }),
105 + })
106 + ).toBe('always_deny');
107 + });
108 +
109 + it.effect('lets execution proceed ungated without a snapshot', () =>
110 + Effect.gen(function* () {
111 + const result = yield* gateToolExecution({ toolSlug: 'GMAIL_SEND_EMAIL' });
112 +
113 + expect(result).toBeUndefined();
114 + })
115 + );
116 +
117 + it.effect('fails closed when interactive approval is needed but permission UI is disabled', () =>
118 + Effect.gen(function* () {
119 + vi.stubEnv('COMPOSIO_DISABLE_PERMISSION_UI', '1');
120 +
121 + const failure = yield* gateToolExecution({
122 + toolSlug: 'GMAIL_SEND_EMAIL',
123 + snapshot: snapshotFixture({ permissions: { default: 'ask_every_call' } }),
124 + }).pipe(Effect.flip);
125 +
126 + expect(failure).toBeInstanceOf(Error);
127 + if (failure instanceof Error) {
128 + expect(failure.message).toContain('permission prompts are disabled');
129 + }
130 + })
131 + );
132 +});
ts/packages/cli/test/src/utils/api-error-extraction.test.ts new
+63
@@ -0,0 +1,63 @@
1 +import { describe, expect, it } from 'vitest';
2 +import { extractApiErrorDetails } from 'src/utils/api-error-extraction';
3 +
4 +describe('extractApiErrorDetails', () => {
5 + it('extracts details from a well-formed API error body', () => {
6 + const details = extractApiErrorDetails({
7 + error: {
8 + message: 'Rate limited',
9 + slug: 'rate_limited',
10 + request_id: 'req_abc',
11 + code: 42901,
12 + },
13 + });
14 +
15 + expect(details).toMatchObject({
16 + message: 'Rate limited',
17 + slug: 'rate_limited',
18 + request_id: 'req_abc',
19 + code: 42901,
20 + });
21 + });
22 +
23 + it('keeps well-typed fields when a sibling field has an unexpected type', () => {
24 + const details = extractApiErrorDetails({
25 + error: {
26 + message: 42901,
27 + slug: 'rate_limited',
28 + request_id: 'req_abc',
29 + },
30 + });
31 +
32 + expect(details?.slug).toBe('rate_limited');
33 + expect(details?.request_id).toBe('req_abc');
34 + expect(details?.message).toBeUndefined();
35 + });
36 +
37 + it('prefers a node with strong fields over a weaker shallower node', () => {
38 + const details = extractApiErrorDetails({
39 + message: 'outer wrapper',
40 + error: {
41 + message: 'API says no',
42 + slug: 'tool_not_found',
43 + },
44 + });
45 +
46 + expect(details?.slug).toBe('tool_not_found');
47 + expect(details?.message).toBe('API says no');
48 + });
49 +
50 + it('skips Error wrappers but follows their cause chain', () => {
51 + const inner = { slug: 'expired_key', message: 'Key expired' };
52 + const wrapper = new Error('generic wrapper');
53 + Object.assign(wrapper, { cause: inner });
54 +
55 + expect(extractApiErrorDetails(wrapper)?.slug).toBe('expired_key');
56 + });
57 +
58 + it('returns undefined when nothing in the chain carries API fields', () => {
59 + expect(extractApiErrorDetails({ foo: 'bar' })).toBeUndefined();
60 + expect(extractApiErrorDetails(undefined)).toBeUndefined();
61 + expect(extractApiErrorDetails('plain string')).toBeUndefined();
62 + });
63 +});