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

next
ts 158 lines 6.16 KB
Raw
1 /**
2 * The CLI's main runner, in place of `BunRuntime.runMain`: it owns the process signal handlers
3 * and decides how the process ends. A runtime boundary, like `bin.ts`.
4 *
5 * - The first SIGINT, SIGTERM or SIGHUP goes to a command that cooperates on it (see
6 * `ShutdownSignal`), which stops by itself; any other command is interrupted.
7 * - An exit made of interruptions alone, after a signal, is reported as 128 + the signal's number
8 * (130, 143, 129); a child `composio run` mirrors that a signal ended is re-raised; anything
9 * else exits with the code `Runtime.defaultTeardown` picks from Effect's runtime markers.
10 * - A second signal, or a first one whose stop outlives {@link SHUTDOWN_DEADLINE}, forces the
11 * exit without waiting for finalizers.
12 */
13 import process from 'node:process';
14 import { Cause, Data, Duration, Exit, Option, Runtime } from 'effect';
15 import { ChildProcessSignaled } from 'src/effects/child-process-exited';
16 import {
17 STOP_SIGNALS,
18 signalExitCode,
19 type ShutdownController,
20 type StopSignal,
21 type TerminationSignal,
22 } from 'src/services/shutdown-signal';
23
24 /** How long a stop may take after the first signal before the runner forces the exit. */
25 export const SHUTDOWN_DEADLINE = Duration.seconds(10);
26
27 /** How long a re-raised signal has to end the process before it exits 128 + n instead. */
28 const RERAISE_FALLBACK = Duration.seconds(1);
29
30 export type ExitAction = Data.TaggedEnum<{
31 /** Exit with this code. */
32 ExitWith: { readonly code: number };
33 /** End the process with this signal, the way the child it mirrors ended. */
34 Reraise: { readonly signal: TerminationSignal };
35 }>;
36
37 export const ExitAction = Data.taggedEnum<ExitAction>();
38
39 /**
40 * How the process ends for `exit`, given the first signal it received.
41 *
42 * A child that a signal ended is mirrored by re-raising that signal. A run cancelled by a signal
43 * (interruptions alone) exits 128 + the signal's number. Everything else, a cooperative stop
44 * included, is what `teardown` (by default `Runtime.defaultTeardown`) picks: 0 on success, 130
45 * on an interruption no signal caused, otherwise the failure's `[Runtime.errorExitCode]`.
46 */
47 export const exitActionFor = (
48 exit: Exit.Exit<unknown, unknown>,
49 received: Option.Option<StopSignal>,
50 teardown: Runtime.Teardown = Runtime.defaultTeardown
51 ): ExitAction => {
52 if (Exit.isFailure(exit)) {
53 const squashed = Cause.squash(exit.cause);
54 if (squashed instanceof ChildProcessSignaled) {
55 return ExitAction.Reraise({ signal: squashed.signal });
56 }
57 if (Option.isSome(received) && Cause.hasInterruptsOnly(exit.cause)) {
58 return ExitAction.ExitWith({ code: signalExitCode(received.value) });
59 }
60 }
61 let code = 1;
62 teardown(exit, teardownCode => {
63 code = teardownCode;
64 });
65 return ExitAction.ExitWith({ code });
66 };
67
68 /** The process operations the runner needs, replaceable in tests. */
69 export interface RunnerPlatform {
70 readonly on: (signal: StopSignal, listener: () => void) => void;
71 readonly off: (signal: StopSignal, listener: () => void) => void;
72 readonly exit: (code: number) => void;
73 /** Ends the process with `signal`, as the default action of that signal would. */
74 readonly raise: (signal: TerminationSignal) => void;
75 /** Runs `f` after `millis`; the returned function cancels it. */
76 readonly schedule: (millis: number, f: () => void) => () => void;
77 }
78
79 const processPlatform: RunnerPlatform = {
80 on: (signal, listener) => {
81 process.on(signal, listener);
82 },
83 off: (signal, listener) => {
84 process.removeListener(signal, listener);
85 },
86 exit: code => process.exit(code),
87 raise: signal => {
88 // The runner removed its own handlers first, so the signal's default action ends the
89 // process and the caller's `wait` sees it signalled. Another listener, or an ignored signal,
90 // would keep it alive; the timer makes sure it still ends.
91 setTimeout(() => process.exit(signalExitCode(signal)), Duration.toMillis(RERAISE_FALLBACK));
92 process.kill(process.pid, signal);
93 },
94 schedule: (millis, f) => {
95 const timer = setTimeout(f, millis);
96 return () => clearTimeout(timer);
97 },
98 };
99
100 /** A `runMain` that reports to `controller` the signals the process receives. */
101 export const makeCliRunMain = (
102 controller: ShutdownController,
103 platform: RunnerPlatform = processPlatform
104 ) =>
105 Runtime.makeRunMain(({ fiber, teardown }) => {
106 let received = Option.none<StopSignal>();
107 let finished = false;
108 let cancelDeadline = () => {};
109
110 const listeners = STOP_SIGNALS.map(signal => ({ signal, listener: () => onSignal(signal) }));
111 const release = () => {
112 cancelDeadline();
113 listeners.forEach(({ signal, listener }) => platform.off(signal, listener));
114 };
115 const finish = (action: ExitAction) => {
116 if (finished) {
117 return;
118 }
119 finished = true;
120 release();
121 ExitAction.$match(action, {
122 ExitWith: ({ code }) => platform.exit(code),
123 Reraise: ({ signal }) => platform.raise(signal),
124 });
125 };
126 // Kill what cooperating commands started, then end now: a forced `composio run` re-raises
127 // the signal like the child it supervises would have died; anything else exits 128 + n.
128 const force = (signal: StopSignal) =>
129 finish(
130 controller.force().reraise
131 ? ExitAction.Reraise({ signal })
132 : ExitAction.ExitWith({ code: signalExitCode(signal) })
133 );
134 const onSignal = (signal: StopSignal) => {
135 if (Option.isSome(received)) {
136 force(signal);
137 return;
138 }
139 received = Option.some(signal);
140 cancelDeadline = platform.schedule(Duration.toMillis(SHUTDOWN_DEADLINE), () => force(signal));
141 if (!controller.offer(signal)) {
142 fiber.interruptUnsafe(fiber.id);
143 }
144 };
145
146 listeners.forEach(({ signal, listener }) => platform.on(signal, listener));
147 fiber.addObserver(exit => {
148 const action = exitActionFor(exit, received, teardown);
149 // Like `BunRuntime.runMain`: a clean success nobody signalled ends when the event loop
150 // drains, so pending output is flushed.
151 if (Option.isNone(received) && ExitAction.$is('ExitWith')(action) && action.code === 0) {
152 finished = true;
153 release();
154 return;
155 }
156 finish(action);
157 });
158 });