@devries-cameron20 / composio-1 / commits / 699b9f55b
Fork 0

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

refactor(cli): move `run` into the directory shape (#5139)

This PR: - targets `next`, now that https://github.com/ComposioHQ/composio/pull/5136 has landed there - moves `composio run` into the directory shape as a pure move; no behaviour, output, flag, error or telemetry change - keeps the `argv-compat.ts` handling of undelimited script arguments and the child-signal forwarding and exit mirroring exactly as they are - updates the helper-runtime path the handler resolves from its new directory (`../../services/run-helpers-runtime`), and adds a test pinning the `installRunHelpers` import the preload emits, which fails with the old relative path - regenerates `COMMANDS.md` | Old | New | | --- | --- | | `src/commands/run.cmd.ts` (flags, argument, description, examples) | `src/commands/run/run.cmd.ts` | | `src/commands/run.cmd.ts` (handler, preload, child supervision) | `src/commands/run/run.handler.ts` (`runScript`, `RunParams`) | | `src/commands/run.cmd.ts` (`ChildSignalError`) | `src/commands/run/run.errors.ts` | | `test/src/commands/run.cmd.test.ts` | `test/src/commands/run/run.cmd.test.ts` | ## Context - `run` does not import from `tools/commands/tools.execute.cmd.ts`, so the parallel `tools execute` move does not touch this PR. - `src/commands/run-source-transforms.ts` stays where it is: `src/services/generation-runtime.ts` bundles it into the `generation-runtime` companion, and `scripts/_shared.ts` and `startup-imports.test.ts` match its path. Only its doc comment now names the handler. - The acting-user changes from #5127 and #5130 to `run.cmd.ts` are now included: the consumer helper context in `run.handler.ts` resolves through `actingUser()`. Verified: root `pnpm typecheck`, `pnpm --filter @composio/cli run lint:effect`, `pnpm --filter @composio/cli test` (validate:boundaries and validate:command-tests included), and oxlint all pass. Tests: 2893 passed / 1 skipped on the base, 2894 passed / 1 skipped here (the `run` suite goes from 49 to 50). --------- Co-authored-by: Vinayak Agarwal <vinayak@composio.dev> Co-authored-by: manobhisriram <manobhisriram@gmail.com>

Alberto Schiabel committed Oct 28, 2026 at 20:07 UTC 699b9f55b977c2e66d9d561e2d106ff98f5151d0
8 files changed +292 -243
ts/packages/cli/src/commands/COMMANDS.md
+1 -1
@@ -76,7 +76,7 @@ Every command registration of the CLI and the file that defines it. To find a co
76 | `orgs list` | root | `ts/packages/cli/src/commands/orgs/list/orgs.list.cmd.ts` | | | yes | listed |
77 | `orgs switch` | root | `ts/packages/cli/src/commands/orgs/switch/orgs.switch.cmd.ts` | | | yes | listed |
78 | `proxy` | root | `ts/packages/cli/src/commands/proxy/proxy.cmd.ts` | | | yes | listed |
79 -| `run` | root | `ts/packages/cli/src/commands/run.cmd.ts` | | | no | listed |
79 +| `run` | root | `ts/packages/cli/src/commands/run/run.cmd.ts` | | | no | listed |
80 | `search` | root | `ts/packages/cli/src/commands/tools/search/tools.search.cmd.ts` | | | yes | listed |
81 | `setup` | root | `ts/packages/cli/src/commands/setup.cmd.ts` | | | no | listed |
82 | `setup skill` | root | `ts/packages/cli/src/commands/setup-skill.cmd.ts` | | | no | listed |
ts/packages/cli/src/commands/argv-compat.ts
+1 -1
@@ -1,5 +1,5 @@
1 import { Array as Arr } from 'effect';
2 -import { RUN_FILE_FLAGS, RUN_KNOWN_BOOLEAN_FLAGS, RUN_KNOWN_VALUE_FLAGS } from './run.cmd';
2 +import { RUN_FILE_FLAGS, RUN_KNOWN_BOOLEAN_FLAGS, RUN_KNOWN_VALUE_FLAGS } from './run/run.cmd';
3 import { rootCommandIndex } from 'src/utils/cli-args';
4
5 export const normalizeListenStreamFlag = (argv: ReadonlyArray<string>): ReadonlyArray<string> => {
ts/packages/cli/src/commands/index.ts
+1 -1
@@ -16,7 +16,7 @@ import { signupCmd } from './signup/signup.cmd';
16 import { setupCmd } from './setup.cmd';
17 import { listenCmd } from './listen.cmd';
18 import { logoutCmd } from './logout.cmd';
19 -import { runCmd } from './run.cmd';
19 +import { runCmd } from './run/run.cmd';
20 import { proxyCmd } from './proxy/proxy.cmd';
21 import { artifactsCmd } from './artifacts/artifacts.cmd';
22 import { installCmd } from './install/install.cmd';
ts/packages/cli/src/commands/run-source-transforms.ts
+4 -4
@@ -3,10 +3,10 @@
3 * to Bun: slug extraction for definition warming, and the two wrappers that turn
4 * a trailing expression into a return value.
5 *
6 - * These live outside `run.cmd.ts` because they are the CLI's only consumer of
7 - * the TypeScript compiler, which costs roughly 95ms to evaluate. `run.cmd.ts`
8 - * imports this module dynamically from inside its handler, so a `composio
9 - * execute` or `composio whoami` invocation never pays for it.
6 + * These live outside `run/run.handler.ts` because they are the CLI's only
7 + * consumer of the TypeScript compiler, which costs roughly 95ms to evaluate. The
8 + * handler imports this module dynamically, so a `composio execute` or `composio
9 + * whoami` invocation never pays for it.
10 */
11 import ts from 'typescript';
12
ts/packages/cli/src/commands/run/run.cmd.ts new
+117
@@ -0,0 +1,117 @@
1 +import { Argument, Command, Flag } from 'effect/cli';
2 +import { CLI_DEBUG_FLAG_NAMES } from 'src/services/runtime-flags';
3 +import { runScript } from './run.handler';
4 +
5 +const RUN_FLAG_NAMES = {
6 + file: 'file',
7 + dryRun: 'dry-run',
8 + debug: 'debug',
9 + skipConnectionCheck: 'skip-connection-check',
10 + skipToolParamsCheck: 'skip-tool-params-check',
11 + skipChecks: 'skip-checks',
12 +} as const;
13 +
14 +const file = Flag.String(RUN_FLAG_NAMES.file).pipe(
15 + Flag.withAlias('f'),
16 + Flag.withDescription('Run a TS/JS file instead of inline code'),
17 + Flag.optional
18 +);
19 +
20 +const dryRun = Flag.Boolean(RUN_FLAG_NAMES.dryRun).pipe(
21 + Flag.withDescription('Preview execute() calls without running them'),
22 + Flag.withDefault(false)
23 +);
24 +const debug = Flag.Boolean(RUN_FLAG_NAMES.debug).pipe(
25 + Flag.withDescription('Log helper steps while the script runs'),
26 + Flag.withDefault(false)
27 +);
28 +const skipConnectionCheck = Flag.Boolean(RUN_FLAG_NAMES.skipConnectionCheck).pipe(
29 + Flag.withDescription('Skip the connected-account check'),
30 + Flag.withDefault(false)
31 +);
32 +const skipToolParamsCheck = Flag.Boolean(RUN_FLAG_NAMES.skipToolParamsCheck).pipe(
33 + Flag.withDescription('Skip input validation against cached schema'),
34 + Flag.withDefault(false)
35 +);
36 +const skipChecks = Flag.Boolean(RUN_FLAG_NAMES.skipChecks).pipe(
37 + Flag.withDescription('Skip both connection and input validation checks'),
38 + Flag.withDefault(false)
39 +);
40 +
41 +const runFlags = {
42 + file,
43 + dryRun,
44 + debug,
45 + skipConnectionCheck,
46 + skipToolParamsCheck,
47 + skipChecks,
48 +};
49 +
50 +/** Share names with the passthrough adapter; the framework owns parsing the flag values. */
51 +export const RUN_FILE_FLAGS = new Set([`--${RUN_FLAG_NAMES.file}`, '-f']);
52 +export const RUN_KNOWN_VALUE_FLAGS = new Set([...RUN_FILE_FLAGS, '--log-level']);
53 +export const RUN_KNOWN_BOOLEAN_FLAGS = new Set([
54 + ...Object.values(RUN_FLAG_NAMES)
55 + .filter(name => name !== RUN_FLAG_NAMES.file)
56 + .map(name => `--${name}`),
57 + ...CLI_DEBUG_FLAG_NAMES.flatMap(name => [`--${name}`, `--no-${name}`]),
58 + '--help',
59 + '-h',
60 + '--version',
61 + '-v',
62 +]);
63 +
64 +const args = Argument.String('arg').pipe(
65 + Argument.variadic(),
66 + Argument.withDescription('Inline code followed by arguments, or just arguments when using --file')
67 +);
68 +
69 +export const runCmd = Command.make(
70 + 'run',
71 + {
72 + ...runFlags,
73 + args,
74 + },
75 + runScript
76 +).pipe(
77 + Command.withDescription(
78 + '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.'
79 + ),
80 + Command.withShortDescription(
81 + 'Run inline TS/JS code or a file with injected Composio helpers that behave like their CLI counterparts.'
82 + ),
83 + Command.withExamples([
84 + {
85 + command:
86 + '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\'',
87 + },
88 + {
89 + command:
90 + 'composio run \'\n // search(query, opts?) — find tools by use case\n const tools = await search("send email");\n console.log(tools);\n\'',
91 + },
92 + {
93 + command:
94 + '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\'',
95 + description: 'Sequential: chain tool outputs across services',
96 + },
97 + {
98 + command:
99 + '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\'',
100 + description: 'Parallel: fetch from multiple services at once with Promise.all',
101 + },
102 + {
103 + command:
104 + '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\'',
105 + description: 'Bulk: fan out with Promise.all + .map()',
106 + },
107 + {
108 + command:
109 + 'composio run \'\n const f = await proxy("gmail");\n console.log(await f("https://gmail.googleapis.com/gmail/v1/users/me/profile"));\n\'',
110 + description: 'proxy(toolkit) — returns a fetch() bound to your connected account',
111 + },
112 + {
113 + command: 'composio run --file ./workflow.ts -- --repo acme/app',
114 + description: 'Run from a file',
115 + },
116 + ])
117 +);
ts/packages/cli/src/commands/run/run.errors.ts new
+8
@@ -0,0 +1,8 @@
1 +import { Data } from 'effect';
2 +import type { TerminationSignal } from 'src/services/shutdown-signal';
3 +
4 +export class ChildSignalError extends Data.TaggedError('ChildSignalError')<{
5 + readonly pid: number;
6 + readonly signal: TerminationSignal;
7 + readonly cause: unknown;
8 +}> {}
ts/packages/cli/src/commands/run/run.handler.ts renamed
+140 -235
@@ -1,10 +1,9 @@
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';
@@ -22,7 +21,6 @@ import { warmToolInputDefinitions } from 'src/services/tool-input-validation';
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,
@@ -40,70 +38,7 @@ import {
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
@@ -155,7 +90,7 @@ const resolveRunHelperModuleUrls: Effect.Effect<
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 };
@@ -329,12 +264,6 @@ interface Escalation {
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 *
@@ -426,168 +355,144 @@ const superviseChild = (child: ChildProcessSpawner.ChildProcessHandle) =>
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);
ts/packages/cli/test/src/commands/run/run.cmd.test.ts renamed
+20 -1
@@ -24,7 +24,7 @@ import {
24 import { TestClock } from 'effect/testing';
25 import { ChildProcess, ChildProcessSpawner } from 'effect/process';
26 import { afterEach, beforeEach, it, vi } from 'vitest';
27 -import { buildRunHelpersSource, inferCliInvocationPrefix } from 'src/commands/run.cmd';
27 +import { buildRunHelpersSource, inferCliInvocationPrefix } from 'src/commands/run/run.handler';
28 import {
29 extractInlineExecuteToolSlugs,
30 wrapInlineCodeForRun,
@@ -449,6 +449,25 @@ describe('CLI: composio run', () => {
449 expect(preloadSource).not.toContain('"cliConfigPath":');
450 })
451 );
452 +
453 + it.effect('[Given] a run from source [Then] the preload imports the helper runtime', () =>
454 + Effect.gen(function* () {
455 + let preloadSource = '';
456 + commandRuns.mockImplementation(command => {
457 + preloadSource = readRunPreloadSource(inspectRunCommand(command).cmd);
458 + return Effect.succeed(ChildProcessSpawner.ExitCode(0));
459 + });
460 +
461 + yield* cli(['run', 'console.log("hi")']);
462 +
463 + const helpersRuntimeUrl = pathToFileURL(
464 + path.resolve(import.meta.dirname, '../../../../src/services/run-helpers-runtime.ts')
465 + ).href;
466 + expect(preloadSource).toContain(
467 + `import { installRunHelpers } from ${JSON.stringify(helpersRuntimeUrl)};`
468 + );
469 + })
470 + );
471 });
472
473 layer(RunTestLive({ baseConfigProvider: enabledRuntimeFlagsConfigProvider }))(it => {