@trama-dev/runtime 0.4.0 → 0.6.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.
- package/README.md +4 -3
- package/dist/abort.d.ts +12 -0
- package/dist/abort.js +31 -0
- package/dist/agent-backend.d.ts +127 -7
- package/dist/agent-backend.js +38 -19
- package/dist/agent-host.d.ts +50 -0
- package/dist/agent-host.js +97 -0
- package/dist/agent-hosts.d.ts +14 -0
- package/dist/agent-hosts.js +321 -0
- package/dist/agent.d.ts +26 -3
- package/dist/agent.js +165 -43
- package/dist/bridge-client.d.ts +6 -0
- package/dist/bridge-client.js +69 -16
- package/dist/budget.d.ts +52 -0
- package/dist/budget.js +118 -0
- package/dist/child-process.d.ts +18 -0
- package/dist/child-process.js +38 -9
- package/dist/client.d.ts +2 -1
- package/dist/client.js +9 -19
- package/dist/context.d.ts +36 -7
- package/dist/context.js +83 -92
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +2 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.js +254 -88
- package/dist/ipc-server.d.ts +14 -5
- package/dist/ipc-server.js +174 -144
- package/dist/journal-view.d.ts +2 -0
- package/dist/journal-view.js +52 -7
- package/dist/journal.d.ts +27 -9
- package/dist/journal.js +216 -79
- package/dist/meta.d.ts +18 -0
- package/dist/meta.js +29 -0
- package/dist/model-relay.d.ts +130 -0
- package/dist/model-relay.js +339 -0
- package/dist/path-guard.d.ts +128 -19
- package/dist/path-guard.js +384 -68
- package/dist/pi-adapter.d.ts +35 -9
- package/dist/pi-adapter.js +865 -66
- package/dist/replace-file.d.ts +31 -0
- package/dist/replace-file.js +75 -0
- package/dist/runner-types.d.ts +35 -0
- package/dist/runner.d.ts +202 -30
- package/dist/runner.js +949 -273
- package/dist/serializable.d.ts +10 -4
- package/dist/serializable.js +56 -31
- package/dist/stopping.d.ts +37 -3
- package/dist/stopping.js +167 -21
- package/dist/tools.d.ts +2 -1
- package/dist/tools.js +90 -21
- package/dist/tree.d.ts +241 -0
- package/dist/tree.js +1431 -0
- package/dist/types.d.ts +106 -15
- package/dist/workspace.d.ts +7 -0
- package/dist/workspace.js +93 -104
- package/package.json +1 -1
package/dist/serializable.d.ts
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Recursively check that a value is strictly JSON-serializable.
|
|
3
3
|
* Throws TypeError with the path to the offending value.
|
|
4
|
-
*
|
|
5
|
-
* Uses a stack (ancestor chain) instead of a flat set so that shared-but-
|
|
6
|
-
* non-circular structures like { a: shared, b: shared } pass validation.
|
|
7
4
|
*/
|
|
8
|
-
export declare function assertSerializable(value: unknown, path: string
|
|
5
|
+
export declare function assertSerializable(value: unknown, path: string): void;
|
|
6
|
+
/** What a parsed JSON value is, for saying what was found where an object was expected. */
|
|
7
|
+
export declare const describeJson: (value: unknown) => string;
|
|
8
|
+
export declare const isJsonObject: (value: unknown) => value is Record<string, unknown>;
|
|
9
|
+
/**
|
|
10
|
+
* Log data as a log line will hold it: what JSON makes of it — or, where JSON
|
|
11
|
+
* can make nothing of it (a circular reference, a BigInt), a note that says
|
|
12
|
+
* so. A log call does not fail over what it was handed.
|
|
13
|
+
*/
|
|
14
|
+
export declare function toLogData(data: unknown): unknown;
|
package/dist/serializable.js
CHANGED
|
@@ -1,41 +1,66 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Recursively check that a value is strictly JSON-serializable.
|
|
3
3
|
* Throws TypeError with the path to the offending value.
|
|
4
|
-
*
|
|
5
|
-
* Uses a stack (ancestor chain) instead of a flat set so that shared-but-
|
|
6
|
-
* non-circular structures like { a: shared, b: shared } pass validation.
|
|
7
4
|
*/
|
|
8
|
-
export function assertSerializable(value, path
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
5
|
+
export function assertSerializable(value, path) {
|
|
6
|
+
// The objects on the way down to the value being checked. An ancestor chain
|
|
7
|
+
// rather than a set of everything seen, so that a structure that is shared
|
|
8
|
+
// but not circular — { a: shared, b: shared } — passes.
|
|
9
|
+
const ancestors = new Set();
|
|
10
|
+
const check = (value, path) => {
|
|
11
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
12
|
+
return;
|
|
13
|
+
if (typeof value === "number") {
|
|
14
|
+
if (!Number.isFinite(value))
|
|
15
|
+
throw new TypeError(`${path} is not JSON-serializable (${value})`);
|
|
16
|
+
return;
|
|
15
17
|
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
18
|
+
if (typeof value !== "object") {
|
|
19
|
+
throw new TypeError(`${path} is not JSON-serializable (${typeof value})`);
|
|
20
|
+
}
|
|
21
|
+
if (ancestors.has(value)) {
|
|
22
|
+
throw new TypeError(`${path} contains a circular reference`);
|
|
23
|
+
}
|
|
24
|
+
ancestors.add(value);
|
|
25
|
+
if (Array.isArray(value)) {
|
|
26
|
+
for (let i = 0; i < value.length; i++)
|
|
27
|
+
check(value[i], `${path}[${i}]`);
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
const proto = Object.getPrototypeOf(value);
|
|
31
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
32
|
+
const name = value.constructor?.name ?? "unknown";
|
|
33
|
+
throw new TypeError(`${path} is not a plain object (${name})`);
|
|
34
|
+
}
|
|
35
|
+
for (const [k, v] of Object.entries(value))
|
|
36
|
+
check(v, `${path}.${k}`);
|
|
28
37
|
}
|
|
29
38
|
ancestors.delete(value);
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
39
|
+
};
|
|
40
|
+
check(value, path);
|
|
41
|
+
}
|
|
42
|
+
/** What a parsed JSON value is, for saying what was found where an object was expected. */
|
|
43
|
+
export const describeJson = (value) => Array.isArray(value) ? "an array" : value === null ? "null" : typeof value;
|
|
44
|
+
export const isJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
45
|
+
/**
|
|
46
|
+
* Log data as a log line will hold it: what JSON makes of it — or, where JSON
|
|
47
|
+
* can make nothing of it (a circular reference, a BigInt), a note that says
|
|
48
|
+
* so. A log call does not fail over what it was handed.
|
|
49
|
+
*/
|
|
50
|
+
export function toLogData(data) {
|
|
51
|
+
try {
|
|
52
|
+
const text = JSON.stringify(data);
|
|
53
|
+
return text === undefined ? undefined : JSON.parse(text);
|
|
36
54
|
}
|
|
37
|
-
|
|
38
|
-
|
|
55
|
+
catch {
|
|
56
|
+
let described;
|
|
57
|
+
// An object with no prototype cannot even be turned into text.
|
|
58
|
+
try {
|
|
59
|
+
described = String(data);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
described = Object.prototype.toString.call(data);
|
|
63
|
+
}
|
|
64
|
+
return { __trama_unserializable: described };
|
|
39
65
|
}
|
|
40
|
-
ancestors.delete(value);
|
|
41
66
|
}
|
package/dist/stopping.d.ts
CHANGED
|
@@ -1,9 +1,40 @@
|
|
|
1
|
+
/** How long what was asked to stop gets to do so: a process group after SIGTERM, before it is sent SIGKILL; a backend's call after it was cancelled, before the run goes on without it. */
|
|
2
|
+
export declare const KILL_GRACE_MS = 5000;
|
|
1
3
|
/**
|
|
2
4
|
* Send a signal to a whole process group. Children spawned with `detached: true`
|
|
3
5
|
* 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
|
|
6
|
+
* Signal 0 only probes. Returns false if the group no longer exists — or
|
|
7
|
+
* holds nothing that can be signalled, which is the same to one who means to
|
|
8
|
+
* stop it. (macOS says so of a group whose last members have exited and are
|
|
9
|
+
* yet to be reaped; to wait for such a group is to wait for nothing.)
|
|
5
10
|
*/
|
|
6
11
|
export declare function signalGroup(pgid: number, signal: NodeJS.Signals | 0): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* What Linux says of its processes — each its id, its parent's and its
|
|
14
|
+
* group's — in files: there is nothing to start to learn it, and nothing that
|
|
15
|
+
* may be missing (a container often has no `ps`). Nothing, where there are no
|
|
16
|
+
* such files — or where they are not of the processes whoever asks is among:
|
|
17
|
+
* a container may have another's files before it, and a number read there
|
|
18
|
+
* is nobody's here. So the files are taken at their word only where they say
|
|
19
|
+
* of the asker (`self`) what it knows of itself: whose child it is (`parent`).
|
|
20
|
+
*
|
|
21
|
+
* It runs in two processes, here and in the watchdog, which is handed its
|
|
22
|
+
* text: it may use nothing but its arguments. So may the two that follow.
|
|
23
|
+
*/
|
|
24
|
+
export declare function processesOnFile(fs: Pick<typeof import("fs"), "readdirSync" | "readFileSync">, self: number, parent: number): number[][];
|
|
25
|
+
/**
|
|
26
|
+
* The process groups of everything a process has under it, as the system has
|
|
27
|
+
* them at this moment — but for the group it leads, and this process's own.
|
|
28
|
+
* A process may start what it starts in groups of their own (pi does so with
|
|
29
|
+
* what an agent runs, and with an MCP server): the group it leads does not
|
|
30
|
+
* hold those, and once it is gone nothing says any more whose they were.
|
|
31
|
+
* (What has cut itself loose of its parent by then is nobody's to find; and
|
|
32
|
+
* where the system cannot be asked — it has no such files, and no `ps` that
|
|
33
|
+
* answers in a while — nothing is found.) Whoever asks is not held while a
|
|
34
|
+
* `ps` answers: it is asked of what is still there, and is to be stopped
|
|
35
|
+
* after.
|
|
36
|
+
*/
|
|
37
|
+
export declare function groupsUnder(pid: number): Promise<number[]>;
|
|
7
38
|
/**
|
|
8
39
|
* Make sure there is a watchdog before anything is started that would need
|
|
9
40
|
* one. Throws if one cannot be started: running without it would mean leaving
|
|
@@ -12,9 +43,12 @@ export declare function signalGroup(pgid: number, signal: NodeJS.Signals | 0): b
|
|
|
12
43
|
export declare function requireWatchdog(): void;
|
|
13
44
|
/**
|
|
14
45
|
* Register a process group this process started: if this process ends before
|
|
15
|
-
* the returned function is called, the group is stopped.
|
|
46
|
+
* the returned function is called, the group is stopped. `withWhatIsUnder`:
|
|
47
|
+
* and so is what its leader has under it in groups of their own — for a
|
|
48
|
+
* process whose children are nobody's to keep (an agent's host; not a
|
|
49
|
+
* program, which may start what is to outlive it).
|
|
16
50
|
*/
|
|
17
|
-
export declare function stopWithThisProcess(pgid: number): () => void;
|
|
51
|
+
export declare function stopWithThisProcess(pgid: number, withWhatIsUnder?: boolean): () => void;
|
|
18
52
|
/**
|
|
19
53
|
* Register a temp directory this process created: if this process ends before
|
|
20
54
|
* the returned function is called, the directory is removed — once the groups
|
package/dist/stopping.js
CHANGED
|
@@ -22,17 +22,20 @@
|
|
|
22
22
|
//
|
|
23
23
|
// Nothing here listens for a signal or for the process exiting: the process
|
|
24
24
|
// that hosts a runner keeps its own way of handling both.
|
|
25
|
-
import { spawn } from "child_process";
|
|
26
|
-
import
|
|
27
|
-
/** How long
|
|
28
|
-
const KILL_GRACE_MS = 5000;
|
|
25
|
+
import { execFile, spawn } from "child_process";
|
|
26
|
+
import * as fs from "fs";
|
|
27
|
+
/** How long what was asked to stop gets to do so: a process group after SIGTERM, before it is sent SIGKILL; a backend's call after it was cancelled, before the run goes on without it. */
|
|
28
|
+
export const KILL_GRACE_MS = 5000;
|
|
29
29
|
const STOP_POLL_MS = 25;
|
|
30
30
|
/** How long a group is waited for after SIGKILL before it is given up on. */
|
|
31
31
|
const KILL_SETTLE_MS = 1000;
|
|
32
32
|
/**
|
|
33
33
|
* Send a signal to a whole process group. Children spawned with `detached: true`
|
|
34
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
|
|
35
|
+
* Signal 0 only probes. Returns false if the group no longer exists — or
|
|
36
|
+
* holds nothing that can be signalled, which is the same to one who means to
|
|
37
|
+
* stop it. (macOS says so of a group whose last members have exited and are
|
|
38
|
+
* yet to be reaped; to wait for such a group is to wait for nothing.)
|
|
36
39
|
*/
|
|
37
40
|
export function signalGroup(pgid, signal) {
|
|
38
41
|
try {
|
|
@@ -43,15 +46,146 @@ export function signalGroup(pgid, signal) {
|
|
|
43
46
|
return false;
|
|
44
47
|
}
|
|
45
48
|
}
|
|
49
|
+
/** How long the system is given to say what processes there are. */
|
|
50
|
+
const PROCESSES_ASKED_MS = 2_000;
|
|
51
|
+
/**
|
|
52
|
+
* What Linux says of its processes — each its id, its parent's and its
|
|
53
|
+
* group's — in files: there is nothing to start to learn it, and nothing that
|
|
54
|
+
* may be missing (a container often has no `ps`). Nothing, where there are no
|
|
55
|
+
* such files — or where they are not of the processes whoever asks is among:
|
|
56
|
+
* a container may have another's files before it, and a number read there
|
|
57
|
+
* is nobody's here. So the files are taken at their word only where they say
|
|
58
|
+
* of the asker (`self`) what it knows of itself: whose child it is (`parent`).
|
|
59
|
+
*
|
|
60
|
+
* It runs in two processes, here and in the watchdog, which is handed its
|
|
61
|
+
* text: it may use nothing but its arguments. So may the two that follow.
|
|
62
|
+
*/
|
|
63
|
+
export function processesOnFile(fs, self, parent) {
|
|
64
|
+
const rows = [];
|
|
65
|
+
let names;
|
|
66
|
+
try {
|
|
67
|
+
names = fs.readdirSync("/proc");
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return rows;
|
|
71
|
+
}
|
|
72
|
+
for (const name of names) {
|
|
73
|
+
if (!/^[0-9]+$/.test(name))
|
|
74
|
+
continue;
|
|
75
|
+
try {
|
|
76
|
+
// "id (name) state parent group …": a name may hold anything, a ")" and a space among it —
|
|
77
|
+
// what follows the last ")" is what is told apart by spaces.
|
|
78
|
+
const stat = fs.readFileSync("/proc/" + name + "/stat", "utf8");
|
|
79
|
+
const after = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
80
|
+
const row = [Number(name), Number(after[1]), Number(after[2])];
|
|
81
|
+
if (row.every(Number.isInteger))
|
|
82
|
+
rows.push(row);
|
|
83
|
+
}
|
|
84
|
+
catch { /* gone since it was listed */ }
|
|
85
|
+
}
|
|
86
|
+
return rows.some(row => row[0] === self && row[1] === parent) ? rows : [];
|
|
87
|
+
}
|
|
88
|
+
/** The same, of what `ps -Ao pid=,ppid=,pgid=` printed. */
|
|
89
|
+
function processesListed(listed) {
|
|
90
|
+
return listed.split("\n").map(line => line.trim().split(/\s+/).map(Number)).filter(row => row.length === 3 && row.every(Number.isInteger));
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Of such rows, the process groups of everything one process has under it —
|
|
94
|
+
* but for the group it leads, and that of whoever asks (`self`).
|
|
95
|
+
*/
|
|
96
|
+
function groupsAmong(rows, pid, self) {
|
|
97
|
+
const under = new Set([pid]);
|
|
98
|
+
for (let grew = true; grew;) {
|
|
99
|
+
grew = false;
|
|
100
|
+
for (const row of rows) {
|
|
101
|
+
if (under.has(row[1]) && !under.has(row[0])) {
|
|
102
|
+
under.add(row[0]);
|
|
103
|
+
grew = true;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const own = rows.find(row => row[0] === self);
|
|
108
|
+
const groups = new Set(rows.filter(row => under.has(row[0])).map(row => row[2]));
|
|
109
|
+
return [...groups].filter(group => group !== pid && !(own && group === own[2]));
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The process groups of everything a process has under it, as the system has
|
|
113
|
+
* them at this moment — but for the group it leads, and this process's own.
|
|
114
|
+
* A process may start what it starts in groups of their own (pi does so with
|
|
115
|
+
* what an agent runs, and with an MCP server): the group it leads does not
|
|
116
|
+
* hold those, and once it is gone nothing says any more whose they were.
|
|
117
|
+
* (What has cut itself loose of its parent by then is nobody's to find; and
|
|
118
|
+
* where the system cannot be asked — it has no such files, and no `ps` that
|
|
119
|
+
* answers in a while — nothing is found.) Whoever asks is not held while a
|
|
120
|
+
* `ps` answers: it is asked of what is still there, and is to be stopped
|
|
121
|
+
* after.
|
|
122
|
+
*/
|
|
123
|
+
export async function groupsUnder(pid) {
|
|
124
|
+
let rows = processesOnFile(fs, process.pid, process.ppid);
|
|
125
|
+
if (rows.length === 0) {
|
|
126
|
+
rows = processesListed(await new Promise((resolve) => {
|
|
127
|
+
execFile("ps", ["-Ao", "pid=,ppid=,pgid="], { encoding: "utf-8", timeout: PROCESSES_ASKED_MS, killSignal: "SIGKILL" }, (err, stdout) => resolve(err ? "" : stdout));
|
|
128
|
+
}));
|
|
129
|
+
}
|
|
130
|
+
return groupsAmong(rows, pid, process.pid);
|
|
131
|
+
}
|
|
132
|
+
// --- Removing what was made ---
|
|
133
|
+
/**
|
|
134
|
+
* Remove a directory tree, whatever has been done to it since it was made. A
|
|
135
|
+
* tree with a directory in it that may not be written to — a copy of a project
|
|
136
|
+
* that has one, or one a program made so — cannot be emptied as it stands; so
|
|
137
|
+
* where removing it fails, its directories are opened first.
|
|
138
|
+
*
|
|
139
|
+
* It runs in two processes, here and in the watchdog, which is handed its
|
|
140
|
+
* text: it may use nothing but its arguments.
|
|
141
|
+
*/
|
|
142
|
+
function removeTree(fs, dir) {
|
|
143
|
+
const remove = () => fs.rmSync(dir, { recursive: true, force: true });
|
|
144
|
+
try {
|
|
145
|
+
return remove();
|
|
146
|
+
}
|
|
147
|
+
catch { /* opened below, and tried once more */ }
|
|
148
|
+
const open = (at) => {
|
|
149
|
+
try {
|
|
150
|
+
fs.chmodSync(at, 0o700);
|
|
151
|
+
for (const entry of fs.readdirSync(at, { withFileTypes: true })) {
|
|
152
|
+
if (entry.isDirectory())
|
|
153
|
+
open(at + "/" + entry.name); // not a link to one: only this tree is touched
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
catch { /* what cannot be opened stays as it is */ }
|
|
157
|
+
};
|
|
158
|
+
open(dir);
|
|
159
|
+
try {
|
|
160
|
+
remove();
|
|
161
|
+
}
|
|
162
|
+
catch { /* left for the OS to reap */ }
|
|
163
|
+
}
|
|
46
164
|
// --- The watchdog ---
|
|
47
165
|
// Run by the watchdog process: the same policy as stopGroups below. A group
|
|
48
166
|
// the runner had already asked to stop is not asked a second time.
|
|
49
167
|
const WATCHDOG = `
|
|
50
|
-
const
|
|
51
|
-
const {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
168
|
+
const fs = require("fs");
|
|
169
|
+
const { execFileSync } = require("child_process");
|
|
170
|
+
${removeTree}
|
|
171
|
+
${signalGroup}
|
|
172
|
+
${processesOnFile}
|
|
173
|
+
${processesListed}
|
|
174
|
+
${groupsAmong}
|
|
175
|
+
const { grace, settle, poll, asking } = JSON.parse(process.argv[1]);
|
|
176
|
+
const lists = { g: new Set(), d: new Set(), asked: new Set(), u: new Set() };
|
|
177
|
+
// What the system says of its processes: by its files, or by ps — which this process can wait for.
|
|
178
|
+
const processes = () => {
|
|
179
|
+
const rows = processesOnFile(fs, process.pid, process.ppid);
|
|
180
|
+
if (rows.length > 0) return rows;
|
|
181
|
+
try {
|
|
182
|
+
return processesListed(execFileSync("ps", ["-Ao", "pid=,ppid=,pgid="], { encoding: "utf8", timeout: asking, killSignal: "SIGKILL", stdio: ["ignore", "pipe", "ignore"] }));
|
|
183
|
+
} catch {
|
|
184
|
+
return [];
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
const alive = (pgid) => signalGroup(pgid, 0);
|
|
188
|
+
const signal = signalGroup;
|
|
55
189
|
|
|
56
190
|
let unread = "";
|
|
57
191
|
process.stdin.setEncoding("utf8");
|
|
@@ -69,10 +203,15 @@ const takeOver = () => {
|
|
|
69
203
|
if (leaving) return;
|
|
70
204
|
leaving = true;
|
|
71
205
|
const finish = () => {
|
|
72
|
-
for (const dir of lists.d)
|
|
206
|
+
for (const dir of lists.d) removeTree(fs, dir);
|
|
73
207
|
process.exit(0);
|
|
74
208
|
};
|
|
75
|
-
|
|
209
|
+
// A group that is to be stopped with what is under it: what it started in groups of their own is
|
|
210
|
+
// looked for now, while it is there to be asked of — it may not be able to end them itself.
|
|
211
|
+
const led = [...lists.u].filter(alive);
|
|
212
|
+
const rows = led.length > 0 ? processes() : [];
|
|
213
|
+
const below = led.flatMap((pid) => groupsAmong(rows, pid, process.pid));
|
|
214
|
+
let left = [...new Set([...lists.g, ...below])].filter(alive);
|
|
76
215
|
for (const pgid of left) { if (!lists.asked.has(pgid)) signal(pgid, "SIGTERM"); }
|
|
77
216
|
let deadline = performance.now() + grace;
|
|
78
217
|
let killed = false;
|
|
@@ -94,7 +233,7 @@ process.stdin.on("close", takeOver);
|
|
|
94
233
|
process.stdin.on("error", takeOver);
|
|
95
234
|
`;
|
|
96
235
|
/** 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() };
|
|
236
|
+
const listed = { g: new Set(), d: new Set(), asked: new Set(), u: new Set() };
|
|
98
237
|
let watchdog = null;
|
|
99
238
|
const tell = (to, op, list, item) => {
|
|
100
239
|
to.stdin?.write(JSON.stringify([op, list, item]) + "\n");
|
|
@@ -109,10 +248,14 @@ function startWatchdog() {
|
|
|
109
248
|
return watchdog;
|
|
110
249
|
let child;
|
|
111
250
|
try {
|
|
112
|
-
const timings = { grace: KILL_GRACE_MS, settle: KILL_SETTLE_MS, poll: STOP_POLL_MS };
|
|
251
|
+
const timings = { grace: KILL_GRACE_MS, settle: KILL_SETTLE_MS, poll: STOP_POLL_MS, asking: PROCESSES_ASKED_MS };
|
|
252
|
+
// It is this file's own few lines, and is to start whatever this process was started with:
|
|
253
|
+
// not with what NODE_OPTIONS would have it load first, or wait for (a debugger, say).
|
|
254
|
+
const { NODE_OPTIONS: _options, ...env } = process.env;
|
|
113
255
|
child = spawn(process.execPath, ["-e", WATCHDOG, JSON.stringify(timings)], {
|
|
114
256
|
detached: true, // a signal sent to this process's group must not reach it
|
|
115
257
|
stdio: ["pipe", "ignore", "ignore"],
|
|
258
|
+
env,
|
|
116
259
|
});
|
|
117
260
|
}
|
|
118
261
|
catch {
|
|
@@ -129,7 +272,7 @@ function startWatchdog() {
|
|
|
129
272
|
child.unref();
|
|
130
273
|
child.stdin?.unref?.();
|
|
131
274
|
watchdog = child;
|
|
132
|
-
for (const name of ["g", "d", "asked"]) {
|
|
275
|
+
for (const name of ["g", "d", "asked", "u"]) {
|
|
133
276
|
for (const item of listed[name])
|
|
134
277
|
tell(child, "+", name, item);
|
|
135
278
|
}
|
|
@@ -159,13 +302,19 @@ function delist(from, item) {
|
|
|
159
302
|
}
|
|
160
303
|
/**
|
|
161
304
|
* Register a process group this process started: if this process ends before
|
|
162
|
-
* the returned function is called, the group is stopped.
|
|
305
|
+
* the returned function is called, the group is stopped. `withWhatIsUnder`:
|
|
306
|
+
* and so is what its leader has under it in groups of their own — for a
|
|
307
|
+
* process whose children are nobody's to keep (an agent's host; not a
|
|
308
|
+
* program, which may start what is to outlive it).
|
|
163
309
|
*/
|
|
164
|
-
export function stopWithThisProcess(pgid) {
|
|
310
|
+
export function stopWithThisProcess(pgid, withWhatIsUnder = false) {
|
|
165
311
|
enlist("g", pgid);
|
|
312
|
+
if (withWhatIsUnder)
|
|
313
|
+
enlist("u", pgid);
|
|
166
314
|
return () => {
|
|
167
315
|
delist("g", pgid);
|
|
168
316
|
delist("asked", pgid);
|
|
317
|
+
delist("u", pgid);
|
|
169
318
|
};
|
|
170
319
|
}
|
|
171
320
|
/**
|
|
@@ -179,10 +328,7 @@ export function removeWithThisProcess(dir) {
|
|
|
179
328
|
}
|
|
180
329
|
/** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
|
|
181
330
|
export function removeTempDir(dir) {
|
|
182
|
-
|
|
183
|
-
rmSync(dir, { recursive: true, force: true });
|
|
184
|
-
}
|
|
185
|
-
catch { /* left for the OS to reap */ }
|
|
331
|
+
removeTree(fs, dir);
|
|
186
332
|
}
|
|
187
333
|
// --- Stopping, while this process is there to see it through ---
|
|
188
334
|
/** Groups this process has asked to stop and is still watching. */
|
package/dist/tools.d.ts
CHANGED
|
@@ -3,4 +3,5 @@ export interface ToolsWithCleanup extends Tools {
|
|
|
3
3
|
/** Stop every shell command still running, and anything they left in the background. Resolves when they are gone. */
|
|
4
4
|
stopActiveShells(): Promise<void>;
|
|
5
5
|
}
|
|
6
|
-
|
|
6
|
+
/** `env` is the variables the run was started with, over the runner's own: every shell command has them. */
|
|
7
|
+
export declare function createTools(projectDir: string, signal?: AbortSignal, env?: Record<string, string>): ToolsWithCleanup;
|
package/dist/tools.js
CHANGED
|
@@ -1,13 +1,38 @@
|
|
|
1
1
|
import { spawn } from "child_process";
|
|
2
|
-
import { readFileSync,
|
|
3
|
-
import { resolve, dirname } from "path";
|
|
4
|
-
import { guardPath } from "./path-guard.js";
|
|
5
|
-
import { superviseChild } from "./child-process.js";
|
|
2
|
+
import { accessSync, constants, readFileSync, statSync, writeFileSync } from "fs";
|
|
3
|
+
import { delimiter, resolve, dirname } from "path";
|
|
4
|
+
import { guardPath, makeDirsIn, projectAt, realRootOf } from "./path-guard.js";
|
|
5
|
+
import { checkedEnv, superviseChild } from "./child-process.js";
|
|
6
|
+
import { messageOf } from "./errors.js";
|
|
6
7
|
import { signalGroup, stopGroups, stopWithThisProcess } from "./stopping.js";
|
|
7
8
|
const MAX_FETCH_BODY = 10 * 1024 * 1024; // 10 MB
|
|
8
9
|
const DEFAULT_SHELL_TIMEOUT = 30_000;
|
|
9
10
|
const GROUP_SWEEP_MS = 250;
|
|
10
|
-
|
|
11
|
+
/**
|
|
12
|
+
* The shell a command is run by: the `sh` that `path` — the runner's own
|
|
13
|
+
* PATH — leads to from where the command runs. Not the one a PATH given for
|
|
14
|
+
* the command would lead to: that PATH is for what the command runs, and one
|
|
15
|
+
* without a shell on it, or with something else of the name, is the
|
|
16
|
+
* command's affair. (Where none is found, the system is left to say so. A
|
|
17
|
+
* runner that has no PATH at all has the system's own, as it would have for
|
|
18
|
+
* anything it started.)
|
|
19
|
+
*/
|
|
20
|
+
function shellOn(path, cwd) {
|
|
21
|
+
if (process.platform === "win32")
|
|
22
|
+
return "sh";
|
|
23
|
+
for (const dir of (path ?? "/usr/bin:/bin").split(delimiter)) {
|
|
24
|
+
const at = resolve(cwd, dir, "sh");
|
|
25
|
+
try {
|
|
26
|
+
accessSync(at, constants.X_OK);
|
|
27
|
+
if (statSync(at).isFile())
|
|
28
|
+
return at;
|
|
29
|
+
}
|
|
30
|
+
catch { /* not there, or not to be run: the next */ }
|
|
31
|
+
}
|
|
32
|
+
return "sh";
|
|
33
|
+
}
|
|
34
|
+
/** `env` is the variables the run was started with, over the runner's own: every shell command has them. */
|
|
35
|
+
export function createTools(projectDir, signal, env) {
|
|
11
36
|
const normalizedProjectDir = resolve(projectDir);
|
|
12
37
|
// Each shell command leads its own process group, so background processes it
|
|
13
38
|
// starts stay killable after the shell itself exits. A group is tracked from
|
|
@@ -27,7 +52,8 @@ export function createTools(projectDir, signal) {
|
|
|
27
52
|
// and update still do when a program calls them. (This covers tools.shell
|
|
28
53
|
// only: what the agent backend runs on its own takes its environment from
|
|
29
54
|
// this process.)
|
|
30
|
-
const { TRAMA_PORT: _port, TRAMA_INIT: _init, ...
|
|
55
|
+
const { TRAMA_PORT: _port, TRAMA_INIT: _init, ...runnersOwn } = process.env;
|
|
56
|
+
const shellEnv = { ...runnersOwn, ...env };
|
|
31
57
|
const stopSweeping = () => {
|
|
32
58
|
if (sweeper)
|
|
33
59
|
clearInterval(sweeper);
|
|
@@ -78,18 +104,36 @@ export function createTools(projectDir, signal) {
|
|
|
78
104
|
},
|
|
79
105
|
async write(path, content) {
|
|
80
106
|
const target = guardPath(normalizedProjectDir, path); // before mkdir — no side effects outside the project
|
|
81
|
-
|
|
107
|
+
// (Asked to write the project itself, the system refuses a directory. Where the project is gone it is refused
|
|
108
|
+
// either way, as any write is: this only says of the project what is otherwise said of "the directory".)
|
|
109
|
+
if (target === realRootOf(normalizedProjectDir))
|
|
110
|
+
projectAt(normalizedProjectDir);
|
|
111
|
+
makeDirsIn(normalizedProjectDir, dirname(target));
|
|
82
112
|
writeFileSync(target, content);
|
|
83
113
|
},
|
|
84
114
|
async shell(command, options = {}) {
|
|
85
115
|
const cwd = options.cwd ? guardPath(normalizedProjectDir, options.cwd) : normalizedProjectDir;
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
116
|
+
const env = options.env == null ? shellEnv : { ...shellEnv, ...checkedEnv(options.env) };
|
|
117
|
+
// The shell is started from where the runner finds it, and is `sh` to itself and to whoever it tells of
|
|
118
|
+
// itself, as it was when the system did the finding: in "$0", in what it says of a command it cannot find,
|
|
119
|
+
// and in what is said of a shell that could not be started.
|
|
120
|
+
const shell = shellOn(runnersOwn.PATH, cwd);
|
|
121
|
+
const notStarted = (why) => ({ exitCode: 1, stdout: "", stderr: messageOf(why).replace(`spawn ${shell} `, "spawn sh ") });
|
|
122
|
+
let child;
|
|
123
|
+
try {
|
|
124
|
+
child = spawn(shell, ["-c", command], {
|
|
125
|
+
cwd,
|
|
126
|
+
env,
|
|
127
|
+
argv0: "sh",
|
|
128
|
+
// Nothing is ever sent to a command: one that reads its input finds it at an end, rather than waiting.
|
|
129
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
130
|
+
detached: true,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
catch (spawnError) {
|
|
134
|
+
// Refused by the system outright (more than it will hand a process, say) — a result, like any failure to start.
|
|
135
|
+
return notStarted(spawnError);
|
|
136
|
+
}
|
|
93
137
|
const pgid = child.pid;
|
|
94
138
|
if (pgid) {
|
|
95
139
|
groups.set(pgid, { shellExited: false, forget: stopWithThisProcess(pgid) });
|
|
@@ -106,9 +150,7 @@ export function createTools(projectDir, signal) {
|
|
|
106
150
|
}
|
|
107
151
|
catch (spawnError) {
|
|
108
152
|
// Failed to start (e.g. cwd does not exist) — a result, not an exception.
|
|
109
|
-
|
|
110
|
-
untrack(pgid);
|
|
111
|
-
return { exitCode: 1, stdout: "", stderr: spawnError.message };
|
|
153
|
+
return notStarted(spawnError);
|
|
112
154
|
}
|
|
113
155
|
},
|
|
114
156
|
async fetch(url, options = {}) {
|
|
@@ -118,10 +160,37 @@ export function createTools(projectDir, signal) {
|
|
|
118
160
|
body: options.body,
|
|
119
161
|
signal,
|
|
120
162
|
});
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
163
|
+
let body;
|
|
164
|
+
if (response.body) {
|
|
165
|
+
const reader = response.body.getReader();
|
|
166
|
+
const decoder = new TextDecoder("utf-8");
|
|
167
|
+
let text = "";
|
|
168
|
+
let truncated = false;
|
|
169
|
+
try {
|
|
170
|
+
for (;;) {
|
|
171
|
+
const { done, value } = await reader.read();
|
|
172
|
+
if (done)
|
|
173
|
+
break;
|
|
174
|
+
text += decoder.decode(value, { stream: true });
|
|
175
|
+
if (text.length > MAX_FETCH_BODY) {
|
|
176
|
+
truncated = true;
|
|
177
|
+
await reader.cancel();
|
|
178
|
+
break;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (!truncated)
|
|
182
|
+
text += decoder.decode();
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
reader.releaseLock();
|
|
186
|
+
}
|
|
187
|
+
body = truncated
|
|
188
|
+
? text.slice(0, MAX_FETCH_BODY) + "\n[trama] response body truncated at 10MB"
|
|
189
|
+
: text;
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
body = ""; // (an answer that has no body: to a HEAD, say)
|
|
193
|
+
}
|
|
125
194
|
const headers = {};
|
|
126
195
|
response.headers.forEach((v, k) => { headers[k] = v; });
|
|
127
196
|
return { status: response.status, body, headers };
|