1
import { CommandInputError } from 'src/commands/errors';
2
import process from 'node:process';
3
-import { Argument, Command, Flag } from 'effect/cli';
3
import * as FileSystem from 'effect/FileSystem';
4
import * as Path from 'effect/Path';
5
import { ChildProcess, ChildProcessSpawner } from 'effect/process';
7
-import { Data, Duration, Effect, Option, Ref, Result } from 'effect';
6
+import { Duration, Effect, Option, Ref, Result } from 'effect';
7
import { APP_VERSION } from 'src/constants';
8
import { ChildProcessExited, ChildProcessSignaled } from 'src/effects/child-process-exited';
9
import { childExitStatus, type ChildExitStatus } from 'src/effects/child-exit-status';
21
import { ComposioUserContext } from 'src/services/user-context';
22
import { resolveConsumerExecutionTransport } from 'src/services/dashboard-tool-execution';
23
import {
25
- CLI_DEBUG_FLAG_NAMES,
24
debugFlagsToChildEnv,
25
isPerfDebugEnabled,
26
isTelemetryDebugEnabled,
38
} from 'src/services/cli-session-artifacts';
39
import { TerminalUI } from 'src/services/terminal-ui';
40
import { NodeOs } from 'src/services/node-os';
43
-
44
-const RUN_FLAG_NAMES = {
45
- file: 'file',
46
- dryRun: 'dry-run',
47
- debug: 'debug',
48
- skipConnectionCheck: 'skip-connection-check',
49
- skipToolParamsCheck: 'skip-tool-params-check',
50
- skipChecks: 'skip-checks',
51
-} as const;
52
-
53
-const file = Flag.String(RUN_FLAG_NAMES.file).pipe(
54
- Flag.withAlias('f'),
55
- Flag.withDescription('Run a TS/JS file instead of inline code'),
56
- Flag.optional
57
-);
58
-
59
-const dryRun = Flag.Boolean(RUN_FLAG_NAMES.dryRun).pipe(
60
- Flag.withDescription('Preview execute() calls without running them'),
61
- Flag.withDefault(false)
62
-);
63
-const debug = Flag.Boolean(RUN_FLAG_NAMES.debug).pipe(
64
- Flag.withDescription('Log helper steps while the script runs'),
65
- Flag.withDefault(false)
66
-);
67
-const skipConnectionCheck = Flag.Boolean(RUN_FLAG_NAMES.skipConnectionCheck).pipe(
68
- Flag.withDescription('Skip the connected-account check'),
69
- Flag.withDefault(false)
70
-);
71
-const skipToolParamsCheck = Flag.Boolean(RUN_FLAG_NAMES.skipToolParamsCheck).pipe(
72
- Flag.withDescription('Skip input validation against cached schema'),
73
- Flag.withDefault(false)
74
-);
75
-const skipChecks = Flag.Boolean(RUN_FLAG_NAMES.skipChecks).pipe(
76
- Flag.withDescription('Skip both connection and input validation checks'),
77
- Flag.withDefault(false)
78
-);
79
-
80
-const runFlags = {
81
- file,
82
- dryRun,
83
- debug,
84
- skipConnectionCheck,
85
- skipToolParamsCheck,
86
- skipChecks,
87
-};
88
-
89
-/** Share names with the passthrough adapter; the framework owns parsing the flag values. */
90
-export const RUN_FILE_FLAGS = new Set([`--${RUN_FLAG_NAMES.file}`, '-f']);
91
-export const RUN_KNOWN_VALUE_FLAGS = new Set([...RUN_FILE_FLAGS, '--log-level']);
92
-export const RUN_KNOWN_BOOLEAN_FLAGS = new Set([
93
- ...Object.values(RUN_FLAG_NAMES)
94
- .filter(name => name !== RUN_FLAG_NAMES.file)
95
- .map(name => `--${name}`),
96
- ...CLI_DEBUG_FLAG_NAMES.flatMap(name => [`--${name}`, `--no-${name}`]),
97
- '--help',
98
- '-h',
99
- '--version',
100
- '-v',
101
-]);
102
-
103
-const args = Argument.String('arg').pipe(
104
- Argument.variadic(),
105
- Argument.withDescription('Inline code followed by arguments, or just arguments when using --file')
106
-);
41
+import { ChildSignalError } from './run.errors';
42
43
const withArgDelimiter = (args: ReadonlyArray<string>) => (args.length > 0 ? ['--', ...args] : []);
44
90
const modulePath = yield* resolveRunCompanionModulePath({
91
callerImportMetaUrl: import.meta.url,
92
execPath: process.execPath,
158
- relativeNoExtensionFromCaller: '../services/run-helpers-runtime',
93
+ relativeNoExtensionFromCaller: '../../services/run-helpers-runtime',
94
});
95
const moduleUrl = yield* Effect.orDie(path.toFileUrl(modulePath));
96
return { helpersRuntimeModuleUrl: moduleUrl.href };
264
readonly sent: ReadonlyArray<TerminationSignal>;
265
}
266
332
-class ChildSignalError extends Data.TaggedError('ChildSignalError')<{
333
- readonly pid: number;
334
- readonly signal: TerminationSignal;
335
- readonly cause: unknown;
336
-}> {}
337
-
267
/**
268
* Sends `signal` to the child's process group.
269
*
355
});
356
});
357
429
-export const runCmd = Command.make('run', {
430
- ...runFlags,
358
+/** The flags and arguments of `composio run`. */
359
+export type RunParams = {
360
+ readonly file: Option.Option<string>;
361
+ readonly dryRun: boolean;
362
+ readonly debug: boolean;
363
+ readonly skipConnectionCheck: boolean;
364
+ readonly skipToolParamsCheck: boolean;
365
+ readonly skipChecks: boolean;
366
+ readonly args: ReadonlyArray<string>;
367
+};
368
+
369
+/**
370
+ * Runs inline code or a script file in a child Bun process with the Composio helpers preloaded,
371
+ * and ends the way the script did.
372
+ */
373
+export const runScript = ({
374
+ file,
375
+ dryRun,
376
+ debug,
377
+ skipConnectionCheck,
378
+ skipToolParamsCheck,
379
+ skipChecks,
380
args,
432
-}).pipe(
433
- Command.withDescription(
434
- 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.\n\nInjected helpers (behave like their CLI counterparts):\n execute(slug, data?) Same as `composio execute` — returns parsed JSON\n search(query, options?) Same as `composio search` — returns matching tools\n result.prompt() Prompt-safe serialization of a helper result\n const f = await proxy(toolkit) Same as `composio proxy` — returns a fetch function\n Example: const f = await proxy("gmail")\n const me = await f("https://gmail.googleapis.com/gmail/v1/users/me/profile")\n z Injected global from `zod` for defining and validating schemas\n\nAll helpers reuse your CLI auth state and connected accounts.\n\nUse composio search "<query>" to discover tools and composio execute <slug> --get-schema to inspect inputs.'
435
- ),
436
- Command.withShortDescription(
437
- 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.'
438
- ),
439
- Command.withExamples([
440
- {
441
- command:
442
- 'composio run \'\n // execute(slug, data?) — run a tool, returns parsed JSON\n const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");\n console.log(me);\n\'',
443
- },
444
- {
445
- command:
446
- 'composio run \'\n // search(query, opts?) — find tools by use case\n const tools = await search("send email");\n console.log(tools);\n\'',
447
- },
448
- {
449
- command:
450
- 'composio run \'\n const issue = await execute("GITHUB_CREATE_ISSUE", { owner: "acme", repo: "app", title: "Deploy v2" });\n await execute("SLACK_SEND_MESSAGE", { channel: "eng", markdown_text: "Created: " + issue.data.html_url });\n\'',
451
- description: 'Sequential: chain tool outputs across services',
452
- },
453
- {
454
- command:
455
- 'composio run \'\n const [emails, issues, events] = await Promise.all([\n execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),\n execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "composiohq", repo: "composio", state: "open" }),\n execute("GOOGLECALENDAR_FIND_EVENT", { calendar_id: "primary" }),\n ]);\n console.log({ emails: emails.data, issues: issues.data, events: events.data });\n\'',
456
- description: 'Parallel: fetch from multiple services at once with Promise.all',
457
- },
458
- {
459
- command:
460
- 'composio run \'\n const issues = [101, 102, 103, 104];\n await Promise.all(issues.map(n =>\n execute("GITHUB_ADD_LABELS_TO_ISSUE", { owner: "acme", repo: "app", issue_number: n, labels: ["priority"] })\n ));\n\'',
461
- description: 'Bulk: fan out with Promise.all + .map()',
462
- },
463
- {
464
- command:
465
- 'composio run \'\n const f = await proxy("gmail");\n console.log(await f("https://gmail.googleapis.com/gmail/v1/users/me/profile"));\n\'',
466
- description: 'proxy(toolkit) — returns a fetch() bound to your connected account',
467
- },
468
- {
469
- command: 'composio run --file ./workflow.ts -- --repo acme/app',
470
- description: 'Run from a file',
471
- },
472
- ]),
473
- Command.withHandler(
474
- ({ file, dryRun, debug, skipConnectionCheck, skipToolParamsCheck, skipChecks, args }) =>
475
- Effect.gen(function* () {
476
- // Checked before any setup work so a bare `composio run` neither creates a run-artifacts
477
- // directory nor advertises a log file for a script that will never start.
478
- if (Option.isNone(file) && !args[0]) {
479
- return yield* Effect.fail(missingRunSource());
480
- }
381
+}: RunParams) =>
382
+ Effect.gen(function* () {
383
+ // Checked before any setup work so a bare `composio run` neither creates a run-artifacts
384
+ // directory nor advertises a log file for a script that will never start.
385
+ if (Option.isNone(file) && !args[0]) {
386
+ return yield* Effect.fail(missingRunSource());
387
+ }
388
482
- const fs = yield* FileSystem.FileSystem;
483
- const path = yield* Path.Path;
484
- const invocation = yield* cliInvocationContext;
485
- const runId = Option.getOrElse(
486
- yield* invocationRunId,
487
- () => invocation.parentRunId ?? crypto.randomUUID()
389
+ const fs = yield* FileSystem.FileSystem;
390
+ const path = yield* Path.Path;
391
+ const invocation = yield* cliInvocationContext;
392
+ const runId = Option.getOrElse(
393
+ yield* invocationRunId,
394
+ () => invocation.parentRunId ?? crypto.randomUUID()
395
+ );
396
+ const perfDebug = yield* isPerfDebugEnabled;
397
+ const toolDebug = yield* isToolDebugEnabled;
398
+ const telemetryDebug = yield* isTelemetryDebugEnabled;
399
+ if (Option.isNone(file)) {
400
+ const [inlineCode] = args;
401
+ const { extractInlineExecuteToolSlugs } = yield* loadSourceTransforms;
402
+ const preloadSlugs = extractInlineExecuteToolSlugs(inlineCode ?? '');
403
+ if (preloadSlugs.length > 0) {
404
+ yield* warmToolInputDefinitions(preloadSlugs).pipe(
405
+ Effect.catch(() => Effect.void),
406
+ Effect.forkDetach
407
);
489
- const perfDebug = yield* isPerfDebugEnabled;
490
- const toolDebug = yield* isToolDebugEnabled;
491
- const telemetryDebug = yield* isTelemetryDebugEnabled;
492
- if (Option.isNone(file)) {
493
- const [inlineCode] = args;
494
- const { extractInlineExecuteToolSlugs } = yield* loadSourceTransforms;
495
- const preloadSlugs = extractInlineExecuteToolSlugs(inlineCode ?? '');
496
- if (preloadSlugs.length > 0) {
497
- yield* warmToolInputDefinitions(preloadSlugs).pipe(
498
- Effect.catch(() => Effect.void),
499
- Effect.forkDetach
500
- );
501
- }
502
- }
408
+ }
409
+ }
410
504
- const helperContext: RunHelperContext = {
505
- ...(yield* resolveRunHelperContext()),
506
- runId,
507
- perfDebug,
508
- toolDebug,
509
- telemetryDebug,
510
- debug,
511
- dryRun,
512
- skipConnectionCheck,
513
- skipToolParamsCheck,
514
- skipChecks,
515
- };
516
- const runHelperModuleUrls = yield* repairMissingInstalledRunCompanionModules({
517
- callerImportMetaUrl: import.meta.url,
518
- execPath: process.execPath,
519
- appVersion: APP_VERSION,
520
- }).pipe(
521
- Effect.mapError(error => new Error(error.message)),
522
- Effect.andThen(resolveRunHelperModuleUrls)
523
- );
524
- const cliPrefix = yield* inferCliInvocationPrefix(path);
525
- const preload = yield* createRunHelpersPreloadFile(
526
- path,
527
- cliPrefix,
528
- helperContext,
529
- runHelperModuleUrls
530
- );
531
- const ui = yield* TerminalUI;
532
- yield* appendCliSessionHistory({
533
- orgId: helperContext.orgId,
534
- consumerUserId: helperContext.consumerUserId,
535
- entry: {
536
- command: 'run',
537
- status: 'start',
538
- file: Option.getOrUndefined(file),
539
- args,
540
- debug,
541
- },
542
- }).pipe(Effect.catch(() => Effect.void));
543
- yield* ui.error(`RUN_LOG_FILE=${preload.runLogFilePath}`);
544
- const runCommand = yield* buildRunCommand({
545
- path,
546
- file,
547
- args,
548
- preloadPath: preload.preloadPath,
549
- preloadDirectory: preload.directory,
550
- });
551
- const status = yield* Effect.gen(function* () {
552
- const [executable, ...commandArgs] = runCommand.cmd;
553
- // Spawning the command (instead of running it to completion) yields the handle whose
554
- // pid the signal forwarding below needs. `extendEnv` keeps the caller's environment.
555
- const child = yield* ChildProcess.make(executable!, commandArgs, {
556
- env: {
557
- BUN_BE_BUN: '1',
558
- COMPOSIO_CLI_PARENT_RUN_ID: runId,
559
- ...debugFlagsToChildEnv({ perfDebug, toolDebug, telemetryDebug }),
560
- },
561
- extendEnv: true,
562
- stdin: 'inherit',
563
- stdout: 'inherit',
564
- stderr: 'inherit',
565
- });
566
- return yield* superviseChild(child);
567
- }).pipe(
568
- Effect.scoped,
569
- Effect.ensuring(
570
- Effect.forEach(
571
- runCommand.cleanupPaths,
572
- cleanupPath => fs.remove(cleanupPath, { force: true }),
573
- { discard: true }
574
- ).pipe(
575
- // The wrapper file sits next to the user's script, so removal can fail on a
576
- // read-only or locked directory. That must not turn an already-successful run
577
- // into a failure, which is what the previous `Effect.orDie` did.
578
- Effect.ignore
579
- )
580
- )
581
- );
582
- // The process ends the way the script did: with its code, or, when a signal ended it,
583
- // by the same signal (the runner re-raises it), so wrappers and `set -e` scripts read a
584
- // cancelled run as cancelled.
585
- if (status.signal !== null) {
586
- return yield* new ChildProcessSignaled({ signal: status.signal });
587
- }
588
- if (status.code !== 0) {
589
- return yield* new ChildProcessExited({ code: status.code });
590
- }
591
- }).pipe(Effect.scoped)
592
- )
593
-);
411
+ const helperContext: RunHelperContext = {
412
+ ...(yield* resolveRunHelperContext()),
413
+ runId,
414
+ perfDebug,
415
+ toolDebug,
416
+ telemetryDebug,
417
+ debug,
418
+ dryRun,
419
+ skipConnectionCheck,
420
+ skipToolParamsCheck,
421
+ skipChecks,
422
+ };
423
+ const runHelperModuleUrls = yield* repairMissingInstalledRunCompanionModules({
424
+ callerImportMetaUrl: import.meta.url,
425
+ execPath: process.execPath,
426
+ appVersion: APP_VERSION,
427
+ }).pipe(
428
+ Effect.mapError(error => new Error(error.message)),
429
+ Effect.andThen(resolveRunHelperModuleUrls)
430
+ );
431
+ const cliPrefix = yield* inferCliInvocationPrefix(path);
432
+ const preload = yield* createRunHelpersPreloadFile(
433
+ path,
434
+ cliPrefix,
435
+ helperContext,
436
+ runHelperModuleUrls
437
+ );
438
+ const ui = yield* TerminalUI;
439
+ yield* appendCliSessionHistory({
440
+ orgId: helperContext.orgId,
441
+ consumerUserId: helperContext.consumerUserId,
442
+ entry: {
443
+ command: 'run',
444
+ status: 'start',
445
+ file: Option.getOrUndefined(file),
446
+ args,
447
+ debug,
448
+ },
449
+ }).pipe(Effect.catch(() => Effect.void));
450
+ yield* ui.error(`RUN_LOG_FILE=${preload.runLogFilePath}`);
451
+ const runCommand = yield* buildRunCommand({
452
+ path,
453
+ file,
454
+ args,
455
+ preloadPath: preload.preloadPath,
456
+ preloadDirectory: preload.directory,
457
+ });
458
+ const status = yield* Effect.gen(function* () {
459
+ const [executable, ...commandArgs] = runCommand.cmd;
460
+ // Spawning the command (instead of running it to completion) yields the handle whose
461
+ // pid the signal forwarding below needs. `extendEnv` keeps the caller's environment.
462
+ const child = yield* ChildProcess.make(executable!, commandArgs, {
463
+ env: {
464
+ BUN_BE_BUN: '1',
465
+ COMPOSIO_CLI_PARENT_RUN_ID: runId,
466
+ ...debugFlagsToChildEnv({ perfDebug, toolDebug, telemetryDebug }),
467
+ },
468
+ extendEnv: true,
469
+ stdin: 'inherit',
470
+ stdout: 'inherit',
471
+ stderr: 'inherit',
472
+ });
473
+ return yield* superviseChild(child);
474
+ }).pipe(
475
+ Effect.scoped,
476
+ Effect.ensuring(
477
+ Effect.forEach(
478
+ runCommand.cleanupPaths,
479
+ cleanupPath => fs.remove(cleanupPath, { force: true }),
480
+ { discard: true }
481
+ ).pipe(
482
+ // The wrapper file sits next to the user's script, so removal can fail on a
483
+ // read-only or locked directory. That must not turn an already-successful run
484
+ // into a failure, which is what the previous `Effect.orDie` did.
485
+ Effect.ignore
486
+ )
487
+ )
488
+ );
489
+ // The process ends the way the script did: with its code, or, when a signal ended it,
490
+ // by the same signal (the runner re-raises it), so wrappers and `set -e` scripts read a
491
+ // cancelled run as cancelled.
492
+ if (status.signal !== null) {
493
+ return yield* new ChildProcessSignaled({ signal: status.signal });
494
+ }
495
+ if (status.code !== 0) {
496
+ return yield* new ChildProcessExited({ code: status.code });
497
+ }
498
+ }).pipe(Effect.scoped);