Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(cli): fail closed on permission gaps and tolerate skewed payloads (#3879)
Alberto Schiabel377de97293a8
diff --git a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.tsindex 891d0467b..220004db1 100644--- a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts+++ b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts@@ -1,5 +1,5 @@import { Args, Command, Options } from '@effect/cli';-import { Effect, Option, Schedule } from 'effect';+import { Data, Effect, Option, Schedule } from 'effect';import type { Composio as RawComposioClient } from '@composio/client';import open from 'open';import { ComposioUserContext } from 'src/services/user-context';@@ -25,6 +25,14 @@ import {} from 'src/services/connected-account-selection';import { ComposioCliUserConfig } from 'src/services/cli-user-config';import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';+import { decodeConnectedAccountItemsWithFallback } from 'src/effects/decode-connected-account-list';++class ConnectedAccountsDecodeError extends Data.TaggedError(+ 'commands/ConnectedAccountsDecodeError'+)<{+ readonly message: string;+ readonly cause: unknown;+}> {}const toolkit = Args.text({ name: 'toolkit' }).pipe(Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),@@ -53,9 +61,7 @@ const noWait = Options.boolean('no-wait').pipe(const noBrowser = Options.boolean('no-browser').pipe(Options.withDefault(false),- Options.withDescription(- 'Do not open the browser automatically; print the URL to open manually'- )+ Options.withDescription('Do not open the browser automatically; print the URL to open manually'));const alias = Options.text('alias').pipe(@@ -431,6 +437,15 @@ const handleListConnectedAccounts = (params: {})));+ const connectedAccounts = yield* decodeConnectedAccountItemsWithFallback(accounts.items).pipe(+ Effect.mapError(+ cause =>+ new ConnectedAccountsDecodeError({+ message: 'The API returned invalid connected account data.',+ cause,+ })+ )+ );if (resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId) {yield* writeConsumerConnectedToolkitsCache({@@ -438,17 +453,13 @@ const handleListConnectedAccounts = (params: {consumerUserId: resolvedProject.consumerUserId,toolkits: [toolkitSlug],toolRouterConnectedAccounts: {- connectedAccounts: resolveDefaultConnectedAccountsByToolkit(- accounts.items as Parameters<typeof resolveDefaultConnectedAccountsByToolkit>[0]- ),- availableConnectedAccounts: groupCachedConnectedAccountsByToolkit(- accounts.items as Parameters<typeof groupCachedConnectedAccountsByToolkit>[0]- ),+ connectedAccounts: resolveDefaultConnectedAccountsByToolkit(connectedAccounts),+ availableConnectedAccounts: groupCachedConnectedAccountsByToolkit(connectedAccounts),},}).pipe(Effect.catchAll(() => Effect.void));}- if (accounts.items.length === 0) {+ if (connectedAccounts.length === 0) {yield* params.ui.log.warn(`No active connected accounts found for "${toolkitSlug}".`);yield* params.ui.output(JSON.stringify({ toolkit: toolkitSlug, items: [], total: 0 }, null, 2),@@ -458,17 +469,15 @@ const handleListConnectedAccounts = (params: {}yield* params.ui.note(- formatConnectedAccountsTable(- accounts.items as Parameters<typeof formatConnectedAccountsTable>[0]- ),+ formatConnectedAccountsTable(connectedAccounts),`${toolkitSlug}: connected accounts`);yield* params.ui.output(JSON.stringify({toolkit: toolkitSlug,- total: accounts.items.length,- items: accounts.items,+ total: connectedAccounts.length,+ items: connectedAccounts,},null,2diff --git a/ts/packages/cli/src/commands/listen.cmd.ts b/ts/packages/cli/src/commands/listen.cmd.tsindex fbda3ff4f..cbc6e7eea 100644--- a/ts/packages/cli/src/commands/listen.cmd.ts+++ b/ts/packages/cli/src/commands/listen.cmd.ts@@ -604,6 +604,15 @@ export const listenCmd = Command.make(ui.log.warn(error instanceof Error ? error.message : String(error))))+ ).pipe(+ Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>+ Effect.gen(function* () {+ yield* ui.log.error(+ `Could not subscribe to realtime trigger events: ${error.message}. Check your network connection or run \`composio login\`.`+ );+ process.exitCode = 1;+ })+ ));})).pipe(diff --git a/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts b/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.tsindex 315017cf3..48ff1fc50 100644--- a/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts+++ b/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts@@ -332,13 +332,24 @@ export const triggersCmd$Listen = Command.make(Effect.onInterrupt(() => ui.log.info('Stopped listening for realtime trigger events.')));- if (maxEventsLimit === undefined) {- yield* listenEffect;- return;- }+ yield* Effect.gen(function* () {+ if (maxEventsLimit === undefined) {+ yield* listenEffect;+ return;+ }- yield* Effect.raceFirst(listenEffect, Deferred.await(stopWhenDone));- yield* ui.outro(`Stopped after receiving ${matchingEvents} matching events.`);+ yield* Effect.raceFirst(listenEffect, Deferred.await(stopWhenDone));+ yield* ui.outro(`Stopped after receiving ${matchingEvents} matching events.`);+ }).pipe(+ Effect.catchTag('services/TriggerRealtimeSubscriptionError', error =>+ Effect.gen(function* () {+ yield* ui.log.error(+ `Could not subscribe to realtime trigger events: ${error.message}. Check your network connection or run \`composio login\`.`+ );+ process.exitCode = 1;+ })+ )+ );})).pipe(Command.withDescription(diff --git a/ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.test.ts b/ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.test.tsindex 29fea00d1..c6faf2aeb 100644--- a/ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.test.ts+++ b/ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.test.ts@@ -11,7 +11,7 @@ describe('extractErrorDetails function', () => {expect(result).toStrictEqual({ isPlainString: true, message: error });});- it('should handle errors with cause', () => {+ it('should preserve the actionable message for tagged errors with a cause', () => {const _tag = 'MyError';const message = 'Oh no!';const cause = 'Some cause';@@ -29,8 +29,8 @@ describe('extractErrorDetails function', () => {expect(result).toStrictEqual({isPlainString: false,- message: cause,- type: _tag,+ message: `${message}\nCaused by: ${cause}`,+ type: 'Error',});});@@ -65,7 +65,7 @@ describe('extractErrorDetails function', () => {expect(result).toStrictEqual({isPlainString: false,message: error.message,- type: error._tag,+ type: error['_tag'],});});diff --git a/ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.ts b/ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.tsindex 7b0edbb1b..0d80ef6dd 100644--- a/ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.ts+++ b/ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.ts@@ -7,6 +7,41 @@ interface ErrorDetails {message: unknown;}+// Wrappers like UpgradeBinaryError carry the actionable specifics (a+// ParseError path, an HTTP body) in `cause`; surface the deepest message so+// the rendered error is debuggable, not just the wrapper's summary line.+const causeDetail = (cause: unknown): string | undefined => {+ const seen = new Set<unknown>();+ let current: unknown = cause;+ let detail: string | undefined;++ while (current !== undefined && current !== null) {+ if (typeof current === 'object') {+ if (seen.has(current)) break;+ seen.add(current);+ }++ if (typeof current === 'string' && current.length > 0) {+ detail = current;+ } else if (+ hasProperty(current, 'message') &&+ typeof current.message === 'string' &&+ current.message.length > 0+ ) {+ detail = current.message;+ }++ current = hasProperty(current, 'cause') ? current.cause : undefined;+ }++ return detail;+};++const withCauseDetail = (message: string, cause: unknown): string => {+ const detail = causeDetail(cause);+ return detail !== undefined && detail !== message ? `${message}\nCaused by: ${detail}` : message;+};+export const extractErrorDetails = (error: unknown): ErrorDetails => {if (typeof error === 'string') {return {@@ -20,8 +55,8 @@ export const extractErrorDetails = (error: unknown): ErrorDetails => {if (isTaggedErrorWithCause) {return {isPlainString: false,- type: error._tag,- message: error.cause,+ type: error.name,+ message: withCauseDetail(error.message, error.cause),};}@@ -39,18 +74,22 @@ export const extractErrorDetails = (error: unknown): ErrorDetails => {if (isPlainObjectsWithTagAttribute) {return {isPlainString: false,- type: error._tag,+ type: error['_tag'],message: error.message,};}- const isPlainObjectsWithToStringImpl =- hasProperty(error, 'toString') &&- isFunction(error.toString) &&- error.toString !== Object.prototype.toString &&- error.toString !== Array.prototype.toString;- if (isPlainObjectsWithToStringImpl) {- const message = (error as { toString: () => string }).toString();+ if (hasProperty(error, 'toString')) {+ const toString = error.toString;+ const isPlainObjectsWithToStringImpl =+ isFunction(toString) &&+ toString !== Object.prototype.toString &&+ toString !== Array.prototype.toString;+ if (!isPlainObjectsWithToStringImpl) {+ return { message: `Error: ${JSON.stringify(error)}`, isPlainString: false };+ }++ const message = String(toString.call(error));const maybeWithUnderlyingType = message.split(': ');if (maybeWithUnderlyingType.length > 1) {diff --git a/ts/packages/cli/src/effects/create-tool-router-session.ts b/ts/packages/cli/src/effects/create-tool-router-session.tsindex ce3f76592..dc0b71238 100644--- a/ts/packages/cli/src/effects/create-tool-router-session.ts+++ b/ts/packages/cli/src/effects/create-tool-router-session.ts@@ -221,18 +221,16 @@ export const createToolRouterSessionContext = (experimental: Object.keys(experimentalPayload).length > 0 ? experimentalPayload : undefined,})).pipe(- Effect.map(- (session): CreatedToolRouterSession => ({- sessionId: session.session_id,- localExperimentalPayload,- permissionSnapshot,- connectedAccounts: connectionContext.connectedAccounts,- connectedAccountWordIds: resolveConnectedAccountWordIds(- connectionContext.connectedAccounts,- connectionContext.availableConnectedAccounts- ),- })- )+ Effect.map((session): CreatedToolRouterSession => ({+ sessionId: session.session_id,+ localExperimentalPayload,+ permissionSnapshot,+ connectedAccounts: connectionContext.connectedAccounts,+ connectedAccountWordIds: resolveConnectedAccountWordIds(+ connectionContext.connectedAccounts,+ connectionContext.availableConnectedAccounts+ ),+ })));});diff --git a/ts/packages/cli/src/effects/decode-connected-account-list.ts b/ts/packages/cli/src/effects/decode-connected-account-list.tsindex 5906870f5..ecd487704 100644--- a/ts/packages/cli/src/effects/decode-connected-account-list.ts+++ b/ts/packages/cli/src/effects/decode-connected-account-list.ts@@ -1,4 +1,9 @@import { Effect, Schema } from 'effect';+import type { ParseResult } from 'effect';+import {+ ConnectedAccountItems,+ ConnectedAccountItemsPermissive,+} from 'src/models/connected-accounts';import {ConnectedAccountListResponse,type ConnectedAccountListResponse as ConnectedAccountListResponseType,@@ -37,3 +42,38 @@ export const decodeConnectedAccountListWithFallback = ());});++/**+ * Item-level variant of {@link decodeConnectedAccountListWithFallback} for+ * call sites that decode `response.items` rather than the whole list+ * response. Same forward-compat contract: on `ParseError` (e.g. a status+ * value newer than this CLI's closed `Schema.Literal(...)`) warn via+ * `ui.log.warn` and retry with `status` widened to `Schema.String`.+ *+ * Unlike the list-response helper above, this one must NOT fall back to the+ * raw payload: `link --list` JSON-dumps the decoded items to stdout, so the+ * schema's field allowlist is what keeps credential-bearing fields (`state`,+ * `data`, ...) out of pipeable output. The permissive re-decode preserves+ * that allowlist; truly malformed data still fails with `ParseError`.+ */+export const decodeConnectedAccountItemsWithFallback = (+ rawItems: unknown+): Effect.Effect<ConnectedAccountItems, ParseResult.ParseError, TerminalUI> =>+ Effect.gen(function* () {+ const ui = yield* TerminalUI;+ return yield* Schema.decodeUnknown(ConnectedAccountItems)(rawItems).pipe(+ Effect.catchTag('ParseError', error =>+ Effect.gen(function* () {+ yield* ui.log.warn(+ `Server returned a connection field this CLI does not recognize ` ++ `(likely a newly-added status). Run "composio upgrade" to pick up ` ++ `the latest schema. Continuing with a permissive schema.\n\n` ++ `Decode error: ${error.message}`+ );+ const permissive = yield* Schema.decodeUnknown(ConnectedAccountItemsPermissive)(rawItems);+ // Identical shape modulo the widened `status`; callers render it as text.+ return permissive as ConnectedAccountItems;+ })+ )+ );+ });diff --git a/ts/packages/cli/src/effects/resolve-cli-release.ts b/ts/packages/cli/src/effects/resolve-cli-release.tsindex 9a212a229..cdfa49a6d 100644--- a/ts/packages/cli/src/effects/resolve-cli-release.ts+++ b/ts/packages/cli/src/effects/resolve-cli-release.ts@@ -1,19 +1,37 @@-import { Effect } from 'effect';-import { HttpClient } from '@effect/platform';+import { Data, Effect, Option, Schema } from 'effect';+import { HttpClient, HttpClientResponse } from '@effect/platform';import { semverComparator } from 'src/effects/compare-semver';import type { CliReleaseChannel } from 'src/constants';-export type GitHubReleaseAsset = {- name: string;- browser_download_url: string;-};+export const GitHubReleaseAsset = Schema.Struct({+ name: Schema.NonEmptyString,+ browser_download_url: Schema.NonEmptyString,+});+export type GitHubReleaseAsset = typeof GitHubReleaseAsset.Type;+export const GitHubReleaseAssets = Schema.Array(GitHubReleaseAsset);-export type GitHubRelease = {- tag_name: string;- prerelease?: boolean;- draft?: boolean;- assets: Array<GitHubReleaseAsset>;-};+export const GitHubRelease = Schema.Struct({+ tag_name: Schema.NonEmptyString,+ prerelease: Schema.optional(Schema.Boolean),+ draft: Schema.optional(Schema.Boolean),+ assets: GitHubReleaseAssets,+});+export type GitHubRelease = typeof GitHubRelease.Type;++// Decoded per element: the endpoint returns up to 100 releases spanning the+// whole repo, and one deviant entry (a draft mid-upload with a null asset+// URL) must not fail resolution for the well-formed CLI releases.+const RawGitHubReleases = Schema.Array(Schema.Unknown);+const decodeGitHubRelease = Schema.decodeUnknownOption(GitHubRelease);++export class CliReleaseResolutionError extends Data.TaggedError(+ 'effects/CliReleaseResolutionError'+)<{+ readonly cause?: unknown;+ readonly message: string;+ readonly reason: 'request' | 'http-status' | 'decode' | 'not-found' | 'compare';+ readonly status?: number;+}> {}export type GitHubRepoConfig = {API_BASE_URL: string;@@ -23,6 +41,50 @@ export type GitHubRepoConfig = {export const CLI_RELEASE_TAG_PATTERN = /^@composio\/cli@\d+\.\d+\.\d+.*$/;+const GitHubReleaseByTag = Schema.Struct({ assets: GitHubReleaseAssets });++export const fetchCliReleaseByTag = ({+ githubConfig,+ httpClient,+ tag,+}: {+ githubConfig: GitHubRepoConfig;+ httpClient: HttpClient.HttpClient;+ tag: string;+}) =>+ Effect.gen(function* () {+ const releaseUrl = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases/tags/${encodeURIComponent(tag)}`;+ const releaseResponse = yield* httpClient.get(releaseUrl).pipe(+ Effect.mapError(+ cause =>+ new CliReleaseResolutionError({+ cause,+ message: `Failed to fetch release ${tag}`,+ reason: 'request',+ })+ )+ );++ if (releaseResponse.status < 200 || releaseResponse.status >= 300) {+ return yield* new CliReleaseResolutionError({+ message: `Release ${tag} not found (HTTP ${releaseResponse.status})`,+ reason: 'http-status',+ status: releaseResponse.status,+ });+ }++ return yield* HttpClientResponse.schemaBodyJson(GitHubReleaseByTag)(releaseResponse).pipe(+ Effect.mapError(+ cause =>+ new CliReleaseResolutionError({+ cause,+ message: `Failed to decode release ${tag}`,+ reason: 'decode',+ })+ )+ );+ });+export const fetchLatestCliRelease = ({assetDescription,channel,@@ -38,54 +100,82 @@ export const fetchLatestCliRelease = ({}) =>Effect.gen(function* () {const releaseUrl = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases?per_page=100`;- const releaseResponse = yield* httpClient- .get(releaseUrl)- .pipe(- Effect.catchAll(error =>- Effect.fail(new Error(`Failed to fetch ${channel} releases from GitHub: ${error}`))- )- );+ const releaseResponse = yield* httpClient.get(releaseUrl).pipe(+ Effect.mapError(+ cause =>+ new CliReleaseResolutionError({+ cause,+ message: `Failed to fetch ${channel} releases from GitHub`,+ reason: 'request',+ })+ )+ );if (releaseResponse.status < 200 || releaseResponse.status >= 300) {return yield* Effect.fail(- new Error(- `Failed to fetch ${channel} releases from GitHub (HTTP ${releaseResponse.status})`- )+ new CliReleaseResolutionError({+ message: `Failed to fetch ${channel} releases from GitHub (HTTP ${releaseResponse.status})`,+ reason: 'http-status',+ status: releaseResponse.status,+ }));}- const releases = (yield* releaseResponse.json.pipe(- Effect.catchAll(() => Effect.fail(new Error('Failed to parse GitHub releases JSON')))- )) as unknown;-- if (!Array.isArray(releases)) {- return yield* Effect.fail(new Error('GitHub releases response was not an array'));+ const rawReleases = yield* HttpClientResponse.schemaBodyJson(RawGitHubReleases)(+ releaseResponse+ ).pipe(+ Effect.mapError(+ cause =>+ new CliReleaseResolutionError({+ cause,+ message: 'Failed to decode GitHub releases response',+ reason: 'decode',+ })+ )+ );+ const releases = rawReleases.flatMap(entry =>+ Option.match(decodeGitHubRelease(entry), {+ onNone: () => [],+ onSome: release => [release],+ })+ );+ if (releases.length < rawReleases.length) {+ yield* Effect.logDebug(+ `Skipped ${rawReleases.length - releases.length} malformed GitHub release entries.`+ );}const prerelease = channel === 'beta';const matchingReleases = releases.filter(- (release): release is GitHubRelease =>- typeof release === 'object' &&- release !== null &&- 'tag_name' in release &&- typeof release.tag_name === 'string' &&- ('prerelease' in release ? release.prerelease === prerelease : prerelease === false) &&- ('draft' in release ? release.draft === false : true) &&+ release =>+ (release.prerelease === undefined+ ? prerelease === false+ : release.prerelease === prerelease) &&+ release.draft !== true &&CLI_RELEASE_TAG_PATTERN.test(release.tag_name) &&- Array.isArray(release.assets) &&hasRequiredAsset(release));if (matchingReleases.length === 0) {return yield* Effect.fail(- new Error(`No ${channel} CLI releases found with ${assetDescription}`)+ new CliReleaseResolutionError({+ message: `No ${channel} CLI releases found with ${assetDescription}`,+ reason: 'not-found',+ }));}let latest = matchingReleases[0];for (const release of matchingReleases.slice(1)) {const comparison = yield* semverComparator(latest.tag_name, release.tag_name).pipe(- Effect.mapError(error => new Error(`Failed to compare release versions: ${error}`))+ Effect.mapError(+ cause =>+ new CliReleaseResolutionError({+ cause,+ message: `Failed to compare release versions: ${latest.tag_name} and ${release.tag_name}`,+ reason: 'compare',+ })+ ));if (comparison < 0) {diff --git a/ts/packages/cli/src/models/connected-accounts.ts b/ts/packages/cli/src/models/connected-accounts.tsindex 9a58d4147..a496202b9 100644--- a/ts/packages/cli/src/models/connected-accounts.ts+++ b/ts/packages/cli/src/models/connected-accounts.ts@@ -42,3 +42,15 @@ export type ConnectedAccountItem = Schema.Schema.Type<typeof ConnectedAccountIteexport const ConnectedAccountItems = Schema.Array(ConnectedAccountItem);export type ConnectedAccountItems = Schema.Schema.Type<typeof ConnectedAccountItems>;++/**+ * Forward-compatible variant of {@link ConnectedAccountItem}: identical field+ * allowlist (same credential-stripping guarantee as above) with `status`+ * widened to accept values newer than this CLI build's closed literal union.+ */+export const ConnectedAccountItemPermissive = Schema.Struct({+ ...ConnectedAccountItem.fields,+ status: Schema.String,+}).annotations({ identifier: 'ConnectedAccountItemPermissive' });++export const ConnectedAccountItemsPermissive = Schema.Array(ConnectedAccountItemPermissive);diff --git a/ts/packages/cli/src/services/agents.ts b/ts/packages/cli/src/services/agents.tsindex 6844ae982..c404146fa 100644--- a/ts/packages/cli/src/services/agents.ts+++ b/ts/packages/cli/src/services/agents.ts@@ -1,5 +1,5 @@import { FileSystem } from '@effect/platform';-import { Data, Effect, Option } from 'effect';+import { Data, Effect, Option, Predicate, Schema } from 'effect';import path from 'node:path';import { setupCacheDir } from 'src/effects/setup-cache-dir';import { ComposioUserContext } from 'src/services/user-context';@@ -10,68 +10,93 @@ export const DEFAULT_AGENTS_BASE_URL = 'https://agents.composio.dev';export type AgentStatus = 'READY' | 'PENDING' | 'UNKNOWN';-export interface AgentComposioCredentials {- readonly member_id?: string;- readonly org_id?: string;- readonly project_id?: string;- readonly api_key?: string;- readonly user_api_key?: string;-}--export interface AgentIdentity {- readonly status?: string;- readonly request_id?: string;- readonly slug?: string;- readonly email?: string;- readonly agent_key?: string;- readonly composio_agent_key?: string;- readonly claimed_by?: string | null;- readonly claimed_at?: string | null;- readonly composio?: AgentComposioCredentials;- readonly [key: string]: unknown;-}--export interface AgentMailMessage {- readonly id?: string;- readonly thread_id?: string;- readonly from?: string;- readonly to?: string;- readonly subject?: string;- readonly preview?: string;- readonly received_at?: string;- readonly [key: string]: unknown;-}--export interface AgentMailResponse {- readonly count?: number;- readonly messages?: ReadonlyArray<AgentMailMessage>;- readonly [key: string]: unknown;-}--export interface AgentClaimResponse {- readonly status?: string;- readonly email?: string;- readonly org_id?: string;- readonly invite_code?: string;- readonly [key: string]: unknown;-}+const UnknownFields = Schema.Record({ key: Schema.String, value: Schema.Unknown });++const AgentComposioCredentials = Schema.Struct({+ member_id: Schema.optional(Schema.NullOr(Schema.String)),+ org_id: Schema.optional(Schema.NullOr(Schema.String)),+ project_id: Schema.optional(Schema.NullOr(Schema.String)),+ api_key: Schema.optional(Schema.NullOr(Schema.String)),+ user_api_key: Schema.optional(Schema.NullOr(Schema.String)),+}).pipe(Schema.extend(UnknownFields));+export type AgentComposioCredentials = Schema.Schema.Type<typeof AgentComposioCredentials>;++const AgentIdentity = Schema.Struct({+ status: Schema.optional(Schema.NullOr(Schema.String)),+ request_id: Schema.optional(Schema.NullOr(Schema.String)),+ slug: Schema.optional(Schema.NullOr(Schema.String)),+ email: Schema.optional(Schema.NullOr(Schema.String)),+ agent_key: Schema.optional(Schema.NullOr(Schema.String)),+ composio_agent_key: Schema.optional(Schema.NullOr(Schema.String)),+ claimed_by: Schema.optional(Schema.NullOr(Schema.String)),+ claimed_at: Schema.optional(Schema.NullOr(Schema.String)),+ composio: Schema.optional(AgentComposioCredentials),+}).pipe(Schema.extend(UnknownFields));+export type AgentIdentity = Schema.Schema.Type<typeof AgentIdentity>;++const AgentMailMessage = Schema.Struct({+ id: Schema.optional(Schema.NullOr(Schema.String)),+ thread_id: Schema.optional(Schema.NullOr(Schema.String)),+ from: Schema.optional(Schema.NullOr(Schema.String)),+ to: Schema.optional(Schema.NullOr(Schema.String)),+ subject: Schema.optional(Schema.NullOr(Schema.String)),+ preview: Schema.optional(Schema.NullOr(Schema.String)),+ received_at: Schema.optional(Schema.NullOr(Schema.String)),+}).pipe(Schema.extend(UnknownFields));+export type AgentMailMessage = Schema.Schema.Type<typeof AgentMailMessage>;++const AgentMailResponse = Schema.Struct({+ count: Schema.optional(Schema.Number),+ messages: Schema.optional(Schema.Array(AgentMailMessage)),+}).pipe(Schema.extend(UnknownFields));+export type AgentMailResponse = Schema.Schema.Type<typeof AgentMailResponse>;++const AgentClaimResponse = Schema.Struct({+ status: Schema.optional(Schema.NullOr(Schema.String)),+ email: Schema.optional(Schema.NullOr(Schema.String)),+ org_id: Schema.optional(Schema.NullOr(Schema.String)),+ invite_code: Schema.optional(Schema.NullOr(Schema.String)),+}).pipe(Schema.extend(UnknownFields));+export type AgentClaimResponse = Schema.Schema.Type<typeof AgentClaimResponse>;export class AgentAuthError extends Data.TaggedError('services/AgentAuthError')<{readonly message: string;readonly nextSteps: ReadonlyArray<string>;}> {}+export class AgentRequestError extends Data.TaggedError('services/AgentRequestError')<{+ readonly message: string;+ readonly pathname: string;+ readonly status?: number;+ readonly cause?: unknown;+}> {}++export class AgentResponseDecodeError extends Data.TaggedError(+ 'services/AgentResponseDecodeError'+)<{+ readonly message: string;+ readonly pathname: string;+ readonly cause: unknown;+}> {}+const agentsBaseURL = (): string =>(process.env.COMPOSIO_AGENTS_BASE_URL ?? DEFAULT_AGENTS_BASE_URL).replace(/\/+$/, '');-const asRecord = (value: unknown): Record<string, unknown> =>- value && typeof value === 'object' && !Array.isArray(value)- ? (value as Record<string, unknown>)- : {};--const readJson = (value: string): unknown => JSON.parse(value) as unknown;+const decodeAgentResponse =+ <A, I>(pathname: string, schema: Schema.Schema<A, I>) =>+ (payload: unknown) =>+ Schema.decodeUnknown(schema)(payload).pipe(+ Effect.mapError(+ cause =>+ new AgentResponseDecodeError({+ message: `agents.composio.dev returned an invalid response for ${pathname}`,+ pathname,+ cause,+ })+ )+ );-export const normalizeAgentStatus = (status: string | undefined): AgentStatus => {+export const normalizeAgentStatus = (status: string | null | undefined): AgentStatus => {const normalized = status?.trim().toUpperCase();if (normalized === 'READY') return 'READY';if (normalized === 'PENDING') return 'PENDING';@@ -87,27 +112,40 @@ export const getAgentKey = (identity: AgentIdentity): string | undefined => {export const isAgentIdentityForApiKey = (identity: AgentIdentity, apiKey: string): boolean =>Boolean(getAgentKey(identity) && identity.composio?.user_api_key === apiKey);+const normalizeDecodedAgentIdentity = (+ identity: AgentIdentity,+ fallbackAgentKey?: string+): AgentIdentity => {+ const agentKey = identity.composio_agent_key ?? identity.agent_key ?? fallbackAgentKey;++ return agentKey ? { ...identity, agent_key: agentKey, composio_agent_key: agentKey } : identity;+};+export const normalizeAgentIdentity = (payload: unknown,fallbackAgentKey?: string-): AgentIdentity => {- const record = asRecord(payload);- const agentKey =- (typeof record.composio_agent_key === 'string' ? record.composio_agent_key : undefined) ??- (typeof record.agent_key === 'string' ? record.agent_key : undefined) ??- fallbackAgentKey;-- const normalized: Record<string, unknown> = { ...record };- if (agentKey) {- normalized.agent_key = agentKey;- normalized.composio_agent_key = agentKey;- }+): AgentIdentity =>+ normalizeDecodedAgentIdentity(+ Schema.decodeUnknownOption(AgentIdentity)(payload).pipe(+ Option.getOrElse((): AgentIdentity => ({}))+ ),+ fallbackAgentKey+ );- return normalized as AgentIdentity;+type SafeAgentSummary = {+ readonly account_type: 'agent';+ readonly status: AgentStatus;+ readonly slug: string | null;+ readonly email: string | null;+ readonly org_id: string | null;+ readonly project_id: string | null;+ readonly member_id: string | null;+ readonly claimed_by: string | null;+ readonly claimed_at: string | null;};-export const safeAgentSummary = (identity: AgentIdentity) => ({- account_type: 'agent' as const,+export const safeAgentSummary = (identity: AgentIdentity): SafeAgentSummary => ({+ account_type: 'agent',status: normalizeAgentStatus(identity.status),slug: identity.slug ?? null,email: identity.email ?? null,@@ -131,13 +169,10 @@ export const readStoredAgentIdentity = Effect.gen(function* () {if (!exists) return Option.none<AgentIdentity>();return yield* fs.readFileString(configPath, 'utf8').pipe(- Effect.map(raw => Option.some(normalizeAgentIdentity(readJson(raw)))),- Effect.catchAll(error =>- Effect.gen(function* () {- yield* Effect.logDebug('Failed to read agent identity:', error);- return Option.none<AgentIdentity>();- })- )+ Effect.flatMap(Schema.decodeUnknown(Schema.parseJson(AgentIdentity))),+ Effect.map(normalizeDecodedAgentIdentity),+ Effect.tapError(error => Effect.logDebug('Failed to read agent identity:', error)),+ Effect.option);});@@ -145,7 +180,7 @@ export const writeStoredAgentIdentity = (identity: AgentIdentity) =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;const configPath = yield* agentConfigPath;- const normalized = normalizeAgentIdentity(identity);+ const normalized = normalizeDecodedAgentIdentity(identity);yield* fs.writeFileString(configPath, `${JSON.stringify(normalized, null, 2)}\n`);return normalized;});@@ -153,34 +188,66 @@ export const writeStoredAgentIdentity = (identity: AgentIdentity) =>export const removeStoredAgentIdentity = Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;const configPath = yield* agentConfigPath;- yield* fs.remove(configPath).pipe(Effect.catchAll(() => Effect.void));+ yield* fs.remove(configPath).pipe(Effect.ignore);});const fetchAgentJson = (pathname: string, init: RequestInit = {}) =>- Effect.tryPromise({- try: async () => {- const response = await fetch(`${agentsBaseURL()}${pathname}`, {- redirect: 'error',- ...init,- headers: {- Accept: 'application/json',- ...(init.body ? { 'Content-Type': 'application/json' } : {}),- ...(init.headers ?? {}),- },+ Effect.gen(function* () {+ const response = yield* Effect.tryPromise({+ try: () =>+ fetch(`${agentsBaseURL()}${pathname}`, {+ redirect: 'error',+ ...init,+ headers: {+ Accept: 'application/json',+ ...(init.body ? { 'Content-Type': 'application/json' } : {}),+ ...(init.headers ?? {}),+ },+ }),+ catch: cause =>+ new AgentRequestError({+ message: `agents.composio.dev request failed for ${pathname}`,+ pathname,+ cause,+ }),+ });++ const text = yield* Effect.tryPromise({+ try: () => response.text(),+ catch: cause =>+ new AgentRequestError({+ message: `Failed to read agents.composio.dev response for ${pathname}`,+ pathname,+ status: response.status,+ cause,+ }),+ });+ const payload = text+ ? yield* Schema.decodeUnknown(Schema.parseJson(Schema.Unknown))(text).pipe(+ Effect.mapError(+ cause =>+ new AgentResponseDecodeError({+ message: `agents.composio.dev returned invalid JSON for ${pathname}`,+ pathname,+ cause,+ })+ )+ )+ : {};++ if (!response.ok) {+ const message =+ Predicate.isRecord(payload) && typeof payload.message === 'string'+ ? payload.message+ : `agents.composio.dev request failed with HTTP ${response.status}`;+ return yield* new AgentRequestError({+ message,+ pathname,+ status: response.status,});+ }- const text = await response.text();- const payload = text ? (JSON.parse(text) as unknown) : {};- if (!response.ok) {- const message =- typeof asRecord(payload).message === 'string'- ? (asRecord(payload).message as string)- : `agents.composio.dev request failed with HTTP ${response.status}`;- throw new Error(message);- }- return payload;- },- catch: error => (error instanceof Error ? error : new Error(String(error))),+ return payload;});export const signupAgent = (params: { wait?: boolean } = {}) =>@@ -190,7 +257,8 @@ export const signupAgent = (params: { wait?: boolean } = {}) =>method: 'POST',body: JSON.stringify({}),});- return yield* writeStoredAgentIdentity(normalizeAgentIdentity(payload));+ const identity = yield* decodeAgentResponse('/api/signup', AgentIdentity)(payload);+ return yield* writeStoredAgentIdentity(identity);});export const fetchAgentWhoami = (agentKey: string) =>@@ -199,21 +267,30 @@ export const fetchAgentWhoami = (agentKey: string) =>method: 'GET',headers: { Authorization: `Bearer ${agentKey}` },});- return normalizeAgentIdentity(payload, agentKey);+ const identity = yield* decodeAgentResponse('/api/whoami', AgentIdentity)(payload);+ return normalizeDecodedAgentIdentity(identity, agentKey);});export const fetchAgentInbox = (params: { agentKey: string; limit?: number }) =>- fetchAgentJson(`/api/mail?limit=${encodeURIComponent(String(params.limit ?? 50))}`, {- method: 'GET',- headers: { Authorization: `Bearer ${params.agentKey}` },- }).pipe(Effect.map(payload => payload as AgentMailResponse));+ Effect.gen(function* () {+ const pathname = `/api/mail?limit=${encodeURIComponent(String(params.limit ?? 50))}`;+ const payload = yield* fetchAgentJson(pathname, {+ method: 'GET',+ headers: { Authorization: `Bearer ${params.agentKey}` },+ });+ return yield* decodeAgentResponse(pathname, AgentMailResponse)(payload);+ });export const claimAgent = (params: { agentKey: string; email: string }) =>- fetchAgentJson('/api/claim', {- method: 'POST',- headers: { Authorization: `Bearer ${params.agentKey}` },- body: JSON.stringify({ email: params.email }),- }).pipe(Effect.map(payload => payload as AgentClaimResponse));+ Effect.gen(function* () {+ const pathname = '/api/claim';+ const payload = yield* fetchAgentJson(pathname, {+ method: 'POST',+ headers: { Authorization: `Bearer ${params.agentKey}` },+ body: JSON.stringify({ email: params.email }),+ });+ return yield* decodeAgentResponse(pathname, AgentClaimResponse)(payload);+ });const humanLoginError = () =>new AgentAuthError({@@ -232,7 +309,7 @@ export const ensureAgentSignupAllowed = Effect.gen(function* () {const stored = yield* readStoredAgentIdentity;if (Option.isSome(stored) && isAgentIdentityForApiKey(stored.value, apiKey.value)) return;- return yield* Effect.fail(humanLoginError());+ return yield* humanLoginError();});export const getCurrentLoggedInAgent = Effect.gen(function* () {@@ -255,35 +332,32 @@ export const resolveStoredAgentKey = Effect.gen(function* () {if (Option.isSome(currentApiKey)) {if (Option.isSome(stored) && isAgentIdentityForApiKey(stored.value, currentApiKey.value)) {- return getAgentKey(stored.value) as string;+ const agentKey = getAgentKey(stored.value);+ if (agentKey) return agentKey;}- return yield* Effect.fail(humanLoginError());+ return yield* humanLoginError();}if (Option.isNone(stored)) {- return yield* Effect.fail(- new AgentAuthError({- message: 'No Composio agent identity is saved on this machine.',- nextSteps: [- 'To create a new agent: run `composio signup` or `composio agent signup`.',- 'To restore an existing agent: run `composio agent login <composio_agent_key>`.',- ],- })- );+ return yield* new AgentAuthError({+ message: 'No Composio agent identity is saved on this machine.',+ nextSteps: [+ 'To create a new agent: run `composio signup` or `composio agent signup`.',+ 'To restore an existing agent: run `composio agent login <composio_agent_key>`.',+ ],+ });}const agentKey = getAgentKey(stored.value);if (!agentKey) {- return yield* Effect.fail(- new AgentAuthError({- message: 'The saved Composio agent identity is missing its composio_agent_key.',- nextSteps: [- 'If you saved the key, run `composio agent login <composio_agent_key>`.',- 'Otherwise create a new agent with `composio signup`.',- ],- })- );+ return yield* new AgentAuthError({+ message: 'The saved Composio agent identity is missing its composio_agent_key.',+ nextSteps: [+ 'If you saved the key, run `composio agent login <composio_agent_key>`.',+ 'Otherwise create a new agent with `composio signup`.',+ ],+ });}return agentKey;@@ -315,11 +389,10 @@ export const loginWithAgentIdentity = (identity: AgentIdentity) =>const orgId = identity.composio?.org_id;if (!userApiKey || !orgId) {- return yield* Effect.fail(- new Error(- 'Agent identity is not ready yet. Run `composio agent whoami` and try again once status is READY.'- )- );+ return yield* new AgentAuthError({+ message: 'Agent identity is not ready yet.',+ nextSteps: ['Run `composio agent whoami` and try again once status is READY.'],+ });}yield* ctx.login(userApiKey, orgId);diff --git a/ts/packages/cli/src/services/connected-account-selection.ts b/ts/packages/cli/src/services/connected-account-selection.tsindex 38d0dd12a..826078323 100644--- a/ts/packages/cli/src/services/connected-account-selection.ts+++ b/ts/packages/cli/src/services/connected-account-selection.ts@@ -1,4 +1,5 @@import type { ConnectedAccountItem } from 'src/models/connected-accounts';+import { Schema } from 'effect';// `ConnectedAccountItem` widened with an `'UNKNOWN'` sentinel for statuses// the closed schema doesn't yet know about. Selection only picks `'ACTIVE'`,@@ -8,13 +9,14 @@ export type SelectableConnectedAccount = Omit<ConnectedAccountItem, 'status'> &readonly status: ConnectedAccountItem['status'] | 'UNKNOWN';};-export type CachedConnectedAccountSummary = {- readonly id: string;- readonly alias: string | null;- readonly wordId: string | null;- readonly updatedAt: string;- readonly createdAt: string;-};+export const CachedConnectedAccountSummarySchema = Schema.Struct({+ id: Schema.String,+ alias: Schema.NullOr(Schema.String),+ wordId: Schema.NullOr(Schema.String),+ updatedAt: Schema.String,+ createdAt: Schema.String,+});+export type CachedConnectedAccountSummary = typeof CachedConnectedAccountSummarySchema.Type;const normalizeSelector = (value: string): string => value.trim().toLowerCase();diff --git a/ts/packages/cli/src/services/consumer-short-term-cache.ts b/ts/packages/cli/src/services/consumer-short-term-cache.tsindex 92d725fd2..2b130efcd 100644--- a/ts/packages/cli/src/services/consumer-short-term-cache.ts+++ b/ts/packages/cli/src/services/consumer-short-term-cache.ts@@ -1,6 +1,6 @@import path from 'node:path';import { FileSystem } from '@effect/platform';-import { Effect, Option } from 'effect';+import { Effect, Option, Record as EffectRecord, Schema } from 'effect';import { APP_CONFIG } from 'src/effects/app-config';import { setupCacheDir } from 'src/effects/setup-cache-dir';import { NodeProcess } from 'src/services/node-process';@@ -10,42 +10,69 @@ import {getConsumerConnectedToolkits,resolveConsumerProject,} from 'src/services/composio-clients';-import type { CachedConnectedAccountSummary } from 'src/services/connected-account-selection';import { resolveCommandProject } from 'src/services/command-project';import { resolveToolRouterSessionConnections } from 'src/services/tool-router-session-connections';import { ComposioUserContext } from 'src/services/user-context';+import {+ CachedConnectedAccountSummarySchema,+ type CachedConnectedAccountSummary,+} from 'src/services/connected-account-selection';const CACHE_FILE = 'consumer-short-term-cache.json';const CACHE_TTL_MS = 15 * 60 * 1000;const SEARCH_SESSION_EXTENSION_MS = 5 * 60 * 1000;-export type ConsumerToolRouterAuthConfigMappings = {- readonly authConfigs?: Record<string, string>;-};--export type ConsumerToolRouterConnectedAccountMappings = {- readonly connectedAccounts?: Record<string, string>;- readonly availableConnectedAccounts?: Record<- string,- ReadonlyArray<CachedConnectedAccountSummary>- >;-};--type CacheEntry = {- readonly toolkits: ReadonlyArray<string>;- readonly expiresAt: string;- readonly toolRouterAuthConfigs?: ConsumerToolRouterAuthConfigMappings;- readonly toolRouterConnectedAccounts?: ConsumerToolRouterConnectedAccountMappings;- readonly probablyMyCliSessionsByCwdHash?: Record<- string,- {- readonly id: string;- readonly expiresAt: string;- }- >;-};--type CacheState = Record<string, CacheEntry>;+const StringMappingsSchema = Schema.Record({ key: Schema.String, value: Schema.String });+const AvailableConnectedAccountsSchema = Schema.Record({+ key: Schema.String,+ value: Schema.Array(CachedConnectedAccountSummarySchema),+});+const ConsumerToolRouterAuthConfigMappingsSchema = Schema.Struct({+ authConfigs: Schema.optional(StringMappingsSchema),+});+const ConsumerToolRouterConnectedAccountMappingsSchema = Schema.Struct({+ connectedAccounts: Schema.optional(StringMappingsSchema),+ availableConnectedAccounts: Schema.optional(AvailableConnectedAccountsSchema),+});+const CacheEntrySchema = Schema.Struct({+ toolkits: Schema.Array(Schema.String),+ expiresAt: Schema.String,+ toolRouterAuthConfigs: Schema.optional(ConsumerToolRouterAuthConfigMappingsSchema),+ toolRouterConnectedAccounts: Schema.optional(ConsumerToolRouterConnectedAccountMappingsSchema),+ probablyMyCliSessionsByCwdHash: Schema.optional(+ Schema.Record({+ key: Schema.String,+ value: Schema.Struct({ id: Schema.String, expiresAt: Schema.String }),+ })+ ),+});+export type ConsumerToolRouterAuthConfigMappings =+ typeof ConsumerToolRouterAuthConfigMappingsSchema.Type;+export type ConsumerToolRouterConnectedAccountMappings =+ typeof ConsumerToolRouterConnectedAccountMappingsSchema.Type;+type CacheEntry = typeof CacheEntrySchema.Type;+type CacheState = { readonly [key: string]: CacheEntry };+const decodeCacheShell = Schema.decodeUnknownOption(+ Schema.parseJson(Schema.Record({ key: Schema.String, value: Schema.Unknown }))+);+const decodeCacheEntry = Schema.decodeUnknownOption(CacheEntrySchema);++// Per-entry decode: one stale or version-skewed entry (e.g. written by a+// newer CLI) drops only itself; discarding the whole cache would also be+// persisted back on the next write, permanently destroying the good entries.+export const decodeCacheStateTolerant = (raw: string): CacheState =>+ Option.match(decodeCacheShell(raw), {+ onNone: (): CacheState => ({}),+ onSome: shell =>+ Object.fromEntries(+ Object.entries(shell).flatMap(([key, value]) =>+ Option.match(decodeCacheEntry(value), {+ onNone: () => [],+ onSome: entry => [[key, entry] as const],+ })+ )+ ),+ });const cacheKey = (orgId: string, consumerUserId: string) => `${orgId}:${consumerUserId}`;@@ -74,8 +101,8 @@ const resolveSearchSessionMetadata = (params: {...(params.currentEntry?.probablyMyCliSessionsByCwdHash ?? {}),};- const probablyMyCliSessionsByCwdHash = Object.fromEntries(- Object.entries(previousMap).filter(([, session]) => {+ const probablyMyCliSessionsByCwdHash = EffectRecord.fromEntries(+ EffectRecord.toEntries(previousMap).filter(([, session]) => {const expiresAtMs = Date.parse(session.expiresAt);return Number.isFinite(expiresAtMs) && expiresAtMs > now;})@@ -110,9 +137,7 @@ const readCache = () =>return {} satisfies CacheState;}const raw = yield* fs.readFileString(filePath, 'utf8');- return yield* Effect.sync(() => JSON.parse(raw) as CacheState).pipe(- Effect.catchAll(() => Effect.succeed({} satisfies CacheState))- );+ return decodeCacheStateTolerant(raw);});const writeCache = (state: CacheState) =>@@ -148,7 +173,7 @@ const normalizeAuthConfigMappings = (.map(([toolkit, authConfigId]) => [toolkit.toLowerCase(), authConfigId]).filter(([, authConfigId]) => typeof authConfigId === 'string' && authConfigId.length > 0));- if (Object.keys(authConfigs).length === 0) {+ if (EffectRecord.isEmptyRecord(authConfigs)) {return undefined;}@@ -204,16 +229,19 @@ const normalizeConnectedAccountMappings = ();if (- Object.keys(connectedAccounts).length === 0 &&- Object.keys(availableConnectedAccounts).length === 0+ EffectRecord.isEmptyRecord(connectedAccounts) &&+ EffectRecord.isEmptyRecord(availableConnectedAccounts)) {return undefined;}return {- connectedAccounts: Object.keys(connectedAccounts).length > 0 ? connectedAccounts : undefined,- availableConnectedAccounts:- Object.keys(availableConnectedAccounts).length > 0 ? availableConnectedAccounts : undefined,+ connectedAccounts: EffectRecord.isEmptyRecord(connectedAccounts)+ ? undefined+ : connectedAccounts,+ availableConnectedAccounts: EffectRecord.isEmptyRecord(availableConnectedAccounts)+ ? undefined+ : availableConnectedAccounts,};};@@ -289,19 +317,16 @@ export const getFreshConsumerToolRouterAuthConfigsFromCache = (params: {}const requestedToolkits = params.toolkits.map(toolkit => toolkit.toLowerCase());- const requestedAuthConfigs = requestedToolkits.map(- toolkit => [toolkit, mappings.authConfigs?.[toolkit]] as const- );-- if (requestedAuthConfigs.some(([, authConfigId]) => typeof authConfigId !== 'string')) {- return Option.none<ConsumerToolRouterAuthConfigMappings>();+ const requestedAuthConfigs: Record<string, string> = {};+ for (const toolkit of requestedToolkits) {+ const authConfigId = mappings.authConfigs?.[toolkit];+ if (typeof authConfigId !== 'string') {+ return Option.none<ConsumerToolRouterAuthConfigMappings>();+ }+ requestedAuthConfigs[toolkit] = authConfigId;}- const filtered = normalizeAuthConfigMappings({- authConfigs: Object.fromEntries(- requestedAuthConfigs.map(([toolkit, authConfigId]) => [toolkit, authConfigId as string])- ),- });+ const filtered = normalizeAuthConfigMappings({ authConfigs: requestedAuthConfigs });return filtered ? Option.some(filtered) : Option.none<ConsumerToolRouterAuthConfigMappings>();});diff --git a/ts/packages/cli/src/services/native-ui-sidecar.ts b/ts/packages/cli/src/services/native-ui-sidecar.tsindex 8c8e11b1d..f35fb2efc 100644--- a/ts/packages/cli/src/services/native-ui-sidecar.ts+++ b/ts/packages/cli/src/services/native-ui-sidecar.ts@@ -3,6 +3,7 @@ import fsSync from 'node:fs';import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';+import { Config, ConfigProvider, Effect, Option, Predicate, Schema } from 'effect';import {detectCliPlatform,ensureBundledBinaryExecutable,@@ -36,6 +37,58 @@ interface NativeUiDecisionPayload {const hasEnvPrefix = (env: NodeJS.ProcessEnv, prefix: string): boolean =>Object.keys(env).some(key => key.startsWith(prefix));+const FALSY_ENV_FLAG_VALUES: ReadonlyArray<string> = ['0', 'false', 'no', 'off'];++// Any other non-empty value counts as set (`CI=woohoo` still disables the UI)+// rather than failing config decoding the way `Config.boolean` would.+const EnvFlagFromString = Schema.transform(+ Schema.compose(Schema.Trim, Schema.Lowercase),+ Schema.Boolean,+ {+ decode: value => !FALSY_ENV_FLAG_VALUES.includes(value),+ encode: enabled => (enabled ? '1' : '0'),+ strict: true,+ }+);+const decodeEnvFlag = Schema.decodeOption(EnvFlagFromString);++// None when the variable is unset or blank, so callers can distinguish+// "not configured" from an explicit true/false.+const envFlag = (name: string): Config.Config<Option.Option<boolean>> =>+ Config.string(name).pipe(+ Config.map(value => value.trim()),+ Config.option,+ Config.map(Option.filter(value => value.length > 0)),+ Config.map(Option.flatMap(decodeEnvFlag))+ );++/**+ * Interactive permission UI (the native sidecar dialog and the browser+ * approval page) must never spawn from automated environments. The explicit+ * COMPOSIO_DISABLE_PERMISSION_UI knob wins in both directions; without it,+ * CI and Vitest runs disable the UI.+ */+export const interactivePermissionUiDisabledConfig: Config.Config<boolean> = Config.all({+ explicit: envFlag('COMPOSIO_DISABLE_PERMISSION_UI'),+ ci: envFlag('CI'),+ vitest: envFlag('VITEST'),+}).pipe(+ Config.map(({ explicit, ci, vitest }) =>+ Option.getOrElse(+ explicit,+ () => Option.getOrElse(ci, () => false) || Option.getOrElse(vitest, () => false)+ )+ )+);++// CI / VITEST / COMPOSIO_DISABLE_PERMISSION_UI are read verbatim, so load them+// through a raw env provider rather than the CLI's COMPOSIO_-prefixed one.+const environmentProvider = ConfigProvider.fromEnv();++export const isInteractivePermissionUiDisabled: Effect.Effect<boolean> = environmentProvider+ .load(interactivePermissionUiDisabledConfig)+ .pipe(Effect.orDie);+const normalizeCallerAgent = (value?: string): NativeUiCallerAgent | undefined => {const normalized = value?.toLowerCase().replace(/[^a-z]/g, '');if (normalized === 'claude' || normalized === 'codex' || normalized === 'openclaw') {@@ -128,8 +181,10 @@ export const requestNativeUiPermissionDecision = async (params: {readonly accountLabel?: string;readonly timeoutSeconds?: number;}): Promise<NativeUiPermissionDecision | undefined> => {+ if (await Effect.runPromise(isInteractivePermissionUiDisabled)) return undefined;+const resolved = resolveNativeUiBinary();- if (resolved._tag !== 'found') return undefined;+ if (!Predicate.isTagged(resolved, 'found')) return undefined;await ensureBundledBinaryExecutable(resolved.binaryPath);diff --git a/ts/packages/cli/src/services/tool-permissions.ts b/ts/packages/cli/src/services/tool-permissions.tsindex e03105a80..8e43d6e38 100644--- a/ts/packages/cli/src/services/tool-permissions.ts+++ b/ts/packages/cli/src/services/tool-permissions.ts@@ -3,10 +3,11 @@ import fs from 'node:fs/promises';import path from 'node:path';import open from 'open';import { detectCliPlatform } from '@composio/cli-local-tools';-import { Effect, Option } from 'effect';+import { Effect, Option, Schema } from 'effect';import { resolveCliConfigDirectorySync } from 'src/services/cli-user-config';import {detectNativeUiCallerAgent,+ isInteractivePermissionUiDisabled,requestNativeUiPermissionDecision,type NativeUiCallerAgent,} from 'src/services/native-ui-sidecar';@@ -29,13 +30,9 @@ export type PermissionDefaultMode = 'allow_all' | 'ask_every_call' | 'ask_once_pexport type PermissionOverrideState = 'always_allow' | 'always_deny' | 'ask_once' | 'ask_always';export type PermissionDecision = 'allow_once' | 'allow_session' | 'deny';export type PermissionApprovalStatus =- | 'always_approved'- | 'cached_approved'- | 'approved_once'- | 'approved_for_session';+ 'always_approved' | 'cached_approved' | 'approved_once' | 'approved_for_session';export type PermissionGateResult =- | { readonly approvalStatus: PermissionApprovalStatus }- | undefined;+ { readonly approvalStatus: PermissionApprovalStatus } | undefined;export interface ToolRouterPermissionsConfig {readonly default: PermissionDefaultMode;@@ -61,6 +58,73 @@ interface CacheFile {readonly allowEntries?: Readonly<Record<string, CachedAllowDecision>>;}+const PermissionDefaultModeSchema = Schema.Literal(+ 'allow_all',+ 'ask_every_call',+ 'ask_once_per_session'+);+const PermissionOverrideStateSchema = Schema.Literal(+ 'always_allow',+ 'always_deny',+ 'ask_once',+ 'ask_always'+);+const ToolRouterPermissionsConfigSchema = Schema.Struct({+ default: PermissionDefaultModeSchema,+ overrides: Schema.optional(+ Schema.Record({ key: Schema.String, value: PermissionOverrideStateSchema })+ ),+});+const ConsumerPermissionSnapshotSchema = Schema.Struct({+ orgId: Schema.String,+ projectId: Schema.String,+ consumerUserId: Schema.String,+ enhancedControlsEnabled: Schema.Boolean,+ permissions: Schema.optional(ToolRouterPermissionsConfigSchema),+ connectedAccountIds: Schema.Array(Schema.String),+ fetchedAt: Schema.Number,+});+const CachedAllowDecisionSchema = Schema.Struct({+ expiresAt: Schema.Number,+});++const UnknownRecordSchema = Schema.Record({ key: Schema.String, value: Schema.Unknown });+const decodeCacheShell = Schema.decodeUnknownOption(+ Schema.parseJson(+ Schema.Struct({+ entries: Schema.optional(UnknownRecordSchema),+ allowEntries: Schema.optional(UnknownRecordSchema),+ })+ )+);+const decodeSnapshotEntry = Schema.decodeUnknownOption(ConsumerPermissionSnapshotSchema);+const decodeAllowEntry = Schema.decodeUnknownOption(CachedAllowDecisionSchema);++const collectDecodedEntries = <A>(+ entries: Readonly<Record<string, unknown>> | undefined,+ decode: (value: unknown) => Option.Option<A>+): Record<string, A> =>+ Object.fromEntries(+ Object.entries(entries ?? {}).flatMap(([key, value]) =>+ Option.match(decode(value), {+ onNone: () => [],+ onSome: entry => [[key, entry] as const],+ })+ )+ );++// Per-entry decode: one stale or version-skewed entry drops only itself.+// Discarding the whole file would also wipe all cached allow decisions and+// be persisted back on the next write.+export const decodeCacheFileTolerant = (raw: string): CacheFile =>+ Option.match(decodeCacheShell(raw), {+ onNone: (): CacheFile => ({ entries: {} }),+ onSome: shell => ({+ entries: collectDecodedEntries(shell.entries, decodeSnapshotEntry),+ allowEntries: collectDecodedEntries(shell.allowEntries, decodeAllowEntry),+ }),+ });+interface PermissionResolveResponse {readonly experimental?: {readonly permissions?: ToolRouterPermissionsConfig;@@ -106,10 +170,11 @@ const pruneAllowEntries = (const readCacheFile = async (): Promise<CacheFile> => {try {const raw = await fs.readFile(cachePath(), 'utf8');- const parsed = JSON.parse(raw) as CacheFile;- return parsed && typeof parsed === 'object' && parsed.entries- ? { entries: parsed.entries, allowEntries: pruneAllowEntries(parsed.allowEntries) }- : { entries: {} };+ const parsed = decodeCacheFileTolerant(raw);+ return {+ entries: parsed.entries,+ allowEntries: pruneAllowEntries(parsed.allowEntries),+ };} catch {return { entries: {} };}@@ -252,7 +317,7 @@ export const refreshConsumerPermissionSnapshot = (params: {}const enhancedControlsEnabled =remoteEnhancedControlsEnabled && platformSupportsEnhancedControls;- const permissions =+ const resolved =enhancedControlsEnabled && connectedAccountIds.length > 0? yield* Effect.tryPromise(() =>fetchJson<PermissionResolveResponse>({@@ -267,19 +332,46 @@ export const refreshConsumerPermissionSnapshot = (params: {default: 'ask_every_call',},})- ).pipe(Effect.map(response => response.experimental?.permissions))- : undefined;+ ).pipe(+ Effect.map(response => ({+ permissions: response.experimental?.permissions,+ resolveFailed: false,+ })),+ // The org said enhanced controls are ON but the policy could not+ // be learned: fail closed to the interactive default instead of+ // silently allowing tools the policy may explicitly deny.+ Effect.catchAll(error =>+ Effect.logDebug(+ 'Failed to resolve consumer permissions; failing closed to ask_every_call',+ error+ ).pipe(+ Effect.as({+ permissions: { default: 'ask_every_call' } as ToolRouterPermissionsConfig,+ resolveFailed: true,+ })+ )+ )+ )+ : { permissions: undefined, resolveFailed: false };const snapshot: ConsumerPermissionSnapshot = {orgId: params.orgId,projectId: params.projectId,consumerUserId: params.consumerUserId,enhancedControlsEnabled,- permissions,+ permissions: resolved.permissions,connectedAccountIds,fetchedAt: Date.now(),};- yield* Effect.tryPromise(() => writeCacheEntry(snapshot));+ // A fail-closed snapshot is not persisted, so a healthy fetch replaces it+ // on the next command instead of pinning ask_every_call for the TTL.+ if (!resolved.resolveFailed) {+ yield* Effect.tryPromise(() => writeCacheEntry(snapshot)).pipe(+ Effect.catchAll(error =>+ Effect.logDebug('Failed to write the tool permissions cache', error)+ )+ );+ }return snapshot;}).pipe(Effect.catchAll(error =>@@ -366,15 +458,26 @@ export const getConnectedAccountPermissionGroup = (params: {};const resolvePermissionState = (- params: GateParams+ params: GateParams & { readonly snapshot: ConsumerPermissionSnapshot }): PermissionOverrideState | PermissionDefaultMode => {- const permissions = params.snapshot?.permissions;+ const permissions = params.snapshot.permissions;const override =permissions?.overrides?.[permissionField(params.toolSlug, params.connectedAccountId)] ??permissions?.overrides?.[accountPermissionField(params.connectedAccountId)];return override ?? permissions?.default ?? 'allow_all';};+// The gate's decision table: 'skip' means gating does not apply (developer+// mode, or controls known disabled). A snapshot synthesized from a failed+// permission resolve carries default: 'ask_every_call' and therefore prompts.+export const resolveGateState = (+ params: GateParams+): PermissionOverrideState | PermissionDefaultMode | 'skip' => {+ if (params.snapshot === undefined) return 'skip';+ if (!params.snapshot.enhancedControlsEnabled || !params.snapshot.permissions) return 'skip';+ return resolvePermissionState({ ...params, snapshot: params.snapshot });+};+const allowCacheKey = (params: GateParams) =>`${params.snapshot?.orgId ?? 'unknown'}:${params.snapshot?.projectId ?? 'unknown'}:${params.snapshot?.consumerUserId ?? 'unknown'}:${permissionField(params.toolSlug, params.connectedAccountId)}`;@@ -843,6 +946,12 @@ const requestPermissionDecision = async (params: {readonly toolSlug: string;readonly accountLabel?: string;}): Promise<PermissionDecision> => {+ if (await Effect.runPromise(isInteractivePermissionUiDisabled)) {+ throw new Error(+ `Interactive permission prompts are disabled in this environment (CI/VITEST, or COMPOSIO_DISABLE_PERMISSION_UI); cannot collect an approval for ${params.toolSlug}.`+ );+ }+// Prefer the bundled macOS native sidecar when it is available. The browser// prompt remains the cross-platform fallback and is only opened when the// native sidecar is missing or fails before returning a decision.@@ -854,9 +963,9 @@ const requestPermissionDecision = async (params: {export const gateToolExecution = (params: GateParams) =>Effect.gen(function* () {- if (!params.snapshot?.enhancedControlsEnabled || !params.snapshot.permissions) return;+ const state = resolveGateState(params);+ if (state === 'skip') return;- const state = resolvePermissionState(params);if (state === 'allow_all' || state === 'always_allow') {return { approvalStatus: 'always_approved' } satisfies PermissionGateResult;}@@ -874,6 +983,16 @@ export const gateToolExecution = (params: GateParams) =>return { approvalStatus: 'cached_approved' } satisfies PermissionGateResult;}+ // Fail closed instead of spawning approval UI where nobody can answer it+ // (tests, CI). Cached allow decisions above still apply.+ if (yield* isInteractivePermissionUiDisabled) {+ return yield* Effect.fail(+ new Error(+ `Tool execution requires interactive approval, but permission prompts are disabled in this environment (CI/VITEST, or COMPOSIO_DISABLE_PERMISSION_UI): ${params.toolSlug}`+ )+ );+ }+const decision = yield* Effect.tryPromise(() =>requestPermissionDecision({toolSlug: params.toolSlug,diff --git a/ts/packages/cli/src/services/triggers-realtime.ts b/ts/packages/cli/src/services/triggers-realtime.tsindex 20266b58b..220bbcb8a 100644--- a/ts/packages/cli/src/services/triggers-realtime.ts+++ b/ts/packages/cli/src/services/triggers-realtime.ts@@ -62,9 +62,13 @@ type ChunkedRealtimeEvent = {export class TriggerRealtimeSubscriptionError extends Data.TaggedError('services/TriggerRealtimeSubscriptionError')<{+ readonly message: string;readonly cause?: unknown;}> {}+const subscriptionError = (message: string) => (cause: unknown) =>+ new TriggerRealtimeSubscriptionError({ message, cause });+/*** Service for listening to trigger events over Composio CLI realtime channels.* Uses:@@ -80,11 +84,14 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(const runtime = yield* Effect.runtime<never>();const listenWith = (params: {- getRealtimeCredentials: () => Effect.Effect<CliRealtimeCredentialsResponse>;+ getRealtimeCredentials: () => Effect.Effect<+ CliRealtimeCredentialsResponse,+ TriggerRealtimeSubscriptionError+ >;authRealtimeChannel: (params: {channel_name: string;socket_id: string;- }) => Effect.Effect<CliRealtimeAuthResponse>;+ }) => Effect.Effect<CliRealtimeAuthResponse, TriggerRealtimeSubscriptionError>;onEvent: (data: RawRealtimeEvent) => void;}) =>Effect.acquireUseRelease(@@ -94,7 +101,7 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(const pusherModule = yield* Effect.tryPromise({try: () => import('pusher-js'),- catch: cause => new TriggerRealtimeSubscriptionError({ cause }),+ catch: subscriptionError('Failed to load the realtime client'),});const Pusher = pusherModule.default as unknown as PusherCtor;@@ -252,14 +259,20 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(resource =>Effect.tryPromise({try: () => resource.shutdown(),- catch: cause => new TriggerRealtimeSubscriptionError({ cause }),+ catch: subscriptionError('Failed to shut down the realtime subscription'),}).pipe(Effect.catchAll(() => Effect.void)));const listen = (onEvent: (data: RawRealtimeEvent) => void) =>listenWith({- getRealtimeCredentials: () => sessionRepo.getRealtimeCredentials().pipe(Effect.orDie),- authRealtimeChannel: params => sessionRepo.authRealtimeChannel(params).pipe(Effect.orDie),+ getRealtimeCredentials: () =>+ sessionRepo+ .getRealtimeCredentials()+ .pipe(Effect.mapError(subscriptionError('Failed to fetch realtime credentials'))),+ authRealtimeChannel: params =>+ sessionRepo+ .authRealtimeChannel(params)+ .pipe(Effect.mapError(subscriptionError('Failed to authorize the realtime channel'))),onEvent,});@@ -277,13 +290,13 @@ export class TriggersRealtime extends Effect.Service<TriggersRealtime>()(getRealtimeCredentials: () =>Effect.tryPromise({try: () => client.cli.realtime.credentials(),- catch: cause => new TriggerRealtimeSubscriptionError({ cause }),- }).pipe(Effect.orDie),+ catch: subscriptionError('Failed to fetch realtime credentials'),+ }),authRealtimeChannel: params =>Effect.tryPromise({try: () => client.cli.realtime.auth(params),- catch: cause => new TriggerRealtimeSubscriptionError({ cause }),- }).pipe(Effect.orDie),+ catch: subscriptionError('Failed to authorize the realtime channel'),+ }),onEvent,});});diff --git a/ts/packages/cli/src/utils/api-error-extraction.ts b/ts/packages/cli/src/utils/api-error-extraction.tsindex 4e7926fcd..d176948bb 100644--- a/ts/packages/cli/src/utils/api-error-extraction.ts+++ b/ts/packages/cli/src/utils/api-error-extraction.ts@@ -9,13 +9,42 @@* `tools execute` command (for error display).*/-export type ApiErrorDetails = {- message?: string;- code?: number;- slug?: string;- status?: number;- request_id?: string;- suggested_fix?: string;+import { Predicate } from 'effect';++export interface ApiErrorDetails {+ readonly message?: string;+ readonly code?: number;+ readonly slug?: string;+ readonly status?: number;+ readonly request_id?: string;+ readonly suggested_fix?: string;+}++const pickString = (value: object, key: string): string | undefined =>+ Predicate.hasProperty(value, key) && Predicate.isString(value[key]) ? value[key] : undefined;++const pickNumber = (value: object, key: string): number | undefined =>+ Predicate.hasProperty(value, key) && Predicate.isNumber(value[key]) ? value[key] : undefined;++// Field-by-field extraction: a present-but-mistyped field (e.g. a numeric+// `message`) drops only that field, not the node's other perfectly good+// details like `slug` and `request_id`.+const extractCandidate = (value: object): ApiErrorDetails | undefined => {+ const candidate: ApiErrorDetails = {+ message: pickString(value, 'message'),+ code: pickNumber(value, 'code'),+ slug: pickString(value, 'slug'),+ status: pickNumber(value, 'status'),+ request_id: pickString(value, 'request_id'),+ suggested_fix: pickString(value, 'suggested_fix'),+ };+ const hasAnyApiField =+ candidate.message !== undefined ||+ candidate.code !== undefined ||+ candidate.slug !== undefined ||+ candidate.status !== undefined ||+ candidate.request_id !== undefined;+ return hasAnyApiField ? candidate : undefined;};/**@@ -98,16 +127,6 @@ export const extractSlug = (value: unknown): string | undefined => {* Skips Error instances and Effect's UnknownException wrappers.*/export const extractApiErrorDetails = (value: unknown): ApiErrorDetails | undefined => {- const isUnknownException = (candidate: object): boolean =>- '_tag' in candidate && (candidate as { _tag?: unknown })._tag === 'UnknownException';-- const hasApiFields = (candidate: ApiErrorDetails): boolean =>- 'message' in candidate ||- 'code' in candidate ||- 'slug' in candidate ||- 'status' in candidate ||- 'request_id' in candidate;-const hasStrongApiFields = (candidate: ApiErrorDetails): boolean =>typeof candidate.slug === 'string' || typeof candidate.request_id === 'string';@@ -123,10 +142,10 @@ export const extractApiErrorDetails = (value: unknown): ApiErrorDetails | undefi}seen.add(current);- const candidate = current as ApiErrorDetails;- const isWrapper = current instanceof Error || isUnknownException(current as object);+ const candidate = extractCandidate(current);+ const isWrapper = current instanceof Error || Predicate.isTagged(current, 'UnknownException');- if (hasApiFields(candidate) && !isWrapper) {+ if (candidate !== undefined && !isWrapper) {if (hasStrongApiFields(candidate)) {return candidate;}diff --git a/ts/packages/cli/test/src/effect-errors/extract-error-details.test.ts b/ts/packages/cli/test/src/effect-errors/extract-error-details.test.tsnew file mode 100644index 000000000..4561b7375--- /dev/null+++ b/ts/packages/cli/test/src/effect-errors/extract-error-details.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest';+import { Data } from 'effect';+import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';++class RequestError extends Data.TaggedError('RequestError')<{+ readonly message: string;+ readonly cause: unknown;+}> {}++describe('extractErrorDetails', () => {+ it('preserves a tagged error message and appends the cause detail', () => {+ const error = new RequestError({+ message: 'The request failed for /api/signup.',+ cause: new TypeError('fetch failed'),+ });++ expect(extractErrorDetails(error)).toStrictEqual({+ isPlainString: false,+ type: 'RequestError',+ message: 'The request failed for /api/signup.\nCaused by: fetch failed',+ });+ });++ it('surfaces the deepest cause message in a nested chain', () => {+ const deepest = new Error('expected NonEmptyString, got null');+ const middle = new Error('Failed to parse GitHub release JSON response', { cause: deepest });+ const error = new RequestError({+ message: 'Upgrade failed.',+ cause: middle,+ });++ expect(extractErrorDetails(error)).toStrictEqual({+ isPlainString: false,+ type: 'RequestError',+ message: 'Upgrade failed.\nCaused by: expected NonEmptyString, got null',+ });+ });++ it('leaves the message untouched when the cause carries no detail', () => {+ const error = new RequestError({+ message: 'The request failed.',+ cause: undefined,+ });++ expect(extractErrorDetails(error)).toStrictEqual({+ isPlainString: false,+ type: 'RequestError',+ message: 'The request failed.',+ });+ });++ it('does not repeat a cause message identical to the wrapper message', () => {+ const error = new RequestError({+ message: 'boom',+ cause: new Error('boom'),+ });++ expect(extractErrorDetails(error)).toStrictEqual({+ isPlainString: false,+ type: 'RequestError',+ message: 'boom',+ });+ });+});diff --git a/ts/packages/cli/test/src/effects/decode-connected-account-list.test.ts b/ts/packages/cli/test/src/effects/decode-connected-account-list.test.tsnew file mode 100644index 000000000..a9bfd77aa--- /dev/null+++ b/ts/packages/cli/test/src/effects/decode-connected-account-list.test.ts@@ -0,0 +1,81 @@+import { describe, expect, layer } from '@effect/vitest';+import { Console, Effect, Layer, ParseResult } from 'effect';+import { decodeConnectedAccountItemsWithFallback } from 'src/effects/decode-connected-account-list';+import type { ConnectedAccountItem } from 'src/models/connected-accounts';+import { MockConsole } from 'test/__utils__';+import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';++const TestLayer = Layer.unwrapEffect(+ Effect.map(MockConsole.make, _console =>+ Layer.mergeAll(Console.setConsole(_console), TerminalUITest)+ )+);++const makeItem = (overrides?: Record<string, unknown>) => ({+ id: 'con_decode_test',+ alias: 'default',+ word_id: 'castle',+ status: 'ACTIVE',+ status_reason: null,+ is_disabled: false,+ user_id: 'user_test',+ toolkit: { slug: 'gmail' },+ auth_config: {+ id: 'ac_gmail_oauth',+ auth_scheme: 'OAUTH2',+ is_composio_managed: true,+ is_disabled: false,+ },+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-15T00:00:00Z',+ test_request_endpoint: '',+ ...overrides,+});++describe('decodeConnectedAccountItemsWithFallback', () => {+ layer(TestLayer)('[Given] items matching the strict schema', it => {+ it.effect('decodes without warning', () =>+ Effect.gen(function* () {+ const items = yield* decodeConnectedAccountItemsWithFallback([makeItem()]);++ expect(items).toStrictEqual([makeItem()]);+ expect(yield* MockConsole.getLines()).toStrictEqual([]);+ })+ );+ });++ layer(TestLayer)('[Given] a status newer than this CLI build', it => {+ it.effect('warns, keeps the unknown status, and still strips credential fields', () =>+ Effect.gen(function* () {+ const raw = makeItem({+ status: 'QUANTUM_LINKED',+ state: { access_token: 'must-not-leak' },+ data: { refresh_token: 'must-not-leak' },+ });++ const items = yield* decodeConnectedAccountItemsWithFallback([raw]);++ expect(items).toStrictEqual([+ makeItem({ status: 'QUANTUM_LINKED' }) as unknown as ConnectedAccountItem,+ ]);+ expect(JSON.stringify(items)).not.toContain('must-not-leak');++ const output = (yield* MockConsole.getLines()).join('\n');+ expect(output).toContain('does not recognize');+ expect(output).toContain('composio upgrade');+ })+ );+ });++ layer(TestLayer)('[Given] a payload the permissive schema cannot decode', it => {+ it.effect('fails with ParseError instead of leaking the raw payload', () =>+ Effect.gen(function* () {+ const error = yield* Effect.flip(+ decodeConnectedAccountItemsWithFallback([{ definitely: 'not-an-account' }])+ );++ expect(ParseResult.isParseError(error)).toBe(true);+ })+ );+ });+});diff --git a/ts/packages/cli/test/src/effects/resolve-cli-release.test.ts b/ts/packages/cli/test/src/effects/resolve-cli-release.test.tsnew file mode 100644index 000000000..46a3c170f--- /dev/null+++ b/ts/packages/cli/test/src/effects/resolve-cli-release.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it } from '@effect/vitest';+import { Effect } from 'effect';+import { HttpClient, HttpClientResponse } from '@effect/platform';+import { fetchLatestCliRelease, type GitHubRelease } from 'src/effects/resolve-cli-release';++const githubConfig = {+ API_BASE_URL: 'https://api.github.test',+ OWNER: 'ComposioHQ',+ REPO: 'composio',+};++const stubHttpClient = (body: unknown) =>+ HttpClient.make(request =>+ Effect.succeed(+ HttpClientResponse.fromWeb(+ request,+ new Response(JSON.stringify(body), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ })+ )+ )+ );++const hasRequiredAsset = (release: GitHubRelease) =>+ release.assets.some(asset => asset.name === 'composio-darwin-arm64');++describe('fetchLatestCliRelease', () => {+ it.effect('skips malformed release entries instead of failing resolution', () =>+ Effect.gen(function* () {+ const malformedDraft = {+ tag_name: '@composio/[email protected]',+ draft: true,+ assets: [{ name: 'composio-darwin-arm64', browser_download_url: null }],+ };+ const wellFormed = {+ tag_name: '@composio/[email protected]',+ prerelease: false,+ assets: [+ { name: 'composio-darwin-arm64', browser_download_url: 'https://example.test/cli' },+ ],+ };+ const unrelated = { something: 'else entirely' };++ const latest = yield* fetchLatestCliRelease({+ assetDescription: 'darwin-arm64 binary',+ channel: 'stable',+ githubConfig,+ hasRequiredAsset,+ httpClient: stubHttpClient([malformedDraft, unrelated, wellFormed]),+ });++ expect(latest.tag_name).toBe('@composio/[email protected]');+ })+ );++ it.effect('still fails with a decode error when the body is not an array', () =>+ Effect.gen(function* () {+ const failure = yield* fetchLatestCliRelease({+ assetDescription: 'darwin-arm64 binary',+ channel: 'stable',+ githubConfig,+ hasRequiredAsset,+ httpClient: stubHttpClient({ message: 'rate limited' }),+ }).pipe(Effect.flip);++ expect(failure.reason).toBe('decode');+ })+ );++ it.effect('reports not-found when every entry is malformed', () =>+ Effect.gen(function* () {+ const failure = yield* fetchLatestCliRelease({+ assetDescription: 'darwin-arm64 binary',+ channel: 'stable',+ githubConfig,+ hasRequiredAsset,+ httpClient: stubHttpClient([{ tag_name: '' }, { assets: 'nope' }]),+ }).pipe(Effect.flip);++ expect(failure.reason).toBe('not-found');+ })+ );+});diff --git a/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts b/ts/packages/cli/test/src/services/consumer-short-term-cache.test.tsindex fee92c65e..ceb082bed 100644--- a/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts+++ b/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts@@ -1,6 +1,9 @@import { describe, expect, layer } from '@effect/vitest';import { vi, afterEach } from 'vitest';+import { FileSystem } from '@effect/platform';import { ConfigProvider, Effect, Option } from 'effect';+import path from 'node:path';+import { setupCacheDir } from 'src/effects/setup-cache-dir';import { extendConfigProvider } from 'src/services/config';import * as composioClients from 'src/services/composio-clients';import {@@ -178,6 +181,36 @@ describe('consumer short-term cache', () => {);});+ layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(+ '[Given] one corrupt entry among valid ones [Then] only the corrupt entry is dropped',+ it => {+ it.scoped('keeps valid cache entries when a sibling entry is corrupt', () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const cacheDir = yield* setupCacheDir;+ yield* fs.writeFileString(+ path.join(cacheDir, 'consumer-short-term-cache.json'),+ JSON.stringify({+ 'org_bad:consumer-user-bad': { toolkits: 'not-an-array', expiresAt: 42 },+ 'org_test:consumer-user-test': {+ toolkits: ['github'],+ expiresAt: new Date(Date.now() + 60_000).toISOString(),+ },+ })+ );++ const cached = yield* getFreshConsumerConnectedToolkitsFromCache({+ orgId: 'org_test',+ consumerUserId: 'consumer-user-test',+ });++ const toolkits = Option.getOrElse(cached, (): ReadonlyArray<string> => []);+ expect(toolkits).toContain('github');+ })+ );+ }+ );+layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))('[Given] a full auth-config cache hit [Then] cache reads are toolkit-complete',it => {diff --git a/ts/packages/cli/test/src/services/native-ui-sidecar.test.ts b/ts/packages/cli/test/src/services/native-ui-sidecar.test.tsnew file mode 100644index 000000000..d2ab51fdd--- /dev/null+++ b/ts/packages/cli/test/src/services/native-ui-sidecar.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from '@effect/vitest';+import { ConfigProvider, Effect } from 'effect';+import { interactivePermissionUiDisabledConfig } from 'src/services/native-ui-sidecar';++const loadFlag = (entries: Record<string, string>): boolean =>+ Effect.runSync(+ ConfigProvider.fromMap(new Map(Object.entries(entries))).load(+ interactivePermissionUiDisabledConfig+ )+ );++describe('native UI sidecar', () => {+ it('disables interactive permission UI in CI and Vitest environments', () => {+ expect(loadFlag({})).toBe(false);+ expect(loadFlag({ CI: 'true' })).toBe(true);+ expect(loadFlag({ CI: '1' })).toBe(true);+ expect(loadFlag({ CI: 'woohoo' })).toBe(true);+ expect(loadFlag({ CI: 'false' })).toBe(false);+ expect(loadFlag({ CI: '' })).toBe(false);+ expect(loadFlag({ VITEST: 'true' })).toBe(true);+ });++ it('lets COMPOSIO_DISABLE_PERMISSION_UI override environment detection in both directions', () => {+ expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '1' })).toBe(true);+ expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: 'true' })).toBe(true);+ expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '0', CI: 'true', VITEST: 'true' })).toBe(+ false+ );+ expect(loadFlag({ COMPOSIO_DISABLE_PERMISSION_UI: '', CI: 'true' })).toBe(true);+ });+});diff --git a/ts/packages/cli/test/src/services/tool-permissions.test.ts b/ts/packages/cli/test/src/services/tool-permissions.test.tsnew file mode 100644index 000000000..cdc5c8aa0--- /dev/null+++ b/ts/packages/cli/test/src/services/tool-permissions.test.ts@@ -0,0 +1,132 @@+import { afterEach, beforeEach, describe, expect, it, vi } from '@effect/vitest';+import { Effect } from 'effect';+import {+ decodeCacheFileTolerant,+ gateToolExecution,+ resolveGateState,+ type ConsumerPermissionSnapshot,+} from 'src/services/tool-permissions';++// Pinned wall clock for deterministic fixtures. The SUT reads the real+// `Date.now()` (snapshot TTL, allow-decision expiry), so every timestamp+// below is expressed relative to this instant.+const PINNED_TIME = new Date('2026-01-01T00:00:00.000Z');+const PINNED_NOW = PINNED_TIME.getTime();++const snapshotFixture = (+ overrides: Partial<ConsumerPermissionSnapshot> = {}+): ConsumerPermissionSnapshot => ({+ orgId: 'org_test',+ projectId: 'project_test',+ consumerUserId: 'user_test',+ enhancedControlsEnabled: true,+ permissions: { default: 'allow_all', overrides: {} },+ connectedAccountIds: [],+ fetchedAt: PINNED_NOW,+ ...overrides,+});++describe('tool permissions', () => {+ beforeEach(() => {+ // Fake ONLY `Date`: the SUT's cache reads/writes run on the live Effect+ // runtime, so real timers and microtasks must keep running.+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(PINNED_TIME);+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllEnvs();+ });++ it('drops only corrupt cache entries, keeping valid snapshots and allow decisions', () => {+ const good = snapshotFixture();+ const raw = JSON.stringify({+ entries: {+ good: good,+ skewed: { ...good, fetchedAt: 'not-a-number' },+ },+ allowEntries: {+ kept: { expiresAt: PINNED_NOW + 60_000 },+ broken: { expiresAt: 'soon' },+ },+ });++ const decoded = decodeCacheFileTolerant(raw);++ expect(Object.keys(decoded.entries)).toStrictEqual(['good']);+ expect(Object.keys(decoded.allowEntries ?? {})).toStrictEqual(['kept']);+ });++ it('returns an empty cache for unparseable cache files', () => {+ expect(decodeCacheFileTolerant('not json')).toStrictEqual({ entries: {} });+ });++ it('skips gating when no snapshot applies (developer mode)', () => {+ expect(resolveGateState({ toolSlug: 'GMAIL_SEND_EMAIL' })).toBe('skip');+ });++ it('skips gating when enhanced controls are known disabled', () => {+ expect(+ resolveGateState({+ toolSlug: 'GMAIL_SEND_EMAIL',+ snapshot: snapshotFixture({ enhancedControlsEnabled: false }),+ })+ ).toBe('skip');+ expect(+ resolveGateState({+ toolSlug: 'GMAIL_SEND_EMAIL',+ snapshot: snapshotFixture({ permissions: undefined }),+ })+ ).toBe('skip');+ });++ it('fails closed via the synthesized ask-every-call snapshot when policy resolution failed', () => {+ // Shape produced by refreshConsumerPermissionSnapshot when the org+ // reports enhanced controls enabled but the permissions resolve fails.+ expect(+ resolveGateState({+ toolSlug: 'GMAIL_SEND_EMAIL',+ snapshot: snapshotFixture({ permissions: { default: 'ask_every_call' } }),+ })+ ).toBe('ask_every_call');+ });++ it('resolves overrides ahead of the default mode', () => {+ expect(+ resolveGateState({+ toolSlug: 'GMAIL_SEND_EMAIL',+ snapshot: snapshotFixture({+ permissions: {+ default: 'allow_all',+ overrides: { 'GMAIL_SEND_EMAIL:__none__': 'always_deny' },+ },+ }),+ })+ ).toBe('always_deny');+ });++ it.effect('lets execution proceed ungated without a snapshot', () =>+ Effect.gen(function* () {+ const result = yield* gateToolExecution({ toolSlug: 'GMAIL_SEND_EMAIL' });++ expect(result).toBeUndefined();+ })+ );++ it.effect('fails closed when interactive approval is needed but permission UI is disabled', () =>+ Effect.gen(function* () {+ vi.stubEnv('COMPOSIO_DISABLE_PERMISSION_UI', '1');++ const failure = yield* gateToolExecution({+ toolSlug: 'GMAIL_SEND_EMAIL',+ snapshot: snapshotFixture({ permissions: { default: 'ask_every_call' } }),+ }).pipe(Effect.flip);++ expect(failure).toBeInstanceOf(Error);+ if (failure instanceof Error) {+ expect(failure.message).toContain('permission prompts are disabled');+ }+ })+ );+});diff --git a/ts/packages/cli/test/src/utils/api-error-extraction.test.ts b/ts/packages/cli/test/src/utils/api-error-extraction.test.tsnew file mode 100644index 000000000..8cd8bb9cc--- /dev/null+++ b/ts/packages/cli/test/src/utils/api-error-extraction.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from 'vitest';+import { extractApiErrorDetails } from 'src/utils/api-error-extraction';++describe('extractApiErrorDetails', () => {+ it('extracts details from a well-formed API error body', () => {+ const details = extractApiErrorDetails({+ error: {+ message: 'Rate limited',+ slug: 'rate_limited',+ request_id: 'req_abc',+ code: 42901,+ },+ });++ expect(details).toMatchObject({+ message: 'Rate limited',+ slug: 'rate_limited',+ request_id: 'req_abc',+ code: 42901,+ });+ });++ it('keeps well-typed fields when a sibling field has an unexpected type', () => {+ const details = extractApiErrorDetails({+ error: {+ message: 42901,+ slug: 'rate_limited',+ request_id: 'req_abc',+ },+ });++ expect(details?.slug).toBe('rate_limited');+ expect(details?.request_id).toBe('req_abc');+ expect(details?.message).toBeUndefined();+ });++ it('prefers a node with strong fields over a weaker shallower node', () => {+ const details = extractApiErrorDetails({+ message: 'outer wrapper',+ error: {+ message: 'API says no',+ slug: 'tool_not_found',+ },+ });++ expect(details?.slug).toBe('tool_not_found');+ expect(details?.message).toBe('API says no');+ });++ it('skips Error wrappers but follows their cause chain', () => {+ const inner = { slug: 'expired_key', message: 'Key expired' };+ const wrapper = new Error('generic wrapper');+ Object.assign(wrapper, { cause: inner });++ expect(extractApiErrorDetails(wrapper)?.slug).toBe('expired_key');+ });++ it('returns undefined when nothing in the chain carries API fields', () => {+ expect(extractApiErrorDetails({ foo: 'bar' })).toBeUndefined();+ expect(extractApiErrorDetails(undefined)).toBeUndefined();+ expect(extractApiErrorDetails('plain string')).toBeUndefined();+ });+});