@code-yeongyu/senpi-codemode 2026.11.2-1 → 2026.11.2-3
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/CHANGELOG.md +27 -0
- package/package.json +4 -4
- package/src/bridge/http-server.ts +32 -3
- package/src/bridge/protocol.ts +4 -0
- package/src/extension/runtime-factory.ts +13 -2
- package/src/extension/session-manager-contract.ts +2 -0
- package/src/extension/session-manager.ts +16 -1
- package/src/kernels/js/interpose.js +8 -0
- package/src/kernels/js/kernel-contract.ts +2 -0
- package/src/kernels/js/permission-runtime.js +2 -0
- package/src/kernels/js/process-entry.js +4 -2
- package/src/kernels/js/process-tree.js +7 -6
- package/src/kernels/js/worker-core.js +25 -0
- package/src/kernels/js/worker-kill-guard.js +131 -0
- package/src/kernels/js/worker-runtime.js +3 -0
- package/src/kernels/js/worker-shell-capture.d.ts +2 -0
- package/src/kernels/js/worker-shell-capture.js +42 -8
- package/src/kernels/js/worker-startup.ts +3 -0
- package/src/kernels/py/kernel-contract.ts +2 -0
- package/src/kernels/py/kill_guard.py +158 -0
- package/src/kernels/py/prelude.py +19 -2
- package/src/kernels/py/transport.ts +5 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,32 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [2026.11.2-3] - 2026-11-02
|
|
4
|
+
|
|
5
|
+
### Breaking Changes
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- Eval cells are judged by the kill guard before a signal leaves them: JS `Bun.$` (and `new Bun.$.Shell()` instances), `Bun.spawn`/`spawnSync`, `child_process` and `process.kill`, and Python `subprocess`, `os.system`, `os.popen`, `os.exec*`/`spawn*`, `os.kill` and `os.killpg`, whether or not permission enforcement is on ([#5354](https://github.com/code-yeongyu/senpi/pull/5354))
|
|
10
|
+
- Eval kernels and the processes they start get the kill guard's runtime shims on `PATH`, its `BASH_ENV` wrapper and its interactive-bash `PROMPT_COMMAND` hook while the guard is on, so `kill`, `pkill` and `killall` run from a cell or its children are judged on their real arguments ([#5358](https://github.com/code-yeongyu/senpi/pull/5358))
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
### Removed
|
|
17
|
+
|
|
18
|
+
## [2026.11.2-2] - 2026-11-02
|
|
19
|
+
|
|
20
|
+
### Breaking Changes
|
|
21
|
+
|
|
22
|
+
### Added
|
|
23
|
+
|
|
24
|
+
### Changed
|
|
25
|
+
|
|
26
|
+
### Fixed
|
|
27
|
+
|
|
28
|
+
### Removed
|
|
29
|
+
|
|
3
30
|
## [2026.11.02-1] - 2026-11-02
|
|
4
31
|
|
|
5
32
|
### Breaking Changes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@code-yeongyu/senpi-codemode",
|
|
3
|
-
"version": "2026.11.
|
|
3
|
+
"version": "2026.11.2-3",
|
|
4
4
|
"description": "Source-only senpi extension package for codemode evaluation tools",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.ts",
|
|
@@ -33,15 +33,15 @@
|
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"@babel/parser": "8.0.4",
|
|
36
|
-
"@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.11.
|
|
36
|
+
"@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.11.2-3",
|
|
37
37
|
"quickjs-wasi": "3.6.2",
|
|
38
38
|
"typebox": "1.3.34"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
|
-
"@code-yeongyu/senpi": "2026.11.
|
|
41
|
+
"@code-yeongyu/senpi": "2026.11.2-3"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@code-yeongyu/senpi": "2026.11.
|
|
44
|
+
"@code-yeongyu/senpi": "2026.11.2-3"
|
|
45
45
|
},
|
|
46
46
|
"keywords": [
|
|
47
47
|
"senpi",
|
|
@@ -34,6 +34,8 @@ export interface BridgeServerOptions {
|
|
|
34
34
|
onCall: (request: BridgeHttpCallRequest) => Promise<unknown>;
|
|
35
35
|
onEmit: (event: BridgeHttpEmitEvent, signal: AbortSignal) => Promise<void>;
|
|
36
36
|
onCompletion: (request: BridgeHttpCompletionRequest) => Promise<unknown>;
|
|
37
|
+
/** Decides a kernel's kill-guard check (senpi#5349); needs no permission token, so it works in full-access mode. */
|
|
38
|
+
onKillGuardCheck?: (request: unknown) => unknown;
|
|
37
39
|
}
|
|
38
40
|
|
|
39
41
|
export interface BridgeServerHandle {
|
|
@@ -43,7 +45,7 @@ export interface BridgeServerHandle {
|
|
|
43
45
|
}
|
|
44
46
|
|
|
45
47
|
type JsonReply = { ok: true; value: unknown } | { ok: false; error: BridgeError };
|
|
46
|
-
type Route = "/call" | "/emit" | "/completion" | "/permission_check";
|
|
48
|
+
type Route = "/call" | "/emit" | "/completion" | "/permission_check" | "/kill_guard_check";
|
|
47
49
|
|
|
48
50
|
export async function startBridgeServer(options: BridgeServerOptions): Promise<BridgeServerHandle> {
|
|
49
51
|
const token = options.token ?? generateBridgeToken();
|
|
@@ -95,7 +97,11 @@ async function handleRequest(
|
|
|
95
97
|
return;
|
|
96
98
|
}
|
|
97
99
|
const auth = parseBearerToken(request.headers.authorization);
|
|
98
|
-
if (
|
|
100
|
+
if (
|
|
101
|
+
route !== "/permission_check" &&
|
|
102
|
+
route !== "/kill_guard_check" &&
|
|
103
|
+
(!auth || !verifyBridgeToken(token, auth).ok)
|
|
104
|
+
) {
|
|
99
105
|
sendJson(response, 401, { ok: false, error: transportError("unauthorized", "Bridge authorization failed") });
|
|
100
106
|
return;
|
|
101
107
|
}
|
|
@@ -114,6 +120,22 @@ async function handleRequest(
|
|
|
114
120
|
return;
|
|
115
121
|
}
|
|
116
122
|
|
|
123
|
+
if (route === "/kill_guard_check") {
|
|
124
|
+
if (options.onKillGuardCheck === undefined) {
|
|
125
|
+
sendJson(response, 404, {
|
|
126
|
+
ok: false,
|
|
127
|
+
error: transportError("not_found", "The kill guard is off for this bridge"),
|
|
128
|
+
});
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
sendJson(response, 200, { ok: true, value: await options.onKillGuardCheck(parsed.value) });
|
|
133
|
+
} catch (error) {
|
|
134
|
+
sendJson(response, 200, { ok: false, error: bridgeError(error) });
|
|
135
|
+
}
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
|
|
117
139
|
if (route === "/emit") {
|
|
118
140
|
const event = parseEmitEvent(parsed.value);
|
|
119
141
|
if (!event.ok) {
|
|
@@ -218,7 +240,14 @@ function parseEmitEvent(value: unknown): { ok: true; event: BridgeHttpEmitEvent
|
|
|
218
240
|
|
|
219
241
|
function routeFromUrl(rawUrl: string): Route | undefined {
|
|
220
242
|
const path = new URL(rawUrl, "http://127.0.0.1").pathname;
|
|
221
|
-
if (
|
|
243
|
+
if (
|
|
244
|
+
path === "/call" ||
|
|
245
|
+
path === "/emit" ||
|
|
246
|
+
path === "/completion" ||
|
|
247
|
+
path === "/permission_check" ||
|
|
248
|
+
path === "/kill_guard_check"
|
|
249
|
+
)
|
|
250
|
+
return path;
|
|
222
251
|
return undefined;
|
|
223
252
|
}
|
|
224
253
|
|
package/src/bridge/protocol.ts
CHANGED
|
@@ -45,6 +45,10 @@ const hostToKernelMessageSchema = Type.Union([
|
|
|
45
45
|
hostToolNames: Type.Optional(Type.Array(Type.String({ minLength: 1 }))),
|
|
46
46
|
foreignLanguageNames: Type.Optional(Type.Array(Type.String({ minLength: 1 }))),
|
|
47
47
|
memory: Type.Optional(kernelMemoryThresholdsSchema),
|
|
48
|
+
/** JS kernels: the kill guard's judge module (imported by URL in the worker) and the agent host's pid (senpi#5349). */
|
|
49
|
+
killGuard: Type.Optional(
|
|
50
|
+
Type.Object({ moduleUrl: Type.String({ minLength: 1 }), agentPid: Type.Integer({ minimum: 1 }) }),
|
|
51
|
+
),
|
|
48
52
|
}),
|
|
49
53
|
Type.Object({
|
|
50
54
|
type: Type.Literal("run"),
|
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
activeKillGuardEnvironment,
|
|
3
|
+
type ExtensionContext,
|
|
4
|
+
readKillGuardSetting,
|
|
5
|
+
withBundledBunCommands,
|
|
6
|
+
} from "@code-yeongyu/senpi";
|
|
2
7
|
import type { AgentExecuteTool } from "../bridges/agent-bridge.ts";
|
|
3
8
|
import type { EvalSchemaToolInfo } from "../bridges/schema-bridge.ts";
|
|
4
9
|
import type { CompletionRequest, CompletionResult } from "../completion/handler.ts";
|
|
@@ -89,7 +94,12 @@ export async function createRuntime(
|
|
|
89
94
|
const executeTool = createExecuteTool(pi, activeTools);
|
|
90
95
|
const create = options.createSessionManager ?? createCodemodeSessionManager;
|
|
91
96
|
const sessionId = sessionIdFrom(event);
|
|
92
|
-
const
|
|
97
|
+
const killGuard = readKillGuardSetting(ctx.cwd, ctx.agentDir) === "on";
|
|
98
|
+
const pathEntry = bundledBunPathEntry();
|
|
99
|
+
// The kill guard's runtime layer (senpi#5349): kernels and their children get the shims first on PATH and
|
|
100
|
+
// bash's BASH_ENV wrapper, as the bash tool does.
|
|
101
|
+
const killGuardEnv = killGuard ? activeKillGuardEnvironment({ ...process.env, ...pathEntry }) : {};
|
|
102
|
+
const sessionEnv = { ...sessionEnvironmentFrom(ctx), ...pathEntry, ...killGuardEnv };
|
|
93
103
|
const configuredPoolWidth = settings.parallelPoolWidth;
|
|
94
104
|
const parallelPoolWidth = Number.isFinite(configuredPoolWidth) ? Math.max(1, Math.trunc(configuredPoolWidth)) : 1;
|
|
95
105
|
const pythonEnvironments =
|
|
@@ -106,6 +116,7 @@ export async function createRuntime(
|
|
|
106
116
|
ownerSessionId: ctx.sessionManager.getSessionId(),
|
|
107
117
|
cwd: ctx.cwd,
|
|
108
118
|
sessionEnv,
|
|
119
|
+
killGuard,
|
|
109
120
|
settings,
|
|
110
121
|
availability,
|
|
111
122
|
artifactsDir: artifacts.dir,
|
|
@@ -38,6 +38,8 @@ export interface CreateCodemodeSessionManagerOptions {
|
|
|
38
38
|
readonly artifactsDir?: string;
|
|
39
39
|
/** Per-session PI_* values exposed to every kernel and the children it spawns. */
|
|
40
40
|
readonly sessionEnv?: SessionEnvironment;
|
|
41
|
+
/** The kill guard is on (`terminal.killGuard` in user settings): kernels judge signals before they leave a cell. */
|
|
42
|
+
readonly killGuard?: boolean;
|
|
41
43
|
readonly executeTool: ExecuteTool;
|
|
42
44
|
readonly listTools?: () => readonly EvalSchemaToolInfo[];
|
|
43
45
|
readonly complete: (request: CompletionRequest, ctx: ExtensionContext) => Promise<CompletionResult>;
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
2
|
import type { ExtensionContext } from "@code-yeongyu/senpi";
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
decideKillGuardRequest,
|
|
5
|
+
KILL_GUARD_MODULE_URL,
|
|
6
|
+
killGuardProtectedPids,
|
|
7
|
+
readProcessFootprint,
|
|
8
|
+
} from "@code-yeongyu/senpi";
|
|
4
9
|
import { type BridgeServerHandle, startBridgeServer } from "../bridge/http-server.ts";
|
|
5
10
|
import type { KernelToHostMessage } from "../bridge/protocol.ts";
|
|
6
11
|
import type { CompletionRequest, CompletionResult } from "../completion/handler.ts";
|
|
@@ -95,6 +100,12 @@ class DefaultCodemodeSessionManager implements CodemodeSessionManager {
|
|
|
95
100
|
onCall: async (request) => await this.#call(request),
|
|
96
101
|
onEmit: async () => undefined,
|
|
97
102
|
onCompletion: async (request) => await dispatchBridgeCompletion(this.#options, request, dispatch),
|
|
103
|
+
...(this.#options.killGuard === true
|
|
104
|
+
? {
|
|
105
|
+
onKillGuardCheck: (request: unknown) =>
|
|
106
|
+
decideKillGuardRequest(request, { agentPid: process.pid, agentPpid: process.ppid }),
|
|
107
|
+
}
|
|
108
|
+
: {}),
|
|
98
109
|
});
|
|
99
110
|
}
|
|
100
111
|
|
|
@@ -285,6 +296,9 @@ class DefaultCodemodeSessionManager implements CodemodeSessionManager {
|
|
|
285
296
|
: {}),
|
|
286
297
|
...(resolveKernelToolsEnabled(this.#options.settings) ? {} : { kernelToolsEnabled: false }),
|
|
287
298
|
...(this.#options.sessionEnv ? { sessionEnv: this.#options.sessionEnv } : {}),
|
|
299
|
+
...(this.#options.killGuard === true
|
|
300
|
+
? { killGuard: { moduleUrl: KILL_GUARD_MODULE_URL, agentPid: process.pid } }
|
|
301
|
+
: {}),
|
|
288
302
|
...(localRoots ? { localRoots: { ...localRoots } } : {}),
|
|
289
303
|
...(this.#options.artifactsDir ? { artifactsDir: this.#options.artifactsDir } : {}),
|
|
290
304
|
});
|
|
@@ -307,6 +321,7 @@ class DefaultCodemodeSessionManager implements CodemodeSessionManager {
|
|
|
307
321
|
sessionId: this.#options.sessionId,
|
|
308
322
|
cwd: this.#options.cwd,
|
|
309
323
|
...(sessionEnv ? { sessionEnv } : {}),
|
|
324
|
+
...(this.#options.killGuard === true ? { killGuard: { protectedPids: killGuardProtectedPids() } } : {}),
|
|
310
325
|
connection,
|
|
311
326
|
onMessage,
|
|
312
327
|
...lifecycle,
|
|
@@ -43,11 +43,18 @@ const installGuardedWorker = (Guarded) => {
|
|
|
43
43
|
};
|
|
44
44
|
const originals = { ...fs.promises, readFileSync: fs.readFileSync, realpathSync: fs.realpathSync };
|
|
45
45
|
const execFile = process.getBuiltinModule("node:child_process").execFile;
|
|
46
|
+
const spawnSync = process.getBuiltinModule("node:child_process").spawnSync;
|
|
46
47
|
const cleanupExecFile = (...args) => {
|
|
47
48
|
engineDepth++;
|
|
48
49
|
try { return execFile(...args); }
|
|
49
50
|
finally { engineDepth--; }
|
|
50
51
|
};
|
|
52
|
+
// The kill guard reads the process table and dry-runs pgrep with the engine's own spawnSync, never a cell wrapper.
|
|
53
|
+
const killGuardSpawnSync = (...args) => {
|
|
54
|
+
engineDepth++;
|
|
55
|
+
try { return spawnSync(...args); }
|
|
56
|
+
finally { engineDepth--; }
|
|
57
|
+
};
|
|
51
58
|
const { dirname } = process.getBuiltinModule("node:path");
|
|
52
59
|
const permissionIO = {
|
|
53
60
|
read(raw, actual) { checkPath(authorize, "read", raw, { executed: actual }); return originals.readFile(actual, "utf8"); },
|
|
@@ -80,6 +87,7 @@ await initializePermissionRuntime((authorize) => { runtimeAuthorize = authorize;
|
|
|
80
87
|
permissionIO,
|
|
81
88
|
resolverIO: originals,
|
|
82
89
|
cleanupExecFile,
|
|
90
|
+
killGuardSpawnSync,
|
|
83
91
|
activate,
|
|
84
92
|
installGuardedWorker,
|
|
85
93
|
});
|
|
@@ -78,6 +78,8 @@ export interface JavaScriptKernelOptions {
|
|
|
78
78
|
readonly hostToolNames?: KernelToolNameSource;
|
|
79
79
|
/** `kernelTools.enabled`; false makes `tool(fn)` refuse with `tools_unavailable`. Unset keeps them on. */
|
|
80
80
|
readonly kernelToolsEnabled?: boolean;
|
|
81
|
+
/** The kill guard (senpi#5349): where the worker imports the judge from, and the agent host's pid. Absent = guard off. */
|
|
82
|
+
readonly killGuard?: { readonly moduleUrl: string | URL; readonly agentPid: number };
|
|
81
83
|
/** Tool names registered in another kernel language, denied as JS kernel-tool identifiers. */
|
|
82
84
|
readonly foreignLanguageNames?: KernelToolNameSource;
|
|
83
85
|
/** Post-cell collection, notice, and ceiling thresholds; absent leaves the worker's memory unmanaged. */
|
|
@@ -190,6 +190,8 @@ export async function initializePermissionRuntime(install, workerData, engine) {
|
|
|
190
190
|
const { initializeProcessCleanup } = await import("./process-tree.js");
|
|
191
191
|
const { initializeWindowsCleanup } = await import("./windows-tree-kill.js");
|
|
192
192
|
initializeProcessCleanup(engine.cleanupExecFile);
|
|
193
|
+
const { initializeKillGuardSpawn } = await import("./worker-kill-guard.js");
|
|
194
|
+
initializeKillGuardSpawn(engine.killGuardSpawnSync);
|
|
193
195
|
initializeWindowsCleanup(engine.cleanupExecFile);
|
|
194
196
|
createWorkerCore({
|
|
195
197
|
send: (message) => parentPort.postMessage(message),
|
|
@@ -25,6 +25,8 @@ import { scanDrainText } from "./process-drain-scan.js";
|
|
|
25
25
|
const stringify = JSON.stringify;
|
|
26
26
|
const writeBytes = writeSync;
|
|
27
27
|
const exit = process.exit.bind(process);
|
|
28
|
+
// The kernel stops itself with the original: the kill guard later wraps the cell-visible process.kill.
|
|
29
|
+
const signalSelf = process.kill.bind(process);
|
|
28
30
|
const fromString = (text) => Buffer.from(text, "utf8");
|
|
29
31
|
|
|
30
32
|
// The host refuses a frame over 10 MiB; text is split well below it (a char can escape to 6 bytes of JSON).
|
|
@@ -376,7 +378,7 @@ function writeAll(bytes) {
|
|
|
376
378
|
} catch (error) {
|
|
377
379
|
if (error && error.code === "EAGAIN") { Atomics.wait(pause, 0, 0, 2); continue; }
|
|
378
380
|
// The host is gone. process.exit would end only this thread, leaving the frame lock held.
|
|
379
|
-
|
|
381
|
+
signalSelf(process.pid, "SIGKILL");
|
|
380
382
|
}
|
|
381
383
|
}
|
|
382
384
|
}
|
|
@@ -437,7 +439,7 @@ function reportCrash(error) {
|
|
|
437
439
|
try {
|
|
438
440
|
writeBytes(2, fromString(`\nsenpi-kernel-crash ${frameToken} ${stringify(cause)}\n`));
|
|
439
441
|
} finally {
|
|
440
|
-
|
|
442
|
+
signalSelf(process.pid, "SIGKILL");
|
|
441
443
|
}
|
|
442
444
|
}
|
|
443
445
|
process.on("uncaughtException", reportCrash);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
2
|
import { killWindowsTree, listWindowsRows } from "./windows-tree-kill.js";
|
|
3
|
+
import { signalUnjudged as signal } from "./worker-kill-guard.js";
|
|
3
4
|
|
|
4
5
|
// Plain JS (with process-tree.d.ts) because the worker runtime imports it and
|
|
5
6
|
// worker files cannot import TypeScript; the host imports the same module so a
|
|
@@ -22,17 +23,17 @@ export function initializeProcessCleanup(original) {
|
|
|
22
23
|
export function isProcessAlive(pid) {
|
|
23
24
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
24
25
|
try {
|
|
25
|
-
|
|
26
|
+
signal(pid, 0);
|
|
26
27
|
return true;
|
|
27
28
|
} catch (error) {
|
|
28
29
|
return isRecord(error) && error.code === "EPERM";
|
|
29
30
|
}
|
|
30
31
|
}
|
|
31
32
|
|
|
32
|
-
export function signalProcess(pid,
|
|
33
|
+
export function signalProcess(pid, signalName) {
|
|
33
34
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
34
35
|
try {
|
|
35
|
-
|
|
36
|
+
signal(pid, signalName);
|
|
36
37
|
return true;
|
|
37
38
|
} catch {
|
|
38
39
|
return false;
|
|
@@ -136,16 +137,16 @@ export async function terminateProcessGroups(groups, options) {
|
|
|
136
137
|
|
|
137
138
|
function groupHasMembers(pgid) {
|
|
138
139
|
try {
|
|
139
|
-
|
|
140
|
+
signal(-pgid, 0);
|
|
140
141
|
return true;
|
|
141
142
|
} catch (error) {
|
|
142
143
|
return isRecord(error) && error.code === "EPERM";
|
|
143
144
|
}
|
|
144
145
|
}
|
|
145
146
|
|
|
146
|
-
function signalGroup(pgid,
|
|
147
|
+
function signalGroup(pgid, signalName) {
|
|
147
148
|
try {
|
|
148
|
-
|
|
149
|
+
signal(-pgid, signalName);
|
|
149
150
|
} catch {
|
|
150
151
|
// The group emptied between the check and the signal.
|
|
151
152
|
}
|
|
@@ -37,6 +37,8 @@ export function createWorkerCore(transport, options) {
|
|
|
37
37
|
let memory = null;
|
|
38
38
|
let heapProbe = null;
|
|
39
39
|
let activeCell = null;
|
|
40
|
+
// The kill guard's judge, imported by URL before the runtime installs its wrappers (senpi#5349).
|
|
41
|
+
let killGuard;
|
|
40
42
|
const rejections = createRejectionReports({
|
|
41
43
|
activeCell: () => activeCell,
|
|
42
44
|
emitText: (data) => emit({ type: "text", stream: "stderr", data }),
|
|
@@ -68,6 +70,10 @@ export function createWorkerCore(transport, options) {
|
|
|
68
70
|
return;
|
|
69
71
|
}
|
|
70
72
|
const startedAtMs = performance.now();
|
|
73
|
+
if (killGuard?.notice !== undefined) {
|
|
74
|
+
emit({ type: "text", stream: "stderr", data: killGuard.notice });
|
|
75
|
+
killGuard = { ...killGuard, notice: undefined };
|
|
76
|
+
}
|
|
71
77
|
const release = Promise.withResolvers();
|
|
72
78
|
const cell = { cellId: message.cellId, interruption: null, released: false, release: release.reject };
|
|
73
79
|
activeCell = cell;
|
|
@@ -167,6 +173,13 @@ export function createWorkerCore(transport, options) {
|
|
|
167
173
|
return;
|
|
168
174
|
}
|
|
169
175
|
if (message.type === "init") {
|
|
176
|
+
if (message.killGuard !== undefined && killGuard === undefined) {
|
|
177
|
+
void loadKillGuard(message.killGuard).then((loaded) => {
|
|
178
|
+
killGuard = loaded;
|
|
179
|
+
onMessage(message);
|
|
180
|
+
});
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
170
183
|
applySessionEnvironment(message.sessionEnv);
|
|
171
184
|
installSessionCwd(options.cwd, options.cwdInstallOptions);
|
|
172
185
|
installKernelWebView(requestWebViewPort);
|
|
@@ -181,6 +194,7 @@ export function createWorkerCore(transport, options) {
|
|
|
181
194
|
hostToolNames: message.hostToolNames ?? [],
|
|
182
195
|
foreignLanguageNames: message.foreignLanguageNames ?? [],
|
|
183
196
|
kernelToolsDisabled: message.kernelToolsDisabled === true,
|
|
197
|
+
...(killGuard?.guard === undefined ? {} : { killGuard: killGuard.guard }),
|
|
184
198
|
onChildEvent: (event) => emit({ type: "status", event: { op: CHILD_LIFECYCLE_OP, ...event } }),
|
|
185
199
|
onShellWaitChange: () => {
|
|
186
200
|
if (activeCell?.interruption) acknowledgeInterrupt();
|
|
@@ -234,6 +248,17 @@ export function createWorkerCore(transport, options) {
|
|
|
234
248
|
};
|
|
235
249
|
}
|
|
236
250
|
|
|
251
|
+
// Judge missing: the cell runs unguarded with one notice, as the design's L2 shim does when its judge is gone.
|
|
252
|
+
async function loadKillGuard(spec) {
|
|
253
|
+
try {
|
|
254
|
+
const judge = await import(String(spec.moduleUrl));
|
|
255
|
+
return { guard: { judge, agentPid: spec.agentPid } };
|
|
256
|
+
} catch (error) {
|
|
257
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
258
|
+
return { notice: `[senpi:kill-guard] the kill guard's judge could not be loaded in this kernel (${detail}); signals from cells are not judged.\n` };
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
237
262
|
function durationMs(startedAtMs) {
|
|
238
263
|
return Math.max(0, Math.round(performance.now() - startedAtMs));
|
|
239
264
|
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// senpi#5349 / code-yeongyu/oh-my-openagent#12096: every signal a JS cell can send goes through the kill guard's judge
|
|
2
|
+
// first, whether or not a cell is active (a timer from an earlier cell signals too). The judge is the coding agent's
|
|
3
|
+
// own module, imported by URL at worker init; its process-table reads and dry runs use a spawnSync captured before any
|
|
4
|
+
// judging wrapper exists, so judging never re-enters a judging wrapper (amendment A8).
|
|
5
|
+
|
|
6
|
+
const { promisify } = process.getBuiltinModule("node:util");
|
|
7
|
+
const childProcess = process.getBuiltinModule("node:child_process");
|
|
8
|
+
|
|
9
|
+
// The cell-visible process.kill the guard replaced; senpi's own retirement signals go through it, never the guard.
|
|
10
|
+
let unguardedProcessKill;
|
|
11
|
+
|
|
12
|
+
/** Senpi-internal signalling (retiring a cell's own work): the process.kill that was there before the guard. */
|
|
13
|
+
export function signalUnjudged(pid, signal) {
|
|
14
|
+
return (unguardedProcessKill ?? process.kill).call(process, pid, signal);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// The permission runtime hands over the engine's own spawnSync (never a cell-facing wrapper) before any cell runs.
|
|
18
|
+
let engineSpawnSync;
|
|
19
|
+
|
|
20
|
+
export function initializeKillGuardSpawn(spawnSync) {
|
|
21
|
+
engineSpawnSync ??= spawnSync;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function capturedSpawnSync(judge) {
|
|
25
|
+
if (typeof engineSpawnSync === "function") return judge.spawnSyncFromNode(engineSpawnSync);
|
|
26
|
+
const bun = globalThis.Bun;
|
|
27
|
+
if (bun !== null && typeof bun === "object" && typeof bun.spawnSync === "function") {
|
|
28
|
+
const original = bun.spawnSync;
|
|
29
|
+
return judge.spawnSyncFromBun((argv, options) => original(argv, options));
|
|
30
|
+
}
|
|
31
|
+
const original = childProcess.spawnSync;
|
|
32
|
+
return judge.spawnSyncFromNode((file, args, options) => original(file, args, options));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function refusal(message) {
|
|
36
|
+
const error = new Error(message);
|
|
37
|
+
error.name = "KillGuardError";
|
|
38
|
+
error.code = "kill_guard_refused";
|
|
39
|
+
return error;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The checks a worker runs before a shell string, an argv or a signal leaves the cell. */
|
|
43
|
+
export function createKillGuard({ judge, agentPid }) {
|
|
44
|
+
const spawnSync = capturedSpawnSync(judge);
|
|
45
|
+
// The in-thread worker signals as the agent itself; a process-isolation kernel signals as its own process.
|
|
46
|
+
const vantage = process.pid === agentPid ? { kind: "agent" } : { kind: "process", pid: process.pid };
|
|
47
|
+
const context = (shell) =>
|
|
48
|
+
judge.killGuardContext({
|
|
49
|
+
platform: process.platform,
|
|
50
|
+
agentPid,
|
|
51
|
+
...(vantage.kind === "agent" ? { agentPpid: process.ppid } : {}),
|
|
52
|
+
vantage,
|
|
53
|
+
shell,
|
|
54
|
+
spawnSync,
|
|
55
|
+
});
|
|
56
|
+
const enforce = (verdict) => {
|
|
57
|
+
if (verdict.action === "refuse") throw refusal(verdict.message);
|
|
58
|
+
};
|
|
59
|
+
return {
|
|
60
|
+
command: (text, shell) => enforce(judge.judgeCommand(String(text), context(shell))),
|
|
61
|
+
argv: (argv) => enforce(judge.judgeArgv(argv.map(String), context("argv"))),
|
|
62
|
+
signal: (target, signal) =>
|
|
63
|
+
enforce(judge.judgeSignal({ target: Number(target), group: false, signal: signal ?? "SIGTERM" }, context("argv"))),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function childProcessCheck(guard, name, args) {
|
|
68
|
+
const [file, second, third] = args;
|
|
69
|
+
if (name === "exec" || name === "execSync") return guard.command(file, "sh");
|
|
70
|
+
const argv = Array.isArray(second) ? second : [];
|
|
71
|
+
const options = Array.isArray(second) || second == null ? third : second;
|
|
72
|
+
if (options?.shell) return guard.command([file, ...argv].join(" "), "sh");
|
|
73
|
+
return guard.argv([file, ...argv]);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const SPAWNERS = ["spawn", "spawnSync", "exec", "execSync", "execFile", "execFileSync"];
|
|
77
|
+
|
|
78
|
+
/** Wraps node:child_process and process.kill; returns the restore. */
|
|
79
|
+
export function installKillGuardWrappers(guard) {
|
|
80
|
+
const originals = new Map();
|
|
81
|
+
for (const name of SPAWNERS) {
|
|
82
|
+
const original = childProcess[name];
|
|
83
|
+
if (typeof original !== "function") continue;
|
|
84
|
+
originals.set(name, original);
|
|
85
|
+
const guarded = function killGuarded(...args) {
|
|
86
|
+
childProcessCheck(guard, name, args);
|
|
87
|
+
return original.apply(this, args);
|
|
88
|
+
};
|
|
89
|
+
// Every own property, symbols included: `util.promisify.custom` is what makes promisify(exec) resolve to
|
|
90
|
+
// { stdout, stderr }, and that custom function calls the original directly, so it is checked too.
|
|
91
|
+
for (const key of Reflect.ownKeys(original)) {
|
|
92
|
+
if (key === "length" || key === "name" || key === "prototype" || key === promisify.custom) continue;
|
|
93
|
+
const descriptor = Object.getOwnPropertyDescriptor(original, key);
|
|
94
|
+
if (descriptor) Object.defineProperty(guarded, key, descriptor);
|
|
95
|
+
}
|
|
96
|
+
const custom = original[promisify.custom];
|
|
97
|
+
if (typeof custom === "function") {
|
|
98
|
+
Object.defineProperty(guarded, promisify.custom, {
|
|
99
|
+
configurable: true,
|
|
100
|
+
value: function killGuardedPromisified(...args) {
|
|
101
|
+
childProcessCheck(guard, name, args);
|
|
102
|
+
return custom.apply(this, args);
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
childProcess[name] = guarded;
|
|
107
|
+
}
|
|
108
|
+
const originalKill = process.kill;
|
|
109
|
+
unguardedProcessKill = originalKill;
|
|
110
|
+
process.kill = function killGuardedSignal(pid, signal) {
|
|
111
|
+
guard.signal(pid, signal);
|
|
112
|
+
return originalKill.call(process, pid, signal);
|
|
113
|
+
};
|
|
114
|
+
return () => {
|
|
115
|
+
process.kill = originalKill;
|
|
116
|
+
unguardedProcessKill = undefined;
|
|
117
|
+
for (const [name, original] of originals) childProcess[name] = original;
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The text Bun.$ runs: each interpolated value is one escaped word, as Bun passes it (`{ raw }` stays raw). */
|
|
122
|
+
export function renderShellTemplate(strings, expressions, escape) {
|
|
123
|
+
if (!Array.isArray(strings)) return String(strings ?? "");
|
|
124
|
+
const quote = typeof escape === "function" ? (value) => escape(String(value)) : (value) => String(value);
|
|
125
|
+
const render = (value) => {
|
|
126
|
+
if (Array.isArray(value)) return value.map(render).join(" ");
|
|
127
|
+
if (value !== null && typeof value === "object" && typeof value.raw === "string") return value.raw;
|
|
128
|
+
return quote(value);
|
|
129
|
+
};
|
|
130
|
+
return strings.reduce((text, part, index) => text + part + (index < expressions.length ? render(expressions[index]) : ""), "");
|
|
131
|
+
}
|
|
@@ -39,8 +39,10 @@ export class JsWorkerRuntime {
|
|
|
39
39
|
#onChildEvent;
|
|
40
40
|
#onShellWaitChange;
|
|
41
41
|
#tools;
|
|
42
|
+
#killGuard;
|
|
42
43
|
|
|
43
44
|
constructor(options) {
|
|
45
|
+
this.#killGuard = options.killGuard;
|
|
44
46
|
this.#parallelPoolWidth = options.parallelPoolWidth;
|
|
45
47
|
this.#onChildEvent = typeof options.onChildEvent === "function" ? options.onChildEvent : null;
|
|
46
48
|
this.#onShellWaitChange = options.onShellWaitChange;
|
|
@@ -219,6 +221,7 @@ export class JsWorkerRuntime {
|
|
|
219
221
|
isActive: () => this.#hooks !== null,
|
|
220
222
|
emitText: (stream, data) => this.#emitText(stream, data),
|
|
221
223
|
onChild: (child, spawnOptions) => this.#trackChild(child, spawnOptions),
|
|
224
|
+
...(this.#killGuard === undefined ? {} : { killGuard: this.#killGuard }),
|
|
222
225
|
onShellWait: (promise, waiting) => {
|
|
223
226
|
if (waiting) this.#shellWaits.add(promise);
|
|
224
227
|
else this.#shellWaits.delete(promise);
|
|
@@ -17,6 +17,8 @@ export interface ShellCaptureOptions {
|
|
|
17
17
|
readonly onChild?: (child: ShellCaptureChild, spawnOptions?: unknown) => void;
|
|
18
18
|
/** Tracks native shell waits without starting an unawaited ShellPromise. */
|
|
19
19
|
readonly onShellWait?: (promise: object, waiting: boolean) => void;
|
|
20
|
+
/** The kill guard (senpi#5349): the judge module a worker imported by URL, and the agent host's pid. */
|
|
21
|
+
readonly killGuard?: { readonly judge: unknown; readonly agentPid: number };
|
|
20
22
|
}
|
|
21
23
|
|
|
22
24
|
export function installShellCapture(options: ShellCaptureOptions): ShellCaptureRestore;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { assertCellLive } from "./cell-run-context.js";
|
|
2
2
|
import { groupSignalNotice, noticeChildProcessGroupSignals, shellCommandText, signalsProcessGroup } from "./group-signal-notice.js";
|
|
3
|
+
import { createKillGuard, installKillGuardWrappers, renderShellTemplate } from "./worker-kill-guard.js";
|
|
3
4
|
|
|
4
5
|
const SHELL_CONFIG_METHODS = ["env", "cwd", "nothrow", "throws"];
|
|
5
6
|
const SHELL_READ_METHODS = ["text", "json", "lines", "arrayBuffer", "bytes", "blob"];
|
|
@@ -12,8 +13,10 @@ const STDIN_ISOLATION_HEAD = "true | (\n";
|
|
|
12
13
|
const STDIN_ISOLATION_TAIL = "\n)";
|
|
13
14
|
|
|
14
15
|
export function installShellCapture(options) {
|
|
16
|
+
// Created before any wrapper below, so the judge's own reads use the originals (A8).
|
|
17
|
+
const guard = options.killGuard === undefined ? undefined : createKillGuard(options.killGuard);
|
|
15
18
|
const bun = globalThis.Bun;
|
|
16
|
-
if (!isBunRuntime(bun)) return () => {};
|
|
19
|
+
if (!isBunRuntime(bun)) return guard === undefined ? () => {} : installKillGuardWrappers(guard);
|
|
17
20
|
const originalShell = bun.$;
|
|
18
21
|
const originalSpawn = bun.spawn;
|
|
19
22
|
const originalSpawnSync = typeof bun.spawnSync === "function" ? bun.spawnSync : null;
|
|
@@ -26,11 +29,14 @@ export function installShellCapture(options) {
|
|
|
26
29
|
// environment view mirrors the bash tool, which always spawns with an explicit env.
|
|
27
30
|
originalShell.env({ ...process.env });
|
|
28
31
|
}
|
|
29
|
-
bun.$ = capturedShell(originalShell, options);
|
|
30
|
-
bun.spawn = capturedSpawn(originalSpawn, options, pinEnv);
|
|
31
|
-
if (originalSpawnSync !== null) bun.spawnSync = capturedSpawnSync(originalSpawnSync, pinEnv);
|
|
32
|
+
bun.$ = capturedShell(originalShell, options, guard);
|
|
33
|
+
bun.spawn = capturedSpawn(originalSpawn, options, pinEnv, guard);
|
|
34
|
+
if (originalSpawnSync !== null) bun.spawnSync = capturedSpawnSync(originalSpawnSync, pinEnv, guard);
|
|
32
35
|
const restoreChildProcessNotice = noticeChildProcessGroupSignals(options.emitText, options.isActive);
|
|
36
|
+
// Outermost, so a refused command never reaches the group-signal notice.
|
|
37
|
+
const restoreKillGuard = guard === undefined ? () => {} : installKillGuardWrappers(guard);
|
|
33
38
|
return () => {
|
|
39
|
+
restoreKillGuard();
|
|
34
40
|
restoreChildProcessNotice();
|
|
35
41
|
bun.$ = originalShell;
|
|
36
42
|
bun.spawn = originalSpawn;
|
|
@@ -42,15 +48,17 @@ function isBunRuntime(bun) {
|
|
|
42
48
|
return bun !== null && typeof bun === "object" && typeof bun.$ === "function" && typeof bun.spawn === "function";
|
|
43
49
|
}
|
|
44
50
|
|
|
45
|
-
function capturedShell(originalShell, options) {
|
|
51
|
+
function capturedShell(originalShell, options, guard, escape = originalShell.escape) {
|
|
46
52
|
const shell = (strings, ...expressions) => {
|
|
47
53
|
assertCellLive();
|
|
54
|
+
guard?.command(renderShellTemplate(strings, expressions, escape), "bun");
|
|
48
55
|
if (!options.isActive()) return originalShell(strings, ...expressions);
|
|
49
56
|
if (signalsProcessGroup(shellCommandText(strings, expressions))) options.emitText("stderr", groupSignalNotice("Bun.$"));
|
|
50
57
|
const promise = originalShell(isolateStdin(strings), ...expressions);
|
|
51
58
|
return captureShellPromise(promise, options);
|
|
52
59
|
};
|
|
53
|
-
|
|
60
|
+
copyShellKeys(shell, originalShell);
|
|
61
|
+
if (typeof originalShell.Shell === "function") shell.Shell = capturedShellClass(originalShell.Shell, options, guard, escape);
|
|
54
62
|
for (const method of SHELL_CONFIG_METHODS) {
|
|
55
63
|
shell[method] = (...args) => {
|
|
56
64
|
originalShell[method](...args);
|
|
@@ -60,6 +68,25 @@ function capturedShell(originalShell, options) {
|
|
|
60
68
|
return shell;
|
|
61
69
|
}
|
|
62
70
|
|
|
71
|
+
// Copies the shell's enumerable own keys the wrapper does not already own, as ordinary writable properties. A
|
|
72
|
+
// function's own `name` and `length` are read-only, so assigning them throws in a module: on Bun 1.4.4 the only own
|
|
73
|
+
// enumerable key of a `new Bun.$.Shell()` instance is `name`. The source's flags are not copied either, because
|
|
74
|
+
// `Bun.$.Shell` itself is non-writable there and the wrapper replaces it right after.
|
|
75
|
+
function copyShellKeys(target, source) {
|
|
76
|
+
for (const key of Object.keys(source)) {
|
|
77
|
+
if (Object.hasOwn(target, key)) continue;
|
|
78
|
+
Object.defineProperty(target, key, { value: source[key], writable: true, enumerable: true, configurable: true });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// `new Bun.$.Shell()` builds an independent `$` with its own env and cwd; each instance is judged and captured
|
|
83
|
+
// exactly like `Bun.$` itself, so it is no way around the kill guard.
|
|
84
|
+
function capturedShellClass(OriginalShell, options, guard, escape) {
|
|
85
|
+
return function Shell(...args) {
|
|
86
|
+
return capturedShell(new OriginalShell(...args), options, guard, escape);
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
63
90
|
function isolateStdin(strings) {
|
|
64
91
|
if (!Array.isArray(strings) || !Array.isArray(strings.raw)) return strings;
|
|
65
92
|
const cooked = [...strings];
|
|
@@ -138,9 +165,10 @@ function outputText(value) {
|
|
|
138
165
|
|
|
139
166
|
// Bun.spawnSync inherits the OS environ the same way Bun.spawn does, so a cell calling it
|
|
140
167
|
// without an explicit env must get the worker's view pinned too (measured on Bun 1.4.0).
|
|
141
|
-
function capturedSpawnSync(originalSpawnSync, pinEnv) {
|
|
168
|
+
function capturedSpawnSync(originalSpawnSync, pinEnv, guard) {
|
|
142
169
|
return (...args) => {
|
|
143
170
|
assertCellLive();
|
|
171
|
+
judgeSpawn(guard, args[0]);
|
|
144
172
|
if (!pinEnv) return originalSpawnSync(...args);
|
|
145
173
|
const [first, second] = args;
|
|
146
174
|
if (Array.isArray(first)) {
|
|
@@ -155,9 +183,15 @@ function capturedSpawnSync(originalSpawnSync, pinEnv) {
|
|
|
155
183
|
};
|
|
156
184
|
}
|
|
157
185
|
|
|
158
|
-
function
|
|
186
|
+
function judgeSpawn(guard, first) {
|
|
187
|
+
const argv = Array.isArray(first) ? first : first?.cmd;
|
|
188
|
+
if (guard !== undefined && Array.isArray(argv)) guard.argv(argv);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function capturedSpawn(originalSpawn, options, pinEnv, guard) {
|
|
159
192
|
return (...args) => {
|
|
160
193
|
assertCellLive();
|
|
194
|
+
judgeSpawn(guard, args[0]);
|
|
161
195
|
if (!options.isActive()) return originalSpawn(...args);
|
|
162
196
|
const [first, second] = args;
|
|
163
197
|
let child;
|
|
@@ -107,6 +107,9 @@ async function initializeWorker(worker: WorkerLike, hooks: WorkerStartupHooks, s
|
|
|
107
107
|
...(options.sessionEnv === undefined ? {} : { sessionEnv: options.sessionEnv }),
|
|
108
108
|
...(options.memory === undefined ? {} : { memory: options.memory }),
|
|
109
109
|
...(options.kernelToolsEnabled === false ? { kernelToolsDisabled: true } : {}),
|
|
110
|
+
...(options.killGuard === undefined
|
|
111
|
+
? {}
|
|
112
|
+
: { killGuard: { moduleUrl: String(options.killGuard.moduleUrl), agentPid: options.killGuard.agentPid } }),
|
|
110
113
|
});
|
|
111
114
|
await ready;
|
|
112
115
|
}
|
|
@@ -20,6 +20,8 @@ export interface PythonKernelStartOptions extends KernelLifecycle {
|
|
|
20
20
|
readonly env?: NodeJS.ProcessEnv;
|
|
21
21
|
/** Per-session PI_* values merged into the interpreter environment at spawn. */
|
|
22
22
|
readonly sessionEnv?: SessionEnvironment;
|
|
23
|
+
/** The kill guard (senpi#5349): the host's protected pids; absent = the guard is off for this kernel. */
|
|
24
|
+
readonly killGuard?: { readonly protectedPids: readonly number[] };
|
|
23
25
|
/** How long a starting interpreter may show no stage change, output or CPU use before startup fails. */
|
|
24
26
|
readonly startupTimeoutMs?: number;
|
|
25
27
|
/** Total startup backstop for an interpreter that stays busy but never becomes ready. */
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""The kill guard for Python cells (senpi#5349, code-yeongyu/oh-my-openagent#12096).
|
|
2
|
+
|
|
3
|
+
Installed for every kernel the host starts with the guard on, independent of permission enforcement: a subprocess
|
|
4
|
+
call, a shell string or a signal that could reach a kill-family command is sent to the host's judge over the bridge
|
|
5
|
+
(`/kill_guard_check`, no permission token) before it runs, and a refusal raises PermissionError. A cheap prefilter
|
|
6
|
+
keeps every other call local. The host decides from this kernel's vantage (its own process group, its own pid).
|
|
7
|
+
"""
|
|
8
|
+
import builtins
|
|
9
|
+
import contextvars
|
|
10
|
+
import functools
|
|
11
|
+
import importlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import socket
|
|
15
|
+
import subprocess
|
|
16
|
+
import time
|
|
17
|
+
|
|
18
|
+
__builtins__ = vars(builtins).copy()
|
|
19
|
+
|
|
20
|
+
KILL_FAMILY = frozenset(("kill", "pkill", "killall"))
|
|
21
|
+
SHELLS = frozenset(("sh", "bash", "zsh", "dash", "ksh", "mksh", "ash", "yash", "posh", "fish", "csh", "tcsh",
|
|
22
|
+
"busybox"))
|
|
23
|
+
REACHES_KILL = KILL_FAMILY | SHELLS
|
|
24
|
+
# The host bounds its table read and its dry run at 2 s each; this covers both plus the round trip.
|
|
25
|
+
DEADLINE_SECONDS = 6.0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def install(port, protected):
|
|
29
|
+
"""Wraps the cell-visible process and signal APIs; `protected` is the host's protected pid list."""
|
|
30
|
+
if getattr(subprocess.Popen.__init__, "__senpi_kill_guard__", False):
|
|
31
|
+
return
|
|
32
|
+
getpid, fsdecode, fspath, basename = os.getpid, os.fsdecode, os.fspath, os.path.basename
|
|
33
|
+
dumps, loads, monotonic = json.dumps, json.loads, time.monotonic
|
|
34
|
+
create_connection = socket.create_connection
|
|
35
|
+
inside = contextvars.ContextVar("senpi_kill_guard_inside", default=False)
|
|
36
|
+
protected = frozenset(protected)
|
|
37
|
+
|
|
38
|
+
def ask(request):
|
|
39
|
+
payload = dumps({**request, "vantagePid": getpid()}).encode()
|
|
40
|
+
deadline = monotonic() + DEADLINE_SECONDS
|
|
41
|
+
with create_connection(("127.0.0.1", port), timeout=DEADLINE_SECONDS) as sock:
|
|
42
|
+
sock.sendall(b"POST /kill_guard_check HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n"
|
|
43
|
+
b"Content-Type: application/json\r\nContent-Length: " + str(len(payload)).encode() +
|
|
44
|
+
b"\r\n\r\n" + payload)
|
|
45
|
+
response = bytearray()
|
|
46
|
+
while True:
|
|
47
|
+
remaining = deadline - monotonic()
|
|
48
|
+
if remaining <= 0:
|
|
49
|
+
raise TimeoutError("kill guard deadline")
|
|
50
|
+
sock.settimeout(remaining)
|
|
51
|
+
chunk = sock.recv(16384)
|
|
52
|
+
if not chunk:
|
|
53
|
+
break
|
|
54
|
+
response.extend(chunk)
|
|
55
|
+
header, _, body = bytes(response).partition(b"\r\n\r\n")
|
|
56
|
+
if not header.startswith(b"HTTP/1.1 200 "):
|
|
57
|
+
raise ValueError("kill guard HTTP failure")
|
|
58
|
+
reply = loads(body.decode())
|
|
59
|
+
if reply.get("ok") is not True or not isinstance(reply.get("value"), dict):
|
|
60
|
+
raise ValueError("kill guard reply failure")
|
|
61
|
+
return reply["value"]
|
|
62
|
+
|
|
63
|
+
def enforce(request):
|
|
64
|
+
try:
|
|
65
|
+
verdict = ask(request)
|
|
66
|
+
except Exception as exc: # noqa: BROAD_EXCEPT_OK — a judge that cannot answer fails closed (amendment A8).
|
|
67
|
+
raise PermissionError(
|
|
68
|
+
f"[senpi:kill-guard] refused (R5 UNKNOWN): the kill guard's judge did not answer ({type(exc).__name__}). "
|
|
69
|
+
'To allow broad kills, set "terminal.killGuard": "off" in your user settings.') from None
|
|
70
|
+
if verdict.get("action") == "refuse":
|
|
71
|
+
raise PermissionError(str(verdict.get("message")))
|
|
72
|
+
|
|
73
|
+
def words(argv):
|
|
74
|
+
return [fsdecode(fspath(arg)) for arg in argv]
|
|
75
|
+
|
|
76
|
+
def argv_reaches_kill(argv):
|
|
77
|
+
# Any element, not only argv[0]: sudo, env, timeout, nice, nohup and xargs put the kill-family command, or the
|
|
78
|
+
# shell that runs one, later in argv (amendment A4). A word holding a whole command line (`env -S
|
|
79
|
+
# "kill -9 -1"`, `--split-string=...`) is split by the program that reads it, so it counts too.
|
|
80
|
+
return any(basename(word) in REACHES_KILL or ("kill" in word and len(word.split()) > 1) for word in argv)
|
|
81
|
+
|
|
82
|
+
def check_shell(text):
|
|
83
|
+
if "kill" in text:
|
|
84
|
+
enforce({"kind": "command", "command": text})
|
|
85
|
+
|
|
86
|
+
def check_argv(argv):
|
|
87
|
+
argv = words(argv)
|
|
88
|
+
if argv_reaches_kill(argv):
|
|
89
|
+
enforce({"kind": "argv", "argv": argv})
|
|
90
|
+
|
|
91
|
+
def guarded(original, check):
|
|
92
|
+
@functools.wraps(original)
|
|
93
|
+
def wrapped(*args, **kwargs):
|
|
94
|
+
if inside.get():
|
|
95
|
+
return original(*args, **kwargs)
|
|
96
|
+
check(*args, **kwargs)
|
|
97
|
+
scope = inside.set(True)
|
|
98
|
+
try:
|
|
99
|
+
return original(*args, **kwargs)
|
|
100
|
+
finally:
|
|
101
|
+
inside.reset(scope)
|
|
102
|
+
wrapped.__senpi_kill_guard__ = True
|
|
103
|
+
return wrapped
|
|
104
|
+
|
|
105
|
+
original_popen_init = subprocess.Popen.__init__
|
|
106
|
+
|
|
107
|
+
# Popen's documented leading parameters; the live __init__ may already be a (self, *args, **kwargs) wrapper.
|
|
108
|
+
def popen_parts(_self, args, _bufsize=-1, executable=None, _stdin=None, _stdout=None, _stderr=None,
|
|
109
|
+
_preexec_fn=None, _close_fds=True, shell=False, *_rest, **_options):
|
|
110
|
+
return args, executable, shell
|
|
111
|
+
|
|
112
|
+
def check_popen(*args, **kwargs):
|
|
113
|
+
command, executable, shell = popen_parts(*args, **kwargs)
|
|
114
|
+
if shell:
|
|
115
|
+
check_shell(fsdecode(command if isinstance(command, (str, bytes)) else command[0]))
|
|
116
|
+
return
|
|
117
|
+
argv = [command] if isinstance(command, (str, bytes, os.PathLike)) else list(command)
|
|
118
|
+
if executable is not None:
|
|
119
|
+
argv[0] = executable
|
|
120
|
+
check_argv(argv)
|
|
121
|
+
|
|
122
|
+
subprocess.Popen.__init__ = guarded(original_popen_init, check_popen)
|
|
123
|
+
for name in ("system", "popen"):
|
|
124
|
+
setattr(os, name, guarded(getattr(os, name), lambda command, *_args, **_kwargs: check_shell(fsdecode(command))))
|
|
125
|
+
|
|
126
|
+
def spawning(name):
|
|
127
|
+
offset = 1 if name.startswith("spawn") else 0
|
|
128
|
+
|
|
129
|
+
def check(*args, **_kwargs):
|
|
130
|
+
rest = args[offset + 1:]
|
|
131
|
+
if name.startswith("posix_spawn"):
|
|
132
|
+
argv = rest[0]
|
|
133
|
+
else:
|
|
134
|
+
letter = name[4] if name.startswith("exec") else name[5]
|
|
135
|
+
argv = rest[0] if letter == "v" else rest[:-1] if name.endswith("e") else rest
|
|
136
|
+
check_argv(list(argv))
|
|
137
|
+
return check
|
|
138
|
+
|
|
139
|
+
for name in dir(os):
|
|
140
|
+
if name.startswith(("exec", "spawn", "posix_spawn")) and callable(getattr(os, name)):
|
|
141
|
+
setattr(os, name, guarded(getattr(os, name), spawning(name)))
|
|
142
|
+
|
|
143
|
+
def check_kill(pid, sig):
|
|
144
|
+
if sig != 0 and (pid <= 0 or pid in protected):
|
|
145
|
+
enforce({"kind": "signal", "target": pid, "group": False, "signal": int(sig)})
|
|
146
|
+
|
|
147
|
+
def check_killpg(pgid, sig):
|
|
148
|
+
enforce({"kind": "signal", "target": pgid, "group": True, "signal": int(sig)})
|
|
149
|
+
|
|
150
|
+
native = importlib.import_module(os.name)
|
|
151
|
+
for name, check in (("kill", check_kill), ("killpg", check_killpg)):
|
|
152
|
+
if not hasattr(os, name):
|
|
153
|
+
continue
|
|
154
|
+
original = getattr(os, name)
|
|
155
|
+
wrapped = guarded(original, check)
|
|
156
|
+
setattr(os, name, wrapped)
|
|
157
|
+
if getattr(native, name, None) is original:
|
|
158
|
+
setattr(native, name, wrapped)
|
|
@@ -54,6 +54,9 @@ if _permission_spec is None or _permission_spec.loader is None:
|
|
|
54
54
|
_permission_module = importlib.util.module_from_spec(_permission_spec)
|
|
55
55
|
exec(compile(_permission_path.read_bytes(), str(_permission_path), "exec"), _permission_module.__dict__)
|
|
56
56
|
initialize_permissions = _permission_module.initialize
|
|
57
|
+
# The kernel's own signals (parent watch, retirement) keep these originals: the kill guard wraps the cell-visible ones.
|
|
58
|
+
_SIGNAL_PROCESS = os.kill
|
|
59
|
+
_SIGNAL_GROUP = getattr(os, "killpg", None)
|
|
57
60
|
|
|
58
61
|
sys.__stdout__.write('{"type":"status","event":{"op":"kernel-startup","stage":"runtime-init"}}\n')
|
|
59
62
|
sys.__stdout__.flush()
|
|
@@ -2329,6 +2332,18 @@ def elapsed(start: float) -> int:
|
|
|
2329
2332
|
return max(0, int((time.monotonic() - start) * 1000))
|
|
2330
2333
|
|
|
2331
2334
|
|
|
2335
|
+
def _install_kill_guard(port: int) -> None:
|
|
2336
|
+
# The host exports the protected pids only while the guard is on (`terminal.killGuard`); absent means off.
|
|
2337
|
+
protected = os.environ.get("SENPI_KILL_GUARD_PROTECTED")
|
|
2338
|
+
if protected is None:
|
|
2339
|
+
return
|
|
2340
|
+
# Loaded only when the guard is on, so a kernel without it starts exactly as before.
|
|
2341
|
+
_kill_guard_path = Path(__file__).with_name("kill_guard.py")
|
|
2342
|
+
namespace: dict[str, Any] = {"__builtins__": __builtins__, "__file__": str(_kill_guard_path)}
|
|
2343
|
+
exec(compile(_kill_guard_path.read_bytes(), str(_kill_guard_path), "exec"), namespace)
|
|
2344
|
+
namespace["install"](port, [int(pid) for pid in protected.split(",") if pid.isdigit()])
|
|
2345
|
+
|
|
2346
|
+
|
|
2332
2347
|
def _handle_message(message: dict[str, Any]) -> bool:
|
|
2333
2348
|
global CONNECTION, permission_context
|
|
2334
2349
|
message_type = message.get("type")
|
|
@@ -2346,6 +2361,7 @@ def _handle_message(message: dict[str, Any]) -> bool:
|
|
|
2346
2361
|
KERNEL_MEMORY._footprint()
|
|
2347
2362
|
if message.get("permission") is not None:
|
|
2348
2363
|
permission_context = initialize_permissions(message["permission"], connection["port"])
|
|
2364
|
+
_install_kill_guard(connection["port"])
|
|
2349
2365
|
emit({"type": "ready"})
|
|
2350
2366
|
return True
|
|
2351
2367
|
if message_type == "run":
|
|
@@ -2405,7 +2421,8 @@ def _terminate_process_group(reason: str) -> None:
|
|
|
2405
2421
|
stream.write(f"{PARENT_WATCH_MARKER} {reason}; stopping the kernel\n")
|
|
2406
2422
|
stream.flush()
|
|
2407
2423
|
with contextlib.suppress(OSError):
|
|
2408
|
-
|
|
2424
|
+
if _SIGNAL_GROUP is not None:
|
|
2425
|
+
_SIGNAL_GROUP(os.getpgrp(), signal.SIGKILL)
|
|
2409
2426
|
|
|
2410
2427
|
|
|
2411
2428
|
def _watch_parent(initial_ppid: int) -> None:
|
|
@@ -2429,7 +2446,7 @@ def _watch_named_parent(parent_pid: int) -> None:
|
|
|
2429
2446
|
while True:
|
|
2430
2447
|
time.sleep(0.5)
|
|
2431
2448
|
try:
|
|
2432
|
-
|
|
2449
|
+
_SIGNAL_PROCESS(parent_pid, 0)
|
|
2433
2450
|
except ProcessLookupError:
|
|
2434
2451
|
_terminate_process_group(f"its host process {parent_pid} is gone")
|
|
2435
2452
|
return
|
|
@@ -50,6 +50,8 @@ export interface PythonTransportOptions {
|
|
|
50
50
|
readonly env?: NodeJS.ProcessEnv;
|
|
51
51
|
/** Per-session PI_* values merged into the interpreter environment at spawn. */
|
|
52
52
|
readonly sessionEnv?: SessionEnvironment;
|
|
53
|
+
/** The kill guard (senpi#5349): the host's protected pids; absent = the guard is off for this kernel. */
|
|
54
|
+
readonly killGuard?: { readonly protectedPids: readonly number[] };
|
|
53
55
|
readonly startupTimeoutMs: number;
|
|
54
56
|
readonly startupCeilingMs: number;
|
|
55
57
|
readonly readCpuTime?: (pid: number | undefined) => bigint | undefined;
|
|
@@ -133,6 +135,9 @@ export class PythonKernelTransport {
|
|
|
133
135
|
...options.env,
|
|
134
136
|
PYTHONUNBUFFERED: "1",
|
|
135
137
|
PYTHONIOENCODING: "utf-8",
|
|
138
|
+
// Present only while the guard is on: it switches the kernel's guard on and feeds its os.kill prefilter.
|
|
139
|
+
SENPI_KILL_GUARD_PROTECTED:
|
|
140
|
+
options.killGuard === undefined ? undefined : options.killGuard.protectedPids.join(","),
|
|
136
141
|
},
|
|
137
142
|
};
|
|
138
143
|
const child = (options.spawnProcess ?? defaultSpawn)(spawnOptions);
|