@trama-dev/runtime 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Send a signal to a whole process group. Children spawned with `detached: true`
3
+ * lead their own group, so this also reaches whatever they started in the background.
4
+ * Signal 0 only probes. Returns false if the group no longer exists.
5
+ */
6
+ export declare function signalGroup(pgid: number, signal: NodeJS.Signals | 0): boolean;
7
+ /**
8
+ * Make sure there is a watchdog before anything is started that would need
9
+ * one. Throws if one cannot be started: running without it would mean leaving
10
+ * processes behind with nobody to stop them.
11
+ */
12
+ export declare function requireWatchdog(): void;
13
+ /**
14
+ * Register a process group this process started: if this process ends before
15
+ * the returned function is called, the group is stopped.
16
+ */
17
+ export declare function stopWithThisProcess(pgid: number): () => void;
18
+ /**
19
+ * Register a temp directory this process created: if this process ends before
20
+ * the returned function is called, the directory is removed — once the groups
21
+ * that may be writing to it are gone.
22
+ */
23
+ export declare function removeWithThisProcess(dir: string): () => void;
24
+ /** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
25
+ export declare function removeTempDir(dir: string): void;
26
+ /**
27
+ * Stop process groups for good: SIGTERM now, SIGKILL after the grace period to
28
+ * whichever are still there. Resolves when none is left — so that what follows
29
+ * (merging a directory they were writing to, deleting it) finds them gone.
30
+ */
31
+ export declare function stopGroups(pgids: number[]): Promise<void>;
@@ -0,0 +1,230 @@
1
+ // Stopping what a runner started, and removing what it made.
2
+ //
3
+ // A program, and every shell command it runs, leads its own process group — so
4
+ // that a timeout can take down everything it started. The cost is that none of
5
+ // them die with the runner: something has to stop them, and delete the temp
6
+ // directories they worked in.
7
+ //
8
+ // Never SIGKILL first. A group gets the chance to end properly — a program to
9
+ // close what it opened, a `trama` command to stop its own run and report it.
10
+ // Killed outright, nothing in it gets to finish anything. So a group is asked
11
+ // to stop, and killed only if it is still there when the grace period is over.
12
+ //
13
+ // That policy is carried out in two places. While the runner is there, it does
14
+ // it itself and waits for the result (stopGroups). When the runner is gone, it
15
+ // cannot: a process that is killed outright, or runs out of memory, or
16
+ // crashes, runs no code on its way out. So there is a process of its own, the
17
+ // watchdog. The runner keeps a pipe to it open, and tells it what it has
18
+ // started and what has ended. When the pipe closes — the runner is gone,
19
+ // however it went — the watchdog stops whatever is still on its list and
20
+ // deletes what is left of the directories. One runner carries every run of a
21
+ // session, so one list covers the whole tree.
22
+ //
23
+ // Nothing here listens for a signal or for the process exiting: the process
24
+ // that hosts a runner keeps its own way of handling both.
25
+ import { spawn } from "child_process";
26
+ import { rmSync } from "fs";
27
+ /** How long a process group gets to exit after SIGTERM before it is sent SIGKILL. */
28
+ const KILL_GRACE_MS = 5000;
29
+ const STOP_POLL_MS = 25;
30
+ /** How long a group is waited for after SIGKILL before it is given up on. */
31
+ const KILL_SETTLE_MS = 1000;
32
+ /**
33
+ * Send a signal to a whole process group. Children spawned with `detached: true`
34
+ * lead their own group, so this also reaches whatever they started in the background.
35
+ * Signal 0 only probes. Returns false if the group no longer exists.
36
+ */
37
+ export function signalGroup(pgid, signal) {
38
+ try {
39
+ process.kill(-pgid, signal);
40
+ return true;
41
+ }
42
+ catch {
43
+ return false;
44
+ }
45
+ }
46
+ // --- The watchdog ---
47
+ // Run by the watchdog process: the same policy as stopGroups below. A group
48
+ // the runner had already asked to stop is not asked a second time.
49
+ const WATCHDOG = `
50
+ const { rmSync } = require("fs");
51
+ const { grace, settle, poll } = JSON.parse(process.argv[1]);
52
+ const lists = { g: new Set(), d: new Set(), asked: new Set() };
53
+ const alive = (pgid) => { try { process.kill(-pgid, 0); return true; } catch { return false; } };
54
+ const signal = (pgid, name) => { try { process.kill(-pgid, name); } catch {} };
55
+
56
+ let unread = "";
57
+ process.stdin.setEncoding("utf8");
58
+ process.stdin.on("data", (chunk) => {
59
+ unread += chunk;
60
+ for (let end; (end = unread.indexOf("\\n")) !== -1; unread = unread.slice(end + 1)) {
61
+ const [op, list, item] = JSON.parse(unread.slice(0, end));
62
+ lists[list][op === "+" ? "add" : "delete"](item);
63
+ }
64
+ });
65
+
66
+ // The pipe has closed: the runner is gone.
67
+ let leaving = false;
68
+ const takeOver = () => {
69
+ if (leaving) return;
70
+ leaving = true;
71
+ const finish = () => {
72
+ for (const dir of lists.d) { try { rmSync(dir, { recursive: true, force: true }); } catch {} }
73
+ process.exit(0);
74
+ };
75
+ let left = [...lists.g].filter(alive);
76
+ for (const pgid of left) { if (!lists.asked.has(pgid)) signal(pgid, "SIGTERM"); }
77
+ let deadline = performance.now() + grace;
78
+ let killed = false;
79
+ const check = () => {
80
+ // A group seen gone is never signalled again: its id may belong to another by now.
81
+ left = left.filter(alive);
82
+ if (left.length === 0) return finish();
83
+ if (performance.now() < deadline) return;
84
+ if (killed) return finish();
85
+ for (const pgid of left) signal(pgid, "SIGKILL");
86
+ killed = true;
87
+ deadline = performance.now() + settle;
88
+ };
89
+ check();
90
+ setInterval(check, poll);
91
+ };
92
+ process.stdin.on("end", takeOver);
93
+ process.stdin.on("close", takeOver);
94
+ process.stdin.on("error", takeOver);
95
+ `;
96
+ /** What the watchdog has been told about and not yet told to forget. */
97
+ const listed = { g: new Set(), d: new Set(), asked: new Set() };
98
+ let watchdog = null;
99
+ const tell = (to, op, list, item) => {
100
+ to.stdin?.write(JSON.stringify([op, list, item]) + "\n");
101
+ };
102
+ /**
103
+ * Start the watchdog if there is none, and return it — or null if it cannot be
104
+ * started. A watchdog that has itself died is replaced, and told again what is
105
+ * still listed.
106
+ */
107
+ function startWatchdog() {
108
+ if (watchdog)
109
+ return watchdog;
110
+ let child;
111
+ try {
112
+ const timings = { grace: KILL_GRACE_MS, settle: KILL_SETTLE_MS, poll: STOP_POLL_MS };
113
+ child = spawn(process.execPath, ["-e", WATCHDOG, JSON.stringify(timings)], {
114
+ detached: true, // a signal sent to this process's group must not reach it
115
+ stdio: ["pipe", "ignore", "ignore"],
116
+ });
117
+ }
118
+ catch {
119
+ return null;
120
+ }
121
+ const lost = () => { if (watchdog === child)
122
+ watchdog = null; };
123
+ child.on("error", lost);
124
+ child.on("exit", lost);
125
+ child.stdin?.on("error", lost);
126
+ if (child.pid === undefined)
127
+ return null; // a failed spawn has no pid from the start
128
+ // Neither the watchdog nor the pipe to it keeps this process alive.
129
+ child.unref();
130
+ child.stdin?.unref?.();
131
+ watchdog = child;
132
+ for (const name of ["g", "d", "asked"]) {
133
+ for (const item of listed[name])
134
+ tell(child, "+", name, item);
135
+ }
136
+ return child;
137
+ }
138
+ /**
139
+ * Make sure there is a watchdog before anything is started that would need
140
+ * one. Throws if one cannot be started: running without it would mean leaving
141
+ * processes behind with nobody to stop them.
142
+ */
143
+ export function requireWatchdog() {
144
+ if (!startWatchdog()) {
145
+ throw new Error("Could not start trama's watchdog process, which stops what a run started if the runner dies.");
146
+ }
147
+ }
148
+ /** Put an item on one of the watchdog's lists. */
149
+ function enlist(on, item) {
150
+ listed[on].add(item);
151
+ const to = startWatchdog();
152
+ if (to)
153
+ tell(to, "+", on, item);
154
+ }
155
+ /** Take it off again. */
156
+ function delist(from, item) {
157
+ if (listed[from].delete(item) && watchdog)
158
+ tell(watchdog, "-", from, item);
159
+ }
160
+ /**
161
+ * Register a process group this process started: if this process ends before
162
+ * the returned function is called, the group is stopped.
163
+ */
164
+ export function stopWithThisProcess(pgid) {
165
+ enlist("g", pgid);
166
+ return () => {
167
+ delist("g", pgid);
168
+ delist("asked", pgid);
169
+ };
170
+ }
171
+ /**
172
+ * Register a temp directory this process created: if this process ends before
173
+ * the returned function is called, the directory is removed — once the groups
174
+ * that may be writing to it are gone.
175
+ */
176
+ export function removeWithThisProcess(dir) {
177
+ enlist("d", dir);
178
+ return () => delist("d", dir);
179
+ }
180
+ /** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
181
+ export function removeTempDir(dir) {
182
+ try {
183
+ rmSync(dir, { recursive: true, force: true });
184
+ }
185
+ catch { /* left for the OS to reap */ }
186
+ }
187
+ // --- Stopping, while this process is there to see it through ---
188
+ /** Groups this process has asked to stop and is still watching. */
189
+ const stopping = new Map();
190
+ function stopGroup(pgid) {
191
+ // Asked once is enough: to some programs a second SIGTERM means "now".
192
+ const watched = stopping.get(pgid);
193
+ if (watched)
194
+ return watched;
195
+ if (!signalGroup(pgid, "SIGTERM"))
196
+ return Promise.resolve();
197
+ // The watchdog, should it take over from here, must not ask again either.
198
+ if (listed.g.has(pgid))
199
+ enlist("asked", pgid);
200
+ const gone = new Promise((resolve) => {
201
+ let deadline = performance.now() + KILL_GRACE_MS;
202
+ let killed = false;
203
+ const poll = setInterval(() => {
204
+ const alive = signalGroup(pgid, 0);
205
+ if (alive && performance.now() < deadline)
206
+ return;
207
+ if (alive && !killed) {
208
+ // Out of patience. A killed group is gone in a moment; allow it that
209
+ // moment, but do not wait on one that for some reason never goes.
210
+ signalGroup(pgid, "SIGKILL");
211
+ killed = true;
212
+ deadline = performance.now() + KILL_SETTLE_MS;
213
+ return;
214
+ }
215
+ clearInterval(poll);
216
+ stopping.delete(pgid);
217
+ resolve();
218
+ }, STOP_POLL_MS);
219
+ });
220
+ stopping.set(pgid, gone);
221
+ return gone;
222
+ }
223
+ /**
224
+ * Stop process groups for good: SIGTERM now, SIGKILL after the grace period to
225
+ * whichever are still there. Resolves when none is left — so that what follows
226
+ * (merging a directory they were writing to, deleting it) finds them gone.
227
+ */
228
+ export async function stopGroups(pgids) {
229
+ await Promise.all(pgids.map(stopGroup));
230
+ }
package/dist/tools.js CHANGED
@@ -2,8 +2,8 @@ import { spawn } from "child_process";
2
2
  import { readFileSync, writeFileSync, mkdirSync } from "fs";
