Repository navigation
Expand file tree
/
Copy pathkernel.ts
More file actions
829 lines (765 loc) · 25.3 KB
/
Copy pathkernel.ts
File metadata and controls
829 lines (765 loc) · 25.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
/**
* PythonKernel — long-lived python3 subprocess speaking the runner.py
* NDJSON wire protocol. One kernel per pi session.
*/
import { type ChildProcessWithoutNullStreams, spawn, spawnSync } from "node:child_process";
import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { dirname, isAbsolute, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const RUNNER_PATH = join(dirname(fileURLToPath(import.meta.url)), "runner.py");
export interface CellRequest {
code: string;
title?: string;
}
export interface CellResult {
index: number;
title?: string;
stdout: string;
stderr: string;
value: string; // repr of the last expression, or "" for statements
ok: boolean;
exception: string; // formatted traceback when !ok
}
export interface ExecuteResult {
cells: CellResult[];
cancelled: boolean;
timedOut: boolean;
cellsRun: number;
reset: boolean;
/**
* The kernel process was hard-killed while this request was in flight,
* so the namespace is gone. Output captured before the kill is still
* present in `cells` — the whole point of surfacing this as a result
* rather than an exception.
*/
killed?: boolean;
}
export interface KernelInfo {
python: string;
executable: string;
pid: number;
cwd: string;
}
export interface KernelOptions {
pythonPath: string;
cwd: string;
env?: NodeJS.ProcessEnv;
/** Memory containment; see `memoryMaxMB` / `oomScoreAdj` in settings.ts. */
memory?: { maxMB: number; oomScoreAdj: number };
}
export interface KernelMemory {
/** Bytes in use: the scope's cgroup `memory.current`, or the process RSS. */
bytes: number;
source: "cgroup" | "rss";
}
/** How the memory limit is applied to the running kernel. */
export interface KernelLimit {
maxMB: number;
/** Name of the transient systemd scope, or null when the limit is not enforced. */
scope: string | null;
/** Why the limit is not enforced, when it is not. */
unenforcedReason?: string;
}
let scopeProbe: { ok: boolean; reason?: string } | null = null;
/**
* Can this process start kernels in a memory-limited systemd user scope?
* Probed once per pi process by running `true` in a throwaway scope.
*/
export function systemdScopeAvailable(): { ok: boolean; reason?: string } {
if (scopeProbe) return scopeProbe;
if (process.platform !== "linux") {
scopeProbe = { ok: false, reason: `not Linux (${process.platform})` };
return scopeProbe;
}
const r = spawnSync(
"systemd-run",
["--user", "--scope", "--quiet", "--collect", "-p", "MemoryMax=64M", "-p", "MemorySwapMax=0", "--", "true"],
{ timeout: 10_000, stdio: ["ignore", "ignore", "pipe"], encoding: "utf8" },
);
if (r.error) scopeProbe = { ok: false, reason: `systemd-run unavailable (${r.error.message})` };
else if (r.status !== 0)
scopeProbe = { ok: false, reason: `systemd-run --user --scope failed: ${(r.stderr || "").trim().split("\n")[0]}` };
else scopeProbe = { ok: true };
return scopeProbe;
}
/** Bytes for an RSS/cgroup reading, as a short human string. */
export function formatBytes(bytes: number): string {
if (bytes >= 1 << 30) return `${(bytes / (1 << 30)).toFixed(1)} GB`;
return `${Math.round(bytes / (1 << 20))} MB`;
}
interface PendingRequest {
id: string;
resolve: (result: ExecuteResult) => void;
reject: (err: Error) => void;
cells: Map<number, CellResult>;
requestedCells: CellRequest[];
cancelled: boolean;
timedOut: boolean;
killed?: boolean;
/** Fires at `timeoutMs`: marks the timeout and sends the first SIGINT. */
timer?: NodeJS.Timeout;
/** Fires at graceMs/2 after the timeout: second SIGINT. */
retryTimer?: NodeJS.Timeout;
/** Fires at graceMs after the timeout: SIGKILL. */
graceTimer?: NodeJS.Timeout;
cellsRun: number;
reset: boolean;
onUpdate?: (snapshot: ExecuteResult) => void;
}
export class PythonKernel {
private readonly options: KernelOptions;
private proc: ChildProcessWithoutNullStreams | null = null;
private buffer = "";
private pending: PendingRequest | null = null;
private readyInfo: KernelInfo | null = null;
private readyPromise: Promise<KernelInfo> | null = null;
private readyResolve: ((info: KernelInfo) => void) | null = null;
private readyReject: ((err: Error) => void) | null = null;
private exitReason: string | null = null;
private nextRequestId = 1;
private limit: KernelLimit | null = null;
constructor(options: KernelOptions) {
this.options = options;
}
getInfo(): KernelInfo | null {
return this.readyInfo;
}
isAlive(): boolean {
// `proc.killed` is set to true by Node *whenever* we call proc.kill(),
// even with a non-fatal signal (SIGINT just interrupts). The only
// reliable "the process is still running" check is whether it has
// reported an exit yet — exitCode and signalCode are both null until
// then.
if (this.proc === null) return false;
return this.proc.exitCode === null && this.proc.signalCode === null;
}
/** The memory limit applied to this kernel, or null when none was requested. */
getLimit(): KernelLimit | null {
return this.limit;
}
/**
* Current memory use. For a scoped kernel this is the scope's cgroup
* `memory.current`, which counts child processes and is what MemoryMax is
* enforced against; otherwise the kernel process's RSS. Null when unknown.
*/
memoryUsage(): KernelMemory | null {
const pid = this.proc?.pid;
if (pid === undefined || !this.isAlive()) return null;
if (this.limit?.scope) {
try {
const line = readFileSync(`/proc/${pid}/cgroup`, "utf8")
.split("\n")
.find((l) => l.startsWith("0::"));
if (line) {
const bytes = Number(readFileSync(`/sys/fs/cgroup${line.slice(3)}/memory.current`, "utf8").trim());
if (Number.isFinite(bytes)) return { bytes, source: "cgroup" };
}
} catch {
// fall back to RSS
}
}
try {
const m = /^VmRSS:\s+(\d+) kB/m.exec(readFileSync(`/proc/${pid}/status`, "utf8"));
if (m) return { bytes: Number(m[1]) * 1024, source: "rss" };
} catch {
// not Linux, or the process just exited
}
return null;
}
/** Lazily spawn and wait for the runner's `ready` event. */
async start(): Promise<KernelInfo> {
if (this.readyInfo) return this.readyInfo;
if (this.readyPromise) return this.readyPromise;
// Python is a first-class execution environment, not a sandbox. Inherit
// the host environment unchanged so project tooling and credentials work
// exactly as they do from the user's shell.
const env = { ...(this.options.env ?? process.env), PYTHONUNBUFFERED: "1" };
// Memory containment. The kernel runs in its own transient systemd scope
// with a hard MemoryMax, so a runaway cell (or an in-process JVM that
// grew to a quarter of RAM) is OOM-killed on its own rather than pushing
// the whole machine into a global OOM that picks an arbitrary victim.
// `systemd-run --scope` execs the command in place: same PID, same stdio,
// so signals and the wire protocol are unaffected.
let command = this.options.pythonPath;
let args = ["-u", RUNNER_PATH];
const mem = this.options.memory;
this.limit = null;
if (mem && mem.maxMB > 0) {
const probe = systemdScopeAvailable();
if (probe.ok) {
const scope = `pi-python-${process.pid}-${Date.now().toString(36)}-${Math.floor(Math.random() * 1e6).toString(36)}`;
args = [
"--user",
"--scope",
"--quiet",
"--collect",
`--unit=${scope}`,
"-p",
`MemoryMax=${mem.maxMB}M`,
"-p",
"MemorySwapMax=0",
"--",
command,
...args,
];
command = "systemd-run";
this.limit = { maxMB: mem.maxMB, scope };
} else {
this.limit = { maxMB: mem.maxMB, scope: null, unenforcedReason: probe.reason };
}
}
const proc = spawn(command, args, {
cwd: this.options.cwd,
env,
stdio: ["pipe", "pipe", "pipe"],
});
if (mem && mem.oomScoreAdj > 0 && proc.pid !== undefined) raiseOomScore(proc.pid, mem.oomScoreAdj);
this.proc = proc;
this.readyPromise = new Promise<KernelInfo>((resolveReady, rejectReady) => {
this.readyResolve = resolveReady;
this.readyReject = rejectReady;
});
proc.stdout.setEncoding("utf8");
proc.stderr.setEncoding("utf8");
// Every handler below is bound to THIS process object and must ignore
// events once it is no longer the live kernel.
//
// Node delivers a killed child's `exit` asynchronously, well after
// kill() returns. Without this guard the corpse's exit event lands on
// whatever is current by then — rejecting the *replacement* kernel's
// startup with "Python kernel exited (signal SIGKILL)", or failing a
// perfectly healthy in-flight request on the new process. That reads
// exactly like a kernel dying at random for no reason.
const isCurrent = () => this.proc === proc;
proc.stdout.on("data", (chunk: string) => {
if (isCurrent()) this.onStdout(chunk);
});
proc.stderr.on("data", (chunk: string) => {
if (isCurrent()) this.onStderrOutOfBand(chunk);
});
proc.on("error", (err) => {
if (!isCurrent()) return;
this.fail(err);
});
proc.on("exit", (code, signal) => {
if (!isCurrent()) return;
let reason = signal ? `signal ${signal}` : `exit code ${code}`;
// Our own kill() detaches the process first (isCurrent() is false by
// then), so a SIGKILL seen here came from outside: in a scoped kernel
// that is almost always the memory limit.
if (signal === "SIGKILL" && this.limit?.scope) {
reason +=
` — most likely the ${this.limit.maxMB} MB kernel memory limit (pi-python memoryMaxMB); ` +
"the namespace is gone. Keep less in memory (stream to files, del + gc.collect()) and rerun.";
}
this.exitReason = reason;
this.fail(new Error(`Python kernel exited (${reason})`));
});
try {
return await this.readyPromise;
} catch (err) {
this.proc = null;
throw err;
}
}
private fail(err: Error): void {
if (this.readyReject) {
this.readyReject(err);
this.readyResolve = null;
this.readyReject = null;
}
if (this.pending) {
this.pending.reject(err);
this.pending = null;
}
}
private onStderrOutOfBand(data: string): void {
// The runner sends framed events on stdout. Anything on stderr is
// usually an interpreter-level diagnostic (import errors, etc.).
// Surface it as part of the current request if there is one, or
// stash it on the ready failure.
if (this.pending) {
this.pending.cells.set(-1, {
index: -1,
stdout: "",
stderr:
(this.pending.cells.get(-1)?.stderr ?? "") + data,
value: "",
ok: false,
exception: "",
});
this.pending.onUpdate?.(this.snapshot(this.pending));
}
}
private onStdout(chunk: string): void {
this.buffer += chunk;
let nl = this.buffer.indexOf("\n");
while (nl >= 0) {
const line = this.buffer.slice(0, nl);
this.buffer = this.buffer.slice(nl + 1);
if (line.length > 0) this.handleLine(line);
nl = this.buffer.indexOf("\n");
}
}
private handleLine(line: string): void {
let msg: Record<string, unknown>;
try {
msg = JSON.parse(line);
} catch {
// Non-JSON output from the runner shouldn't happen, but if it does,
// dump it into the current request's stderr stream.
if (this.pending) {
this.appendStream(this.pending, -1, "stderr", `${line}\n`);
}
return;
}
const type = msg.type as string | undefined;
if (type === "ready") {
this.readyInfo = {
python: String(msg.python ?? ""),
executable: String(msg.executable ?? this.options.pythonPath),
pid: Number(msg.pid ?? this.proc?.pid ?? 0),
cwd: String(msg.cwd ?? this.options.cwd),
};
this.readyResolve?.(this.readyInfo);
this.readyResolve = null;
this.readyReject = null;
return;
}
if (!this.pending || msg.id !== this.pending.id) {
// Stale or unsolicited message — ignore.
return;
}
const pending = this.pending;
const cellIndex = typeof msg.cell === "number" ? msg.cell : -1;
switch (type) {
case "stdout":
case "stderr":
this.appendStream(pending, cellIndex, type, String(msg.data ?? ""));
break;
case "cell_end": {
const cell = this.ensureCell(pending, cellIndex);
cell.ok = Boolean(msg.ok);
cell.value = String(msg.value ?? "");
cell.exception = String(msg.exception ?? "");
pending.cellsRun = Math.max(pending.cellsRun, cellIndex + 1);
pending.onUpdate?.(this.snapshot(pending));
break;
}
case "done": {
pending.cellsRun = Number(msg.cells_run ?? pending.cellsRun);
pending.reset = Boolean(msg.reset ?? pending.reset);
this.finalize(pending);
break;
}
case "fatal": {
pending.cancelled = true;
const err = new Error(`python kernel fatal: ${msg.error ?? "unknown"}`);
pending.reject(err);
this.pending = null;
break;
}
default:
// Unknown type — ignore so we stay forward-compatible.
break;
}
}
private ensureCell(pending: PendingRequest, index: number): CellResult {
let cell = pending.cells.get(index);
if (!cell) {
const requested = index >= 0 ? pending.requestedCells[index] : undefined;
cell = {
index,
title: requested?.title,
stdout: "",
stderr: "",
value: "",
ok: false,
exception: "",
};
pending.cells.set(index, cell);
}
return cell;
}
private appendStream(
pending: PendingRequest,
index: number,
stream: "stdout" | "stderr",
data: string,
): void {
const cell = this.ensureCell(pending, index);
if (stream === "stdout") cell.stdout += data;
else cell.stderr += data;
pending.onUpdate?.(this.snapshot(pending));
}
private snapshot(pending: PendingRequest): ExecuteResult {
const cells = [...pending.cells.values()]
.filter((cell) => cell.index >= 0)
.sort((a, b) => a.index - b.index);
return {
cells,
cancelled: pending.cancelled,
timedOut: pending.timedOut,
cellsRun: pending.cellsRun,
reset: pending.reset,
...(pending.killed ? { killed: true } : {}),
};
}
private finalize(pending: PendingRequest): void {
if (pending.timer) {
clearTimeout(pending.timer);
pending.timer = undefined;
}
// The cell answered the SIGINT after all — disarm the escalation so
// we don't SIGKILL a kernel that just recovered.
if (pending.retryTimer) {
clearTimeout(pending.retryTimer);
pending.retryTimer = undefined;
}
if (pending.graceTimer) {
clearTimeout(pending.graceTimer);
pending.graceTimer = undefined;
}
const result = this.snapshot(pending);
this.pending = null;
pending.resolve(result);
}
/**
* Execute one or more cells. Throws if a previous request is still in flight.
*/
async execute(
cells: CellRequest[],
opts: {
timeoutMs?: number;
reset?: boolean;
signal?: AbortSignal;
cwd?: string;
onUpdate?: (snapshot: ExecuteResult) => void;
/**
* How long to wait after the timeout SIGINT before hard-killing
* the kernel. Default 30s. Set to 0 to never auto-kill (rely on
* the user's /python-restart for truly wedged kernels).
*/
interruptGraceMs?: number;
} = {},
): Promise<ExecuteResult> {
if (!this.isAlive()) {
await this.start();
}
if (this.pending) {
throw new Error("python kernel is busy");
}
const proc = this.proc;
if (!proc) throw new Error("python kernel not running");
const id = `req-${this.nextRequestId++}`;
const pending: PendingRequest = {
id,
resolve: () => {},
reject: () => {},
cells: new Map(),
requestedCells: cells,
cancelled: false,
timedOut: false,
cellsRun: 0,
reset: Boolean(opts.reset),
onUpdate: opts.onUpdate,
};
const promise = new Promise<ExecuteResult>((resolveExec, rejectExec) => {
pending.resolve = resolveExec;
pending.reject = rejectExec;
});
this.pending = pending;
// Pre-seed cells so partial snapshots reflect requested order.
cells.forEach((cell, i) => {
pending.cells.set(i, {
index: i,
title: cell.title,
stdout: "",
stderr: "",
value: "",
ok: false,
exception: "",
});
});
const onAbort = () => {
pending.cancelled = true;
this.interrupt();
};
if (opts.signal) {
if (opts.signal.aborted) onAbort();
else opts.signal.addEventListener("abort", onAbort, { once: true });
}
if (opts.timeoutMs && opts.timeoutMs > 0) {
const graceMs = opts.interruptGraceMs ?? 30_000;
pending.timer = setTimeout(() => {
pending.timedOut = true;
pending.cancelled = true;
this.interrupt();
// Send SIGINT first; the runner re-enables Python's default
// interrupt handler around each cell so the SIGINT becomes a
// KeyboardInterrupt the cell catches, returning cleanly with
// the namespace intact.
//
// A cell sitting inside a C extension (capstone, pysap,
// playwright, a blocking socket read) never reaches an
// interpreter check, so the first SIGINT does nothing. Send a
// second one midway through the grace period: Python-level
// loops that swallowed the first, and libraries that install
// their own handler, often act on the repeat.
if (graceMs > 0) {
pending.retryTimer = setTimeout(
() => {
if (this.pending === pending) this.interrupt();
},
Math.floor(graceMs / 2),
);
// Last resort. Costs the namespace, so the result carries
// `killed` and every byte captured so far.
pending.graceTimer = setTimeout(() => {
if (this.pending === pending) this.kill();
}, graceMs);
}
}, opts.timeoutMs);
}
const payload = JSON.stringify({
id,
cells: cells.map((c) => ({ code: c.code, title: c.title })),
reset: Boolean(opts.reset),
cwd: opts.cwd,
});
try {
proc.stdin.write(`${payload}\n`);
} catch (err) {
this.pending = null;
throw err instanceof Error ? err : new Error(String(err));
}
try {
return await promise;
} finally {
if (opts.signal) opts.signal.removeEventListener("abort", onAbort);
// All three must be cleared: the grace/retry timers outlive the
// timeout timer by design, and a stray one left armed keeps the
// event loop alive for up to graceMs after the call returned.
if (pending.timer) clearTimeout(pending.timer);
if (pending.retryTimer) clearTimeout(pending.retryTimer);
if (pending.graceTimer) clearTimeout(pending.graceTimer);
}
}
/** Interrupt the current cell, preserving the kernel where the OS permits it. */
interrupt(): void {
// Node cannot deliver a catchable SIGINT to a Windows child: kill("SIGINT")
// terminates it outright and the exit event rejects the request before we can
// return a useful result. Make that unavoidable hard kill explicit instead,
// preserving partial output and reporting `killed: true` consistently.
if (process.platform === "win32") {
this.kill();
return;
}
if (this.proc && this.proc.exitCode === null) {
try {
this.proc.kill("SIGINT");
} catch {
// best-effort
}
}
}
/**
* Hard-kill the kernel. The next execute() will respawn it.
*
* If a request is in flight it is *resolved* with whatever output the
* cells produced before the kill, flagged `killed`, rather than
* rejected. Rejecting used to throw away every byte the cell had
* printed — a 10-minute sweep that hung on its last HTTP call came back
* as the bare string "python kernel killed" with all its findings
* discarded. Partial output is usually the most valuable thing we have
* at that point, so it must survive.
*/
kill(): void {
if (!this.proc) return;
try {
this.proc.kill("SIGKILL");
} catch {
// best-effort
}
this.proc = null;
this.readyInfo = null;
this.readyPromise = null;
if (this.pending) {
const pending = this.pending;
this.pending = null;
pending.killed = true;
pending.cancelled = true;
pending.resolve(this.snapshot(pending));
}
}
/** Polite shutdown — close stdin so the runner exits, then reap. */
async shutdown(): Promise<void> {
const proc = this.proc;
if (!proc) return;
try {
proc.stdin.end();
} catch {
// ignore
}
const exited = await new Promise<boolean>((resolveExit) => {
const timer = setTimeout(() => resolveExit(false), 500);
proc.once("exit", () => {
clearTimeout(timer);
resolveExit(true);
});
});
if (!exited) this.kill();
this.proc = null;
this.readyInfo = null;
this.readyPromise = null;
}
}
/**
* Resolve which python interpreter to use.
*
* Order of precedence:
* 1. Explicit `override` (the `--python` flag or `python_set_interpreter`).
* 2. `$PI_PYTHON` env var.
* 3. `$VIRTUAL_ENV` env var (canonical for direnv / `source .venv/bin/activate`).
* 4. A venv directory — named by `venvDirNames`, default `.venv` and
* `venv` — found in `cwd`. When `walkParents` is true (the default),
* the search ascends from `cwd` until either a venv is found or a
* repo root (dir with `.git`) is encountered — we never cross a repo
* boundary, so a pi session started in some unrelated subdir won't
* latch onto a far-away venv.
* 5. Bare `python3` / `python.exe` on PATH; spawn() resolves it.
*/
export function resolvePythonPath(opts: {
override?: string | null;
cwd: string;
env?: NodeJS.ProcessEnv;
walkParents?: boolean;
venvDirNames?: string[];
}): string {
const env = opts.env ?? process.env;
// Explicit override wins. Validate it points at an actual binary so a
// stale override doesn't silently fall back and leave the user wondering
// why the wrong python is in use.
if (opts.override) {
return validateInterpreterPath(opts.override);
}
const candidates: string[] = [];
if (env.PI_PYTHON) candidates.push(env.PI_PYTHON);
if (env.VIRTUAL_ENV) {
candidates.push(join(env.VIRTUAL_ENV, "bin", "python"));
candidates.push(join(env.VIRTUAL_ENV, "Scripts", "python.exe"));
}
const venvDirs = opts.venvDirNames ?? [".venv", "venv"];
const walk = opts.walkParents !== false;
let dir = opts.cwd;
while (true) {
for (const sub of venvDirs) {
candidates.push(resolve(dir, sub, "bin", "python"));
candidates.push(resolve(dir, sub, "Scripts", "python.exe"));
}
if (!walk) break;
// This level is a repo root — search it (already pushed above) then stop.
if (existsSync(join(dir, ".git"))) break;
const parent = dirname(dir);
if (parent === dir) break; // filesystem root
dir = parent;
}
for (const candidate of candidates) {
if (candidate && existsSync(candidate)) return candidate;
}
// Fall through to a name on PATH; spawn() will resolve it.
return process.platform === "win32" ? "python.exe" : "python3";
}
/**
* Validate that `input` points at a python interpreter binary.
*
* Accepts:
* - an absolute or relative path to an existing file
* - a bare command name (e.g. "python3.12") to be resolved on PATH by spawn()
*
* Rejects directories — if a venv happens to live behind the binary, that's
* incidental; callers must pass the binary path itself, not the venv root.
*/
export function validateInterpreterPath(input: string): string {
const trimmed = input.trim();
if (!trimmed) throw new Error("interpreter path is empty");
// Bare command names (no path separator) are deferred to PATH lookup at
// spawn time. We don't try to resolve them eagerly because PATH may
// differ between the host process and the eventual subprocess env.
const looksLikePath = isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\");
if (!looksLikePath) return trimmed;
const path = resolve(trimmed);
if (!existsSync(path)) {
throw new Error(`Python interpreter not found: ${path}`);
}
if (statSync(path).isDirectory()) {
throw new Error(
`Expected a python interpreter binary, got a directory: ${path}. ` +
`Pass the path to the interpreter itself (e.g. ${join(path, "bin", "python")}).`,
);
}
return path;
}
export interface InterpreterCheck {
ok: boolean;
/** First line of stdout when ok (e.g. "Python 3.12.3"), or empty. */
version: string;
/** Error message when !ok. */
error: string;
}
/**
* Cheap smoke-test: spawn `<interpreter> --version` synchronously and
* inspect the result. Catches typos in --python flags / settings before the
* agent makes its first call. Pure validation — no kernel started.
*/
export function verifyInterpreterRuns(
interpreter: string,
timeoutMs = 3000,
): InterpreterCheck {
try {
const result = spawnSync(interpreter, ["--version"], {
encoding: "utf-8",
timeout: timeoutMs,
shell: false,
});
if (result.error) {
return { ok: false, version: "", error: result.error.message };
}
if (result.signal) {
return { ok: false, version: "", error: `killed by signal ${result.signal}` };
}
if (result.status !== 0) {
const stderr = (result.stderr ?? "").trim();
return {
ok: false,
version: "",
error: `exit ${result.status}${stderr ? `: ${stderr}` : ""}`,
};
}
// `python --version` writes to stdout on 3.4+, stderr on older builds.
const combined = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim();
const firstLine = combined.split("\n")[0]?.trim() ?? "";
return { ok: true, version: firstLine, error: "" };
} catch (err) {
return {
ok: false,
version: "",
error: err instanceof Error ? err.message : String(err),
};
}
}
/**
* Raise a process's `oom_score_adj` so the kernel OOM killer prefers it over
* longer-lived services. Raising needs no privilege; a value at or below the
* current one is left alone (lowering would need CAP_SYS_RESOURCE).
* Best-effort: any failure leaves the default in place.
*/
function raiseOomScore(pid: number, value: number): void {
const path = `/proc/${pid}/oom_score_adj`;
try {
const current = Number(readFileSync(path, "utf8").trim());
if (Number.isFinite(current) && value > current) writeFileSync(path, String(value));
} catch {
// not Linux, or the process is already gone
}
}