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

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

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

Synced Nov 21, 07:15 UTC

refactor(cli): move `tools execute` into the directory shape (#5140)

This PR: - targets `next`, now that https://github.com/ComposioHQ/composio/pull/5136 has landed there - splits `tools/commands/tools.execute.cmd.ts` (2095 lines) into `tools/execute/`, see the table below. It is a pure move: same strings, flags, error classes, tags, messages, telemetry and exit codes - `execute` and `dev playground-execute` keep two registrations and now pass the same `runToolsExecuteCommand` to `Command.make`. It reads `tree` and `projectName` from `CommandSurface`, which the root tree provides as `root` with both options empty, and the acting user comes from `actingUser()` as before. That gives the same values the two inline handlers hardcoded (`root`/`consumer`/none vs `dev`/`developer`/surface flags) - nothing outside the command imported these helpers (only `index.ts`, `dev.cmd.ts` and tests), so none move to `src/effects` or `src/services` - moves the three execute suites to `test/src/commands/tools/execute/` (only the fixture path and import paths change) and regenerates `COMMANDS.md` - includes the changes #5127 and #5130 (acting user via `actingUser()`) and #5126 made to the old file since this branch was opened, ported into the new files: user resolution in `tools.execute.context.ts`, the narrowed `ToolExecutionError` reasons in `tools.execute.errors.ts`, `setArgumentAt` in `tools.execute.arguments.ts`, and `checkDryRunArguments` in `tools.execute.validation.ts` | Old (`tools/commands/tools.execute.cmd.ts`) | New (`tools/execute/`) | | --- | --- | | flags, examples, both `Command.make` | `tools.execute.cmd.ts` | | shared handler, single-tool run, connection fail-fast, spinner flow | `tools.execute.handler.ts` | | `ToolExecutionError`, `ReportedToolExecutionError`, `invalidArguments` | `tools.execute.errors.ts` | | stdout JSON redaction, hints, success suffix, schema output | `tools.execute.format.ts` | | `-d`/`--file` parsing and injection | `tools.execute.arguments.ts` | | project, user and client resolution | `tools.execute.context.ts` | | dry-run and pre-execute validation | `tools.execute.validation.ts` | | large-response storage | `tools.execute.output.ts` | | failure telemetry and error rendering | `tools.execute.failure.ts` | | `--parallel` parser and runner, `ExecuteInvocationArgs` | `tools.execute.parallel.ts` | | the perf logger (one instance, as before) | `tools.execute.debug.ts` | ## Context Verified: root `pnpm typecheck`; `pnpm --filter @composio/cli run lint:effect` (0 diagnostics); `oxlint ts/packages/cli` (exit 0, no warnings in touched files); `pnpm --filter @composio/cli test`: 222 files, 2893 passed and 1 skipped, the same as the base branch. `validate:boundaries` and `validate:command-tests` pass (57 commands, 0 exemptions). I also compared every top-level declaration, ignoring imports and `export`, against the old file as it is on the base branch. The only differences are the two inline handlers becoming one, prettier line wrapping, and three comment edits: one pointer to "below" removed, "this file" changed to "this command", and a new comment on `perfDebugLog`. --------- Co-authored-by: Vinayak Agarwal <vinayak@composio.dev> Co-authored-by: manobhisriram <manobhisriram@gmail.com>

Alberto Schiabel committed Oct 28, 2026 at 20:12 UTC bf324c50be911e803d2e41ac34ffcd40047bbdfa
19 files changed +2170 -2103
ts/packages/cli/src/commands/COMMANDS.md
+2 -2
@@ -45,7 +45,7 @@ Every command registration of the CLI and the file that defines it. To find a co
45 | `dev logs` | dev | `ts/packages/cli/src/commands/logs/logs.cmd.ts` | | | yes | listed |
46 | `dev logs tools` | dev | `ts/packages/cli/src/commands/logs/tools/logs.tools.cmd.ts` | | | yes | listed |
47 | `dev logs triggers` | dev | `ts/packages/cli/src/commands/logs/triggers/logs.triggers.cmd.ts` | | | yes | listed |
48 -| `dev playground-execute` | dev | `ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts` | | | yes | listed |
48 +| `dev playground-execute` | dev | `ts/packages/cli/src/commands/tools/execute/tools.execute.cmd.ts` | | | yes | listed |
49 | `dev projects` | dev | `ts/packages/cli/src/commands/projects/projects.cmd.ts` | | | no | listed |
50 | `dev projects list` | dev | `ts/packages/cli/src/commands/projects/list/projects.list.cmd.ts` | | | yes | listed |
51 | `dev projects switch` | dev | `ts/packages/cli/src/commands/projects/switch/projects.switch.cmd.ts` | | | no | listed |
@@ -62,7 +62,7 @@ Every command registration of the CLI and the file that defines it. To find a co
62 | `dev triggers list` | dev | `ts/packages/cli/src/commands/triggers/list/triggers.list.cmd.ts` | | `triggers list` | yes | listed |
63 | `dev triggers listen` | dev | `ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts` | | `dev listen` | yes | listed |
64 | `dev triggers status` | dev | `ts/packages/cli/src/commands/triggers/status/triggers.status.cmd.ts` | | | yes | listed |
65 -| `execute` | root | `ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts` | | | yes | listed |
65 +| `execute` | root | `ts/packages/cli/src/commands/tools/execute/tools.execute.cmd.ts` | | | yes | listed |
66 | `generate` | root | `ts/packages/cli/src/commands/generate/generate.cmd.ts` | | | no | listed |
67 | `generate py` | root | `ts/packages/cli/src/commands/generate/py/generate.py.cmd.ts` | | | no | listed |
68 | `generate ts` | root | `ts/packages/cli/src/commands/generate/ts/generate.ts.cmd.ts` | | | no | listed |
ts/packages/cli/src/commands/dev.cmd.ts
+1 -1
@@ -5,7 +5,7 @@ import { CommandInputError } from './errors';
5 import { initCmd } from './init.cmd';
6 import { triggersCmd$Listen } from './triggers/commands/triggers.listen.cmd';
7 import { logsCmd } from './logs/logs.cmd';
8 -import { devToolsCmd$Execute } from './tools/commands/tools.execute.cmd';
8 +import { devToolsCmd$Execute } from './tools/execute/tools.execute.cmd';
9 import { toolkitsCmd } from './toolkits/toolkits.cmd';
10 import { authConfigsCmd } from './auth-configs/auth-configs.cmd';
11 import { connectedAccountsCmd } from './connected-accounts/connected-accounts.cmd';
ts/packages/cli/src/commands/index.ts
+2 -2
@@ -22,7 +22,7 @@ import { artifactsCmd } from './artifacts/artifacts.cmd';
22 import { installCmd } from './install/install.cmd';
23 import { generateCmd } from './generate/generate.cmd';
24 import { buildDevCommand } from './dev.cmd';
25 -import { ExecuteInvocationArgs } from './tools/commands/tools.execute.cmd';
25 +import { ExecuteInvocationArgs } from './tools/execute/tools.execute.parallel';
26 import {
27 buildHelpCommand,
28 RootHelpMarker,
@@ -31,7 +31,7 @@ import {
31 showCommandHelp,
32 } from './root-help';
33 import { toolsCmd$Search } from './tools/search/tools.search.cmd';
34 -import { rootToolsCmd$Execute } from './tools/commands/tools.execute.cmd';
34 +import { rootToolsCmd$Execute } from './tools/execute/tools.execute.cmd';
35 import { rootToolsCmd } from './tools/tools.cmd';
36 import { rootTriggersCmd } from './triggers/root-triggers.cmd';
37 import { connectedAccountsCmd$Link } from './connected-accounts/link/connected-accounts.link.cmd';
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts deleted
-2095
@@ -1,2095 +0,0 @@
1 -import { withCommandMeta } from 'src/invocation/command-identity';
2 -import { actingUser, CommandSurface } from 'src/commands/surface';
3 -import { commandInputError } from 'src/commands/errors';
4 -import { ExpectedFailure } from 'src/effects/expected-failure';
5 -import { Argument, Command, Flag } from 'effect/cli';
6 -import util from 'node:util';
7 -import { Data, Effect, Context, Option, Result, Runtime } from 'effect';
8 -import * as FileSystem from 'effect/FileSystem';
9 -import * as Path from 'effect/Path';
10 -import { redact } from 'src/ui/redact';
11 -import { parseJsonRecord, isPlainRecord } from 'src/utils/parse-json';
12 -import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
13 -import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
14 -import {
15 - getOrFetchToolInputDefinition,
16 - invalidateToolInputDefinition,
17 - ToolInputValidationError,
18 - validateToolInputArguments,
19 - validateToolInputArgumentsWithDefinition,
20 -} from 'src/services/tool-input-validation';
21 -import { TerminalUI } from 'src/services/terminal-ui';
22 -import { logToolDebug, makePerfDebugLogger } from 'src/services/runtime-debug-logger';
23 -import { ToolsExecutor, detectInBandWarning } from 'src/services/tools-executor';
24 -import { resolveConsumerExecutionTransport } from 'src/services/dashboard-tool-execution';
25 -import type {
26 - InstantCharge,
27 - ToolExecuteParams,
28 - ToolExecuteResponse,
29 -} from 'src/services/tools-executor';
30 -import type { ToolkitProjectScope } from 'src/services/composio-clients';
31 -import { trackCliCodactFailureEffect, trackCliEventEffect } from 'src/analytics/dispatch';
32 -import { cliInvocationContext } from 'src/services/runtime-cli-context';
33 -import {
34 - getToolExecuteFailedEvent,
35 - getToolExecuteToolNotFoundEvent,
36 - getToolExecuteValidationFailedEvent,
37 - isMaybeToolValidationError,
38 - isMaybeToolNotFoundError,
39 -} from 'src/analytics/events';
40 -import { ComposioClientSingleton } from 'src/services/composio-clients';
41 -import { resolveCommandProject } from 'src/services/command-project';
42 -import { commandHintStep } from 'src/services/command-hints';
43 -import {
44 - getFreshConsumerConnectedToolkitsFromCache,
45 - refreshConsumerConnectedToolkitsCache,
46 -} from 'src/services/consumer-short-term-cache';
47 -import { resolveConnectedAccountForToolkit } from 'src/services/connected-account-selection';
48 -import {
49 - appendCliSessionHistory,
50 - resolveCliSessionArtifacts,
51 -} from 'src/services/cli-session-artifacts';
52 -import { storeCliSessionArtifact } from 'src/services/cli-session-artifacts';
53 -import {
54 - findFileUploadablePaths,
55 - normalizeFileUploadSchema,
56 - schemaHasFileUploadable,
57 - rejectLocalFilesWithoutUpload,
58 - setArgumentAt,
59 -} from 'src/services/tool-file-uploads';
60 -import { isMetaToolSlug } from 'src/utils/meta-tool-slugs';
61 -import {
62 - ComposioNoActiveConnectionError,
63 - mapComposioError,
64 - normalizeCliError,
65 -} from 'src/services/composio-error-overrides';
66 -import * as constants from 'src/constants';
67 -import { APP_CONFIG } from 'src/config';
68 -import { CLI_DEBUG_FLAG_NAMES } from 'src/services/runtime-flags';
69 -
70 -export const ExecuteInvocationArgs = Context.Reference<ReadonlyArray<string>>(
71 - 'commands/ExecuteInvocationArgs',
72 - { defaultValue: () => [] }
73 -);
74 -
75 -const slug = Argument.String('slug').pipe(
76 - Argument.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')
77 -);
78 -
79 -const additionalSlugs = Argument.String('additional-slugs').pipe(
80 - Argument.variadic(),
81 - Argument.withDescription('Additional tool slugs for --parallel')
82 -);
83 -const parallel = Flag.Boolean('parallel').pipe(
84 - Flag.withAlias('p'),
85 - Flag.withDefault(false),
86 - Flag.withDescription('Execute repeated tool slug/data groups concurrently')
87 -);
88 -
89 -const data = Flag.String('data').pipe(
90 - Flag.withAlias('d'),
91 - Flag.withDescription('JSON arguments, @file, or - for stdin'),
92 - Flag.optional
93 -);
94 -const file = Flag.String('file').pipe(
95 - Flag.withDescription('Inject a local file path into the single file_uploadable input'),
96 - Flag.optional
97 -);
98 -const accountOption = Flag.String('account').pipe(
99 - Flag.withDescription(
100 - 'Connected account selector for the inferred toolkit. Matches alias, word_id, or connected account id.'
101 - ),
102 - Flag.optional
103 -);
104 -
105 -const getSchema = Flag.Boolean('get-schema').pipe(
106 - Flag.withDescription('Fetch and print the CLI-facing input schema without executing'),
107 - Flag.withDefault(false)
108 -);
109 -const dryRun = Flag.Boolean('dry-run').pipe(
110 - Flag.withDescription('Validate and preview the tool call without executing'),
111 - Flag.withDefault(false)
112 -);
113 -const skipConnectionCheck = Flag.Boolean('skip-connection-check').pipe(
114 - Flag.withDescription('Skip the connected-account check'),
115 - Flag.withDefault(false)
116 -);
117 -const skipToolParamsCheck = Flag.Boolean('skip-tool-params-check').pipe(
118 - Flag.withDescription('Skip input validation against cached schema'),
119 - Flag.withDefault(false)
120 -);
121 -const skipChecks = Flag.Boolean('skip-checks').pipe(
122 - Flag.withDescription('Skip both connection and input validation checks'),
123 - Flag.withDefault(false)
124 -);
125 -
126 -const resolveInput = (input: Option.Option<string>) =>
127 - resolveOptionalTextInput(input, {
128 - // Default to empty object when no data provided (e.g. tools with no required args)
129 - missingValue: '{}',
130 - });
131 -
132 -// Also raised by the hand-rolled `--parallel` mini-parser (`parseParallelExecuteArgs` below).
133 -const invalidArguments = commandInputError('execute');
134 -
135 -// The reasons below are the ones this file constructs each error with; TypeScript cannot infer a
136 -// union from scattered constructor calls, so a new reason is added here next to its first use.
137 -
138 -/**
139 - * `composio execute` cannot run the tool as invoked: a `--file` the tool cannot take, or (with
140 - * `--parallel`) a toolkit the user has not connected. An expected failure: the invocation prints
141 - * the message and exits 1.
142 - */
143 -export class ToolExecutionError extends Data.TaggedError('ToolExecutionError')<{
144 - readonly reason: 'file_input' | 'connection_check';
145 - readonly message: string;
146 - readonly toolSlug?: string;
147 -}> {
148 - get [ExpectedFailure]() {
149 - return true;
150 - }
151 -}
152 -
153 -/**
154 - * A failed execution whose result is already on stdout as `{ "successful": false, ... }`.
155 - * The runtime prints nothing more for it (`[Runtime.errorReported]` is false) and exits 1.
156 - */
157 -export class ReportedToolExecutionError extends Data.TaggedError('ReportedToolExecutionError')<{
158 - readonly reason: 'connection_check' | 'execution_failed' | 'parallel_failed';
159 - readonly message: string;
160 - readonly toolSlug?: string;
161 -}> {
162 - get [Runtime.errorReported]() {
163 - return false;
164 - }
165 -
166 - get [Runtime.errorExitCode]() {
167 - return 1;
168 - }
169 -}
170 -
171 -const parseArguments = (raw: string) =>
172 - Effect.fromResult(
173 - parseJsonRecord(raw).pipe(
174 - Result.mapError(error =>
175 - invalidArguments(
176 - error.reason === 'not-a-record'
177 - ? 'Expected a JSON object for tool arguments, e.g. -d \'{ "key": "value" }\''
178 - : 'Invalid JSON input. Provide JSON or a JS-style object literal, e.g. -d \'{ "key": "value" }\''
179 - )
180 - )
181 - )
182 - );
183 -
184 -const hasNestedKey = (
185 - record: Record<string, unknown>,
186 - pathParts: ReadonlyArray<string | number>
187 -): boolean => {
188 - let current: unknown = record;
189 - for (const key of pathParts) {
190 - if (Array.isArray(current) && typeof key === 'number' && key < current.length) {
191 - current = current[key];
192 - } else if (isPlainRecord(current) && typeof key === 'string' && Object.hasOwn(current, key)) {
193 - current = current[key];
194 - } else return false;
195 - }
196 - return true;
197 -};
198 -
199 -const injectSingleFileArgument = (params: {
200 - readonly slug: string;
201 - readonly args: Record<string, unknown>;
202 - readonly filePath: string;
203 - readonly schema: Record<string, unknown>;
204 -}) =>
205 - Effect.gen(function* () {
206 - const uploadablePaths = findFileUploadablePaths(params.schema, [], params.args);
207 -
208 - if (uploadablePaths.length === 0) {
209 - return yield* new ToolExecutionError({
210 - reason: 'file_input',
211 - toolSlug: params.slug,
212 - message: schemaHasFileUploadable(params.schema)
213 - ? `Tool "${params.slug}" has no matching file_uploadable input in the supplied arguments. Supply the target array item with -d, or remove --file.`
214 - : `Tool "${params.slug}" has no file_uploadable input. Remove --file or pass JSON via -d.`,
215 - });
216 - }
217 -
218 - if (uploadablePaths.length > 1) {
219 - return yield* new ToolExecutionError({
220 - reason: 'file_input',
221 - toolSlug: params.slug,
222 - message: `Tool "${params.slug}" has multiple file_uploadable inputs (${uploadablePaths.map(parts => parts.join('.')).join(', ')}). Pass the target field explicitly with -d instead of --file.`,
223 - });
224 - }
225 -
226 - const targetPath = uploadablePaths[0] ?? [];
227 - if (hasNestedKey(params.args, targetPath)) {
228 - return yield* new ToolExecutionError({
229 - reason: 'file_input',
230 - toolSlug: params.slug,
231 - message: `Cannot use --file because "${targetPath.join('.')}" is already set in -d. Remove that field or omit --file.`,
232 - });
233 - }
234 -
235 - return setArgumentAt(params.args, targetPath, params.filePath);
236 - });
237 -
238 -const connectionTips = (params: {
239 - readonly toolkit: string | undefined;
240 - readonly toolSlug: string;
241 - readonly surface: 'root' | 'dev';
242 -}) => {
243 - const { toolkit, toolSlug, surface } = params;
244 - const executeStep =
245 - surface === 'dev'
246 - ? commandHintStep('Retry', 'dev.playgroundExecute', {
247 - slug: toolSlug,
248 - userId: '<user-id>',
249 - data: '...',
250 - })
251 - : commandHintStep('Retry', 'root.execute', { slug: toolSlug, data: '...' });
252 - if (!toolkit) {
253 - return executeStep;
254 - }
255 - return [
256 - commandHintStep(
257 - 'Link the toolkit first',
258 - surface === 'dev' ? 'dev.connectedAccounts.link' : 'root.link',
259 - surface === 'dev' ? { toolkit, userId: '<user-id>' } : { toolkit }
260 - ),
261 - executeStep.replace('Retry:', 'Then retry:'),
262 - ].join('\n');
263 -};
264 -
265 -const ciRedactReplacer = (_key: string, value: unknown): unknown => {
266 - if (typeof value !== 'string') return value;
267 - if (_key === 'logId') return redact({ value, prefix: 'log_' });
268 - if (_key === 'id' || _key.endsWith('Id') || _key.endsWith('_id')) {
269 - return redact({ value });
270 - }
271 - return value;
272 -};
273 -
274 -// JSON.stringify throws synchronously on circular or BigInt-bearing API
275 -// payloads; fall back to util.inspect so the formatter stays a plain string
276 -// function for its callers.
277 -const formatUnknownObject = (value: object): string =>
278 - Result.getOrElse(
279 - Result.try(() => JSON.stringify(value, null, 2)),
280 - () => util.inspect(value, { depth: 5, breakLength: 120 })
281 - );
282 -
283 -const redactRequestId = (value: object): object => {
284 - if (!value || typeof value !== 'object' || Array.isArray(value)) {
285 - return value;
286 - }
287 - if (!isPlainRecord(value)) return value;
288 - const requestId = value.request_id;
289 - if (typeof requestId !== 'string') {
290 - return value;
291 - }
292 - return {
293 - ...value,
294 - request_id: redact({ value: requestId }),
295 - };
296 -};
297 -
298 -// Responses larger than this are stored in a session file instead of printed,
299 -// so a caller such as an agent does not take a huge payload into its context.
300 -// Measured in UTF-8 bytes: about 10,000 tokens of JSON at the estimate below.
301 -const EXECUTE_INLINE_OUTPUT_BYTE_THRESHOLD = 40_000;
302 -
303 -// JSON averages roughly four bytes per token. The `tokenCount` of a stored
304 -// response is this estimate rather than a tokenizer count, since the real count
305 -// depends on the model that reads the file.
306 -const ESTIMATED_BYTES_PER_OUTPUT_TOKEN = 4;
307 -
308 -const describeStoredOutputSize = ({
309 - sizeBytes,
310 - tokenCount,
311 -}: {
312 - readonly sizeBytes: number;
313 - readonly tokenCount: number;
314 -}): string => `${Math.ceil(sizeBytes / 1024)} KB, ~${tokenCount} tokens`;
315 -
316 -const shouldStoreLargeExecuteOutput = APP_CONFIG.CLI_INVOCATION_ORIGIN.pipe(
317 - Effect.orDie,
318 - Effect.map(origin => origin !== 'run')
319 -);
320 -
321 -type StoredExecuteOutputSummary = {
322 - readonly successful: true;
323 - readonly error: null;
324 - readonly logId: string;
325 - readonly instantCharge?: InstantCharge;
326 - readonly storedInFile: true;
327 - readonly tokenCount: number;
328 - readonly sizeBytes: number;
329 - readonly outputFilePath: string;
330 -};
331 -
332 -type PreparedExecuteOutput =
333 - | { readonly kind: 'inline'; readonly json: string }
334 - | { readonly kind: 'file'; readonly summary: StoredExecuteOutputSummary };
335 -
336 -const serializeExecuteOutput = (result: unknown): string =>
337 - JSON.stringify(result, ciRedactReplacer, 2);
338 -
339 -const permissionApprovalLabel = (approval?: string): string | undefined => {
340 - switch (approval) {
341 - case 'always_approved':
342 - return 'always approved';
343 - case 'cached_approved':
344 - return 'cached approved';
345 - case 'approved_once':
346 - return 'approved once';
347 - case 'approved_for_session':
348 - return 'approved for session';
349 - default:
350 - return undefined;
351 - }
352 -};
353 -
354 -const instantChargeLabel = (charge?: InstantCharge): string | undefined => {
355 - if (!charge) return undefined;
356 - return `instant charge: ${charge.amount} ${charge.currency}`;
357 -};
358 -
359 -const executionSuccessSuffix = (result: {
360 - readonly logId?: string;
361 - readonly permissionApproval?: string;
362 - readonly instantCharge?: InstantCharge;
363 -}) => {
364 - const metadata = [
365 - permissionApprovalLabel(result.permissionApproval),
366 - instantChargeLabel(result.instantCharge),
367 - result.logId ? `logId: ${redact({ value: result.logId, prefix: 'log_' })}` : undefined,
368 - ].filter((value): value is string => Boolean(value));
369 - return metadata.length > 0 ? ` (${metadata.join(', ')})` : '';
370 -};
371 -
372 -const persistLargeExecuteOutput = (
373 - toolSlug: string,
374 - json: string,
375 - sizeBytes: number,
376 - sharedDirectory?: string
377 -) =>
378 - Effect.gen(function* () {
379 - const runOutputDirectory = yield* APP_CONFIG.RUN_OUTPUT_DIR;
380 - const outputFilePath = yield* storeCliSessionArtifact({
381 - contents: json,
382 - name: `${toolSlug}_OUTPUT`,
383 - extension: 'json',
384 - directoryPath: sharedDirectory?.trim() || runOutputDirectory,
385 - });
386 -
387 - return {
388 - successful: true,
389 - error: null,
390 - logId: '',
391 - storedInFile: true,
392 - tokenCount: Math.ceil(sizeBytes / ESTIMATED_BYTES_PER_OUTPUT_TOKEN),
393 - sizeBytes,
394 - outputFilePath: outputFilePath ?? '(could not write to disk)',
395 - } satisfies StoredExecuteOutputSummary;
396 - });
397 -
398 -const perfDebugLog = makePerfDebugLogger();
399 -
400 -const prepareExecuteOutput = (
401 - toolSlug: string,
402 - result: ToolExecuteResponse,
403 - sharedDirectory?: string
404 -) =>
405 - Effect.gen(function* () {
406 - const json = serializeExecuteOutput(result);
407 - const sizeBytes = new TextEncoder().encode(json).length;
408 - // `composio run` always prints inline.
409 - if (
410 - sizeBytes <= EXECUTE_INLINE_OUTPUT_BYTE_THRESHOLD ||
411 - !(yield* shouldStoreLargeExecuteOutput)
412 - ) {
413 - return {
414 - kind: 'inline',
415 - json,
416 - } satisfies PreparedExecuteOutput;
417 - }
418 -
419 - return {
420 - kind: 'file',
421 - summary: {
422 - ...(yield* persistLargeExecuteOutput(toolSlug, json, sizeBytes, sharedDirectory)),
423 - logId: result.logId,
424 - ...(result.instantCharge ? { instantCharge: result.instantCharge } : {}),
425 - } satisfies StoredExecuteOutputSummary,
426 - } satisfies PreparedExecuteOutput;
427 - });
428 -
429 -const emitExecuteFailureTelemetry = (params: {
430 - readonly toolSlug: string;
431 - readonly args: Record<string, unknown>;
432 - readonly error: unknown;
433 - readonly surface: 'root' | 'dev';
434 - readonly projectMode: 'consumer' | 'developer';
435 - readonly stage: 'schema_fetch' | 'dry_run' | 'validation' | 'execution';
436 - readonly logId?: string;
437 - readonly mappedError?: ReturnType<typeof mapComposioError>;
438 - readonly projectScope?: ToolkitProjectScope;
439 -}) =>
440 - Effect.gen(function* () {
441 - const toolkitSlug = yield* toolkitFromToolSlug(params.toolSlug, params.projectScope);
442 - const { invocationOrigin } = yield* cliInvocationContext;
443 - const normalized = params.mappedError?.normalized ?? normalizeCliError(params.error);
444 - const failureOrigin: 'fast_fail' | 'main_endpoint' =
445 - normalized instanceof ToolInputValidationError || params.stage !== 'execution'
446 - ? 'fast_fail'
447 - : 'main_endpoint';
448 -
449 - if (normalized instanceof ToolInputValidationError) {
450 - yield* trackCliEventEffect(
451 - getToolExecuteValidationFailedEvent({
452 - toolSlug: params.toolSlug,
453 - toolkitSlug,
454 - args: params.args,
455 - error: normalized,
456 - invocationOrigin,
457 - surface: params.surface,
458 - projectMode: params.projectMode,
459 - stage: params.stage === 'dry_run' ? 'dry_run' : 'validation',
460 - failureOrigin,
461 - logId: params.logId,
462 - })
463 - );
464 - yield* trackCliCodactFailureEffect({
465 - failureType: 'wrong_tool_input_param',
466 - toolInfo: {
467 - ...(toolkitSlug ? { toolkit: toolkitSlug } : {}),
468 - },
469 - ctx: {
470 - tool_slug: params.toolSlug,
471 - issues: [...normalized.issues].slice(0, 50),
472 - schema_path: normalized.schemaPath,
473 - stage: params.stage === 'dry_run' ? 'dry_run' : 'validation',
474 - },
475 - session: {
476 - source: 'cli',
477 - command_path: params.surface === 'root' ? 'execute' : 'dev playground-execute',
478 - project_mode: params.projectMode,
479 - surface: params.surface,
480 - cli_version: constants.APP_VERSION,
481 - },
482 - });
483 - return;
484 - }
485 -
486 - const mapped =
487 - params.mappedError ??
488 - mapComposioError({
489 - error: params.error,
490 - toolkit: toolkitSlug,
491 - toolSlug: params.toolSlug,
492 - });
493 - const apiDetails = mapped.apiDetails;
494 - const message = mapped.message;
495 - const errorSlug = mapped.slugValue;
496 - const status = apiDetails?.status;
497 - const apiCode = apiDetails?.code;
498 - const isNoConnectionError =
499 - normalized instanceof ComposioNoActiveConnectionError || Boolean(mapped.override);
500 -
501 - const isValidationError = isMaybeToolValidationError({ message, errorSlug, apiCode });
502 - const executionStage = params.stage === 'validation' ? 'execution' : params.stage;
503 - const failureEvent = () => {
504 - if (isValidationError) {
505 - return getToolExecuteValidationFailedEvent({
506 - toolSlug: params.toolSlug,
507 - toolkitSlug,
508 - args: params.args,
509 - error: new ToolInputValidationError({
510 - toolSlug: params.toolSlug,
511 - schemaPath: 'server',
512 - issues: [message],
513 - }),
514 - invocationOrigin,
515 - surface: params.surface,
516 - projectMode: params.projectMode,
517 - stage: params.stage === 'dry_run' ? 'dry_run' : 'execution',
518 - failureOrigin,
519 - logId: params.logId,
520 - });
521 - }
522 - if (isMaybeToolNotFoundError({ message, errorSlug, status, apiCode })) {
523 - return getToolExecuteToolNotFoundEvent({
524 - toolSlug: params.toolSlug,
525 - toolkitSlug,
526 - args: params.args,
527 - invocationOrigin,
528 - surface: params.surface,
529 - projectMode: params.projectMode,
530 - stage: executionStage,
531 - failureOrigin,
532 - logId: params.logId,
533 - errorSlug,
534 - status,
535 - apiCode,
536 - message,
537 - });
538 - }
539 - return getToolExecuteFailedEvent({
540 - toolSlug: params.toolSlug,
541 - toolkitSlug,
542 - args: params.args,
543 - invocationOrigin,
544 - surface: params.surface,
545 - projectMode: params.projectMode,
546 - stage: executionStage,
547 - failureOrigin,
548 - logId: params.logId,
549 - errorSlug,
550 - status,
551 - apiCode,
552 - message,
553 - errorName: normalized instanceof Error ? normalized.name : undefined,
554 - isNoConnectionError,
555 - });
556 - };
557 -
558 - yield* trackCliEventEffect(failureEvent());
559 -
560 - if (isNoConnectionError) {
561 - return;
562 - }
563 -
564 - if (isValidationError) {
565 - yield* trackCliCodactFailureEffect({
566 - failureType: 'wrong_tool_input_param',
567 - toolInfo: {
568 - ...(toolkitSlug ? { toolkit: toolkitSlug } : {}),
569 - },
570 - ctx: {
571 - tool_slug: params.toolSlug,
572 - error_slug: errorSlug,
573 - api_error_code: apiCode,
574 - http_status: status,
575 - error_message: message,
576 - stage: params.stage === 'dry_run' ? 'dry_run' : 'execution',
577 - },
578 - session: {
579 - source: 'cli',
580 - command_path: params.surface === 'root' ? 'execute' : 'dev playground-execute',
581 - project_mode: params.projectMode,
582 - surface: params.surface,
583 - cli_version: constants.APP_VERSION,
584 - },
585 - requestId: apiDetails?.request_id,
586 - });
587 - return;
588 - }
589 -
590 - if (
591 - isMaybeToolNotFoundError({
592 - message,
593 - errorSlug,
594 - status,
595 - apiCode,
596 - })
597 - ) {
598 - yield* trackCliCodactFailureEffect({
599 - failureType: 'wrong_tool_slug',
600 - toolInfo: {
601 - ...(toolkitSlug ? { toolkit: toolkitSlug } : {}),
602 - },
603 - ctx: {
604 - invalid_tool_slug: params.toolSlug,
605 - error_slug: errorSlug,
606 - api_error_code: apiCode,
607 - http_status: status,
608 - error_message: message,
609 - stage: params.stage === 'validation' ? 'execution' : params.stage,
610 - },
611 - session: {
612 - source: 'cli',
613 - command_path: params.surface === 'root' ? 'execute' : 'dev playground-execute',
614 - project_mode: params.projectMode,
615 - surface: params.surface,
616 - cli_version: constants.APP_VERSION,
617 - },
618 - requestId: apiDetails?.request_id,
619 - });
620 - }
621 - });
622 -
623 -const writeExecuteStdout = (ui: TerminalUI, data: string) => ui.output(data, { force: true });
624 -
625 -const handleExecutionError = (
626 - ui: TerminalUI,
627 - error: unknown,
628 - context: {
629 - toolSlug: string;
630 - args: Record<string, unknown>;
631 - surface: 'root' | 'dev';
632 - projectMode: 'consumer' | 'developer';
633 - stage: 'schema_fetch' | 'dry_run' | 'validation' | 'execution';
634 - logId?: string;
635 - projectScope?: ToolkitProjectScope;
636 - }
637 -) =>
638 - Effect.gen(function* () {
639 - const toolkit = yield* toolkitFromToolSlug(context.toolSlug, context.projectScope);
640 - const mapped = mapComposioError({ error, toolkit, toolSlug: context.toolSlug });
641 - const normalized = mapped.normalized;
642 - if (normalized instanceof ToolInputValidationError) {
643 - yield* emitExecuteFailureTelemetry({
644 - toolSlug: context.toolSlug,
645 - args: context.args,
646 - error: normalized,
647 - surface: context.surface,
648 - projectMode: context.projectMode,
649 - stage: context.stage,
650 - logId: context.logId,
651 - projectScope: context.projectScope,
652 - });
653 - yield* ui.log.error(`Input validation failed for ${context.toolSlug}`);
654 - yield* ui.note(
655 - [`Schema: ${normalized.schemaPath}`, ...normalized.issues.map(issue => `- ${issue}`)].join(
656 - '\n'
657 - ),
658 - 'Tool schema validation'
659 - );
660 - return { error: normalized.message, slug: context.toolSlug };
661 - }
662 -
663 - const apiDetails = mapped.apiDetails;
664 - const slugValue = mapped.slugValue;
665 -
666 - yield* emitExecuteFailureTelemetry({
667 - toolSlug: context.toolSlug,
668 - args: context.args,
669 - error,
670 - surface: context.surface,
671 - projectMode: context.projectMode,
672 - stage: context.stage,
673 - logId: context.logId,
674 - projectScope: context.projectScope,
675 - mappedError: mapped,
676 - });
677 -
678 - if (normalized instanceof ComposioNoActiveConnectionError) {
679 - yield* ui.log.error(mapped.message);
680 - if (toolkit) {
681 - yield* ui.note(
682 - connectionTips({ toolkit, toolSlug: context.toolSlug, surface: context.surface }),
683 - 'Tips'
684 - );
685 - }
686 - return { error: mapped.message, slug: slugValue ?? context.toolSlug };
687 - }
688 -
689 - yield* ui.log.error(mapped.message);
690 -
691 - const detailsObject = apiDetails;
692 - if (detailsObject) {
693 - yield* ui.note(formatUnknownObject(redactRequestId(detailsObject)), 'Error details');
694 - }
695 -
696 - return { error: mapped.message, slug: slugValue };
697 - });
698 -
699 -// What a dry run checks, matching the real call: the arguments against the
700 -// schema unless checks are skipped, then any local file the tool cannot upload.
701 -// The real call refuses that file whatever the skip flags say, loading the
702 -// schema for it and going on without one, and never for a meta tool, which
703 -// uploads nothing. Returns the schema only when the arguments were checked.
704 -const checkDryRunArguments = (params: {
705 - readonly slug: string;
706 - readonly args: Record<string, unknown>;
707 - readonly projectScope: { readonly orgId?: string; readonly projectId?: string };
708 - readonly verificationDisabled: boolean;
709 -}) =>
710 - Effect.gen(function* () {
711 - const { slug, args, verificationDisabled } = params;
712 - if (verificationDisabled && isMetaToolSlug(slug)) return null;
713 -
714 - const definition = verificationDisabled
715 - ? yield* getOrFetchToolInputDefinition(slug, params.projectScope).pipe(
716 - Effect.catch(() => Effect.succeed(null))
717 - )
718 - : yield* getOrFetchToolInputDefinition(slug, params.projectScope);
719 - if (!definition) return null;
720 -
721 - if (!verificationDisabled) {
722 - yield* validateToolInputArgumentsWithDefinition(slug, args, definition);
723 - }
724 - if (!isMetaToolSlug(slug)) {
725 - yield* rejectLocalFilesWithoutUpload({
726 - fs: yield* FileSystem.FileSystem,
727 - path: yield* Path.Path,
728 - toolSlug: slug,
729 - arguments_: args,
730 - inputSchema: definition.schema,
731 - });
732 - }
733 - return verificationDisabled ? null : definition;
734 - });
735 -
736 -// Gates the tool call: the request is only sent once the arguments pass. A
737 -// schema that cannot be loaded does not block the call, the server validates too.
738 -const validateToolInputBeforeExecute = (params: {
739 - readonly slug: string;
740 - readonly args: Record<string, unknown>;
741 - readonly resolvedProject: {
742 - readonly orgId: string;
743 - readonly projectId: string;
744 - };
745 -}) =>
746 - validateToolInputArguments(params.slug, params.args, {
747 - orgId: params.resolvedProject.orgId,
748 - projectId: params.resolvedProject.projectId,
749 - }).pipe(
750 - Effect.asVoid,
751 - Effect.catchIf(
752 - error => !(error instanceof ToolInputValidationError),
753 - () => perfDebugLog('execute.validation.schema_unavailable', { slug: params.slug })
754 - )
755 - );
756 -
757 -type DryRunSummary = {
758 - readonly successful: true;
759 - readonly dryRun: true;
760 - readonly slug: string;
761 - readonly arguments: Record<string, unknown>;
762 - readonly userId: string;
763 - readonly schemaPath?: string;
764 - readonly schemaVersion?: string | null;
765 -};
766 -
767 -type RunToolsExecuteParams = {
768 - slug: string;
769 - data: Option.Option<string>;
770 - file: Option.Option<string>;
771 - account: Option.Option<string>;
772 - projectName: Option.Option<string>;
773 - surface: 'root' | 'dev';
774 - projectMode: 'consumer' | 'developer';
775 - getSchema: boolean;
776 - dryRun: boolean;
777 - skipConnectionCheck: boolean;
778 - skipToolParamsCheck: boolean;
779 - skipChecks: boolean;
780 -};
781 -
782 -type SharedRunToolsExecuteParams = Omit<RunToolsExecuteParams, 'slug' | 'data' | 'file'>;
783 -
784 -type ParallelExecuteSpec = {
785 - readonly slug: string;
786 - readonly data: Option.Option<string>;
787 - readonly account: Option.Option<string>;
788 -};
789 -
790 -type ParsedParallelExecuteArgs = SharedRunToolsExecuteParams & {
791 - readonly userId: Option.Option<string>;
792 - readonly specs: ReadonlyArray<ParallelExecuteSpec>;
793 -};
794 -
795 -type ParallelExecuteResult =
796 - | {
797 - readonly slug: string;
798 - readonly successful: true;
799 - readonly version: string | null;
800 - readonly schemaPath: string;
801 - readonly inputSchema: Record<string, unknown>;
802 - }
803 - | {
804 - readonly slug: string;
805 - readonly successful: false;
806 - readonly error: string;
807 - };
808 -
809 -type ResolvedExecuteContext = {
810 - readonly ui: TerminalUI;
811 - readonly executor: ToolsExecutor;
812 - readonly resolvedProject: {
813 - readonly orgId: string;
814 - readonly projectId: string;
815 - readonly projectType: 'CONSUMER' | 'DEVELOPER';
816 - readonly consumerUserId?: string;
817 - };
818 - readonly args: Record<string, unknown>;
819 - readonly resolvedUserId: string;
820 - readonly selectedConnectedAccountId?: string;
821 - readonly executeParams: ToolExecuteParams;
822 - readonly executeOutputDir?: string;
823 -};
824 -
825 -/**
826 - * The resolved project as toolkit resolution needs it: custom toolkits are
827 - * listed per project, and it has to be the project execute runs against.
828 - */
829 -const toolkitProjectScope = (resolvedProject: ToolkitProjectScope): ToolkitProjectScope => ({
830 - orgId: resolvedProject.orgId,
831 - projectId: resolvedProject.projectId,
832 -});
833 -
834 -type ResolvedSchemaContext = {
835 - readonly ui: TerminalUI;
836 - readonly resolvedProject: {
837 - readonly orgId: string;
838 - readonly projectId: string;
839 - readonly projectType: 'CONSUMER' | 'DEVELOPER';
840 - readonly consumerUserId?: string;
841 - };
842 -};
843 -
844 -const emitCachedSchema = (
845 - ui: TerminalUI,
846 - slug: string,
847 - definition: {
848 - readonly version: string | null;
849 - readonly schemaPath: string;
850 - readonly schema: Record<string, unknown>;
851 - }
852 -) =>
853 - Effect.gen(function* () {
854 - const displaySchema = normalizeFileUploadSchema(definition.schema);
855 - yield* ui.log.message(
856 - `Schema saved, inspect keys like: jq '{required: (.inputSchema.required // []), keys: (.inputSchema.properties | keys)}' ${definition.schemaPath}`
857 - );
858 - yield* writeExecuteStdout(
859 - ui,
860 - JSON.stringify(
861 - {
862 - slug,
863 - version: definition.version,
864 - schemaPath: definition.schemaPath,
865 - inputSchema: displaySchema,
866 - },
867 - null,
868 - 2
869 - )
870 - );
871 - });
872 -
873 -const resolveExecuteContext = (
874 - params: RunToolsExecuteParams,
875 - /** The acting user; `--parallel` resolves it once for all its tools. */
876 - user: ReturnType<typeof actingUser> = actingUser()
877 -) =>
878 - Effect.gen(function* () {
879 - const ui = yield* TerminalUI;
880 - const executor = yield* ToolsExecutor;
881 - const input = (yield* resolveInput(params.data)) ?? '{}';
882 - const parsedArgs = yield* parseArguments(input);
883 - const runOutputDirectory = yield* APP_CONFIG.RUN_OUTPUT_DIR;
884 -
885 - const { userId: resolvedUserId, project: resolvedProject } = yield* user;
886 - const clientSingleton = yield* ComposioClientSingleton;
887 - const client = yield* clientSingleton.getFor({
888 - orgId: resolvedProject.orgId,
889 - projectId: resolvedProject.projectId,
890 - });
891 - const toolkitSlug = yield* toolkitFromToolSlug(
892 - params.slug,
893 - toolkitProjectScope(resolvedProject)
894 - );
895 - const selectedConnectedAccountId = yield* resolveConnectedAccountForToolkit({
896 - client,
897 - toolkitSlug,
898 - userId: resolvedUserId,
899 - selector: params.account,
900 - });
901 - const args = Option.isSome(params.file)
902 - ? yield* getOrFetchToolInputDefinition(params.slug, {
903 - orgId: resolvedProject.orgId,
904 - projectId: resolvedProject.projectId,
905 - }).pipe(
906 - Effect.flatMap(definition =>
907 - injectSingleFileArgument({
908 - slug: params.slug,
909 - args: parsedArgs,
910 - filePath: Option.getOrThrow(params.file),
911 - schema: definition.schema,
912 - })
913 - )
914 - )
915 - : parsedArgs;
916 - const executeOutputDir =
917 - runOutputDirectory ||
918 - Option.getOrUndefined(
919 - yield* resolveCliSessionArtifacts({
920 - orgId: resolvedProject.projectType === 'CONSUMER' ? resolvedProject.orgId : undefined,
921 - consumerUserId:
922 - resolvedProject.projectType === 'CONSUMER' ? resolvedProject.consumerUserId : undefined,
923 - }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
924 - );
925 -
926 - // Root `execute` (the consumer surface, which is also what `composio run`
927 - // spawns) goes through the Dashboard; `dev playground-execute` stays on the
928 - // backend. The one exception is a backend URL overridden without a
929 - // matching `COMPOSIO_WEB_URL`: the key is never sent to another
930 - // deployment's Dashboard.
931 - const executesViaDashboard =
932 - params.surface === 'root' && (yield* resolveConsumerExecutionTransport) === 'dashboard';
933 -
934 - return {
935 - ui,
936 - executor,
937 - resolvedProject,
938 - args,
939 - resolvedUserId,
940 - selectedConnectedAccountId,
941 - executeOutputDir,
942 - executeParams: {
943 - userId: resolvedUserId,
944 - target: executesViaDashboard
945 - ? { kind: 'dashboard', orgId: resolvedProject.orgId }
946 - : { kind: 'backend' },
947 - arguments: args,
948 - client,
949 - projectScope: {
950 - orgId: resolvedProject.orgId,
951 - projectId: resolvedProject.projectId,
952 - },
953 - connectedAccounts:
954 - toolkitSlug && selectedConnectedAccountId
955 - ? {
956 - [toolkitSlug]: selectedConnectedAccountId,
957 - }
958 - : undefined,
959 - cacheScope:
960 - resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
961 - ? {
962 - orgId: resolvedProject.orgId,
963 - projectId: resolvedProject.projectId,
964 - consumerUserId: resolvedProject.consumerUserId,
965 - }
966 - : undefined,
967 - },
968 - } satisfies ResolvedExecuteContext;
969 - });
970 -
971 -const resolveSchemaContext = (params: SharedRunToolsExecuteParams) =>
972 - Effect.gen(function* () {
973 - const resolvedProject = yield* resolveCommandProject({
974 - mode: params.projectMode,
975 - projectName:
976 - params.surface === 'root' ? undefined : Option.getOrUndefined(params.projectName),
977 - });
978 - const ui = yield* TerminalUI;
979 -
980 - return {
981 - ui,
982 - resolvedProject,
983 - } satisfies ResolvedSchemaContext;
984 - });
985 -
986 -const runConnectedToolkitFailFast = (params: {
987 - readonly slug: string;
988 - readonly surface: 'root' | 'dev';
989 - readonly ui: TerminalUI;
990 - readonly resolvedProject: ResolvedExecuteContext['resolvedProject'];
991 - readonly resolvedUserId: string;
992 - readonly skipConnectionCheck: boolean;
993 - readonly skipChecks: boolean;
994 -}) =>
995 - Effect.gen(function* () {
996 - if (params.skipConnectionCheck || params.skipChecks) {
997 - yield* perfDebugLog('execute.connected_toolkits.skipped', {
998 - slug: params.slug,
999 - reason: params.skipChecks ? 'skip-checks' : 'skip-connection-check',
1000 - });
1001 - return;
1002 - }
1003 - if (params.resolvedProject.projectType !== 'CONSUMER') return;
1004 -
1005 - yield* perfDebugLog('execute.connected_toolkits.refresh_start', {
1006 - slug: params.slug,
1007 - orgId: params.resolvedProject.orgId,
1008 - consumerUserId: params.resolvedUserId,
1009 - });
1010 - yield* refreshConsumerConnectedToolkitsCache({
1011 - orgId: params.resolvedProject.orgId,
1012 - consumerUserId: params.resolvedUserId,
1013 - }).pipe(
1014 - Effect.tap(() =>
1015 - perfDebugLog('execute.connected_toolkits.refresh_end', {
1016 - slug: params.slug,
1017 - orgId: params.resolvedProject.orgId,
1018 - consumerUserId: params.resolvedUserId,
1019 - successful: true,
1020 - })
1021 - ),
1022 - Effect.catch(() =>
1023 - perfDebugLog('execute.connected_toolkits.refresh_end', {
1024 - slug: params.slug,
1025 - orgId: params.resolvedProject.orgId,
1026 - consumerUserId: params.resolvedUserId,
1027 - successful: false,
1028 - })
1029 - ),
1030 - Effect.forkDetach,
1031 - Effect.asVoid
1032 - );
1033 -
1034 - const toolkit = yield* toolkitFromToolSlug(
1035 - params.slug,
1036 - toolkitProjectScope(params.resolvedProject)
1037 - );
1038 - if (!toolkit) return;
1039 -
1040 - const cachedToolkits = yield* getFreshConsumerConnectedToolkitsFromCache({
1041 - orgId: params.resolvedProject.orgId,
1042 - consumerUserId: params.resolvedUserId,
1043 - });
1044 - yield* perfDebugLog(
1045 - Option.isSome(cachedToolkits)
1046 - ? 'execute.connected_toolkits.cache_hit'
1047 - : 'execute.connected_toolkits.cache_miss',
1048 - {
1049 - slug: params.slug,
1050 - toolkit,
1051 - orgId: params.resolvedProject.orgId,
1052 - consumerUserId: params.resolvedUserId,
1053 - cachedToolkits: Option.isSome(cachedToolkits) ? cachedToolkits.value : undefined,
1054 - }
1055 - );
1056 -
1057 - if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(toolkit)) {
1058 - yield* perfDebugLog('execute.connected_toolkits.fail_fast', {
1059 - slug: params.slug,
1060 - toolkit,
1061 - orgId: params.resolvedProject.orgId,
1062 - consumerUserId: params.resolvedUserId,
1063 - });
1064 - const message = `Toolkit "${toolkit}" is not connected for this user (cached within the last 5 minutes). If you just connected the account, use --skip-connection-check.`;
1065 - yield* params.ui.log.error(message);
1066 - yield* params.ui.note(
1067 - connectionTips({ toolkit, toolSlug: params.slug, surface: params.surface }),
1068 - 'Tips'
1069 - );
1070 - yield* writeExecuteStdout(
1071 - params.ui,
1072 - JSON.stringify(
1073 - {
1074 - successful: false,
1075 - error: message,
1076 - slug: params.slug,
1077 - },
1078 - ciRedactReplacer,
1079 - 2
1080 - )
1081 - );
1082 - return yield* new ReportedToolExecutionError({
1083 - reason: 'connection_check',
1084 - toolSlug: params.slug,
1085 - message,
1086 - });
1087 - }
1088 - });
1089 -
1090 -const executeSessionHistoryScope = (resolvedProject: ResolvedExecuteContext['resolvedProject']) =>
1091 - resolvedProject.projectType === 'CONSUMER'
1092 - ? {
1093 - orgId: resolvedProject.orgId,
1094 - consumerUserId: resolvedProject.consumerUserId,
1095 - }
1096 - : {};
1097 -
1098 -const runExecuteWithSpinner = (params: {
1099 - readonly slug: string;
1100 - readonly surface: 'root' | 'dev';
1101 - readonly projectMode: 'consumer' | 'developer';
1102 - readonly dryRun: boolean;
1103 - readonly ui: TerminalUI;
1104 - readonly executor: ToolsExecutor;
1105 - readonly resolvedProject: ResolvedExecuteContext['resolvedProject'];
1106 - readonly args: Record<string, unknown>;
1107 - readonly resolvedUserId: string;
1108 - readonly executeParams: ToolExecuteParams;
1109 - readonly executeOutputDir?: string;
1110 - readonly skipToolParamsCheck: boolean;
1111 - readonly skipChecks: boolean;
1112 -}) =>
1113 - Effect.gen(function* () {
1114 - const verificationDisabled = params.skipChecks || params.skipToolParamsCheck;
1115 -
1116 - yield* params.ui.useMakeSpinner(`Executing tool "${params.slug}"...`, spinner =>
1117 - Effect.gen(function* () {
1118 - if (params.dryRun) {
1119 - const definition = yield* checkDryRunArguments({
1120 - slug: params.slug,
1121 - args: params.args,
1122 - projectScope: {
1123 - orgId: params.resolvedProject.orgId,
1124 - projectId: params.resolvedProject.projectId,
1125 - },
1126 - verificationDisabled,
1127 - }).pipe(
1128 - Effect.tapError(error =>
1129 - emitExecuteFailureTelemetry({
1130 - toolSlug: params.slug,
1131 - args: params.args,
1132 - error,
1133 - surface: params.surface,
1134 - projectMode: params.projectMode,
1135 - stage: 'dry_run',
1136 - projectScope: toolkitProjectScope(params.resolvedProject),
1137 - })
1138 - )
1139 - );
1140 - const summary: DryRunSummary = {
1141 - successful: true,
1142 - dryRun: true,
1143 - slug: params.slug,
1144 - arguments: params.args,
1145 - userId: params.resolvedUserId,
1146 - schemaPath: definition?.schemaPath,
1147 - schemaVersion: definition?.version,
1148 - };
1149 - yield* spinner.stop('Dry run successful');
1150 - yield* params.ui.log.message(
1151 - verificationDisabled
1152 - ? 'No tool was executed. Local validation was skipped.'
1153 - : 'No tool was executed. Arguments were validated locally only.'
1154 - );
1155 - yield* writeExecuteStdout(params.ui, JSON.stringify(summary, ciRedactReplacer, 2));
1156 - yield* appendCliSessionHistory({
1157 - ...executeSessionHistoryScope(params.resolvedProject),
1158 - entry: {
1159 - command: 'execute',
1160 - status: 'dry-run',
1161 - slug: params.slug,
1162 - arguments: params.args,
1163 - },
1164 - }).pipe(Effect.catch(() => Effect.void));
1165 - return;
1166 - }
1167 -
1168 - yield* perfDebugLog('execute.tool_call.start', { slug: params.slug });
1169 - const validateArgs = verificationDisabled
1170 - ? Effect.void
1171 - : validateToolInputBeforeExecute({
1172 - slug: params.slug,
1173 - args: params.args,
1174 - resolvedProject: params.resolvedProject,
1175 - });
1176 - const result = yield* validateArgs.pipe(
1177 - Effect.andThen(params.executor.execute(params.slug, params.executeParams)),
1178 - Effect.matchEffect({
1179 - onFailure: error =>
1180 - Effect.gen(function* () {
1181 - yield* logToolDebug('execute_result', { slug: params.slug, result: error });
1182 - yield* perfDebugLog('execute.tool_call.end', {
1183 - slug: params.slug,
1184 - successful: false,
1185 - });
1186 - // The validation error points the user at the cached schema, so
1187 - // it has to stay on disk.
1188 - if (!(error instanceof ToolInputValidationError)) {
1189 - yield* invalidateToolInputDefinition(params.slug).pipe(
1190 - Effect.catch(() => Effect.void)
1191 - );
1192 - }
1193 - yield* spinner.error();
1194 - const summary = yield* handleExecutionError(params.ui, error, {
1195 - toolSlug: params.slug,
1196 - args: params.args,
1197 - surface: params.surface,
1198 - projectMode: params.projectMode,
1199 - stage: 'execution',
1200 - projectScope: toolkitProjectScope(params.resolvedProject),
1201 - });
1202 - yield* writeExecuteStdout(
1203 - params.ui,
1204 - JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)
1205 - );
1206 - yield* appendCliSessionHistory({
1207 - ...executeSessionHistoryScope(params.resolvedProject),
1208 - entry: {
1209 - command: 'execute',
1210 - status: 'error',
1211 - slug: params.slug,
1212 - arguments: params.args,
1213 - error: summary.error,
1214 - },
1215 - }).pipe(Effect.catch(() => Effect.void));
1216 - return yield* new ReportedToolExecutionError({
1217 - reason: 'execution_failed',
1218 - toolSlug: params.slug,
1219 - message: summary.error,
1220 - });
1221 - }),
1222 - onSuccess: result =>
1223 - Effect.gen(function* () {
1224 - yield* logToolDebug('execute_result', { slug: params.slug, result });
1225 - yield* perfDebugLog('execute.tool_call.end', {
1226 - slug: params.slug,
1227 - successful: true,
1228 - });
1229 - return result;
1230 - }),
1231 - })
1232 - );
1233 - if (!result.successful) {
1234 - yield* invalidateToolInputDefinition(params.slug).pipe(Effect.catch(() => Effect.void));
1235 - const logId = result.logId
1236 - ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
1237 - : '';
1238 - yield* spinner.error(`Execution failed${logId}`);
1239 -
1240 - const summary = yield* handleExecutionError(params.ui, result.error ?? result, {
1241 - toolSlug: params.slug,
1242 - args: params.args,
1243 - surface: params.surface,
1244 - projectMode: params.projectMode,
1245 - stage: 'execution',
1246 - logId: result.logId,
1247 - projectScope: toolkitProjectScope(params.resolvedProject),
1248 - });
1249 - yield* writeExecuteStdout(params.ui, JSON.stringify(result, ciRedactReplacer, 2));
1250 - return yield* new ReportedToolExecutionError({
1251 - reason: 'execution_failed',
1252 - toolSlug: params.slug,
1253 - message: summary.error,
1254 - });
1255 - }
1256 -
1257 - yield* spinner.stop(`Execution successful${executionSuccessSuffix(result)}`);
1258 - const inBandWarning = detectInBandWarning(result.data);
1259 - if (inBandWarning) {
1260 - yield* params.ui.log.warn(
1261 - `The tool executed successfully but the response may contain an error: ${inBandWarning}`
1262 - );
1263 - }
1264 - const output = yield* prepareExecuteOutput(params.slug, result, params.executeOutputDir);
1265 - if (output.kind === 'file') {
1266 - yield* params.ui.log.message(
1267 - `Response stored in ${output.summary.outputFilePath} (${describeStoredOutputSize(output.summary)})`
1268 - );
1269 - yield* writeExecuteStdout(params.ui, JSON.stringify(output.summary, ciRedactReplacer, 2));
1270 - yield* appendCliSessionHistory({
1271 - ...executeSessionHistoryScope(params.resolvedProject),
1272 - entry: {
1273 - command: 'execute',
1274 - status: 'success',
1275 - slug: params.slug,
1276 - arguments: params.args,
1277 - storedInFile: true,
1278 - outputFilePath: output.summary.outputFilePath,
1279 - tokenCount: output.summary.tokenCount,
1280 - sizeBytes: output.summary.sizeBytes,
1281 - logId: result.logId,
1282 - },
1283 - }).pipe(Effect.catch(() => Effect.void));
1284 - return;
1285 - }
1286 -
1287 - yield* writeExecuteStdout(params.ui, output.json);
1288 - yield* appendCliSessionHistory({
1289 - ...executeSessionHistoryScope(params.resolvedProject),
1290 - entry: {
1291 - command: 'execute',
1292 - status: 'success',
1293 - slug: params.slug,
1294 - arguments: params.args,
1295 - storedInFile: false,
1296 - logId: result.logId,
1297 - },
1298 - }).pipe(Effect.catch(() => Effect.void));
1299 - })
1300 - );
1301 - });
1302 -
1303 -const runToolsExecute = (params: RunToolsExecuteParams) =>
1304 - Effect.gen(function* () {
1305 - if (params.getSchema) {
1306 - const context = yield* resolveSchemaContext(params);
1307 - const definition = yield* getOrFetchToolInputDefinition(params.slug, {
1308 - orgId: context.resolvedProject.orgId,
1309 - projectId: context.resolvedProject.projectId,
1310 - }).pipe(
1311 - Effect.tapError(error =>
1312 - emitExecuteFailureTelemetry({
1313 - toolSlug: params.slug,
1314 - args: {},
1315 - error,
1316 - surface: params.surface,
1317 - projectMode: params.projectMode,
1318 - stage: 'schema_fetch',
1319 - projectScope: toolkitProjectScope(context.resolvedProject),
1320 - })
1321 - )
1322 - );
1323 - yield* emitCachedSchema(context.ui, params.slug, definition);
1324 - return;
1325 - }
1326 -
1327 - const context = yield* resolveExecuteContext(params);
1328 -
1329 - yield* runConnectedToolkitFailFast({
1330 - slug: params.slug,
1331 - surface: params.surface,
1332 - ui: context.ui,
1333 - resolvedProject: context.resolvedProject,
1334 - resolvedUserId: context.resolvedUserId,
1335 - skipConnectionCheck: params.skipConnectionCheck,
1336 - skipChecks: params.skipChecks,
1337 - });
1338 - yield* logToolDebug('execute_params', {
1339 - slug: params.slug,
1340 - userId: context.resolvedUserId,
1341 - connectedAccountId: context.selectedConnectedAccountId,
1342 - arguments: context.args,
1343 - projectId: context.resolvedProject.projectId,
1344 - orgId: context.resolvedProject.orgId,
1345 - });
1346 - yield* perfDebugLog('execute.prepare', {
1347 - slug: params.slug,
1348 - surface: params.surface,
1349 - projectMode: params.projectMode,
1350 - });
1351 - yield* runExecuteWithSpinner({
1352 - slug: params.slug,
1353 - surface: params.surface,
1354 - projectMode: params.projectMode,
1355 - dryRun: params.dryRun,
1356 - ui: context.ui,
1357 - executor: context.executor,
1358 - resolvedProject: context.resolvedProject,
1359 - args: context.args,
1360 - resolvedUserId: context.resolvedUserId,
1361 - executeParams: context.executeParams,
1362 - skipToolParamsCheck: params.skipToolParamsCheck,
1363 - skipChecks: params.skipChecks,
1364 - });
1365 - });
1366 -
1367 -export const parseParallelExecuteArgs = (
1368 - args: ReadonlyArray<string>,
1369 - config: {
1370 - readonly surface: 'root' | 'dev';
1371 - readonly projectMode: 'consumer' | 'developer';
1372 - readonly allowUserId: boolean;
1373 - readonly allowProjectName: boolean;
1374 - }
1375 -) =>
1376 - Effect.gen(function* () {
1377 - let getSchema = false;
1378 - let dryRun = false;
1379 - let skipConnectionCheck = false;
1380 - let skipToolParamsCheck = false;
1381 - let skipChecks = false;
1382 - let account = Option.none<string>();
1383 - let userId = Option.none<string>();
1384 - let projectName = Option.none<string>();
1385 - const specs: ParallelExecuteSpec[] = [];
1386 - let currentSpec: ParallelExecuteSpec | null = null;
1387 -
1388 - const pushCurrentSpec = () => {
1389 - if (!currentSpec) return;
1390 - specs.push(currentSpec);
1391 - currentSpec = null;
1392 - };
1393 -
1394 - const readValue = (token: string, index: number) => {
1395 - if (token.includes('=')) {
1396 - return Effect.succeed({
1397 - value: token.slice(token.indexOf('=') + 1),
1398 - nextIndex: index,
1399 - });
1400 - }
1401 -
1402 - const next = args[index + 1];
1403 - if (!next) {
1404 - return Effect.fail(invalidArguments(`Missing value for ${token}.`));
1405 - }
1406 - return Effect.succeed({ value: next, nextIndex: index + 1 });
1407 - };
1408 -
1409 - for (let i = 0; i < args.length; i += 1) {
1410 - const token = args[i];
1411 - if (!token) continue;
1412 -
1413 - const flagName = token.split('=')[0];
1414 - if (
1415 - CLI_DEBUG_FLAG_NAMES.some(name => flagName === `--${name}` || flagName === `--no-${name}`)
1416 - )
1417 - continue;
1418 - if (flagName === '--log-level') {
1419 - if (!token.includes('=')) i += 1;
1420 - continue;
1421 - }
1422 - // The framework supplies these values; this parser only preserves tool/data grouping.
1423 - if (
1424 - [
1425 - 'parallel',
1426 - 'get-schema',
1427 - 'dry-run',
1428 - 'skip-connection-check',
1429 - 'skip-tool-params-check',
1430 - 'skip-checks',
1431 - ].some(name => flagName === `--${name}` || flagName === `--no-${name}`) &&
1432 - (token !== flagName || flagName.startsWith('--no-'))
1433 - )
1434 - continue;
1435 - if (token === '--parallel' || token === '-p') {
1436 - continue;
1437 - }
1438 - if (token === '--get-schema') {
1439 - getSchema = true;
1440 - continue;
1441 - }
1442 - if (token === '--dry-run') {
1443 - dryRun = true;
1444 - continue;
1445 - }
1446 - if (token === '--skip-connection-check') {
1447 - skipConnectionCheck = true;
1448 - continue;
1449 - }
1450 - if (token === '--skip-tool-params-check') {
1451 - skipToolParamsCheck = true;
1452 - continue;
1453 - }
1454 - if (token === '--skip-checks') {
1455 - skipChecks = true;
1456 - continue;
1457 - }
1458 - if (token === '--account' || token.startsWith('--account=')) {
1459 - const parsed = yield* readValue(token, i);
1460 - if (currentSpec) {
1461 - currentSpec = {
1462 - slug: currentSpec.slug,
1463 - data: currentSpec.data,
1464 - account: Option.some(parsed.value),
1465 - };
1466 - } else {
1467 - account = Option.some(parsed.value);
1468 - }
1469 - i = parsed.nextIndex;
1470 - continue;
1471 - }
1472 - if (token === '--user-id' || token.startsWith('--user-id=')) {
1473 - if (!config.allowUserId) {
1474 - return yield* Effect.fail(
1475 - invalidArguments(`${token} is not supported for this execute command.`)
1476 - );
1477 - }
1478 - const parsed = yield* readValue(token, i);
1479 - userId = Option.some(parsed.value);
1480 - i = parsed.nextIndex;
1481 - continue;
1482 - }
1483 - if (token === '--project-name' || token.startsWith('--project-name=')) {
1484 - if (!config.allowProjectName) {
1485 - return yield* Effect.fail(
1486 - invalidArguments(`${token} is not supported for this execute command.`)
1487 - );
1488 - }
1489 - const parsed = yield* readValue(token, i);
1490 - projectName = Option.some(parsed.value);
1491 - i = parsed.nextIndex;
1492 - continue;
1493 - }
1494 - if (
1495 - token === '--data' ||
1496 - token === '-d' ||
1497 - token.startsWith('--data=') ||
1498 - token.startsWith('-d=')
1499 - ) {
1500 - if (!currentSpec) {
1501 - return yield* Effect.fail(
1502 - invalidArguments(
1503 - `Expected a tool slug before ${token}. Use: composio execute --parallel TOOL_SLUG -d '{}' TOOL_SLUG_2 -d '{}'.`
1504 - )
1505 - );
1506 - }
1507 - const parsed = yield* readValue(token, i);
1508 - currentSpec = {
1509 - slug: currentSpec.slug,
1510 - data: Option.some(parsed.value),
1511 - account: currentSpec.account,
1512 - };
1513 - i = parsed.nextIndex;
1514 - continue;
1515 - }
1516 - if (token.startsWith('-')) {
1517 - return yield* Effect.fail(
1518 - invalidArguments(`Unknown option for parallel execute: ${token}`)
1519 - );
1520 - }
1521 -
1522 - pushCurrentSpec();
1523 - currentSpec = {
1524 - slug: token,
1525 - data: Option.none(),
1526 - account,
1527 - };
1528 - }
1529 -
1530 - pushCurrentSpec();
1531 -
1532 - if (specs.length === 0) {
1533 - return yield* Effect.fail(
1534 - invalidArguments(
1535 - "No tool slugs were provided. Use: composio execute --parallel TOOL_SLUG -d '{}' TOOL_SLUG_2 -d '{}'."
1536 - )
1537 - );
1538 - }
1539 -
1540 - return {
1541 - specs,
1542 - userId,
1543 - projectName,
1544 - surface: config.surface,
1545 - projectMode: config.projectMode,
1546 - getSchema,
1547 - dryRun,
1548 - skipConnectionCheck,
1549 - skipToolParamsCheck,
1550 - skipChecks,
1551 - account,
1552 - } satisfies ParsedParallelExecuteArgs;
1553 - });
1554 -
1555 -const checkConnectedToolkitOrFail = (params: {
1556 - readonly slug: string;
1557 - readonly resolvedProject: ResolvedExecuteContext['resolvedProject'];
1558 - readonly resolvedUserId: string;
1559 - readonly skipConnectionCheck: boolean;
1560 - readonly skipChecks: boolean;
1561 -}) =>
1562 - Effect.gen(function* () {
1563 - if (params.skipConnectionCheck || params.skipChecks) return;
1564 - if (params.resolvedProject.projectType !== 'CONSUMER') return;
1565 -
1566 - yield* refreshConsumerConnectedToolkitsCache({
1567 - orgId: params.resolvedProject.orgId,
1568 - consumerUserId: params.resolvedUserId,
1569 - }).pipe(
1570 - Effect.catch(() => Effect.void),
1571 - Effect.forkDetach,
1572 - Effect.asVoid
1573 - );
1574 -
1575 - const toolkit = yield* toolkitFromToolSlug(
1576 - params.slug,
1577 - toolkitProjectScope(params.resolvedProject)
1578 - );
1579 - if (!toolkit) return;
1580 -
1581 - const cachedToolkits = yield* getFreshConsumerConnectedToolkitsFromCache({
1582 - orgId: params.resolvedProject.orgId,
1583 - consumerUserId: params.resolvedUserId,
1584 - });
1585 -
1586 - if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(toolkit)) {
1587 - return yield* new ToolExecutionError({
1588 - reason: 'connection_check',
1589 - toolSlug: params.slug,
1590 - message: `Toolkit "${toolkit}" is not connected for this user (cached within the last 5 minutes). If you just connected the account, use --skip-connection-check.`,
1591 - });
1592 - }
1593 - });
1594 -
1595 -const runParallelSchemaFetchFromParsed = (params: ParsedParallelExecuteArgs) =>
1596 - Effect.gen(function* () {
1597 - const contexts = yield* Effect.forEach(
1598 - params.specs,
1599 - () =>
1600 - resolveSchemaContext({
1601 - account: params.account,
1602 - projectName: params.projectName,
1603 - surface: params.surface,
1604 - projectMode: params.projectMode,
1605 - getSchema: params.getSchema,
1606 - dryRun: params.dryRun,
1607 - skipConnectionCheck: params.skipConnectionCheck,
1608 - skipToolParamsCheck: params.skipToolParamsCheck,
1609 - skipChecks: params.skipChecks,
1610 - }),
1611 - { concurrency: 'unbounded' }
1612 - );
1613 - const entries = contexts.map((context, index) => ({
1614 - context,
1615 - spec: params.specs[index]!,
1616 - }));
1617 -
1618 - const ui = contexts[0]?.ui;
1619 - const results = yield* Effect.forEach(
1620 - entries,
1621 - ({ context, spec }) =>
1622 - Effect.gen(function* () {
1623 - const definition = yield* getOrFetchToolInputDefinition(spec.slug, {
1624 - orgId: context.resolvedProject.orgId,
1625 - projectId: context.resolvedProject.projectId,
1626 - });
1627 - return {
1628 - slug: spec.slug,
1629 - successful: true,
1630 - version: definition.version,
1631 - schemaPath: definition.schemaPath,
1632 - inputSchema: normalizeFileUploadSchema(definition.schema),
1633 - } satisfies Extract<
1634 - ParallelExecuteResult,
1635 - { readonly inputSchema: Record<string, unknown> }
1636 - >;
1637 - }).pipe(
1638 - Effect.catch(error =>
1639 - toolkitFromToolSlug(spec.slug, toolkitProjectScope(context.resolvedProject)).pipe(
1640 - Effect.map(toolkit => {
1641 - const mapped = mapComposioError({ error, toolkit, toolSlug: spec.slug });
1642 - return {
1643 - slug: spec.slug,
1644 - successful: false,
1645 - error: mapped.message,
1646 - } satisfies Extract<ParallelExecuteResult, { readonly successful: false }>;
1647 - })
1648 - )
1649 - )
1650 - ),
1651 - { concurrency: 'unbounded' }
1652 - );
1653 -
1654 - if (ui) {
1655 - for (const result of results) {
1656 - if (!result.successful) {
1657 - yield* ui.log.error(`[${result.slug}] ${result.error}`);
1658 - continue;
1659 - }
1660 -
1661 - yield* ui.log.step(`[${result.slug}] Schema fetched: ${result.schemaPath}`);
1662 - }
1663 -
1664 - const successful = results.every(result => result.successful);
1665 - yield* ui.log.message(
1666 - `Parallel execute completed: ${results.filter(result => result.successful).length}/${results.length} successful`
1667 - );
1668 - yield* writeExecuteStdout(
1669 - ui,
1670 - JSON.stringify(
1671 - {
1672 - successful,
1673 - parallel: true,
1674 - results,
1675 - },
1676 - ciRedactReplacer,
1677 - 2
1678 - )
1679 - );
1680 - if (!successful) {
1681 - return yield* new ReportedToolExecutionError({
1682 - reason: 'parallel_failed',
1683 - message: 'One or more parallel tool executions failed.',
1684 - });
1685 - }
1686 - }
1687 - });
1688 -
1689 -const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
1690 - Effect.gen(function* () {
1691 - if (params.getSchema) {
1692 - return yield* runParallelSchemaFetchFromParsed(params);
1693 - }
1694 -
1695 - // Resolved once, so a test user's notice prints once; each tool still fails on its own
1696 - // input before it fails on a missing user.
1697 - const user = Effect.fromResult(yield* Effect.result(actingUser()));
1698 - const contexts = yield* Effect.forEach(
1699 - params.specs,
1700 - spec =>
1701 - resolveExecuteContext(
1702 - {
1703 - slug: spec.slug,
1704 - data: spec.data,
1705 - file: Option.none(),
1706 - account: spec.account,
1707 - projectName: params.projectName,
1708 - surface: params.surface,
1709 - projectMode: params.projectMode,
1710 - getSchema: params.getSchema,
1711 - dryRun: params.dryRun,
1712 - skipConnectionCheck: params.skipConnectionCheck,
1713 - skipToolParamsCheck: params.skipToolParamsCheck,
1714 - skipChecks: params.skipChecks,
1715 - },
1716 - user
1717 - ),
1718 - { concurrency: 'unbounded' }
1719 - );
1720 - const entries = contexts.map((context, index) => ({
1721 - context,
1722 - spec: params.specs[index]!,
1723 - }));
1724 -
1725 - const ui = contexts[0]?.ui;
1726 - const results = yield* Effect.forEach(
1727 - entries,
1728 - ({ context, spec }) =>
1729 - Effect.gen(function* () {
1730 - const toolSlug = spec.slug;
1731 -
1732 - yield* checkConnectedToolkitOrFail({
1733 - slug: toolSlug,
1734 - resolvedProject: context.resolvedProject,
1735 - resolvedUserId: context.resolvedUserId,
1736 - skipConnectionCheck: params.skipConnectionCheck,
1737 - skipChecks: params.skipChecks,
1738 - });
1739 -
1740 - if (params.dryRun) {
1741 - const definition = yield* checkDryRunArguments({
1742 - slug: toolSlug,
1743 - args: context.args,
1744 - projectScope: {
1745 - orgId: context.resolvedProject.orgId,
1746 - projectId: context.resolvedProject.projectId,
1747 - },
1748 - verificationDisabled: params.skipChecks || params.skipToolParamsCheck,
1749 - });
1750 - return {
1751 - successful: true,
1752 - dryRun: true,
1753 - slug: toolSlug,
1754 - arguments: context.args,
1755 - userId: context.resolvedUserId,
1756 - schemaPath: definition?.schemaPath,
1757 - schemaVersion: definition?.version,
1758 - } satisfies DryRunSummary;
1759 - }
1760 -
1761 - if (!params.skipChecks && !params.skipToolParamsCheck) {
1762 - const definition = yield* getOrFetchToolInputDefinition(toolSlug, {
1763 - orgId: context.resolvedProject.orgId,
1764 - projectId: context.resolvedProject.projectId,
1765 - });
1766 - yield* validateToolInputArgumentsWithDefinition(toolSlug, context.args, definition);
1767 - }
1768 -
1769 - const result = yield* context.executor.execute(toolSlug, context.executeParams);
1770 - if (!result.successful) {
1771 - const failed = {
1772 - slug: toolSlug,
1773 - successful: false as const,
1774 - error: result.error ?? 'Execution failed.',
1775 - logId: result.logId,
1776 - };
1777 - if (!result.instantCharge) return failed;
1778 - return { ...failed, instantCharge: result.instantCharge };
1779 - }
1780 -
1781 - const output = yield* prepareExecuteOutput(toolSlug, result, context.executeOutputDir);
1782 - if (output.kind === 'file') {
1783 - return {
1784 - slug: toolSlug,
1785 - ...output.summary,
1786 - };
1787 - }
1788 -
1789 - return {
1790 - slug: toolSlug,
1791 - ...result,
1792 - };
1793 - }).pipe(
1794 - Effect.catch(error =>
1795 - toolkitFromToolSlug(spec.slug, toolkitProjectScope(context.resolvedProject)).pipe(
1796 - Effect.map(toolkit => {
1797 - const mapped = mapComposioError({ error, toolkit, toolSlug: spec.slug });
1798 - return {
1799 - slug: spec.slug,
1800 - successful: false,
1801 - error: mapped.message,
1802 - } satisfies ParallelExecuteResult;
1803 - })
1804 - )
1805 - )
1806 - ),
1807 - { concurrency: 'unbounded' }
1808 - );
1809 -
1810 - if (ui) {
1811 - for (const result of results) {
1812 - if (!result.successful) {
1813 - const logId =
1814 - 'logId' in result && typeof result.logId === 'string' && result.logId.length > 0
1815 - ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
1816 - : '';
1817 - yield* ui.log.error(`[${result.slug}] ${result.error}${logId}`);
1818 - continue;
1819 - }
1820 -
1821 - if ('dryRun' in result && result.dryRun) {
1822 - yield* ui.log.step(`[${result.slug}] Dry run successful`);
1823 - continue;
1824 - }
1825 -
1826 - if ('inputSchema' in result) {
1827 - yield* ui.log.step(`[${result.slug}] Schema fetched: ${result.schemaPath}`);
1828 - continue;
1829 - }
1830 -
1831 - if ('storedInFile' in result && result.storedInFile) {
1832 - yield* ui.log.step(
1833 - `[${result.slug}] Response stored in ${result.outputFilePath} (${describeStoredOutputSize(result)})`
1834 - );
1835 - continue;
1836 - }
1837 -
1838 - yield* ui.log.step(
1839 - `[${result.slug}] Execution successful${executionSuccessSuffix(result)}`
1840 - );
1841 - if ('data' in result) {
1842 - yield* ui.note(serializeExecuteOutput(result), `Response: ${result.slug}`);
1843 - }
1844 - }
1845 - }
1846 -
1847 - const successful = results.every(result => result.successful);
1848 - if (ui) {
1849 - yield* ui.log.message(
1850 - `Parallel execute completed: ${results.filter(result => result.successful).length}/${results.length} successful`
1851 - );
1852 - yield* writeExecuteStdout(
1853 - ui,
1854 - JSON.stringify(
1855 - {
1856 - successful,
1857 - parallel: true,
1858 - results,
1859 - },
1860 - ciRedactReplacer,
1861 - 2
1862 - )
1863 - );
1864 - }
1865 -
1866 - if (!successful) {
1867 - return yield* new ReportedToolExecutionError({
1868 - reason: 'parallel_failed',
1869 - message: 'One or more parallel tool executions failed.',
1870 - });
1871 - }
1872 - });
1873 -
1874 -// Flags that can precede the command name and take the next token as their value
1875 -// (`$default.cmd.ts`, `dev.cmd.ts`), so a value equal to the command name is not the command.
1876 -const VALUE_FLAGS_BEFORE_COMMAND = new Set([
1877 - '--log-level',
1878 - '--mode',
1879 - '--user-id',
1880 - '--project-name',
1881 -]);
1882 -
1883 -/** The index of the command name in argv, skipping a flag value that spells the same word. */
1884 -const commandNameIndex = (argv: ReadonlyArray<string>, name: string) =>
1885 - argv.findIndex(
1886 - (token, index) => token === name && !VALUE_FLAGS_BEFORE_COMMAND.has(argv[index - 1] ?? '')
1887 - );
1888 -
1889 -const runParallelFromCommand = (config: {
1890 - readonly surface: 'root' | 'dev';
1891 - readonly projectMode: 'consumer' | 'developer';
1892 - readonly getSchema: boolean;
1893 - readonly dryRun: boolean;
1894 - readonly skipConnectionCheck: boolean;
1895 - readonly skipToolParamsCheck: boolean;
1896 - readonly skipChecks: boolean;
1897 -}) =>
1898 - Effect.gen(function* () {
1899 - const argv = yield* ExecuteInvocationArgs;
1900 - const name = config.surface === 'root' ? 'execute' : 'playground-execute';
1901 - const tail = argv.slice(commandNameIndex(argv, name) + 1);
1902 - const parsed = yield* parseParallelExecuteArgs(tail, {
1903 - ...config,
1904 - allowUserId: config.surface === 'dev',
1905 - allowProjectName: config.surface === 'dev',
1906 - });
1907 - // The tail starts after the command name, so the `dev` group's shared flags given before
1908 - // it reach the command only through the surface; the tail's own win.
1909 - const surface = yield* CommandSurface;
1910 - const userId = Option.orElse(parsed.userId, () => surface.userId);
1911 - const projectName = Option.orElse(parsed.projectName, () => surface.projectName);
1912 - return yield* runParallelToolsExecuteFromParsed({
1913 - ...parsed,
1914 - ...config,
1915 - userId,
1916 - projectName,
1917 - }).pipe(
1918 - Effect.provideService(CommandSurface, CommandSurface.of({ ...surface, userId, projectName }))
1919 - );
1920 - });
1921 -
1922 -const executeExamples = [
1923 - {
1924 - command:
1925 - 'composio execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", subject: "Hello", body: "World" }\'',
1926 - description: 'Send an email',
1927 - },
1928 - {
1929 - command:
1930 - 'composio execute GITHUB_CREATE_ISSUE --account work -d \'{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }\'',
1931 - description: 'Create a GitHub issue with a named account',
1932 - },
1933 - {
1934 - command:
1935 - 'composio execute SLACK_SEND_MESSAGE --dry-run -d \'{ channel: "general", markdown_text: "Hello team" }\'',
1936 - description: 'Preview what a tool call would send without executing',
1937 - },
1938 - {
1939 - command: 'composio execute GMAIL_SEND_EMAIL --get-schema',
1940 - description: 'Print the tool input schema as JSON (--help shows command options)',
1941 - },
1942 - {
1943 - command: 'composio execute GITHUB_CREATE_ISSUE -d @issue.json',
1944 - description: 'Read arguments from a file',
1945 - },
1946 - {
1947 - command:
1948 - 'composio execute -p GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com" }\' GITHUB_CREATE_AN_ISSUE -d \'{ owner: "acme", repo: "app", title: "Bug" }\'',
1949 - description: 'Execute multiple tools concurrently',
1950 - },
1951 -];
1952 -
1953 -export const rootToolsCmd$Execute = Command.make(
1954 - 'execute',
1955 - {
1956 - slug,
1957 - additionalSlugs,
1958 - parallel,
1959 - data,
1960 - file,
1961 - account: accountOption,
1962 - getSchema,
1963 - dryRun,
1964 - skipConnectionCheck,
1965 - skipToolParamsCheck,
1966 - skipChecks,
1967 - },
1968 - ({
1969 - slug,
1970 - additionalSlugs,
1971 - parallel,
1972 - data,
1973 - file,
1974 - account,
1975 - getSchema,
1976 - dryRun,
1977 - skipConnectionCheck,
1978 - skipToolParamsCheck,
1979 - skipChecks,
1980 - }) =>
1981 - Effect.gen(function* () {
1982 - if (parallel) {
1983 - return yield* runParallelFromCommand({
1984 - surface: 'root',
1985 - projectMode: 'consumer',
1986 - getSchema,
1987 - dryRun,
1988 - skipConnectionCheck,
1989 - skipToolParamsCheck,
1990 - skipChecks,
1991 - });
1992 - }
1993 - if (additionalSlugs.length > 0) {
1994 - return yield* invalidArguments('Additional tool slugs require --parallel.');
1995 - }
1996 - return yield* runToolsExecute({
1997 - slug,
1998 - data,
1999 - file,
2000 - account,
2001 - projectName: Option.none(),
2002 - surface: 'root',
2003 - projectMode: 'consumer',
2004 - getSchema,
2005 - dryRun,
2006 - skipConnectionCheck,
2007 - skipToolParamsCheck,
2008 - skipChecks,
2009 - });
2010 - })
2011 -).pipe(
2012 - Command.withDescription(
2013 - 'Execute a tool by slug. Validates inputs against cached schemas and checks connections\nautomatically — just try it and it will tell you what to fix.'
2014 - ),
2015 - Command.withShortDescription(
2016 - 'Execute a tool by slug. Validates inputs against cached schemas and checks connections'
2017 - ),
2018 - Command.withExamples(executeExamples),
2019 - withCommandMeta({ requiresLogin: true })
2020 -);
2021 -
2022 -export const devToolsCmd$Execute = Command.make(
2023 - 'playground-execute',
2024 - {
2025 - slug,
2026 - additionalSlugs,
2027 - parallel,
2028 - data,
2029 - file,
2030 - account: accountOption,
2031 - getSchema,
2032 - dryRun,
2033 - skipConnectionCheck,
2034 - skipToolParamsCheck,
2035 - skipChecks,
2036 - },
2037 - ({
2038 - slug,
2039 - additionalSlugs,
2040 - parallel,
2041 - data,
2042 - file,
2043 - account,
2044 - getSchema,
2045 - dryRun,
2046 - skipConnectionCheck,
2047 - skipToolParamsCheck,
2048 - skipChecks,
2049 - }) =>
2050 - Effect.gen(function* () {
2051 - const { projectName } = yield* CommandSurface;
2052 - if (parallel) {
2053 - return yield* runParallelFromCommand({
2054 - surface: 'dev',
2055 - projectMode: 'developer',
2056 - getSchema,
2057 - dryRun,
2058 - skipConnectionCheck,
2059 - skipToolParamsCheck,
2060 - skipChecks,
2061 - });
2062 - }
2063 - if (additionalSlugs.length > 0) {
2064 - return yield* invalidArguments('Additional tool slugs require --parallel.');
2065 - }
2066 - return yield* runToolsExecute({
2067 - slug,
2068 - data,
2069 - file,
2070 - account,
2071 - projectName,
2072 - surface: 'dev',
2073 - projectMode: 'developer',
2074 - getSchema,
2075 - dryRun,
2076 - skipConnectionCheck,
2077 - skipToolParamsCheck,
2078 - skipChecks,
2079 - });
2080 - })
2081 -).pipe(
2082 - Command.withDescription(
2083 - 'Test tool executions against playground users using your developer project auth configs.\nUses --user-id when provided, otherwise falls back to your local or global playground test user id.\nArguments are validated against cached tool schemas in `~/.composio/tool_definitions/` when available.'
2084 - ),
2085 - Command.withShortDescription(
2086 - 'Test tool executions against playground users using your developer project auth configs.'
2087 - ),
2088 - Command.withExamples(
2089 - executeExamples.map(example => ({
2090 - ...example,
2091 - command: example.command.replace('composio execute', 'composio dev playground-execute'),
2092 - }))
2093 - ),
2094 - withCommandMeta({ requiresLogin: true })
2095 -);
ts/packages/cli/src/commands/tools/execute/tools.execute.arguments.ts new
+82
@@ -0,0 +1,82 @@
1 +import { Effect, Option, Result } from 'effect';
2 +import { resolveOptionalTextInput } from 'src/effects/resolve-optional-text-input';
3 +import {
4 + findFileUploadablePaths,
5 + schemaHasFileUploadable,
6 + setArgumentAt,
7 +} from 'src/services/tool-file-uploads';
8 +import { isPlainRecord, parseJsonRecord } from 'src/utils/parse-json';
9 +import { invalidArguments, ToolExecutionError } from './tools.execute.errors';
10 +
11 +export const resolveInput = (input: Option.Option<string>) =>
12 + resolveOptionalTextInput(input, {
13 + // Default to empty object when no data provided (e.g. tools with no required args)
14 + missingValue: '{}',
15 + });
16 +
17 +export const parseArguments = (raw: string) =>
18 + Effect.fromResult(
19 + parseJsonRecord(raw).pipe(
20 + Result.mapError(error =>
21 + invalidArguments(
22 + error.reason === 'not-a-record'
23 + ? 'Expected a JSON object for tool arguments, e.g. -d \'{ "key": "value" }\''
24 + : 'Invalid JSON input. Provide JSON or a JS-style object literal, e.g. -d \'{ "key": "value" }\''
25 + )
26 + )
27 + )
28 + );
29 +
30 +const hasNestedKey = (
31 + record: Record<string, unknown>,
32 + pathParts: ReadonlyArray<string | number>
33 +): boolean => {
34 + let current: unknown = record;
35 + for (const key of pathParts) {
36 + if (Array.isArray(current) && typeof key === 'number' && key < current.length) {
37 + current = current[key];
38 + } else if (isPlainRecord(current) && typeof key === 'string' && Object.hasOwn(current, key)) {
39 + current = current[key];
40 + } else return false;
41 + }
42 + return true;
43 +};
44 +
45 +export const injectSingleFileArgument = (params: {
46 + readonly slug: string;
47 + readonly args: Record<string, unknown>;
48 + readonly filePath: string;
49 + readonly schema: Record<string, unknown>;
50 +}) =>
51 + Effect.gen(function* () {
52 + const uploadablePaths = findFileUploadablePaths(params.schema, [], params.args);
53 +
54 + if (uploadablePaths.length === 0) {
55 + return yield* new ToolExecutionError({
56 + reason: 'file_input',
57 + toolSlug: params.slug,
58 + message: schemaHasFileUploadable(params.schema)
59 + ? `Tool "${params.slug}" has no matching file_uploadable input in the supplied arguments. Supply the target array item with -d, or remove --file.`
60 + : `Tool "${params.slug}" has no file_uploadable input. Remove --file or pass JSON via -d.`,
61 + });
62 + }
63 +
64 + if (uploadablePaths.length > 1) {
65 + return yield* new ToolExecutionError({
66 + reason: 'file_input',
67 + toolSlug: params.slug,
68 + message: `Tool "${params.slug}" has multiple file_uploadable inputs (${uploadablePaths.map(parts => parts.join('.')).join(', ')}). Pass the target field explicitly with -d instead of --file.`,
69 + });
70 + }
71 +
72 + const targetPath = uploadablePaths[0] ?? [];
73 + if (hasNestedKey(params.args, targetPath)) {
74 + return yield* new ToolExecutionError({
75 + reason: 'file_input',
76 + toolSlug: params.slug,
77 + message: `Cannot use --file because "${targetPath.join('.')}" is already set in -d. Remove that field or omit --file.`,
78 + });
79 + }
80 +
81 + return setArgumentAt(params.args, targetPath, params.filePath);
82 + });
ts/packages/cli/src/commands/tools/execute/tools.execute.cmd.ts new
+144
@@ -0,0 +1,144 @@
1 +import { Argument, Command, Flag } from 'effect/cli';
2 +import { withCommandMeta } from 'src/invocation/command-identity';
3 +import { runToolsExecuteCommand } from './tools.execute.handler';
4 +
5 +const slug = Argument.String('slug').pipe(
6 + Argument.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')
7 +);
8 +
9 +const additionalSlugs = Argument.String('additional-slugs').pipe(
10 + Argument.variadic(),
11 + Argument.withDescription('Additional tool slugs for --parallel')
12 +);
13 +const parallel = Flag.Boolean('parallel').pipe(
14 + Flag.withAlias('p'),
15 + Flag.withDefault(false),
16 + Flag.withDescription('Execute repeated tool slug/data groups concurrently')
17 +);
18 +
19 +const data = Flag.String('data').pipe(
20 + Flag.withAlias('d'),
21 + Flag.withDescription('JSON arguments, @file, or - for stdin'),
22 + Flag.optional
23 +);
24 +const file = Flag.String('file').pipe(
25 + Flag.withDescription('Inject a local file path into the single file_uploadable input'),
26 + Flag.optional
27 +);
28 +const accountOption = Flag.String('account').pipe(
29 + Flag.withDescription(
30 + 'Connected account selector for the inferred toolkit. Matches alias, word_id, or connected account id.'
31 + ),
32 + Flag.optional
33 +);
34 +
35 +const getSchema = Flag.Boolean('get-schema').pipe(
36 + Flag.withDescription('Fetch and print the CLI-facing input schema without executing'),
37 + Flag.withDefault(false)
38 +);
39 +const dryRun = Flag.Boolean('dry-run').pipe(
40 + Flag.withDescription('Validate and preview the tool call without executing'),
41 + Flag.withDefault(false)
42 +);
43 +const skipConnectionCheck = Flag.Boolean('skip-connection-check').pipe(
44 + Flag.withDescription('Skip the connected-account check'),
45 + Flag.withDefault(false)
46 +);
47 +const skipToolParamsCheck = Flag.Boolean('skip-tool-params-check').pipe(
48 + Flag.withDescription('Skip input validation against cached schema'),
49 + Flag.withDefault(false)
50 +);
51 +const skipChecks = Flag.Boolean('skip-checks').pipe(
52 + Flag.withDescription('Skip both connection and input validation checks'),
53 + Flag.withDefault(false)
54 +);
55 +
56 +const executeExamples = [
57 + {
58 + command:
59 + 'composio execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", subject: "Hello", body: "World" }\'',
60 + description: 'Send an email',
61 + },
62 + {
63 + command:
64 + 'composio execute GITHUB_CREATE_ISSUE --account work -d \'{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }\'',
65 + description: 'Create a GitHub issue with a named account',
66 + },
67 + {
68 + command:
69 + 'composio execute SLACK_SEND_MESSAGE --dry-run -d \'{ channel: "general", markdown_text: "Hello team" }\'',
70 + description: 'Preview what a tool call would send without executing',
71 + },
72 + {
73 + command: 'composio execute GMAIL_SEND_EMAIL --get-schema',
74 + description: 'Print the tool input schema as JSON (--help shows command options)',
75 + },
76 + {
77 + command: 'composio execute GITHUB_CREATE_ISSUE -d @issue.json',
78 + description: 'Read arguments from a file',
79 + },
80 + {
81 + command:
82 + 'composio execute -p GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com" }\' GITHUB_CREATE_AN_ISSUE -d \'{ owner: "acme", repo: "app", title: "Bug" }\'',
83 + description: 'Execute multiple tools concurrently',
84 + },
85 +];
86 +
87 +export const rootToolsCmd$Execute = Command.make(
88 + 'execute',
89 + {
90 + slug,
91 + additionalSlugs,
92 + parallel,
93 + data,
94 + file,
95 + account: accountOption,
96 + getSchema,
97 + dryRun,
98 + skipConnectionCheck,
99 + skipToolParamsCheck,
100 + skipChecks,
101 + },
102 + runToolsExecuteCommand
103 +).pipe(
104 + Command.withDescription(
105 + 'Execute a tool by slug. Validates inputs against cached schemas and checks connections\nautomatically — just try it and it will tell you what to fix.'
106 + ),
107 + Command.withShortDescription(
108 + 'Execute a tool by slug. Validates inputs against cached schemas and checks connections'
109 + ),
110 + Command.withExamples(executeExamples),
111 + withCommandMeta({ requiresLogin: true })
112 +);
113 +
114 +export const devToolsCmd$Execute = Command.make(
115 + 'playground-execute',
116 + {
117 + slug,
118 + additionalSlugs,
119 + parallel,
120 + data,
121 + file,
122 + account: accountOption,
123 + getSchema,
124 + dryRun,
125 + skipConnectionCheck,
126 + skipToolParamsCheck,
127 + skipChecks,
128 + },
129 + runToolsExecuteCommand
130 +).pipe(
131 + Command.withDescription(
132 + 'Test tool executions against playground users using your developer project auth configs.\nUses --user-id when provided, otherwise falls back to your local or global playground test user id.\nArguments are validated against cached tool schemas in `~/.composio/tool_definitions/` when available.'
133 + ),
134 + Command.withShortDescription(
135 + 'Test tool executions against playground users using your developer project auth configs.'
136 + ),
137 + Command.withExamples(
138 + executeExamples.map(example => ({
139 + ...example,
140 + command: example.command.replace('composio execute', 'composio dev playground-execute'),
141 + }))
142 + ),
143 + withCommandMeta({ requiresLogin: true })
144 +);
ts/packages/cli/src/commands/tools/execute/tools.execute.context.ts new
+180
@@ -0,0 +1,180 @@
1 +import { Effect, Option } from 'effect';
2 +import { actingUser } from 'src/commands/surface';
3 +import { APP_CONFIG } from 'src/config';
4 +import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
5 +import { resolveCliSessionArtifacts } from 'src/services/cli-session-artifacts';
6 +import { resolveCommandProject } from 'src/services/command-project';
7 +import { ComposioClientSingleton } from 'src/services/composio-clients';
8 +import type { ToolkitProjectScope } from 'src/services/composio-clients';
9 +import { resolveConnectedAccountForToolkit } from 'src/services/connected-account-selection';
10 +import { resolveConsumerExecutionTransport } from 'src/services/dashboard-tool-execution';
11 +import { TerminalUI } from 'src/services/terminal-ui';
12 +import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
13 +import { ToolsExecutor } from 'src/services/tools-executor';
14 +import type { ToolExecuteParams } from 'src/services/tools-executor';
15 +import { injectSingleFileArgument, parseArguments, resolveInput } from './tools.execute.arguments';
16 +
17 +export type RunToolsExecuteParams = {
18 + slug: string;
19 + data: Option.Option<string>;
20 + file: Option.Option<string>;
21 + account: Option.Option<string>;
22 + projectName: Option.Option<string>;
23 + surface: 'root' | 'dev';
24 + projectMode: 'consumer' | 'developer';
25 + getSchema: boolean;
26 + dryRun: boolean;
27 + skipConnectionCheck: boolean;
28 + skipToolParamsCheck: boolean;
29 + skipChecks: boolean;
30 +};
31 +
32 +export type SharedRunToolsExecuteParams = Omit<RunToolsExecuteParams, 'slug' | 'data' | 'file'>;
33 +
34 +export type ResolvedExecuteContext = {
35 + readonly ui: TerminalUI;
36 + readonly executor: ToolsExecutor;
37 + readonly resolvedProject: {
38 + readonly orgId: string;
39 + readonly projectId: string;
40 + readonly projectType: 'CONSUMER' | 'DEVELOPER';
41 + readonly consumerUserId?: string;
42 + };
43 + readonly args: Record<string, unknown>;
44 + readonly resolvedUserId: string;
45 + readonly selectedConnectedAccountId?: string;
46 + readonly executeParams: ToolExecuteParams;
47 + readonly executeOutputDir?: string;
48 +};
49 +
50 +/**
51 + * The resolved project as toolkit resolution needs it: custom toolkits are
52 + * listed per project, and it has to be the project execute runs against.
53 + */
54 +export const toolkitProjectScope = (resolvedProject: ToolkitProjectScope): ToolkitProjectScope => ({
55 + orgId: resolvedProject.orgId,
56 + projectId: resolvedProject.projectId,
57 +});
58 +
59 +type ResolvedSchemaContext = {
60 + readonly ui: TerminalUI;
61 + readonly resolvedProject: {
62 + readonly orgId: string;
63 + readonly projectId: string;
64 + readonly projectType: 'CONSUMER' | 'DEVELOPER';
65 + readonly consumerUserId?: string;
66 + };
67 +};
68 +
69 +export const resolveExecuteContext = (
70 + params: RunToolsExecuteParams,
71 + /** The acting user; `--parallel` resolves it once for all its tools. */
72 + user: ReturnType<typeof actingUser> = actingUser()
73 +) =>
74 + Effect.gen(function* () {
75 + const ui = yield* TerminalUI;
76 + const executor = yield* ToolsExecutor;
77 + const input = (yield* resolveInput(params.data)) ?? '{}';
78 + const parsedArgs = yield* parseArguments(input);
79 + const runOutputDirectory = yield* APP_CONFIG.RUN_OUTPUT_DIR;
80 +
81 + const { userId: resolvedUserId, project: resolvedProject } = yield* user;
82 + const clientSingleton = yield* ComposioClientSingleton;
83 + const client = yield* clientSingleton.getFor({
84 + orgId: resolvedProject.orgId,
85 + projectId: resolvedProject.projectId,
86 + });
87 + const toolkitSlug = yield* toolkitFromToolSlug(
88 + params.slug,
89 + toolkitProjectScope(resolvedProject)
90 + );
91 + const selectedConnectedAccountId = yield* resolveConnectedAccountForToolkit({
92 + client,
93 + toolkitSlug,
94 + userId: resolvedUserId,
95 + selector: params.account,
96 + });
97 + const args = Option.isSome(params.file)
98 + ? yield* getOrFetchToolInputDefinition(params.slug, {
99 + orgId: resolvedProject.orgId,
100 + projectId: resolvedProject.projectId,
101 + }).pipe(
102 + Effect.flatMap(definition =>
103 + injectSingleFileArgument({
104 + slug: params.slug,
105 + args: parsedArgs,
106 + filePath: Option.getOrThrow(params.file),
107 + schema: definition.schema,
108 + })
109 + )
110 + )
111 + : parsedArgs;
112 + const executeOutputDir =
113 + runOutputDirectory ||
114 + Option.getOrUndefined(
115 + yield* resolveCliSessionArtifacts({
116 + orgId: resolvedProject.projectType === 'CONSUMER' ? resolvedProject.orgId : undefined,
117 + consumerUserId:
118 + resolvedProject.projectType === 'CONSUMER' ? resolvedProject.consumerUserId : undefined,
119 + }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
120 + );
121 +
122 + // Root `execute` (the consumer surface, which is also what `composio run`
123 + // spawns) goes through the Dashboard; `dev playground-execute` stays on the
124 + // backend. The one exception is a backend URL overridden without a
125 + // matching `COMPOSIO_WEB_URL`: the key is never sent to another
126 + // deployment's Dashboard.
127 + const executesViaDashboard =
128 + params.surface === 'root' && (yield* resolveConsumerExecutionTransport) === 'dashboard';
129 +
130 + return {
131 + ui,
132 + executor,
133 + resolvedProject,
134 + args,
135 + resolvedUserId,
136 + selectedConnectedAccountId,
137 + executeOutputDir,
138 + executeParams: {
139 + userId: resolvedUserId,
140 + target: executesViaDashboard
141 + ? { kind: 'dashboard', orgId: resolvedProject.orgId }
142 + : { kind: 'backend' },
143 + arguments: args,
144 + client,
145 + projectScope: {
146 + orgId: resolvedProject.orgId,
147 + projectId: resolvedProject.projectId,
148 + },
149 + connectedAccounts:
150 + toolkitSlug && selectedConnectedAccountId
151 + ? {
152 + [toolkitSlug]: selectedConnectedAccountId,
153 + }
154 + : undefined,
155 + cacheScope:
156 + resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
157 + ? {
158 + orgId: resolvedProject.orgId,
159 + projectId: resolvedProject.projectId,
160 + consumerUserId: resolvedProject.consumerUserId,
161 + }
162 + : undefined,
163 + },
164 + } satisfies ResolvedExecuteContext;
165 + });
166 +
167 +export const resolveSchemaContext = (params: SharedRunToolsExecuteParams) =>
168 + Effect.gen(function* () {
169 + const resolvedProject = yield* resolveCommandProject({
170 + mode: params.projectMode,
171 + projectName:
172 + params.surface === 'root' ? undefined : Option.getOrUndefined(params.projectName),
173 + });
174 + const ui = yield* TerminalUI;
175 +
176 + return {
177 + ui,
178 + resolvedProject,
179 + } satisfies ResolvedSchemaContext;
180 + });
ts/packages/cli/src/commands/tools/execute/tools.execute.debug.ts new
+4
@@ -0,0 +1,4 @@
1 +import { makePerfDebugLogger } from 'src/services/runtime-debug-logger';
2 +
3 +// One logger for the whole command, so every perf line measures from the same start.
4 +export const perfDebugLog = makePerfDebugLogger();
ts/packages/cli/src/commands/tools/execute/tools.execute.errors.ts new
+42
@@ -0,0 +1,42 @@
1 +import { Data, Runtime } from 'effect';
2 +import { commandInputError } from 'src/commands/errors';
3 +import { ExpectedFailure } from 'src/effects/expected-failure';
4 +
5 +// Also raised by the hand-rolled `--parallel` mini-parser (`parseParallelExecuteArgs` in `tools.execute.parallel.ts`).
6 +export const invalidArguments = commandInputError('execute');
7 +
8 +// The reasons below are the ones this command constructs each error with; TypeScript cannot infer a
9 +// union from scattered constructor calls, so a new reason is added here next to its first use.
10 +
11 +/**
12 + * `composio execute` cannot run the tool as invoked: a `--file` the tool cannot take, or (with
13 + * `--parallel`) a toolkit the user has not connected. An expected failure: the invocation prints
14 + * the message and exits 1.
15 + */
16 +export class ToolExecutionError extends Data.TaggedError('ToolExecutionError')<{
17 + readonly reason: 'file_input' | 'connection_check';
18 + readonly message: string;
19 + readonly toolSlug?: string;
20 +}> {
21 + get [ExpectedFailure]() {
22 + return true;
23 + }
24 +}
25 +
26 +/**
27 + * A failed execution whose result is already on stdout as `{ "successful": false, ... }`.
28 + * The runtime prints nothing more for it (`[Runtime.errorReported]` is false) and exits 1.
29 + */
30 +export class ReportedToolExecutionError extends Data.TaggedError('ReportedToolExecutionError')<{
31 + readonly reason: 'connection_check' | 'execution_failed' | 'parallel_failed';
32 + readonly message: string;
33 + readonly toolSlug?: string;
34 +}> {
35 + get [Runtime.errorReported]() {
36 + return false;
37 + }
38 +
39 + get [Runtime.errorExitCode]() {
40 + return 1;
41 + }
42 +}
ts/packages/cli/src/commands/tools/execute/tools.execute.failure.ts new
+289
@@ -0,0 +1,289 @@
1 +import { Effect } from 'effect';
2 +import { trackCliCodactFailureEffect, trackCliEventEffect } from 'src/analytics/dispatch';
3 +import {
4 + getToolExecuteFailedEvent,
5 + getToolExecuteToolNotFoundEvent,
6 + getToolExecuteValidationFailedEvent,
7 + isMaybeToolValidationError,
8 + isMaybeToolNotFoundError,
9 +} from 'src/analytics/events';
10 +import * as constants from 'src/constants';
11 +import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
12 +import type { ToolkitProjectScope } from 'src/services/composio-clients';
13 +import {
14 + ComposioNoActiveConnectionError,
15 + mapComposioError,
16 + normalizeCliError,
17 +} from 'src/services/composio-error-overrides';
18 +import { cliInvocationContext } from 'src/services/runtime-cli-context';
19 +import type { TerminalUI } from 'src/services/terminal-ui';
20 +import { ToolInputValidationError } from 'src/services/tool-input-validation';
21 +import { connectionTips, formatUnknownObject, redactRequestId } from './tools.execute.format';
22 +
23 +export const emitExecuteFailureTelemetry = (params: {
24 + readonly toolSlug: string;
25 + readonly args: Record<string, unknown>;
26 + readonly error: unknown;
27 + readonly surface: 'root' | 'dev';
28 + readonly projectMode: 'consumer' | 'developer';
29 + readonly stage: 'schema_fetch' | 'dry_run' | 'validation' | 'execution';
30 + readonly logId?: string;
31 + readonly mappedError?: ReturnType<typeof mapComposioError>;
32 + readonly projectScope?: ToolkitProjectScope;
33 +}) =>
34 + Effect.gen(function* () {
35 + const toolkitSlug = yield* toolkitFromToolSlug(params.toolSlug, params.projectScope);
36 + const { invocationOrigin } = yield* cliInvocationContext;
37 + const normalized = params.mappedError?.normalized ?? normalizeCliError(params.error);
38 + const failureOrigin: 'fast_fail' | 'main_endpoint' =
39 + normalized instanceof ToolInputValidationError || params.stage !== 'execution'
40 + ? 'fast_fail'
41 + : 'main_endpoint';
42 +
43 + if (normalized instanceof ToolInputValidationError) {
44 + yield* trackCliEventEffect(
45 + getToolExecuteValidationFailedEvent({
46 + toolSlug: params.toolSlug,
47 + toolkitSlug,
48 + args: params.args,
49 + error: normalized,
50 + invocationOrigin,
51 + surface: params.surface,
52 + projectMode: params.projectMode,
53 + stage: params.stage === 'dry_run' ? 'dry_run' : 'validation',
54 + failureOrigin,
55 + logId: params.logId,
56 + })
57 + );
58 + yield* trackCliCodactFailureEffect({
59 + failureType: 'wrong_tool_input_param',
60 + toolInfo: {
61 + ...(toolkitSlug ? { toolkit: toolkitSlug } : {}),
62 + },
63 + ctx: {
64 + tool_slug: params.toolSlug,
65 + issues: [...normalized.issues].slice(0, 50),
66 + schema_path: normalized.schemaPath,
67 + stage: params.stage === 'dry_run' ? 'dry_run' : 'validation',
68 + },
69 + session: {
70 + source: 'cli',
71 + command_path: params.surface === 'root' ? 'execute' : 'dev playground-execute',
72 + project_mode: params.projectMode,
73 + surface: params.surface,
74 + cli_version: constants.APP_VERSION,
75 + },
76 + });
77 + return;
78 + }
79 +
80 + const mapped =
81 + params.mappedError ??
82 + mapComposioError({
83 + error: params.error,
84 + toolkit: toolkitSlug,
85 + toolSlug: params.toolSlug,
86 + });
87 + const apiDetails = mapped.apiDetails;
88 + const message = mapped.message;
89 + const errorSlug = mapped.slugValue;
90 + const status = apiDetails?.status;
91 + const apiCode = apiDetails?.code;
92 + const isNoConnectionError =
93 + normalized instanceof ComposioNoActiveConnectionError || Boolean(mapped.override);
94 +
95 + const isValidationError = isMaybeToolValidationError({ message, errorSlug, apiCode });
96 + const executionStage = params.stage === 'validation' ? 'execution' : params.stage;
97 + const failureEvent = () => {
98 + if (isValidationError) {
99 + return getToolExecuteValidationFailedEvent({
100 + toolSlug: params.toolSlug,
101 + toolkitSlug,
102 + args: params.args,
103 + error: new ToolInputValidationError({
104 + toolSlug: params.toolSlug,
105 + schemaPath: 'server',
106 + issues: [message],
107 + }),
108 + invocationOrigin,
109 + surface: params.surface,
110 + projectMode: params.projectMode,
111 + stage: params.stage === 'dry_run' ? 'dry_run' : 'execution',
112 + failureOrigin,
113 + logId: params.logId,
114 + });
115 + }
116 + if (isMaybeToolNotFoundError({ message, errorSlug, status, apiCode })) {
117 + return getToolExecuteToolNotFoundEvent({
118 + toolSlug: params.toolSlug,
119 + toolkitSlug,
120 + args: params.args,
121 + invocationOrigin,
122 + surface: params.surface,
123 + projectMode: params.projectMode,
124 + stage: executionStage,
125 + failureOrigin,
126 + logId: params.logId,
127 + errorSlug,
128 + status,
129 + apiCode,
130 + message,
131 + });
132 + }
133 + return getToolExecuteFailedEvent({
134 + toolSlug: params.toolSlug,
135 + toolkitSlug,
136 + args: params.args,
137 + invocationOrigin,
138 + surface: params.surface,
139 + projectMode: params.projectMode,
140 + stage: executionStage,
141 + failureOrigin,
142 + logId: params.logId,
143 + errorSlug,
144 + status,
145 + apiCode,
146 + message,
147 + errorName: normalized instanceof Error ? normalized.name : undefined,
148 + isNoConnectionError,
149 + });
150 + };
151 +
152 + yield* trackCliEventEffect(failureEvent());
153 +
154 + if (isNoConnectionError) {
155 + return;
156 + }
157 +
158 + if (isValidationError) {
159 + yield* trackCliCodactFailureEffect({
160 + failureType: 'wrong_tool_input_param',
161 + toolInfo: {
162 + ...(toolkitSlug ? { toolkit: toolkitSlug } : {}),
163 + },
164 + ctx: {
165 + tool_slug: params.toolSlug,
166 + error_slug: errorSlug,
167 + api_error_code: apiCode,
168 + http_status: status,
169 + error_message: message,
170 + stage: params.stage === 'dry_run' ? 'dry_run' : 'execution',
171 + },
172 + session: {
173 + source: 'cli',
174 + command_path: params.surface === 'root' ? 'execute' : 'dev playground-execute',
175 + project_mode: params.projectMode,
176 + surface: params.surface,
177 + cli_version: constants.APP_VERSION,
178 + },
179 + requestId: apiDetails?.request_id,
180 + });
181 + return;
182 + }
183 +
184 + if (
185 + isMaybeToolNotFoundError({
186 + message,
187 + errorSlug,
188 + status,
189 + apiCode,
190 + })
191 + ) {
192 + yield* trackCliCodactFailureEffect({
193 + failureType: 'wrong_tool_slug',
194 + toolInfo: {
195 + ...(toolkitSlug ? { toolkit: toolkitSlug } : {}),
196 + },
197 + ctx: {
198 + invalid_tool_slug: params.toolSlug,
199 + error_slug: errorSlug,
200 + api_error_code: apiCode,
201 + http_status: status,
202 + error_message: message,
203 + stage: params.stage === 'validation' ? 'execution' : params.stage,
204 + },
205 + session: {
206 + source: 'cli',
207 + command_path: params.surface === 'root' ? 'execute' : 'dev playground-execute',
208 + project_mode: params.projectMode,
209 + surface: params.surface,
210 + cli_version: constants.APP_VERSION,
211 + },
212 + requestId: apiDetails?.request_id,
213 + });
214 + }
215 + });
216 +
217 +export const handleExecutionError = (
218 + ui: TerminalUI,
219 + error: unknown,
220 + context: {
221 + toolSlug: string;
222 + args: Record<string, unknown>;
223 + surface: 'root' | 'dev';
224 + projectMode: 'consumer' | 'developer';
225 + stage: 'schema_fetch' | 'dry_run' | 'validation' | 'execution';
226 + logId?: string;
227 + projectScope?: ToolkitProjectScope;
228 + }
229 +) =>
230 + Effect.gen(function* () {
231 + const toolkit = yield* toolkitFromToolSlug(context.toolSlug, context.projectScope);
232 + const mapped = mapComposioError({ error, toolkit, toolSlug: context.toolSlug });
233 + const normalized = mapped.normalized;
234 + if (normalized instanceof ToolInputValidationError) {
235 + yield* emitExecuteFailureTelemetry({
236 + toolSlug: context.toolSlug,
237 + args: context.args,
238 + error: normalized,
239 + surface: context.surface,
240 + projectMode: context.projectMode,
241 + stage: context.stage,
242 + logId: context.logId,
243 + projectScope: context.projectScope,
244 + });
245 + yield* ui.log.error(`Input validation failed for ${context.toolSlug}`);
246 + yield* ui.note(
247 + [`Schema: ${normalized.schemaPath}`, ...normalized.issues.map(issue => `- ${issue}`)].join(
248 + '\n'
249 + ),
250 + 'Tool schema validation'
251 + );
252 + return { error: normalized.message, slug: context.toolSlug };
253 + }
254 +
255 + const apiDetails = mapped.apiDetails;
256 + const slugValue = mapped.slugValue;
257 +
258 + yield* emitExecuteFailureTelemetry({
259 + toolSlug: context.toolSlug,
260 + args: context.args,
261 + error,
262 + surface: context.surface,
263 + projectMode: context.projectMode,
264 + stage: context.stage,
265 + logId: context.logId,
266 + projectScope: context.projectScope,
267 + mappedError: mapped,
268 + });
269 +
270 + if (normalized instanceof ComposioNoActiveConnectionError) {
271 + yield* ui.log.error(mapped.message);
272 + if (toolkit) {
273 + yield* ui.note(
274 + connectionTips({ toolkit, toolSlug: context.toolSlug, surface: context.surface }),
275 + 'Tips'
276 + );
277 + }
278 + return { error: mapped.message, slug: slugValue ?? context.toolSlug };
279 + }
280 +
281 + yield* ui.log.error(mapped.message);
282 +
283 + const detailsObject = apiDetails;
284 + if (detailsObject) {
285 + yield* ui.note(formatUnknownObject(redactRequestId(detailsObject)), 'Error details');
286 + }
287 +
288 + return { error: mapped.message, slug: slugValue };
289 + });
ts/packages/cli/src/commands/tools/execute/tools.execute.format.ts new
+154
@@ -0,0 +1,154 @@
1 +import util from 'node:util';
2 +import { Effect, Result } from 'effect';
3 +import { commandHintStep } from 'src/services/command-hints';
4 +import type { TerminalUI } from 'src/services/terminal-ui';
5 +import { normalizeFileUploadSchema } from 'src/services/tool-file-uploads';
6 +import type { InstantCharge } from 'src/services/tools-executor';
7 +import { redact } from 'src/ui/redact';
8 +import { isPlainRecord } from 'src/utils/parse-json';
9 +
10 +export const connectionTips = (params: {
11 + readonly toolkit: string | undefined;
12 + readonly toolSlug: string;
13 + readonly surface: 'root' | 'dev';
14 +}) => {
15 + const { toolkit, toolSlug, surface } = params;
16 + const executeStep =
17 + surface === 'dev'
18 + ? commandHintStep('Retry', 'dev.playgroundExecute', {
19 + slug: toolSlug,
20 + userId: '<user-id>',
21 + data: '...',
22 + })
23 + : commandHintStep('Retry', 'root.execute', { slug: toolSlug, data: '...' });
24 + if (!toolkit) {
25 + return executeStep;
26 + }
27 + return [
28 + commandHintStep(
29 + 'Link the toolkit first',
30 + surface === 'dev' ? 'dev.connectedAccounts.link' : 'root.link',
31 + surface === 'dev' ? { toolkit, userId: '<user-id>' } : { toolkit }
32 + ),
33 + executeStep.replace('Retry:', 'Then retry:'),
34 + ].join('\n');
35 +};
36 +
37 +export const ciRedactReplacer = (_key: string, value: unknown): unknown => {
38 + if (typeof value !== 'string') return value;
39 + if (_key === 'logId') return redact({ value, prefix: 'log_' });
40 + if (_key === 'id' || _key.endsWith('Id') || _key.endsWith('_id')) {
41 + return redact({ value });
42 + }
43 + return value;
44 +};
45 +
46 +// JSON.stringify throws synchronously on circular or BigInt-bearing API
47 +// payloads; fall back to util.inspect so the formatter stays a plain string
48 +// function for its callers.
49 +export const formatUnknownObject = (value: object): string =>
50 + Result.getOrElse(
51 + Result.try(() => JSON.stringify(value, null, 2)),
52 + () => util.inspect(value, { depth: 5, breakLength: 120 })
53 + );
54 +
55 +export const redactRequestId = (value: object): object => {
56 + if (!value || typeof value !== 'object' || Array.isArray(value)) {
57 + return value;
58 + }
59 + if (!isPlainRecord(value)) return value;
60 + const requestId = value.request_id;
61 + if (typeof requestId !== 'string') {
62 + return value;
63 + }
64 + return {
65 + ...value,
66 + request_id: redact({ value: requestId }),
67 + };
68 +};
69 +
70 +export const describeStoredOutputSize = ({
71 + sizeBytes,
72 + tokenCount,
73 +}: {
74 + readonly sizeBytes: number;
75 + readonly tokenCount: number;
76 +}): string => `${Math.ceil(sizeBytes / 1024)} KB, ~${tokenCount} tokens`;
77 +
78 +export const serializeExecuteOutput = (result: unknown): string =>
79 + JSON.stringify(result, ciRedactReplacer, 2);
80 +
81 +const permissionApprovalLabel = (approval?: string): string | undefined => {
82 + switch (approval) {
83 + case 'always_approved':
84 + return 'always approved';
85 + case 'cached_approved':
86 + return 'cached approved';
87 + case 'approved_once':
88 + return 'approved once';
89 + case 'approved_for_session':
90 + return 'approved for session';
91 + default:
92 + return undefined;
93 + }
94 +};
95 +
96 +const instantChargeLabel = (charge?: InstantCharge): string | undefined => {
97 + if (!charge) return undefined;
98 + return `instant charge: ${charge.amount} ${charge.currency}`;
99 +};
100 +
101 +export const executionSuccessSuffix = (result: {
102 + readonly logId?: string;
103 + readonly permissionApproval?: string;
104 + readonly instantCharge?: InstantCharge;
105 +}) => {
106 + const metadata = [
107 + permissionApprovalLabel(result.permissionApproval),
108 + instantChargeLabel(result.instantCharge),
109 + result.logId ? `logId: ${redact({ value: result.logId, prefix: 'log_' })}` : undefined,
110 + ].filter((value): value is string => Boolean(value));
111 + return metadata.length > 0 ? ` (${metadata.join(', ')})` : '';
112 +};
113 +
114 +export const writeExecuteStdout = (ui: TerminalUI, data: string) =>
115 + ui.output(data, { force: true });
116 +
117 +export type DryRunSummary = {
118 + readonly successful: true;
119 + readonly dryRun: true;
120 + readonly slug: string;
121 + readonly arguments: Record<string, unknown>;
122 + readonly userId: string;
123 + readonly schemaPath?: string;
124 + readonly schemaVersion?: string | null;
125 +};
126 +
127 +export const emitCachedSchema = (
128 + ui: TerminalUI,
129 + slug: string,
130 + definition: {
131 + readonly version: string | null;
132 + readonly schemaPath: string;
133 + readonly schema: Record<string, unknown>;
134 + }
135 +) =>
136 + Effect.gen(function* () {
137 + const displaySchema = normalizeFileUploadSchema(definition.schema);
138 + yield* ui.log.message(
139 + `Schema saved, inspect keys like: jq '{required: (.inputSchema.required // []), keys: (.inputSchema.properties | keys)}' ${definition.schemaPath}`
140 + );
141 + yield* writeExecuteStdout(
142 + ui,
143 + JSON.stringify(
144 + {
145 + slug,
146 + version: definition.version,
147 + schemaPath: definition.schemaPath,
148 + inputSchema: displaySchema,
149 + },
150 + null,
151 + 2
152 + )
153 + );
154 + });
ts/packages/cli/src/commands/tools/execute/tools.execute.handler.ts new
+485
@@ -0,0 +1,485 @@
1 +import { Effect, Option } from 'effect';
2 +import { CommandSurface } from 'src/commands/surface';
3 +import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
4 +import { appendCliSessionHistory } from 'src/services/cli-session-artifacts';
5 +import {
6 + getFreshConsumerConnectedToolkitsFromCache,
7 + refreshConsumerConnectedToolkitsCache,
8 +} from 'src/services/consumer-short-term-cache';
9 +import { logToolDebug } from 'src/services/runtime-debug-logger';
10 +import type { TerminalUI } from 'src/services/terminal-ui';
11 +import {
12 + getOrFetchToolInputDefinition,
13 + invalidateToolInputDefinition,
14 + ToolInputValidationError,
15 +} from 'src/services/tool-input-validation';
16 +import { detectInBandWarning } from 'src/services/tools-executor';
17 +import type { ToolExecuteParams, ToolsExecutor } from 'src/services/tools-executor';
18 +import { redact } from 'src/ui/redact';
19 +import {
20 + resolveExecuteContext,
21 + resolveSchemaContext,
22 + toolkitProjectScope,
23 + type ResolvedExecuteContext,
24 + type RunToolsExecuteParams,
25 +} from './tools.execute.context';
26 +import { perfDebugLog } from './tools.execute.debug';
27 +import { invalidArguments, ReportedToolExecutionError } from './tools.execute.errors';
28 +import { emitExecuteFailureTelemetry, handleExecutionError } from './tools.execute.failure';
29 +import {
30 + ciRedactReplacer,
31 + connectionTips,
32 + describeStoredOutputSize,
33 + emitCachedSchema,
34 + executionSuccessSuffix,
35 + writeExecuteStdout,
36 + type DryRunSummary,
37 +} from './tools.execute.format';
38 +import { prepareExecuteOutput } from './tools.execute.output';
39 +import { runParallelFromCommand } from './tools.execute.parallel';
40 +import { checkDryRunArguments, validateToolInputBeforeExecute } from './tools.execute.validation';
41 +
42 +const runConnectedToolkitFailFast = (params: {
43 + readonly slug: string;
44 + readonly surface: 'root' | 'dev';
45 + readonly ui: TerminalUI;
46 + readonly resolvedProject: ResolvedExecuteContext['resolvedProject'];
47 + readonly resolvedUserId: string;
48 + readonly skipConnectionCheck: boolean;
49 + readonly skipChecks: boolean;
50 +}) =>
51 + Effect.gen(function* () {
52 + if (params.skipConnectionCheck || params.skipChecks) {
53 + yield* perfDebugLog('execute.connected_toolkits.skipped', {
54 + slug: params.slug,
55 + reason: params.skipChecks ? 'skip-checks' : 'skip-connection-check',
56 + });
57 + return;
58 + }
59 + if (params.resolvedProject.projectType !== 'CONSUMER') return;
60 +
61 + yield* perfDebugLog('execute.connected_toolkits.refresh_start', {
62 + slug: params.slug,
63 + orgId: params.resolvedProject.orgId,
64 + consumerUserId: params.resolvedUserId,
65 + });
66 + yield* refreshConsumerConnectedToolkitsCache({
67 + orgId: params.resolvedProject.orgId,
68 + consumerUserId: params.resolvedUserId,
69 + }).pipe(
70 + Effect.tap(() =>
71 + perfDebugLog('execute.connected_toolkits.refresh_end', {
72 + slug: params.slug,
73 + orgId: params.resolvedProject.orgId,
74 + consumerUserId: params.resolvedUserId,
75 + successful: true,
76 + })
77 + ),
78 + Effect.catch(() =>
79 + perfDebugLog('execute.connected_toolkits.refresh_end', {
80 + slug: params.slug,
81 + orgId: params.resolvedProject.orgId,
82 + consumerUserId: params.resolvedUserId,
83 + successful: false,
84 + })
85 + ),
86 + Effect.forkDetach,
87 + Effect.asVoid
88 + );
89 +
90 + const toolkit = yield* toolkitFromToolSlug(
91 + params.slug,
92 + toolkitProjectScope(params.resolvedProject)
93 + );
94 + if (!toolkit) return;
95 +
96 + const cachedToolkits = yield* getFreshConsumerConnectedToolkitsFromCache({
97 + orgId: params.resolvedProject.orgId,
98 + consumerUserId: params.resolvedUserId,
99 + });
100 + yield* perfDebugLog(
101 + Option.isSome(cachedToolkits)
102 + ? 'execute.connected_toolkits.cache_hit'
103 + : 'execute.connected_toolkits.cache_miss',
104 + {
105 + slug: params.slug,
106 + toolkit,
107 + orgId: params.resolvedProject.orgId,
108 + consumerUserId: params.resolvedUserId,
109 + cachedToolkits: Option.isSome(cachedToolkits) ? cachedToolkits.value : undefined,
110 + }
111 + );
112 +
113 + if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(toolkit)) {
114 + yield* perfDebugLog('execute.connected_toolkits.fail_fast', {
115 + slug: params.slug,
116 + toolkit,
117 + orgId: params.resolvedProject.orgId,
118 + consumerUserId: params.resolvedUserId,
119 + });
120 + const message = `Toolkit "${toolkit}" is not connected for this user (cached within the last 5 minutes). If you just connected the account, use --skip-connection-check.`;
121 + yield* params.ui.log.error(message);
122 + yield* params.ui.note(
123 + connectionTips({ toolkit, toolSlug: params.slug, surface: params.surface }),
124 + 'Tips'
125 + );
126 + yield* writeExecuteStdout(
127 + params.ui,
128 + JSON.stringify(
129 + {
130 + successful: false,
131 + error: message,
132 + slug: params.slug,
133 + },
134 + ciRedactReplacer,
135 + 2
136 + )
137 + );
138 + return yield* new ReportedToolExecutionError({
139 + reason: 'connection_check',
140 + toolSlug: params.slug,
141 + message,
142 + });
143 + }
144 + });
145 +
146 +const executeSessionHistoryScope = (resolvedProject: ResolvedExecuteContext['resolvedProject']) =>
147 + resolvedProject.projectType === 'CONSUMER'
148 + ? {
149 + orgId: resolvedProject.orgId,
150 + consumerUserId: resolvedProject.consumerUserId,
151 + }
152 + : {};
153 +
154 +const runExecuteWithSpinner = (params: {
155 + readonly slug: string;
156 + readonly surface: 'root' | 'dev';
157 + readonly projectMode: 'consumer' | 'developer';
158 + readonly dryRun: boolean;
159 + readonly ui: TerminalUI;
160 + readonly executor: ToolsExecutor;
161 + readonly resolvedProject: ResolvedExecuteContext['resolvedProject'];
162 + readonly args: Record<string, unknown>;
163 + readonly resolvedUserId: string;
164 + readonly executeParams: ToolExecuteParams;
165 + readonly executeOutputDir?: string;
166 + readonly skipToolParamsCheck: boolean;
167 + readonly skipChecks: boolean;
168 +}) =>
169 + Effect.gen(function* () {
170 + const verificationDisabled = params.skipChecks || params.skipToolParamsCheck;
171 +
172 + yield* params.ui.useMakeSpinner(`Executing tool "${params.slug}"...`, spinner =>
173 + Effect.gen(function* () {
174 + if (params.dryRun) {
175 + const definition = yield* checkDryRunArguments({
176 + slug: params.slug,
177 + args: params.args,
178 + projectScope: {
179 + orgId: params.resolvedProject.orgId,
180 + projectId: params.resolvedProject.projectId,
181 + },
182 + verificationDisabled,
183 + }).pipe(
184 + Effect.tapError(error =>
185 + emitExecuteFailureTelemetry({
186 + toolSlug: params.slug,
187 + args: params.args,
188 + error,
189 + surface: params.surface,
190 + projectMode: params.projectMode,
191 + stage: 'dry_run',
192 + projectScope: toolkitProjectScope(params.resolvedProject),
193 + })
194 + )
195 + );
196 + const summary: DryRunSummary = {
197 + successful: true,
198 + dryRun: true,
199 + slug: params.slug,
200 + arguments: params.args,
201 + userId: params.resolvedUserId,
202 + schemaPath: definition?.schemaPath,
203 + schemaVersion: definition?.version,
204 + };
205 + yield* spinner.stop('Dry run successful');
206 + yield* params.ui.log.message(
207 + verificationDisabled
208 + ? 'No tool was executed. Local validation was skipped.'
209 + : 'No tool was executed. Arguments were validated locally only.'
210 + );
211 + yield* writeExecuteStdout(params.ui, JSON.stringify(summary, ciRedactReplacer, 2));
212 + yield* appendCliSessionHistory({
213 + ...executeSessionHistoryScope(params.resolvedProject),
214 + entry: {
215 + command: 'execute',
216 + status: 'dry-run',
217 + slug: params.slug,
218 + arguments: params.args,
219 + },
220 + }).pipe(Effect.catch(() => Effect.void));
221 + return;
222 + }
223 +
224 + yield* perfDebugLog('execute.tool_call.start', { slug: params.slug });
225 + const validateArgs = verificationDisabled
226 + ? Effect.void
227 + : validateToolInputBeforeExecute({
228 + slug: params.slug,
229 + args: params.args,
230 + resolvedProject: params.resolvedProject,
231 + });
232 + const result = yield* validateArgs.pipe(
233 + Effect.andThen(params.executor.execute(params.slug, params.executeParams)),
234 + Effect.matchEffect({
235 + onFailure: error =>
236 + Effect.gen(function* () {
237 + yield* logToolDebug('execute_result', { slug: params.slug, result: error });
238 + yield* perfDebugLog('execute.tool_call.end', {
239 + slug: params.slug,
240 + successful: false,
241 + });
242 + // The validation error points the user at the cached schema, so
243 + // it has to stay on disk.
244 + if (!(error instanceof ToolInputValidationError)) {
245 + yield* invalidateToolInputDefinition(params.slug).pipe(
246 + Effect.catch(() => Effect.void)
247 + );
248 + }
249 + yield* spinner.error();
250 + const summary = yield* handleExecutionError(params.ui, error, {
251 + toolSlug: params.slug,
252 + args: params.args,
253 + surface: params.surface,
254 + projectMode: params.projectMode,
255 + stage: 'execution',
256 + projectScope: toolkitProjectScope(params.resolvedProject),
257 + });
258 + yield* writeExecuteStdout(
259 + params.ui,
260 + JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)
261 + );
262 + yield* appendCliSessionHistory({
263 + ...executeSessionHistoryScope(params.resolvedProject),
264 + entry: {
265 + command: 'execute',
266 + status: 'error',
267 + slug: params.slug,
268 + arguments: params.args,
269 + error: summary.error,
270 + },
271 + }).pipe(Effect.catch(() => Effect.void));
272 + return yield* new ReportedToolExecutionError({
273 + reason: 'execution_failed',
274 + toolSlug: params.slug,
275 + message: summary.error,
276 + });
277 + }),
278 + onSuccess: result =>
279 + Effect.gen(function* () {
280 + yield* logToolDebug('execute_result', { slug: params.slug, result });
281 + yield* perfDebugLog('execute.tool_call.end', {
282 + slug: params.slug,
283 + successful: true,
284 + });
285 + return result;
286 + }),
287 + })
288 + );
289 + if (!result.successful) {
290 + yield* invalidateToolInputDefinition(params.slug).pipe(Effect.catch(() => Effect.void));
291 + const logId = result.logId
292 + ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
293 + : '';
294 + yield* spinner.error(`Execution failed${logId}`);
295 +
296 + const summary = yield* handleExecutionError(params.ui, result.error ?? result, {
297 + toolSlug: params.slug,
298 + args: params.args,
299 + surface: params.surface,
300 + projectMode: params.projectMode,
301 + stage: 'execution',
302 + logId: result.logId,
303 + projectScope: toolkitProjectScope(params.resolvedProject),
304 + });
305 + yield* writeExecuteStdout(params.ui, JSON.stringify(result, ciRedactReplacer, 2));
306 + return yield* new ReportedToolExecutionError({
307 + reason: 'execution_failed',
308 + toolSlug: params.slug,
309 + message: summary.error,
310 + });
311 + }
312 +
313 + yield* spinner.stop(`Execution successful${executionSuccessSuffix(result)}`);
314 + const inBandWarning = detectInBandWarning(result.data);
315 + if (inBandWarning) {
316 + yield* params.ui.log.warn(
317 + `The tool executed successfully but the response may contain an error: ${inBandWarning}`
318 + );
319 + }
320 + const output = yield* prepareExecuteOutput(params.slug, result, params.executeOutputDir);
321 + if (output.kind === 'file') {
322 + yield* params.ui.log.message(
323 + `Response stored in ${output.summary.outputFilePath} (${describeStoredOutputSize(output.summary)})`
324 + );
325 + yield* writeExecuteStdout(params.ui, JSON.stringify(output.summary, ciRedactReplacer, 2));
326 + yield* appendCliSessionHistory({
327 + ...executeSessionHistoryScope(params.resolvedProject),
328 + entry: {
329 + command: 'execute',
330 + status: 'success',
331 + slug: params.slug,
332 + arguments: params.args,
333 + storedInFile: true,
334 + outputFilePath: output.summary.outputFilePath,
335 + tokenCount: output.summary.tokenCount,
336 + sizeBytes: output.summary.sizeBytes,
337 + logId: result.logId,
338 + },
339 + }).pipe(Effect.catch(() => Effect.void));
340 + return;
341 + }
342 +
343 + yield* writeExecuteStdout(params.ui, output.json);
344 + yield* appendCliSessionHistory({
345 + ...executeSessionHistoryScope(params.resolvedProject),
346 + entry: {
347 + command: 'execute',
348 + status: 'success',
349 + slug: params.slug,
350 + arguments: params.args,
351 + storedInFile: false,
352 + logId: result.logId,
353 + },
354 + }).pipe(Effect.catch(() => Effect.void));
355 + })
356 + );
357 + });
358 +
359 +const runToolsExecute = (params: RunToolsExecuteParams) =>
360 + Effect.gen(function* () {
361 + if (params.getSchema) {
362 + const context = yield* resolveSchemaContext(params);
363 + const definition = yield* getOrFetchToolInputDefinition(params.slug, {
364 + orgId: context.resolvedProject.orgId,
365 + projectId: context.resolvedProject.projectId,
366 + }).pipe(
367 + Effect.tapError(error =>
368 + emitExecuteFailureTelemetry({
369 + toolSlug: params.slug,
370 + args: {},
371 + error,
372 + surface: params.surface,
373 + projectMode: params.projectMode,
374 + stage: 'schema_fetch',
375 + projectScope: toolkitProjectScope(context.resolvedProject),
376 + })
377 + )
378 + );
379 + yield* emitCachedSchema(context.ui, params.slug, definition);
380 + return;
381 + }
382 +
383 + const context = yield* resolveExecuteContext(params);
384 +
385 + yield* runConnectedToolkitFailFast({
386 + slug: params.slug,
387 + surface: params.surface,
388 + ui: context.ui,
389 + resolvedProject: context.resolvedProject,
390 + resolvedUserId: context.resolvedUserId,
391 + skipConnectionCheck: params.skipConnectionCheck,
392 + skipChecks: params.skipChecks,
393 + });
394 + yield* logToolDebug('execute_params', {
395 + slug: params.slug,
396 + userId: context.resolvedUserId,
397 + connectedAccountId: context.selectedConnectedAccountId,
398 + arguments: context.args,
399 + projectId: context.resolvedProject.projectId,
400 + orgId: context.resolvedProject.orgId,
401 + });
402 + yield* perfDebugLog('execute.prepare', {
403 + slug: params.slug,
404 + surface: params.surface,
405 + projectMode: params.projectMode,
406 + });
407 + yield* runExecuteWithSpinner({
408 + slug: params.slug,
409 + surface: params.surface,
410 + projectMode: params.projectMode,
411 + dryRun: params.dryRun,
412 + ui: context.ui,
413 + executor: context.executor,
414 + resolvedProject: context.resolvedProject,
415 + args: context.args,
416 + resolvedUserId: context.resolvedUserId,
417 + executeParams: context.executeParams,
418 + skipToolParamsCheck: params.skipToolParamsCheck,
419 + skipChecks: params.skipChecks,
420 + });
421 + });
422 +
423 +export type ToolsExecuteParams = {
424 + readonly slug: string;
425 + readonly additionalSlugs: ReadonlyArray<string>;
426 + readonly parallel: boolean;
427 + readonly data: Option.Option<string>;
428 + readonly file: Option.Option<string>;
429 + readonly account: Option.Option<string>;
430 + readonly getSchema: boolean;
431 + readonly dryRun: boolean;
432 + readonly skipConnectionCheck: boolean;
433 + readonly skipToolParamsCheck: boolean;
434 + readonly skipChecks: boolean;
435 +};
436 +
437 +/**
438 + * The handler of both `execute` (root tree, the consumer project) and `dev playground-execute`
439 + * (`dev` tree, the developer project, with the `dev` group's `--user-id` and `--project-name`).
440 + */
441 +export const runToolsExecuteCommand = ({
442 + slug,
443 + additionalSlugs,
444 + parallel,
445 + data,
446 + file,
447 + account,
448 + getSchema,
449 + dryRun,
450 + skipConnectionCheck,
451 + skipToolParamsCheck,
452 + skipChecks,
453 +}: ToolsExecuteParams) =>
454 + Effect.gen(function* () {
455 + const { tree, projectName } = yield* CommandSurface;
456 + const projectMode = tree === 'root' ? 'consumer' : 'developer';
457 + if (parallel) {
458 + return yield* runParallelFromCommand({
459 + surface: tree,
460 + projectMode,
461 + getSchema,
462 + dryRun,
463 + skipConnectionCheck,
464 + skipToolParamsCheck,
465 + skipChecks,
466 + });
467 + }
468 + if (additionalSlugs.length > 0) {
469 + return yield* invalidArguments('Additional tool slugs require --parallel.');
470 + }
471 + return yield* runToolsExecute({
472 + slug,
473 + data,
474 + file,
475 + account,
476 + projectName,
477 + surface: tree,
478 + projectMode,
479 + getSchema,
480 + dryRun,
481 + skipConnectionCheck,
482 + skipToolParamsCheck,
483 + skipChecks,
484 + });
485 + });
ts/packages/cli/src/commands/tools/execute/tools.execute.output.ts new
+90
@@ -0,0 +1,90 @@
1 +import { Effect } from 'effect';
2 +import { APP_CONFIG } from 'src/config';
3 +import { storeCliSessionArtifact } from 'src/services/cli-session-artifacts';
4 +import type { InstantCharge, ToolExecuteResponse } from 'src/services/tools-executor';
5 +import { serializeExecuteOutput } from './tools.execute.format';
6 +
7 +// Responses larger than this are stored in a session file instead of printed,
8 +// so a caller such as an agent does not take a huge payload into its context.
9 +// Measured in UTF-8 bytes: about 10,000 tokens of JSON at the estimate below.
10 +const EXECUTE_INLINE_OUTPUT_BYTE_THRESHOLD = 40_000;
11 +
12 +// JSON averages roughly four bytes per token. The `tokenCount` of a stored
13 +// response is this estimate rather than a tokenizer count, since the real count
14 +// depends on the model that reads the file.
15 +const ESTIMATED_BYTES_PER_OUTPUT_TOKEN = 4;
16 +
17 +const shouldStoreLargeExecuteOutput = APP_CONFIG.CLI_INVOCATION_ORIGIN.pipe(
18 + Effect.orDie,
19 + Effect.map(origin => origin !== 'run')
20 +);
21 +
22 +type StoredExecuteOutputSummary = {
23 + readonly successful: true;
24 + readonly error: null;
25 + readonly logId: string;
26 + readonly instantCharge?: InstantCharge;
27 + readonly storedInFile: true;
28 + readonly tokenCount: number;
29 + readonly sizeBytes: number;
30 + readonly outputFilePath: string;
31 +};
32 +
33 +type PreparedExecuteOutput =
34 + | { readonly kind: 'inline'; readonly json: string }
35 + | { readonly kind: 'file'; readonly summary: StoredExecuteOutputSummary };
36 +
37 +const persistLargeExecuteOutput = (
38 + toolSlug: string,
39 + json: string,
40 + sizeBytes: number,
41 + sharedDirectory?: string
42 +) =>
43 + Effect.gen(function* () {
44 + const runOutputDirectory = yield* APP_CONFIG.RUN_OUTPUT_DIR;
45 + const outputFilePath = yield* storeCliSessionArtifact({
46 + contents: json,
47 + name: `${toolSlug}_OUTPUT`,
48 + extension: 'json',
49 + directoryPath: sharedDirectory?.trim() || runOutputDirectory,
50 + });
51 +
52 + return {
53 + successful: true,
54 + error: null,
55 + logId: '',
56 + storedInFile: true,
57 + tokenCount: Math.ceil(sizeBytes / ESTIMATED_BYTES_PER_OUTPUT_TOKEN),
58 + sizeBytes,
59 + outputFilePath: outputFilePath ?? '(could not write to disk)',
60 + } satisfies StoredExecuteOutputSummary;
61 + });
62 +
63 +export const prepareExecuteOutput = (
64 + toolSlug: string,
65 + result: ToolExecuteResponse,
66 + sharedDirectory?: string
67 +) =>
68 + Effect.gen(function* () {
69 + const json = serializeExecuteOutput(result);
70 + const sizeBytes = new TextEncoder().encode(json).length;
71 + // `composio run` always prints inline.
72 + if (
73 + sizeBytes <= EXECUTE_INLINE_OUTPUT_BYTE_THRESHOLD ||
74 + !(yield* shouldStoreLargeExecuteOutput)
75 + ) {
76 + return {
77 + kind: 'inline',
78 + json,
79 + } satisfies PreparedExecuteOutput;
80 + }
81 +
82 + return {
83 + kind: 'file',
84 + summary: {
85 + ...(yield* persistLargeExecuteOutput(toolSlug, json, sizeBytes, sharedDirectory)),
86 + logId: result.logId,
87 + ...(result.instantCharge ? { instantCharge: result.instantCharge } : {}),
88 + } satisfies StoredExecuteOutputSummary,
89 + } satisfies PreparedExecuteOutput;
90 + });
ts/packages/cli/src/commands/tools/execute/tools.execute.parallel.ts new
+622
@@ -0,0 +1,622 @@
1 +import { Context, Effect, Option } from 'effect';
2 +import { actingUser, CommandSurface } from 'src/commands/surface';
3 +import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
4 +import { mapComposioError } from 'src/services/composio-error-overrides';
5 +import {
6 + getFreshConsumerConnectedToolkitsFromCache,
7 + refreshConsumerConnectedToolkitsCache,
8 +} from 'src/services/consumer-short-term-cache';
9 +import { CLI_DEBUG_FLAG_NAMES } from 'src/services/runtime-flags';
10 +import { normalizeFileUploadSchema } from 'src/services/tool-file-uploads';
11 +import {
12 + getOrFetchToolInputDefinition,
13 + validateToolInputArgumentsWithDefinition,
14 +} from 'src/services/tool-input-validation';
15 +import { redact } from 'src/ui/redact';
16 +import {
17 + resolveExecuteContext,
18 + resolveSchemaContext,
19 + toolkitProjectScope,
20 + type ResolvedExecuteContext,
21 + type SharedRunToolsExecuteParams,
22 +} from './tools.execute.context';
23 +import {
24 + invalidArguments,
25 + ReportedToolExecutionError,
26 + ToolExecutionError,
27 +} from './tools.execute.errors';
28 +import {
29 + ciRedactReplacer,
30 + describeStoredOutputSize,
31 + executionSuccessSuffix,
32 + serializeExecuteOutput,
33 + writeExecuteStdout,
34 + type DryRunSummary,
35 +} from './tools.execute.format';
36 +import { prepareExecuteOutput } from './tools.execute.output';
37 +import { checkDryRunArguments } from './tools.execute.validation';
38 +
39 +export const ExecuteInvocationArgs = Context.Reference<ReadonlyArray<string>>(
40 + 'commands/ExecuteInvocationArgs',
41 + { defaultValue: () => [] }
42 +);
43 +
44 +type ParallelExecuteSpec = {
45 + readonly slug: string;
46 + readonly data: Option.Option<string>;
47 + readonly account: Option.Option<string>;
48 +};
49 +
50 +type ParsedParallelExecuteArgs = SharedRunToolsExecuteParams & {
51 + readonly userId: Option.Option<string>;
52 + readonly specs: ReadonlyArray<ParallelExecuteSpec>;
53 +};
54 +
55 +type ParallelExecuteResult =
56 + | {
57 + readonly slug: string;
58 + readonly successful: true;
59 + readonly version: string | null;
60 + readonly schemaPath: string;
61 + readonly inputSchema: Record<string, unknown>;
62 + }
63 + | {
64 + readonly slug: string;
65 + readonly successful: false;
66 + readonly error: string;
67 + };
68 +
69 +export const parseParallelExecuteArgs = (
70 + args: ReadonlyArray<string>,
71 + config: {
72 + readonly surface: 'root' | 'dev';
73 + readonly projectMode: 'consumer' | 'developer';
74 + readonly allowUserId: boolean;
75 + readonly allowProjectName: boolean;
76 + }
77 +) =>
78 + Effect.gen(function* () {
79 + let getSchema = false;
80 + let dryRun = false;
81 + let skipConnectionCheck = false;
82 + let skipToolParamsCheck = false;
83 + let skipChecks = false;
84 + let account = Option.none<string>();
85 + let userId = Option.none<string>();
86 + let projectName = Option.none<string>();
87 + const specs: ParallelExecuteSpec[] = [];
88 + let currentSpec: ParallelExecuteSpec | null = null;
89 +
90 + const pushCurrentSpec = () => {
91 + if (!currentSpec) return;
92 + specs.push(currentSpec);
93 + currentSpec = null;
94 + };
95 +
96 + const readValue = (token: string, index: number) => {
97 + if (token.includes('=')) {
98 + return Effect.succeed({
99 + value: token.slice(token.indexOf('=') + 1),
100 + nextIndex: index,
101 + });
102 + }
103 +
104 + const next = args[index + 1];
105 + if (!next) {
106 + return Effect.fail(invalidArguments(`Missing value for ${token}.`));
107 + }
108 + return Effect.succeed({ value: next, nextIndex: index + 1 });
109 + };
110 +
111 + for (let i = 0; i < args.length; i += 1) {
112 + const token = args[i];
113 + if (!token) continue;
114 +
115 + const flagName = token.split('=')[0];
116 + if (
117 + CLI_DEBUG_FLAG_NAMES.some(name => flagName === `--${name}` || flagName === `--no-${name}`)
118 + )
119 + continue;
120 + if (flagName === '--log-level') {
121 + if (!token.includes('=')) i += 1;
122 + continue;
123 + }
124 + // The framework supplies these values; this parser only preserves tool/data grouping.
125 + if (
126 + [
127 + 'parallel',
128 + 'get-schema',
129 + 'dry-run',
130 + 'skip-connection-check',
131 + 'skip-tool-params-check',
132 + 'skip-checks',
133 + ].some(name => flagName === `--${name}` || flagName === `--no-${name}`) &&
134 + (token !== flagName || flagName.startsWith('--no-'))
135 + )
136 + continue;
137 + if (token === '--parallel' || token === '-p') {
138 + continue;
139 + }
140 + if (token === '--get-schema') {
141 + getSchema = true;
142 + continue;
143 + }
144 + if (token === '--dry-run') {
145 + dryRun = true;
146 + continue;
147 + }
148 + if (token === '--skip-connection-check') {
149 + skipConnectionCheck = true;
150 + continue;
151 + }
152 + if (token === '--skip-tool-params-check') {
153 + skipToolParamsCheck = true;
154 + continue;
155 + }
156 + if (token === '--skip-checks') {
157 + skipChecks = true;
158 + continue;
159 + }
160 + if (token === '--account' || token.startsWith('--account=')) {
161 + const parsed = yield* readValue(token, i);
162 + if (currentSpec) {
163 + currentSpec = {
164 + slug: currentSpec.slug,
165 + data: currentSpec.data,
166 + account: Option.some(parsed.value),
167 + };
168 + } else {
169 + account = Option.some(parsed.value);
170 + }
171 + i = parsed.nextIndex;
172 + continue;
173 + }
174 + if (token === '--user-id' || token.startsWith('--user-id=')) {
175 + if (!config.allowUserId) {
176 + return yield* Effect.fail(
177 + invalidArguments(`${token} is not supported for this execute command.`)
178 + );
179 + }
180 + const parsed = yield* readValue(token, i);
181 + userId = Option.some(parsed.value);
182 + i = parsed.nextIndex;
183 + continue;
184 + }
185 + if (token === '--project-name' || token.startsWith('--project-name=')) {
186 + if (!config.allowProjectName) {
187 + return yield* Effect.fail(
188 + invalidArguments(`${token} is not supported for this execute command.`)
189 + );
190 + }
191 + const parsed = yield* readValue(token, i);
192 + projectName = Option.some(parsed.value);
193 + i = parsed.nextIndex;
194 + continue;
195 + }
196 + if (
197 + token === '--data' ||
198 + token === '-d' ||
199 + token.startsWith('--data=') ||
200 + token.startsWith('-d=')
201 + ) {
202 + if (!currentSpec) {
203 + return yield* Effect.fail(
204 + invalidArguments(
205 + `Expected a tool slug before ${token}. Use: composio execute --parallel TOOL_SLUG -d '{}' TOOL_SLUG_2 -d '{}'.`
206 + )
207 + );
208 + }
209 + const parsed = yield* readValue(token, i);
210 + currentSpec = {
211 + slug: currentSpec.slug,
212 + data: Option.some(parsed.value),
213 + account: currentSpec.account,
214 + };
215 + i = parsed.nextIndex;
216 + continue;
217 + }
218 + if (token.startsWith('-')) {
219 + return yield* Effect.fail(
220 + invalidArguments(`Unknown option for parallel execute: ${token}`)
221 + );
222 + }
223 +
224 + pushCurrentSpec();
225 + currentSpec = {
226 + slug: token,
227 + data: Option.none(),
228 + account,
229 + };
230 + }
231 +
232 + pushCurrentSpec();
233 +
234 + if (specs.length === 0) {
235 + return yield* Effect.fail(
236 + invalidArguments(
237 + "No tool slugs were provided. Use: composio execute --parallel TOOL_SLUG -d '{}' TOOL_SLUG_2 -d '{}'."
238 + )
239 + );
240 + }
241 +
242 + return {
243 + specs,
244 + userId,
245 + projectName,
246 + surface: config.surface,
247 + projectMode: config.projectMode,
248 + getSchema,
249 + dryRun,
250 + skipConnectionCheck,
251 + skipToolParamsCheck,
252 + skipChecks,
253 + account,
254 + } satisfies ParsedParallelExecuteArgs;
255 + });
256 +
257 +const checkConnectedToolkitOrFail = (params: {
258 + readonly slug: string;
259 + readonly resolvedProject: ResolvedExecuteContext['resolvedProject'];
260 + readonly resolvedUserId: string;
261 + readonly skipConnectionCheck: boolean;
262 + readonly skipChecks: boolean;
263 +}) =>
264 + Effect.gen(function* () {
265 + if (params.skipConnectionCheck || params.skipChecks) return;
266 + if (params.resolvedProject.projectType !== 'CONSUMER') return;
267 +
268 + yield* refreshConsumerConnectedToolkitsCache({
269 + orgId: params.resolvedProject.orgId,
270 + consumerUserId: params.resolvedUserId,
271 + }).pipe(
272 + Effect.catch(() => Effect.void),
273 + Effect.forkDetach,
274 + Effect.asVoid
275 + );
276 +
277 + const toolkit = yield* toolkitFromToolSlug(
278 + params.slug,
279 + toolkitProjectScope(params.resolvedProject)
280 + );
281 + if (!toolkit) return;
282 +
283 + const cachedToolkits = yield* getFreshConsumerConnectedToolkitsFromCache({
284 + orgId: params.resolvedProject.orgId,
285 + consumerUserId: params.resolvedUserId,
286 + });
287 +
288 + if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(toolkit)) {
289 + return yield* new ToolExecutionError({
290 + reason: 'connection_check',
291 + toolSlug: params.slug,
292 + message: `Toolkit "${toolkit}" is not connected for this user (cached within the last 5 minutes). If you just connected the account, use --skip-connection-check.`,
293 + });
294 + }
295 + });
296 +
297 +const runParallelSchemaFetchFromParsed = (params: ParsedParallelExecuteArgs) =>
298 + Effect.gen(function* () {
299 + const contexts = yield* Effect.forEach(
300 + params.specs,
301 + () =>
302 + resolveSchemaContext({
303 + account: params.account,
304 + projectName: params.projectName,
305 + surface: params.surface,
306 + projectMode: params.projectMode,
307 + getSchema: params.getSchema,
308 + dryRun: params.dryRun,
309 + skipConnectionCheck: params.skipConnectionCheck,
310 + skipToolParamsCheck: params.skipToolParamsCheck,
311 + skipChecks: params.skipChecks,
312 + }),
313 + { concurrency: 'unbounded' }
314 + );
315 + const entries = contexts.map((context, index) => ({
316 + context,
317 + spec: params.specs[index]!,
318 + }));
319 +
320 + const ui = contexts[0]?.ui;
321 + const results = yield* Effect.forEach(
322 + entries,
323 + ({ context, spec }) =>
324 + Effect.gen(function* () {
325 + const definition = yield* getOrFetchToolInputDefinition(spec.slug, {
326 + orgId: context.resolvedProject.orgId,
327 + projectId: context.resolvedProject.projectId,
328 + });
329 + return {
330 + slug: spec.slug,
331 + successful: true,
332 + version: definition.version,
333 + schemaPath: definition.schemaPath,
334 + inputSchema: normalizeFileUploadSchema(definition.schema),
335 + } satisfies Extract<
336 + ParallelExecuteResult,
337 + { readonly inputSchema: Record<string, unknown> }
338 + >;
339 + }).pipe(
340 + Effect.catch(error =>
341 + toolkitFromToolSlug(spec.slug, toolkitProjectScope(context.resolvedProject)).pipe(
342 + Effect.map(toolkit => {
343 + const mapped = mapComposioError({ error, toolkit, toolSlug: spec.slug });
344 + return {
345 + slug: spec.slug,
346 + successful: false,
347 + error: mapped.message,
348 + } satisfies Extract<ParallelExecuteResult, { readonly successful: false }>;
349 + })
350 + )
351 + )
352 + ),
353 + { concurrency: 'unbounded' }
354 + );
355 +
356 + if (ui) {
357 + for (const result of results) {
358 + if (!result.successful) {
359 + yield* ui.log.error(`[${result.slug}] ${result.error}`);
360 + continue;
361 + }
362 +
363 + yield* ui.log.step(`[${result.slug}] Schema fetched: ${result.schemaPath}`);
364 + }
365 +
366 + const successful = results.every(result => result.successful);
367 + yield* ui.log.message(
368 + `Parallel execute completed: ${results.filter(result => result.successful).length}/${results.length} successful`
369 + );
370 + yield* writeExecuteStdout(
371 + ui,
372 + JSON.stringify(
373 + {
374 + successful,
375 + parallel: true,
376 + results,
377 + },
378 + ciRedactReplacer,
379 + 2
380 + )
381 + );
382 + if (!successful) {
383 + return yield* new ReportedToolExecutionError({
384 + reason: 'parallel_failed',
385 + message: 'One or more parallel tool executions failed.',
386 + });
387 + }
388 + }
389 + });
390 +
391 +const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
392 + Effect.gen(function* () {
393 + if (params.getSchema) {
394 + return yield* runParallelSchemaFetchFromParsed(params);
395 + }
396 +
397 + // Resolved once, so a test user's notice prints once; each tool still fails on its own
398 + // input before it fails on a missing user.
399 + const user = Effect.fromResult(yield* Effect.result(actingUser()));
400 + const contexts = yield* Effect.forEach(
401 + params.specs,
402 + spec =>
403 + resolveExecuteContext(
404 + {
405 + slug: spec.slug,
406 + data: spec.data,
407 + file: Option.none(),
408 + account: spec.account,
409 + projectName: params.projectName,
410 + surface: params.surface,
411 + projectMode: params.projectMode,
412 + getSchema: params.getSchema,
413 + dryRun: params.dryRun,
414 + skipConnectionCheck: params.skipConnectionCheck,
415 + skipToolParamsCheck: params.skipToolParamsCheck,
416 + skipChecks: params.skipChecks,
417 + },
418 + user
419 + ),
420 + { concurrency: 'unbounded' }
421 + );
422 + const entries = contexts.map((context, index) => ({
423 + context,
424 + spec: params.specs[index]!,
425 + }));
426 +
427 + const ui = contexts[0]?.ui;
428 + const results = yield* Effect.forEach(
429 + entries,
430 + ({ context, spec }) =>
431 + Effect.gen(function* () {
432 + const toolSlug = spec.slug;
433 +
434 + yield* checkConnectedToolkitOrFail({
435 + slug: toolSlug,
436 + resolvedProject: context.resolvedProject,
437 + resolvedUserId: context.resolvedUserId,
438 + skipConnectionCheck: params.skipConnectionCheck,
439 + skipChecks: params.skipChecks,
440 + });
441 +
442 + if (params.dryRun) {
443 + const definition = yield* checkDryRunArguments({
444 + slug: toolSlug,
445 + args: context.args,
446 + projectScope: {
447 + orgId: context.resolvedProject.orgId,
448 + projectId: context.resolvedProject.projectId,
449 + },
450 + verificationDisabled: params.skipChecks || params.skipToolParamsCheck,
451 + });
452 + return {
453 + successful: true,
454 + dryRun: true,
455 + slug: toolSlug,
456 + arguments: context.args,
457 + userId: context.resolvedUserId,
458 + schemaPath: definition?.schemaPath,
459 + schemaVersion: definition?.version,
460 + } satisfies DryRunSummary;
461 + }
462 +
463 + if (!params.skipChecks && !params.skipToolParamsCheck) {
464 + const definition = yield* getOrFetchToolInputDefinition(toolSlug, {
465 + orgId: context.resolvedProject.orgId,
466 + projectId: context.resolvedProject.projectId,
467 + });
468 + yield* validateToolInputArgumentsWithDefinition(toolSlug, context.args, definition);
469 + }
470 +
471 + const result = yield* context.executor.execute(toolSlug, context.executeParams);
472 + if (!result.successful) {
473 + const failed = {
474 + slug: toolSlug,
475 + successful: false as const,
476 + error: result.error ?? 'Execution failed.',
477 + logId: result.logId,
478 + };
479 + if (!result.instantCharge) return failed;
480 + return { ...failed, instantCharge: result.instantCharge };
481 + }
482 +
483 + const output = yield* prepareExecuteOutput(toolSlug, result, context.executeOutputDir);
484 + if (output.kind === 'file') {
485 + return {
486 + slug: toolSlug,
487 + ...output.summary,
488 + };
489 + }
490 +
491 + return {
492 + slug: toolSlug,
493 + ...result,
494 + };
495 + }).pipe(
496 + Effect.catch(error =>
497 + toolkitFromToolSlug(spec.slug, toolkitProjectScope(context.resolvedProject)).pipe(
498 + Effect.map(toolkit => {
499 + const mapped = mapComposioError({ error, toolkit, toolSlug: spec.slug });
500 + return {
501 + slug: spec.slug,
502 + successful: false,
503 + error: mapped.message,
504 + } satisfies ParallelExecuteResult;
505 + })
506 + )
507 + )
508 + ),
509 + { concurrency: 'unbounded' }
510 + );
511 +
512 + if (ui) {
513 + for (const result of results) {
514 + if (!result.successful) {
515 + const logId =
516 + 'logId' in result && typeof result.logId === 'string' && result.logId.length > 0
517 + ? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
518 + : '';
519 + yield* ui.log.error(`[${result.slug}] ${result.error}${logId}`);
520 + continue;
521 + }
522 +
523 + if ('dryRun' in result && result.dryRun) {
524 + yield* ui.log.step(`[${result.slug}] Dry run successful`);
525 + continue;
526 + }
527 +
528 + if ('inputSchema' in result) {
529 + yield* ui.log.step(`[${result.slug}] Schema fetched: ${result.schemaPath}`);
530 + continue;
531 + }
532 +
533 + if ('storedInFile' in result && result.storedInFile) {
534 + yield* ui.log.step(
535 + `[${result.slug}] Response stored in ${result.outputFilePath} (${describeStoredOutputSize(result)})`
536 + );
537 + continue;
538 + }
539 +
540 + yield* ui.log.step(
541 + `[${result.slug}] Execution successful${executionSuccessSuffix(result)}`
542 + );
543 + if ('data' in result) {
544 + yield* ui.note(serializeExecuteOutput(result), `Response: ${result.slug}`);
545 + }
546 + }
547 + }
548 +
549 + const successful = results.every(result => result.successful);
550 + if (ui) {
551 + yield* ui.log.message(
552 + `Parallel execute completed: ${results.filter(result => result.successful).length}/${results.length} successful`
553 + );
554 + yield* writeExecuteStdout(
555 + ui,
556 + JSON.stringify(
557 + {
558 + successful,
559 + parallel: true,
560 + results,
561 + },
562 + ciRedactReplacer,
563 + 2
564 + )
565 + );
566 + }
567 +
568 + if (!successful) {
569 + return yield* new ReportedToolExecutionError({
570 + reason: 'parallel_failed',
571 + message: 'One or more parallel tool executions failed.',
572 + });
573 + }
574 + });
575 +
576 +// Flags that can precede the command name and take the next token as their value
577 +// (`$default.cmd.ts`, `dev.cmd.ts`), so a value equal to the command name is not the command.
578 +const VALUE_FLAGS_BEFORE_COMMAND = new Set([
579 + '--log-level',
580 + '--mode',
581 + '--user-id',
582 + '--project-name',
583 +]);
584 +
585 +/** The index of the command name in argv, skipping a flag value that spells the same word. */
586 +const commandNameIndex = (argv: ReadonlyArray<string>, name: string) =>
587 + argv.findIndex(
588 + (token, index) => token === name && !VALUE_FLAGS_BEFORE_COMMAND.has(argv[index - 1] ?? '')
589 + );
590 +
591 +export const runParallelFromCommand = (config: {
592 + readonly surface: 'root' | 'dev';
593 + readonly projectMode: 'consumer' | 'developer';
594 + readonly getSchema: boolean;
595 + readonly dryRun: boolean;
596 + readonly skipConnectionCheck: boolean;
597 + readonly skipToolParamsCheck: boolean;
598 + readonly skipChecks: boolean;
599 +}) =>
600 + Effect.gen(function* () {
601 + const argv = yield* ExecuteInvocationArgs;
602 + const name = config.surface === 'root' ? 'execute' : 'playground-execute';
603 + const tail = argv.slice(commandNameIndex(argv, name) + 1);
604 + const parsed = yield* parseParallelExecuteArgs(tail, {
605 + ...config,
606 + allowUserId: config.surface === 'dev',
607 + allowProjectName: config.surface === 'dev',
608 + });
609 + // The tail starts after the command name, so the `dev` group's shared flags given before
610 + // it reach the command only through the surface; the tail's own win.
611 + const surface = yield* CommandSurface;
612 + const userId = Option.orElse(parsed.userId, () => surface.userId);
613 + const projectName = Option.orElse(parsed.projectName, () => surface.projectName);
614 + return yield* runParallelToolsExecuteFromParsed({
615 + ...parsed,
616 + ...config,
617 + userId,
618 + projectName,
619 + }).pipe(
620 + Effect.provideService(CommandSurface, CommandSurface.of({ ...surface, userId, projectName }))
621 + );
622 + });
ts/packages/cli/src/commands/tools/execute/tools.execute.validation.ts new
+70
@@ -0,0 +1,70 @@
1 +import { Effect } from 'effect';
2 +import * as FileSystem from 'effect/FileSystem';
3 +import * as Path from 'effect/Path';
4 +import { rejectLocalFilesWithoutUpload } from 'src/services/tool-file-uploads';
5 +import {
6 + getOrFetchToolInputDefinition,
7 + ToolInputValidationError,
8 + validateToolInputArguments,
9 + validateToolInputArgumentsWithDefinition,
10 +} from 'src/services/tool-input-validation';
11 +import { isMetaToolSlug } from 'src/utils/meta-tool-slugs';
12 +import { perfDebugLog } from './tools.execute.debug';
13 +
14 +// What a dry run checks, matching the real call: the arguments against the
15 +// schema unless checks are skipped, then any local file the tool cannot upload.
16 +// The real call refuses that file whatever the skip flags say, loading the
17 +// schema for it and going on without one, and never for a meta tool, which
18 +// uploads nothing. Returns the schema only when the arguments were checked.
19 +export const checkDryRunArguments = (params: {
20 + readonly slug: string;
21 + readonly args: Record<string, unknown>;
22 + readonly projectScope: { readonly orgId?: string; readonly projectId?: string };
23 + readonly verificationDisabled: boolean;
24 +}) =>
25 + Effect.gen(function* () {
26 + const { slug, args, verificationDisabled } = params;
27 + if (verificationDisabled && isMetaToolSlug(slug)) return null;
28 +
29 + const definition = verificationDisabled
30 + ? yield* getOrFetchToolInputDefinition(slug, params.projectScope).pipe(
31 + Effect.catch(() => Effect.succeed(null))
32 + )
33 + : yield* getOrFetchToolInputDefinition(slug, params.projectScope);
34 + if (!definition) return null;
35 +
36 + if (!verificationDisabled) {
37 + yield* validateToolInputArgumentsWithDefinition(slug, args, definition);
38 + }
39 + if (!isMetaToolSlug(slug)) {
40 + yield* rejectLocalFilesWithoutUpload({
41 + fs: yield* FileSystem.FileSystem,
42 + path: yield* Path.Path,
43 + toolSlug: slug,
44 + arguments_: args,
45 + inputSchema: definition.schema,
46 + });
47 + }
48 + return verificationDisabled ? null : definition;
49 + });
50 +
51 +// Gates the tool call: the request is only sent once the arguments pass. A
52 +// schema that cannot be loaded does not block the call, the server validates too.
53 +export const validateToolInputBeforeExecute = (params: {
54 + readonly slug: string;
55 + readonly args: Record<string, unknown>;
56 + readonly resolvedProject: {
57 + readonly orgId: string;
58 + readonly projectId: string;
59 + };
60 +}) =>
61 + validateToolInputArguments(params.slug, params.args, {
62 + orgId: params.resolvedProject.orgId,
63 + projectId: params.resolvedProject.projectId,
64 + }).pipe(
65 + Effect.asVoid,
66 + Effect.catchIf(
67 + error => !(error instanceof ToolInputValidationError),
68 + () => perfDebugLog('execute.validation.schema_unavailable', { slug: params.slug })
69 + )
70 + );
ts/packages/cli/test/src/commands/errors.test.ts
+1 -1
@@ -8,7 +8,7 @@ import { MissingActingUserError } from 'src/commands/surface';
8 import {
9 ReportedToolExecutionError,
10 ToolExecutionError,
11 -} from 'src/commands/tools/commands/tools.execute.cmd';
11 +} from 'src/commands/tools/execute/tools.execute.errors';
12 import { LoginSessionError } from 'src/effects/browser-login';
13 import { ExpectedFailure } from 'src/effects/expected-failure';
14 import { ComposioCorePkgNotFound } from 'src/effects/find-composio-core-generated';
ts/packages/cli/test/src/commands/tools/execute/tools.execute.client.cmd.test.ts renamed
ts/packages/cli/test/src/commands/tools/execute/tools.execute.cmd.test.ts renamed
+2 -2
@@ -19,7 +19,7 @@ import * as redactModule from 'src/ui/redact';
19 import { cli, TestLive, MockConsole } from 'test/__utils__';
20 import { liveEnvConfigProvider } from 'test/__utils__/live-env-config-provider';
21 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
22 -import { parseParallelExecuteArgs } from 'src/commands/tools/commands/tools.execute.cmd';
22 +import { parseParallelExecuteArgs } from 'src/commands/tools/execute/tools.execute.parallel';
23 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
24 import type { ToolkitDetailed } from 'src/models/toolkits';
25 import { makeToolkitFixture } from 'test/__utils__/models/toolkits';
@@ -68,7 +68,7 @@ const noActiveConnectionEnvelope: ApiErrorEnvelope = {
68 // need a cache directory of their own, seeded with the fixture's user data.
69 const isolatedCacheConfigProvider = (fixture: string) => {
70 const cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-cli-test-cache-'));
71 - fs.cpSync(new URL(`../../../__fixtures__/${fixture}/.composio`, import.meta.url), cacheDir, {
71 + fs.cpSync(new URL(`../../../../__fixtures__/${fixture}/.composio`, import.meta.url), cacheDir, {
72 recursive: true,
73 });
74 // Fresh learned slugs keep the background catalog refresh from running, so
ts/packages/cli/test/src/commands/tools/execute/tools.execute.transport.test.ts renamed