1
import { Args, Command, Options } from '@effect/cli';
2
+import * as fs from 'node:fs';
3
+import * as path from 'node:path';
4
import util from 'node:util';
3
-import { Effect, Option, Either } from 'effect';
5
+import { Effect, Option, Either, Exit, Fiber, Cause } from 'effect';
6
import { FileSystem } from '@effect/platform';
5
-import { JSONParse } from 'src/effects/json';
7
+import { parse as parseJsonWithComments } from 'comment-json';
8
+import { encodingForModel } from 'js-tiktoken';
9
import { redact } from 'src/ui/redact';
10
import { readStdin, readStdinIfPiped } from 'src/effects/read-stdin';
11
import { requireAuth } from 'src/effects/require-auth';
12
+import {
13
+ getCachedToolInputDefinition,
14
+ getOrFetchToolInputDefinition,
15
+ invalidateToolInputDefinition,
16
+ refreshToolInputDefinitionIfVersionChanged,
17
+ ToolInputValidationError,
18
+ validateToolInputArguments,
19
+ validateToolInputArgumentsWithDefinition,
20
+} from 'src/services/tool-input-validation';
21
import { TerminalUI } from 'src/services/terminal-ui';
22
import {
23
ActionExecuteConnectedAccountNotFoundError,
24
ToolsExecutor,
25
} from 'src/services/tools-executor';
14
-import type { ToolExecuteParams } from 'src/services/tools-executor';
26
+import type { ToolExecuteParams, ToolExecuteResponse } from 'src/services/tools-executor';
27
import { ComposioToolkitsRepository } from 'src/services/composio-clients';
28
import { ComposioUserContext } from 'src/services/user-context';
29
+import { ProjectContext } from 'src/services/project-context';
30
import {
31
extractApiErrorDetails,
32
extractMessage,
33
extractSlug,
34
} from 'src/utils/api-error-extraction';
22
-import { bold } from 'src/ui/colors';
35
import { handleHttpServerError } from 'src/effects/handle-http-error';
36
import { formatToolInputParameters } from '../format';
37
import { ComposioClientSingleton } from 'src/services/composio-clients';
39
resolveCommandProject,
40
formatResolveCommandProjectError,
41
} from 'src/services/command-project';
42
+import { commandHintStep } from 'src/services/command-hints';
43
+import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';
44
+import {
45
+ getFreshConsumerConnectedToolkitsFromCache,
46
+ refreshConsumerConnectedToolkitsCache,
47
+} from 'src/services/consumer-short-term-cache';
48
49
const slug = Args.text({ name: 'slug' }).pipe(
50
Args.withDescription('Tool slug (e.g. "GITHUB_CREATE_ISSUE")')
66
Options.withDescription('Developer project name override for this command')
67
);
68
69
+const getSchema = Options.boolean('get-schema').pipe(Options.withDefault(false));
70
+const dryRun = Options.boolean('dry-run').pipe(Options.withDefault(false));
71
+const skipConnectionCheck = Options.boolean('skip-connection-check').pipe(
72
+ Options.withDefault(false)
73
+);
74
+const skipToolParamsCheck = Options.boolean('skip-tool-params-check').pipe(
75
+ Options.withDefault(false)
76
+);
77
+const noVerify = Options.boolean('no-verify').pipe(Options.withDefault(false));
78
+
79
const resolveInput = (input: Option.Option<string>) =>
80
Effect.gen(function* () {
81
const fs = yield* FileSystem.FileSystem;
106
107
const parseArguments = (raw: string) =>
108
Effect.gen(function* () {
81
- const parsed = (yield* JSONParse(raw).pipe(
82
- Effect.mapError(
83
- () =>
84
- new Error('Invalid JSON input. Provide a JSON object, e.g. -d "{\\"key\\":\\"value\\"}"')
85
- )
86
- )) as unknown;
109
+ const parsed = yield* Effect.try({
110
+ try: () => {
111
+ try {
112
+ return JSON.parse(raw) as unknown;
113
+ } catch {
114
+ try {
115
+ return parseJsonWithComments(raw, undefined, true) as unknown;
116
+ } catch {
117
+ return Function(`"use strict"; return (${raw});`)() as unknown;
118
+ }
119
+ }
120
+ },
121
+ catch: () =>
122
+ new Error(
123
+ 'Invalid JSON input. Provide JSON or a JS-style object literal, e.g. -d \'{ "key": "value" }\''
124
+ ),
125
+ });
126
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
127
return yield* Effect.fail(
89
- new Error('Expected a JSON object for tool arguments, e.g. -d "{\\"key\\":\\"value\\"}"')
128
+ new Error('Expected a JSON object for tool arguments, e.g. -d \'{ "key": "value" }\'')
129
);
130
}
131
return parsed as Record<string, unknown>;
139
return prefix;
140
};
141
103
-const connectionTips = (toolSlug: string, surface: 'root' | 'manage') => {
142
+const connectionTips = (toolSlug: string, surface: 'root' | 'manage' | 'dev') => {
143
const toolkit = toolkitFromToolSlug(toolSlug);
144
+ const executeStep =
145
+ surface === 'dev'
146
+ ? commandHintStep('Retry', 'dev.execute', {
147
+ slug: toolSlug,
148
+ userId: '<user-id>',
149
+ data: '...',
150
+ })
151
+ : commandHintStep('Retry', 'root.execute', { slug: toolSlug, data: '...' });
152
if (!toolkit) {
106
- return `Retry: ${bold(`composio execute ${toolSlug} ...`)}`;
153
+ return executeStep;
154
}
155
return [
109
- `Link the toolkit first: ${bold(
110
- surface === 'root'
111
- ? `composio link ${toolkit}`
112
- : `composio manage connected-accounts link ${toolkit} --user-id "<user-id>"`
113
- )}`,
114
- `Then retry: ${bold(
115
- surface === 'root'
116
- ? `composio execute ${toolSlug} ...`
117
- : `composio manage tools execute ${toolSlug} ...`
118
- )}`,
156
+ commandHintStep(
157
+ 'Link the toolkit first',
158
+ surface === 'dev' ? 'manage.connectedAccounts.link' : 'root.link',
159
+ surface === 'dev' ? { toolkit, userId: '<user-id>' } : { toolkit }
160
+ ),
161
+ executeStep.replace('Retry:', 'Then retry:'),
162
].join('\n');
163
};
164
165
+const isNoActiveConnectionError = (details: { code?: number; slug?: string } | undefined) =>
166
+ details?.code === 4302 || details?.slug === 'ToolRouterV2_NoActiveConnection';
167
+
168
+const noActiveConnectionMessage = (toolSlug: string) => {
169
+ const toolkit = toolkitFromToolSlug(toolSlug);
170
+ if (!toolkit) {
171
+ return 'No active connection found for this tool call. Link the required toolkit/app, then retry.';
172
+ }
173
+ return `No active connection found for toolkit "${toolkit}". Run \`composio link ${toolkit}\`, then retry.`;
174
+};
175
+
176
const ciRedactReplacer = (_key: string, value: unknown): unknown => {
177
if (typeof value !== 'string') return value;
178
if (_key === 'logId') return redact({ value, prefix: 'log_' });
205
};
206
};
207
208
+const EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD = 10_000;
209
+let executeOutputEncoder: ReturnType<typeof encodingForModel> | undefined;
210
+
211
+const getExecuteOutputEncoder = () => {
212
+ if (!executeOutputEncoder) {
213
+ executeOutputEncoder = encodingForModel('gpt-4o');
214
+ }
215
+ return executeOutputEncoder;
216
+};
217
+
218
+type StoredExecuteOutputSummary = {
219
+ readonly successful: true;
220
+ readonly error: null;
221
+ readonly logId: string;
222
+ readonly storedInFile: true;
223
+ readonly tokenCount: number;
224
+ readonly outputFilePath: string;
225
+};
226
+
227
+const serializeExecuteOutput = (result: unknown): string =>
228
+ JSON.stringify(result, ciRedactReplacer, 2);
229
+
230
+const randomToken = (length = 16) => crypto.randomUUID().replace(/-/g, '').slice(0, length);
231
+
232
+const persistLargeExecuteOutput = (json: string): StoredExecuteOutputSummary => {
233
+ const directoryPath = path.join('/tmp/composio', randomToken());
234
+ const outputHash = randomToken();
235
+ const outputFilePath = path.join(directoryPath, `output-${outputHash}.json`);
236
+ fs.mkdirSync(directoryPath, { recursive: true });
237
+ fs.writeFileSync(outputFilePath, json, 'utf8');
238
+
239
+ return {
240
+ successful: true,
241
+ error: null,
242
+ logId: '',
243
+ storedInFile: true,
244
+ tokenCount: getExecuteOutputEncoder().encode(json).length,
245
+ outputFilePath,
246
+ };
247
+};
248
+
249
+const perfDebugEpoch = Date.now();
250
+const perfDebugLog = (label: string, details: Record<string, unknown> = {}) => {
251
+ if (!isPerfDebugEnabled()) return;
252
+ console.error(
253
+ `[perf] ${JSON.stringify({
254
+ phase: 'event',
255
+ label,
256
+ elapsedMs: Date.now() - perfDebugEpoch,
257
+ ...details,
258
+ })}`
259
+ );
260
+};
261
+const toolDebugLog = (label: string, details: Record<string, unknown> = {}) => {
262
+ if (!isToolDebugEnabled()) return;
263
+ console.error(`[tool-debug] ${JSON.stringify({ label, ...details })}`);
264
+};
265
+
266
+const prepareExecuteOutput = (result: ToolExecuteResponse) => {
267
+ const json = serializeExecuteOutput(result);
268
+ const tokenCount = getExecuteOutputEncoder().encode(json).length;
269
+ if (tokenCount <= EXECUTE_INLINE_OUTPUT_TOKEN_THRESHOLD) {
270
+ return {
271
+ kind: 'inline' as const,
272
+ json,
273
+ };
274
+ }
275
+
276
+ return {
277
+ kind: 'file' as const,
278
+ summary: {
279
+ ...persistLargeExecuteOutput(json),
280
+ logId: result.logId,
281
+ } satisfies StoredExecuteOutputSummary,
282
+ };
283
+};
284
+
285
const normalizeError = (error: unknown): unknown => {
286
let current: unknown = error;
287
const seen = new Set<unknown>();
322
'services/HttpServerError',
323
handleHttpServerError(ui, {
324
fallbackMessage: `Tool "${toolSlug}" not found.`,
194
- hint: 'Browse available tools:\n> composio manage tools list',
325
+ hint: [
326
+ commandHintStep('Browse available toolkits', 'manage.toolkits.list'),
327
+ commandHintStep('Then list tools', 'root.tools.list'),
328
+ ].join('\n'),
329
fallbackValue: Option.none(),
330
searchForSuggestions: () =>
331
repo.searchTools({ search: toolSlug, limit: 3 }).pipe(
353
const handleExecutionError = (
354
ui: TerminalUI,
355
error: unknown,
222
- context: { toolSlug: string; surface: 'root' | 'manage' }
356
+ context: { toolSlug: string; surface: 'root' | 'manage' | 'dev' }
357
) =>
358
Effect.gen(function* () {
359
const normalized = normalizeError(error);
360
+ if (normalized instanceof ToolInputValidationError) {
361
+ yield* ui.log.error(`Input validation failed for ${context.toolSlug}`);
362
+ yield* ui.note(
363
+ [`Schema: ${normalized.schemaPath}`, ...normalized.issues.map(issue => `- ${issue}`)].join(
364
+ '\n'
365
+ ),
366
+ 'Tool schema validation'
367
+ );
368
+ return { error: normalized.message, slug: context.toolSlug };
369
+ }
370
+
371
const connAccountDetails =
372
normalized instanceof ActionExecuteConnectedAccountNotFoundError
373
? normalized.details
378
extractApiErrorDetails(normalized) ??
379
extractApiErrorDetails(connAccountDetails);
380
const slugValue = apiDetails?.slug ?? extractSlug(error) ?? extractSlug(connAccountDetails);
381
+ const noActiveConnection =
382
+ normalized instanceof ActionExecuteConnectedAccountNotFoundError ||
383
+ isNoActiveConnectionError(apiDetails);
384
const message = extractMessage(apiDetails) ?? extractMessage(normalized) ?? 'Unknown error';
385
386
+ if (noActiveConnection) {
387
+ const rewrittenMessage = noActiveConnectionMessage(context.toolSlug);
388
+ yield* ui.log.error(rewrittenMessage);
389
+ if (toolkitFromToolSlug(context.toolSlug)) {
390
+ yield* ui.note(connectionTips(context.toolSlug, context.surface), 'Tips');
391
+ }
392
+ return { error: rewrittenMessage, slug: slugValue ?? context.toolSlug };
393
+ }
394
+
395
yield* ui.log.error(message);
396
397
const detailsObject =
417
constructor(readonly message: string) {}
418
}
419
263
-const runToolsExecute = (params: {
420
+type CachedValidationDecision =
421
+ | { readonly status: 'valid' | 'stale' }
422
+ | { readonly status: 'fail'; readonly error: unknown };
423
+
424
+type ValidationState = {
425
+ readonly cacheHit: boolean;
426
+ readonly validationGuard: Effect.Effect<never, unknown>;
427
+ readonly awaitCachedValidationDecision: Effect.Effect<CachedValidationDecision, never> | null;
428
+};
429
+
430
+type CachedDefinition = {
431
+ readonly schemaPath: string;
432
+ readonly schema: Record<string, unknown>;
433
+ readonly version: string | null;
434
+} | null;
435
+
436
+const validationGuardFromFiber = (validationFiber: Fiber.RuntimeFiber<unknown, unknown>) =>
437
+ Fiber.await(validationFiber).pipe(
438
+ Effect.flatMap(
439
+ Exit.match({
440
+ onFailure: cause => {
441
+ const defect = Cause.failureOption(cause);
442
+ if (Option.isSome(defect) && defect.value instanceof ToolInputValidationError) {
443
+ return Effect.failCause(cause);
444
+ }
445
+ return Effect.never;
446
+ },
447
+ onSuccess: () => Effect.never,
448
+ })
449
+ )
450
+ );
451
+
452
+const spawnBackgroundValidationGuard = (params: {
453
+ readonly slug: string;
454
+ readonly args: Record<string, unknown>;
455
+ readonly resolvedProject: {
456
+ readonly orgId: string;
457
+ readonly projectId: string;
458
+ };
459
+}) =>
460
+ Effect.gen(function* () {
461
+ perfDebugLog('execute.validation.background_spawn', { slug: params.slug });
462
+ const validationFiber = yield* validateToolInputArguments(params.slug, params.args, {
463
+ orgId: params.resolvedProject.orgId,
464
+ projectId: params.resolvedProject.projectId,
465
+ }).pipe(Effect.forkDaemon);
466
+ perfDebugLog('execute.validation.background_spawned', { slug: params.slug });
467
+ return validationGuardFromFiber(validationFiber);
468
+ });
469
+
470
+const initializeValidationState = (params: {
471
+ readonly slug: string;
472
+ readonly args: Record<string, unknown>;
473
+ readonly cachedDefinition: CachedDefinition;
474
+ readonly resolvedProject: {
475
+ readonly orgId: string;
476
+ readonly projectId: string;
477
+ };
478
+}) =>
479
+ Effect.gen(function* () {
480
+ if (!params.cachedDefinition) {
481
+ perfDebugLog('execute.validation.cache_miss', { slug: params.slug });
482
+ return {
483
+ cacheHit: false,
484
+ validationGuard: Effect.never,
485
+ awaitCachedValidationDecision: null,
486
+ } satisfies ValidationState;
487
+ }
488
+ const cachedDefinition = params.cachedDefinition;
489
+
490
+ perfDebugLog('execute.validation.cache_hit', {
491
+ slug: params.slug,
492
+ cachedVersion: cachedDefinition.version,
493
+ });
494
+ const versionCheckFiber = yield* refreshToolInputDefinitionIfVersionChanged(
495
+ params.slug,
496
+ cachedDefinition.version,
497
+ {
498
+ orgId: params.resolvedProject.orgId,
499
+ projectId: params.resolvedProject.projectId,
500
+ }
501
+ ).pipe(
502
+ Effect.tap(result =>
503
+ Effect.sync(() =>
504
+ perfDebugLog('execute.validation.version_check_done', {
505
+ slug: params.slug,
506
+ cachedVersion: cachedDefinition.version,
507
+ latestVersion: result.latestVersion,
508
+ isStale: result.isStale,
509
+ })
510
+ )
511
+ ),
512
+ Effect.either,
513
+ Effect.forkDaemon
514
+ );
515
+ const cachedValidationDecisionFiber = yield* Effect.gen(function* () {
516
+ perfDebugLog('execute.validation.cached_start', { slug: params.slug });
517
+ const result = yield* validateToolInputArgumentsWithDefinition(
518
+ params.slug,
519
+ params.args,
520
+ cachedDefinition
521
+ ).pipe(Effect.either);
522
+ perfDebugLog('execute.validation.cached_end', {
523
+ slug: params.slug,
524
+ successful: Either.isRight(result),
525
+ });
526
+ if (Either.isRight(result)) {
527
+ return { status: 'valid' as const };
528
+ }
529
+
530
+ const freshnessEither = yield* Fiber.join(versionCheckFiber);
531
+ const isStale = Either.isRight(freshnessEither) && freshnessEither.right.isStale;
532
+ perfDebugLog('execute.validation.cached_failed', {
533
+ slug: params.slug,
534
+ cacheStillCurrent: !isStale,
535
+ });
536
+ return isStale
537
+ ? { status: 'stale' as const }
538
+ : { status: 'fail' as const, error: result.left };
539
+ }).pipe(Effect.forkDaemon);
540
+ const awaitCachedValidationDecision = Fiber.join(
541
+ cachedValidationDecisionFiber
542
+ ) as Effect.Effect<CachedValidationDecision, never>;
543
+
544
+ return {
545
+ cacheHit: true,
546
+ awaitCachedValidationDecision,
547
+ validationGuard: awaitCachedValidationDecision.pipe(
548
+ Effect.flatMap(decision => {
549
+ if (decision.status === 'fail') {
550
+ return Effect.fail(decision.error);
551
+ }
552
+
553
+ return Effect.never;
554
+ })
555
+ ),
556
+ } satisfies ValidationState;
557
+ });
558
+
559
+type DryRunSummary = {
560
+ readonly successful: true;
561
+ readonly dryRun: true;
562
+ readonly slug: string;
563
+ readonly arguments: Record<string, unknown>;
564
+ readonly userId: string;
565
+ readonly schemaPath?: string;
566
+ readonly schemaVersion?: string | null;
567
+};
568
+
569
+type RunToolsExecuteParams = {
570
slug: string;
571
data: Option.Option<string>;
572
userId: Option.Option<string>;
573
projectName: Option.Option<string>;
268
- rootOnly: boolean;
269
-}) =>
574
+ surface: 'root' | 'manage' | 'dev';
575
+ projectMode: 'consumer' | 'developer';
576
+ getSchema: boolean;
577
+ dryRun: boolean;
578
+ skipConnectionCheck: boolean;
579
+ skipToolParamsCheck: boolean;
580
+ noVerify: boolean;
581
+};
582
+
583
+type ResolvedExecuteContext = {
584
+ readonly ui: TerminalUI;
585
+ readonly executor: ToolsExecutor;
586
+ readonly resolvedProject: {
587
+ readonly orgId: string;
588
+ readonly projectId: string;
589
+ readonly projectType: 'CONSUMER' | 'DEVELOPER';
590
+ readonly consumerUserId?: string;
591
+ };
592
+ readonly args: Record<string, unknown>;
593
+ readonly resolvedUserId: string;
594
+ readonly executeParams: ToolExecuteParams;
595
+};
596
+
597
+const emitCachedSchema = (
598
+ ui: TerminalUI,
599
+ slug: string,
600
+ definition: {
601
+ readonly version: string | null;
602
+ readonly schemaPath: string;
603
+ readonly schema: Record<string, unknown>;
604
+ }
605
+) =>
606
Effect.gen(function* () {
271
- if (!(yield* requireAuth)) return;
607
+ yield* ui.log.message(
608
+ `Schema saved, inspect keys like: jq '{required: (.inputSchema.required // []), keys: (.inputSchema.properties | keys)}' ${definition.schemaPath}`
609
+ );
610
+ yield* ui.output(
611
+ JSON.stringify(
612
+ {
613
+ slug,
614
+ version: definition.version,
615
+ schemaPath: definition.schemaPath,
616
+ inputSchema: definition.schema,
617
+ },
618
+ null,
619
+ 2
620
+ )
621
+ );
622
+ });
623
624
+const resolveExecuteContext = (params: RunToolsExecuteParams) =>
625
+ Effect.gen(function* () {
626
+ const resolvedProject = yield* resolveCommandProject({
627
+ mode: params.projectMode,
628
+ projectName:
629
+ params.surface === 'root' ? undefined : Option.getOrUndefined(params.projectName),
630
+ }).pipe(Effect.mapError(formatResolveCommandProjectError));
631
const ui = yield* TerminalUI;
632
const executor = yield* ToolsExecutor;
633
const clientSingleton = yield* ComposioClientSingleton;
634
const userContext = yield* ComposioUserContext;
635
+ const projectContext = yield* ProjectContext;
636
637
const input = yield* resolveInput(params.data);
638
const args = yield* parseArguments(input);
280
- const resolvedProject = yield* resolveCommandProject({
281
- mode: 'consumer',
282
- projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
283
- }).pipe(Effect.mapError(formatResolveCommandProjectError));
639
+ const localProjectContext = yield* projectContext.resolve.pipe(
640
+ Effect.catchAll(() => Effect.succeed(Option.none()))
641
+ );
642
+ const localTestUserId = Option.flatMap(localProjectContext, keys => keys.testUserId);
643
const resolvedUserId =
644
resolvedProject.projectType === 'CONSUMER'
645
? Option.fromNullable(resolvedProject.consumerUserId)
646
: Option.match(params.userId, {
647
onSome: value => Option.some(value),
289
- onNone: () => userContext.data.testUserId,
648
+ onNone: () => Option.orElse(localTestUserId, () => userContext.data.testUserId),
649
});
650
+
651
if (Option.isNone(resolvedUserId)) {
652
return yield* Effect.fail(
653
new Error(
294
- 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
654
+ params.projectMode === 'developer'
655
+ ? 'Missing user id. Provide --user-id or run `composio dev init` to set a playground test user id.'
656
+ : 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
657
)
658
);
659
}
660
+
661
const client = yield* clientSingleton.getFor({
662
orgId: resolvedProject.orgId,
663
projectId: resolvedProject.projectId,
664
});
665
303
- const executeParams: ToolExecuteParams = {
304
- userId: resolvedUserId.value,
305
- arguments: args,
306
- client,
307
- };
666
+ return {
667
+ ui,
668
+ executor,
669
+ resolvedProject,
670
+ args,
671
+ resolvedUserId: resolvedUserId.value,
672
+ executeParams: {
673
+ userId: resolvedUserId.value,
674
+ arguments: args,
675
+ client,
676
+ },
677
+ } satisfies ResolvedExecuteContext;
678
+ });
679
309
- yield* ui.useMakeSpinner(`Executing tool "${params.slug}"...`, spinner =>
680
+const runConnectedToolkitFailFast = (params: {
681
+ readonly slug: string;
682
+ readonly surface: 'root' | 'manage' | 'dev';
683
+ readonly ui: TerminalUI;
684
+ readonly resolvedProject: ResolvedExecuteContext['resolvedProject'];
685
+ readonly resolvedUserId: string;
686
+ readonly skipConnectionCheck: boolean;
687
+ readonly noVerify: boolean;
688
+}) =>
689
+ Effect.gen(function* () {
690
+ if (params.skipConnectionCheck || params.noVerify) {
691
+ perfDebugLog('execute.connected_toolkits.skipped', {
692
+ slug: params.slug,
693
+ reason: params.noVerify ? 'no-verify' : 'skip-connection-check',
694
+ });
695
+ return;
696
+ }
697
+ if (params.resolvedProject.projectType !== 'CONSUMER') return;
698
+
699
+ perfDebugLog('execute.connected_toolkits.refresh_start', {
700
+ slug: params.slug,
701
+ orgId: params.resolvedProject.orgId,
702
+ consumerUserId: params.resolvedUserId,
703
+ });
704
+ yield* refreshConsumerConnectedToolkitsCache({
705
+ orgId: params.resolvedProject.orgId,
706
+ consumerUserId: params.resolvedUserId,
707
+ }).pipe(
708
+ Effect.tap(() =>
709
+ Effect.sync(() =>
710
+ perfDebugLog('execute.connected_toolkits.refresh_end', {
711
+ slug: params.slug,
712
+ orgId: params.resolvedProject.orgId,
713
+ consumerUserId: params.resolvedUserId,
714
+ successful: true,
715
+ })
716
+ )
717
+ ),
718
+ Effect.catchAll(() =>
719
+ Effect.sync(() =>
720
+ perfDebugLog('execute.connected_toolkits.refresh_end', {
721
+ slug: params.slug,
722
+ orgId: params.resolvedProject.orgId,
723
+ consumerUserId: params.resolvedUserId,
724
+ successful: false,
725
+ })
726
+ )
727
+ ),
728
+ Effect.forkDaemon,
729
+ Effect.asVoid
730
+ );
731
+
732
+ const toolkit = toolkitFromToolSlug(params.slug);
733
+ if (!toolkit) return;
734
+
735
+ const cachedToolkits = yield* getFreshConsumerConnectedToolkitsFromCache({
736
+ orgId: params.resolvedProject.orgId,
737
+ consumerUserId: params.resolvedUserId,
738
+ });
739
+ perfDebugLog(
740
+ Option.isSome(cachedToolkits)
741
+ ? 'execute.connected_toolkits.cache_hit'
742
+ : 'execute.connected_toolkits.cache_miss',
743
+ {
744
+ slug: params.slug,
745
+ toolkit,
746
+ orgId: params.resolvedProject.orgId,
747
+ consumerUserId: params.resolvedUserId,
748
+ cachedToolkits: Option.isSome(cachedToolkits) ? cachedToolkits.value : undefined,
749
+ }
750
+ );
751
+
752
+ if (Option.isSome(cachedToolkits) && !cachedToolkits.value.includes(toolkit)) {
753
+ perfDebugLog('execute.connected_toolkits.fail_fast', {
754
+ slug: params.slug,
755
+ toolkit,
756
+ orgId: params.resolvedProject.orgId,
757
+ consumerUserId: params.resolvedUserId,
758
+ });
759
+ 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.`;
760
+ yield* params.ui.log.error(message);
761
+ yield* params.ui.note(connectionTips(params.slug, params.surface), 'Tips');
762
+ yield* params.ui.output(
763
+ JSON.stringify(
764
+ {
765
+ successful: false,
766
+ error: message,
767
+ slug: params.slug,
768
+ },
769
+ ciRedactReplacer,
770
+ 2
771
+ )
772
+ );
773
+ return yield* Effect.fail(new ToolExecutionError(message));
774
+ }
775
+ });
776
+
777
+const runExecuteWithSpinner = (params: {
778
+ readonly slug: string;
779
+ readonly surface: 'root' | 'manage' | 'dev';
780
+ readonly dryRun: boolean;
781
+ readonly ui: TerminalUI;
782
+ readonly executor: ToolsExecutor;
783
+ readonly resolvedProject: ResolvedExecuteContext['resolvedProject'];
784
+ readonly args: Record<string, unknown>;
785
+ readonly resolvedUserId: string;
786
+ readonly executeParams: ToolExecuteParams;
787
+ readonly skipToolParamsCheck: boolean;
788
+ readonly noVerify: boolean;
789
+}) =>
790
+ Effect.gen(function* () {
791
+ const verificationDisabled = params.noVerify || params.skipToolParamsCheck;
792
+ const cachedDefinition = verificationDisabled
793
+ ? null
794
+ : yield* getCachedToolInputDefinition(params.slug);
795
+ const validationState = verificationDisabled
796
+ ? ({
797
+ cacheHit: false,
798
+ validationGuard: Effect.never,
799
+ awaitCachedValidationDecision: null,
800
+ } satisfies ValidationState)
801
+ : yield* initializeValidationState({
802
+ slug: params.slug,
803
+ args: params.args,
804
+ cachedDefinition,
805
+ resolvedProject: params.resolvedProject,
806
+ });
807
+
808
+ yield* params.ui.useMakeSpinner(`Executing tool "${params.slug}"...`, spinner =>
809
Effect.gen(function* () {
311
- const resultEither = yield* executor
312
- .execute(params.slug, executeParams)
810
+ let validationGuard = validationState.validationGuard;
811
+ if (!verificationDisabled && !validationState.cacheHit) {
812
+ validationGuard = yield* spawnBackgroundValidationGuard({
813
+ slug: params.slug,
814
+ args: params.args,
815
+ resolvedProject: params.resolvedProject,
816
+ });
817
+ }
818
+
819
+ if (params.dryRun) {
820
+ const definition = verificationDisabled
821
+ ? null
822
+ : (cachedDefinition ??
823
+ (yield* getOrFetchToolInputDefinition(params.slug, {
824
+ orgId: params.resolvedProject.orgId,
825
+ projectId: params.resolvedProject.projectId,
826
+ })));
827
+ if (definition) {
828
+ yield* validateToolInputArgumentsWithDefinition(params.slug, params.args, definition);
829
+ }
830
+ const summary: DryRunSummary = {
831
+ successful: true,
832
+ dryRun: true,
833
+ slug: params.slug,
834
+ arguments: params.args,
835
+ userId: params.resolvedUserId,
836
+ schemaPath: definition?.schemaPath,
837
+ schemaVersion: definition?.version,
838
+ };
839
+ yield* spinner.stop('Dry run successful');
840
+ yield* params.ui.log.message(
841
+ verificationDisabled
842
+ ? 'No tool was executed. Local validation was skipped.'
843
+ : 'No tool was executed. Arguments were validated locally only.'
844
+ );
845
+ yield* params.ui.output(JSON.stringify(summary, ciRedactReplacer, 2));
846
+ return;
847
+ }
848
+
849
+ perfDebugLog('execute.tool_call.start', { slug: params.slug });
850
+ const resultEither = yield* params.executor
851
+ .execute(params.slug, params.executeParams)
852
+ .pipe(Effect.raceFirst(validationGuard))
853
.pipe(Effect.either);
854
+ toolDebugLog('execute_result', {
855
+ slug: params.slug,
856
+ result: Either.isRight(resultEither) ? resultEither.right : resultEither.left,
857
+ });
858
+ perfDebugLog('execute.tool_call.end', {
859
+ slug: params.slug,
860
+ successful: Either.isRight(resultEither),
861
+ });
862
863
if (Either.isLeft(resultEither)) {
864
+ yield* invalidateToolInputDefinition(params.slug).pipe(
865
+ Effect.catchAll(() => Effect.void)
866
+ );
867
yield* spinner.error();
317
- const summary = yield* handleExecutionError(ui, resultEither.left, {
868
+ const summary = yield* handleExecutionError(params.ui, resultEither.left, {
869
toolSlug: params.slug,
319
- surface: params.rootOnly ? 'root' : 'manage',
870
+ surface: params.surface,
871
});
321
- yield* ui.output(JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2));
872
+ yield* params.ui.output(
873
+ JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)
874
+ );
875
return yield* Effect.fail(new ToolExecutionError(summary.error));
876
}
877
878
const result = resultEither.right;
879
+ if (validationState.awaitCachedValidationDecision) {
880
+ const decision = yield* validationState.awaitCachedValidationDecision;
881
+ if (decision.status === 'fail') {
882
+ perfDebugLog('execute.validation.post_success_failure_ignored', {
883
+ slug: params.slug,
884
+ });
885
+ }
886
+ }
887
888
if (!result.successful) {
889
+ yield* invalidateToolInputDefinition(params.slug).pipe(
890
+ Effect.catchAll(() => Effect.void)
891
+ );
892
const logId = result.logId
893
? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
894
: '';
895
yield* spinner.error(`Execution failed${logId}`);
896
333
- const summary = yield* handleExecutionError(ui, result.error ?? result, {
897
+ const summary = yield* handleExecutionError(params.ui, result.error ?? result, {
898
toolSlug: params.slug,
335
- surface: params.rootOnly ? 'root' : 'manage',
899
+ surface: params.surface,
900
});
337
- yield* ui.output(JSON.stringify(result, ciRedactReplacer, 2));
901
+ yield* params.ui.output(JSON.stringify(result, ciRedactReplacer, 2));
902
return yield* Effect.fail(new ToolExecutionError(summary.error));
903
}
904
906
? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
907
: '';
908
yield* spinner.stop(`Execution successful${logId}`);
345
- yield* ui.log.message(`Response\n${JSON.stringify(result, ciRedactReplacer, 2)}`);
346
- yield* ui.output(JSON.stringify(result, ciRedactReplacer, 2));
909
+ const output = prepareExecuteOutput(result);
910
+ if (output.kind === 'file') {
911
+ yield* params.ui.log.message(
912
+ `Response stored in ${output.summary.outputFilePath} (${output.summary.tokenCount} tokens)`
913
+ );
914
+ yield* params.ui.output(JSON.stringify(output.summary, ciRedactReplacer, 2));
915
+ return;
916
+ }
917
+
918
+ yield* params.ui.log.message(`Response\n${output.json}`);
919
+ yield* params.ui.output(output.json);
920
})
921
);
922
});
923
924
+const runToolsExecute = (params: RunToolsExecuteParams) =>
925
+ Effect.gen(function* () {
926
+ if (!(yield* requireAuth)) return;
927
+
928
+ const context = yield* resolveExecuteContext(params);
929
+ if (params.getSchema) {
930
+ const definition = yield* getOrFetchToolInputDefinition(params.slug, {
931
+ orgId: context.resolvedProject.orgId,
932
+ projectId: context.resolvedProject.projectId,
933
+ });
934
+ yield* emitCachedSchema(context.ui, params.slug, definition);
935
+ return;
936
+ }
937
+
938
+ yield* runConnectedToolkitFailFast({
939
+ slug: params.slug,
940
+ surface: params.surface,
941
+ ui: context.ui,
942
+ resolvedProject: context.resolvedProject,
943
+ resolvedUserId: context.resolvedUserId,
944
+ skipConnectionCheck: params.skipConnectionCheck,
945
+ noVerify: params.noVerify,
946
+ });
947
+ toolDebugLog('execute_params', {
948
+ slug: params.slug,
949
+ userId: context.resolvedUserId,
950
+ arguments: context.args,
951
+ projectId: context.resolvedProject.projectId,
952
+ orgId: context.resolvedProject.orgId,
953
+ });
954
+ perfDebugLog('execute.prepare', {
955
+ slug: params.slug,
956
+ surface: params.surface,
957
+ projectMode: params.projectMode,
958
+ });
959
+ yield* runExecuteWithSpinner({
960
+ slug: params.slug,
961
+ surface: params.surface,
962
+ dryRun: params.dryRun,
963
+ ui: context.ui,
964
+ executor: context.executor,
965
+ resolvedProject: context.resolvedProject,
966
+ args: context.args,
967
+ resolvedUserId: context.resolvedUserId,
968
+ executeParams: context.executeParams,
969
+ skipToolParamsCheck: params.skipToolParamsCheck,
970
+ noVerify: params.noVerify,
971
+ });
972
+ });
973
+
974
export const toolsCmd$Execute = Command.make(
975
'execute',
353
- { slug, data, userId, projectName },
354
- ({ slug, data, userId, projectName }) =>
355
- runToolsExecute({ slug, data, userId, projectName, rootOnly: false })
976
+ {
977
+ slug,
978
+ data,
979
+ userId,
980
+ projectName,
981
+ getSchema,
982
+ dryRun,
983
+ skipConnectionCheck,
984
+ skipToolParamsCheck,
985
+ noVerify,
986
+ },
987
+ ({
988
+ slug,
989
+ data,
990
+ userId,
991
+ projectName,
992
+ getSchema,
993
+ dryRun,
994
+ skipConnectionCheck,
995
+ skipToolParamsCheck,
996
+ noVerify,
997
+ }) =>
998
+ runToolsExecute({
999
+ slug,
1000
+ data,
1001
+ userId,
1002
+ projectName,
1003
+ surface: 'manage',
1004
+ projectMode: 'consumer',
1005
+ getSchema,
1006
+ dryRun,
1007
+ skipConnectionCheck,
1008
+ skipToolParamsCheck,
1009
+ noVerify,
1010
+ })
1011
).pipe(
1012
Command.withDescription(
1013
[
359
- 'Execute a tool by slug with JSON arguments.',
1014
+ 'Execute a tool by slug with JSON arguments, or preview it locally with --dry-run.',
1015
+ 'Arguments are validated against cached tool schemas in `~/.composio/tool_definitions/` when available.',
1016
+ 'Use `--get-schema` to fetch the latest raw input schema into the cache and print it without executing the tool.',
1017
+ 'Use `composio tools info <slug>` for the same schema plus a short human summary and jq hints.',
1018
+ 'Successful execute responses are parsed immediately, and failed calls validate inputs against cached schemas when available, so it is often fastest to just try the real call first before inspecting schema.',
1019
+ '',
1020
+ 'Examples:',
1021
+ ' composio execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1022
+ ' composio execute GMAIL_SEND_EMAIL --skip-connection-check -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1023
+ ' composio execute GMAIL_SEND_EMAIL --skip-tool-params-check -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1024
+ ' composio execute GMAIL_SEND_EMAIL --no-verify -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1025
+ ' composio execute GMAIL_SEND_EMAIL --dry-run -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1026
+ ' composio execute GMAIL_SEND_EMAIL --get-schema',
1027
'',
1028
'Related:',
1029
+ ' composio run \'const first = await execute("TOOL_SLUG", { ... }); const second = await execute("OTHER_TOOL", { ... }); console.log({ first, second })\'',
1030
' composio search "<query>"',
1031
' composio link <toolkit>',
1032
].join('\n')
1033
)
1034
);
1035
368
-export const rootToolsCmd$Execute = Command.make('execute', { slug, data }, ({ slug, data }) =>
369
- runToolsExecute({
370
- slug,
371
- data,
372
- userId: Option.none(),
373
- projectName: Option.none(),
374
- rootOnly: true,
375
- })
1036
+export const rootToolsCmd$Execute = Command.make(
1037
+ 'execute',
1038
+ { slug, data, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, noVerify },
1039
+ ({ slug, data, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, noVerify }) =>
1040
+ runToolsExecute({
1041
+ slug,
1042
+ data,
1043
+ userId: Option.none(),
1044
+ projectName: Option.none(),
1045
+ surface: 'root',
1046
+ projectMode: 'consumer',
1047
+ getSchema,
1048
+ dryRun,
1049
+ skipConnectionCheck,
1050
+ skipToolParamsCheck,
1051
+ noVerify,
1052
+ })
1053
).pipe(
1054
Command.withDescription(
1055
[
379
- 'Execute a tool by slug with JSON arguments.',
1056
+ 'Execute a tool by slug with JSON arguments, or preview it locally with --dry-run.',
1057
+ 'Arguments are validated against cached tool schemas in `~/.composio/tool_definitions/` when available.',
1058
+ 'Use `--get-schema` to fetch the latest raw input schema into the cache and print it without executing the tool.',
1059
+ 'Use `composio tools info <slug>` for the same schema plus a short human summary and jq hints.',
1060
+ 'Successful execute responses are parsed immediately, and failed calls validate inputs against cached schemas when available, so it is often fastest to just try the real call first before inspecting schema.',
1061
+ '',
1062
+ 'Examples:',
1063
+ ' composio execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1064
+ ' composio execute GMAIL_SEND_EMAIL --skip-connection-check -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1065
+ ' composio execute GMAIL_SEND_EMAIL --skip-tool-params-check -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1066
+ ' composio execute GMAIL_SEND_EMAIL --no-verify -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1067
+ ' composio execute GMAIL_SEND_EMAIL --dry-run -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1068
+ ' composio execute GMAIL_SEND_EMAIL --get-schema',
1069
'',
1070
'Related:',
1071
+ ' composio run \'const first = await execute("TOOL_SLUG", { ... }); const second = await execute("OTHER_TOOL", { ... }); console.log({ first, second })\'',
1072
' composio search "<query>"',
1073
' composio link <toolkit>',
1074
].join('\n')
1075
)
1076
);
1077
+
1078
+export const devToolsCmd$Execute = Command.make(
1079
+ 'execute',
1080
+ {
1081
+ slug,
1082
+ data,
1083
+ userId,
1084
+ projectName,
1085
+ getSchema,
1086
+ dryRun,
1087
+ skipConnectionCheck,
1088
+ skipToolParamsCheck,
1089
+ noVerify,
1090
+ },
1091
+ ({
1092
+ slug,
1093
+ data,
1094
+ userId,
1095
+ projectName,
1096
+ getSchema,
1097
+ dryRun,
1098
+ skipConnectionCheck,
1099
+ skipToolParamsCheck,
1100
+ noVerify,
1101
+ }) =>
1102
+ runToolsExecute({
1103
+ slug,
1104
+ data,
1105
+ userId,
1106
+ projectName,
1107
+ surface: 'dev',
1108
+ projectMode: 'developer',
1109
+ getSchema,
1110
+ dryRun,
1111
+ skipConnectionCheck,
1112
+ skipToolParamsCheck,
1113
+ noVerify,
1114
+ })
1115
+).pipe(
1116
+ Command.withDescription(
1117
+ [
1118
+ 'Execute a tool with your playground test user id against your developer project auth configs.',
1119
+ 'Uses --user-id when provided, otherwise falls back to your local or global playground test user id.',
1120
+ 'Arguments are validated against cached tool schemas in `~/.composio/tool_definitions/` when available.',
1121
+ '',
1122
+ 'Examples:',
1123
+ ' composio dev execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1124
+ ' composio dev execute GMAIL_SEND_EMAIL --dry-run -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1125
+ ' composio dev execute GMAIL_SEND_EMAIL --get-schema',
1126
+ ].join('\n')
1127
+ )
1128
+);