@devries-cameron20 / composio Mirror · read-only / commits / cb3f55e0f
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 07:15 UTC

fix(cli): exit per command type on interrupt and handle SIGHUP (#5131)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/5128 (now merged), replacing its "every interrupt exits 130" with a per-command rule - replaces `BunRuntime.runMain` with `makeCliRunMain` (`src/run-main.ts`, on `Runtime.makeRunMain`): it handles SIGINT, SIGTERM and SIGHUP, exits 128 + n for a run a signal cancelled, and otherwise defers to `Runtime.defaultTeardown`, so `[Runtime.errorExitCode]` markers and `ShowHelp` keep their codes - adds the invocation-scoped `ShutdownSignal` service: a command that `cooperate`s on a signal gets it through `requested` instead of being interrupted; a second signal, or a stop longer than 10s, forces the exit - `listen` and `dev triggers listen` cooperate on SIGINT/SIGTERM once Pusher confirms the subscription (new `onSubscribed` hook on `TriggersRealtime`, run after `pusher:subscription_succeeded`; `pusher:subscription_error` fails the listener), run their cleanup, and exit 0 - `run` forwards every signal to the script's process group, escalates to SIGTERM and then SIGKILL 2s apart, and mirrors the script: its code (`ChildProcessExited`) or its signal (`ChildProcessSignaled`, re-raised by the runner), or the first signal the CLI received when its own escalation killed the script; `childExitStatus` recovers the `{ code, signal }` the spawner drops - no new lint-boundary disables: `process.on`, `process.kill` and `process.exit` are not lint-banned, and `run` no longer installs its own `process.on` handlers | Command | SIGINT | SIGTERM | SIGHUP | second signal | | --- | --- | --- | --- | --- | | `listen`, `dev triggers listen` (subscribed) | 0 after cleanup | 0 after cleanup | 129 | 128 + n | | same, before the subscription is confirmed | 130 | 143 | 129 | 128 + n | | one-shot commands, `login`, `upgrade` | 130 | 143 | 129 | 128 + n | | `run` | forward, mirror the script | same | same | kill the group, re-raise | ## Context Similar CLIs do not agree on what a listener should exit with. `wrangler tail`, `kubectl port-forward` and `stripe listen` return normally (0) on Ctrl-C. `docker` maps signal deaths to 128 + n. `vercel dev` exits 130/143/129. For a wrapper, npm's run-script, turbo's JS shim, pnpm and `bun run` all forward the signal and end the way the child did. Each row above follows from what the command owns: a listener owns a session the user is expected to stop, a one-shot owns an operation the signal cancelled, and `run` supervises another program, so the script decides the result. `upgrade`: each file swap is atomic (copy to a sibling staging dir, then `rename`), but the companions, the release tag and the binary are swapped one after another. An interrupt between them leaves new companions next to the old binary. This PR does not change that. Verification: `pnpm typecheck`, `lint:effect`, `pnpm --filter @composio/cli test` (214 files, 2619 passed, 1 skipped, including a spawned `bun src/bin.ts` test asserting 130/143/129 for a blocked `orgs list`), and oxlint. Manual `bun src/bin.ts run …` against a stub backend: default script + SIGINT → CLI killed by SIGINT; a script that traps SIGINT and exits 0 → 0; one that traps SIGTERM and exits 5 → 5; SIGHUP → killed by SIGHUP; ignores SIGINT → killed by SIGTERM; ignores both → SIGKILL (these two manual runs predate the change that ends the CLI by the first signal when its escalation killed the script; that case is covered by `run.cmd.test.ts`). Not exercised live: `listen` against a real realtime backend (covered by command tests with a stubbed subscription). --------- Co-authored-by: Vinayak Agarwal <vinayak@composio.dev> Co-authored-by: manobhisriram <manobhisriram@gmail.com>

Alberto Schiabel committed Oct 28, 2026 at 14:27 UTC cb3f55e0f5968889c68cd667419e6f2a7f6eeb28
23 files changed +1468 -184
.agents/skills/cli-command/references/design.md
+1 -1
@@ -26,7 +26,7 @@
26 - Runtime config is read from environment variables via `effect/Config`. Every variable the CLI reads is declared, under its full name, in one of the catalogs in `src/config` (`APP_CONFIG` for user-facing `COMPOSIO_*` settings, `DEBUG_CONFIG`, `TELEMETRY_CONFIG`, `HOST_CONFIG`, `GITHUB_CONFIG`); add new variables there, never inline. Tests inject `ConfigProvider.fromEnvRecord({...})`.
27 - Persistent user/auth state lives in `~/.composio/user-config.json`; `ComposioUserContext` merges environment variables over the stored file, so an env var overrides the stored value.
28 - Project-scoped data uses a project-local `.composio/` directory.
29 -- Exit `0` on success, `1` on failure, and `130` on interruption (Ctrl-C, SIGTERM); `composio run` exits with its script's code. Never assign `process.exitCode`: an error declares `[Runtime.errorExitCode]` / `[Runtime.errorReported]` (effect `Runtime`), and `Runtime.defaultTeardown`, run by `BunRuntime.runMain` in `src/cli-main.ts`, picks the code. There is no distinct "invalid usage" exit code — do not invent one.
29 +- Exit `0` on success and `1` on failure. A command a signal cancels exits 128 + the signal's number: `130` (Ctrl-C), `143` (SIGTERM), `129` (SIGHUP). A listener stopped with Ctrl-C or SIGTERM once subscribed exits `0`; `composio run` ends the way its script did (its code, or the same signal). Never assign `process.exitCode`: an error declares `[Runtime.errorExitCode]` / `[Runtime.errorReported]` (effect `Runtime`), and `Runtime.defaultTeardown`, run by the CLI's runner (`src/run-main.ts`), picks the code. Never install signal handlers in a command; cooperate through `ShutdownSignal` instead (see `ts/packages/cli/AGENTS.md`). There is no distinct "invalid usage" exit code — do not invent one.
30
31 ## References
32
.agents/skills/effect-v4/references/cli-surface.md
+5 -4
@@ -99,14 +99,15 @@ The CLI's own errors use the same contract. A failure a command already printed
99 (`ReportedFailure` from `src/effects/report-failure.ts`, `ReportedToolExecutionError`,
100 `ShellSetupAbortError`, `SetupCommandError`, …) or that carries a custom code
101 (`ChildProcessExited` from `composio run`) declares the markers as getters, and
102 -`ts/packages/cli/src/cli-main.ts` runs with `Runtime.defaultTeardown`, which exits 0 on
103 -success, 130 on interruption alone, and otherwise with the squashed failure's
104 -`errorExitCode` (1 when unset). Nothing in `src/` assigns `process.exitCode`.
102 +the CLI's runner (`ts/packages/cli/src/run-main.ts`, built on `Runtime.makeRunMain`) exits
103 +through `Runtime.defaultTeardown`: 0 on success, and otherwise with the squashed failure's
104 +`errorExitCode` (1 when unset). An exit made of interruptions alone after a signal is 128 + the
105 +signal's number instead (130, 143, 129). Nothing in `src/` assigns `process.exitCode`.
106
107 `cli-main.ts`'s sandboxed catch-all handler drops every failure whose `errorReported` is
108 false (`ShowHelp` included) from the cause; when nothing is left it re-fails with the
109 original `Cause` via `Effect.failCause(cause)`, so the failure reaches
109 -`BunRuntime.runMain` untouched and the markers take over. If you add rendering anywhere in
110 +the runner untouched and the markers take over. If you add rendering anywhere in
111 this path, you will double-print — this is the single most important rule when touching
112 the runner. Whatever is left is a genuine defect, captured via `effect-errors`, printed,
113 and re-failed as a `ReportedFailure`; `Command.runWith` never renders that path, so
ts/packages/cli/AGENTS.md
+4 -2
@@ -16,7 +16,7 @@ The CLI is built on the **Effect.ts ecosystem** and runs on **Bun**. Service-ori
16
17 ### Entry Point — `src/bin.ts` / `src/cli-main.ts`
18
19 -`bin.ts` is a thin bootstrap: it routes background-worker invocations (analytics dispatch) through a minimal layer set and otherwise passes argv unchanged to the dynamically imported `cli-main.ts`, which composes the full Effect layer stack and drives the root command through `effect/cli`'s `Command.runWith`, run via `BunRuntime.runMain()`. Key layers (see `cli-main.ts` for the complete list):
19 +`bin.ts` is a thin bootstrap: it routes background-worker invocations (analytics dispatch) through a minimal layer set and otherwise passes argv unchanged to the dynamically imported `cli-main.ts`, which composes the full Effect layer stack and drives the root command through `effect/cli`'s `Command.runWith`, run by the CLI's own runner (`makeCliRunMain` in `src/run-main.ts`, built on `Runtime.makeRunMain`). Key layers (see `cli-main.ts` for the complete list):
20
21 - `CliConfigLive` — `effect/cli` `CliConfig` restricted to `builtIns: [Help, GlobalFlag.Version]` (see Configuration below); a small `CliOutput.Formatter` keeps versions bare and appends a short root overview; Effect generates command help and parse errors
22 - `ComposioUserContextLive` — User authentication state from `~/.composio/`
@@ -25,7 +25,9 @@ The CLI is built on the **Effect.ts ecosystem** and runs on **Bun**. Service-ori
25 - `UpgradeBinaryLive` — Self-update from GitHub releases
26 - `BunFileSystem.layer`, `BunPath.layer`, `BunServices.layer`, `FetchHttpClient.layer` — Bun runtime integration (`@effect/platform-bun`'s `BunContext` no longer exists in v4; `BunServices.layer` is the aggregate replacement)
27
28 -Explicit help and version actions complete successfully. `Command.runWith` renders parse/validation errors and contextual help itself before re-failing with `CliError.ShowHelp`, which carries `[Runtime.errorReported] = false` (suppresses `runMain`'s automatic error log) and `[Runtime.errorExitCode]` (1 alongside parse errors). `cli-main.ts`'s sandboxed catch-all re-fails every failure already on screen (`[Runtime.errorReported] = false`, `ShowHelp` included) with its original `Cause` via `Effect.failCause` instead of printing it, and `BunRuntime.runMain` runs with `Runtime.defaultTeardown`: exit 0 on success, 130 on interruption (Ctrl-C, SIGTERM), otherwise the squashed failure's `[Runtime.errorExitCode]`, or 1 without one. This preserves failing exit codes without duplicate error output. Never assign `process.exitCode`; an error that needs a code other than 1 declares it (`ChildProcessExited` in `src/effects/child-process-exited.ts`, which `composio run` fails with when its script exits non-zero). See the module docstring at the top of `cli-main.ts` for the argv-prefix contract with `src/commands/index.ts`.
28 +Explicit help and version actions complete successfully. `Command.runWith` renders parse/validation errors and contextual help itself before re-failing with `CliError.ShowHelp`, which carries `[Runtime.errorReported] = false` (suppresses the runner's automatic error log) and `[Runtime.errorExitCode]` (1 alongside parse errors). `cli-main.ts`'s sandboxed catch-all re-fails every failure already on screen (`[Runtime.errorReported] = false`, `ShowHelp` included) with its original `Cause` via `Effect.failCause` instead of printing it, and the runner exits through `Runtime.defaultTeardown`: 0 on success, otherwise the squashed failure's `[Runtime.errorExitCode]`, or 1 without one. This preserves failing exit codes without duplicate error output. Never assign `process.exitCode`; an error that needs a code other than 1 declares it (`ChildProcessExited` in `src/effects/child-process-exited.ts`, which `composio run` fails with when its script exits non-zero). See the module docstring at the top of `cli-main.ts` for the argv-prefix contract with `src/commands/index.ts`.
29 +
30 +Signals belong to the runner, the one place that installs SIGINT, SIGTERM and SIGHUP handlers; never add `process.on` for them elsewhere. It hands the first signal to the invocation's `ShutdownSignal` service (`src/services/shutdown-signal.ts`). A command that registered with `cooperate` for that signal stops by itself and ends normally: `listen` and `dev triggers listen` register `LISTENER_STOP` (SIGINT, SIGTERM) once Pusher confirms the subscription, through `TriggersRealtime`'s `onSubscribed`, and exit 0; `run` registers every signal, forwards it to its script's process group, and mirrors how the script ended (its code, or `ChildProcessSignaled`, whose signal the runner re-raises; when the CLI's own SIGTERM/SIGKILL escalation ended the script, the first signal instead). Every other command is interrupted, and an exit made of interruptions alone after a signal is 128 + its number: 130 (SIGINT), 143 (SIGTERM), 129 (SIGHUP). A second signal, or a stop longer than `SHUTDOWN_DEADLINE` (10 seconds), forces the exit: 128 + n, or for `run`, kill the script's group and re-raise.
31
32 Errors are captured via the custom `effect-errors/` module (source-mapped stack traces, Effect span timelines, formatted output).
33
ts/packages/cli/CHANGELOG.md
+17 -4
@@ -4,6 +4,22 @@
4
5 ### Minor Changes
6
7 +- A signal now ends each command the way its work ends. A one-shot command,
8 + `composio login` and `composio upgrade` stopped with Ctrl-C (SIGINT), SIGTERM
9 + or a closed terminal (SIGHUP) exit 130, 143 or 129. They used to exit 0, so a
10 + wrapper or `set -e` script read a cancelled command as a successful one.
11 + `composio listen` and `composio dev triggers listen` (`composio dev listen`)
12 + treat Ctrl-C and SIGTERM as the way to stop them once subscribed: they
13 + disable the temporary trigger, print their summary, and exit 0. A signal
14 + before the subscription is confirmed, or SIGHUP, exits 130, 143 or 129 instead.
15 + `composio run` forwards SIGINT, SIGTERM and SIGHUP to its script and ends the
16 + way the script did: with its exit code, or killed by the same signal. A
17 + script still running 2 seconds later gets SIGTERM, then SIGKILL; a script the
18 + CLI had to kill this way ends the CLI by the signal it received. A second
19 + signal, or a stop that takes longer than 10 seconds, ends the CLI at once:
20 + 128 plus the signal's number, or, for `composio run`, the script's process
21 + group is killed and the CLI is killed by that signal.
22 +
23 - `composio dev connected-accounts link <toolkit>` (with or without `--list`)
24 now acts on your developer project, like the other `composio dev` commands:
25 the directory's project, or the one `--project-name` names. It links or lists
@@ -68,10 +84,7 @@
84 `""`. `composio run` starts the script without the consumer user's context,
85 as it does when there is no consumer user.
86
71 -- Stopping any command with Ctrl-C (SIGINT) or SIGTERM now exits 130, as
72 - `composio run` already did. Other commands, `composio listen` among them,
73 - used to exit 0, so a wrapper or `set -e` script read a cancelled command as a
74 - successful one. CLI telemetry now records a command that prints its own
87 +- CLI telemetry now records a command that prints its own
88 failure and exits 1 (a failed API request, an alias conflict on
89 `composio link`, a `--fail-fast` listener stop) as failed instead of
90 succeeded, and a `composio run` whose script exits non-zero as
ts/packages/cli/src/analytics/events.ts
+4 -2
@@ -4,7 +4,7 @@ import { APP_VERSION } from 'src/constants';
4 import { inferSkillReleaseChannel } from 'src/effects/install-skill';
5 import type { AgentHost } from 'src/services/agent-host';
6 import type { CliInvocationContext } from 'src/services/runtime-cli-context';
7 -import { ChildProcessExited } from 'src/effects/child-process-exited';
7 +import { ChildProcessExited, ChildProcessSignaled } from 'src/effects/child-process-exited';
8 import { SetupCommandError } from 'src/services/setup-command-error';
9 import { ToolInputValidationError } from 'src/services/tool-input-validation';
10 import { guessToolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
@@ -263,7 +263,9 @@ const errorNameOf = (error: unknown): string =>
263
264 const failureReasonProperties = (error: unknown) => {
265 if (error instanceof SetupCommandError) return { failure_reason_code: error.reasonCode };
266 - if (error instanceof ChildProcessExited) return { failure_reason_code: 'child_exit' };
266 + if (error instanceof ChildProcessExited || error instanceof ChildProcessSignaled) {
267 + return { failure_reason_code: 'child_exit' };
268 + }
269 return {};
270 };
271
ts/packages/cli/src/cli-main.ts
+16 -11
@@ -4,16 +4,15 @@
4 *
5 * Exit codes come from Effect's runtime markers, never `process.exitCode`: a failure that is
6 * already on screen (ShowHelp, a command's own report, or a message printed here) carries
7 - * `[Runtime.errorReported] = false`, so `BunRuntime.runMain` logs nothing, and
8 - * `Runtime.defaultTeardown` exits with its `[Runtime.errorExitCode]` (1 when unset), 0 on
9 - * success, and 130 on interruption.
7 + * `[Runtime.errorReported] = false`, so the runner logs nothing, and `Runtime.defaultTeardown`
8 + * exits with its `[Runtime.errorExitCode]` (1 when unset), or 0 on success. Signals are the
9 + * runner's (`src/run-main.ts`): a command a signal cancelled exits 128 + its number.
10 */
11 import { Cause, ConfigProvider, Effect, Layer, Logger, Option, Runtime } from 'effect';
12 import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
13 import { CliConfig, CliError } from 'effect/cli';
14 import { FetchHttpClient } from 'effect/http';
15 import * as BunServices from '@effect/platform-bun/BunServices';
16 -import * as BunRuntime from '@effect/platform-bun/BunRuntime';
16 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
17 import * as BunPath from '@effect/platform-bun/BunPath';
18 import { runWithConfig, type RootCommandBootstrap } from 'src/commands';
@@ -69,6 +68,8 @@ import { ReportedFailure } from 'src/effects/report-failure';
68 import { cliInvocationContext } from 'src/services/runtime-cli-context';
69 import { readTelemetryDebugOverride, telemetryDebugModeLayer } from 'src/services/runtime-flags';
70 import { normalizeRunScriptArgs } from 'src/commands/argv-compat';
71 +import { makeShutdownController, ShutdownSignal } from 'src/services/shutdown-signal';
72 +import { makeCliRunMain } from 'src/run-main';
73
74 // Layer is contravariant in ROut and covariant in E, so `never`/`unknown` accept any
75 // produced context and error type while still pinning the requirements (RIn) to `never`.
@@ -181,7 +182,8 @@ const layers = Layer.mergeAll(
182
183 /**
184 * Whether `reason` has nothing for the catch-all to print: a failure already on screen, or an
184 - * interruption, which must reach `Runtime.defaultTeardown` untouched to exit 130.
185 + * interruption, which must reach the runner untouched: 128 + n after a signal, else 130 from
186 + * `Runtime.defaultTeardown`.
187 */
188 const hasNothingToPrint = (reason: Cause.Reason<unknown>): boolean =>
189 Cause.isInterruptReason(reason) ||
@@ -192,9 +194,9 @@ const hasNothingToPrint = (reason: Cause.Reason<unknown>): boolean =>
194 * nothing to print (a failure already on screen — `ShowHelp`, which `Command.runWith` printed
195 * with any parse/validation errors, a command's own report, or a message printed in
196 * `cliProgram` — or an interruption) is re-failed untouched: its `[Runtime.errorReported]` is
195 - * false, so `BunRuntime.runMain` logs nothing, and `Runtime.defaultTeardown` exits with its
196 - * `[Runtime.errorExitCode]`, or 130 for interruptions alone. Nothing here may print it, or
197 - * output doubles.
197 + * false, so the runner logs nothing, and `Runtime.defaultTeardown` exits with its
198 + * `[Runtime.errorExitCode]`; interruptions alone exit 128 + n after a signal, else 130. Nothing
199 + * here may print it, or output doubles.
200 */
201 export const reportUnreportedCause = Effect.fn(function* (cause: Cause.Cause<unknown>) {
202 const unreported = Cause.fromReasons(cause.reasons.filter(reason => !hasNothingToPrint(reason)));
@@ -214,7 +216,7 @@ export const reportUnreportedCause = Effect.fn(function* (cause: Cause.Cause<unk
216 return yield* new ReportedFailure({ message });
217 }
218 }
217 - // Nothing printable: keep the original cause so its exit code survives and `runMain` logs
219 + // Nothing printable: keep the original cause so its exit code survives and the runner logs
220 // whatever is still unreported, instead of exiting 0.
221 return yield* Effect.failCause(cause);
222 });
@@ -230,7 +232,7 @@ const runWithArgs = (argv: ReadonlyArray<string>, bootstrap: RootCommandBootstra
232 Effect.flatMap(runWithConfig, run => run(argv, bootstrap)) as Effect.Effect<
233 void,
234 unknown,
233 - Layer.Success<typeof layers>
235 + Layer.Success<typeof layers> | ShutdownSignal
236 >;
237
238 const runWithTelemetry = (argv: ReadonlyArray<string>) =>
@@ -351,9 +353,12 @@ const cliProgram = (argv: ReadonlyArray<string>) =>
353
354 export const runCli = (options: CliBootstrapOptions): void => {
355 const debug = readTelemetryDebugOverride(normalizeRunScriptArgs(options.argv));
356 + // One per invocation: the runner reports the process's signals to the command through it.
357 + const shutdown = makeShutdownController();
358 cliProgram(options.argv).pipe(
359 + Effect.provideService(ShutdownSignal, shutdown.service),
360 effect =>
361 debug === undefined ? effect : Effect.provide(effect, telemetryDebugModeLayer(debug)),
357 - BunRuntime.runMain({ teardown: Runtime.defaultTeardown })
362 + makeCliRunMain(shutdown)()
363 );
364 };
ts/packages/cli/src/commands/listen.cmd.ts
+14 -14
@@ -16,6 +16,7 @@ import {
16 } from 'src/services/cli-session-artifacts';
17 import { TerminalUI } from 'src/services/terminal-ui';
18 import { TriggersRealtime } from 'src/services/triggers-realtime';
19 +import { LISTENER_STOP, ShutdownSignal } from 'src/services/shutdown-signal';
20 import { resolveConnectedAccountForToolkit } from 'src/services/connected-account-selection';
21 import { parseJsonRecord } from 'src/utils/parse-json';
22 import { toolkitFromToolSlug } from 'src/effects/toolkit-from-tool-slug';
@@ -29,10 +30,7 @@ type TriggerCreateParams = NonNullable<
30
31 export class ListenCommandError extends Data.TaggedError('commands/ListenCommandError')<{
32 readonly reason:
32 - | 'connected_account_not_found'
33 - | 'unknown_trigger'
34 - | 'create_trigger'
35 - | 'disable_trigger';
33 + 'connected_account_not_found' | 'unknown_trigger' | 'create_trigger' | 'disable_trigger';
34 readonly message: string;
35 readonly slug?: string;
36 readonly toolkitSlug?: string;
@@ -470,6 +468,7 @@ export const listenCmd = Command.make(
468 const path = yield* Path.Path;
469 const clientSingleton = yield* ComposioClientSingleton;
470 const realtime = yield* TriggersRealtime;
471 + const shutdown = yield* ShutdownSignal;
472
473 const { userId: actingUserId, project: resolvedProject } = yield* actingUser();
474
@@ -647,11 +646,9 @@ export const listenCmd = Command.make(
646
647 const listenEffect = realtime
648 .listenInProject(
650 - {
651 - orgId: resolvedProject.orgId,
652 - projectId: resolvedProject.projectId,
653 - },
654 - onEvent
649 + { orgId: resolvedProject.orgId, projectId: resolvedProject.projectId },
650 + onEvent,
651 + { onSubscribed: shutdown.cooperate(LISTENER_STOP) }
652 )
653 .pipe(Effect.onInterrupt(() => ui.log.info(`Stopped listening for events ${slug}.`)));
654
@@ -664,9 +661,12 @@ export const listenCmd = Command.make(
661 );
662 }
663
667 - // Without --max-events, --timeout or --fail-fast nothing resolves stopWhenDone, so
668 - // this waits on the listener until it is interrupted.
669 - const stopReason = yield* Effect.raceFirst(listenEffect, Deferred.await(stopWhenDone));
664 + // Ctrl-C or SIGTERM after the subscription is a clean stop: exit 0 after the release.
665 + const stopReason = yield* Effect.raceAllFirst([
666 + listenEffect,
667 + Deferred.await(stopWhenDone),
668 + Effect.as(shutdown.requested, 'signal' as const),
669 + ]);
670 if (stopReason === 'max-events' || stopReason === 'timeout') {
671 yield* finishAcceptedEvents(events, failed);
672 }
@@ -696,8 +696,8 @@ export const listenCmd = Command.make(
696 if (created !== null) {
697 yield* disableTemporaryTrigger({ client, ui, slug, triggerId: created.trigger_id });
698 }
699 - // Runs on every stop of the use phase — max-events, timeout, --fail-fast, and the
700 - // interruption by Ctrl+C or SIGTERM — so a piped caller always gets the count.
699 + // Runs on every stop of the use phase — max-events, timeout, --fail-fast, Ctrl+C or
700 + // SIGTERM, and an interruption — so a piped caller always gets the count.
701 yield* writeFailures.report;
702 })
703 ).pipe(
ts/packages/cli/src/commands/run.cmd.ts
+90 -70
@@ -4,9 +4,17 @@ import { Argument, Command, Flag } from 'effect/cli';
4 import * as FileSystem from 'effect/FileSystem';
5 import * as Path from 'effect/Path';
6 import { ChildProcess, ChildProcessSpawner } from 'effect/process';
7 -import { Data, Deferred, Duration, Effect, MutableRef, Option, Result } from 'effect';
7 +import { Data, Duration, Effect, Option, Ref, Result } from 'effect';
8 import { APP_VERSION } from 'src/constants';
9 -import { ChildProcessExited } from 'src/effects/child-process-exited';
9 +import { ChildProcessExited, ChildProcessSignaled } from 'src/effects/child-process-exited';
10 +import { childExitStatus, type ChildExitStatus } from 'src/effects/child-exit-status';
11 +import {
12 + STOP_SIGNALS,
13 + ShutdownSignal,
14 + type ShutdownSignalShape,
15 + type StopSignal,
16 + type TerminationSignal,
17 +} from 'src/services/shutdown-signal';
18 import { loadGenerationRuntime } from 'src/effects/generation-runtime';
19 import { actingUser } from 'src/commands/surface';
20 import { type RunHelperContext } from 'src/services/run-helpers-runtime';
@@ -309,102 +317,112 @@ const resolveRunHelperContext = () =>
317 });
318
319 /**
312 - * Signals the CLI forwards to the script it runs. Anything else (SIGHUP, SIGQUIT, …) keeps the
313 - * platform default: the executor's finalizer still tears the child's process group down.
314 - */
315 -const FORWARDED_SIGNALS = ['SIGINT', 'SIGTERM'] as const;
316 -
317 -type ForwardedSignal = (typeof FORWARDED_SIGNALS)[number];
318 -
319 -/**
320 - * How long the CLI waits for the script to finish its own signal handling before the platform
321 - * executor's finalizer sends SIGTERM to the process group.
320 + * How long the script gets to handle a forwarded signal before the CLI sends it SIGTERM, and
321 + * again before SIGKILL.
322 */
323 const CHILD_SIGNAL_GRACE_PERIOD = Duration.seconds(2);
324
325 +/** The first signal the CLI received, and the signals it then sent the script itself. */
326 +interface Escalation {
327 + readonly first: StopSignal;
328 + readonly sent: ReadonlyArray<TerminationSignal>;
329 +}
330 +
331 class ChildSignalError extends Data.TaggedError('ChildSignalError')<{
332 readonly pid: number;
327 - readonly signal: ForwardedSignal;
333 + readonly signal: TerminationSignal;
334 readonly cause: unknown;
335 }> {}
336
337 /**
332 - * Sends `signal` to the child's process group and reports whether it was delivered.
338 + * Sends `signal` to the child's process group.
339 *
340 * The `effect/process` spawner spawns with `detached: true` on POSIX, so the script leads its
341 * own process group and a negative pid is what reaches it (and anything it spawned). Delivery
342 * fails with ESRCH when the group is already gone, which is a normal race, not a run failure.
343 */
338 -const signalChildProcessGroup = (pid: number, signal: ForwardedSignal): boolean =>
344 +const signalChildProcessGroup = (pid: number, signal: TerminationSignal): void => {
345 Result.try({
346 try: () => process.kill(-pid, signal),
347 catch: cause => new ChildSignalError({ pid, signal, cause }),
342 - }).pipe(Result.getOrElse(() => false));
348 + });
349 +};
350
351 /**
345 - * Waits for the script to exit, giving up after `duration`.
352 + * Hands the CLI's first signal to the script, then makes sure the script ends: SIGTERM after a
353 + * grace period, SIGKILL after another. The script decides how the run ends, as it would under a
354 + * shell: one that handles SIGINT and exits 0 makes the run succeed.
355 *
347 - * `Effect.timeout` cannot express this here: the wait runs in a release, while the fiber is
348 - * already interrupted, and the timer `Effect.timeout` forks as a child of that fiber is
349 - * interrupted along with it — leaving the wait hanging until the script exits on its own.
350 - * Daemon fibers are detached from the interrupted fiber, so their deadline still fires.
356 + * `escalation` records the first signal and each signal the CLI sends of its own, so a script
357 + * that one of them killed is reported as cancelled by the first signal rather than by SIGTERM or
358 + * SIGKILL.
359 */
352 -const awaitChildExitWithin = (
360 +const relayStopToChild = (
361 child: ChildProcessSpawner.ChildProcessHandle,
354 - duration: Duration.Duration
362 + pid: number,
363 + shutdown: ShutdownSignalShape,
364 + escalation: Ref.Ref<Option.Option<Escalation>>
365 ) =>
366 Effect.gen(function* () {
357 - const settled = yield* Deferred.make<void>();
358 - const complete = Deferred.succeed(settled, undefined);
359 - yield* Effect.forkDetach(Effect.andThen(Effect.ignore(child.exitCode), complete));
360 - yield* Effect.forkDetach(Effect.andThen(Effect.sleep(duration), complete));
361 - yield* Deferred.await(settled);
367 + const signal = yield* shutdown.requested;
368 + signalChildProcessGroup(pid, signal);
369 + const followUps: ReadonlyArray<TerminationSignal> =
370 + signal === 'SIGTERM' ? ['SIGKILL'] : ['SIGTERM', 'SIGKILL'];
371 + yield* Effect.forEach(
372 + followUps,
373 + (next, index) =>
374 + Effect.sleep(CHILD_SIGNAL_GRACE_PERIOD).pipe(
375 + Effect.andThen(child.isRunning),
376 + Effect.flatMap(running =>
377 + running
378 + ? Ref.set(
379 + escalation,
380 + Option.some({ first: signal, sent: followUps.slice(0, index + 1) })
381 + ).pipe(Effect.andThen(Effect.sync(() => signalChildProcessGroup(pid, next))))
382 + : Effect.void
383 + )
384 + ),
385 + { discard: true }
386 + );
387 });
388
389 /**
365 - * Forwards terminal signals to the running script for as long as it is alive.
390 + * Waits for the script and reports how it ended, relaying the CLI's signals to it meanwhile.
391 *
392 * A terminal Ctrl-C only reaches the CLI's process group, so without this the script never
368 - * observes SIGINT and its `process.on('SIGINT')` cleanup never runs — it is reached later and
369 - * only as the executor's SIGTERM. Handlers are registered and removed with the scope so they
370 - * never leak into a later run.
393 + * observes SIGINT and its `process.on('SIGINT')` cleanup never runs. The run cooperates on every
394 + * signal the runner handles (`ShutdownSignal`): the CLI is not interrupted, it forwards the
395 + * signal and mirrors the script's exit. When the CLI's own SIGTERM or SIGKILL ended the script,
396 + * the run ends by the first signal instead; a script that dies by any other signal (a SIGABRT in
397 + * its cleanup, say) keeps that signal, so its crash stays visible. A second signal kills the
398 + * script's process group and re-raises that signal.
399 */
372 -const forwardSignalsToChild = (child: ChildProcessSpawner.ChildProcessHandle) =>
400 +const superviseChild = (child: ChildProcessSpawner.ChildProcessHandle) =>
401 Effect.gen(function* () {
402 const os = yield* NodeOs;
375 - // Windows has no process groups and the executor does not detach there.
403 + // Windows has no process groups and the executor does not detach there: a signal interrupts
404 + // the run, and the spawner's finalizer ends the script.
405 if (os.platform === 'win32') {
377 - return;
406 + return yield* childExitStatus(child);
407 }
408
409 + const shutdown = yield* ShutdownSignal;
410 const pid = Number(child.pid);
381 - const forwarded = MutableRef.make(false);
382 -
383 - yield* Effect.acquireRelease(
384 - Effect.sync(() =>
385 - FORWARDED_SIGNALS.map(signal => {
386 - const listener = () => {
387 - if (signalChildProcessGroup(pid, signal)) {
388 - MutableRef.set(forwarded, true);
389 - }
390 - };
391 - process.on(signal, listener);
392 - return { signal, listener } as const;
393 - })
394 - ),
395 - listeners =>
396 - Effect.sync(() => {
397 - for (const { signal, listener } of listeners) {
398 - process.removeListener(signal, listener);
399 - }
400 - }).pipe(
401 - Effect.andThen(
402 - MutableRef.get(forwarded)
403 - ? awaitChildExitWithin(child, CHILD_SIGNAL_GRACE_PERIOD)
404 - : Effect.void
405 - )
406 - )
407 - );
411 + yield* shutdown.cooperate({
412 + signals: STOP_SIGNALS,
413 + onForce: () => signalChildProcessGroup(pid, 'SIGKILL'),
414 + reraiseOnForce: true,
415 + });
416 + const escalation = yield* Ref.make(Option.none<Escalation>());
417 + yield* Effect.forkScoped(relayStopToChild(child, pid, shutdown, escalation));
418 + const status = yield* childExitStatus(child);
419 + return Option.match(yield* Ref.get(escalation), {
420 + onNone: (): ChildExitStatus => status,
421 + onSome: ({ first, sent }): ChildExitStatus =>
422 + status.signal !== null && sent.includes(status.signal)
423 + ? { code: null, signal: first }
424 + : status,
425 + });
426 });
427
428 export const runCmd = Command.make('run', {
@@ -529,7 +547,7 @@ export const runCmd = Command.make('run', {
547 preloadPath: preload.preloadPath,
548 preloadDirectory: preload.directory,
549 });
532 - const exitCode = yield* Effect.gen(function* () {
550 + const status = yield* Effect.gen(function* () {
551 const [executable, ...commandArgs] = runCommand.cmd;
552 // Spawning the command (instead of running it to completion) yields the handle whose
553 // pid the signal forwarding below needs. `extendEnv` keeps the caller's environment.
@@ -544,8 +562,7 @@ export const runCmd = Command.make('run', {
562 stdout: 'inherit',
563 stderr: 'inherit',
564 });
547 - yield* forwardSignalsToChild(child);
548 - return Number(yield* child.exitCode);
565 + return yield* superviseChild(child);
566 }).pipe(
567 Effect.scoped,
568 Effect.ensuring(
@@ -561,11 +578,14 @@ export const runCmd = Command.make('run', {
578 )
579 )
580 );
564 - // The process exits with the child's code. An interrupted run (Ctrl-C) never gets here:
565 - // `Runtime.defaultTeardown` exits 130 for it, so wrappers and `set -e` scripts do not
566 - // read a cancelled run as a passing one.
567 - if (exitCode !== 0) {
568 - return yield* new ChildProcessExited({ code: exitCode });
581 + // The process ends the way the script did: with its code, or, when a signal ended it,
582 + // by the same signal (the runner re-raises it), so wrappers and `set -e` scripts read a
583 + // cancelled run as cancelled.
584 + if (status.signal !== null) {
585 + return yield* new ChildProcessSignaled({ signal: status.signal });
586 + }
587 + if (status.code !== 0) {
588 + return yield* new ChildProcessExited({ code: status.code });
589 }
590 }).pipe(Effect.scoped)
591 )
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+16 -9
@@ -9,6 +9,7 @@ import { APP_CONFIG } from 'src/config';
9 import { CommandSurface, resolveSurfaceProject } from 'src/commands/surface';
10 import { TerminalUI } from 'src/services/terminal-ui';
11 import { TriggersRealtime } from 'src/services/triggers-realtime';
12 +import { LISTENER_STOP, ShutdownSignal } from 'src/services/shutdown-signal';
13 import { matchesTriggerListenFilters } from '../filter';
14 import {
15 formatTriggerListenSummary,
@@ -181,6 +182,7 @@ export const triggersCmd$Listen = Command.make(
182 const fs = yield* FileSystem.FileSystem;
183 const path = yield* Path.Path;
184 const realtime = yield* TriggersRealtime;
185 + const shutdown = yield* ShutdownSignal;
186 const forwardUrl = Option.getOrUndefined(forward);
187 const generatedWebhookSecret = `composio-forward-secret-${randomUUID()}`;
188 const configuredWebhookSecret = yield* APP_CONFIG.WEBHOOK_SECRET;
@@ -346,14 +348,17 @@ export const triggersCmd$Listen = Command.make(
348 );
349 };
350
351 + // From the subscription on, Ctrl-C and SIGTERM stop the listener instead of interrupting it.
352 + const listenOptions = { onSubscribed: shutdown.cooperate(LISTENER_STOP) };
353 // The default credentials serve the configured project; a named one needs its own.
354 const listenEffect = (runEvent: RunEvent) =>
355 (Option.isSome(surface.projectName)
356 ? realtime.listenInProject(
357 { orgId: project.orgId, projectId: project.projectId },
354 - onEvent(runEvent)
358 + onEvent(runEvent),
359 + listenOptions
360 )
356 - : realtime.listen(onEvent(runEvent))
361 + : realtime.listen(onEvent(runEvent), listenOptions)
362 ).pipe(
363 Effect.onInterrupt(() => ui.log.info('Stopped listening for realtime trigger events.'))
364 );
@@ -364,20 +369,22 @@ export const triggersCmd$Listen = Command.make(
369 const events = yield* FiberSet.make();
370 const runEvent = yield* FiberSet.runtime(events)();
371 // Without --max-events or --fail-fast nothing resolves stopWhenDone, so this waits on
367 - // the listener until it is interrupted.
368 - const stopReason = yield* Effect.raceFirst(
372 + // the listener until Ctrl-C or SIGTERM stops it or another signal interrupts it.
373 + const stopReason = yield* Effect.raceAllFirst([
374 listenEffect(runEvent),
370 - Deferred.await(stopWhenDone)
371 - );
375 + Deferred.await(stopWhenDone),
376 + shutdown.requested,
377 + ]);
378 if (stopReason === 'max-events') {
379 yield* finishAcceptedEvents(events, failed);
380 yield* ui.outro(`Stopped after receiving ${matchingEvents} matching events.`);
381 }
382 }).pipe(
383 Effect.scoped,
378 - // An onExit finalizer, so the summaries print on every stop — including the
379 - // interruption by Ctrl+C or SIGTERM, where the code after this block would not run. With
380 - // --fail-fast a summary fails the command, so the second one still prints after it.
384 + // An onExit finalizer, so the summaries print on every stop — including an
385 + // interruption (a signal before the subscription, or SIGHUP), where the code after this
386 + // block would not run. With --fail-fast a summary fails the command, so the second one
387 + // still prints after it.
388 Effect.onExit(() =>
389 Effect.gen(function* () {
390 const forwarded = yield* Effect.exit(forwardFailures.report);
ts/packages/cli/src/effects/child-exit-status.ts new
+39
@@ -0,0 +1,39 @@
1 +import { Effect, Option, type PlatformError } from 'effect';
2 +import type { ChildProcessSpawner } from 'effect/process';
3 +import { isTerminationSignal, type TerminationSignal } from 'src/services/shutdown-signal';
4 +
5 +/** How a child process ended: with an exit code, or killed by a signal. */
6 +export type ChildExitStatus =
7 + | { readonly code: number; readonly signal: null }
8 + | { readonly code: null; readonly signal: TerminationSignal };
9 +
10 +/**
11 + * The cause message `@effect/platform-node-shared`'s spawner fails `exitCode` with when a signal
12 + * ended the child. The spawner has Node's `(code, signal)` pair but keeps only this message.
13 + */
14 +const SIGNAL_DEATH = /^Process interrupted due to receipt of signal: '([A-Z0-9]+)'$/u;
15 +
16 +const signalOf = (error: PlatformError.PlatformError): Option.Option<TerminationSignal> =>
17 + error.reason.method === 'exitCode' && error.reason.cause instanceof Error
18 + ? Option.fromNullishOr(SIGNAL_DEATH.exec(error.reason.cause.message)?.[1]).pipe(
19 + Option.filter(isTerminationSignal)
20 + )
21 + : Option.none();
22 +
23 +/**
24 + * Waits for `child` and reports its `{ code, signal }`, which `handle.exitCode` drops for a child
25 + * a signal ended (it fails instead). A signal outside `TerminationSignal`, or any other failure,
26 + * stays the spawner's `PlatformError`.
27 + */
28 +export const childExitStatus = (
29 + child: ChildProcessSpawner.ChildProcessHandle
30 +): Effect.Effect<ChildExitStatus, PlatformError.PlatformError> =>
31 + child.exitCode.pipe(
32 + Effect.map((code): ChildExitStatus => ({ code: Number(code), signal: null })),
33 + Effect.catchTag('PlatformError', error =>
34 + Option.match(signalOf(error), {
35 + onNone: () => Effect.fail(error),
36 + onSome: signal => Effect.succeed<ChildExitStatus>({ code: null, signal }),
37 + })
38 + )
39 + );
ts/packages/cli/src/effects/child-process-exited.ts
+20 -2
@@ -1,9 +1,10 @@
1 import { Data, Runtime } from 'effect';
2 +import { signalExitCode, type TerminationSignal } from 'src/services/shutdown-signal';
3
4 /**
5 * A child process the command proxies (`composio run`) exited with a non-zero `code`. The child
5 - * already wrote its own output, so `BunRuntime.runMain` logs nothing (`[Runtime.errorReported]`
6 - * is false) and `Runtime.defaultTeardown` exits with the child's code.
6 + * already wrote its own output, so the runner logs nothing (`[Runtime.errorReported]` is false)
7 + * and `Runtime.defaultTeardown` exits with the child's code.
8 */
9 export class ChildProcessExited extends Data.TaggedError('effects/ChildProcessExited')<{
10 readonly code: number;
@@ -16,3 +17,20 @@ export class ChildProcessExited extends Data.TaggedError('effects/ChildProcessEx
17 return this.code;
18 }
19 }
20 +
21 +/**
22 + * A child process the command proxies (`composio run`) was ended by `signal`. The runner
23 + * (`src/run-main.ts`) re-raises the signal so the CLI ends the same way; the exit code, 128 + n,
24 + * is what a caller sees if the re-raise cannot end the process.
25 + */
26 +export class ChildProcessSignaled extends Data.TaggedError('effects/ChildProcessSignaled')<{
27 + readonly signal: TerminationSignal;
28 +}> {
29 + get [Runtime.errorReported]() {
30 + return false;
31 + }
32 +
33 + get [Runtime.errorExitCode]() {
34 + return signalExitCode(this.signal);
35 + }
36 +}
ts/packages/cli/src/run-main.ts new
+158
@@ -0,0 +1,158 @@
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 + });
ts/packages/cli/src/services/shutdown-signal.ts new
+131
@@ -0,0 +1,131 @@
1 +import { Context, Deferred, Effect, Layer, Schema, type Scope } from 'effect';
2 +
3 +/**
4 + * Signals whose numbers agree on Linux and macOS, so `128 + n` is the code a shell reports for
5 + * a process they end. Others (`SIGUSR1`, `SIGBUS`, …) differ between platforms.
6 + */
7 +const SIGNAL_NUMBERS = {
8 + SIGHUP: 1,
9 + SIGINT: 2,
10 + SIGQUIT: 3,
11 + SIGILL: 4,
12 + SIGTRAP: 5,
13 + SIGABRT: 6,
14 + SIGFPE: 8,
15 + SIGKILL: 9,
16 + SIGSEGV: 11,
17 + SIGPIPE: 13,
18 + SIGALRM: 14,
19 + SIGTERM: 15,
20 +} as const;
21 +
22 +/** A signal that can end a process, with the same number on every platform the CLI ships for. */
23 +export type TerminationSignal = keyof typeof SIGNAL_NUMBERS;
24 +
25 +export const isTerminationSignal = Schema.is(
26 + Schema.Literals([
27 + 'SIGHUP',
28 + 'SIGINT',
29 + 'SIGQUIT',
30 + 'SIGILL',
31 + 'SIGTRAP',
32 + 'SIGABRT',
33 + 'SIGFPE',
34 + 'SIGKILL',
35 + 'SIGSEGV',
36 + 'SIGPIPE',
37 + 'SIGALRM',
38 + 'SIGTERM',
39 + ] satisfies ReadonlyArray<TerminationSignal>)
40 +);
41 +
42 +/** The code a shell reports for a process `signal` ended: 130 for SIGINT, 143 for SIGTERM. */
43 +export const signalExitCode = (signal: TerminationSignal): number => 128 + SIGNAL_NUMBERS[signal];
44 +
45 +/** The signals the CLI's runner handles: Ctrl-C, a polite stop, and a closed terminal. */
46 +export const STOP_SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const;
47 +
48 +export type StopSignal = (typeof STOP_SIGNALS)[number];
49 +
50 +/** How a command stops by itself when the CLI receives a signal, instead of being interrupted. */
51 +export interface CooperativeStop {
52 + /** The signals the command handles. Any other signal interrupts it. */
53 + readonly signals: ReadonlyArray<StopSignal>;
54 + /**
55 + * Runs synchronously when a second signal, or the shutdown deadline, forces the CLI to exit
56 + * before the command finished stopping: the last chance to kill what the command started.
57 + */
58 + readonly onForce?: () => void;
59 + /** Ends a forced exit by re-raising the signal (`composio run`) rather than exiting 128 + n. */
60 + readonly reraiseOnForce?: boolean;
61 +}
62 +
63 +export interface ShutdownSignalShape {
64 + /**
65 + * Handles `stop.signals` cooperatively for the life of the current scope: the first such
66 + * signal completes `requested` instead of interrupting the command. Register right after the
67 + * command acquired what it has to release; a signal before that still interrupts it.
68 + */
69 + readonly cooperate: (stop: CooperativeStop) => Effect.Effect<void, never, Scope.Scope>;
70 + /** Completes with the first signal a cooperative command took. */
71 + readonly requested: Effect.Effect<StopSignal>;
72 +}
73 +
74 +/**
75 + * The signal the CLI process received, for the one invocation that runs in it. The runner
76 + * (`src/run-main.ts`) owns the process signal handlers and hands the signal to a command that
77 + * cooperates; every other command is interrupted.
78 + */
79 +export class ShutdownSignal extends Context.Service<ShutdownSignal, ShutdownSignalShape>()(
80 + 'services/ShutdownSignal'
81 +) {
82 + /** A service no runner signals: for tests and invocations without process signals. */
83 + static readonly Default: Layer.Layer<ShutdownSignal> = Layer.sync(
84 + ShutdownSignal,
85 + () => makeShutdownController().service
86 + );
87 +}
88 +
89 +/**
90 + * How a listener (`composio listen`, `dev triggers listen`) stops: Ctrl-C and SIGTERM are the
91 + * documented way to end it, so it stops cleanly and exits 0. A closed terminal (SIGHUP) still
92 + * interrupts it and exits 129.
93 + */
94 +export const LISTENER_STOP: CooperativeStop = { signals: ['SIGINT', 'SIGTERM'] };
95 +
96 +/** The runner's side of {@link ShutdownSignal}. */
97 +export interface ShutdownController {
98 + readonly service: ShutdownSignalShape;
99 + /** Gives `signal` to a command that cooperates on it; `false` when the runner must interrupt. */
100 + readonly offer: (signal: StopSignal) => boolean;
101 + /** Runs every cooperating command's `onForce`; says whether the forced exit re-raises. */
102 + readonly force: () => { readonly reraise: boolean };
103 +}
104 +
105 +export const makeShutdownController = (): ShutdownController => {
106 + const requested = Deferred.makeUnsafe<StopSignal>();
107 + const active = new Set<CooperativeStop>();
108 + return {
109 + service: ShutdownSignal.of({
110 + cooperate: stop =>
111 + Effect.acquireRelease(
112 + // A fresh entry per registration, so registering one value twice is two registrations.
113 + Effect.sync(() => {
114 + const entry = { ...stop };
115 + active.add(entry);
116 + return entry;
117 + }),
118 + entry => Effect.sync(() => active.delete(entry))
119 + ),
120 + requested: Deferred.await(requested),
121 + }),
122 + offer: signal =>
123 + [...active].some(stop => stop.signals.includes(signal)) &&
124 + Deferred.doneUnsafe(requested, Effect.succeed(signal)),
125 + force: () => {
126 + const stops = [...active];
127 + stops.forEach(stop => stop.onForce?.());
128 + return { reraise: stops.some(stop => stop.reraiseOnForce === true) };
129 + },
130 + };
131 +};
ts/packages/cli/src/services/triggers-realtime.ts
+38 -3
@@ -1,6 +1,7 @@
1 import {
2 Array as Arr,
3 Data,
4 + Deferred,
5 Effect,
6 Result,
7 Option,
@@ -8,6 +9,7 @@ import {
9 Schema,
10 Context,
11 Layer,
12 + type Scope,
13 } from 'effect';
14 import { JsonRecordSchema } from 'src/effects/json';
15 import type {
@@ -36,6 +38,15 @@ export class TriggerRealtimeSubscriptionError extends Data.TaggedError(
38 readonly cause?: unknown;
39 }> {}
40
41 +export interface ListenOptions {
42 + /**
43 + * Runs once Pusher confirmed the subscription (`pusher:subscription_succeeded`), in a scope
44 + * that stays open while it does: the place to register for a cooperative stop
45 + * (`ShutdownSignal.cooperate`).
46 + */
47 + readonly onSubscribed?: Effect.Effect<void, never, Scope.Scope>;
48 +}
49 +
50 const subscriptionError = (message: string) => (cause: unknown) =>
51 new TriggerRealtimeSubscriptionError({ message, cause });
52
@@ -101,6 +112,7 @@ const makeTriggersRealtime = Effect.gen(function* () {
112 socket_id: string;
113 }) => Effect.Effect<CliRealtimeAuthResponse, TriggerRealtimeSubscriptionError>;
114 onEvent: (data: RawRealtimeEvent) => void;
115 + options?: ListenOptions;
116 }) =>
117 Effect.acquireUseRelease(
118 Effect.gen(function* () {
@@ -154,6 +166,20 @@ const makeTriggersRealtime = Effect.gen(function* () {
166
167 const channel = pusher.subscribe(channelName);
168
169 + // Pusher confirms or rejects the subscription later, once the socket is connected and the
170 + // channel is authorized. pusher-js does not catch listener exceptions, so these callbacks
171 + // only complete the Deferred and never throw.
172 + const subscribed = Deferred.makeUnsafe<void, TriggerRealtimeSubscriptionError>();
173 + channel.bind('pusher:subscription_succeeded', () => {
174 + Deferred.doneUnsafe(subscribed, Effect.void);
175 + });
176 + channel.bind('pusher:subscription_error', (status: unknown) => {
177 + Deferred.doneUnsafe(
178 + subscribed,
179 + Effect.fail(subscriptionError('Failed to subscribe to realtime trigger events')(status))
180 + );
181 + });
182 +
183 // Pusher has a 10 KB per-message limit. When the Composio backend
184 // produces a trigger payload that exceeds this, it splits the JSON
185 // into numbered chunks sent as separate `chunked-trigger_to_client`
@@ -256,6 +282,7 @@ const makeTriggersRealtime = Effect.gen(function* () {
282 });
283
284 return {
285 + subscribed: Deferred.await(subscribed),
286 shutdown: async () => {
287 clearInterval(cleanupInterval);
288 channel.unbind_all?.();
@@ -264,7 +291,12 @@ const makeTriggersRealtime = Effect.gen(function* () {
291 },
292 };
293 }),
267 - () => Effect.never,
294 + resource =>
295 + resource.subscribed.pipe(
296 + Effect.andThen(params.options?.onSubscribed ?? Effect.void),
297 + Effect.andThen(Effect.never),
298 + Effect.scoped
299 + ),
300 resource =>
301 Effect.tryPromise({
302 try: () => resource.shutdown(),
@@ -272,7 +304,7 @@ const makeTriggersRealtime = Effect.gen(function* () {
304 }).pipe(Effect.catch(() => Effect.void))
305 );
306
275 - const listen = (onEvent: (data: RawRealtimeEvent) => void) =>
307 + const listen = (onEvent: (data: RawRealtimeEvent) => void, options?: ListenOptions) =>
308 listenWith({
309 getRealtimeCredentials: () =>
310 sessionRepo
@@ -283,11 +315,13 @@ const makeTriggersRealtime = Effect.gen(function* () {
315 .authRealtimeChannel(params)
316 .pipe(Effect.mapError(subscriptionError('Failed to authorize the realtime channel'))),
317 onEvent,
318 + options,
319 });
320
321 const listenInProject = (
322 scope: { orgId: string; projectId: string },
290 - onEvent: (data: RawRealtimeEvent) => void
323 + onEvent: (data: RawRealtimeEvent) => void,
324 + options?: ListenOptions
325 ) =>
326 Effect.gen(function* () {
327 const client = yield* clientSingleton.getFor({
@@ -305,6 +339,7 @@ const makeTriggersRealtime = Effect.gen(function* () {
339 .auth(params, idempotent)
340 .pipe(Effect.mapError(subscriptionError('Failed to authorize the realtime channel'))),
341 onEvent,
342 + options,
343 });
344 });
345
ts/packages/cli/test/__utils__/services/test-layer.ts
+9 -4
@@ -50,6 +50,7 @@ import { CliUserConfig } from 'src/models/cli-user-config';
50 import { UpgradeBinary } from 'src/services/upgrade-binary';
51 import { NodeOs } from 'src/services/node-os';
52 import { TriggersRealtime } from 'src/services/triggers-realtime';
53 +import { ShutdownSignal } from 'src/services/shutdown-signal';
54 import { ToolsExecutor, ToolsExecutorLive } from 'src/services/tools-executor';
55 import { DashboardToolExecutionTest, type DashboardTestResponder } from '../layers/dashboard';
56 import { ToolkitSlugCatalog } from 'src/services/toolkit-slug-catalog';
@@ -392,16 +393,18 @@ export const TestLayer = (input?: TestLiveInput) =>
393 const TriggersRealtimeTest = Layer.succeed(
394 TriggersRealtime,
395 TriggersRealtime.of({
395 - listen: onEvent =>
396 + listen: (onEvent, options) =>
397 Effect.gen(function* () {
398 + yield* options?.onSubscribed ?? Effect.void;
399 yield* Effect.forEach(realtimeData.events, event => Effect.sync(() => onEvent(event)));
400 return yield* Effect.never;
399 - }),
400 - listenInProject: (_scope, onEvent) =>
401 + }).pipe(Effect.scoped),
402 + listenInProject: (_scope, onEvent, options) =>
403 Effect.gen(function* () {
404 + yield* options?.onSubscribed ?? Effect.void;
405 yield* Effect.forEach(realtimeData.events, event => Effect.sync(() => onEvent(event)));
406 return yield* Effect.never;
404 - }),
407 + }).pipe(Effect.scoped),
408 })
409 );
410
@@ -893,6 +896,8 @@ export const TestLayer = (input?: TestLiveInput) =>
896 ComposioClientSingletonTest,
897 ComposioSessionRepositoryTest,
898 TriggersRealtimeTest,
899 + // No runner signals tests; a suite that needs one provides its own controller's service.
900 + ShutdownSignal.Default,
901 ComposioToolkitsRepositoryTest,
902 ToolkitSlugCatalogTest,
903 JsPackageManagerDetector.Default,
ts/packages/cli/test/src/cli-main.test.ts
+63
@@ -922,3 +922,66 @@ describe('local file uploads', () => {
922 });
923 }, 30_000);
924 });
925 +
926 +describe('signals', () => {
927 + /**
928 + * Runs `composio orgs list` against a backend that never answers, sends `signal` once the
929 + * request arrives, and reports how the process ended.
930 + */
931 + const signalBlockedCommand = async (signal: NodeJS.Signals) => {
932 + let child: ReturnType<typeof spawn> | undefined;
933 + let ended: { code: number | null; signal: NodeJS.Signals | null } | undefined;
934 + // Holds every request open: the command blocks until the signal ends it.
935 + await withHttpServer(
936 + () => child?.kill(signal),
937 + async baseUrl => {
938 + const configDirectory = tempy.temporaryDirectory();
939 + fs.writeFileSync(
940 + path.join(configDirectory, 'user_data.json'),
941 + JSON.stringify({ api_key: 'uak_test', base_url: baseUrl, web_url: baseUrl, org_id: null })
942 + );
943 + const {
944 + COMPOSIO_USER_API_KEY: _apiKey,
945 + COMPOSIO_ENVIRONMENT: _environment,
946 + ...host
947 + } = process.env;
948 + const spawned = spawn('bun', ['run', 'src/bin.ts', 'orgs', 'list'], {
949 + cwd: process.cwd(),
950 + env: {
951 + ...host,
952 + CI: '1',
953 + NO_COLOR: '1',
954 + COMPOSIO_CACHE_DIR: configDirectory,
955 + COMPOSIO_BASE_URL: baseUrl,
956 + COMPOSIO_CLI_TELEMETRY_DISABLED: '1',
957 + },
958 + stdio: 'ignore',
959 + });
960 + child = spawned;
961 + ended = await new Promise((resolve, reject) => {
962 + const deadline = setTimeout(() => {
963 + spawned.kill('SIGKILL');
964 + reject(new Error(`CLI did not exit within ${CLI_DEADLINE_MS}ms after ${signal}`));
965 + }, CLI_DEADLINE_MS);
966 + spawned.once('close', (code, endSignal) => {
967 + clearTimeout(deadline);
968 + resolve({ code, signal: endSignal });
969 + });
970 + });
971 + }
972 + );
973 + return ended;
974 + };
975 +
976 + it.each([
977 + { signal: 'SIGINT', code: 130 },
978 + { signal: 'SIGTERM', code: 143 },
979 + { signal: 'SIGHUP', code: 129 },
980 + ] as const)(
981 + '[Given] a one-shot command waiting on the backend [When] it receives $signal [Then] it exits $code',
982 + async ({ signal, code }) => {
983 + expect(await signalBlockedCommand(signal)).toEqual({ code, signal: null });
984 + },
985 + 30_000
986 + );
987 +});
ts/packages/cli/test/src/commands/listen.cmd.test.ts
+71 -4
@@ -9,6 +9,11 @@ import { MissingActingUserError } from 'src/commands/surface';
9 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
10 import { ComposioUserContext } from 'src/services/user-context';
11 import { TriggerRealtimeSubscriptionError, TriggersRealtime } from 'src/services/triggers-realtime';
12 +import {
13 + makeShutdownController,
14 + ShutdownSignal,
15 + type ShutdownController,
16 +} from 'src/services/shutdown-signal';
17 import { cli, MockConsole, TestLive } from 'test/__utils__';
18 import { exitCodeOf } from 'test/__utils__/exit-code';
19 import { failingFileWrites } from 'test/__utils__/services/failing-file-writes';
@@ -61,6 +66,35 @@ describe('CLI: composio listen', () => {
66 expect(exitCodeOf(exit)).toBe(1);
67 })
68 );
69 +
70 + // Still connecting: a signal now interrupts the listener, so the CLI exits 130/143.
71 + it.effect(
72 + '[When] a signal arrives before the subscription exists [Then] it is not taken',
73 + () =>
74 + Effect.gen(function* () {
75 + yield* enableListen;
76 + const shutdown = makeShutdownController();
77 + const connecting = Latch.makeUnsafe(false);
78 + const neverSubscribes = Layer.succeed(
79 + TriggersRealtime,
80 + TriggersRealtime.of({
81 + listen: () => Effect.never,
82 + listenInProject: () => Effect.andThen(connecting.open, Effect.never),
83 + })
84 + );
85 + const fiber = yield* Effect.forkChild(
86 + cli(['listen', 'composio.connected_account.expired']).pipe(
87 + Effect.provide(Layer.merge(neverSubscribes, redirectedTerminalUI().layer)),
88 + Effect.provideService(ShutdownSignal, shutdown.service)
89 + )
90 + );
91 + yield* connecting.await;
92 +
93 + expect(shutdown.offer('SIGINT')).toBe(false);
94 + yield* Fiber.interrupt(fiber);
95 + expect(exitCodeOf(yield* Fiber.await(fiber))).toBe(130);
96 + })
97 + );
98 }
99 );
100
@@ -169,7 +203,10 @@ describe('CLI: composio listen', () => {
203
204 // The write failure logs its warn only after it was counted, so the latch is an ordered
205 // count-is-set signal — no polling, no sleeps.
172 - const listenUntilWriteFails = (args: ReadonlyArray<string>) =>
206 + const listenUntilWriteFails = (
207 + args: ReadonlyArray<string>,
208 + shutdown: ShutdownController = makeShutdownController()
209 + ) =>
210 Effect.gen(function* () {
211 const writeFailed = Latch.makeUnsafe(false);
212 const terminal = redirectedTerminalUI({
@@ -179,7 +216,8 @@ describe('CLI: composio listen', () => {
216 });
217 const fiber = yield* Effect.forkChild(
218 cli(['listen', 'composio.connected_account.expired', ...args]).pipe(
182 - Effect.provide(Layer.merge(payloadWritesFail, terminal.layer))
219 + Effect.provide(Layer.merge(payloadWritesFail, terminal.layer)),
220 + Effect.provideService(ShutdownSignal, shutdown.service)
221 )
222 );
223 yield* writeFailed.await;
@@ -227,8 +265,37 @@ describe('CLI: composio listen', () => {
265 })
266 );
267
230 - // Ctrl+C/SIGTERM: runMain interrupts the listener fiber; the release hook must run the
231 - // summary anyway.
268 + // Ctrl+C or SIGTERM once subscribed: the listener stops itself, runs its release, succeeds.
269 + it.effect.each(['SIGINT', 'SIGTERM'] as const)(
270 + '[When] %s arrives after the subscription [Then] it stops cleanly, sums up, and exits 0',
271 + signal =>
272 + Effect.gen(function* () {
273 + yield* enableListen;
274 + const shutdown = makeShutdownController();
275 + const { fiber, terminal } = yield* listenUntilWriteFails([], shutdown);
276 +
277 + expect(shutdown.offer(signal)).toBe(true);
278 + const exit = yield* Fiber.await(fiber);
279 +
280 + expect(terminal.stderr()).toContain('1 event failed to write while listening.');
281 + expect(exitCodeOf(exit)).toBe(0);
282 + })
283 + );
284 +
285 + // A closed terminal is not a stop the listener handles: the runner interrupts it (129).
286 + it.effect('[When] SIGHUP arrives [Then] the listener does not take it', () =>
287 + Effect.gen(function* () {
288 + yield* enableListen;
289 + const shutdown = makeShutdownController();
290 + const { fiber } = yield* listenUntilWriteFails([], shutdown);
291 +
292 + expect(shutdown.offer('SIGHUP')).toBe(false);
293 + yield* Fiber.interrupt(fiber);
294 + })
295 + );
296 +
297 + // A signal the listener does not take (before the subscription, or SIGHUP): the runner
298 + // interrupts the listener fiber; the release hook must run the summary anyway.
299 it.effect('[Then] sums the write failures up even when the listener is interrupted', () =>
300 Effect.gen(function* () {
301 yield* enableListen;
ts/packages/cli/test/src/commands/run.cmd.test.ts
+206 -41
@@ -7,9 +7,23 @@ import { describe, expect, layer } from '@effect/vitest';
7 import { assertDefined } from '@effect/vitest/utils';
8 import * as BunServices from '@effect/platform-bun/BunServices';
9 import * as Path from 'effect/Path';
10 -import { ConfigProvider, Deferred, Effect, Fiber, Layer, Runtime, Sink, Stream } from 'effect';
10 +import {
11 + Cause,
12 + ConfigProvider,
13 + Deferred,
14 + Effect,
15 + Exit,
16 + Fiber,
17 + Layer,
18 + Option,
19 + PlatformError,
20 + Runtime,
21 + Sink,
22 + Stream,
23 +} from 'effect';
24 +import { TestClock } from 'effect/testing';
25 import { ChildProcess, ChildProcessSpawner } from 'effect/process';
12 -import { afterEach, it, vi } from 'vitest';
26 +import { afterEach, beforeEach, it, vi } from 'vitest';
27 import { createCliCommandTelemetryContext } from 'src/analytics/events';
28 import { buildRunHelpersSource, inferCliInvocationPrefix } from 'src/commands/run.cmd';
29 import {
@@ -28,7 +42,14 @@ import { DEFAULT_CLI_INVOCATION_ORIGIN } from 'src/services/runtime-cli-context'
42 import { cli, MockConsole, TestLive } from 'test/__utils__';
43 import { exitCodeOf } from 'test/__utils__/exit-code';
44 import { CommandRunner } from 'src/services/command-runner';
31 -import { ChildProcessExited } from 'src/effects/child-process-exited';
45 +import { ChildProcessExited, ChildProcessSignaled } from 'src/effects/child-process-exited';
46 +import { ExitAction, exitActionFor } from 'src/run-main';
47 +import {
48 + makeShutdownController,
49 + ShutdownSignal,
50 + type ShutdownController,
51 + type TerminationSignal,
52 +} from 'src/services/shutdown-signal';
53
54 const enabledRuntimeFlagsConfigProvider = ConfigProvider.fromEnvRecord({
55 COMPOSIO_RUN_ACP_ONLY: '1',
@@ -54,9 +75,14 @@ const tempScript = Effect.acquireRelease(
75 const SCRIPT = 'console.log("hi")';
76 const SCRIPT_FLAGS = ['--perf-debug', '--tool-debug', '--telemetry-debug', '--help', '--version'];
77
57 -const commandRuns = vi.fn((_: ChildProcess.Command) =>
58 - Effect.succeed(ChildProcessSpawner.ExitCode(0))
78 +const commandRuns = vi.fn(
79 + (
80 + _: ChildProcess.Command
81 + ): Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError> =>
82 + Effect.succeed(ChildProcessSpawner.ExitCode(0))
83 );
84 +/** Whether the stub child is still running, which the escalation after a signal checks. */
85 +const childRunning = vi.fn(() => false);
86
87 // `composio run` starts the child through the platform `ChildProcessSpawner` so it owns the
88 // pid it forwards signals to, so the stub has to replace the spawner rather than
@@ -68,7 +94,7 @@ const stubHandle = (command: ChildProcess.Command): ChildProcessSpawner.ChildPro
94 ChildProcessSpawner.makeHandle({
95 pid: ChildProcessSpawner.ProcessId(STUB_CHILD_PID),
96 exitCode: Effect.suspend(() => commandRuns(command)),
71 - isRunning: Effect.succeed(false),
97 + isRunning: Effect.sync(() => childRunning()),
98 kill: () => Effect.void,
99 stdin: Sink.drain,
100 stdout: Stream.empty,
@@ -114,6 +140,7 @@ describe('CLI: composio run', () => {
140 commandRuns
141 .mockReset()
142 .mockImplementation(() => Effect.succeed(ChildProcessSpawner.ExitCode(0)));
143 + childRunning.mockReset().mockImplementation(() => false);
144 vi.unstubAllGlobals();
145 vi.restoreAllMocks();
146 });
@@ -144,46 +171,184 @@ describe('CLI: composio run', () => {
171 );
172 });
173
147 - layer(RunTestLive())(it => {
148 - it.effect(
149 - '[Given] a terminal interrupt [Then] it forwards the signal to the child process group and unregisters its handlers',
150 - () =>
174 + describe('signals', () => {
175 + // The runner's controller for this run: the test delivers the CLI's signals through it.
176 + let controller: ShutdownController = makeShutdownController();
177 + const signalled: Array<readonly [number, string]> = [];
178 + // Completes once `process.kill` received each signal, so a test can wait for delivery.
179 + let delivered = new Map<string, Deferred.Deferred<void>>();
180 + const deliveryOf = (signal: string) => {
181 + const deferred = delivered.get(signal) ?? Deferred.makeUnsafe<void>();
182 + delivered.set(signal, deferred);
183 + return deferred;
184 + };
185 +
186 + beforeEach(() => {
187 + controller = makeShutdownController();
188 + signalled.length = 0;
189 + delivered = new Map();
190 + vi.spyOn(process, 'kill').mockImplementation((pid, signal) => {
191 + signalled.push([Number(pid), String(signal)]);
192 + Deferred.doneUnsafe(deliveryOf(String(signal)), Effect.void);
193 + return true;
194 + });
195 + });
196 +
197 + /** `composio run` with the CLI receiving `signal` while the child runs. */
198 + const runWithSignals = Effect.suspend(() =>
199 + Effect.exit(
200 + cli(['run', 'console.log("hi")']).pipe(
201 + Effect.provideService(ShutdownSignal, controller.service)
202 + )
203 + )
204 + );
205 +
206 + /** A child that, once the CLI took `signal`, waits for it and then ends with `ends`. */
207 + const childEndingAfter = (
208 + signal: 'SIGINT' | 'SIGTERM' | 'SIGHUP',
209 + ends: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>
210 + ) =>
211 + commandRuns.mockImplementation(() =>
212 + Effect.sync(() => expect(controller.offer(signal)).toBe(true)).pipe(
213 + Effect.andThen(Deferred.await(deliveryOf(signal))),
214 + Effect.andThen(ends)
215 + )
216 + );
217 +
218 + /** The spawner's failure for a child a signal ended. */
219 + const killedBy = (signal: TerminationSignal) =>
220 + Effect.fail(
221 + PlatformError.systemError({
222 + _tag: 'Unknown',
223 + module: 'ChildProcess',
224 + method: 'exitCode',
225 + cause: new Error(`Process interrupted due to receipt of signal: '${signal}'`),
226 + })
227 + );
228 +
229 + layer(RunTestLive())(it => {
230 + it.effect.each(['SIGINT', 'SIGTERM', 'SIGHUP'] as const)(
231 + '[Given] the CLI receives %s [Then] it forwards it to the child process group',
232 + signal =>
233 + Effect.gen(function* () {
234 + childEndingAfter(signal, Effect.succeed(ChildProcessSpawner.ExitCode(0)));
235 +
236 + const exit = yield* runWithSignals;
237 +
238 + // Negative pid: the detached child leads its own process group.
239 + expect(signalled).toEqual([[-STUB_CHILD_PID, signal]]);
240 + // A script that handles the signal and exits 0 makes the run succeed.
241 + expect(exitCodeOf(exit)).toBe(0);
242 + })
243 + );
244 +
245 + it.effect(
246 + '[Given] the child exits non-zero after the signal [Then] the run mirrors its code',
247 + () =>
248 + Effect.gen(function* () {
249 + childEndingAfter('SIGINT', Effect.succeed(ChildProcessSpawner.ExitCode(7)));
250 +
251 + const exit = yield* runWithSignals;
252 +
253 + expect(exitCodeOf(exit)).toBe(7);
254 + })
255 + );
256 +
257 + it.effect('[Given] the signal ends the child [Then] the runner re-raises that signal', () =>
258 Effect.gen(function* () {
152 - const signalled: Array<readonly [number, string]> = [];
153 - vi.spyOn(process, 'kill').mockImplementation((pid, signal) => {
154 - signalled.push([Number(pid), String(signal)]);
155 - return true;
156 - });
259 + childEndingAfter('SIGTERM', killedBy('SIGTERM'));
260
158 - const sigintBaseline = process.listenerCount('SIGINT');
159 - const sigtermBaseline = process.listenerCount('SIGTERM');
160 - const registeredWhileRunning: Array<{ sigint: number; sigterm: number }> = [];
161 -
162 - commandRuns.mockImplementation(() =>
163 - Effect.sync(() => {
164 - registeredWhileRunning.push({
165 - sigint: process.listenerCount('SIGINT') - sigintBaseline,
166 - sigterm: process.listenerCount('SIGTERM') - sigtermBaseline,
167 - });
168 - // Stand in for the terminal delivering Ctrl-C to the CLI only: the child is
169 - // detached into its own process group and never sees it directly.
170 - process
171 - .listeners('SIGINT')
172 - .slice(sigintBaseline)
173 - .forEach(listener => listener('SIGINT'));
174 - return ChildProcessSpawner.ExitCode(0);
175 - })
261 + const exit = yield* runWithSignals;
262 + const failure = Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
263 +
264 + expect(failure).toBeInstanceOf(ChildProcessSignaled);
265 + expect(Runtime.getErrorReported(failure)).toBe(false);
266 + expect(exitActionFor(exit, Option.some('SIGTERM'))).toEqual(
267 + ExitAction.Reraise({ signal: 'SIGTERM' })
268 );
269 + })
270 + );
271
178 - yield* cli(['run', 'console.log("hi")']);
272 + it.effect(
273 + '[Given] a child that ignores the signal [Then] it gets SIGTERM, then SIGKILL, and the run ends by the first signal',
274 + () =>
275 + Effect.gen(function* () {
276 + childRunning.mockImplementation(() => true);
277 + const killed = deliveryOf('SIGKILL');
278 + childEndingAfter(
279 + 'SIGINT',
280 + Deferred.await(killed).pipe(Effect.andThen(killedBy('SIGKILL')))
281 + );
282
180 - expect(registeredWhileRunning[0]).toEqual({ sigint: 1, sigterm: 1 });
181 - // Negative pid: the detached child leads its own process group.
182 - expect(signalled).toEqual([[-STUB_CHILD_PID, 'SIGINT']]);
183 - expect(process.listenerCount('SIGINT')).toBe(sigintBaseline);
184 - expect(process.listenerCount('SIGTERM')).toBe(sigtermBaseline);
185 - })
186 - );
283 + const fiber = yield* Effect.forkChild(runWithSignals);
284 + yield* Deferred.await(deliveryOf('SIGINT'));
285 + yield* TestClock.adjust('2 seconds');
286 + yield* Deferred.await(deliveryOf('SIGTERM'));
287 + yield* TestClock.adjust('2 seconds');
288 + const exit = yield* Fiber.join(fiber);
289 +
290 + expect(signalled).toEqual([
291 + [-STUB_CHILD_PID, 'SIGINT'],
292 + [-STUB_CHILD_PID, 'SIGTERM'],
293 + [-STUB_CHILD_PID, 'SIGKILL'],
294 + ]);
295 + // The CLI's own SIGKILL ended the script; the user cancelled with SIGINT.
296 + expect(exitActionFor(exit, Option.some('SIGINT'))).toEqual(
297 + ExitAction.Reraise({ signal: 'SIGINT' })
298 + );
299 + })
300 + );
301 +
302 + it.effect(
303 + '[Given] a child that crashes by another signal during the escalation [Then] the run ends by that signal',
304 + () =>
305 + Effect.gen(function* () {
306 + childRunning.mockImplementation(() => true);
307 + // The script ignores SIGINT, then aborts while cleaning up after the CLI's SIGTERM.
308 + childEndingAfter(
309 + 'SIGINT',
310 + Deferred.await(deliveryOf('SIGTERM')).pipe(Effect.andThen(killedBy('SIGABRT')))
311 + );
312 +
313 + const fiber = yield* Effect.forkChild(runWithSignals);
314 + yield* Deferred.await(deliveryOf('SIGINT'));
315 + yield* TestClock.adjust('2 seconds');
316 + const exit = yield* Fiber.join(fiber);
317 + const failure = Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
318 +
319 + expect(signalled).toEqual([
320 + [-STUB_CHILD_PID, 'SIGINT'],
321 + [-STUB_CHILD_PID, 'SIGTERM'],
322 + ]);
323 + // The crash is the script's own, not the user's cancellation.
324 + expect(failure).toBeInstanceOf(ChildProcessSignaled);
325 + expect(exitActionFor(exit, Option.some('SIGINT'))).toEqual(
326 + ExitAction.Reraise({ signal: 'SIGABRT' })
327 + );
328 + })
329 + );
330 +
331 + it.effect(
332 + '[Given] a second signal [Then] forcing the exit kills the child group and re-raises',
333 + () =>
334 + Effect.gen(function* () {
335 + const forced = yield* Deferred.make<{ readonly reraise: boolean }>();
336 + commandRuns.mockImplementation(() =>
337 + Effect.sync(() => {
338 + controller.offer('SIGINT');
339 + // What the runner does on the second signal, while the child still runs.
340 + Deferred.doneUnsafe(forced, Effect.succeed(controller.force()));
341 + return ChildProcessSpawner.ExitCode(0);
342 + })
343 + );
344 +
345 + yield* runWithSignals;
346 +
347 + expect(yield* Deferred.await(forced)).toEqual({ reraise: true });
348 + expect(signalled).toContainEqual([-STUB_CHILD_PID, 'SIGKILL']);
349 + })
350 + );
351 + });
352 });
353
354 layer(RunTestLive())(it => {
ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts
+36 -3
@@ -4,6 +4,7 @@ import { describe, expect, layer } from '@effect/vitest';
4 import { ConfigProvider, Effect, Fiber, Latch, Layer } from 'effect';
5 import { ComposioCliUserConfig } from 'src/services/cli-user-config';
6 import { TriggerRealtimeSubscriptionError, TriggersRealtime } from 'src/services/triggers-realtime';
7 +import { makeShutdownController, ShutdownSignal } from 'src/services/shutdown-signal';
8 import { cli, TestLive } from 'test/__utils__';
9 import { exitCodeOf } from 'test/__utils__/exit-code';
10 import { withHttpServerEffect } from 'test/__utils__/http-server';
@@ -139,9 +140,41 @@ describe('CLI: composio dev listen', () => {
140 })
141 );
142
142 - // Ctrl+C/SIGTERM: runMain interrupts the listener fiber; the onExit finalizer must run the
143 - // summary anyway. The forwarding failure logs its warn only after the failure was counted,
144 - // so awaiting the latch is an ordered count-is-set signal — no polling, no sleeps.
143 + // Ctrl+C or SIGTERM once subscribed: the listener stops itself, sums up, and succeeds. The
144 + // forwarding failure logs its warn only after the failure was counted, so awaiting the latch
145 + // is an ordered count-is-set signal — no polling, no sleeps.
146 + it.effect.each(['SIGINT', 'SIGTERM'] as const)(
147 + '[When] %s arrives after the subscription [Then] it stops cleanly, sums up, and exits 0',
148 + signal =>
149 + Effect.gen(function* () {
150 + yield* enableListen;
151 + const shutdown = makeShutdownController();
152 + const forwardFailed = Latch.makeUnsafe(false);
153 + const terminal = redirectedTerminalUI({
154 + onWarn: message => {
155 + if (message.includes('Failed forwarding event to')) forwardFailed.openUnsafe();
156 + },
157 + });
158 + const fiber = yield* Effect.forkChild(
159 + cli(['dev', 'listen', '--forward', 'http://']).pipe(
160 + Effect.provide(terminal.layer),
161 + Effect.provideService(ShutdownSignal, shutdown.service)
162 + )
163 + );
164 +
165 + yield* forwardFailed.await;
166 + expect(shutdown.offer(signal)).toBe(true);
167 + const exit = yield* Fiber.await(fiber);
168 +
169 + expect(terminal.stderr()).toContain(
170 + '1 event failed to forward to http:// while listening.'
171 + );
172 + expect(exitCodeOf(exit)).toBe(0);
173 + })
174 + );
175 +
176 + // A signal the listener does not take (before the subscription, or SIGHUP): the runner
177 + // interrupts the listener fiber; the onExit finalizer must run the summary anyway.
178 it.effect('[Then] sums the failures up even when the listener is interrupted mid-run', () =>
179 Effect.gen(function* () {
180 yield* enableListen;
ts/packages/cli/test/src/effects/child-exit-status.test.ts new
+34
@@ -0,0 +1,34 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import * as BunServices from '@effect/platform-bun/BunServices';
3 +import { Effect } from 'effect';
4 +import { ChildProcess } from 'effect/process';
5 +import { childExitStatus } from 'src/effects/child-exit-status';
6 +
7 +// Runs real children through the installed spawner, so an Effect upgrade that changes how it
8 +// reports a child a signal ended fails here instead of silently breaking `composio run`.
9 +const statusOf = (script: string) =>
10 + ChildProcess.make(process.execPath, ['-e', script]).pipe(
11 + Effect.flatMap(childExitStatus),
12 + Effect.scoped
13 + );
14 +
15 +describe('childExitStatus', () => {
16 + layer(BunServices.layer)(it => {
17 + it.effect('[Given] a child that exits [Then] reports its code', () =>
18 + Effect.gen(function* () {
19 + expect(yield* statusOf('process.exit(3)')).toEqual({ code: 3, signal: null });
20 + })
21 + );
22 +
23 + it.effect.each(['SIGINT', 'SIGTERM', 'SIGKILL'] as const)(
24 + '[Given] a child %s ends [Then] reports the signal',
25 + signal =>
26 + Effect.gen(function* () {
27 + expect(yield* statusOf(`process.kill(process.pid, '${signal}')`)).toEqual({
28 + code: null,
29 + signal,
30 + });
31 + })
32 + );
33 + });
34 +});
ts/packages/cli/test/src/run-main.test.ts new
+272
@@ -0,0 +1,272 @@
1 +import { describe, expect, it } from 'vitest';
2 +import { Cause, Deferred, Effect, Exit, Option } from 'effect';
3 +import { ChildProcessExited, ChildProcessSignaled } from 'src/effects/child-process-exited';
4 +import { ReportedFailure } from 'src/effects/report-failure';
5 +import { ExitAction, exitActionFor, makeCliRunMain, type RunnerPlatform } from 'src/run-main';
6 +import {
7 + makeShutdownController,
8 + type ShutdownController,
9 + type StopSignal,
10 +} from 'src/services/shutdown-signal';
11 +
12 +const exitWith = (code: number): ExitAction => ExitAction.ExitWith({ code });
13 +const reraiseKill: ExitAction = ExitAction.Reraise({ signal: 'SIGKILL' });
14 +
15 +// Each exit, then the action expected with no signal, SIGINT, SIGTERM and SIGHUP received.
16 +const exits = [
17 + {
18 + kind: 'success',
19 + exit: Exit.succeed(undefined),
20 + expected: [exitWith(0), exitWith(0), exitWith(0), exitWith(0)],
21 + },
22 + {
23 + kind: 'interrupted',
24 + exit: Exit.failCause(Cause.interrupt()),
25 + expected: [exitWith(130), exitWith(130), exitWith(143), exitWith(129)],
26 + },
27 + {
28 + kind: 'child exited 7',
29 + exit: Exit.fail(new ChildProcessExited({ code: 7 })),
30 + expected: [exitWith(7), exitWith(7), exitWith(7), exitWith(7)],
31 + },
32 + {
33 + kind: 'child killed',
34 + exit: Exit.fail(new ChildProcessSignaled({ signal: 'SIGKILL' })),
35 + expected: [reraiseKill, reraiseKill, reraiseKill, reraiseKill],
36 + },
37 + {
38 + kind: 'reported failure',
39 + exit: Exit.fail(new ReportedFailure({ message: 'printed' })),
40 + expected: [exitWith(1), exitWith(1), exitWith(1), exitWith(1)],
41 + },
42 + {
43 + kind: 'defect',
44 + exit: Exit.die(new Error('boom')),
45 + expected: [exitWith(1), exitWith(1), exitWith(1), exitWith(1)],
46 + },
47 +] as const;
48 +
49 +const received = [
50 + { name: 'no signal', signal: Option.none<StopSignal>() },
51 + { name: 'SIGINT', signal: Option.some<StopSignal>('SIGINT') },
52 + { name: 'SIGTERM', signal: Option.some<StopSignal>('SIGTERM') },
53 + { name: 'SIGHUP', signal: Option.some<StopSignal>('SIGHUP') },
54 +] as const;
55 +
56 +const cases = exits.flatMap(({ kind, exit, expected }) =>
57 + received.map(({ name, signal }, index) => ({
58 + kind,
59 + name,
60 + exit: exit as Exit.Exit<unknown, unknown>,
61 + signal: signal as Option.Option<StopSignal>,
62 + action: expected[index],
63 + }))
64 +);
65 +
66 +describe('exitActionFor', () => {
67 + it.each(cases)(
68 + '[Given] $kind after $name [Then] ends as expected',
69 + ({ exit, signal, action }) => {
70 + expect(exitActionFor(exit, signal)).toEqual(action);
71 + }
72 + );
73 +});
74 +
75 +/** A process stand-in: signals are delivered by hand, timers fire by hand. */
76 +const fakePlatform = () => {
77 + const listeners = new Map<StopSignal, Set<() => void>>();
78 + const timers: Array<() => void> = [];
79 + const ended: Array<ExitAction> = [];
80 + let onEnd = () => {};
81 + const platform: RunnerPlatform = {
82 + on: (signal, listener) => {
83 + listeners.set(signal, (listeners.get(signal) ?? new Set()).add(listener));
84 + },
85 + off: (signal, listener) => {
86 + listeners.get(signal)?.delete(listener);
87 + },
88 + exit: code => {
89 + ended.push(ExitAction.ExitWith({ code }));
90 + onEnd();
91 + },
92 + raise: signal => {
93 + ended.push(ExitAction.Reraise({ signal }));
94 + onEnd();
95 + },
96 + schedule: (_millis, f) => {
97 + timers.push(f);
98 + return () => timers.splice(timers.indexOf(f), 1);
99 + },
100 + };
101 + return {
102 + platform,
103 + ended,
104 + timers,
105 + send: (signal: StopSignal) => [...(listeners.get(signal) ?? [])].forEach(f => f()),
106 + listenerCount: () => [...listeners.values()].reduce((sum, set) => sum + set.size, 0),
107 + /** Resolves on the first exit or re-raise. */
108 + end: new Promise<void>(resolve => {
109 + onEnd = resolve;
110 + }),
111 + };
112 +};
113 +
114 +/** Lets the runtime settle a fiber the test cannot await. */
115 +const settle = () => new Promise(resolve => setTimeout(resolve, 20));
116 +
117 +const start = (controller: ShutdownController, program: Effect.Effect<unknown, unknown>) => {
118 + const fake = fakePlatform();
119 + makeCliRunMain(controller, fake.platform)(program, { disableErrorReporting: true });
120 + return fake;
121 +};
122 +
123 +describe('makeCliRunMain', () => {
124 + it.each([
125 + { signal: 'SIGINT', code: 130 },
126 + { signal: 'SIGTERM', code: 143 },
127 + { signal: 'SIGHUP', code: 129 },
128 + ] as const)(
129 + '[Given] a command that does not cooperate [When] $signal arrives [Then] it is interrupted and exits $code',
130 + async ({ signal, code }) => {
131 + const fake = start(makeShutdownController(), Effect.never);
132 +
133 + fake.send(signal);
134 + await fake.end;
135 +
136 + expect(fake.ended).toEqual([ExitAction.ExitWith({ code })]);
137 + expect(fake.listenerCount()).toBe(0);
138 + }
139 + );
140 +
141 + it('[Given] a command that cooperates [When] SIGTERM arrives [Then] it stops by itself and exits 0', async () => {
142 + const controller = makeShutdownController();
143 + const stopped = Deferred.makeUnsafe<StopSignal>();
144 + const program = Effect.gen(function* () {
145 + yield* controller.service.cooperate({ signals: ['SIGINT', 'SIGTERM'] });
146 + const signal = yield* controller.service.requested;
147 + yield* Deferred.succeed(stopped, signal);
148 + }).pipe(Effect.scoped);
149 + const fake = start(controller, program);
150 + await settle();
151 +
152 + fake.send('SIGTERM');
153 + await fake.end;
154 +
155 + expect(Deferred.isDoneUnsafe(stopped)).toBe(true);
156 + expect(fake.ended).toEqual([ExitAction.ExitWith({ code: 0 })]);
157 + });
158 +
159 + it('[Given] a cooperating command [When] a signal it does not take arrives [Then] it is interrupted', async () => {
160 + const controller = makeShutdownController();
161 + const program = controller.service
162 + .cooperate({ signals: ['SIGINT', 'SIGTERM'] })
163 + .pipe(Effect.andThen(Effect.never), Effect.scoped);
164 + const fake = start(controller, program);
165 + await settle();
166 +
167 + fake.send('SIGHUP');
168 + await fake.end;
169 +
170 + expect(fake.ended).toEqual([ExitAction.ExitWith({ code: 129 })]);
171 + });
172 +
173 + it.each([
174 + { reraiseOnForce: false, ended: ExitAction.ExitWith({ code: 143 }) },
175 + { reraiseOnForce: true, ended: ExitAction.Reraise({ signal: 'SIGTERM' }) },
176 + ])(
177 + '[Given] a stop in progress [When] a second signal arrives (reraise: $reraiseOnForce) [Then] it forces the exit',
178 + async ({ reraiseOnForce, ended }) => {
179 + const controller = makeShutdownController();
180 + const release = Deferred.makeUnsafe<void>();
181 + let forced = 0;
182 + const program = Effect.gen(function* () {
183 + yield* controller.service.cooperate({
184 + signals: ['SIGINT', 'SIGTERM'],
185 + onForce: () => {
186 + forced += 1;
187 + },
188 + reraiseOnForce,
189 + });
190 + yield* controller.service.requested;
191 + // A stop that never finishes on its own.
192 + yield* Deferred.await(release);
193 + }).pipe(Effect.scoped);
194 + const fake = start(controller, program);
195 + await settle();
196 +
197 + fake.send('SIGINT');
198 + await settle();
199 + expect(fake.ended).toEqual([]);
200 + fake.send('SIGTERM');
201 + await fake.end;
202 +
203 + expect(forced).toBe(1);
204 + expect(fake.ended).toEqual([ended]);
205 + Deferred.doneUnsafe(release, Effect.void);
206 + }
207 + );
208 +
209 + it('[Given] a stop that outlives the deadline [Then] the deadline forces the exit with the first signal', async () => {
210 + const controller = makeShutdownController();
211 + const release = Deferred.makeUnsafe<void>();
212 + const program = controller.service
213 + .cooperate({ signals: ['SIGINT'] })
214 + .pipe(
215 + Effect.andThen(controller.service.requested),
216 + Effect.andThen(Deferred.await(release)),
217 + Effect.scoped
218 + );
219 + const fake = start(controller, program);
220 + await settle();
221 +
222 + fake.send('SIGINT');
223 + expect(fake.timers).toHaveLength(1);
224 + fake.timers[0]!();
225 + await fake.end;
226 +
227 + expect(fake.ended).toEqual([ExitAction.ExitWith({ code: 130 })]);
228 + Deferred.doneUnsafe(release, Effect.void);
229 + });
230 +
231 + it('[Given] a stop that finishes in time [Then] the deadline is cancelled', async () => {
232 + const controller = makeShutdownController();
233 + const program = controller.service
234 + .cooperate({ signals: ['SIGINT'] })
235 + .pipe(Effect.andThen(controller.service.requested), Effect.scoped);
236 + const fake = start(controller, program);
237 + await settle();
238 +
239 + fake.send('SIGINT');
240 + await fake.end;
241 +
242 + expect(fake.timers).toHaveLength(0);
243 + });
244 +
245 + it('[Given] a child a signal ended [Then] the runner re-raises that signal', async () => {
246 + const fake = start(
247 + makeShutdownController(),
248 + Effect.fail(new ChildProcessSignaled({ signal: 'SIGINT' }))
249 + );
250 +
251 + await fake.end;
252 +
253 + expect(fake.ended).toEqual([ExitAction.Reraise({ signal: 'SIGINT' })]);
254 + });
255 +
256 + it('[Given] a failure without a signal [Then] it exits with the failure code', async () => {
257 + const fake = start(makeShutdownController(), Effect.fail(new ChildProcessExited({ code: 3 })));
258 +
259 + await fake.end;
260 +
261 + expect(fake.ended).toEqual([ExitAction.ExitWith({ code: 3 })]);
262 + });
263 +
264 + it('[Given] a success nobody signalled [Then] it leaves the exit to the event loop', async () => {
265 + const fake = start(makeShutdownController(), Effect.void);
266 +
267 + await settle();
268 +
269 + expect(fake.ended).toEqual([]);
270 + expect(fake.listenerCount()).toBe(0);
271 + });
272 +});
ts/packages/cli/test/src/services/shutdown-signal.test.ts new
+87
@@ -0,0 +1,87 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { Deferred, Effect, Fiber } from 'effect';
3 +import {
4 + LISTENER_STOP,
5 + makeShutdownController,
6 + signalExitCode,
7 +} from 'src/services/shutdown-signal';
8 +
9 +describe('ShutdownSignal', () => {
10 + it.effect('[Given] no command cooperates [Then] the runner must interrupt', () =>
11 + Effect.sync(() => {
12 + expect(makeShutdownController().offer('SIGINT')).toBe(false);
13 + })
14 + );
15 +
16 + it.effect('[Given] a listener [Then] it takes SIGINT and SIGTERM but not SIGHUP', () =>
17 + Effect.gen(function* () {
18 + const takes = (signal: 'SIGINT' | 'SIGTERM' | 'SIGHUP') =>
19 + Effect.gen(function* () {
20 + const controller = makeShutdownController();
21 + yield* controller.service.cooperate(LISTENER_STOP);
22 + return controller.offer(signal);
23 + }).pipe(Effect.scoped);
24 +
25 + expect(yield* takes('SIGINT')).toBe(true);
26 + expect(yield* takes('SIGTERM')).toBe(true);
27 + expect(yield* takes('SIGHUP')).toBe(false);
28 + })
29 + );
30 +
31 + it.effect(
32 + '[Given] a cooperating command [When] it takes a signal [Then] `requested` yields it',
33 + () =>
34 + Effect.gen(function* () {
35 + const controller = makeShutdownController();
36 + yield* controller.service.cooperate(LISTENER_STOP);
37 + const waiting = yield* Effect.forkChild(controller.service.requested);
38 +
39 + expect(controller.offer('SIGTERM')).toBe(true);
40 + expect(yield* Fiber.join(waiting)).toBe('SIGTERM');
41 + })
42 + );
43 +
44 + it.effect('[Given] the cooperating scope closed [Then] a signal interrupts again', () =>
45 + Effect.gen(function* () {
46 + const controller = makeShutdownController();
47 + yield* Effect.scoped(controller.service.cooperate(LISTENER_STOP));
48 +
49 + expect(controller.offer('SIGINT')).toBe(false);
50 + })
51 + );
52 +
53 + it.effect(
54 + '[Given] a forced exit [Then] it runs every onForce and reports whether to re-raise',
55 + () =>
56 + Effect.gen(function* () {
57 + const controller = makeShutdownController();
58 + const forced = yield* Deferred.make<void>();
59 + yield* controller.service.cooperate({
60 + signals: ['SIGINT'],
61 + onForce: () => Deferred.doneUnsafe(forced, Effect.void),
62 + reraiseOnForce: true,
63 + });
64 +
65 + expect(controller.force()).toEqual({ reraise: true });
66 + expect(Deferred.isDoneUnsafe(forced)).toBe(true);
67 + })
68 + );
69 +
70 + it.effect('[Given] a listener only [Then] a forced exit does not re-raise', () =>
71 + Effect.gen(function* () {
72 + const controller = makeShutdownController();
73 + yield* controller.service.cooperate(LISTENER_STOP);
74 +
75 + expect(controller.force()).toEqual({ reraise: false });
76 + })
77 + );
78 +
79 + it.each([
80 + { signal: 'SIGHUP', code: 129 },
81 + { signal: 'SIGINT', code: 130 },
82 + { signal: 'SIGKILL', code: 137 },
83 + { signal: 'SIGTERM', code: 143 },
84 + ] as const)('signalExitCode($signal) is $code', ({ signal, code }) => {
85 + expect(signalExitCode(signal)).toBe(code);
86 + });
87 +});
ts/packages/cli/test/src/services/triggers-realtime.listen.test.ts
+137 -10
@@ -1,11 +1,11 @@
1 -import { afterEach, describe, expect, it } from '@effect/vitest';
1 +import { afterEach, beforeEach, describe, expect, it } from '@effect/vitest';
2 import { vi } from 'vitest';
3 import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
4 import * as BunPath from '@effect/platform-bun/BunPath';
5 -import { ConfigProvider, Effect, Fiber, Layer } from 'effect';
5 +import { ConfigProvider, Deferred, Effect, Exit, Fiber, Layer } from 'effect';
6 import * as tempy from 'tempy';
7 import { defaultNodeOs, NodeOs } from 'src/services/node-os';
8 -import { TriggersRealtime } from 'src/services/triggers-realtime';
8 +import { TriggerRealtimeSubscriptionError, TriggersRealtime } from 'src/services/triggers-realtime';
9
10 // Exercise real user-context/config resolution without opening the OS credential store.
11 vi.mock('@composio/cli-keyring/effect', async importOriginal => {
@@ -37,13 +37,23 @@ interface ConstructedPusher {
37 readonly authorize: ChannelAuthorizer;
38 }
39
40 -// The realtime client, replaced by one that only records how it was built.
40 +// The realtime client, replaced by one that records how it was built and lets a test emit the
41 +// channel's events. Each `listenInProject` builds one client, so `reset` starts a fresh record.
42 const pusher = vi.hoisted(() => {
42 - let announce: (constructed: ConstructedPusher) => void = () => undefined;
43 - const constructed = new Promise<ConstructedPusher>(resolve => {
44 - announce = resolve;
45 - });
46 - return { constructed, announce: (value: ConstructedPusher) => announce(value) };
43 + const state = {
44 + constructed: undefined as unknown as Promise<ConstructedPusher>,
45 + announce: (_value: ConstructedPusher) => undefined as void,
46 + handlers: new Map<string, (data?: unknown) => void>(),
47 + reset: () => {
48 + state.handlers = new Map();
49 + state.constructed = new Promise<ConstructedPusher>(resolve => {
50 + state.announce = resolve;
51 + });
52 + },
53 + emit: (event: string, data?: unknown) => state.handlers.get(event)?.(data),
54 + };
55 + state.reset();
56 + return state;
57 });
58
59 vi.mock('pusher-js', () => {
@@ -62,7 +72,12 @@ vi.mock('pusher-js', () => {
72 });
73 }
74 subscribe() {
65 - return { bind: () => undefined, unbind_all: () => undefined };
75 + return {
76 + bind: (event: string, handler: (data?: unknown) => void) => {
77 + pusher.handlers.set(event, handler);
78 + },
79 + unbind_all: () => undefined,
80 + };
81 }
82 unsubscribe() {}
83 disconnect() {}
@@ -90,11 +105,123 @@ const realtimeLayer = () =>
105 )
106 );
107
108 +const realtimeResponses: Record<string, unknown> = {
109 + '/api/v3.1/cli/realtime/credentials': {
110 + pusher_key: 'pk_test',
111 + pusher_cluster: 'mt1',
112 + project_id: 'pr_nano',
113 + },
114 +};
115 +
116 describe('TriggersRealtime.listenInProject', () => {
117 + beforeEach(() => {
118 + pusher.reset();
119 + });
120 +
121 afterEach(() => {
122 vi.restoreAllMocks();
123 });
124
125 + // Ctrl-C while the socket connects or the channel is authorized must still cancel the listener,
126 + // so the cooperative stop is registered only once Pusher confirms the subscription.
127 + it.live(
128 + '[Given] a pending subscription [Then] onSubscribed waits for Pusher to confirm it',
129 + () => {
130 + vi.spyOn(globalThis, 'fetch').mockImplementation(async input =>
131 + Response.json(realtimeResponses[new URL(new Request(input).url).pathname])
132 + );
133 +
134 + return Effect.gen(function* () {
135 + const realtime = yield* TriggersRealtime;
136 + const onSubscribed = yield* Deferred.make<void>();
137 + const listening = yield* Effect.forkChild(
138 + realtime.listenInProject({ orgId: 'org_test', projectId: 'pr_test' }, () => undefined, {
139 + onSubscribed: Deferred.succeed(onSubscribed, undefined),
140 + })
141 + );
142 + yield* Effect.promise(() => pusher.constructed);
143 + yield* Effect.yieldNow;
144 +
145 + const beforeConfirmation = yield* Deferred.isDone(onSubscribed);
146 + pusher.emit('pusher:subscription_succeeded');
147 + yield* Deferred.await(onSubscribed);
148 + yield* Fiber.interrupt(listening);
149 +
150 + expect(beforeConfirmation).toBe(false);
151 + }).pipe(Effect.provide(realtimeLayer()));
152 + }
153 + );
154 +
155 + // pusher-js emits the subscription events again whenever it resubscribes after a reconnect.
156 + // Completing the already-done Deferred again returns false rather than throwing, so the
157 + // listener keeps delivering events.
158 + it.live(
159 + '[Given] Pusher resubscribes after a reconnect [Then] the listener keeps handling events',
160 + () => {
161 + vi.spyOn(globalThis, 'fetch').mockImplementation(async input =>
162 + Response.json(realtimeResponses[new URL(new Request(input).url).pathname])
163 + );
164 +
165 + return Effect.gen(function* () {
166 + const realtime = yield* TriggersRealtime;
167 + const onSubscribed = yield* Deferred.make<void>();
168 + const received: Array<unknown> = [];
169 + const listening = yield* Effect.forkChild(
170 + realtime.listenInProject(
171 + { orgId: 'org_test', projectId: 'pr_test' },
172 + event => received.push(event),
173 + { onSubscribed: Deferred.succeed(onSubscribed, undefined) }
174 + )
175 + );
176 + yield* Effect.promise(() => pusher.constructed);
177 + yield* Effect.yieldNow;
178 +
179 + pusher.emit('pusher:subscription_succeeded');
180 + yield* Deferred.await(onSubscribed);
181 + expect(() => pusher.emit('pusher:subscription_succeeded')).not.toThrow();
182 + expect(() =>
183 + pusher.emit('pusher:subscription_error', { type: 'AuthError', status: 403 })
184 + ).not.toThrow();
185 + pusher.emit('trigger_to_client', { id: 'evt_after_reconnect' });
186 + yield* Effect.yieldNow;
187 + const stillListening = listening.pollUnsafe() === undefined;
188 + yield* Fiber.interrupt(listening);
189 +
190 + expect(stillListening).toBe(true);
191 + expect(received).toEqual([{ id: 'evt_after_reconnect' }]);
192 + }).pipe(Effect.provide(realtimeLayer()));
193 + }
194 + );
195 +
196 + it.live('[Given] Pusher rejects the subscription [Then] the listener fails', () => {
197 + vi.spyOn(globalThis, 'fetch').mockImplementation(async input =>
198 + Response.json(realtimeResponses[new URL(new Request(input).url).pathname])
199 + );
200 +
201 + return Effect.gen(function* () {
202 + const realtime = yield* TriggersRealtime;
203 + const listening = yield* Effect.forkChild(
204 + realtime.listenInProject({ orgId: 'org_test', projectId: 'pr_test' }, () => undefined, {
205 + onSubscribed: Effect.die(new Error('onSubscribed ran for a rejected subscription')),
206 + })
207 + );
208 + yield* Effect.promise(() => pusher.constructed);
209 + yield* Effect.yieldNow;
210 +
211 + pusher.emit('pusher:subscription_error', { type: 'AuthError', status: 403 });
212 + const exit = yield* Fiber.await(listening);
213 +
214 + expect(exit).toEqual(
215 + Exit.fail(
216 + new TriggerRealtimeSubscriptionError({
217 + message: 'Failed to subscribe to realtime trigger events',
218 + cause: { type: 'AuthError', status: 403 },
219 + })
220 + )
221 + );
222 + }).pipe(Effect.provide(realtimeLayer()));
223 + });
224 +
225 it.live('authorizes the private channel when the realtime client asks for it', () => {
226 const requests: Array<{ method: string; path: string; body: unknown }> = [];
227 const responses: Record<string, unknown> = {