1
-// eslint-disable-next-line no-restricted-imports -- synchronous fs (mkdtempSync/writeFileSync/rmSync/existsSync) builds and tears down the run preload files in plain helpers that execute outside the Effect runtime
2
-import * as fs from 'node:fs';
3
-// eslint-disable-next-line no-restricted-imports -- os.tmpdir and os.homedir locate the preload scratch directory and ~/.composio in the same synchronous helpers
4
-import * as os from 'node:os';
1
import process from 'node:process';
6
-import { pathToFileURL } from 'node:url';
2
import { Args, Command, Options } from '@effect/cli';
8
-import { FileSystem, Path } from '@effect/platform';
9
-import { Effect, Option } from 'effect';
3
+import { Command as PlatformCommand, CommandExecutor, FileSystem, Path } from '@effect/platform';
4
+import { Data, Deferred, Duration, Effect, Either, MutableRef, Option } from 'effect';
5
import { ts } from 'ts-morph';
6
import { APP_VERSION } from 'src/constants';
7
+import { APP_CONFIG, UNPREFIXED_CONFIG } from 'src/effects/app-config';
8
import { resolveCommandProject } from 'src/services/command-project';
9
import { type RunHelperContext } from 'src/services/run-helpers-runtime';
10
import { warmToolInputDefinitions } from 'src/services/tool-input-validation';
11
import { ComposioUserContext } from 'src/services/user-context';
16
-import { isPerfDebugEnabled, isToolDebugEnabled } from 'src/services/runtime-debug-flags';
17
-import { detectMaster } from 'src/services/master-detector';
12
+import {
13
+ debugFlagsToChildEnv,
14
+ isAcpOnlyEnabled,
15
+ isPerfDebugEnabled,
16
+ isTelemetryDebugEnabled,
17
+ isToolDebugEnabled,
18
+} from 'src/services/runtime-flags';
19
+import { detectMasterFromHost } from 'src/services/master-detector';
20
+import { cliInvocationContext, CliRunId } from 'src/services/runtime-cli-context';
21
import {
22
repairMissingInstalledRunCompanionModules,
23
resolveRunCompanionModulePath,
28
} from 'src/services/cli-session-artifacts';
29
import { USER_COMPOSIO_DIR } from 'src/constants';
30
import { TerminalUI } from 'src/services/terminal-ui';
31
+import { loadHostConfig } from 'src/services/config';
32
+import { resolveCliConfigPath } from 'src/services/cli-user-config';
33
+import { NodeOs } from 'src/services/node-os';
34
35
const file = Options.text('file').pipe(
36
Options.withAlias('f'),
158
export const inferCliInvocationPrefix = (
159
path: Path.Path,
160
argv: ReadonlyArray<string> = process.argv
155
-): ReadonlyArray<string> => {
156
- const entrypoint = argv[1];
157
- if (!entrypoint) {
158
- return [process.execPath];
159
- }
161
+) =>
162
+ Effect.gen(function* () {
163
+ const entrypoint = argv[1];
164
+ if (!entrypoint) {
165
+ return [process.execPath];
166
+ }
167
161
- // Compiled Bun binaries report an internal $bunfs entrypoint which cannot be
162
- // re-executed as a real filesystem path. In that case the binary itself is
163
- // the CLI entrypoint.
164
- if (entrypoint.startsWith('/$bunfs/')) {
165
- return [process.execPath];
166
- }
168
+ // Compiled Bun binaries report an internal $bunfs entrypoint which cannot be
169
+ // re-executed as a real filesystem path. In that case the binary itself is
170
+ // the CLI entrypoint.
171
+ if (entrypoint.startsWith('/$bunfs/')) {
172
+ return [process.execPath];
173
+ }
174
168
- const resolvedEntrypoint = path.resolve(entrypoint);
169
- return fs.existsSync(resolvedEntrypoint)
170
- ? [process.execPath, resolvedEntrypoint]
171
- : [process.execPath];
172
-};
175
+ const fs = yield* FileSystem.FileSystem;
176
+ const resolvedEntrypoint = path.resolve(entrypoint);
177
+ return (yield* fs.exists(resolvedEntrypoint))
178
+ ? [process.execPath, resolvedEntrypoint]
179
+ : [process.execPath];
180
+ });
181
182
type RunHelperModuleUrls = {
183
readonly helpersRuntimeModuleUrl: string;
187
RunHelperModuleUrls,
188
never,
189
FileSystem.FileSystem | Path.Path
182
-> = Effect.map(
183
- resolveRunCompanionModulePath({
190
+> = Effect.gen(function* () {
191
+ const path = yield* Path.Path;
192
+ const modulePath = yield* resolveRunCompanionModulePath({
193
callerImportMetaUrl: import.meta.url,
194
execPath: process.execPath,
195
relativeNoExtensionFromCaller: '../services/run-helpers-runtime',
187
- }),
188
- modulePath => ({ helpersRuntimeModuleUrl: pathToFileURL(modulePath).href })
189
-);
196
+ });
197
+ const moduleUrl = yield* Effect.orDie(path.toFileUrl(modulePath));
198
+ return { helpersRuntimeModuleUrl: moduleUrl.href };
199
+});
200
export const buildRunHelpersSource = (
201
cliPrefix: ReadonlyArray<string>,
202
context: RunHelperContext = {},
213
cliPrefix: ReadonlyArray<string>,
214
context: RunHelperContext,
215
moduleUrls: RunHelperModuleUrls
206
-) => {
207
- const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-'));
208
- const preloadPath = path.join(directory, 'globals.mjs');
209
- const runOutputDir =
210
- typeof context.runOutputDir === 'string' && context.runOutputDir.length > 0
211
- ? context.runOutputDir
212
- : path.join(directory, 'artifacts');
213
- const runLogFilePath = path.join(runOutputDir, 'run.log');
214
- const readAccessRoots = [
215
- ...new Set(
216
- [
217
- ...(Array.isArray(context.readAccessRoots) ? context.readAccessRoots : []),
218
- runOutputDir,
219
- ].map(value => path.resolve(value))
220
- ),
221
- ];
222
- fs.mkdirSync(runOutputDir, { recursive: true });
223
- fs.writeFileSync(runLogFilePath, '', 'utf8');
224
- fs.writeFileSync(
225
- preloadPath,
226
- buildRunHelpersSource(
227
- cliPrefix,
228
- {
229
- ...context,
230
- runOutputDir,
231
- runLogFilePath,
232
- readAccessRoots,
233
- },
234
- moduleUrls
235
- ),
236
- 'utf8'
237
- );
238
- return { directory, preloadPath, runOutputDir, runLogFilePath };
239
-};
216
+) =>
217
+ Effect.gen(function* () {
218
+ const fs = yield* FileSystem.FileSystem;
219
+ const os = yield* NodeOs;
220
+ const directory = yield* fs.makeTempDirectoryScoped({
221
+ directory: os.tmpdir,
222
+ prefix: 'composio-run-',
223
+ });
224
+ const preloadPath = path.join(directory, 'globals.mjs');
225
+ // The preload directory is scoped and removed when the run ends, but the run log and any
226
+ // large tool outputs are advertised to the caller on stderr (`RUN_LOG_FILE=`) and must
227
+ // outlive the process that printed them, so they get their own unscoped directory.
228
+ const runOutputDir =
229
+ typeof context.runOutputDir === 'string' && context.runOutputDir.length > 0
230
+ ? context.runOutputDir
231
+ : yield* fs.makeTempDirectory({ directory: os.tmpdir, prefix: 'composio-run-artifacts-' });
232
+ const runLogFilePath = path.join(runOutputDir, 'run.log');
233
+ const readAccessRoots = [
234
+ ...new Set(
235
+ [
236
+ ...(Array.isArray(context.readAccessRoots) ? context.readAccessRoots : []),
237
+ runOutputDir,
238
+ ].map(value => path.resolve(value))
239
+ ),
240
+ ];
241
+ yield* fs.makeDirectory(runOutputDir, { recursive: true });
242
+ yield* fs.writeFileString(runLogFilePath, '');
243
+ yield* fs.writeFileString(
244
+ preloadPath,
245
+ buildRunHelpersSource(
246
+ cliPrefix,
247
+ {
248
+ ...context,
249
+ runOutputDir,
250
+ runLogFilePath,
251
+ readAccessRoots,
252
+ },
253
+ moduleUrls
254
+ )
255
+ );
256
+ return { directory, preloadPath, runOutputDir, runLogFilePath };
257
+ });
258
+
259
+/**
260
+ * `composio run` was given neither inline code nor `--file`.
261
+ *
262
+ * An ordinary usage mistake rather than a broken invariant, so it is a typed failure with a
263
+ * one-line message instead of a defect: the caller sees the fix, not a stack trace.
264
+ */
265
+export class MissingRunSourceError extends Data.TaggedError('commands/MissingRunSourceError')<{
266
+ readonly message: string;
267
+}> {}
268
+
269
+const MISSING_RUN_SOURCE_MESSAGE = [
270
+ 'Provide inline code or use --file to run a script file.',
271
+ ` composio run 'console.log(1)'`,
272
+ ' composio run --file ./script.ts',
273
+].join('\n');
274
275
export const buildRunCommand = ({
276
path,
284
args: ReadonlyArray<string>;
285
preloadPath: string;
286
preloadDirectory: string;
253
-}) => {
254
- // Use process.execPath directly — the child is spawned with BUN_BE_BUN=1
255
- // which makes compiled Bun binaries act as a plain Bun runtime.
256
- // Avoid the `run` subcommand entirely since Bun intercepts it as its own
257
- // built-in; `bun --preload <file> <script>` works without it.
258
- const base = [process.execPath, '--preload', preloadPath];
259
- if (Option.isSome(file)) {
260
- const filePath = path.resolve(file.value);
261
- const wrapperFilePath = path.join(
262
- path.dirname(filePath),
263
- `.composio-run-${path.basename(preloadDirectory)}${path.extname(filePath) || '.ts'}`
264
- );
265
- fs.writeFileSync(
266
- wrapperFilePath,
267
- wrapFileSourceForRun(fs.readFileSync(filePath, 'utf8')),
268
- 'utf8'
269
- );
270
- return {
271
- cmd: [...base, wrapperFilePath, ...withArgDelimiter(args)],
272
- cleanupPaths: [wrapperFilePath],
273
- };
274
- }
287
+}) =>
288
+ Effect.gen(function* () {
289
+ const fs = yield* FileSystem.FileSystem;
290
+ // Use process.execPath directly — the child is spawned with BUN_BE_BUN=1
291
+ // which makes compiled Bun binaries act as a plain Bun runtime.
292
+ // Avoid the `run` subcommand entirely since Bun intercepts it as its own
293
+ // built-in; `bun --preload <file> <script>` works without it.
294
+ const base = [process.execPath, '--preload', preloadPath];
295
+ if (Option.isSome(file)) {
296
+ const filePath = path.resolve(file.value);
297
+ const wrapperFilePath = path.join(
298
+ path.dirname(filePath),
299
+ `.composio-run-${path.basename(preloadDirectory)}${path.extname(filePath) || '.ts'}`
300
+ );
301
+ yield* fs.writeFileString(
302
+ wrapperFilePath,
303
+ wrapFileSourceForRun(yield* fs.readFileString(filePath, 'utf8'))
304
+ );
305
+ return {
306
+ cmd: [...base, wrapperFilePath, ...withArgDelimiter(args)],
307
+ cleanupPaths: [wrapperFilePath],
308
+ };
309
+ }
310
276
- const [inlineCode, ...scriptArgs] = args;
277
- if (inlineCode) {
278
- const wrappedInlineCode = [
279
- '(async () => {',
280
- wrapInlineCodeForRun(inlineCode),
281
- '})().then((__composioResult) => {',
282
- ' if (__composioResult !== undefined) {',
283
- ' console.log(__composioResult);',
284
- ' }',
285
- '});',
286
- ].join('\n');
287
- return {
288
- cmd: [...base, '--eval', wrappedInlineCode, ...withArgDelimiter(scriptArgs)],
289
- cleanupPaths: [],
290
- };
291
- }
311
+ const [inlineCode, ...scriptArgs] = args;
312
+ if (inlineCode) {
313
+ const wrappedInlineCode = [
314
+ '(async () => {',
315
+ wrapInlineCodeForRun(inlineCode),
316
+ '})().then((__composioResult) => {',
317
+ ' if (__composioResult !== undefined) {',
318
+ ' console.log(__composioResult);',
319
+ ' }',
320
+ '});',
321
+ ].join('\n');
322
+ return {
323
+ cmd: [...base, '--eval', wrappedInlineCode, ...withArgDelimiter(scriptArgs)],
324
+ cleanupPaths: [],
325
+ };
326
+ }
327
293
- throw new Error('Provide inline code or use --file to run a script file.');
294
-};
328
+ return yield* Effect.fail(new MissingRunSourceError({ message: MISSING_RUN_SOURCE_MESSAGE }));
329
+ });
330
331
const resolveRunHelperContext = () =>
332
Effect.gen(function* () {
333
const path = yield* Path.Path;
334
+ const os = yield* NodeOs;
335
const userContext = yield* ComposioUserContext;
336
const apiKey = Option.getOrUndefined(userContext.data.apiKey);
337
const orgId = Option.getOrUndefined(userContext.data.orgId);
302
- const defaultComposioDir = path.join(os.homedir(), USER_COMPOSIO_DIR);
303
- const configuredCacheDir =
304
- // eslint-disable-next-line eslint-js/no-restricted-syntax -- honors the same COMPOSIO_CACHE_DIR/CACHE_DIR overrides the run-helpers child runtime reads, so the sandbox read roots match the child's cache location
305
- process.env.COMPOSIO_CACHE_DIR?.trim() || process.env.CACHE_DIR?.trim() || defaultComposioDir;
338
+ const defaultComposioDir = path.join(os.homedir, USER_COMPOSIO_DIR);
339
+ // Honors the same COMPOSIO_CACHE_DIR-then-CACHE_DIR precedence the spawned
340
+ // run-helpers child applies when locating its cache, so the sandbox read
341
+ // roots below always include the directory the child actually uses.
342
+ const composioCacheDir = yield* APP_CONFIG.CACHE_DIR;
343
+ const hostCacheDir = yield* loadHostConfig(UNPREFIXED_CONFIG.CACHE_DIR);
344
+ const configuredCacheDir = composioCacheDir || hostCacheDir || defaultComposioDir;
345
const baseReadAccessRoots = [
346
...new Set([defaultComposioDir, configuredCacheDir].map(value => path.resolve(value))),
347
];
351
baseURL: userContext.data.baseURL,
352
webURL: userContext.data.webURL,
353
orgId,
354
+ cliConfigPath: yield* resolveCliConfigPath,
355
readAccessRoots: baseReadAccessRoots,
356
} satisfies RunHelperContext;
357
364
return baseContext;
365
}
366
367
+ const sessionArtifactsDir = Option.getOrUndefined(
368
+ yield* resolveCliSessionArtifacts({
369
+ orgId,
370
+ consumerUserId: consumerProject.value.consumerUserId,
371
+ }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
372
+ );
373
+
374
return {
375
...baseContext,
376
consumerUserId: consumerProject.value.consumerUserId,
377
consumerProjectId: consumerProject.value.projectId,
378
consumerProjectName: consumerProject.value.projectName,
332
- runOutputDir: Option.getOrUndefined(
333
- yield* resolveCliSessionArtifacts({
334
- orgId,
335
- consumerUserId: consumerProject.value.consumerUserId,
336
- }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
337
- ),
379
+ runOutputDir: sessionArtifactsDir,
380
readAccessRoots: [
381
...new Set(
340
- [
341
- ...baseReadAccessRoots,
342
- Option.getOrUndefined(
343
- yield* resolveCliSessionArtifacts({
344
- orgId,
345
- consumerUserId: consumerProject.value.consumerUserId,
346
- }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
347
- ),
348
- ]
382
+ [...baseReadAccessRoots, sessionArtifactsDir]
383
.filter((value): value is string => typeof value === 'string' && value.length > 0)
384
.map(value => path.resolve(value))
385
),
387
} satisfies RunHelperContext;
388
});
389
390
+/**
391
+ * Signals the CLI forwards to the script it runs. Anything else (SIGHUP, SIGQUIT, …) keeps the
392
+ * platform default: the executor's finalizer still tears the child's process group down.
393
+ */
394
+const FORWARDED_SIGNALS = ['SIGINT', 'SIGTERM'] as const;
395
+
396
+type ForwardedSignal = (typeof FORWARDED_SIGNALS)[number];
397
+
398
+/**
399
+ * How long the CLI waits for the script to finish its own signal handling before the platform
400
+ * executor's finalizer sends SIGTERM to the process group.
401
+ */
402
+const CHILD_SIGNAL_GRACE_PERIOD = Duration.seconds(2);
403
+
404
+class ChildSignalError extends Data.TaggedError('ChildSignalError')<{
405
+ readonly pid: number;
406
+ readonly signal: ForwardedSignal;
407
+ readonly cause: unknown;
408
+}> {}
409
+
410
+/**
411
+ * Sends `signal` to the child's process group and reports whether it was delivered.
412
+ *
413
+ * The @effect/platform executor spawns with `detached: true` on POSIX, so the script leads its
414
+ * own process group and a negative pid is what reaches it (and anything it spawned). Delivery
415
+ * fails with ESRCH when the group is already gone, which is a normal race, not a run failure.
416
+ */
417
+const signalChildProcessGroup = (pid: number, signal: ForwardedSignal): boolean =>
418
+ Either.try({
419
+ try: () => process.kill(-pid, signal),
420
+ catch: cause => new ChildSignalError({ pid, signal, cause }),
421
+ }).pipe(Either.getOrElse(() => false));
422
+
423
+/**
424
+ * Waits for the script to exit, giving up after `duration`.
425
+ *
426
+ * `Effect.timeout` cannot express this here: the wait runs in a release, while the fiber is
427
+ * already interrupted, and the timer `Effect.timeout` forks as a child of that fiber is
428
+ * interrupted along with it — leaving the wait hanging until the script exits on its own.
429
+ * Daemon fibers are detached from the interrupted fiber, so their deadline still fires.
430
+ */
431
+const awaitChildExitWithin = (child: CommandExecutor.Process, duration: Duration.Duration) =>
432
+ Effect.gen(function* () {
433
+ const settled = yield* Deferred.make<void>();
434
+ const complete = Deferred.succeed(settled, undefined);
435
+ yield* Effect.forkDaemon(Effect.zipRight(Effect.ignore(child.exitCode), complete));
436
+ yield* Effect.forkDaemon(Effect.zipRight(Effect.sleep(duration), complete));
437
+ yield* Deferred.await(settled);
438
+ });
439
+
440
+/**
441
+ * Forwards terminal signals to the running script for as long as it is alive.
442
+ *
443
+ * A terminal Ctrl-C only reaches the CLI's process group, so without this the script never
444
+ * observes SIGINT and its `process.on('SIGINT')` cleanup never runs — it is reached later and
445
+ * only as the executor's SIGTERM. Handlers are registered and removed with the scope so they
446
+ * never leak into a later run.
447
+ */
448
+const forwardSignalsToChild = (child: CommandExecutor.Process) =>
449
+ Effect.gen(function* () {
450
+ const os = yield* NodeOs;
451
+ // Windows has no process groups and the executor does not detach there.
452
+ if (os.platform === 'win32') {
453
+ return;
454
+ }
455
+
456
+ const pid = Number(child.pid);
457
+ const forwarded = MutableRef.make(false);
458
+
459
+ yield* Effect.acquireRelease(
460
+ Effect.sync(() =>
461
+ FORWARDED_SIGNALS.map(signal => {
462
+ const listener = () => {
463
+ if (signalChildProcessGroup(pid, signal)) {
464
+ MutableRef.set(forwarded, true);
465
+ }
466
+ };
467
+ process.on(signal, listener);
468
+ return { signal, listener } as const;
469
+ })
470
+ ),
471
+ listeners =>
472
+ Effect.sync(() => {
473
+ for (const { signal, listener } of listeners) {
474
+ process.removeListener(signal, listener);
475
+ }
476
+ }).pipe(
477
+ Effect.zipRight(
478
+ MutableRef.get(forwarded)
479
+ ? awaitChildExitWithin(child, CHILD_SIGNAL_GRACE_PERIOD)
480
+ : Effect.void
481
+ )
482
+ )
483
+ );
484
+ });
485
+
486
export const runCmd = Command.make('run', {
487
file,
488
dryRun,
559
args,
560
}) =>
561
Effect.gen(function* () {
562
+ // Checked before any setup work so a bare `composio run` neither creates a run-artifacts
563
+ // directory nor advertises a log file for a script that will never start.
564
+ if (Option.isNone(file) && !args[0]) {
565
+ return yield* Effect.fail(
566
+ new MissingRunSourceError({ message: MISSING_RUN_SOURCE_MESSAGE })
567
+ );
568
+ }
569
+
570
+ const fs = yield* FileSystem.FileSystem;
571
const path = yield* Path.Path;
433
- // eslint-disable-next-line eslint-js/no-restricted-syntax -- reuses the run ID a parent `composio run` process passed via env so nested runs share one run identity
434
- const runId = process.env.COMPOSIO_CLI_PARENT_RUN_ID ?? crypto.randomUUID();
435
- const perfDebug = isPerfDebugEnabled();
436
- const toolDebug = isToolDebugEnabled();
437
- // eslint-disable-next-line eslint-js/no-restricted-syntax -- reads the COMPOSIO_RUN_ACP_ONLY flag a parent process sets to force the ACP-only subagent path in the child run
438
- const acpOnly = process.env.COMPOSIO_RUN_ACP_ONLY === '1';
572
+ const invocation = yield* cliInvocationContext;
573
+ const runId = Option.getOrElse(
574
+ yield* CliRunId,
575
+ () => invocation.parentRunId ?? crypto.randomUUID()
576
+ );
577
+ const perfDebug = yield* isPerfDebugEnabled;
578
+ const toolDebug = yield* isToolDebugEnabled;
579
+ const acpOnly = yield* isAcpOnlyEnabled;
580
+ const telemetryDebug = yield* isTelemetryDebugEnabled;
581
if (Option.isNone(file)) {
582
const [inlineCode] = args;
583
const preloadSlugs = extractInlineExecuteToolSlugs(inlineCode ?? '');
592
const helperContext: RunHelperContext = {
593
...(yield* resolveRunHelperContext()),
594
runId,
453
- master: detectMaster(),
595
+ master: yield* detectMasterFromHost,
596
perfDebug,
597
toolDebug,
598
+ telemetryDebug,
599
debug,
600
logsOff,
601
acpOnly,
612
Effect.mapError(error => new Error(error.message)),
613
Effect.andThen(resolveRunHelperModuleUrls)
614
);
472
- const preload = createRunHelpersPreloadFile(
615
+ const cliPrefix = yield* inferCliInvocationPrefix(path);
616
+ const preload = yield* createRunHelpersPreloadFile(
617
path,
474
- inferCliInvocationPrefix(path),
618
+ cliPrefix,
619
helperContext,
620
runHelperModuleUrls
621
);
622
const ui = yield* TerminalUI;
479
- let cleanupPaths: ReadonlyArray<string> = [];
480
- // eslint-disable-next-line eslint-js/no-restricted-syntax -- try/finally removes the temp preload and wrapper files around the imperative Bun.spawn block, whose success path ends in process.exit
481
- try {
482
- yield* appendCliSessionHistory({
483
- orgId: helperContext.orgId,
484
- consumerUserId: helperContext.consumerUserId,
485
- entry: {
486
- command: 'run',
487
- status: 'start',
488
- file: Option.getOrUndefined(file),
489
- args,
490
- debug,
491
- },
492
- }).pipe(Effect.catchAll(() => Effect.void));
493
- yield* ui.error(`RUN_LOG_FILE=${preload.runLogFilePath}`);
494
- const runCommand = buildRunCommand({
495
- path,
496
- file,
623
+ yield* appendCliSessionHistory({
624
+ orgId: helperContext.orgId,
625
+ consumerUserId: helperContext.consumerUserId,
626
+ entry: {
627
+ command: 'run',
628
+ status: 'start',
629
+ file: Option.getOrUndefined(file),
630
args,
498
- preloadPath: preload.preloadPath,
499
- preloadDirectory: preload.directory,
500
- });
501
- cleanupPaths = runCommand.cleanupPaths;
502
- const child = Bun.spawn({
503
- cmd: runCommand.cmd,
504
- env: {
505
- // eslint-disable-next-line eslint-js/no-restricted-syntax -- spreads the caller's full environment into the spawned script so user-provided variables reach the child process
506
- ...process.env,
631
+ debug,
632
+ },
633
+ }).pipe(Effect.catchAll(() => Effect.void));
634
+ yield* ui.error(`RUN_LOG_FILE=${preload.runLogFilePath}`);
635
+ const runCommand = yield* buildRunCommand({
636
+ path,
637
+ file,
638
+ args,
639
+ preloadPath: preload.preloadPath,
640
+ preloadDirectory: preload.directory,
641
+ });
642
+ const exitCode = yield* Effect.gen(function* () {
643
+ const [executable, ...commandArgs] = runCommand.cmd;
644
+ const command = PlatformCommand.make(executable, ...commandArgs).pipe(
645
+ PlatformCommand.env({
646
BUN_BE_BUN: '1',
647
COMPOSIO_CLI_PARENT_RUN_ID: runId,
509
- ...(perfDebug ? { COMPOSIO_PERF_DEBUG: '1' } : {}),
510
- ...(toolDebug ? { COMPOSIO_TOOL_DEBUG: '1' } : {}),
511
- },
512
- stdio: ['inherit', 'inherit', 'inherit'],
513
- });
514
-
515
- const exitCode = yield* Effect.promise(() => child.exited);
516
- process.exit(exitCode);
517
- } finally {
518
- for (const cleanupPath of cleanupPaths) {
519
- fs.rmSync(cleanupPath, { force: true });
520
- }
521
- fs.rmSync(preload.directory, { recursive: true, force: true });
522
- }
523
- })
648
+ ...debugFlagsToChildEnv({ perfDebug, toolDebug, acpOnly, telemetryDebug }),
649
+ }),
650
+ PlatformCommand.stdin('inherit'),
651
+ PlatformCommand.stdout('inherit'),
652
+ PlatformCommand.stderr('inherit')
653
+ );
654
+ // Start the process instead of running it to completion: only a started process
655
+ // exposes the pid the signal forwarding below needs.
656
+ const child = yield* PlatformCommand.start(command);
657
+ yield* forwardSignalsToChild(child);
658
+ return Number(yield* child.exitCode);
659
+ }).pipe(
660
+ Effect.scoped,
661
+ Effect.ensuring(
662
+ Effect.forEach(
663
+ runCommand.cleanupPaths,
664
+ cleanupPath => fs.remove(cleanupPath, { force: true }),
665
+ { discard: true }
666
+ ).pipe(
667
+ // The wrapper file sits next to the user's script, so removal can fail on a
668
+ // read-only or locked directory. That must not turn an already-successful run
669
+ // into a failure, which is what the previous `Effect.orDie` did.
670
+ Effect.ignore
671
+ )
672
+ ),
673
+ // Interruption (Ctrl-C) skips the assignment below, and the default teardown reports
674
+ // an interrupt-only exit as success. Report the conventional 128+SIGINT instead so
675
+ // wrappers and `set -e` scripts do not read a cancelled run as a passing one.
676
+ Effect.onInterrupt(() =>
677
+ Effect.sync(() => {
678
+ process.exitCode = 130;
679
+ })
680
+ )
681
+ );
682
+ process.exitCode = exitCode;
683
+ }).pipe(Effect.scoped)
684
)
685
);