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
-);