@omercnet/paseo-pr-radar 3.3.0-next.533.1 → 3.3.0-next.534.1
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 +1 -1
- package/index.server.ts +12 -2
- package/package.json +1 -1
- package/server/routing-script.ts +502 -0
- package/server/workspace-ops.ts +5 -233
package/README.md
CHANGED
|
@@ -36,7 +36,7 @@ DevTools before capture. Both PNGs come from an isolated Paseo test daemon at 2
|
|
|
36
36
|
- `Start New Agent`: available on every PR (orange when a local checkout/worktree exists, brown when `CWD-TBD` and a clone or directory pick is needed). Opens an interactive directory/worktree chooser (supporting incremental typing, GUI selection, `CWD-WORKTREE` vs `CWD-BASE`, and one-click clone + worktree creation), or launches immediately when configured in Settings.
|
|
37
37
|
- `Open Existing Agent`: jumps directly to an existing linked Paseo agent.
|
|
38
38
|
- `Ask agent` / `Open workspace` / `Copy link` / `Open PR`.
|
|
39
|
-
- Settings (`PR Radar settings`): configure `sourceCodeDir` (default `~/src`), `defaultCwdMode` (`CWD-WORKTREE` or `CWD-BASE`), `autoLaunchMode` (`prompt`, `existing_only`, or `existing_or_clone`), default agent launch options (profile, provider, model, effort, mode, context mode), and an optional absolute/`~/` routing script path (copy `examples/pr-radar-route.py`, a small example of the stdin/stdout contract, to e.g. `~/.config/pr-radar/route.py` and edit it). The script path and `sourceCodeDir` are read from the saved settings on the server, never from the request. The script must be an executable regular file owned by you or root, in directories that group and others cannot write (a sticky directory such as `/tmp` is fine)
|
|
39
|
+
- Settings (`PR Radar settings`): configure `sourceCodeDir` (default `~/src`), `defaultCwdMode` (`CWD-WORKTREE` or `CWD-BASE`), `autoLaunchMode` (`prompt`, `existing_only`, or `existing_or_clone`), default agent launch options (profile, provider, model, effort, mode, context mode), and an optional absolute/`~/` routing script path (copy `examples/pr-radar-route.py`, a small example of the stdin/stdout contract, to e.g. `~/.config/pr-radar/route.py` and edit it). The script path and `sourceCodeDir` are read from the saved settings on the server, never from the request. The script must be an executable regular file owned by you or root, in directories that group and others cannot write (a sticky directory such as `/tmp` is fine). Symbolic links on the configured path are checked hop by hop: each link must be owned by you or root, and the directory holding it and that directory's parents must not be writable by group or others. The check reads owners and the classic permission bits only: it does not read macOS extended ACLs (or POSIX ACLs on Linux), so an ACL that grants another user write access to the script or one of its directories is not detected. Review `ls -le` output for such entries yourself. The script runs with a minimal environment and a fixed `PATH` (`/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`, not the daemon's), so an interpreter named with `#!/usr/bin/env` is found only there (a directory in that list is dropped if another user owns it, or if group or others can write it or one of its parents. Homebrew leaves `/opt/homebrew/bin` writable by the `admin` group on many Macs, so `#!/usr/bin/env python3` then finds the root-owned `/usr/bin/python3`. To use Homebrew's interpreter, run `chmod go-w` on `/opt/homebrew/bin` and on any parent that group or others can write; that restores the PATH entry but does not check the interpreter it links to (for example under `Cellar`). A `#!/opt/homebrew/bin/python3` line also works but skips this check: any `admin` member could replace that interpreter); name any other tool by absolute path. The interpreter a `#!` line names is not itself checked. It has a 30 second timeout (time spent waiting for an earlier call counts against it) a 1 MiB output cap, and a 1 MiB cap on the input it is sent (PR text is written by others; an oversize payload is refused and the script is not run, and the launch then goes ahead without routing). One script runs at a time: up to two more calls wait their turn, and further calls are refused while they wait (not on Windows). Its whole process group is killed as soon as the script exits, so a background process it starts does not outlive it unless it detaches itself (`setsid`). When Paseo stops, reloads or disables the plugin, the plugin's cleanup ends a script that is still running (SIGTERM, then SIGKILL after one second) and refuses calls still waiting; the script runs in its own process group, so stopping the plugin process alone would not reach it. A daemon that is killed outright (SIGKILL, a crash) never runs the cleanup, and the script then keeps running until it ends by itself, because nothing is left to time it out. It may set only the `default`, `plan`, `acceptEdits` and `read-only` permission modes and the `contextMode` option; other values are ignored and the launch notice says so. A profile it names is ignored too when that profile sets another permission mode, option or feature value. Directories outside `sourceCodeDir` are refused for clones, checkouts and worktrees. These checks are defense in depth against crafted requests, not a privilege boundary: the settings are the trust source, but any Paseo client can write them.
|
|
40
40
|
|
|
41
41
|
#### Routing script labels
|
|
42
42
|
|
package/index.server.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import type { PluginServerContext } from "@getpaseo/plugin/server";
|
|
2
|
+
import {
|
|
3
|
+
runRoutingScriptHandler,
|
|
4
|
+
startRoutingScripts,
|
|
5
|
+
stopRoutingScripts,
|
|
6
|
+
} from "./server/routing-script";
|
|
2
7
|
import {
|
|
3
8
|
acknowledgeViewerUpdates,
|
|
4
9
|
resolveViewerScope,
|
|
@@ -8,7 +13,6 @@ import {
|
|
|
8
13
|
listLocalDirsHandler,
|
|
9
14
|
prepareWorkspaceCwdHandler,
|
|
10
15
|
type ReadWorkspaceSettings,
|
|
11
|
-
runRoutingScriptHandler,
|
|
12
16
|
} from "./server/workspace-ops";
|
|
13
17
|
import { prRadarSettings } from "./shared/settings";
|
|
14
18
|
import {
|
|
@@ -20,6 +24,7 @@ import {
|
|
|
20
24
|
} from "./shared/viewer-scope";
|
|
21
25
|
|
|
22
26
|
export default function contribute(server: PluginServerContext) {
|
|
27
|
+
startRoutingScripts();
|
|
23
28
|
const settings = server.registerSettings(prRadarSettings);
|
|
24
29
|
// Directories and the routing script come from these registered settings, never from RPC input.
|
|
25
30
|
const readSettings: ReadWorkspaceSettings = async () => {
|
|
@@ -36,5 +41,10 @@ export default function contribute(server: PluginServerContext) {
|
|
|
36
41
|
server.handle(runRoutingScript, (input) => runRoutingScriptHandler(input, readSettings));
|
|
37
42
|
// Keep GitHub data warm so opening the radar never waits on gh.
|
|
38
43
|
const stop = startBackgroundRefresh();
|
|
39
|
-
|
|
44
|
+
// Cleanup runs when the daemon stops, reloads or disables the plugin; the routing script is
|
|
45
|
+
// detached from the plugin process, so it is ended here.
|
|
46
|
+
return async () => {
|
|
47
|
+
stop();
|
|
48
|
+
await stopRoutingScripts();
|
|
49
|
+
};
|
|
40
50
|
}
|
package/package.json
CHANGED
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
import { type ChildProcessByStdio, spawn } from "node:child_process";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { access, lstat, readlink, realpath, stat } from "node:fs/promises";
|
|
4
|
+
import { dirname, isAbsolute, join } from "node:path";
|
|
5
|
+
import type { Readable, Writable } from "node:stream";
|
|
6
|
+
import type { z } from "zod";
|
|
7
|
+
import { RoutingScriptResultSchema, type runRoutingScript } from "../shared/viewer-scope";
|
|
8
|
+
import {
|
|
9
|
+
allowListedEnv,
|
|
10
|
+
COMMAND_TIMEOUT_MS,
|
|
11
|
+
exists,
|
|
12
|
+
expandUserPath,
|
|
13
|
+
isAbsoluteOrHomePath,
|
|
14
|
+
type ReadWorkspaceSettings,
|
|
15
|
+
} from "./workspace-ops";
|
|
16
|
+
|
|
17
|
+
export interface RoutingScriptLimits {
|
|
18
|
+
timeoutMs: number;
|
|
19
|
+
outputBytes: number;
|
|
20
|
+
killGraceMs: number;
|
|
21
|
+
/** Largest stdin payload the script is sent; `DEFAULT_ROUTING_INPUT_BYTES` when left out. */
|
|
22
|
+
inputBytes?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The payload carries PR text (title, labels, linked issues) that another person wrote, so it has
|
|
26
|
+
// no natural bound. An oversize one is refused rather than cut: the script would otherwise route
|
|
27
|
+
// on a silently shortened record. The cap matches the output cap.
|
|
28
|
+
const DEFAULT_ROUTING_INPUT_BYTES = 1024 * 1024;
|
|
29
|
+
|
|
30
|
+
const DEFAULT_ROUTING_LIMITS: RoutingScriptLimits = {
|
|
31
|
+
timeoutMs: COMMAND_TIMEOUT_MS,
|
|
32
|
+
outputBytes: 1024 * 1024,
|
|
33
|
+
killGraceMs: 2_000,
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const STICKY_BIT = 0o1000;
|
|
37
|
+
|
|
38
|
+
// The script's PATH. The daemon's own PATH can list directories other users or tools write to
|
|
39
|
+
// (~/.local/bin, a project's node_modules/.bin), and the script's `#!/usr/bin/env interpreter` line
|
|
40
|
+
// would search it. These are the system and Homebrew directories; a script that needs a tool
|
|
41
|
+
// elsewhere should name it by absolute path. A directory is dropped at run time unless it passes the
|
|
42
|
+
// same trust check as the script's own directories (a Homebrew prefix owned by another user, or one
|
|
43
|
+
// group-writable, would let that user supply the interpreter).
|
|
44
|
+
const ROUTING_SCRIPT_PATH_DIRS = [
|
|
45
|
+
"/opt/homebrew/bin",
|
|
46
|
+
"/usr/local/bin",
|
|
47
|
+
"/usr/bin",
|
|
48
|
+
"/bin",
|
|
49
|
+
"/usr/sbin",
|
|
50
|
+
"/sbin",
|
|
51
|
+
];
|
|
52
|
+
|
|
53
|
+
export async function trustedScriptPath(
|
|
54
|
+
uid: number | undefined = process.getuid?.(),
|
|
55
|
+
dirs: readonly string[] = ROUTING_SCRIPT_PATH_DIRS,
|
|
56
|
+
// Directories whose own trust is already settled; the walk up from a PATH entry stops at them.
|
|
57
|
+
verified: Set<string> = new Set(),
|
|
58
|
+
): Promise<string> {
|
|
59
|
+
const trustedOwner = (owner: number) => uid === undefined || owner === uid || owner === 0;
|
|
60
|
+
const kept: string[] = [];
|
|
61
|
+
for (const dir of dirs) {
|
|
62
|
+
try {
|
|
63
|
+
// Strict: a sticky bit stops others deleting each other's files, not creating a `python3`.
|
|
64
|
+
// The entry may be, or sit behind, a symbolic link: every link on the way, the directory
|
|
65
|
+
// holding it and that directory's ancestors are checked, then the real directory it ends at
|
|
66
|
+
// and every real parent of that (a link into a directory under a writable parent would
|
|
67
|
+
// otherwise pass, since a walk of the entry's own parents never reaches it).
|
|
68
|
+
await assertTrustedSymlinkChain(dir, trustedOwner, verified, false);
|
|
69
|
+
await assertTrustedDirectories(dir, trustedOwner, verified, false);
|
|
70
|
+
kept.push(dir);
|
|
71
|
+
} catch {
|
|
72
|
+
// Missing, owned by another user, or writable by others: not searched.
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return kept.join(":");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
type OwnerCheck = (owner: number) => boolean;
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* `start` and every directory above it must have a trusted owner and not be group/other-writable.
|
|
82
|
+
* A sticky directory (like /tmp) is exempt from the write test unless `allowSticky` is false.
|
|
83
|
+
* `start` is resolved first, so a symbolic link is judged by the real directory it ends at and by
|
|
84
|
+
* that directory's real parents, never by the parents of the link's own spelling.
|
|
85
|
+
*/
|
|
86
|
+
async function assertTrustedDirectories(
|
|
87
|
+
start: string,
|
|
88
|
+
trustedOwner: OwnerCheck,
|
|
89
|
+
verified: Set<string>,
|
|
90
|
+
allowSticky = true,
|
|
91
|
+
): Promise<void> {
|
|
92
|
+
// Remembered as trusted only once the whole walk has passed: a directory is trustworthy only if
|
|
93
|
+
// everything above it is, so one that sat below a failure must not vouch for a later walk that
|
|
94
|
+
// reaches it (say, through a link) and stops there.
|
|
95
|
+
const passed: string[] = [];
|
|
96
|
+
for (let dir = await realpath(start); !verified.has(dir); dir = dirname(dir)) {
|
|
97
|
+
const dirInfo = await stat(dir);
|
|
98
|
+
if (!trustedOwner(dirInfo.uid)) {
|
|
99
|
+
throw new Error(
|
|
100
|
+
`Routing script directory ${dir} is owned by another user; move the script somewhere you own, or run chown on it.`,
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
if ((dirInfo.mode & 0o022) !== 0 && !(allowSticky && (dirInfo.mode & STICKY_BIT) !== 0)) {
|
|
104
|
+
throw new Error(
|
|
105
|
+
`Routing script directory ${dir} must not be writable by group or others; run chmod go-w on it.`,
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
passed.push(dir);
|
|
109
|
+
if (dirname(dir) === dir) break;
|
|
110
|
+
}
|
|
111
|
+
for (const dir of passed) verified.add(dir);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// The kernel stops following links after this many (MAXSYMLINKS is 32 on macOS, 40 on Linux).
|
|
115
|
+
const MAX_SYMLINK_HOPS = 32;
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Walks the configured path component by component, as the kernel would, without following a link
|
|
119
|
+
* blindly: every symbolic link met on the way (including links reached through another link, such
|
|
120
|
+
* as /a/l1 -> /b/l2 -> /c/file) must belong to a trusted owner, and the directory that holds it
|
|
121
|
+
* and all that directory's ancestors must not be writable by group or others. A link that anyone
|
|
122
|
+
* else can create, replace or rename could otherwise point the script at any executable the user
|
|
123
|
+
* can run, and that executable would pass every check on the resolved path.
|
|
124
|
+
*/
|
|
125
|
+
async function assertTrustedSymlinkChain(
|
|
126
|
+
expanded: string,
|
|
127
|
+
trustedOwner: OwnerCheck,
|
|
128
|
+
verifiedDirs = new Set<string>(),
|
|
129
|
+
allowSticky = true,
|
|
130
|
+
): Promise<void> {
|
|
131
|
+
const split = (path: string) => path.split("/").filter((part) => part !== "" && part !== ".");
|
|
132
|
+
let pending = split(expanded);
|
|
133
|
+
let current = "/";
|
|
134
|
+
let hops = 0;
|
|
135
|
+
while (pending.length > 0) {
|
|
136
|
+
const [name, ...rest] = pending;
|
|
137
|
+
pending = rest;
|
|
138
|
+
if (name === "..") {
|
|
139
|
+
// The directory being left is part of the path too, even though realpath will not list it.
|
|
140
|
+
await assertTrustedDirectories(current, trustedOwner, verifiedDirs, allowSticky);
|
|
141
|
+
current = dirname(current);
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
const next = join(current, name);
|
|
145
|
+
const info = await lstat(next);
|
|
146
|
+
if (!info.isSymbolicLink()) {
|
|
147
|
+
current = next;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
hops += 1;
|
|
151
|
+
if (hops > MAX_SYMLINK_HOPS) {
|
|
152
|
+
throw new Error(`Routing script path ${expanded} has too many levels of symbolic links.`);
|
|
153
|
+
}
|
|
154
|
+
if (!trustedOwner(info.uid)) {
|
|
155
|
+
throw new Error(
|
|
156
|
+
`Routing script path goes through the symbolic link ${next}, which is owned by another user; point the setting at the real file, or run chown on the link.`,
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
// `current` holds no links (each one is replaced by its target), so this is the real directory
|
|
160
|
+
// that contains the link.
|
|
161
|
+
await assertTrustedDirectories(current, trustedOwner, verifiedDirs, allowSticky);
|
|
162
|
+
const target = await readlink(next);
|
|
163
|
+
pending = [...split(target), ...pending];
|
|
164
|
+
if (isAbsolute(target)) current = "/";
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Resolves the configured script to a real path and refuses anything but a regular, executable
|
|
170
|
+
* file that only this user (or root) can modify: the file must be owned by the user or root, and so
|
|
171
|
+
* must every directory above it, none of them writable by group or others unless sticky (like
|
|
172
|
+
* /tmp). Otherwise another local user could create the script or swap a path component for their
|
|
173
|
+
* own, and it would run as this user. `uid` is a parameter so tests can stand in for another user.
|
|
174
|
+
*/
|
|
175
|
+
export async function resolveRoutingScript(
|
|
176
|
+
rawPath: string,
|
|
177
|
+
uid: number | undefined = process.getuid?.(),
|
|
178
|
+
): Promise<string> {
|
|
179
|
+
const trimmed = rawPath.trim();
|
|
180
|
+
if (!trimmed) {
|
|
181
|
+
throw new Error("No routing script is configured in the PR Radar settings.");
|
|
182
|
+
}
|
|
183
|
+
if (!isAbsoluteOrHomePath(trimmed)) {
|
|
184
|
+
throw new Error(`Routing script path must be an absolute or ~/ path: ${trimmed}`);
|
|
185
|
+
}
|
|
186
|
+
const expanded = expandUserPath(trimmed);
|
|
187
|
+
if (!(await exists(expanded))) {
|
|
188
|
+
throw new Error(`Routing script not found: ${expanded}`);
|
|
189
|
+
}
|
|
190
|
+
const trustedOwner = (owner: number) => uid === undefined || owner === uid || owner === 0;
|
|
191
|
+
await assertTrustedSymlinkChain(expanded, trustedOwner);
|
|
192
|
+
const scriptPath = await realpath(expanded);
|
|
193
|
+
const info = await stat(scriptPath);
|
|
194
|
+
if (!info.isFile()) {
|
|
195
|
+
throw new Error(`Routing script is not a regular file: ${scriptPath}`);
|
|
196
|
+
}
|
|
197
|
+
if (!trustedOwner(info.uid)) {
|
|
198
|
+
throw new Error(
|
|
199
|
+
`Routing script ${scriptPath} is owned by another user; run chown on it, or use a script you own.`,
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
if ((info.mode & 0o022) !== 0) {
|
|
203
|
+
throw new Error(
|
|
204
|
+
`Routing script ${scriptPath} must not be writable by group or others; run chmod go-w on it.`,
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
await assertTrustedDirectories(dirname(scriptPath), trustedOwner, new Set());
|
|
208
|
+
try {
|
|
209
|
+
await access(scriptPath, constants.X_OK);
|
|
210
|
+
} catch {
|
|
211
|
+
throw new Error(`Routing script is not executable: ${scriptPath}`);
|
|
212
|
+
}
|
|
213
|
+
return scriptPath;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
interface ScriptRun {
|
|
217
|
+
/** Settles with the script's stdout, or rejects on failure, timeout or the output cap. */
|
|
218
|
+
result: Promise<string>;
|
|
219
|
+
/** Resolves once the script's process group has exited or has been sent SIGKILL. */
|
|
220
|
+
finished: Promise<void>;
|
|
221
|
+
/** Ends the script now (SIGTERM, then SIGKILL after a short grace) and fails `result`. */
|
|
222
|
+
stop(): void;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function startScriptCapped(
|
|
226
|
+
scriptPath: string,
|
|
227
|
+
stdin: string,
|
|
228
|
+
limits: RoutingScriptLimits,
|
|
229
|
+
path: string,
|
|
230
|
+
): ScriptRun {
|
|
231
|
+
const finishedGate = Promise.withResolvers<void>();
|
|
232
|
+
let stop = () => {};
|
|
233
|
+
const result = new Promise<string>((resolvePromise, rejectPromise) => {
|
|
234
|
+
// Its own process group, so a timeout reaches the script's descendants too.
|
|
235
|
+
let child: ChildProcessByStdio<Writable, Readable, Readable>;
|
|
236
|
+
try {
|
|
237
|
+
child = spawn(scriptPath, [], {
|
|
238
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
239
|
+
env: { ...allowListedEnv(new Set()), PATH: path },
|
|
240
|
+
detached: true,
|
|
241
|
+
});
|
|
242
|
+
} catch (spawnError) {
|
|
243
|
+
finishedGate.resolve();
|
|
244
|
+
rejectPromise(spawnError);
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
const out: Buffer[] = [];
|
|
248
|
+
const err: Buffer[] = [];
|
|
249
|
+
let outBytes = 0;
|
|
250
|
+
let errBytes = 0;
|
|
251
|
+
let settled = false;
|
|
252
|
+
let terminating = false;
|
|
253
|
+
let exited = false;
|
|
254
|
+
let killTimer: NodeJS.Timeout | undefined;
|
|
255
|
+
|
|
256
|
+
// Once the script has exited its process-group id is free to be reused, so nothing may signal
|
|
257
|
+
// it after the one SIGKILL sent from the 'exit' handler.
|
|
258
|
+
function signalGroup(signal: NodeJS.Signals): void {
|
|
259
|
+
if (exited) return;
|
|
260
|
+
try {
|
|
261
|
+
if (child.pid !== undefined) process.kill(-child.pid, signal);
|
|
262
|
+
} catch {
|
|
263
|
+
// The group is already gone.
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function settle(finish: () => void): void {
|
|
267
|
+
if (settled) return;
|
|
268
|
+
settled = true;
|
|
269
|
+
clearTimeout(timer);
|
|
270
|
+
// A surviving descendant could otherwise keep feeding buffers nobody reads any more.
|
|
271
|
+
child.stdout.destroy();
|
|
272
|
+
child.stderr.destroy();
|
|
273
|
+
finish();
|
|
274
|
+
}
|
|
275
|
+
function terminate(graceMs = limits.killGraceMs): void {
|
|
276
|
+
if (terminating) return;
|
|
277
|
+
terminating = true;
|
|
278
|
+
signalGroup("SIGTERM");
|
|
279
|
+
killTimer = setTimeout(() => {
|
|
280
|
+
signalGroup("SIGKILL");
|
|
281
|
+
finishedGate.resolve();
|
|
282
|
+
}, graceMs);
|
|
283
|
+
}
|
|
284
|
+
stop = () => {
|
|
285
|
+
if (terminating) {
|
|
286
|
+
// A timeout or the output cap already sent SIGTERM and armed the full grace, which can
|
|
287
|
+
// outlast the host's own deadline: end the group now.
|
|
288
|
+
clearTimeout(killTimer);
|
|
289
|
+
signalGroup("SIGKILL");
|
|
290
|
+
finishedGate.resolve();
|
|
291
|
+
} else {
|
|
292
|
+
terminate(Math.min(limits.killGraceMs, SHUTDOWN_KILL_GRACE_MS));
|
|
293
|
+
}
|
|
294
|
+
settle(() => rejectPromise(new Error(ROUTING_STOPPED_MESSAGE)));
|
|
295
|
+
};
|
|
296
|
+
function overCap(): void {
|
|
297
|
+
terminate();
|
|
298
|
+
settle(() =>
|
|
299
|
+
rejectPromise(new Error(`Routing script output exceeded ${limits.outputBytes} bytes.`)),
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const timer = setTimeout(() => {
|
|
304
|
+
terminate();
|
|
305
|
+
settle(() =>
|
|
306
|
+
rejectPromise(new Error(`Routing script timed out after ${limits.timeoutMs}ms.`)),
|
|
307
|
+
);
|
|
308
|
+
}, limits.timeoutMs);
|
|
309
|
+
|
|
310
|
+
child.stdout.on("data", (chunk: Buffer) => {
|
|
311
|
+
if (settled) return;
|
|
312
|
+
outBytes += chunk.length;
|
|
313
|
+
if (outBytes > limits.outputBytes) return overCap();
|
|
314
|
+
out.push(chunk);
|
|
315
|
+
});
|
|
316
|
+
child.stderr.on("data", (chunk: Buffer) => {
|
|
317
|
+
if (settled) return;
|
|
318
|
+
errBytes += chunk.length;
|
|
319
|
+
if (errBytes > limits.outputBytes) return overCap();
|
|
320
|
+
err.push(chunk);
|
|
321
|
+
});
|
|
322
|
+
child.on("error", (spawnError) => {
|
|
323
|
+
settle(() => rejectPromise(spawnError));
|
|
324
|
+
finishedGate.resolve();
|
|
325
|
+
});
|
|
326
|
+
// 'exit' fires when the script itself has ended, while 'close' waits for every holder of the
|
|
327
|
+
// pipes. A descendant that kept them open would otherwise delay 'close' until the timeout and a
|
|
328
|
+
// script that exited 0 would be reported as timed out. Bytes the script already wrote stay in
|
|
329
|
+
// the pipe, so 'close' still delivers the full output.
|
|
330
|
+
// That one kill is the only group signal once the script has ended: a `setsid` descendant can
|
|
331
|
+
// hold the pipes (and 'close') for up to the timeout, and by then the group id may belong to an
|
|
332
|
+
// unrelated process.
|
|
333
|
+
child.on("exit", () => {
|
|
334
|
+
signalGroup("SIGKILL");
|
|
335
|
+
exited = true;
|
|
336
|
+
});
|
|
337
|
+
child.on("close", (code) => {
|
|
338
|
+
clearTimeout(killTimer);
|
|
339
|
+
finishedGate.resolve();
|
|
340
|
+
settle(() => {
|
|
341
|
+
if (code !== 0) {
|
|
342
|
+
const message = Buffer.concat(err).toString("utf8").trim();
|
|
343
|
+
rejectPromise(new Error(message || `Routing script exited with code ${code}.`));
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
resolvePromise(Buffer.concat(out).toString("utf8").trim());
|
|
347
|
+
});
|
|
348
|
+
});
|
|
349
|
+
child.stdin.on("error", () => {});
|
|
350
|
+
child.stdin.end(stdin);
|
|
351
|
+
});
|
|
352
|
+
return { result, finished: finishedGate.promise, stop: () => stop() };
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// The daemon waits 2 s for a plugin's cleanup before it signals the plugin process, so the script
|
|
356
|
+
// must be gone sooner than that.
|
|
357
|
+
const SHUTDOWN_KILL_GRACE_MS = 1_000;
|
|
358
|
+
const ROUTING_STOPPED_MESSAGE = "The routing script was stopped because PR Radar is shutting down.";
|
|
359
|
+
|
|
360
|
+
// One script runs at a time; up to this many further calls wait their turn, the rest are refused.
|
|
361
|
+
const MAX_QUEUED_ROUTING_CALLS = 2;
|
|
362
|
+
const ROUTING_BUSY_MESSAGE = "A routing script is already running; try again when it has finished.";
|
|
363
|
+
|
|
364
|
+
// Resolves when every admitted call has finished its turn: its script's process group is gone or
|
|
365
|
+
// has been sent SIGKILL, which can be after the call itself has failed on a timeout. A queued call
|
|
366
|
+
// waits on this gate (`run.finished`), not on the previous call's result, so a timed-out script
|
|
367
|
+
// that ignores SIGTERM never overlaps the next one.
|
|
368
|
+
let routingTail: Promise<void> = Promise.resolve();
|
|
369
|
+
let routingInFlight = 0;
|
|
370
|
+
let routingWaiting = 0;
|
|
371
|
+
// The script now running, and whether the plugin has been told to stop.
|
|
372
|
+
let activeRun: ScriptRun | undefined;
|
|
373
|
+
let routingStopped = false;
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Plugin cleanup. The script runs in its own process group (so a timeout reaches its descendants),
|
|
377
|
+
* which also means the daemon stopping, reloading or disabling the plugin does not reach it: end
|
|
378
|
+
* it here, and refuse any call still waiting. Resolves once its process group is gone or has been
|
|
379
|
+
* sent SIGKILL. A daemon that is killed outright never runs this; the script then ends on its own.
|
|
380
|
+
*/
|
|
381
|
+
export async function stopRoutingScripts(): Promise<void> {
|
|
382
|
+
routingStopped = true;
|
|
383
|
+
const run = activeRun;
|
|
384
|
+
if (!run) return;
|
|
385
|
+
run.stop();
|
|
386
|
+
await run.finished;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Called when the plugin starts: a plugin process is fresh, and tests start it more than once. */
|
|
390
|
+
export function startRoutingScripts(): void {
|
|
391
|
+
routingStopped = false;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
export async function waitForRoutingScriptIdleForTests(): Promise<void> {
|
|
395
|
+
for (let tail = routingTail; ; tail = routingTail) {
|
|
396
|
+
await tail;
|
|
397
|
+
if (tail === routingTail) return;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// Resolves with `work`, or rejects with `message` once `ms` have passed. The work itself cannot be
|
|
402
|
+
// cancelled, but the caller stops waiting for it, so a hung filesystem read cannot hold a turn.
|
|
403
|
+
async function withinBudget<T>(work: Promise<T>, ms: number, message: string): Promise<T> {
|
|
404
|
+
// Work abandoned below may still reject later; nobody is left to hear it.
|
|
405
|
+
work.catch(() => {});
|
|
406
|
+
if (ms <= 0) throw new Error(message);
|
|
407
|
+
let timer: NodeJS.Timeout | undefined;
|
|
408
|
+
const expired = new Promise<never>((_, reject) => {
|
|
409
|
+
timer = setTimeout(() => reject(new Error(message)), ms);
|
|
410
|
+
});
|
|
411
|
+
try {
|
|
412
|
+
return await Promise.race([work, expired]);
|
|
413
|
+
} finally {
|
|
414
|
+
clearTimeout(timer);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
const ROUTING_PREFLIGHT_MESSAGE =
|
|
419
|
+
"Reading the routing script settings or checking the script took longer than the time budget.";
|
|
420
|
+
|
|
421
|
+
export async function runRoutingScriptHandler(
|
|
422
|
+
input: z.output<typeof runRoutingScript.input>,
|
|
423
|
+
readSettings: ReadWorkspaceSettings,
|
|
424
|
+
limits: RoutingScriptLimits = DEFAULT_ROUTING_LIMITS,
|
|
425
|
+
): Promise<z.output<typeof runRoutingScript.output>> {
|
|
426
|
+
if (process.platform === "win32") {
|
|
427
|
+
throw new Error("Routing scripts are not supported on Windows.");
|
|
428
|
+
}
|
|
429
|
+
if (routingStopped) throw new Error(ROUTING_STOPPED_MESSAGE);
|
|
430
|
+
// Checked before a place in line is taken: an oversize payload costs nothing to refuse.
|
|
431
|
+
const stdin = `${JSON.stringify(input.payload)}\n`;
|
|
432
|
+
const inputCap = limits.inputBytes ?? DEFAULT_ROUTING_INPUT_BYTES;
|
|
433
|
+
const inputBytes = Buffer.byteLength(stdin);
|
|
434
|
+
if (inputBytes > inputCap) {
|
|
435
|
+
throw new Error(
|
|
436
|
+
`The routing script input is ${inputBytes} bytes, over the ${inputCap} byte limit; the script was not run.`,
|
|
437
|
+
);
|
|
438
|
+
}
|
|
439
|
+
// Paseo gives a plugin request the same 30 s as one script run, so time spent queued comes out
|
|
440
|
+
// of the run's own budget.
|
|
441
|
+
const startedAt = performance.now();
|
|
442
|
+
const budgetLeft = () => Math.floor(limits.timeoutMs - (performance.now() - startedAt));
|
|
443
|
+
|
|
444
|
+
// Take a place in line before the first await, so calls keep their arrival order however long
|
|
445
|
+
// each one's settings read and path check take, and the capacity check sees every earlier call.
|
|
446
|
+
const queued = routingInFlight > 0;
|
|
447
|
+
if (queued && routingWaiting >= MAX_QUEUED_ROUTING_CALLS) {
|
|
448
|
+
throw new Error(ROUTING_BUSY_MESSAGE);
|
|
449
|
+
}
|
|
450
|
+
const previous = routingTail;
|
|
451
|
+
const myTurn = Promise.withResolvers<void>();
|
|
452
|
+
routingTail = myTurn.promise;
|
|
453
|
+
routingInFlight += 1;
|
|
454
|
+
void myTurn.promise.then(() => {
|
|
455
|
+
routingInFlight -= 1;
|
|
456
|
+
});
|
|
457
|
+
let waiting = queued;
|
|
458
|
+
if (waiting) routingWaiting += 1;
|
|
459
|
+
const stopWaiting = () => {
|
|
460
|
+
if (!waiting) return;
|
|
461
|
+
waiting = false;
|
|
462
|
+
routingWaiting -= 1;
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
let run: ScriptRun;
|
|
466
|
+
try {
|
|
467
|
+
const preflight = async () => resolveRoutingScript((await readSettings()).routingScriptPath);
|
|
468
|
+
let scriptPath = await withinBudget(preflight(), budgetLeft(), ROUTING_PREFLIGHT_MESSAGE);
|
|
469
|
+
if (queued) {
|
|
470
|
+
try {
|
|
471
|
+
await withinBudget(previous, budgetLeft(), ROUTING_BUSY_MESSAGE);
|
|
472
|
+
} finally {
|
|
473
|
+
stopWaiting();
|
|
474
|
+
}
|
|
475
|
+
// The configuration may have changed while this call waited.
|
|
476
|
+
scriptPath = await withinBudget(preflight(), budgetLeft(), ROUTING_PREFLIGHT_MESSAGE);
|
|
477
|
+
}
|
|
478
|
+
const path = await withinBudget(trustedScriptPath(), budgetLeft(), ROUTING_PREFLIGHT_MESSAGE);
|
|
479
|
+
// A call that was waiting or reading settings when the plugin stopped must not start a script.
|
|
480
|
+
if (routingStopped) throw new Error(ROUTING_STOPPED_MESSAGE);
|
|
481
|
+
// Taken last, after every await, so the script's own timer starts when the budget says. A first
|
|
482
|
+
// call has spent time on its settings read and path checks too, so it is trimmed like a queued one.
|
|
483
|
+
const remaining = budgetLeft();
|
|
484
|
+
if (remaining <= 0) throw new Error(queued ? ROUTING_BUSY_MESSAGE : ROUTING_PREFLIGHT_MESSAGE);
|
|
485
|
+
run = startScriptCapped(scriptPath, stdin, { ...limits, timeoutMs: remaining }, path);
|
|
486
|
+
} catch (error) {
|
|
487
|
+
// This call never ran: pass the turn on once the one in front is done, so the order holds.
|
|
488
|
+
stopWaiting();
|
|
489
|
+
void previous.then(() => myTurn.resolve());
|
|
490
|
+
throw error;
|
|
491
|
+
}
|
|
492
|
+
activeRun = run;
|
|
493
|
+
void run.finished.then(() => {
|
|
494
|
+
if (activeRun === run) activeRun = undefined;
|
|
495
|
+
myTurn.resolve();
|
|
496
|
+
});
|
|
497
|
+
const stdout = await run.result;
|
|
498
|
+
|
|
499
|
+
if (!stdout) return {};
|
|
500
|
+
const parsed = JSON.parse(stdout) as unknown;
|
|
501
|
+
return RoutingScriptResultSchema.parse(parsed);
|
|
502
|
+
}
|
package/server/workspace-ops.ts
CHANGED
|
@@ -1,22 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { constants } from "node:fs";
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
3
2
|
import { access, mkdir, readdir, realpath, stat } from "node:fs/promises";
|
|
4
3
|
import { homedir } from "node:os";
|
|
5
4
|
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
6
|
-
import type { Readable, Writable } from "node:stream";
|
|
7
5
|
import { promisify } from "node:util";
|
|
8
6
|
import type { z } from "zod";
|
|
9
7
|
import type { PrRadarSettings } from "../shared/settings";
|
|
10
|
-
import {
|
|
11
|
-
type LocalDirEntry,
|
|
12
|
-
type listLocalDirs,
|
|
13
|
-
type prepareWorkspaceCwd,
|
|
14
|
-
RoutingScriptResultSchema,
|
|
15
|
-
type runRoutingScript,
|
|
16
|
-
} from "../shared/viewer-scope";
|
|
8
|
+
import type { LocalDirEntry, listLocalDirs, prepareWorkspaceCwd } from "../shared/viewer-scope";
|
|
17
9
|
|
|
18
10
|
const execFileAsync = promisify(execFile);
|
|
19
|
-
const COMMAND_TIMEOUT_MS = 30_000;
|
|
11
|
+
export const COMMAND_TIMEOUT_MS = 30_000;
|
|
20
12
|
const CLONE_TIMEOUT_MS = 120_000;
|
|
21
13
|
const MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
|
22
14
|
|
|
@@ -24,18 +16,6 @@ const MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
|
|
24
16
|
export type WorkspaceOpsSettings = Pick<PrRadarSettings, "sourceCodeDir" | "routingScriptPath">;
|
|
25
17
|
export type ReadWorkspaceSettings = () => Promise<WorkspaceOpsSettings>;
|
|
26
18
|
|
|
27
|
-
export interface RoutingScriptLimits {
|
|
28
|
-
timeoutMs: number;
|
|
29
|
-
outputBytes: number;
|
|
30
|
-
killGraceMs: number;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
const DEFAULT_ROUTING_LIMITS: RoutingScriptLimits = {
|
|
34
|
-
timeoutMs: COMMAND_TIMEOUT_MS,
|
|
35
|
-
outputBytes: 1024 * 1024,
|
|
36
|
-
killGraceMs: 2_000,
|
|
37
|
-
};
|
|
38
|
-
|
|
39
19
|
// Environment handed to child processes. Everything else in the daemon's environment (API keys,
|
|
40
20
|
// cloud credentials, tokens for other tools) stays behind. A routing script gets only what a
|
|
41
21
|
// script needs to find its interpreter and locale. gh additionally needs its own credentials and
|
|
@@ -105,7 +85,7 @@ const GIT_ENV_KEYS: ReadonlySet<string> = new Set([
|
|
|
105
85
|
"all_proxy",
|
|
106
86
|
]);
|
|
107
87
|
|
|
108
|
-
function allowListedEnv(extraKeys: ReadonlySet<string>): NodeJS.ProcessEnv {
|
|
88
|
+
export function allowListedEnv(extraKeys: ReadonlySet<string>): NodeJS.ProcessEnv {
|
|
109
89
|
const env: NodeJS.ProcessEnv = {};
|
|
110
90
|
for (const [key, value] of Object.entries(process.env)) {
|
|
111
91
|
if (value === undefined) continue;
|
|
@@ -121,7 +101,7 @@ export function expandUserPath(rawPath: string): string {
|
|
|
121
101
|
return resolve(trimmed);
|
|
122
102
|
}
|
|
123
103
|
|
|
124
|
-
async function exists(target: string): Promise<boolean> {
|
|
104
|
+
export async function exists(target: string): Promise<boolean> {
|
|
125
105
|
try {
|
|
126
106
|
await access(target);
|
|
127
107
|
return true;
|
|
@@ -1276,211 +1256,3 @@ async function prepareLockedWorkspaceCwd(
|
|
|
1276
1256
|
worktreeCreated: true,
|
|
1277
1257
|
};
|
|
1278
1258
|
}
|
|
1279
|
-
|
|
1280
|
-
const STICKY_BIT = 0o1000;
|
|
1281
|
-
|
|
1282
|
-
/**
|
|
1283
|
-
* Resolves the configured script to a real path and refuses anything but a regular, executable
|
|
1284
|
-
* file that only this user (or root) can modify: the file must be owned by the user or root, and so
|
|
1285
|
-
* must every directory above it, none of them writable by group or others unless sticky (like
|
|
1286
|
-
* /tmp). Otherwise another local user could create the script or swap a path component for their
|
|
1287
|
-
* own, and it would run as this user. `uid` is a parameter so tests can stand in for another user.
|
|
1288
|
-
*/
|
|
1289
|
-
export async function resolveRoutingScript(
|
|
1290
|
-
rawPath: string,
|
|
1291
|
-
uid: number | undefined = process.getuid?.(),
|
|
1292
|
-
): Promise<string> {
|
|
1293
|
-
const trimmed = rawPath.trim();
|
|
1294
|
-
if (!trimmed) {
|
|
1295
|
-
throw new Error("No routing script is configured in the PR Radar settings.");
|
|
1296
|
-
}
|
|
1297
|
-
if (!isAbsoluteOrHomePath(trimmed)) {
|
|
1298
|
-
throw new Error(`Routing script path must be an absolute or ~/ path: ${trimmed}`);
|
|
1299
|
-
}
|
|
1300
|
-
const expanded = expandUserPath(trimmed);
|
|
1301
|
-
if (!(await exists(expanded))) {
|
|
1302
|
-
throw new Error(`Routing script not found: ${expanded}`);
|
|
1303
|
-
}
|
|
1304
|
-
const scriptPath = await realpath(expanded);
|
|
1305
|
-
const info = await stat(scriptPath);
|
|
1306
|
-
if (!info.isFile()) {
|
|
1307
|
-
throw new Error(`Routing script is not a regular file: ${scriptPath}`);
|
|
1308
|
-
}
|
|
1309
|
-
const trustedOwner = (owner: number) => uid === undefined || owner === uid || owner === 0;
|
|
1310
|
-
if (!trustedOwner(info.uid)) {
|
|
1311
|
-
throw new Error(
|
|
1312
|
-
`Routing script ${scriptPath} is owned by another user; run chown on it, or use a script you own.`,
|
|
1313
|
-
);
|
|
1314
|
-
}
|
|
1315
|
-
if ((info.mode & 0o022) !== 0) {
|
|
1316
|
-
throw new Error(
|
|
1317
|
-
`Routing script ${scriptPath} must not be writable by group or others; run chmod go-w on it.`,
|
|
1318
|
-
);
|
|
1319
|
-
}
|
|
1320
|
-
for (let dir = dirname(scriptPath); ; dir = dirname(dir)) {
|
|
1321
|
-
const dirInfo = await stat(dir);
|
|
1322
|
-
if (!trustedOwner(dirInfo.uid)) {
|
|
1323
|
-
throw new Error(
|
|
1324
|
-
`Routing script directory ${dir} is owned by another user; move the script somewhere you own, or run chown on it.`,
|
|
1325
|
-
);
|
|
1326
|
-
}
|
|
1327
|
-
if ((dirInfo.mode & 0o022) !== 0 && (dirInfo.mode & STICKY_BIT) === 0) {
|
|
1328
|
-
throw new Error(
|
|
1329
|
-
`Routing script directory ${dir} must not be writable by group or others; run chmod go-w on it.`,
|
|
1330
|
-
);
|
|
1331
|
-
}
|
|
1332
|
-
if (dirname(dir) === dir) break;
|
|
1333
|
-
}
|
|
1334
|
-
try {
|
|
1335
|
-
await access(scriptPath, constants.X_OK);
|
|
1336
|
-
} catch {
|
|
1337
|
-
throw new Error(`Routing script is not executable: ${scriptPath}`);
|
|
1338
|
-
}
|
|
1339
|
-
return scriptPath;
|
|
1340
|
-
}
|
|
1341
|
-
|
|
1342
|
-
interface ScriptRun {
|
|
1343
|
-
/** Settles with the script's stdout, or rejects on failure, timeout or the output cap. */
|
|
1344
|
-
result: Promise<string>;
|
|
1345
|
-
/** Resolves once the script's process group has exited or has been sent SIGKILL. */
|
|
1346
|
-
finished: Promise<void>;
|
|
1347
|
-
}
|
|
1348
|
-
|
|
1349
|
-
function startScriptCapped(
|
|
1350
|
-
scriptPath: string,
|
|
1351
|
-
payload: unknown,
|
|
1352
|
-
limits: RoutingScriptLimits,
|
|
1353
|
-
): ScriptRun {
|
|
1354
|
-
const finishedGate = Promise.withResolvers<void>();
|
|
1355
|
-
const result = new Promise<string>((resolvePromise, rejectPromise) => {
|
|
1356
|
-
// Its own process group, so a timeout reaches the script's descendants too.
|
|
1357
|
-
let child: ChildProcessByStdio<Writable, Readable, Readable>;
|
|
1358
|
-
try {
|
|
1359
|
-
child = spawn(scriptPath, [], {
|
|
1360
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
1361
|
-
env: allowListedEnv(new Set()),
|
|
1362
|
-
detached: true,
|
|
1363
|
-
});
|
|
1364
|
-
} catch (spawnError) {
|
|
1365
|
-
finishedGate.resolve();
|
|
1366
|
-
rejectPromise(spawnError);
|
|
1367
|
-
return;
|
|
1368
|
-
}
|
|
1369
|
-
const out: Buffer[] = [];
|
|
1370
|
-
const err: Buffer[] = [];
|
|
1371
|
-
let outBytes = 0;
|
|
1372
|
-
let errBytes = 0;
|
|
1373
|
-
let settled = false;
|
|
1374
|
-
let terminating = false;
|
|
1375
|
-
let killTimer: NodeJS.Timeout | undefined;
|
|
1376
|
-
|
|
1377
|
-
function signalGroup(signal: NodeJS.Signals): void {
|
|
1378
|
-
try {
|
|
1379
|
-
if (child.pid !== undefined) process.kill(-child.pid, signal);
|
|
1380
|
-
} catch {
|
|
1381
|
-
// The group is already gone.
|
|
1382
|
-
}
|
|
1383
|
-
}
|
|
1384
|
-
function settle(finish: () => void): void {
|
|
1385
|
-
if (settled) return;
|
|
1386
|
-
settled = true;
|
|
1387
|
-
clearTimeout(timer);
|
|
1388
|
-
// A surviving descendant could otherwise keep feeding buffers nobody reads any more.
|
|
1389
|
-
child.stdout.destroy();
|
|
1390
|
-
child.stderr.destroy();
|
|
1391
|
-
finish();
|
|
1392
|
-
}
|
|
1393
|
-
function terminate(): void {
|
|
1394
|
-
if (terminating) return;
|
|
1395
|
-
terminating = true;
|
|
1396
|
-
signalGroup("SIGTERM");
|
|
1397
|
-
killTimer = setTimeout(() => {
|
|
1398
|
-
signalGroup("SIGKILL");
|
|
1399
|
-
finishedGate.resolve();
|
|
1400
|
-
}, limits.killGraceMs);
|
|
1401
|
-
}
|
|
1402
|
-
function overCap(): void {
|
|
1403
|
-
terminate();
|
|
1404
|
-
settle(() =>
|
|
1405
|
-
rejectPromise(new Error(`Routing script output exceeded ${limits.outputBytes} bytes.`)),
|
|
1406
|
-
);
|
|
1407
|
-
}
|
|
1408
|
-
|
|
1409
|
-
const timer = setTimeout(() => {
|
|
1410
|
-
terminate();
|
|
1411
|
-
settle(() =>
|
|
1412
|
-
rejectPromise(new Error(`Routing script timed out after ${limits.timeoutMs}ms.`)),
|
|
1413
|
-
);
|
|
1414
|
-
}, limits.timeoutMs);
|
|
1415
|
-
|
|
1416
|
-
child.stdout.on("data", (chunk: Buffer) => {
|
|
1417
|
-
if (settled) return;
|
|
1418
|
-
outBytes += chunk.length;
|
|
1419
|
-
if (outBytes > limits.outputBytes) return overCap();
|
|
1420
|
-
out.push(chunk);
|
|
1421
|
-
});
|
|
1422
|
-
child.stderr.on("data", (chunk: Buffer) => {
|
|
1423
|
-
if (settled) return;
|
|
1424
|
-
errBytes += chunk.length;
|
|
1425
|
-
if (errBytes > limits.outputBytes) return overCap();
|
|
1426
|
-
err.push(chunk);
|
|
1427
|
-
});
|
|
1428
|
-
child.on("error", (spawnError) => {
|
|
1429
|
-
settle(() => rejectPromise(spawnError));
|
|
1430
|
-
finishedGate.resolve();
|
|
1431
|
-
});
|
|
1432
|
-
child.on("close", (code) => {
|
|
1433
|
-
// Having asked it to stop, make sure no descendant outlives the script.
|
|
1434
|
-
if (terminating) signalGroup("SIGKILL");
|
|
1435
|
-
clearTimeout(killTimer);
|
|
1436
|
-
finishedGate.resolve();
|
|
1437
|
-
settle(() => {
|
|
1438
|
-
if (code !== 0) {
|
|
1439
|
-
const message = Buffer.concat(err).toString("utf8").trim();
|
|
1440
|
-
rejectPromise(new Error(message || `Routing script exited with code ${code}.`));
|
|
1441
|
-
return;
|
|
1442
|
-
}
|
|
1443
|
-
resolvePromise(Buffer.concat(out).toString("utf8").trim());
|
|
1444
|
-
});
|
|
1445
|
-
});
|
|
1446
|
-
child.stdin.on("error", () => {});
|
|
1447
|
-
child.stdin.end(`${JSON.stringify(payload)}\n`);
|
|
1448
|
-
});
|
|
1449
|
-
return { result, finished: finishedGate.promise };
|
|
1450
|
-
}
|
|
1451
|
-
|
|
1452
|
-
let routingScriptRunning = false;
|
|
1453
|
-
let routingScriptFinished: Promise<void> | null = null;
|
|
1454
|
-
|
|
1455
|
-
export async function waitForRoutingScriptIdleForTests(): Promise<void> {
|
|
1456
|
-
await routingScriptFinished;
|
|
1457
|
-
}
|
|
1458
|
-
|
|
1459
|
-
export async function runRoutingScriptHandler(
|
|
1460
|
-
input: z.output<typeof runRoutingScript.input>,
|
|
1461
|
-
readSettings: ReadWorkspaceSettings,
|
|
1462
|
-
limits: RoutingScriptLimits = DEFAULT_ROUTING_LIMITS,
|
|
1463
|
-
): Promise<z.output<typeof runRoutingScript.output>> {
|
|
1464
|
-
if (process.platform === "win32") {
|
|
1465
|
-
throw new Error("Routing scripts are not supported on Windows.");
|
|
1466
|
-
}
|
|
1467
|
-
const settings = await readSettings();
|
|
1468
|
-
const scriptPath = await resolveRoutingScript(settings.routingScriptPath);
|
|
1469
|
-
if (routingScriptRunning) {
|
|
1470
|
-
throw new Error("A routing script is already running; try again when it has finished.");
|
|
1471
|
-
}
|
|
1472
|
-
routingScriptRunning = true;
|
|
1473
|
-
// The guard is held until the script's process group is gone or has been sent SIGKILL, which can
|
|
1474
|
-
// be after the call itself has failed on a timeout.
|
|
1475
|
-
const run = startScriptCapped(scriptPath, input.payload, limits);
|
|
1476
|
-
routingScriptFinished = run.finished.then(() => {
|
|
1477
|
-
routingScriptRunning = false;
|
|
1478
|
-
routingScriptFinished = null;
|
|
1479
|
-
});
|
|
1480
|
-
void routingScriptFinished;
|
|
1481
|
-
const stdout = await run.result;
|
|
1482
|
-
|
|
1483
|
-
if (!stdout) return {};
|
|
1484
|
-
const parsed = JSON.parse(stdout) as unknown;
|
|
1485
|
-
return RoutingScriptResultSchema.parse(parsed);
|
|
1486
|
-
}
|