@devries-cameron20 / composio-1 / commits / d27294aff
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.

fix(cli): use the public tool execution logs API (#5144)

This PR: - closes [PRDE-1916](https://linear.app/composio/issue/PRDE-1916) - moves `composio dev logs tools` list and detail requests to the typed public `logs.createToolExecution()` and `logs.retrieveToolExecution()` operations on the CLI's `@composio/client/effect` client, typed with `LogCreateToolExecutionParams` and the response types from `@composio/client/resources/logs` - caps pages at 100, maps shorthand filters to the public fields, preserves string cursors, and supplies both bounds for one-sided time ranges - renders unified log metadata and request/response details while retaining tolerant response handling; a log without a recorded duration shows `-` instead of `0ms` - breaking: piped JSON now uses the public `logs` / `next_cursor` envelope and unified detail fields; `--case-sensitive` and the legacy `--session-id` filter fail explicitly because the public API cannot represent them (`--tool-router-session-id` remains supported) - breaking: each filter flag (`--toolkit`, `--tool`, `--status`, `--user-id`, `--log-id`, `--connected-account-id`, `--auth-config-id`, `--tool-router-session-id`) takes one value. The public API ANDs every filter and has no `in` operator, so a comma-separated list would match nothing; it now fails with a `CommandInputError` naming the flag Validation: `pnpm typecheck`; CLI suite (2,908 passed, 1 skipped, with agent-host markers unset for subprocess stderr assertions); `pnpm --filter @composio/cli run lint:effect`; Oxlint on the changed source/tests with `--no-ignore`; agent-skills and skill-routing validators. Request tests use the real client over local HTTP stubs; live API authentication was not exercised. No recording: this developer command keeps its existing list/detail invocation. Review the full diff, especially the documented JSON and filter changes.

Alberto Schiabel committed Nov 16, 2026 at 12:00 UTC d27294aff99f9a54d7374d84d705aaf14943b386
13 files changed +460 -478
ts/e2e-tests/runtimes/node/custom-tools/e2e.test.ts
+1 -1
@@ -3,7 +3,7 @@
3 *
4 * Verifies local tool execution, Zod validation, session context, error handling,
5 * mixed local+remote chaining, and edge cases against the live Composio API.
6 - * Uses weathermap toolkit (no auth needed).
6 + * Uses the hackernews toolkit (public, no auth needed).
7 * Requires COMPOSIO_API_KEY in environment.
8 */
9
ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjs
+20 -20
@@ -3,7 +3,7 @@
3 * Tests local execution, remote execution, mixed routing, error handling,
4 * and SessionContext chaining against the live Composio API.
5 *
6 - * Uses weathermap toolkit (no auth needed, active connection).
6 + * Uses the hackernews toolkit (public, no auth needed).
7 * Requires COMPOSIO_API_KEY in environment.
8 */
9 import { Composio, experimental_createTool as createCustomTool } from '@composio/core';
@@ -64,22 +64,22 @@ const strictTool = createCustomTool('STRICT_TOOL', {
64 });
65
66 // Tool that chains into a remote tool via SessionContext.execute()
67 -const weatherChain = createCustomTool('WEATHER_CHAIN', {
68 - name: 'Weather chain',
69 - description: 'Fetches weather via remote tool and enriches with local context',
67 +const hackerNewsChain = createCustomTool('HACKERNEWS_CHAIN', {
68 + name: 'Hacker News chain',
69 + description: 'Fetches a Hacker News profile via a remote tool and enriches it locally',
70 inputParams: z.object({
71 - city: z.string(),
71 + username: z.string(),
72 }),
73 execute: async (input, ctx) => {
74 - // Call remote WEATHERMAP_WEATHER tool through SessionContext
75 - const weather = await ctx.execute('WEATHERMAP_WEATHER', {
76 - location: input.city,
74 + // Call remote HACKERNEWS_GET_USER tool through SessionContext
75 + const profile = await ctx.execute('HACKERNEWS_GET_USER', {
76 + username: input.username,
77 });
78 return {
79 - city: input.city,
79 + username: input.username,
80 userId: ctx.userId,
81 - weatherData: weather.data,
82 - weatherError: weather.error,
81 + remoteData: profile.data,
82 + remoteError: profile.error,
83 };
84 },
85 });
@@ -92,10 +92,10 @@ async function main() {
92 const userId = `e2e-custom-tools-${Date.now()}`;
93
94 const session = await composio.create(userId, {
95 - toolkits: ['weathermap'],
95 + toolkits: ['hackernews'],
96 manageConnections: false,
97 experimental: {
98 - customTools: [getUserContext, enrichedSearch, throwingTool, strictTool, weatherChain],
98 + customTools: [getUserContext, enrichedSearch, throwingTool, strictTool, hackerNewsChain],
99 },
100 });
101
@@ -190,21 +190,21 @@ async function main() {
190
191 // ── Test 9: SessionContext.execute() chaining — local tool calls remote tool ──
192 // This is mixed local+remote execution: local tool runs in-process,
193 - // then calls WEATHERMAP_WEATHER on the backend via session.execute()
193 + // then calls HACKERNEWS_GET_USER on the backend via session.execute()
194 {
195 - const result = await session.execute('WEATHER_CHAIN', { city: 'London' });
195 + const result = await session.execute('HACKERNEWS_CHAIN', { username: 'pg' });
196 if (result.error) {
197 throw new Error(`CHAINED_EXECUTE failed: ${result.error}`);
198 }
199 - if (result.data?.city !== 'London') {
200 - throw new Error(`CHAINED_EXECUTE city mismatch: ${JSON.stringify(result)}`);
199 + if (result.data?.username !== 'pg') {
200 + throw new Error(`CHAINED_EXECUTE username mismatch: ${JSON.stringify(result)}`);
201 }
202 if (!result.data?.userId) {
203 throw new Error(`CHAINED_EXECUTE missing userId: ${JSON.stringify(result)}`);
204 }
205 - // The chained remote call should have returned weather data
206 - if (!result.data?.weatherData) {
207 - throw new Error(`CHAINED_EXECUTE missing weatherData: ${JSON.stringify(result)}`);
205 + // The chained remote call should have returned the Hacker News profile
206 + if (!result.data?.remoteData) {
207 + throw new Error(`CHAINED_EXECUTE missing remoteData: ${JSON.stringify(result)}`);
208 }
209 console.log('CHAINED_EXECUTE_OK');
210 }
ts/packages/cli/AGENTS.md
+1 -1
@@ -208,7 +208,7 @@ Each nested `Arr.flatMap` adds one independent axis; the innermost `Arr.map` bui
208
209 - Never branch on an Effect value's internal tag field directly. Use the owning module's public refinement or matcher (`Option`, `Result`, `Exit`, `Cause`, `CliError`), `Match.valueTags` for exhaustive unions, or `Predicate.isTagged` for a single narrowing guard.
210 - Do not wrap a plain `Error` in `Effect.fail` for expected failures. Give the failure a meaningful `Data.TaggedError` type with structured fields and a preserved cause, then recover with `catchTag` / `catchTags`. Reserve `Effect.die` and `Effect.dieMessage` for impossible invariants.
211 -- Treat `unknown`, JSON, and persisted state as trust boundaries. Decode them with `effect/Schema` or narrow them with `Predicate`; an `as` assertion is not validation, and hand-rolled structural guards (`'x' in obj` / `typeof` chains) are not a substitute for a schema. Each typed API response is validated at most once. The CLI's own schema validates a response the CLI transforms, filters for stdout, or writes to a cache file: the catalog models (`src/models/toolkits.ts`, `tools.ts`, `trigger-types.ts`), the auth-config and connected-account allowlists that keep credential-bearing fields off stdout (including the list responses and the `auth-configs create` response in `src/models/auth-configs.ts` and `connected-accounts.ts`), the `ToolkitSlug` path-safety check, the `Session` `DateTime` transform, and `TriggerInstanceItems`. Those calls decode with the CLI schema, failing with `services/HttpDecodingError`. The client validates a response against its own generated schema only when the call passes the `validated` request option (`src/services/composio-request.ts`); a mismatch fails with the client's `DecodeError`, which the CLI reports with the operation, the request id, and an upgrade hint. Pass `validated` only on a read the CLI consumes whole through the client's types, where no field may drift: `cli.realtime.credentials` (every field feeds the realtime connection), `org.list` (organization ids and names for login), and `org.consumer.listConnectedToolkits` (a list of slugs). Every other typed call leaves it off: calls that are not reads, because failing after the server acted would invite a retry that repeats the side effect; reads the CLI validates with its own schema; and reads that must tolerate drift because the CLI consumes a few fields of a response whose client schema fixes enums or requires fields the CLI never reads (`logs.tools.*`, `logs.triggers.*`, `tools.list`, `tools.retrieve`, `org.project.list`, `toolRouter.session.search`, `toolRouter.session.toolkits`, `connectedAccounts.list`, which tolerates unknown statuses, and `triggerInstances.listActive`, whose page counts the CLI defaults). Adding a validated read means saying in its doc comment why the CLI cannot tolerate drift there. Responses fetched with the raw `client.get`/`client.post` are untyped and always need a CLI schema (`LatestToolVersionResponse` in `src/models/tools.ts`, and the consumer config and permission payloads in `tool-permissions.ts`). `effect/Schema` is the CLI's schema tool — do not introduce zod here (zod is the convention in the SDK packages and docs).
211 +- Treat `unknown`, JSON, and persisted state as trust boundaries. Decode them with `effect/Schema` or narrow them with `Predicate`; an `as` assertion is not validation, and hand-rolled structural guards (`'x' in obj` / `typeof` chains) are not a substitute for a schema. Each typed API response is validated at most once. The CLI's own schema validates a response the CLI transforms, filters for stdout, or writes to a cache file: the catalog models (`src/models/toolkits.ts`, `tools.ts`, `trigger-types.ts`), the auth-config and connected-account allowlists that keep credential-bearing fields off stdout (including the list responses and the `auth-configs create` response in `src/models/auth-configs.ts` and `connected-accounts.ts`), the `ToolkitSlug` path-safety check, the `Session` `DateTime` transform, and `TriggerInstanceItems`. Those calls decode with the CLI schema, failing with `services/HttpDecodingError`. The client validates a response against its own generated schema only when the call passes the `validated` request option (`src/services/composio-request.ts`); a mismatch fails with the client's `DecodeError`, which the CLI reports with the operation, the request id, and an upgrade hint. Pass `validated` only on a read the CLI consumes whole through the client's types, where no field may drift: `cli.realtime.credentials` (every field feeds the realtime connection), `org.list` (organization ids and names for login), and `org.consumer.listConnectedToolkits` (a list of slugs). Every other typed call leaves it off: calls that are not reads, because failing after the server acted would invite a retry that repeats the side effect; reads the CLI validates with its own schema; and reads that must tolerate drift because the CLI consumes a few fields of a response whose client schema fixes enums or requires fields the CLI never reads (`logs.createToolExecution`, `logs.retrieveToolExecution`, `logs.triggers.*`, `tools.list`, `tools.retrieve`, `org.project.list`, `toolRouter.session.search`, `toolRouter.session.toolkits`, `connectedAccounts.list`, which tolerates unknown statuses, and `triggerInstances.listActive`, whose page counts the CLI defaults). Adding a validated read means saying in its doc comment why the CLI cannot tolerate drift there. Responses fetched with the raw `client.get`/`client.post` are untyped and always need a CLI schema (`LatestToolVersionResponse` in `src/models/tools.ts`, and the consumer config and permission payloads in `tool-permissions.ts`). `effect/Schema` is the CLI's schema tool — do not introduce zod here (zod is the convention in the SDK packages and docs).
212 - Do not inspect private `effect/cli` internals (parser state, `HelpDoc` string shapes, `CliError` suggestion machinery). `Command.runWith` renders help and parse/validation errors itself — see the entry-point section above — so command-tree introspection must stay on the public `Command.Any` surface (`name`, `alias`, `subcommands`). `CliError.InvalidValue` takes structured `{ option, value, expected, kind }` fields, not a free-form message — handler-level validation raises `CommandInputError` from `src/commands/errors.ts` (built with `commandInputError('<command>')`, carrying `command`, `message`, and the `option` at fault), not a hand-built `CliError`. It, `NotLoggedInError`, `ProjectResolutionError`, `ConnectedAccountResolutionError` (an `--account` selector that matches no connected account, or the account lookup behind it failing), and the other expected failures (a missing user id, login, or SDK install; an unknown org, toolkit, or version) declare `get [ExpectedFailure]() { return true; }` from `src/effects/expected-failure.ts` where the class is defined; `isUsageFailure` in `errors.ts` checks that marker, and the invocation prints the message and exits 1, with no defect banner. A new expected error opts in the same way, with no central list to update; a defect stays unmarked. A failure the command prints itself fails already reported: `reportFailure` (`src/effects/report-failure.ts`) prints a message and hint, then fails with `ReportedFailure`; a command that prints more after the message calls `printFailure`, prints the rest, then fails with `ReportedFailure`. A command-specific error the command already printed (`ReportedToolExecutionError` and `ReportedProxyCommandError`, whose result is on stdout as `{ "successful": false }`, `ShellSetupAbortError`, `SetupCommandError`) declares `get [Runtime.errorReported]() { return false; }` and `get [Runtime.errorExitCode]() { return 1; }` where the class is defined. Either way the runtime prints nothing more and exits 1, and telemetry records the command as failed.
213 - Prefer `Effect.mapError`, `Effect.matchEffect`, and typed recovery over `Effect.catch` blocks (the v4 name for what was `Effect.catchAll`) that flatten distinct failures into one message-only error.
214
ts/packages/cli/CHANGELOG.md
+8
@@ -61,6 +61,14 @@
61 128 plus the signal's number, or, for `composio run`, the script's process
62 group is killed and the CLI is killed by that signal.
63
64 +- `composio dev logs tools` now searches and retrieves logs through the public
65 + tool execution logs API. Pages are capped at 100. Piped JSON uses the public
66 + `logs` / `next_cursor` envelope and unified log detail fields. The public API
67 + does not support `--case-sensitive` or the legacy `--session-id` filter;
68 + these now fail with an explanation. `--tool-router-session-id` remains supported.
69 + Each filter flag takes one value; a comma-separated list now fails instead of
70 + matching nothing.
71 +
72 - `composio dev connected-accounts link <toolkit>` (with or without `--list`)
73 now acts on your developer project, like the other `composio dev` commands:
74 the directory's project, or the one `--project-name` names. It links or lists
ts/packages/cli/src/commands/logs/format.ts
+51 -22
@@ -1,10 +1,24 @@
1 -import type { ToolListResponse, ToolRetrieveResponse } from '@composio/client/resources/_internal/logs';
1 +import type {
2 + LogCreateToolExecutionResponse,
3 + LogRetrieveToolExecutionResponse,
4 +} from '@composio/client/resources/logs';
5 +import { Option, Schema } from 'effect';
6 import type { TriggerLogRecord } from 'src/commands/logs/trigger-log-record';
7 import { bold, gray, green, red } from 'src/ui/colors';
8 import { truncate } from 'src/ui/truncate';
9
6 -type ToolLog = ToolListResponse['data'][number];
7 -type ToolLogDetailed = ToolRetrieveResponse;
10 +type ToolLog = LogCreateToolExecutionResponse['logs'][number];
11 +type ToolLogDetailed = LogRetrieveToolExecutionResponse;
12 +
13 +const readRecord = (value: unknown): Record<string, unknown> =>
14 + Option.getOrElse(
15 + Schema.decodeUnknownOption(Schema.Record(Schema.String, Schema.Unknown))(value),
16 + () => ({})
17 + );
18 +const readString = (value: unknown): string | undefined =>
19 + Option.getOrUndefined(Schema.decodeUnknownOption(Schema.String)(value));
20 +const readNumber = (value: unknown): number | undefined =>
21 + Option.getOrUndefined(Schema.decodeUnknownOption(Schema.Number)(value));
22
23 const TRIGGER_LOG_TABLE = {
24 createdAt: 24,
@@ -81,21 +95,27 @@ export const formatToolLogsTable = (logs: ReadonlyArray<ToolLog>): string => {
95 ].join(' ');
96
97 const rows = logs.map(log => {
98 + const metadata = readRecord(log.metadata);
99 + const metrics = readRecord(log.metrics);
100 const createdAt = gray(
85 - truncate(formatCreatedAt(log.createdAt), TOOL_LOG_TABLE.createdAt).padEnd(
101 + truncate(formatCreatedAt(log.timestamp), TOOL_LOG_TABLE.createdAt).padEnd(
102 TOOL_LOG_TABLE.createdAt
103 )
104 );
105 // Keep log ids untruncated for copy/paste workflows.
106 const id = (log.id ?? '-').padEnd(TOOL_LOG_TABLE.id);
107 const status = formatLogStatus(log.status, TOOL_LOG_TABLE.status);
92 - const app = truncate(log.app?.name ?? '-', TOOL_LOG_TABLE.app).padEnd(TOOL_LOG_TABLE.app);
93 - const actionKey = truncate(log.actionKey ?? '-', TOOL_LOG_TABLE.actionKey).padEnd(
108 + const app = truncate(
109 + readString(readRecord(metadata.toolkit).slug) ?? '-',
110 + TOOL_LOG_TABLE.app
111 + ).padEnd(TOOL_LOG_TABLE.app);
112 + const actionKey = truncate(
113 + readString(readRecord(metadata.tool).slug) ?? '-',
114 TOOL_LOG_TABLE.actionKey
95 - );
96 - const executionMs = `${log.executionTime ?? 0}ms`.padEnd(TOOL_LOG_TABLE.executionMs);
115 + ).padEnd(TOOL_LOG_TABLE.actionKey);
116 + const executionMs = formatDuration(metrics.duration_ms).padEnd(TOOL_LOG_TABLE.executionMs);
117 const connectedAccountId = truncate(
98 - valueOrDash(log.connectedAccountId),
118 + valueOrDash(readString(metadata.connected_account_id)),
119 TOOL_LOG_TABLE.connectedAccountId
120 );
121
@@ -120,6 +140,11 @@ const valueOrDash = (value: string | null | undefined): string => {
140 return normalizedValue.length > 0 ? normalizedValue : '-';
141 };
142
143 +const formatDuration = (value: unknown): string => {
144 + const durationMs = readNumber(value);
145 + return durationMs === undefined ? '-' : `${durationMs}ms`;
146 +};
147 +
148 const formatEpoch = (value: number): string => {
149 const date = new Date(value);
150 if (Number.isNaN(date.getTime())) return '-';
@@ -133,19 +158,23 @@ const formatCreatedAt = (value: number | string | null | undefined): string => {
158 };
159
160 export const formatToolLogInfo = (toolLog: ToolLogDetailed): string => {
136 - const lines: string[] = [];
137 - lines.push(`${bold('logId:')} ${toolLog.actionLogId}`);
138 - lines.push(`${bold('toolSlug:')} ${toolLog.actionId}`);
139 - lines.push(`${bold('Status:')} ${toolLog.status}`);
140 - lines.push(`${bold('toolkit:')} ${toolLog.app?.name ?? '-'}`);
141 - lines.push(`${bold('Connection ID:')} ${toolLog.connection?.id ?? '-'}`);
142 - lines.push(`${bold('Entity:')} ${toolLog.connection?.entity ?? '-'}`);
143 - lines.push(`${bold('Start Time:')} ${formatCreatedAt(toolLog.startTime)}`);
144 - lines.push(`${bold('End Time:')} ${formatCreatedAt(toolLog.endTime)}`);
145 - lines.push(`${bold('Total Duration:')} ${toolLog.totalDuration}`);
146 - lines.push(`${bold('Version:')} ${toolLog.version}`);
147 - lines.push(`${bold('Steps:')} ${toolLog.steps?.length ?? 0}`);
148 - return lines.join('\n');
161 + const metadata = readRecord(toolLog.metadata);
162 + const tool = readRecord(metadata.tool);
163 + const data = readRecord(toolLog.data);
164 + return [
165 + `${bold('logId:')} ${toolLog.id}`,
166 + `${bold('toolSlug:')} ${valueOrDash(readString(tool.slug))}`,
167 + `${bold('Status:')} ${valueOrDash(toolLog.status)}`,
168 + `${bold('toolkit:')} ${valueOrDash(readString(readRecord(metadata.toolkit).slug))}`,
169 + `${bold('Connection ID:')} ${valueOrDash(readString(metadata.connected_account_id))}`,
170 + `${bold('Entity:')} ${valueOrDash(readString(metadata.user_id))}`,
171 + `${bold('Start Time:')} ${formatCreatedAt(toolLog.timings?.start_time ?? toolLog.timestamp)}`,
172 + `${bold('End Time:')} ${formatCreatedAt(toolLog.timings?.end_time)}`,
173 + `${bold('Total Duration:')} ${formatDuration(readRecord(toolLog.metrics).duration_ms)}`,
174 + `${bold('Version:')} ${valueOrDash(readString(tool.version))}`,
175 + `\nPayload:\n${JSON.stringify(readRecord(data.request).payload ?? {}, null, 2)}`,
176 + `\nResponse:\n${JSON.stringify(readRecord(data.response).body ?? {}, null, 2)}`,
177 + ].join('\n');
178 };
179
180 export const formatTriggerLogInfo = (triggerLog: TriggerLogRecord): string => {
ts/packages/cli/src/commands/logs/tools/logs.tools.cmd.ts
+13 -13
@@ -1,7 +1,7 @@
1 import { Argument, Command, Flag } from 'effect/cli';
2 import { runLogsTools } from './logs.tools.handler';
3
4 -const cursor = Flag.Int('cursor').pipe(
4 +const cursor = Flag.String('cursor').pipe(
5 Flag.optional,
6 Flag.withDescription('Cursor for pagination')
7 );
@@ -18,59 +18,59 @@ const to = Flag.Int('to').pipe(
18
19 const limit = Flag.Int('limit').pipe(
20 Flag.withDefault(30),
21 - Flag.withDescription('Number of logs to fetch (1-1000)')
21 + Flag.withDescription('Number of logs to fetch (1-100)')
22 );
23
24 const caseSensitive = Flag.Boolean('case-sensitive').pipe(
25 Flag.withDefault(false),
26 - Flag.withDescription('Whether search params are case-sensitive')
26 + Flag.withDescription('Unsupported by the public API; use case-insensitive search')
27 );
28
29 const toolkit = Flag.String('toolkit').pipe(
30 - Flag.withDescription('Filter by toolkit key(s), comma-separated (e.g. "gmail,slack")'),
30 + Flag.withDescription('Filter by one toolkit key (e.g. "gmail")'),
31 Flag.optional
32 );
33
34 const tool = Flag.String('tool').pipe(
35 - Flag.withDescription('Filter by tool key(s), comma-separated (e.g. "GMAIL_SEND_EMAIL")'),
35 + Flag.withDescription('Filter by one tool key (e.g. "GMAIL_SEND_EMAIL")'),
36 Flag.optional
37 );
38
39 const connectedAccountId = Flag.String('connected-account-id').pipe(
40 - Flag.withDescription('Filter by connected account id(s), comma-separated'),
40 + Flag.withDescription('Filter by one connected account id'),
41 Flag.optional
42 );
43
44 const authConfigId = Flag.String('auth-config-id').pipe(
45 - Flag.withDescription('Filter by auth config id(s), comma-separated'),
45 + Flag.withDescription('Filter by one auth config id'),
46 Flag.optional
47 );
48
49 const status = Flag.String('status').pipe(
50 - Flag.withDescription('Filter by execution status value(s), comma-separated'),
50 + Flag.withDescription('Filter by success or failed'),
51 Flag.optional
52 );
53
54 -// Declared for its help row, which documents the comma-separated filter in place of the `dev`
54 +// Declared for its help row, which documents the user filter in place of the `dev`
55 // group's shared row. The parser hands every `--user-id` under `dev` to the shared flag, so
56 // the value is read from `CommandSurface`.
57 const userId = Flag.String('user-id').pipe(
58 - Flag.withDescription('Filter by user id(s), comma-separated'),
58 + Flag.withDescription('Filter by one user id'),
59 Flag.optional
60 );
61
62 const logIdFilter = Flag.String('log-id').pipe(
63 - Flag.withDescription('Filter by log id(s), comma-separated'),
63 + Flag.withDescription('Filter by one log id'),
64 Flag.optional
65 );
66
67 const toolRouterSessionId = Flag.String('tool-router-session-id').pipe(
68 - Flag.withDescription('Filter by tool router session id(s), comma-separated'),
68 + Flag.withDescription('Filter by one tool router session id'),
69 Flag.optional
70 );
71
72 const sessionId = Flag.String('session-id').pipe(
73 - Flag.withDescription('Filter by session id(s), comma-separated'),
73 + Flag.withDescription('Legacy session filter (unsupported by the public API)'),
74 Flag.optional
75 );
76
ts/packages/cli/src/commands/logs/tools/logs.tools.handler.ts
+84 -52
@@ -1,4 +1,6 @@
1 -import { Array as Arr, Effect, Option, String as Str } from 'effect';
1 +import type { LogCreateToolExecutionParams } from '@composio/client/resources/logs';
2 +import { Array as Arr, Clock, Effect, Option, String as Str } from 'effect';
3 +import { commandInputError } from 'src/commands/errors';
4 import { CommandSurface } from 'src/commands/surface';
5 import { parseCsv } from 'src/commands/triggers/parse-csv';
6 import { failedWith } from 'src/effects/request-error';
@@ -6,15 +8,13 @@ import { commandHintStep } from 'src/services/command-hints';
8 import { ComposioClientSingleton } from 'src/services/composio-clients';
9 import { idempotent } from 'src/services/composio-request';
10 import { TerminalUI } from 'src/services/terminal-ui';
9 -import { clampLimit } from 'src/ui/clamp-limit';
11 import { nonEmptyOrUndefined, optionalParams } from 'src/utils/optional-params';
12 import { formatToolLogInfo, formatToolLogsTable } from '../format';
12 -import { toSearchParam, type SearchParam } from '../utils';
13 import { ToolLogsRequestError } from './logs.tools.errors';
14
15 export type LogsToolsParams = {
16 readonly logId: Option.Option<string>;
17 - readonly cursor: Option.Option<number>;
17 + readonly cursor: Option.Option<string>;
18 readonly from: Option.Option<number>;
19 readonly to: Option.Option<number>;
20 readonly limit: number;
@@ -40,34 +40,39 @@ type ToolLogFilterInput = {
40 readonly userId?: string;
41 readonly logId?: string;
42 readonly toolRouterSessionId?: string;
43 - readonly sessionId?: string;
43 };
44
46 -/** The search field each filter is sent as, in the order the filters are sent. */
45 +/**
46 + * The search field each filter is sent as and the flag that sets it, in the
47 + * order the filters are sent.
48 + */
49 const TOOL_LOG_FILTER_FIELDS = [
48 - ['tool', 'action_key'],
49 - ['toolkit', 'toolkit_key'],
50 - ['connectedAccountId', 'connected_account_id'],
51 - ['authConfigId', 'auth_config_id'],
52 - ['status', 'execution_status'],
53 - ['userId', 'user_id'],
54 - ['logId', 'log_id'],
55 - ['toolRouterSessionId', 'tool_router_session_id'],
56 - ['sessionId', 'session_id'],
57 -] as const satisfies ReadonlyArray<readonly [keyof ToolLogFilterInput, string]>;
50 + ['tool', 'tool_slug', '--tool'],
51 + ['toolkit', 'toolkit_slug', '--toolkit'],
52 + ['connectedAccountId', 'connected_account_id', '--connected-account-id'],
53 + ['authConfigId', 'auth_config_id', '--auth-config-id'],
54 + ['status', 'status', '--status'],
55 + ['userId', 'user_id', '--user-id'],
56 + ['logId', 'log_id', '--log-id'],
57 + ['toolRouterSessionId', 'session_id', '--tool-router-session-id'],
58 +] as const satisfies ReadonlyArray<readonly [keyof ToolLogFilterInput, string, string]>;
59
60 /**
60 - * One `==` search param per comma-separated value of each present filter, in
61 - * the order of `TOOL_LOG_FILTER_FIELDS`.
61 + * The flag of the first filter given more than one comma-separated value. The
62 + * public API combines filters with AND, so several values for one field would
63 + * match nothing.
64 */
63 -export const buildToolLogShorthandSearchParams = (
65 +const findMultiValuedFilter = (filters: ToolLogFilterInput): Option.Option<string> =>
66 + Arr.findFirst(TOOL_LOG_FILTER_FIELDS, ([key]) => parseCsv(filters[key] ?? '').length > 1).pipe(
67 + Option.map(([, , flag]) => flag)
68 + );
69 +
70 +/** One equality filter for each present flag, in the order of `TOOL_LOG_FILTER_FIELDS`. */
71 +const buildToolLogFilters = (
72 filters: ToolLogFilterInput
65 -): Array<SearchParam> =>
73 +): NonNullable<LogCreateToolExecutionParams['filters']> =>
74 Arr.flatMap(TOOL_LOG_FILTER_FIELDS, ([key, field]) =>
67 - Option.match(Option.fromUndefinedOr(filters[key]), {
68 - onNone: () => [],
69 - onSome: csv => parseCsv(csv).map(value => toSearchParam(field, value)),
70 - })
75 + parseCsv(filters[key] ?? '').map(value => ({ field, operator: '==' as const, value }))
76 );
77
78 const showToolLog = (toolLogId: string) =>
@@ -76,14 +81,12 @@ const showToolLog = (toolLogId: string) =>
81 const client = yield* (yield* ComposioClientSingleton).get();
82 const toolLog = yield* ui.withSpinner(
83 `Fetching tool log "${toolLogId}"...`,
79 - client._internal.logs.tools
80 - .retrieve(toolLogId, idempotent)
84 + client.logs
85 + .retrieveToolExecution(toolLogId, idempotent)
86 .pipe(failedWith(ToolLogsRequestError, `Failed to fetch tool log "${toolLogId}".`))
87 );
88
84 - yield* ui.log.info(
85 - `${formatToolLogInfo(toolLog)}\n\nPayload:\n${JSON.stringify(toolLog.payloadReceived, null, 2)}\n\nResponse:\n${JSON.stringify(toolLog.response, null, 2)}`
86 - );
89 + yield* ui.log.info(formatToolLogInfo(toolLog));
90 yield* ui.output(JSON.stringify(toolLog, null, 2));
91 });
92
@@ -106,38 +109,67 @@ const listToolLogs = ({
109 Effect.gen(function* () {
110 const userIdFilter = Option.orElse((yield* CommandSurface).userId, () => userId);
111 const ui = yield* TerminalUI;
109 - const client = yield* (yield* ComposioClientSingleton).get();
110 - const searchParams = buildToolLogShorthandSearchParams(
111 - optionalParams({
112 - tool,
113 - toolkit,
114 - connectedAccountId,
115 - authConfigId,
116 - status,
117 - userId: userIdFilter,
118 - logId: logIdFilter,
119 - toolRouterSessionId,
120 - sessionId,
121 - })
122 - );
112 + const now = yield* Clock.currentTimeMillis;
113 + const invalidInput = commandInputError('dev logs tools');
114 + if (caseSensitive) {
115 + return yield* invalidInput(
116 + 'The public tool logs API does not support --case-sensitive. Remove this flag.',
117 + '--case-sensitive'
118 + );
119 + }
120 + if (Option.isSome(sessionId)) {
121 + return yield* invalidInput(
122 + 'The public tool logs API does not support the legacy --session-id filter. Use --tool-router-session-id for a Tool Router session.',
123 + '--session-id'
124 + );
125 + }
126 + const filterInput = optionalParams({
127 + tool,
128 + toolkit,
129 + connectedAccountId,
130 + authConfigId,
131 + status,
132 + userId: userIdFilter,
133 + logId: logIdFilter,
134 + toolRouterSessionId,
135 + });
136 + const multiValuedFlag = findMultiValuedFilter(filterInput);
137 + if (Option.isSome(multiValuedFlag)) {
138 + return yield* invalidInput(
139 + `The public tool logs API matches one value per filter. Pass a single value to ${multiValuedFlag.value}.`,
140 + multiValuedFlag.value
141 + );
142 + }
143 + if (
144 + Option.isSome(status) &&
145 + parseCsv(status.value).some(value => value !== 'success' && value !== 'failed')
146 + ) {
147 + return yield* invalidInput('Use success or failed for --status.', '--status');
148 + }
149 + const timeRange =
150 + Option.isSome(from) || Option.isSome(to)
151 + ? { from: Option.getOrElse(from, () => 0), to: Option.getOrElse(to, () => now) }
152 + : undefined;
153 + const filters = buildToolLogFilters(filterInput);
154
155 + const client = yield* (yield* ComposioClientSingleton).get();
156 + // The client names this read-only search POST createToolExecution.
157 const response = yield* ui.withSpinner(
158 'Fetching tool logs...',
126 - client._internal.logs.tools
127 - .list(
159 + client.logs
160 + .createToolExecution(
161 {
129 - ...optionalParams({ from, to }),
162 + time_range: timeRange,
163 cursor: Option.getOrNull(cursor),
131 - limit: clampLimit(limit),
132 - case_sensitive: caseSensitive,
133 - search_params: nonEmptyOrUndefined(searchParams),
164 + limit: Math.max(1, Math.min(100, limit)),
165 + filters: nonEmptyOrUndefined(filters),
166 },
167 idempotent
168 )
169 .pipe(failedWith(ToolLogsRequestError, 'Failed to fetch tool logs.'))
170 );
171
140 - yield* Arr.match(response.data ?? [], {
172 + yield* Arr.match(response.logs ?? [], {
173 onEmpty: () => ui.log.warn('No tool logs found for the given filters.'),
174 onNonEmpty: logs =>
175 Effect.gen(function* () {
@@ -154,8 +186,8 @@ const listToolLogs = ({
186 );
187 }
188
157 - if (response.nextCursor !== null && response.nextCursor !== undefined) {
158 - yield* ui.log.step(`Next cursor: ${response.nextCursor}`);
189 + if (response.next_cursor !== null && response.next_cursor !== undefined) {
190 + yield* ui.log.step(`Next cursor: ${response.next_cursor}`);
191 }
192 }),
193 });
ts/packages/cli/src/effects/request-error.ts
+1 -1
@@ -28,7 +28,7 @@ export const requestError = <Tag extends string>(
28 *
29 * @example
30 * ```ts
31 - * client._internal.logs.tools.list(query, idempotent).pipe(failedWith(ToolLogsRequestError, 'Failed to fetch tool logs.'))
31 + * client.logs.createToolExecution(body, idempotent).pipe(failedWith(ToolLogsRequestError, 'Failed to fetch tool logs.'))
32 * ```
33 */
34 export const failedWith =
ts/packages/cli/test/src/commands/logs/format.test.ts
+48 -21
@@ -1,4 +1,7 @@
1 -import type { ToolListResponse, ToolRetrieveResponse } from '@composio/client/resources/_internal/logs';
1 +import type {
2 + LogCreateToolExecutionResponse,
3 + LogRetrieveToolExecutionResponse,
4 +} from '@composio/client/resources/logs';
5 import { describe, expect, it } from 'vitest';
6 import {
7 formatTriggerLogInfo,
@@ -12,8 +15,8 @@ import {
15 } from 'src/commands/logs/trigger-log-record';
16 import { green, red } from 'src/ui/colors';
17
15 -type ToolLog = ToolListResponse['data'][number];
16 -type ToolLogDetailed = ToolRetrieveResponse;
18 +type ToolLog = LogCreateToolExecutionResponse['logs'][number];
19 +type ToolLogDetailed = LogRetrieveToolExecutionResponse;
20
21 const makeTriggerLog = (createdAt: string | number): TriggerLogRecord =>
22 decodeTriggerLogRecord({
@@ -33,37 +36,46 @@ const makeTriggerLog = (createdAt: string | number): TriggerLogRecord =>
36 });
37
38 const makeToolLog = (
36 - createdAt: ToolLog['createdAt'] | null,
39 + createdAt: number | string | null,
40 overrides: {
41 status?: string;
42 connectedAccountId?: string | null;
43 + metrics?: Record<string, unknown>;
44 } = {}
45 ): ToolLog =>
46 ({
47 id: 'tool_log_1',
44 - createdAt,
48 + type: 'tool.execution',
49 + level: 'info',
50 + parent: null,
51 + timestamp: typeof createdAt === 'number' ? new Date(createdAt).toISOString() : createdAt,
52 status: overrides.status ?? 'success',
46 - app: { name: 'gmail' },
47 - actionKey: 'GMAIL_SEND_EMAIL',
48 - executionTime: 20,
49 - connectedAccountId:
50 - overrides.connectedAccountId === undefined ? 'conn_123' : overrides.connectedAccountId,
53 + metadata: {
54 + toolkit: { slug: 'gmail' },
55 + tool: { slug: 'GMAIL_SEND_EMAIL' },
56 + connected_account_id:
57 + overrides.connectedAccountId === undefined ? 'conn_123' : overrides.connectedAccountId,
58 + },
59 + metrics: overrides.metrics ?? { duration_ms: 20 },
60 }) as ToolLog;
61
62 const makeToolLogDetailed = (
54 - overrides: Partial<{ startTime: number | null; endTime: number | null }> = {}
63 + overrides: Partial<{
64 + startTime: number | null;
65 + endTime: number | null;
66 + metrics: Record<string, unknown>;
67 + }> = {}
68 ): ToolLogDetailed =>
69 ({
57 - actionLogId: 'tool_log_1',
58 - actionId: 'GMAIL_SEND_EMAIL',
70 + id: 'tool_log_1',
71 status: 'success',
60 - app: null,
61 - connection: null,
62 - startTime: overrides.startTime === undefined ? 0 : overrides.startTime,
63 - endTime: overrides.endTime === undefined ? 0 : overrides.endTime,
64 - totalDuration: '20ms',
65 - version: '20260101_00',
66 - steps: null,
72 + metadata: {},
73 + timings: {
74 + start_time: overrides.startTime === undefined ? 0 : overrides.startTime,
75 + end_time: overrides.endTime === undefined ? 0 : overrides.endTime,
76 + },
77 + metrics: overrides.metrics ?? { duration_ms: 20 },
78 + data: {},
79 }) as unknown as ToolLogDetailed;
80
81 describe('formatTriggerLogsTable', () => {
@@ -128,6 +140,16 @@ describe('formatToolLogsTable', () => {
140 expect(output).toContain(red('failed '.padEnd(8)));
141 });
142
143 + it.each([
144 + { metrics: { duration_ms: 20 }, expected: '20ms' },
145 + { metrics: {}, expected: '-' },
146 + ])('[Given] metrics $metrics [Then] Exec Time is $expected', ({ metrics, expected }) => {
147 + const [header, row] = stripAnsi(formatToolLogsTable([makeToolLog(0, { metrics })])).split('\n');
148 + const column = header.indexOf('Exec Time');
149 +
150 + expect(row.slice(column, column + 12).trim()).toBe(expected);
151 + });
152 +
153 it('[Given] null connected account [Then] it renders dash', () => {
154 const output = stripAnsi(formatToolLogsTable([makeToolLog(0, { connectedAccountId: null })]));
155 const [, rowLine] = output.split('\n');
@@ -145,7 +167,7 @@ describe('formatToolLogInfo', () => {
167 expect(plain).toContain('toolkit: -');
168 expect(plain).toContain('Connection ID: -');
169 expect(plain).toContain('Entity: -');
148 - expect(plain).toContain('Steps: 0');
170 + expect(plain).toContain('Version: -');
171 });
172
173 it('[Given] null start/end time [Then] it renders dashes for timestamps', () => {
@@ -155,6 +177,11 @@ describe('formatToolLogInfo', () => {
177 expect(plain).toContain('End Time: -');
178 expect(plain).not.toContain('1970-01-01T00:00:00.000Z');
179 });
180 +
181 + it('[Given] no recorded duration [Then] it renders a dash', () => {
182 + const plain = stripAnsi(formatToolLogInfo(makeToolLogDetailed({ metrics: {} })));
183 + expect(plain).toContain('Total Duration: -');
184 + });
185 });
186
187 describe('formatTriggerLogInfo', () => {
ts/packages/cli/test/src/commands/logs/tools/logs.tools.client.cmd.test.ts
+95 -174
@@ -3,192 +3,113 @@ import { Cause, ConfigProvider, Effect, Exit } from 'effect';
3 import { extractErrorDetails } from 'src/effect-errors/logic/errors/extract-error-details';
4 import { cli, MockConsole, TestLive } from 'test/__utils__';
5 import { stubClientResources } from 'test/__utils__/services/stub-composio-client';
6 +import { detail, log } from './logs.tools.fixtures';
7
8 const testLayer = TestLive({
9 baseConfigProvider: ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } }),
10 fixture: 'global-test-user-id',
11 });
12
12 -const page = {
13 - data: [
14 - {
15 - id: 'log_send_1',
16 - actionKey: 'GMAIL_SEND_EMAIL',
17 - appKey: 'gmail',
18 - app: { icon: 'https://logos.composio.dev/gmail', name: 'Gmail' },
19 - connectedAccountId: 'ca_gmail_1',
20 - entityId: 'user_1',
21 - status: 'success',
22 - executionTime: 412,
23 - minimalResponse: '{"id":"msg_1"}',
24 - createdAt: 1767225600000,
25 - },
26 - {
27 - id: 'log_fetch_2',
28 - actionKey: 'GMAIL_FETCH_EMAILS',
29 - appKey: 'gmail',
30 - app: { icon: 'https://logos.composio.dev/gmail', name: 'Gmail' },
31 - connectedAccountId: 'ca_gmail_1',
32 - entityId: 'user_1',
33 - status: 'failed',
34 - executionTime: 97,
35 - minimalResponse: '{"error":"quota"}',
36 - createdAt: 1767225660000,
37 - },
38 - ],
39 - nextCursor: null,
40 -};
41 -
42 -describe('CLI: composio dev logs tools over the API client', () => {
43 - layer(testLayer)('[Given] a page of tool logs', it => {
44 - it.effect('[Then] the logs are listed as a table and printed as the API returned them', () =>
45 - Effect.gen(function* () {
46 - const stub = stubClientResources(['_internal'], () => Response.json(page));
47 - yield* cli(['dev', 'logs', 'tools', '--toolkit', 'gmail']).pipe(Effect.provide(stub.layer));
48 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
49 -
50 - expect(lines).toEqual([
51 - 'Fetching tool logs...',
52 - [
53 - 'Listing 2 tool logs',
54 - '',
55 - 'Created At Log Id Status Toolkit Tool Exec Time Connected Account',
56 - '2026-01-01T00:00:00.000Z log_send_1 success Gmail GMAIL_SEND_EMAIL 412ms ca_gmail_1',
57 - '2026-01-01T00:01:00.000Z log_fetch_2 failed Gmail GMAIL_FETCH_EMAILS 97ms ca_gmail_1',
58 - ].join('\n'),
59 - 'To view full details for a log:\n> composio dev logs tools "log_send_1"',
60 - JSON.stringify(page, null, 2),
61 - ]);
62 - expect(stub.requests).toEqual([
63 - {
64 - method: 'POST',
65 - path: '/api/v3.1/internal/action_execution/logs',
66 - body: {
67 - cursor: null,
68 - limit: 30,
69 - case_sensitive: false,
70 - search_params: [{ field: 'toolkit_key', operation: '==', value: 'gmail' }],
71 - },
72 - },
73 - ]);
74 - })
75 - );
76 - });
77 -
78 - layer(testLayer)('[Given] a comma-separated --user-id filter', it => {
79 - it.effect.each([
80 - {
81 - name: 'after the subcommand',
82 - args: ['dev', 'logs', 'tools', '--user-id', 'user_1,user_2'],
83 - },
84 - {
85 - name: 'before the subcommand',
86 - args: ['dev', '--user-id', 'user_1,user_2', 'logs', 'tools'],
87 - },
88 - ])('[Then] each user id is sent as a search param when passed $name', ({ args }) =>
89 - Effect.gen(function* () {
90 - const stub = stubClientResources(['_internal'], () => Response.json({ data: [] }));
91 - yield* cli(args).pipe(Effect.provide(stub.layer));
92 -
93 - expect(stub.requests).toMatchObject([
94 - {
95 - body: {
96 - search_params: [
97 - { field: 'user_id', operation: '==', value: 'user_1' },
98 - { field: 'user_id', operation: '==', value: 'user_2' },
99 - ],
100 - },
101 - },
102 - ]);
103 - })
13 +describe('CLI: public tool logs over the API client', () => {
14 + layer(testLayer)(it => {
15 + it.effect(
16 + '[Given] unified logs [Then] renders public metadata and preserves the response on stdout',
17 + () =>
18 + Effect.gen(function* () {
19 + const stdoutBefore = (yield* MockConsole.getLines({ stream: 'stdout' })).length;
20 + const page = { logs: [log], next_cursor: null };
21 + const stub = stubClientResources(['logs'], () => Response.json(page));
22 + yield* cli(['dev', 'logs', 'tools']).pipe(Effect.provide(stub.layer));
23 + const stderr = (yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).join(
24 + '\n'
25 + );
26 + expect(stderr).toContain('2026-01-01T00:00:00.000Z log_send_1');
27 + expect(stderr).toContain('gmail');
28 + expect(stderr).toContain('GMAIL_SEND_EMAIL');
29 + expect(stderr).toContain('412ms');
30 + expect(stderr).toContain('ca_gmail_1');
31 + expect((yield* MockConsole.getLines({ stream: 'stdout' })).slice(stdoutBefore)).toEqual([
32 + JSON.stringify(page, null, 2),
33 + ]);
34 + })
35 );
105 - });
106 -
107 - layer(testLayer)('[Given] the API rejects the request', it => {
108 - it.effect('[Then] the command fails with the status and response body as the cause', () =>
109 - Effect.gen(function* () {
110 - const stub = stubClientResources(['_internal'], () =>
111 - Response.json(
112 - { error: { message: 'Not allowed', code: 1403, slug: 'Forbidden', status: 403 } },
113 - { status: 403 }
114 - )
115 - );
116 - const exit = yield* cli(['dev', 'logs', 'tools']).pipe(
117 - Effect.provide(stub.layer),
118 - Effect.exit
119 - );
120 - const failure = Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
36
122 - expect(failure).toMatchObject({ _tag: 'commands/ToolLogsRequestError' });
123 - expect(extractErrorDetails(failure).message).toBe(
124 - 'Failed to fetch tool logs.\nCaused by: 403 {"error":{"message":"Not allowed","code":1403,"slug":"Forbidden","status":403}}'
125 - );
126 - })
37 + it.effect(
38 + '[Given] one log id [Then] retrieves public detail and shows its request and response',
39 + () =>
40 + Effect.gen(function* () {
41 + const stdoutBefore = (yield* MockConsole.getLines({ stream: 'stdout' })).length;
42 + const stub = stubClientResources(['logs'], () => Response.json(detail));
43 + yield* cli(['dev', 'logs', 'tools', log.id]).pipe(Effect.provide(stub.layer));
44 + expect(stub.requests).toEqual([
45 + { method: 'GET', path: '/api/v3.1/logs/tool_execution/log_send_1' },
46 + ]);
47 + const stderr = (yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).join(
48 + '\n'
49 + );
50 + expect(stderr).toContain('toolSlug: GMAIL_SEND_EMAIL');
51 + expect(stderr).toContain('Payload:\n{\n "to": "a@b.c"\n}');
52 + expect(stderr).toContain('Response:\n{\n "id": "msg_1"\n}');
53 + expect((yield* MockConsole.getLines({ stream: 'stdout' })).slice(stdoutBefore)).toEqual([
54 + JSON.stringify(detail, null, 2),
55 + ]);
56 + })
57 );
128 - });
129 -
130 - layer(testLayer)('[Given] a page with a log in a shape the API contract does not allow', it => {
131 - it.effect('[Then] the log is listed with dashes for what it lacks', () =>
132 - Effect.gen(function* () {
133 - // A null status, a missing connected account, a missing execution
134 - // time, and no `nextCursor`: the response schema the client ships
135 - // allows none of that, while the table renders each as a dash.
136 - const driftedPage = {
137 - data: [
138 - {
139 - id: 'log_drift_1',
140 - actionKey: 'GMAIL_SEND_EMAIL',
141 - appKey: 'gmail',
142 - app: { icon: null, name: 'Gmail' },
143 - connectedAccountId: null,
144 - entityId: 'user_1',
145 - status: null,
146 - createdAt: 1767225600000,
147 - },
148 - ],
149 - };
150 - const stub = stubClientResources(['_internal'], () => Response.json(driftedPage));
151 - yield* cli(['dev', 'logs', 'tools']).pipe(Effect.provide(stub.layer));
152 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
58
154 - expect(lines[1]).toBe(
155 - [
156 - 'Listing 1 tool log',
157 - '',
158 - 'Created At Log Id Status Toolkit Tool Exec Time Connected Account',
159 - '2026-01-01T00:00:00.000Z log_drift_1 - Gmail GMAIL_SEND_EMAIL 0ms -',
160 - ].join('\n')
161 - );
162 - expect(lines.at(-1)).toBe(JSON.stringify(driftedPage, null, 2));
163 - })
59 + it.effect(
60 + '[Given] drifted metadata and status [Then] keeps tolerant rendering without client decoding',
61 + () =>
62 + Effect.gen(function* () {
63 + const stdoutBefore = (yield* MockConsole.getLines({ stream: 'stdout' })).length;
64 + const drifted = {
65 + logs: [
66 + {
67 + id: 'log_drift',
68 + timestamp: log.timestamp,
69 + status: null,
70 + metadata: {
71 + toolkit: null,
72 + tool: { slug: 'GMAIL_SEND_EMAIL' },
73 + connected_account_id: null,
74 + },
75 + metrics: {},
76 + },
77 + ],
78 + };
79 + const stub = stubClientResources(['logs'], () => Response.json(drifted));
80 + yield* cli(['dev', 'logs', 'tools']).pipe(Effect.provide(stub.layer));
81 + const stderr = (yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).join(
82 + '\n'
83 + );
84 + expect(stderr).toContain('log_drift');
85 + expect(stderr).toContain('GMAIL_SEND_EMAIL');
86 + expect(stderr).not.toContain('0ms');
87 + expect((yield* MockConsole.getLines({ stream: 'stdout' })).slice(stdoutBefore)).toEqual([
88 + JSON.stringify(drifted, null, 2),
89 + ]);
90 + })
91 );
165 - });
166 -
167 - layer(testLayer)('[Given] one tool log in a shape the API contract does not allow', it => {
168 - it.effect('[Then] its details are shown and it is printed as the API returned it', () =>
169 - Effect.gen(function* () {
170 - const driftedLog = {
171 - id: 'log_drift_1',
172 - actionKey: 'GMAIL_SEND_EMAIL',
173 - appKey: 'gmail',
174 - app: { icon: null, name: 'Gmail' },
175 - connectedAccountId: null,
176 - entityId: 'user_1',
177 - status: null,
178 - createdAt: 1767225600000,
179 - payloadReceived: { recipient_email: 'a@b.c' },
180 - response: { id: 'msg_1' },
181 - };
182 - const stub = stubClientResources(['_internal'], () => Response.json(driftedLog));
183 - yield* cli(['dev', 'logs', 'tools', 'log_drift_1']).pipe(Effect.provide(stub.layer));
184 - const lines = yield* MockConsole.getLines({ stripAnsi: true });
92
186 - expect(lines.join('\n')).toContain('GMAIL_SEND_EMAIL');
187 - expect(lines.at(-1)).toBe(JSON.stringify(driftedLog, null, 2));
188 - expect(stub.requests).toEqual([
189 - { method: 'GET', path: '/api/v3.1/internal/action_execution/log/log_drift_1' },
190 - ]);
191 - })
93 + it.effect.each([
94 + { args: [], status: 403, message: 'Failed to fetch tool logs.' },
95 + { args: ['log_missing'], status: 404, message: 'Failed to fetch tool log "log_missing".' },
96 + ])(
97 + '[Given] an API error [Then] preserves the error and command context',
98 + ({ args, status, message }) =>
99 + Effect.gen(function* () {
100 + const stub = stubClientResources(['logs'], () =>
101 + Response.json({ error: { message: 'Not allowed' } }, { status })
102 + );
103 + const exit = yield* cli(['dev', 'logs', 'tools', ...args]).pipe(
104 + Effect.provide(stub.layer),
105 + Effect.exit
106 + );
107 + const failure = Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
108 + expect(failure).toMatchObject({ _tag: 'commands/ToolLogsRequestError', message });
109 + expect(extractErrorDetails(failure).message).toContain(
110 + `${status} {"error":{"message":"Not allowed"}}`
111 + );
112 + })
113 );
114 });
115 });
ts/packages/cli/test/src/commands/logs/tools/logs.tools.cmd.test.ts
+108 -172
@@ -1,115 +1,32 @@
1 -import { describe, expect, it, layer } from '@effect/vitest';
1 +import { describe, expect, layer } from '@effect/vitest';
2 import { ConfigProvider, Effect } from 'effect';
3 -import { buildToolLogShorthandSearchParams } from 'src/commands/logs/tools/logs.tools.handler';
3 +import { TestClock } from 'effect/testing';
4 import { cli, MockConsole, TestLive } from 'test/__utils__';
5 import { stubClientResources } from 'test/__utils__/services/stub-composio-client';
6 +import { log } from './logs.tools.fixtures';
7
8 const testLayer = TestLive({
9 baseConfigProvider: ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } }),
10 fixture: 'global-test-user-id',
11 });
12
12 -const log = {
13 - id: 'log_1',
14 - actionKey: 'GMAIL_SEND_EMAIL',
15 - appKey: 'gmail',
16 - app: { icon: 'https://logos.composio.dev/gmail', name: 'Gmail' },
17 - connectedAccountId: 'ca_gmail_1',
18 - entityId: 'user_1',
19 - status: 'success',
20 - executionTime: 412,
21 - minimalResponse: '{"id":"msg_1"}',
22 - createdAt: 1767225600000,
23 -};
24 -
25 -describe('buildToolLogShorthandSearchParams', () => {
26 - it('[Given] no filters [Then] returns empty search params', () => {
27 - expect(buildToolLogShorthandSearchParams({})).toEqual([]);
28 - });
29 -
30 - it('[Given] all supported filters [Then] maps each one to the expected backend key', () => {
31 - const output = buildToolLogShorthandSearchParams({
32 - tool: 'GMAIL_SEND_EMAIL',
33 - toolkit: 'gmail',
34 - connectedAccountId: 'ca_123',
35 - authConfigId: 'ac_123',
36 - status: 'success',
37 - userId: 'user_123',
38 - logId: 'log_123',
39 - toolRouterSessionId: 'trs_123',
40 - sessionId: 'sess_123',
41 - });
42 -
43 - expect(output).toEqual([
44 - { field: 'action_key', operation: '==', value: 'GMAIL_SEND_EMAIL' },
45 - { field: 'toolkit_key', operation: '==', value: 'gmail' },
46 - { field: 'connected_account_id', operation: '==', value: 'ca_123' },
47 - { field: 'auth_config_id', operation: '==', value: 'ac_123' },
48 - { field: 'execution_status', operation: '==', value: 'success' },
49 - { field: 'user_id', operation: '==', value: 'user_123' },
50 - { field: 'log_id', operation: '==', value: 'log_123' },
51 - { field: 'tool_router_session_id', operation: '==', value: 'trs_123' },
52 - { field: 'session_id', operation: '==', value: 'sess_123' },
53 - ]);
54 - });
55 -
56 - it('[Given] comma-separated filter values [Then] expands each value into separate search params', () => {
57 - const output = buildToolLogShorthandSearchParams({
58 - tool: 'GMAIL_SEND_EMAIL,SLACK_SEND_MESSAGE',
59 - toolkit: 'gmail,slack',
60 - status: 'success,failed',
61 - logId: 'log_1,log_2',
62 - });
63 -
64 - expect(output).toEqual([
65 - { field: 'action_key', operation: '==', value: 'GMAIL_SEND_EMAIL' },
66 - { field: 'action_key', operation: '==', value: 'SLACK_SEND_MESSAGE' },
67 - { field: 'toolkit_key', operation: '==', value: 'gmail' },
68 - { field: 'toolkit_key', operation: '==', value: 'slack' },
69 - { field: 'execution_status', operation: '==', value: 'success' },
70 - { field: 'execution_status', operation: '==', value: 'failed' },
71 - { field: 'log_id', operation: '==', value: 'log_1' },
72 - { field: 'log_id', operation: '==', value: 'log_2' },
73 - ]);
74 - });
75 -});
76 -
13 describe('CLI: composio dev logs tools', () => {
78 - layer(testLayer)('[Given] no filters and no logs', it => {
79 - it.effect('[Then] it warns and prints the empty page as the API returned it', () =>
80 - Effect.gen(function* () {
81 - const page = { data: [], nextCursor: null };
82 - const stub = stubClientResources(['_internal'], () => Response.json(page));
83 - yield* cli(['dev', 'logs', 'tools']).pipe(Effect.provide(stub.layer));
84 - const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
85 - const stdout = yield* MockConsole.getLines({ stream: 'stdout' });
86 -
87 - expect(stderr.join('\n')).toContain('No tool logs found for the given filters.');
88 - expect(stdout).toEqual([JSON.stringify(page, null, 2)]);
89 - expect(stub.requests).toMatchObject([
90 - { method: 'POST', body: { cursor: null, limit: 30, case_sensitive: false } },
91 - ]);
92 - expect(stub.requests[0]?.body).not.toHaveProperty('search_params');
93 - })
94 - );
95 - });
96 -
97 - layer(testLayer)('[Given] every filter flag', it => {
14 + layer(testLayer)(it => {
15 it.effect(
99 - '[Then] each is sent as search params in a fixed order and the limit is clamped',
16 + '[Given] every supported filter [Then] searches the public API with at most 100 results',
17 () =>
18 Effect.gen(function* () {
102 - const stub = stubClientResources(['_internal'], () => Response.json({ data: [] }));
19 + const stub = stubClientResources(['logs'], () =>
20 + Response.json({ logs: [], next_cursor: null })
21 + );
22 yield* cli([
23 'dev',
24 'logs',
25 'tools',
107 - '--session-id',
108 - 'sess_1',
26 '--tool-router-session-id',
27 'trs_1',
28 '--log-id',
112 - 'log_a,log_b',
29 + 'log_a',
30 '--user-id',
31 'user_1',
32 '--status',
@@ -119,7 +36,7 @@ describe('CLI: composio dev logs tools', () => {
36 '--connected-account-id',
37 'ca_1',
38 '--toolkit',
122 - 'gmail,slack',
39 + 'gmail',
40 '--tool',
41 'GMAIL_SEND_EMAIL',
42 '--cursor',
@@ -130,114 +47,133 @@ describe('CLI: composio dev logs tools', () => {
47 '2',
48 '--limit',
49 '5000',
133 - '--case-sensitive',
50 ]).pipe(Effect.provide(stub.layer));
135 -
51 expect(stub.requests).toEqual([
52 {
53 method: 'POST',
139 - path: '/api/v3.1/internal/action_execution/logs',
54 + path: '/api/v3.1/logs/tool_execution',
55 body: {
141 - from: 1,
142 - to: 2,
143 - cursor: 7,
144 - limit: 1000,
145 - case_sensitive: true,
146 - search_params: [
147 - { field: 'action_key', operation: '==', value: 'GMAIL_SEND_EMAIL' },
148 - { field: 'toolkit_key', operation: '==', value: 'gmail' },
149 - { field: 'toolkit_key', operation: '==', value: 'slack' },
150 - { field: 'connected_account_id', operation: '==', value: 'ca_1' },
151 - { field: 'auth_config_id', operation: '==', value: 'ac_1' },
152 - { field: 'execution_status', operation: '==', value: 'failed' },
153 - { field: 'user_id', operation: '==', value: 'user_1' },
154 - { field: 'log_id', operation: '==', value: 'log_a' },
155 - { field: 'log_id', operation: '==', value: 'log_b' },
156 - { field: 'tool_router_session_id', operation: '==', value: 'trs_1' },
157 - { field: 'session_id', operation: '==', value: 'sess_1' },
56 + cursor: '7',
57 + limit: 100,
58 + time_range: { from: 1, to: 2 },
59 + filters: [
60 + { field: 'tool_slug', operator: '==', value: 'GMAIL_SEND_EMAIL' },
61 + { field: 'toolkit_slug', operator: '==', value: 'gmail' },
62 + { field: 'connected_account_id', operator: '==', value: 'ca_1' },
63 + { field: 'auth_config_id', operator: '==', value: 'ac_1' },
64 + { field: 'status', operator: '==', value: 'failed' },
65 + { field: 'user_id', operator: '==', value: 'user_1' },
66 + { field: 'log_id', operator: '==', value: 'log_a' },
67 + { field: 'session_id', operator: '==', value: 'trs_1' },
68 ],
69 },
70 },
71 ]);
72 })
73 );
164 - });
74
166 - layer(testLayer)('[Given] a page with a next cursor', it => {
167 - it.effect('[Then] it lists the logs, hints at the first one, and prints the cursor', () =>
75 + it.effect.each([
76 + { args: ['--limit', '0'], expected: { limit: 1 } },
77 + { args: ['--from', '10'], expected: { time_range: { from: 10, to: 1000 } } },
78 + { args: ['--to', '20'], expected: { time_range: { from: 0, to: 20 } } },
79 + ])('[Given] $args [Then] builds a bounded public request', ({ args, expected }) =>
80 Effect.gen(function* () {
169 - const page = { data: [log], nextCursor: 42 };
170 - const stub = stubClientResources(['_internal'], () => Response.json(page));
171 - yield* cli(['dev', 'logs', 'tools']).pipe(Effect.provide(stub.layer));
172 - const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
173 - const stdout = yield* MockConsole.getLines({ stream: 'stdout' });
174 -
175 - expect(stderr.join('\n')).toContain('Listing 1 tool log\n');
176 - expect(stderr).toContain(
177 - 'To view full details for a log:\n> composio dev logs tools "log_1"'
178 - );
179 - expect(stderr).toContain('Next cursor: 42');
180 - expect(stdout).toEqual([JSON.stringify(page, null, 2)]);
81 + yield* TestClock.setTime(1000);
82 + const stub = stubClientResources(['logs'], () => Response.json({ logs: [] }));
83 + yield* cli(['dev', 'logs', 'tools', ...args]).pipe(Effect.provide(stub.layer));
84 + expect(stub.requests[0]?.body).toMatchObject(expected);
85 })
86 );
183 - });
184 -
185 - layer(testLayer)('[Given] a log id argument', it => {
186 - it.effect('[Then] it fetches that log alone and prints it as the API returned it', () =>
187 - Effect.gen(function* () {
188 - const toolLog = { ...log, payloadReceived: { to: 'a@b.c' }, response: { id: 'msg_1' } };
189 - const stub = stubClientResources(['_internal'], () => Response.json(toolLog));
190 - yield* cli(['dev', 'logs', 'tools', 'log_1']).pipe(Effect.provide(stub.layer));
191 - const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
192 - const stdout = yield* MockConsole.getLines({ stream: 'stdout' });
87
194 - expect(stub.requests).toEqual([
195 - { method: 'GET', path: '/api/v3.1/internal/action_execution/log/log_1' },
196 - ]);
197 - expect(stderr.join('\n')).toContain('Payload:\n{\n "to": "a@b.c"\n}');
198 - expect(stdout).toEqual([JSON.stringify(toolLog, null, 2)]);
199 - })
88 + it.effect.each([
89 + { args: ['dev', 'logs', 'tools', '--user-id', 'user_1'] },
90 + { args: ['dev', '--user-id', 'user_1', 'logs', 'tools'] },
91 + ])(
92 + '[Given] a shared user filter at either position [Then] includes the user in the public filters',
93 + ({ args }) =>
94 + Effect.gen(function* () {
95 + const stub = stubClientResources(['logs'], () => Response.json({ logs: [] }));
96 + yield* cli(args).pipe(Effect.provide(stub.layer));
97 + expect(stub.requests[0]?.body).toMatchObject({
98 + filters: [{ field: 'user_id', operator: '==', value: 'user_1' }],
99 + });
100 + })
101 );
201 - });
102
203 - layer(testLayer)('[Given] an empty log id argument', it => {
204 - it.effect('[Then] it lists logs instead of fetching one', () =>
205 - Effect.gen(function* () {
206 - const stub = stubClientResources(['_internal'], () => Response.json({ data: [] }));
207 - yield* cli(['dev', 'logs', 'tools', '']).pipe(Effect.provide(stub.layer));
103 + it.effect.each([
104 + { args: ['--case-sensitive'], option: '--case-sensitive' },
105 + { args: ['--session-id', 'cli_session'], option: '--session-id' },
106 + { args: ['--status', 'unknown'], option: '--status' },
107 + { args: ['--status', 'success,failed'], option: '--status' },
108 + { args: ['--toolkit', 'gmail,slack'], option: '--toolkit' },
109 + { args: ['--log-id', 'log_a,log_b'], option: '--log-id' },
110 + { args: ['--user-id', 'user_1,user_2'], option: '--user-id' },
111 + ])(
112 + '[Given] $args [Then] rejects unsupported filtering before requesting logs',
113 + ({ args, option }) =>
114 + Effect.gen(function* () {
115 + const stub = stubClientResources(['logs'], () => Response.json({ logs: [] }));
116 + const failure = yield* cli(['dev', 'logs', 'tools', ...args]).pipe(
117 + Effect.provide(stub.layer),
118 + Effect.flip
119 + );
120 + expect(failure).toMatchObject({ _tag: 'commands/CommandInputError', option });
121 + expect(stub.requests).toEqual([]);
122 + })
123 + );
124
209 - expect(stub.requests).toMatchObject([{ method: 'POST' }]);
210 - })
125 + it.effect(
126 + '[Given] an empty public page [Then] warns on stderr and returns the page on stdout',
127 + () =>
128 + Effect.gen(function* () {
129 + const stdoutBefore = (yield* MockConsole.getLines({ stream: 'stdout' })).length;
130 + const page = { logs: [], next_cursor: null };
131 + const stub = stubClientResources(['logs'], () => Response.json(page));
132 + yield* cli(['dev', 'logs', 'tools']).pipe(Effect.provide(stub.layer));
133 + expect(
134 + (yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true })).join('\n')
135 + ).toContain('No tool logs found for the given filters.');
136 + expect((yield* MockConsole.getLines({ stream: 'stdout' })).slice(stdoutBefore)).toEqual([
137 + JSON.stringify(page, null, 2),
138 + ]);
139 + expect(stub.requests).toEqual([
140 + {
141 + method: 'POST',
142 + path: '/api/v3.1/logs/tool_execution',
143 + body: { cursor: null, limit: 30 },
144 + },
145 + ]);
146 + })
147 );
212 - });
148
214 - layer(testLayer)('[Given] the API rejects the request for one log', it => {
215 - it.effect('[Then] the failure names the log id', () =>
149 + it.effect('[Given] a page cursor [Then] displays it and sends it back unchanged', () =>
150 Effect.gen(function* () {
217 - const stub = stubClientResources(['_internal'], () =>
218 - Response.json(
219 - { error: { message: 'Not found', code: 1404, slug: 'Not_Found', status: 404 } },
220 - { status: 404 }
221 - )
151 + const stdoutBefore = (yield* MockConsole.getLines({ stream: 'stdout' })).length;
152 + const page = { logs: [log], next_cursor: '1767225600000' };
153 + const stub = stubClientResources(['logs'], () => Response.json(page));
154 + yield* cli(['dev', 'logs', 'tools']).pipe(Effect.provide(stub.layer));
155 + const stderr = yield* MockConsole.getLines({ stream: 'stderr', stripAnsi: true });
156 + expect(stderr).toContain('Next cursor: 1767225600000');
157 + expect(stderr).toContain(
158 + 'To view full details for a log:\n> composio dev logs tools "log_send_1"'
159 );
223 - const failure = yield* cli(['dev', 'logs', 'tools', 'log_missing']).pipe(
224 - Effect.provide(stub.layer),
225 - Effect.flip
160 + expect((yield* MockConsole.getLines({ stream: 'stdout' })).slice(stdoutBefore)).toEqual([
161 + JSON.stringify(page, null, 2),
162 + ]);
163 + yield* cli(['dev', 'logs', 'tools', '--cursor', page.next_cursor]).pipe(
164 + Effect.provide(stub.layer)
165 );
227 -
228 - expect(failure).toMatchObject({
229 - _tag: 'commands/ToolLogsRequestError',
230 - message: 'Failed to fetch tool log "log_missing".',
231 - });
166 + expect(stub.requests[1]?.body).toMatchObject({ cursor: page.next_cursor });
167 })
168 );
169 });
170
236 - layer(TestLive())('[Given] no API key', it => {
237 - it.effect('[Then] it fails with NotLoggedInError', () =>
171 + layer(TestLive())(it => {
172 + it.effect('[Given] no API key [Then] fails with NotLoggedInError', () =>
173 Effect.gen(function* () {
239 - const error = yield* cli(['dev', 'logs', 'tools']).pipe(Effect.flip);
240 - expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
174 + expect(yield* cli(['dev', 'logs', 'tools']).pipe(Effect.flip)).toMatchObject({
175 + _tag: 'commands/NotLoggedInError',
176 + });
177 })
178 );
179 });
ts/packages/cli/test/src/commands/logs/tools/logs.tools.fixtures.ts new
+29
@@ -0,0 +1,29 @@
1 +import type {
2 + LogCreateToolExecutionResponse,
3 + LogRetrieveToolExecutionResponse,
4 +} from '@composio/client/resources/logs';
5 +
6 +export const log = {
7 + id: 'log_send_1',
8 + timestamp: '2026-01-01T00:00:00.000Z',
9 + type: 'tool.execution',
10 + status: 'success',
11 + level: 'info',
12 + metadata: {
13 + toolkit: { slug: 'gmail' },
14 + tool: { slug: 'GMAIL_SEND_EMAIL', version: '20260101_00' },
15 + connected_account_id: 'ca_gmail_1',
16 + user_id: 'user_1',
17 + credential_source: 'connected_account',
18 + },
19 + metrics: { duration_ms: 412 },
20 + parent: null,
21 +} satisfies LogCreateToolExecutionResponse['logs'][number];
22 +
23 +export const detail = {
24 + ...log,
25 + timings: { start_time: 1767225600000, end_time: 1767225600412 },
26 + context: {},
27 + source: {},
28 + data: { request: { payload: { to: 'a@b.c' } }, response: { body: { id: 'msg_1' } } },
29 +} satisfies LogRetrieveToolExecutionResponse;
ts/packages/cli/test/src/commands/request-failures.client.test.ts
+1 -1
@@ -54,7 +54,7 @@ const rejectedRequests: ReadonlyArray<{
54 {
55 command: 'dev logs tools <id>',
56 args: ['dev', 'logs', 'tools', 'log_1'],
57 - resources: ['_internal'],
57 + resources: ['logs'],
58 tag: 'commands/ToolLogsRequestError',
59 message: 'Failed to fetch tool log "log_1".',
60 },