@hy-sde-org/dsh-code-runtime-kernels 0.2.1-rc.5 → 0.2.2-rc.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/README.md CHANGED
@@ -36,6 +36,10 @@ Add the bundle row (or a similar row in any `cordis.yml`):
36
36
 
37
37
  All row ids carry the `hy-sde-` prefix so they never clash with shipped rows (a duplicate loader id fails the boot). Then the model sees the `run_kernel_code` tool.
38
38
 
39
+ ## Upgrading from 0.2.1-rc.5
40
+
41
+ Standalone installations must satisfy the new `@deepseek-ai/dsh-subprocess` peer; supported DSH profiles already provide it. `KernelManager.run` keeps the output-limit callback's first `content` argument and adds an optional second `{ complete }` argument, so existing callbacks need no source change.
42
+
39
43
  ## Config
40
44
 
41
45
  | Key | Default | Meaning |
@@ -46,7 +50,7 @@ All row ids carry the `hy-sde-` prefix so they never clash with shipped rows (a
46
50
  | `nodePath` | `node` | Explicit node executable (PATH discovery by default). |
47
51
  | `toolTimeoutMs` | `30000` | Cooperative tool-call timeout (`exec.signal` becomes the per-run abort). |
48
52
  | `maxWallMs` | `600000` | Per-run wall-clock budget; interrupt gradates SIGINT → SIGTERM → SIGKILL when the kernel does not respond. |
49
- | `maxOutputBytes` | `67108864` | Combined serialized log-, completion-, and failure-message byte cap (an `'output-limit'` failure). |
53
+ | `maxOutputBytes` | `67108864` | Combined serialized log-, completion-, and failure-message byte cap (an `'output-limit'` failure). A host-capture overflow can spill only its retained prefix and says that the discarded tail is unavailable. |
50
54
  | `maxOutputLineChars` | `4096` | Per-line output cap (chars): a longer line is clipped with a `…` marker so one log bomb cannot own the budget. |
51
55
  | `sessionIdleMs` | `0` | Reap a session whose kernel sits unused for this long (`0` disables; state loss is the explicit cost). |
52
56
  | `interruptEscalationMs` | `5000` | Wait after SIGINT before SIGTERM, then the same again before SIGKILL. |
@@ -56,10 +60,10 @@ All row ids carry the `hy-sde-` prefix so they never clash with shipped rows (a
56
60
  | `snapshotDir` | `~/.dsh/code-runtime-kernels/state` | Snapshot root; files live under `<language>/<session-id-hash>.snapshot`. |
57
61
  | `snapshotMaxBytes` | `134217728` | Combined byte cap for one snapshot file; entries past it are skipped by name. |
58
62
  | `snapshotMaxEntryBytes` | `8388608` | Per-entry byte cap; an entry larger than this is skipped and named. |
59
- | `preload` | `{}` | Session "toolbox": `{ python?: string; typescript?: string }` sources run as one hidden first cell of every fresh session kernel (before the snapshot restores, so a restored name shadows a same-named helper). A preload failure fails the triggering run like an exception. |
63
+ | `preload` | `{}` | Session "toolbox": `{ python?: string; typescript?: string }` sources run as one hidden first cell of every fresh session kernel, with the triggering call's cwd and environment, before snapshot restore. A preload failure fails the triggering run like an exception. |
60
64
  | `pythonImpl` | `'stdlib'` | Python execution semantics: `stdlib` (self-contained runner) or `ipykernel` (a real IPython shell: magics, `!cmd`, display — the interpreter pointed at by `pythonPath` must have IPython installed; the kernel fails loud at boot otherwise). |
61
65
  | `sandboxConfinement` | `false` | Route kernel subprocess spawns through the sandbox seam (structural `confine` capability, see `SandboxProvider` in `@deepseek-ai/dsh-sandbox`) instead of `spawn`ing the interpreter directly. |
62
- | `sandboxProvider` | — | The confinement capability; required when `sandboxConfinement` is `true` (fail closed). |
66
+ | `sandboxProvider` | — | The confinement capability; required when `sandboxConfinement` is `true` (fail closed). Policy receives the owning DSH session id, never the model-chosen kernel sub-session id. |
63
67
  | `sandboxWorkspaceRoot` | `process.cwd()` | Writable root under `workspace-write` confinement. |
64
68
  | `sandboxMode` | `'workspace-write'` | File-effect mode for confined kernels (`'read-only'` or `'workspace-write'`). |
65
69
 
@@ -99,10 +103,13 @@ It resolves the seam's result envelope — `value` (JSON completion), `logs`, `e
99
103
 
100
104
  - **Sessions.** A call with a non-empty `session` runs in that session's kernel; `executionCount` reports the running count. `reset: true` shuts the old kernel down before a fresh one answers.
101
105
  - **One-shot.** Without `session`, a fresh kernel is spawned, exactly one program runs, and the kernel is shut down.
106
+ - **Working directory.** Every tool call resolves the conversation's current working directory. Resolution failures fail the call; a fresh kernel's preload and user cell receive the same directory.
107
+ - **Child environment.** Kernel processes use DSH's credential-safe parent-environment scrub, then add only deliberate runner controls. Ambient credential-shaped and `DSH_*` entries do not reach model code.
102
108
  - **Persistence.** Python: module-level variables and loop state survive across cells. JavaScript: `state` (a long-lived shared object) and sloppy-mode global assignments survive; `const`/`let`/`function`/`class` at cell top level are per-cell (async body), so persistent definitions go on `state`. A cell completes `return <json>` for a completion value, or with no `return` for a no-value run; non-lossless completions (cycles, `BigInt`, sets) are `'invalid-output'`.
109
+ - **JavaScript imports.** Dynamic imports use Node's native ESM loader from the call's working directory, including `exports` import conditions, package `imports`, import attributes, and absolute filesystem paths.
103
110
  - **Snapshots.** After each successful run the namespace is saved (Python: `pickle` + `marshal` for bytecode, per-name loss reporting; JavaScript: V8 binary serialization, so `Map`/`Set`/`Date`/cyclic values survive but function-valued keys are named as lost). A fresh kernel for the session restores the last snapshot once — the restoring run's logs carry `[dsh-kernels] restored N names from snapshot (could not restore: …)`. `reset: true` deletes the snapshot first, so it never resurrects discarded state. Python bytecode is `marshal`-format-dependent: restoring across a Python minor-version upgrade should be expected to lose function/class entries (named in the notice), not data.
104
111
  - **Toolbox.** With `preload` set, every fresh session kernel runs the language's source as one hidden first cell before the snapshot restores: helpers behave like any other session state (they ride snapshots; a restored name shadows a same-named helper). Its output is hidden from the model; a preload failure fails the run it triggered.
105
- - **Budgets and failure kinds.** Wall-clock expiry → `'timeout'`; cancellation or a kernel that had to die → `'abort'`; thrown exceptions → `'exception'`; non-JSON completions → `'invalid-output'`; combined output overflow → `'output-limit'`; kernel death → the session registry replaces the kernel and retries once. All are result FIELDS, never rejections of the tool.
112
+ - **Budgets and failure kinds.** Wall-clock expiry → `'timeout'`; cancellation or a kernel that had to die → `'abort'`; thrown exceptions → `'exception'`; non-JSON completions → `'invalid-output'`; combined output overflow → `'output-limit'`; spontaneous kernel death → `'worker-exit'`. A dead kernel is retired without replaying the failed cell; the next call starts fresh. All are result fields, never tool-call rejections.
106
113
 
107
114
  ## Model experience
108
115
 
@@ -111,6 +118,7 @@ The system-prompt guide tells the model to prefer `run_kernel_code` over scratch
111
118
  ## Known limitations
112
119
 
113
120
  - **A busy synchronous cell resists SIGINT.** A `while (true) {}`/`while True:` loop never yields to the event loop, so the interrupt handler cannot run and the escalation ladder (SIGTERM then SIGKILL) is what actually stops it — costing the kernel's state, hence the session. Cells that yield (async `await` on timers/I/O/tool calls) cancel cleanly and the kernel survives (the wall-clock/timeout tests cover this split).
121
+ - **Capture truncation is irreversible.** When one kernel frame crosses the host capture cap, the result and spill metadata identify the spill as a retained prefix; the discarded tail is not claimed as recoverable.
114
122
  - **State can be poisoned.** A buggy program can corrupt the session's state at any time; `reset: true` is the intended recovery primitive (it also deletes the snapshot, so the corruption cannot come back).
115
123
  - **No security boundary.** Kernel code has bash-equivalent trust, matching the harness's own process backends — and so do snapshot files (`pickle`/`marshal` are not safe to read from untrusted input). Keep `snapshotDir` user-private; a planted snapshot executes as the host.
116
124
  - **Snapshot granularity is per-name.** Python: data, modules, importable callables, and `__main__`-defined functions/classes are saved by value; user-class instances, closures over non-picklables, and entries past the caps are named as lost on the next restore. JavaScript: `state` and sloppy-mode global assignments are saved per key; a function anywhere inside a key's value discards that whole key (named).
package/README.zh.md CHANGED
@@ -34,6 +34,10 @@
34
34
 
35
35
  所有行 id 带 `hy-sde-` 前缀以避免与内置行冲突(重复的 loader id 会导致启动失败)。随后模型即看到 `run_kernel_code` 工具。
36
36
 
37
+ ## 从 0.2.1-rc.5 升级
38
+
39
+ 独立安装需满足新增的 `@deepseek-ai/dsh-subprocess` peer;受支持的 DSH profile 已自带该包。`KernelManager.run` 保留 output-limit 回调的首个 `content` 参数,并新增可选的第二个 `{ complete }` 参数,现有回调无需改源码。
40
+
37
41
  ## 配置
38
42
 
39
43
  | 键 | 默认 | 含义 |
@@ -44,7 +48,7 @@
44
48
  | `nodePath` | `node` | 显式 node 可执行文件(默认走 PATH 发现)。 |
45
49
  | `toolTimeoutMs` | `30000` | 协作式工具调用超时(`exec.signal` 变为每次运行的 abort 源)。 |
46
50
  | `maxWallMs` | `600000` | 每次运行的墙钟预算;中断按 SIGINT→SIGTERM→SIGKILL 升级。 |
47
- | `maxOutputBytes` | `67108864` | 日志、完成值与失败消息合并后的字节上限(触发 `'output-limit'`)。 |
51
+ | `maxOutputBytes` | `67108864` | 日志、完成值与失败消息合并后的字节上限(触发 `'output-limit'`)。若 host 捕获上限先溢出,spill 只能保存已保留前缀,并明确说明尾部不可恢复。 |
48
52
  | `maxOutputLineChars` | `4096` | 单行输出上限(字符):更长行以 `…` 截断,防止一条日志炸弹独占预算。 |
49
53
  | `sessionIdleMs` | `0` | 空闲超过该毫秒数的会话被回收(`0` 禁用;状态丢失是显式代价)。 |
50
54
  | `interruptEscalationMs` | `5000` | SIGINT 后等待再发 SIGTERM,再等同样时长发 SIGKILL。 |
@@ -54,10 +58,10 @@
54
58
  | `snapshotDir` | `~/.dsh/code-runtime-kernels/state` | 快照根目录;文件位于 `<language>/<session-id-hash>.snapshot`。 |
55
59
  | `snapshotMaxBytes` | `134217728` | 单个快照文件的合并字节上限;超出的条目按名跳过。 |
56
60
  | `snapshotMaxEntryBytes` | `8388608` | 单条字节上限;超出的条目按名跳过。 |
57
- | `preload` | `{}` | 会话“工具箱”:`{ python?: string; typescript?: string }`,在每个新会话 kernel 上先作为隐藏首 cell 运行(快照恢复之前;同名恢复值会遮蔽助手)。preload 失败则本次运行报错。 |
61
+ | `preload` | `{}` | 会话“工具箱”:`{ python?: string; typescript?: string }`,在每个新会话 kernel 上以触发调用的 cwd 与环境作为隐藏首 cell 运行,再恢复快照。preload 失败则本次运行报错。 |
58
62
  | `pythonImpl` | `'stdlib'` | Python 执行语义:`stdlib`(自包含 runner)或 `ipykernel`(真实 IPython shell:魔法命令、`!cmd`、display——`pythonPath` 指向的解释器需装有 IPython,否则启动即报错)。 |
59
63
  | `sandboxConfinement` | `false` | 将 kernel 子进程经沙箱接缝启动(结构式 `confine` 能力,见 `@deepseek-ai/dsh-sandbox` 的 `SandboxProvider`)而非直接 spawn。 |
60
- | `sandboxProvider` | — | 约束能力;`sandboxConfinement: true` 时必须提供(fail closed)。 |
64
+ | `sandboxProvider` | — | 约束能力;`sandboxConfinement: true` 时必须提供(fail closed)。策略接收所属 DSH 会话 id,绝不接收模型选择的 kernel 子会话 id。 |
61
65
  | `sandboxWorkspaceRoot` | `process.cwd()` | `workspace-write` 模式下的可写根目录。 |
62
66
  | `sandboxMode` | `'workspace-write'` | 被约束 kernel 的文件效应模式(`'read-only'` 或 `'workspace-write'`)。 |
63
67
 
@@ -96,10 +100,13 @@ runner 不自带 Python——它 spawn `pythonPath` 指向的解释器。要用
96
100
 
97
101
  - **会话**。带非空 `session` 的调用运行于该会话的 kernel;`executionCount` 报告累计次数。`reset: true` 先关旧 kernel 再开新 kernel 响应。
98
102
  - **一次性**。没有 `session` 时,spawn 一个新 kernel,恰好运行一个程序后关闭。
103
+ - **工作目录**。每次工具调用都解析会话当前工作目录;解析失败即令调用失败。新 kernel 的 preload 与用户 cell 使用同一目录。
104
+ - **子进程环境**。kernel 使用 DSH 统一的凭据安全父环境清除策略,再加入显式 runner 控制项;环境中的凭据型变量与 `DSH_*` 不会进入模型代码。
99
105
  - **持久化**。Python:模块级变量与循环状态跨 cell 保留。JavaScript:`state`(长寿命共享对象)与 sloppy 全局赋值跨 cell 保留;cell 顶层的 `const`/`let`/`function`/`class` 是每 cell 作用域(async 函数体),持久定义请放 `state`。cell 以 `return <json>` 携带完成值,或以无 `return` 结束为无值运行;非 lossless JSON 完成值(环、`BigInt`、集合)判为 `'invalid-output'`。
106
+ - **JavaScript 导入**。动态导入从调用工作目录使用 Node 原生 ESM loader,支持 `exports` import 条件、package `imports`、import attributes 与绝对文件路径。
100
107
  - **快照**。每次成功运行后保存命名空间(Python:`pickle` + `marshal` 字节码,逐名报告丢失;JavaScript:V8 二进制序列化,`Map`/`Set`/`Date`/环可保留,函数值键按名判丢)。该会话的新 kernel 只恢复一次最近快照——恢复运行日志中带 `[dsh-kernels] restored N names from snapshot (could not restore: …)`。`reset: true` 先删除快照,杜绝回魂。Python 字节码依赖 `marshal` 格式:跨 Python 小版本升级恢复时函数/类条目可能报丢(指名),数据不受影响。
101
108
  - **工具箱**。配置 `preload` 后,每个新会话 kernel 会先把该语言的源码作为隐藏首 cell 运行(先于快照恢复):助手与普通会话状态一样参与快照,同名恢复值遮蔽同名助手。其输出对模型隐藏;preload 失败则本次运行报错。
102
- - **预算与失败种类**。墙钟超时 → `'timeout'`;取消或被迫终止 → `'abort'`;抛异常 → `'exception'`;非 JSON 完成 → `'invalid-output'`;合并输出溢出 → `'output-limit'`;kernel 死亡 → 会话注册表替换 kernel 并重试一次。全部是结果字段,绝不会 reject 工具调用。
109
+ - **预算与失败种类**。墙钟超时 → `'timeout'`;取消或被迫终止 → `'abort'`;抛异常 → `'exception'`;非 JSON 完成 → `'invalid-output'`;合并输出溢出 → `'output-limit'`;kernel 自发死亡 → `'worker-exit'`。死亡 kernel 会被退役,但失败 cell 不会重放;下一次调用启动新 kernel。全部是结果字段,绝不会 reject 工具调用。
103
110
 
104
111
  ## 模型体验
105
112
 
@@ -108,6 +115,7 @@ runner 不自带 Python——它 spawn `pythonPath` 指向的解释器。要用
108
115
  ## 已知限制
109
116
 
110
117
  - **同步忙循环抗拒 SIGINT**。`while (true) {}` / `while True:` 永不交还事件循环,中断处理器无法运行,实际由升级梯(SIGTERM 再 SIGKILL)终止——代价是会话状态与 kernel。会让出事件循环的 cell(对定时器/IO/工具调用的 `await`)可被干净取消,kernel 存活(墙钟/中止测试即覆盖这一分界)。
118
+ - **捕获截断不可逆**。单个 kernel 帧越过 host 捕获上限时,结果与 spill 元数据会把保存内容标为已保留前缀,不会声称被丢弃尾部可恢复。
111
119
  - **状态可能被污染**。错误程序随时可能弄坏会话状态;`reset: true` 是设计的恢复原语(同时删除快照,污染不会复活)。
112
120
  - **无安全边界**。kernel 代码拥有与内置 process 后端相同的 bash 级信任——快照文件同理(`pickle`/`marshal` 不可用于不可信输入);请保持 `snapshotDir` 为用户私有。
113
121
  - **快照按名粒度**。Python:数据、模块、可导入调用及 `__main__` 内定义的函数/类按值保存;用户类实例、含不可 pickle 闭包者、超限条目在下次恢复时点名报告。JavaScript:`state` 与 sloppy 全局赋值按键保存;键值内任意位置出现函数即丢弃整键(点名)。
@@ -10,6 +10,7 @@
10
10
  * @module @hy-sde-org/dsh-code-runtime-kernels/src/core/kernel
11
11
  */
12
12
  import type { PtcBindingNamespace, PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime';
13
+ import type { SessionId } from '@deepseek-ai/dsh-session';
13
14
  import type { DoneFrame, KernelFrame, KernelHostMessage, SnapshotSpec } from './protocol.ts';
14
15
  export type { DoneFrame, KernelFrame, KernelHostMessage, SnapshotSpec };
15
16
  /** How to spawn and label one language's kernel. */
@@ -49,29 +50,63 @@ export interface KernelStartConfig {
49
50
  shutdownGraceMs: number;
50
51
  /**
51
52
  * Confinement wrapper applied to the fully-assembled argv (command +
52
- * argvPrefix + runner) just before spawn — e.g. the output of
53
+ * argvPrefix + runner) just before spawn — e.g. wrapping
53
54
  * {@link KernelSandboxProvider.confine} so the kernel launches under real
54
55
  * filesystem confinement (bwrap / landlock-run / seatbelt). Must fail
55
- * closed: a non-enforcing return is the provider's bug, not a fallback.
56
- * The wrapper becomes the process-group leader; the escalation ladder
57
- * unwinds through it.
56
+ * closed: a rejection or a non-enforcing return is the provider's bug, not
57
+ * a fallback. The wrapper becomes the process-group leader; the escalation
58
+ * ladder unwinds through it.
58
59
  */
59
- confine?: (argv: readonly string[]) => {
60
+ confine?: (argv: readonly string[], signal?: AbortSignal, sessionId?: SessionId) => Promise<{
60
61
  argv: string[];
61
- };
62
+ }>;
63
+ /**
64
+ * Cancellation for the confinement call itself (the triggering run's
65
+ * signal): an aborted or failing confine fails the start structured, never
66
+ * the host process.
67
+ */
68
+ signal?: AbortSignal;
69
+ /**
70
+ * Owning DSH session id, when the run belongs to one — forwarded into the
71
+ * confinement policy so per-session sandbox grants apply.
72
+ */
73
+ sandboxSessionId?: SessionId;
74
+ /**
75
+ * Upper bound on captured log bytes per run. On overflow the host retains a
76
+ * UTF-8-safe prefix and marks the missing tail; `undefined` disables the cap.
77
+ */
78
+ captureCapBytes?: number;
62
79
  }
63
80
  /**
64
81
  * The sandbox seam's confine capability, structurally typed (no runtime
65
82
  * dependency on `@deepseek-ai/dsh-sandbox`): wrap exact argv under a
66
- * file-effect policy, or fail closed. See the published seam for the contract.
83
+ * file-effect policy, or fail closed. ASYNC, matching the real harness
84
+ * provider (`confine(…): Promise<ConfinedArgv>`) — a synchronous stand-in is
85
+ * still accepted structurally only by tests; production providers resolve.
67
86
  */
87
+ export interface KernelSandboxPolicy {
88
+ mode: 'read-only' | 'workspace-write';
89
+ workspaceRoot: string;
90
+ /** Owning DSH session, when the run has one (forwarded to the provider). */
91
+ sessionId?: SessionId;
92
+ }
68
93
  export interface KernelSandboxProvider {
69
- confine(argv: readonly string[], policy: {
70
- mode: 'read-only' | 'workspace-write';
71
- workspaceRoot: string;
72
- }): {
94
+ confine(argv: readonly string[], policy: KernelSandboxPolicy, signal?: AbortSignal): Promise<{
73
95
  argv: string[];
74
- };
96
+ }>;
97
+ }
98
+ /** Structured snapshot/persistence status reported by the runners. */
99
+ export interface KernelPersistenceStatus {
100
+ /** Names persisted by the last successful run's save. */
101
+ saved?: number;
102
+ /** Names dropped by the save (over the per-entry/total caps). */
103
+ saveLost?: string[];
104
+ /** Save failure cause, when the snapshot could not be written at all. */
105
+ saveError?: string;
106
+ /** Names restored from the snapshot at kernel start. */
107
+ restored?: number;
108
+ /** Snapshot names that could not be restored. */
109
+ restoreLost?: string[];
75
110
  }
76
111
  /** The outcome of one kernel execution; budgets and kind mapping stay with the provider. */
77
112
  export interface KernelExecResult {
@@ -93,6 +128,12 @@ export interface KernelExecResult {
93
128
  message: string;
94
129
  /** True when the kernel had to be terminated to settle this run. */
95
130
  killed: boolean;
131
+ /** True when the kernel process died without host-initiated termination (maps to `worker-exit`). */
132
+ crashed?: boolean;
133
+ /** True when host-side capture discarded an output tail. */
134
+ captureTruncated?: boolean;
135
+ /** Snapshot persistence status when the run carried a snapshot spec. */
136
+ persistence?: KernelPersistenceStatus;
96
137
  }
97
138
  /** The Node.js runner shipped as a package file (raw source in development, compiled ESM in the output). */
98
139
  declare const RUNNER_PATH: string;
@@ -1 +1 @@
1
- {"version":3,"file":"kernel.d.ts","sourceRoot":"","sources":["../../src/core/kernel.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAOH,OAAO,KAAK,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAA;AAErF,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAG5F,YAAY,EAAE,SAAS,EAAE,WAAW,EAAE,iBAAiB,EAAE,YAAY,EAAE,CAAA;AAEvE,oDAAoD;AACpD,MAAM,WAAW,oBAAoB;IACnC,kFAAkF;IAClF,GAAG,EAAE,MAAM,CAAA;IACX,2CAA2C;IAC3C,OAAO,EAAE,MAAM,CAAA;IACf,8CAA8C;IAC9C,UAAU,EAAE,MAAM,EAAE,CAAA;IACpB,uDAAuD;IACvD,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,8EAA8E;IAC9E,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,oDAAoD;IACpD,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,sDAAsD;IACtD,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAA;IACvB,mDAAmD;IACnD,MAAM,EAAE,MAAM,CAAA;IACd,wCAAwC;IACxC,QAAQ,EAAE,MAAM,CAAA;IAChB,8DAA8D;IAC9D,KAAK,EAAE,MAAM,CAAA;CACd;AAED,yEAAyE;AACzE,MAAM,WAAW,iBAAiB;IAChC,4CAA4C;IAC5C,GAAG,EAAE,MAAM,CAAA;IACX,2EAA2E;IAC3E,G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E,IAAI,EAAE,WAAW,GAAG,gBAAgB,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,CAY5I;AAkBD;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,GAAG,WAAW,GAAG,SAAS,CA6CtE;AAED,4EAA4E;AAC5E,qBAAa,UAAU;;IACrB,EAAE,EAAE,MAAM,CAAA;IACV,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;IACvB,QAAQ,CAAC,OAAO,EAAE,oBAAoB,CAAA;IAsBtC;;;;OAIG;WACU,KAAK,CAAC,OAAO,EAAE,oBAAoB,EAAE,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAAC,UAAU,CAAC;IAoHjG,OAAO;IAiEP,iDAAiD;IACjD,OAAO,IAAI,OAAO;IAIlB;;;;;;;;OAQG;IACG,OAAO,CACX,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,mBAAmB,EAAE,EACjC,OAAO,GAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAAC,QAAQ,CAAC,EAAE,YAAY,CAAA;KAAO,GAC1G,OAAO,CAAC,gBAAgB,CAAC;IAgI5B,uFAAuF;IACjF,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;IAwChC;;;;OAIG;IACG,QAAQ,IAAI,OAAO,CAAC;QAAE,SAAS,EAAE,OAAO,CAAA;KAAE,CAAC;IAmCjD,2DAA2D;YAC7C,kBAAkB;CAgNjC;AAED,OAAO,EAAE,WAAW,EAAE,CAAA"}
@@ -23,7 +23,9 @@ export function nodejsKernelProfile(command) {
23
23
  return {
24
24
  key: 'typescript',
25
25
  command,
26
- argvPrefix: ['--no-warnings'],
26
+ // compileFunction delegates dynamic imports to Node's main ESM loader;
27
+ // vm modules must be enabled for that loader to run inside compiled cells.
28
+ argvPrefix: ['--no-warnings', '--experimental-vm-modules'],
27
29
  runnerPath: RUNNER_PATH,
28
30
  prefix: 'dsh-code-runtime-kernels-nodejs',
29
31
  idPrefix: 'js-',
@@ -104,6 +106,27 @@ export function doneFailure(frame) {
104
106
  }
105
107
  return { ok: false, error: { kind: 'exception', message: frame.message ?? 'program failed' } };
106
108
  }
109
+ /**
110
+ * Validate a runner-reported persistence status field by field (hostile-peer
111
+ * revalidation, like every other frame field): junk yields `undefined`.
112
+ */
113
+ function parsePersistence(raw) {
114
+ if (typeof raw !== 'object' || raw === null)
115
+ return undefined;
116
+ const record = raw;
117
+ const out = {};
118
+ if (typeof record.saved === 'number' && Number.isFinite(record.saved))
119
+ out.saved = record.saved;
120
+ if (Array.isArray(record.saveLost))
121
+ out.saveLost = record.saveLost.filter((entry) => typeof entry === 'string');
122
+ if (typeof record.saveError === 'string')
123
+ out.saveError = record.saveError;
124
+ if (typeof record.restored === 'number' && Number.isFinite(record.restored))
125
+ out.restored = record.restored;
126
+ if (Array.isArray(record.restoreLost))
127
+ out.restoreLost = record.restoreLost.filter((entry) => typeof entry === 'string');
128
+ return Object.keys(out).length > 0 ? out : undefined;
129
+ }
107
130
  /**
108
131
  * Parse one kernel frame. The peer runs MODEL CODE and can emit anything, so
109
132
  * everything is re-validated and rebuilt field by field; junk returns
@@ -160,6 +183,9 @@ export function parseKernelFrame(raw) {
160
183
  frame.invalidOutput = true;
161
184
  if (typeof message.message === 'string')
162
185
  frame.message = message.message;
186
+ const persistence = parsePersistence(message.persistence);
187
+ if (persistence !== undefined)
188
+ frame.persistence = persistence;
163
189
  return frame;
164
190
  }
165
191
  default: return undefined;
@@ -177,24 +203,29 @@ export class KernelHost {
177
203
  #runs = new Map();
178
204
  #ready;
179
205
  #settleReady;
206
+ #failReady;
180
207
  #exited;
208
+ #settleExited;
181
209
  #alive = true;
182
210
  #disposed = false;
183
211
  #interruptEscalationMs;
184
212
  #shutdownGraceMs;
213
+ /** Per-run captured-output cap in bytes; `undefined` disables capping. */
214
+ #captureCapBytes;
185
215
  /** Last stdin failure cause (omp #14196/#14199), surfaced in the next write's rejection. */
186
216
  #stdinFailure;
217
+ /** First spawn-level failure (missing executable, …), when any. */
218
+ #spawnFailure;
187
219
  /**
188
220
  * Spawn a kernel per the profile and wait for the bootstrap handshake.
189
221
  * Rejects on spawn failure, startup timeout, or an early process exit
190
222
  * (grading the fresh subprocess up to termination behind us).
191
223
  */
192
224
  static async start(profile, config) {
225
+ if (config.signal?.aborted) {
226
+ throw new Error(`${profile.prefix}: kernel start aborted (${tryMessageOf(config.signal.reason)})`);
227
+ }
193
228
  const argv = [...profile.argvPrefix];
194
- // A runner may be a shipped file, or embedded source staged to a scratch
195
- // file per spawn (tempdirs are shared host state; the embedded code may
196
- // change between versions). Only the staged variant touches the disk, in
197
- // an owner-private per-uid dir re-validated on every spawn.
198
229
  let stagedPath;
199
230
  if (profile.stagedSource !== undefined) {
200
231
  stagedPath = join(resolveRunnerStagingDir(RUNNER_DIR_NAME), `runner-${process.pid}-${Math.random().toString(36).slice(2, 10)}${profile.stagedSuffix ?? ''}`);
@@ -208,56 +239,122 @@ export class KernelHost {
208
239
  const runnerArg = stagedPath ?? profile.runnerPath;
209
240
  if (runnerArg !== undefined)
210
241
  argv.push(runnerArg);
211
- const fullArgv = [...argv];
212
- if (profile.command !== undefined)
213
- fullArgv.unshift(profile.command);
214
- // `--no-warnings` for the Node runner is statically safe: a development
215
- // spawn of the .ts kernel would otherwise leak the type-stripping
216
- // ExperimentalWarning into the captured stderr. Python gets unfiltered
217
- // stdout via -u plus PYTHONUNBUFFERED/PYTHONIOENCODING.
218
- // `detached: true` on POSIX calls setsid(2), making the runner a session
219
- // leader: anything it spawns stays in ITS process group, so a shutdown can
220
- // sweep the whole tree via killProcessGroup (the #7714 orphan fix) instead
221
- // of leaving grandchildren holding the kernel's pipes open.
222
- const wrapped = config.confine !== undefined ? config.confine(fullArgv).argv : fullArgv;
223
- const proc = spawn(wrapped[0] ?? profile.command, wrapped.slice(1), {
224
- cwd: config.cwd,
225
- env: { ...(config.env ?? process.env), ...profile.env },
226
- stdio: ['pipe', 'pipe', 'pipe'],
227
- detached: process.platform !== 'win32',
228
- windowsHide: true,
229
- });
242
+ const fullArgv = [profile.command, ...argv];
243
+ let wrapped;
244
+ if (config.confine !== undefined) {
245
+ try {
246
+ const confinement = config.confine(fullArgv, config.signal, config.sandboxSessionId);
247
+ const cancellation = Promise.withResolvers();
248
+ const onAbort = () => {
249
+ cancellation.reject(new Error(`kernel start aborted (${tryMessageOf(config.signal?.reason)})`));
250
+ };
251
+ if (config.signal !== undefined) {
252
+ if (config.signal.aborted)
253
+ onAbort();
254
+ else
255
+ config.signal.addEventListener('abort', onAbort, { once: true });
256
+ }
257
+ try {
258
+ const confined = config.signal === undefined
259
+ ? await confinement
260
+ : await Promise.race([confinement, cancellation.promise]);
261
+ wrapped = confined.argv;
262
+ }
263
+ finally {
264
+ config.signal?.removeEventListener('abort', onAbort);
265
+ }
266
+ }
267
+ catch (error) {
268
+ if (stagedPath !== undefined) {
269
+ try {
270
+ rmSync(stagedPath);
271
+ }
272
+ catch { /* best effort */ }
273
+ }
274
+ throw new Error(`${profile.prefix}: sandbox confinement failed: ${tryMessageOf(error)}`);
275
+ }
276
+ if (!Array.isArray(wrapped) || wrapped.length === 0 || wrapped.some(entry => typeof entry !== 'string')) {
277
+ if (stagedPath !== undefined) {
278
+ try {
279
+ rmSync(stagedPath);
280
+ }
281
+ catch { /* best effort */ }
282
+ }
283
+ throw new Error(`${profile.prefix}: sandbox confinement returned a malformed argv`);
284
+ }
285
+ }
286
+ else {
287
+ wrapped = fullArgv;
288
+ }
289
+ if (config.signal?.aborted) {
290
+ if (stagedPath !== undefined) {
291
+ try {
292
+ rmSync(stagedPath);
293
+ }
294
+ catch { /* best effort */ }
295
+ }
296
+ throw new Error(`${profile.prefix}: kernel start aborted (${tryMessageOf(config.signal.reason)})`);
297
+ }
298
+ let proc;
299
+ try {
300
+ proc = spawn(wrapped[0] ?? profile.command, wrapped.slice(1), {
301
+ cwd: config.cwd,
302
+ env: { ...(config.env ?? process.env), ...profile.env },
303
+ stdio: ['pipe', 'pipe', 'pipe'],
304
+ detached: process.platform !== 'win32',
305
+ windowsHide: true,
306
+ });
307
+ }
308
+ catch (error) {
309
+ if (stagedPath !== undefined) {
310
+ try {
311
+ rmSync(stagedPath);
312
+ }
313
+ catch { /* best effort */ }
314
+ }
315
+ throw error;
316
+ }
230
317
  if (proc.pid === undefined)
231
318
  proc.unref();
232
319
  const kernel = new KernelHost(profile, stagedPath, proc, config);
233
320
  kernel.id = `${profile.idPrefix}${Math.random().toString(36).slice(2, 10)}`;
234
321
  kernel.pid = proc.pid;
322
+ const startupTimeout = Promise.withResolvers();
323
+ const startupTimer = setTimeout(() => {
324
+ startupTimeout.reject(new Error(`${profile.prefix}: kernel did not become ready within ${config.startupTimeoutMs}ms`));
325
+ }, config.startupTimeoutMs);
326
+ startupTimer.unref();
327
+ const aborted = Promise.withResolvers();
328
+ let onAbort;
329
+ if (config.signal !== undefined) {
330
+ onAbort = () => {
331
+ aborted.reject(new Error(`${profile.prefix}: kernel start aborted (${tryMessageOf(config.signal?.reason)})`));
332
+ };
333
+ if (config.signal.aborted)
334
+ onAbort();
335
+ else
336
+ config.signal.addEventListener('abort', onAbort, { once: true });
337
+ }
235
338
  try {
236
339
  await Promise.race([
237
340
  kernel.#ready,
238
- // An early exit before the handshake must fail the start FAST (a
239
- // runner that cannot even boot — missing interpreter feature, syntax
240
- // error in a staged script — otherwise costs the full startup budget).
241
341
  kernel.#exited.then((code) => {
242
342
  throw new Error(`${profile.prefix}: kernel exited with code ${code} before becoming ready`);
243
343
  }),
244
- new Promise((_resolve, reject) => {
245
- const timer = setTimeout(() => {
246
- reject(new Error(`${profile.prefix}: kernel did not become ready within ${config.startupTimeoutMs}ms`));
247
- }, config.startupTimeoutMs);
248
- timer.unref();
249
- }),
344
+ startupTimeout.promise,
345
+ aborted.promise,
250
346
  ]);
251
347
  return kernel;
252
348
  }
253
349
  catch (error) {
254
- // An early exit already settled every in-flight run (none); a start
255
- // timeout must grade the half-booted subprocess up to termination.
256
- await kernel.killForFailedStart(typeof error === 'object' && error !== null
257
- ? tryMessageOf(error)
258
- : `${profile.label} startup failed`);
350
+ await kernel.killForFailedStart(tryMessageOf(error));
259
351
  throw error;
260
352
  }
353
+ finally {
354
+ clearTimeout(startupTimer);
355
+ if (onAbort !== undefined)
356
+ config.signal?.removeEventListener('abort', onAbort);
357
+ }
261
358
  }
262
359
  constructor(profile, stagedPath, proc, config) {
263
360
  this.profile = profile;
@@ -266,6 +363,7 @@ export class KernelHost {
266
363
  this.#stagedPath = stagedPath;
267
364
  this.#interruptEscalationMs = config.interruptEscalationMs;
268
365
  this.#shutdownGraceMs = config.shutdownGraceMs;
366
+ this.#captureCapBytes = config.captureCapBytes;
269
367
  proc.stderr?.setEncoding('utf8');
270
368
  // stdout stays raw bytes: frames are split at the byte level (lines.ts),
271
369
  // decoded per complete line — multibyte-safe across chunk boundaries.
@@ -280,9 +378,41 @@ export class KernelHost {
280
378
  // cause for the next write's rejection; the kernel's retirement stays
281
379
  // with the write path that observed the failure.
282
380
  proc.stdin?.on('error', (error) => { this.#stdinFailure ??= messageOf(error); });
283
- this.#exited = new Promise((resolve) => { proc.once('exit', (code) => { resolve(code ?? 0); }); });
381
+ // A failed SPAWN (missing executable, EACCES, …) emits an 'error' event
382
+ // and NO 'exit' event. Without this listener the unhandled event kills
383
+ // the whole host process (the review's finding: `nodePath: /nonexistent`
384
+ // took the harness down); with it, the failure is structured: runs are
385
+ // settled as killed, the start handshake rejects through #failReady, and
386
+ // shutdown/kill paths see #exited settled (there is no exit event to wait
387
+ // for) instead of hanging on the grace race.
388
+ proc.on('error', (error) => { this.#onSpawnError(error); });
389
+ this.#exited = new Promise((resolve) => { this.#settleExited = resolve; });
390
+ proc.once('exit', (code) => { this.#settleExited(code ?? 0); });
284
391
  void this.#exited.then((code) => { this.#onProcessExit(code); });
285
- this.#ready = new Promise((resolve) => { this.#settleReady = resolve; });
392
+ this.#ready = new Promise((resolve, reject) => {
393
+ this.#settleReady = resolve;
394
+ this.#failReady = reject;
395
+ });
396
+ }
397
+ /**
398
+ * Spawn-level failure: no process exists (so there is nothing to signal and
399
+ * no 'exit' event coming). Mark the host dead, settle #exited with a
400
+ * synthetic code, settle every admitted run as killed, and reject the
401
+ * startup handshake.
402
+ */
403
+ #onSpawnError(error) {
404
+ const cause = messageOf(error);
405
+ this.#spawnFailure ??= cause;
406
+ this.#alive = false;
407
+ this.#settleExited(-1);
408
+ for (const run of [...this.#runs.values()]) {
409
+ run.status = 'error';
410
+ run.message = `${this.profile.label} process failed: ${cause}`;
411
+ run.killed = true;
412
+ run.finalize();
413
+ }
414
+ this.#runs.clear();
415
+ this.#failReady(new Error(`${this.profile.prefix}: kernel process failed to spawn: ${cause}`));
286
416
  }
287
417
  /** The process is healthy and accepting runs. */
288
418
  isAlive() {
@@ -298,6 +428,12 @@ export class KernelHost {
298
428
  * (omp #14196/#14199).
299
429
  */
300
430
  async execute(id, code, namespaces, options = {}) {
431
+ if (options.signal?.aborted) {
432
+ return {
433
+ status: 'error', logs: [], cancelled: true, invalidOutput: false,
434
+ message: 'run aborted before the kernel admitted it', killed: false,
435
+ };
436
+ }
301
437
  if (!this.isAlive()) {
302
438
  return {
303
439
  status: 'error', logs: [], cancelled: false, invalidOutput: false,
@@ -316,6 +452,8 @@ export class KernelHost {
316
452
  invalidOutput: false,
317
453
  message: '',
318
454
  killed: false,
455
+ captureBytes: 0,
456
+ captureTruncated: false,
319
457
  done: Promise.resolve(),
320
458
  finalize: () => { },
321
459
  };
@@ -384,8 +522,42 @@ export class KernelHost {
384
522
  invalidOutput: run.invalidOutput,
385
523
  message: run.message,
386
524
  killed: run.killed,
525
+ ...run.captureTruncated ? { captureTruncated: true } : {},
526
+ ...run.crashed ? { crashed: true } : {},
527
+ ...run.persistence !== undefined ? { persistence: run.persistence } : {},
387
528
  };
388
529
  }
530
+ /**
531
+ * Append one captured-output chunk. On overflow, retain a UTF-8-safe prefix
532
+ * up to the cap and mark the missing tail explicitly on the result.
533
+ */
534
+ #appendLog(run, text, stream) {
535
+ const cap = this.#captureCapBytes;
536
+ if (run.captureTruncated)
537
+ return;
538
+ if (cap === undefined) {
539
+ run.logs.push({ text, stream });
540
+ return;
541
+ }
542
+ const bytes = Buffer.byteLength(text);
543
+ if (run.captureBytes + bytes <= cap) {
544
+ run.captureBytes += bytes;
545
+ run.logs.push({ text, stream });
546
+ return;
547
+ }
548
+ let remaining = Math.max(0, cap - run.captureBytes);
549
+ const source = Buffer.from(text, 'utf8');
550
+ let prefix = source.subarray(0, remaining).toString('utf8');
551
+ while (remaining > 0 && Buffer.byteLength(prefix) > remaining) {
552
+ remaining -= 1;
553
+ prefix = source.subarray(0, remaining).toString('utf8');
554
+ }
555
+ if (prefix.length > 0) {
556
+ run.logs.push({ text: prefix, stream });
557
+ run.captureBytes += Buffer.byteLength(prefix);
558
+ }
559
+ run.captureTruncated = true;
560
+ }
389
561
  /** Request cancellation of the in-flight run via SIGINT, escalating to termination. */
390
562
  async interrupt() {
391
563
  for (const run of [...this.#runs.values()])
@@ -454,7 +626,7 @@ export class KernelHost {
454
626
  run.finalize();
455
627
  }
456
628
  const exited = this.#exited;
457
- await this.#write({ type: 'exit' }).catch(() => { });
629
+ void this.#write({ type: 'exit' }).catch(() => { });
458
630
  const grace = () => new Promise((resolve) => {
459
631
  const timer = setTimeout(() => { resolve('timeout'); }, this.#shutdownGraceMs);
460
632
  timer.unref();
@@ -504,6 +676,8 @@ export class KernelHost {
504
676
  timer.unref();
505
677
  await this.#exited.catch(() => { });
506
678
  clearTimeout(timer);
679
+ // The leader can exit before its descendants; always finish the group.
680
+ killProcessGroup(this.#proc.pid, 'SIGKILL');
507
681
  }
508
682
  #onProcessExit(code) {
509
683
  this.#alive = false;
@@ -516,6 +690,11 @@ export class KernelHost {
516
690
  run.status = 'error';
517
691
  run.message = `${this.profile.label} exited with code ${code} before completing`;
518
692
  run.killed = true;
693
+ // Host-initiated terminations (#interrupt escalation, shutdown) set
694
+ // `cancelled` before the process dies; a spontaneous death of a run the
695
+ // host did not cancel is a crash → surfaced as `worker-exit`.
696
+ if (!run.cancelled)
697
+ run.crashed = true;
519
698
  run.finalize();
520
699
  }
521
700
  // The staged scratch script has served its purpose; remove it once the
@@ -536,7 +715,7 @@ export class KernelHost {
536
715
  return;
537
716
  for (const run of [...this.#runs.values()]) {
538
717
  if (!run.killed)
539
- run.logs.push({ text, stream: 'stderr' });
718
+ this.#appendLog(run, text, 'stderr');
540
719
  }
541
720
  }
542
721
  #ingest(chunk) {
@@ -575,7 +754,7 @@ export class KernelHost {
575
754
  case 'log': {
576
755
  const run = this.#runs.get(frame.id);
577
756
  if (run !== undefined)
578
- run.logs.push({ text: frame.text, stream: frame.stream ?? 'stdout' });
757
+ this.#appendLog(run, frame.text, frame.stream ?? 'stdout');
579
758
  return;
580
759
  }
581
760
  case 'call': {
@@ -603,6 +782,8 @@ export class KernelHost {
603
782
  run.invalidOutput = true;
604
783
  if (frame.message !== undefined)
605
784
  run.message = frame.message;
785
+ if (frame.persistence !== undefined)
786
+ run.persistence = frame.persistence;
606
787
  run.finalize();
607
788
  return;
608
789
  }