3
3
  import { resolve, dirname } from "path";
4
4
  import { guardPath } from "./path-guard.js";
5
- import { signalGroup, stopGroups, superviseChild } from "./child-process.js";
6
- import { stopWithThisProcess } from "./lifetime.js";
5
+ import { superviseChild } from "./child-process.js";
6
+ import { signalGroup, stopGroups, stopWithThisProcess } from "./stopping.js";
7
7
  const MAX_FETCH_BODY = 10 * 1024 * 1024; // 10 MB
8
8
  const DEFAULT_SHELL_TIMEOUT = 30_000;
9
9
  const GROUP_SWEEP_MS = 250;
@@ -13,7 +13,7 @@ export function createTools(projectDir, signal) {
13
13
  // starts stay killable after the shell itself exits. A group is tracked from
14
14
  // spawn until it has no members left. `shellExited` marks groups whose shell
15
15
  // has exited — only those are probed, since a group that is still starting
16
- // up may not be visible yet. `forget` tells the process-lifetime guard the
16
+ // up may not be visible yet. `forget` tells the watchdog the
17
17
  // group no longer needs killing if this process dies.
18
18
  const groups = new Map();
19
19
  let sweeper = null;
@@ -22,10 +22,11 @@ export function createTools(projectDir, signal) {
22
22
  groups.delete(pgid);
23
23
  };
24
24
  // Shell commands run here do not get the bridge's address or the init file
25
- // (which holds its secret). A top-level runner has neither in its
26
- // environment, but a runner inside a program — a session's creator —
27
- // inherits both. (This covers tools.shell only: what the agent backend runs
28
- // on its own takes its environment from this process.)
25
+ // (which holds its secret). A runner normally has neither in its
26
+ // environment; it does when it is working inside a program — which create
27
+ // and update still do when a program calls them. (This covers tools.shell
28
+ // only: what the agent backend runs on its own takes its environment from
29
+ // this process.)
29
30
  const { TRAMA_PORT: _port, TRAMA_INIT: _init, ...shellEnv } = process.env;
30
31
  const stopSweeping = () => {
31
32
  if (sweeper)
@@ -85,7 +86,8 @@ export function createTools(projectDir, signal) {
85
86
  const child = spawn("sh", ["-c", command], {
86
87
  cwd,
87
88
  env: shellEnv,
88
- stdio: ["pipe", "pipe", "pipe"],
89
+ // Nothing is ever sent to a command: one that reads its input finds it at an end, rather than waiting.
90
+ stdio: ["ignore", "pipe", "pipe"],
89
91
  detached: true,
90
92
  });
91
93
  const pgid = child.pid;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trama-dev/runtime",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -13,7 +13,7 @@
13
13
  }
14
14
  },
15
15
  "scripts": {
16
- "build": "tsc"
16
+ "build": "rm -rf dist && tsc"
17
17
  },
18
18
  "publishConfig": {
19
19
  "access": "public"
@@ -1,12 +0,0 @@
1
- /**
2
- * Register a process group this process started: if this process ends before
3
- * the returned function is called, the group is stopped (see stopGroupsOnExit).
4
- */
5
- export declare function stopWithThisProcess(pgid: number): () => void;
6
- /**
7
- * Register a temp directory this process created: if this process ends before
8
- * the returned function is called, the directory is removed.
9
- */
10
- export declare function removeWithThisProcess(dir: string): () => void;
11
- /** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
12
- export declare function removeTempDir(dir: string): void;
package/dist/lifetime.js DELETED
@@ -1,85 +0,0 @@
1
- // What this process must undo if it ends while a run is still in flight:
2
- // stop the processes it started, and delete what it left in the temp directory.
3
- //
4
- // A program, and every shell command it runs, leads its own process group — so
5
- // that a timeout can take down everything it started. The cost is that none of
6
- // them die with the runner: without this, Ctrl-C on `trama run` would leave the
7
- // program running, and a program that coordinates others (a session) would
8
- // leave them running when it ended.
9
- import { rmSync } from "fs";
10
- import { stopGroupsOnExit } from "./child-process.js";
11
- const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
12
- const pendingGroups = new Set();
13
- const pendingDirs = new Set();
14
- let installed = false;
15
- function runPending() {
16
- const groups = [...pendingGroups];
17
- const dirs = [...pendingDirs];
18
- pendingGroups.clear();
19
- pendingDirs.clear();
20
- // The groups are asked to stop and given a moment; whatever sees that through
21
- // also removes the directories again once they are gone, in case they were
22
- // still writing to them.
23
- stopGroupsOnExit(groups, dirs);
24
- for (const dir of dirs)
25
- removeTempDir(dir);
26
- }
27
- function onSignal(signal) {
28
- runPending();
29
- // Having a handler at all cancelled the signal's default action. Step aside
30
- // and send it again, so that what happens next is what would have happened
31
- // had this handler never been installed: the process dies of it, or whoever
32
- // else handles the signal decides. (Common libraries only act on a signal
33
- // when they are its sole listener, so simply staying out of the way is not
34
- // enough — the signal has to arrive once more without us.)
35
- uninstall();
36
- process.kill(process.pid, signal);
37
- }
38
- function install() {
39
- if (installed)
40
- return;
41
- installed = true;
42
- process.on("exit", runPending);
43
- for (const signal of SIGNALS)
44
- process.on(signal, onSignal);
45
- }
46
- /** Leave the host process's signal handling untouched whenever nothing is in flight. */
47
- function uninstall() {
48
- if (!installed)
49
- return;
50
- installed = false;
51
- process.removeListener("exit", runPending);
52
- for (const signal of SIGNALS)
53
- process.removeListener(signal, onSignal);
54
- }
55
- /** Keep `item` pending until the returned function is called. */
56
- function track(pending, item) {
57
- pending.add(item);
58
- install();
59
- return () => {
60
- pending.delete(item);
61
- if (pendingGroups.size === 0 && pendingDirs.size === 0)
62
- uninstall();
63
- };
64
- }
65
- /**
66
- * Register a process group this process started: if this process ends before
67
- * the returned function is called, the group is stopped (see stopGroupsOnExit).
68
- */
69
- export function stopWithThisProcess(pgid) {
70
- return track(pendingGroups, pgid);
71
- }
72
- /**
73
- * Register a temp directory this process created: if this process ends before
74
- * the returned function is called, the directory is removed.
75
- */
76
- export function removeWithThisProcess(dir) {
77
- return track(pendingDirs, dir);
78
- }
79
- /** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
80
- export function removeTempDir(dir) {
81
- try {
82
- rmSync(dir, { recursive: true, force: true });
83
- }
84
- catch { /* left for the OS to reap */ }
85
- }