A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
Minimal CPython REPL runtime (rlm.repl) (#1685)
Sebastian Müller61eb64748eb0
diff --git a/README.md b/README.mdindex 2b6dbe3ee0..e4b77ad79f 100644--- a/README.md+++ b/README.md@@ -43,7 +43,7 @@ Prime Agent is an open-source coding and research agent for general and long-runPrime Agent combines a persistent Python control environment with durable harness state, so useful working context and reusable operating patterns can outlive a single chat window.-- **Everything is programmatic:** persistent IPython is the built-in model tool; file operations, shell commands, tool use, subagents, and context management happen through code.+- **Everything is programmatic:** a persistent Python REPL is the built-in model tool; file operations, shell commands, tool use, subagents, and context management happen through code.- **Subagents are built in:** `rlm(...)` spawns real child agents for parallel or background work and returns their results programmatically.- **The harness can improve:** `/refine` reviews the current trajectory and can apply small, evidence-backed updates to supplemental harness state. It never rewrites the immutable base system prompt, and recorded snapshots support rollback.- **Skills are executable:** skills are importable Python packages, and the built-in skill creator can turn recurring workflows into project or personal skills.@@ -59,7 +59,7 @@ Install the latest stable release on macOS or Linux:curl -fsSL https://app.primeintellect.ai/prime-agent/install.sh | sh```-The installer downloads a versioned release, verifies its SHA-256 checksum, installs the `prime-agent` command, and can prepare the IPython runtime used by the agent.+The installer downloads a versioned release, verifies its SHA-256 checksum, installs the `prime-agent` command, and can prepare the Python runtime used by the agent.Start Prime Agent from the repository or directory you want it to work in:@@ -90,7 +90,7 @@ Prime Agent is built for long-running work, especially for evaluations in resear- **Continual Harness:** `/refine` can persist focused, reviewable lessons as supplemental prompts, memories, reusable skill descriptions, or subagent specifications, with recorded refinement history. It does not replace packaging and reviewing new executable skills.- **Direct agent-to-agent communication:** running agents and retained subagents can discover one another, exchange messages, and steer active work.-- **Daemon-backed continuity:** active sessions, IPython state, schedules, and subagents keep running when the terminal detaches and can be reattached later.+- **Daemon-backed continuity:** active sessions, Python REPL state, schedules, and subagents keep running when the terminal detaches and can be reattached later.- **Heartbeats and schedules:** `/heartbeat`, `rlm_heartbeat`, and `prime-agent schedule` can re-enter a session periodically or at a specific time.- **Persistent goals:** `/goal` keeps an objective and its progress active across turns until it is completed, paused, or cleared.- **Bounded autonomous mode:** `/autonomous` continues within configured turn, token, and time budgets and can run user-defined quality gates. A passed gate checks only what that gate verifies; reaching a limit does not imply task success.@@ -100,7 +100,7 @@ Prime Agent is built for long-running work, especially for evaluations in resear- [Quickstart](packages/coding-agent/docs/quickstart.md) — install, authenticate, and run a first session- [Usage and CLI reference](packages/coding-agent/docs/usage.md) — commands, sessions, autonomous limits, and output modes- [Long-running and background agents](packages/coding-agent/docs/long-running-agents.md) — detach and reattach, goals, heartbeats, and schedules-- [RLM programming model](packages/coding-agent/docs/rlm.md) — persistent IPython, subagents, skills, and the trust model+- [RLM programming model](packages/coding-agent/docs/rlm.md) — the persistent Python REPL, subagents, skills, and the trust model- [JSON mode](packages/coding-agent/docs/json.md) and [RPC mode](packages/coding-agent/docs/rpc.md) — headless automation and integrations- [Skills](packages/coding-agent/docs/skills.md) — install and create reusable capabilities- [Provider setup](packages/coding-agent/docs/providers.md) — subscription and API-key providersdiff --git a/install.sh b/install.shindex 0e76ea5437..c1b5c52458 100755--- a/install.sh+++ b/install.sh@@ -1565,8 +1565,8 @@ confirm_kernel_runtime_setup() {esacif prime_agent_prompt_yes_no \- "Prepare IPython runtime now?" \- "Installs uv, Python 3.11, ipykernel, and Prime Agent runtime." \+ "Prepare Python runtime now?" \+ "Installs uv, Python 3.11, and the Prime Agent runtime." \"Prepare? [Y/n]"; thenprime_agent_bootstrap_kernel_on_install=1return@@ -1575,17 +1575,17 @@ confirm_kernel_runtime_setup() {fiif [ "$prompt_status" -eq 2 ]; then- printf 'No terminal detected; preparing the IPython runtime during install.\n'+ printf 'No terminal detected; preparing the Python runtime during install.\n'prime_agent_bootstrap_kernel_on_install=1returnfiprime_agent_bootstrap_kernel_on_install=0if [ "$prime_agent_screen_enabled" = 1 ]; then- prime_agent_screen "IPython setup skipped" "" "The runtime can be prepared on first ipython use." ""+ prime_agent_screen "Python setup skipped" "" "The runtime can be prepared on first ipython use." ""sleep 0.4else- printf '\nSkipping IPython runtime setup.\n'+ printf '\nSkipping Python runtime setup.\n'fi}@@ -1596,7 +1596,7 @@ install_prime_agent_package() {Linking command binaries.Installing runtime packages.Preloading search tools.-Preparing IPython kernel.+Preparing Python kernel.Finalizing npm install."prime_agent_run_quiet_with_animation_steps \"Installing Prime Agent" \diff --git a/package-lock.json b/package-lock.jsonindex b8cc996d58..e2faaa6da8 100644--- a/package-lock.json+++ b/package-lock.json@@ -481,9 +481,6 @@"arm64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT OR Apache-2.0","optional": true,"os": [@@ -501,9 +498,6 @@"arm64"],"dev": true,- "libc": [- "musl"- ],"license": "MIT OR Apache-2.0","optional": true,"os": [@@ -521,9 +515,6 @@"x64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT OR Apache-2.0","optional": true,"os": [@@ -541,9 +532,6 @@"x64"],"dev": true,- "libc": [- "musl"- ],"license": "MIT OR Apache-2.0","optional": true,"os": [@@ -611,43 +599,6 @@"resolved": "packages/tui","link": true},- "node_modules/@emnapi/core": {- "version": "2.0.0-alpha.3",- "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-alpha.3.tgz",- "integrity": "sha512-AZypUeJ/yByuxyS7BlSNRDOMLMlROYtjYdIAuBmJssVz1UJDSeYxLrdizhXCFYhedC5bqd/ASy8EuNXbVVXp9g==",- "dev": true,- "license": "MIT",- "optional": true,- "peer": true,- "dependencies": {- "@emnapi/wasi-threads": "2.0.1",- "tslib": "^2.4.0"- }- },- "node_modules/@emnapi/runtime": {- "version": "2.0.0-alpha.3",- "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-alpha.3.tgz",- "integrity": "sha512-hFPAhMUjJD9BSyCANEISPOogeXC9Zo9ZQl7L6vKnaVsMkCtzznaW/naYypeyl0Gv5rYfWYsZbpixTMpjDJzQeA==",- "dev": true,- "license": "MIT",- "optional": true,- "peer": true,- "dependencies": {- "tslib": "^2.4.0"- }- },- "node_modules/@emnapi/wasi-threads": {- "version": "2.0.1",- "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.0.1.tgz",- "integrity": "sha512-9DsSk+o5NBX0CCJT8s0EROGSGxjR/tKu6aBTaVyq+SjAEQH4XcdcRxPBRzsBLizTTJ49MJjF+jgu3qnO9GLQcQ==",- "dev": true,- "license": "MIT",- "optional": true,- "peer": true,- "dependencies": {- "tslib": "^2.4.0"- }- },"node_modules/@esbuild/aix-ppc64": {"version": "0.28.1","resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",@@ -1193,9 +1144,6 @@"cpu": ["arm64"],- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -1212,9 +1160,6 @@"cpu": ["arm64"],- "libc": [- "musl"- ],"license": "MIT","optional": true,"os": [@@ -1231,9 +1176,6 @@"cpu": ["riscv64"],- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -1250,9 +1192,6 @@"cpu": ["x64"],- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -1269,9 +1208,6 @@"cpu": ["x64"],- "libc": [- "musl"- ],"license": "MIT","optional": true,"os": [@@ -1528,9 +1464,6 @@"arm64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -1548,9 +1481,6 @@"arm64"],"dev": true,- "libc": [- "musl"- ],"license": "MIT","optional": true,"os": [@@ -1568,9 +1498,6 @@"ppc64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -1588,9 +1515,6 @@"s390x"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -1608,9 +1532,6 @@"x64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -1628,9 +1549,6 @@"x64"],"dev": true,- "libc": [- "musl"- ],"license": "MIT","optional": true,"os": [@@ -2819,15 +2737,6 @@"node": ">=8"}},- "node_modules/cmake-ts": {- "version": "1.0.2",- "resolved": "https://registry.npmjs.org/cmake-ts/-/cmake-ts-1.0.2.tgz",- "integrity": "sha512-5l++JHE7MxFuyV/OwJf3ek7ZZN1aGPFPM5oUz6AnK5inQAPe4TFXRMz5sA2qg2FRgByPWdqO+gSfIPo8GzoKNQ==",- "license": "MIT",- "bin": {- "cmake-ts": "build/main.js"- }- },"node_modules/color-convert": {"version": "2.0.1","license": "MIT",@@ -3100,6 +3009,7 @@"dev": true,"hasInstallScript": true,"license": "MIT",+ "peer": true,"bin": {"esbuild": "bin/esbuild"},@@ -3697,6 +3607,7 @@"node_modules/jiti": {"version": "2.7.0","license": "MIT",+ "peer": true,"bin": {"jiti": "lib/jiti-cli.mjs"}@@ -3888,9 +3799,6 @@"arm64"],"dev": true,- "libc": [- "glibc"- ],"license": "MPL-2.0","optional": true,"os": [@@ -3912,9 +3820,6 @@"arm64"],"dev": true,- "libc": [- "musl"- ],"license": "MPL-2.0","optional": true,"os": [@@ -3936,9 +3841,6 @@"x64"],"dev": true,- "libc": [- "glibc"- ],"license": "MPL-2.0","optional": true,"os": [@@ -3960,9 +3862,6 @@"x64"],"dev": true,- "libc": [- "musl"- ],"license": "MPL-2.0","optional": true,"os": [@@ -5157,6 +5056,7 @@"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"},@@ -5223,6 +5123,7 @@"integrity": "sha512-GQHnkIfxyx1wYCOS/wonik5MVRZU9hi1TEZmzGZSCJB1y9YgoZ8H6itNE/u4suE+yLmOzuE4E5S4TZ/ZX2wcWQ==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"esbuild": "~0.28.0"},@@ -5333,6 +5234,7 @@"integrity": "sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"lightningcss": "^1.32.0","picomatch": "^4.0.5",@@ -5623,6 +5525,7 @@"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz","integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==","license": "ISC",+ "peer": true,"bin": {"yaml": "bin.mjs"},@@ -5666,34 +5569,12 @@"fd-slicer": "~1.1.0"}},- "node_modules/zeromq": {- "version": "6.5.0",- "resolved": "https://registry.npmjs.org/zeromq/-/zeromq-6.5.0.tgz",- "integrity": "sha512-vWOrt19lvcXTxu5tiHXfEGQuldSlU+qZn2TT+4EbRQzaciWGwNZ99QQTolQOmcwVgZLodv+1QfC6UZs2PX/6pQ==",- "hasInstallScript": true,- "license": "MIT AND MPL-2.0",- "dependencies": {- "cmake-ts": "1.0.2",- "node-addon-api": "^8.3.1"- },- "engines": {- "node": ">= 12"- }- },- "node_modules/zeromq/node_modules/node-addon-api": {- "version": "8.9.1",- "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.1.tgz",- "integrity": "sha512-4eUQWVPCUUUiBjLnHS3cXWeC6ryoPUc0U3rP7IuzapoGbzMqd/r6KKO0clr0b+snQhsrueFEhCZDdK+LK7hxKg==",- "license": "MIT",- "engines": {- "node": "^18 || ^20 || >= 21"- }- },"node_modules/zod": {"version": "3.25.76","resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz","integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==","license": "MIT",+ "peer": true,"funding": {"url": "https://github.com/sponsors/colinhacks"}@@ -5812,8 +5693,7 @@"typebox": "^1.3.9","undici": "^7.29.0","uuid": "^14.0.0",- "yaml": "^2.9.0",- "zeromq": "^6.1.2"+ "yaml": "^2.9.0"},"bin": {"pi": "dist/bundle/cli.js"diff --git a/packages/coding-agent/.changes/repl-03-host-swap.md b/packages/coding-agent/.changes/repl-03-host-swap.mdnew file mode 100644index 0000000000..cfc4c95871--- /dev/null+++ b/packages/coding-agent/.changes/repl-03-host-swap.md@@ -0,0 +1 @@+- Changed the kernel to run on a minimal CPython REPL runtime speaking JSON lines over stdio.diff --git a/packages/coding-agent/.changes/repl-04-cutover.md b/packages/coding-agent/.changes/repl-04-cutover.mdnew file mode 100644index 0000000000..86d5e9b8a5--- /dev/null+++ b/packages/coding-agent/.changes/repl-04-cutover.md@@ -0,0 +1,2 @@+- Changed the kernel to a minimal Python REPL: `%%bash` cells, `%cd`, `%env`, and `!` escapes were replaced by `bash('cmd')` and `os.chdir(...)`/`os.environ[...]` (magic-style cells fail with a plain Python `SyntaxError`); startup is faster and memory use is lower.+- Removed the Jupyter/ipykernel kernel client; existing kernel venvs are rebuilt once (slimmer, no ipykernel) on next start.diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex cbb4dd7875..17ed90b35c 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -2,10 +2,31 @@## [Unreleased]+- Fixed background (unattributed) kernel output missing from the expanded IPython cell view: it is now surfaced in the tool details and rendered under a "background output (unattributed)" label after stdout/stderr/result.+- Fixed a protocol interrupt during a REPL state restore leaving a mixed old/new namespace: names are now staged first and applied atomically with SIGINT parked across the apply, and an interrupt landing anywhere between a committed snapshot or restore and its request finishing is recovered instead of misreporting the completed operation as failed.+- Fixed the REPL snapshot writer leaving a new payload beside a truncated manifest on mid-write failures: payload and manifest now commit via unique same-directory temp files and atomic renames with guaranteed cleanup, and an interrupt during cleanup can no longer misreport a completed destructive snapshot as failed.+- Fixed the REPL runtime `list_names` request crashing the serve loop when the namespace held a non-string key; non-string keys are now skipped and every runtime request fails individually through the shared backstop instead of killing the loop.+- Addressed REPL host-swap review findings: reworded stale IPython-specific busy/restart messages for the default kernel and stopped `restart()` from resurrecting a concurrently killed REPL kernel.+- Fixed graceful REPL kernel `shutdown()` losing teardown ownership to its own child's exit handler, which made `restart()` misread the shutdown as superseded and never start the kernel again.+- Fixed REPL kernel `start()` waiting out the full 30s ready timeout when the kernel process fails to spawn; the spawn error now rejects startup immediately.+- Fixed a cell that rebound or ignored SIGINT (or a restored prior handler) permanently breaking protocol interrupts: the REPL runtime now re-asserts its SIGINT handler between cells.+- Fixed the Python REPL runtime surviving its owning process's death while a non-yielding cell runs: an owner-watchdog thread now hard-exits the runtime (killing live bash children first) when the owner process dies.+- Fixed an interrupt parked during a snapshot's prune window misreporting the completed destructive snapshot as failed; it is now consumed once the manifest is committed, and an interrupt landing just after a completed snapshot/restore request is consumed too instead of failing its done.+- Fixed a REPL runtime interrupt gap where an interrupt landing during a cell's trailing-expression repr or output drain was dropped; the request now stays interruptible until its done event is emitted, so a slow user __repr__ can be cancelled.+- Fixed two REPL runtime request-lifecycle bugs: a cell closing sys.stdout/sys.stderr no longer kills the serve loop (done still arrives and later cells run), and an untargeted interrupt parked for a request that fails to compile is consumed with that request instead of spuriously cancelling the next cell.+- Fixed the REPL runtime leaking a finished cell's id onto late background-thread output: the current cell is now cleared right after the post-cell drain, so `done` stays the last event with that id and between-cell output carries a null id.- Fixed bash() cells failing under strict-POSIX shells (dash) when the status pipe landed on a multi-digit fd.+- Fixed rlm.run outside a live kernel hanging forever instead of failing fast, which stalled CI shard 3 until timeout.- Fixed two bash() spawn races: status-channel fds no longer leak when pipe creation fails mid-setup, and a status-socket gate keeps the command from starting until its pid is journaled (a kernel kill in that window now stops the child instead of orphaning it past the reaper).+- Fixed a compile-phase crash (e.g. RecursionError from a pathologically deep attribute chain) killing the REPL runtime instead of failing the one cell: any per-request failure now becomes error+done and the serve loop keeps running; rebinding sys.stdout/sys.stderr to flush-less objects no longer kills it either.+- Fixed the REPL runtime hanging before done when a cell closes fd 1/2 and a later open() reclaims the number: drain sync tokens now go through a private dup of the capture pipe, with a pump-liveness backstop so a dead pump can no longer wedge the serve loop.- Fixed the Windows orphan reaper killing only the journaled bash() shell pid; it now uses taskkill /T so descendants die with the tree, matching the in-kernel bash() kill paths, and resolves taskkill via an absolute System32 path (with NoDefaultCurrentDirectoryInExePath) so a planted CWD taskkill.exe cannot hijack cleanup.+- Fixed a snapshot request with identical `path` and `manifest_path` silently clobbering the just-written state payload; the runtime now rejects it as a failed request.+- Fixed a snapshot request with a negative `max_bytes`/`max_variable_bytes` and `prune_oversized` writing an empty payload and then deleting every user variable; size caps must now be non-negative integers.+- Fixed an interrupt landing mid-snapshot leaving prune deletions half-applied: once the snapshot manifest is committed, SIGINT is deferred until every oversized name is removed, so the namespace always matches the on-disk snapshot.- Hardened bash(): cancelling `await bash(cmd)` now kills the command's process group (background handles are unaffected), Windows helper binaries resolve via absolute System32 paths, kill() retries taskkill for already-reaped Windows trees, and orphan-journal enrollment fails closed when configured.+- Fixed cross-cell output misattribution in the REPL runtime: stream events are attributed at write time via context, and raw fd or user-thread output is emitted with a null id instead of being credited to whichever cell is running.+- REPL kernel: output from user threads, other cells' leftovers, and raw fd writes is no longer merged into the running cell's stdout; it is surfaced separately as unattributed background output.- Hardened bash() further: the host now injects an absolute default shell into the kernel (no PATH lookup; /bin/bash else /bin/sh on POSIX), macOS start-id lookup uses /bin/ps, and Windows worker-teardown orphan kills go through hardened taskkill /T.- Hardened Windows bash execution: the kernel shell is resolved only from trusted absolute paths (never PATH), and bash children are contained by kill-on-close job objects so a crashed kernel cannot leak process trees (taskkill remains only as a fallback when job creation fails).- Hardened Windows bash() containment: children are now created directly inside the kill-on-close job (PROC_THREAD_ATTRIBUTE_JOB_LIST at CreateProcessW time), so no window exists in which a kernel kill can leak a suspended, never-run process; handle inheritance is restricted to exactly the child's stdio handles (PROC_THREAD_ATTRIBUTE_HANDLE_LIST), so concurrent spawns cannot leak each other's handles; the journal start-id query still runs only while the job-contained child is suspended, and bash() still raises instead of falling back to jobless taskkill when containment fails.diff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.mdindex 8788fe95de..5f6bd39454 100644--- a/packages/coding-agent/README.md+++ b/packages/coding-agent/README.md@@ -68,7 +68,7 @@ prime-agentThen just talk to Prime Agent. By default, Prime Agent gives the model one tool: `ipython`. The model uses the persistent kernel to read files, run commands, edit code, and inspect data. Add capabilities via [skills](#skills), [prompt templates](#prompt-templates), [extensions](#extensions), or [Prime Agent packages](#prime-agent-packages).-The Python kernel runtime is set up automatically on first invocation. Set `PRIME_AGENT_KERNEL_PYTHON` to use an existing Python environment with `ipykernel`.+The Python kernel runtime is set up automatically on first invocation. Set `PRIME_AGENT_KERNEL_PYTHON` to use an existing Python environment with `prime-agent-runtime`.**Platform notes:** [Windows](docs/windows.md) | [Termux (Android)](docs/termux.md) | [tmux](docs/tmux.md) | [Terminal setup](docs/terminal-setup.md) | [Shell aliases](docs/shell-aliases.md)@@ -309,7 +309,7 @@ description: Use this skill when the user asks about X.2. Then that```-Skills can also be Python-backed. A Python skill is a normal skill directory with `SKILL.md` plus a Python package at `src/<import_name>/`. Prime Agent installs it into the persistent IPython kernel and exposes it by import name, so the model can call it directly, inspect it with `help()`, or use any console scripts the skill declares.+Skills can also be Python-backed. A Python skill is a normal skill directory with `SKILL.md` plus a Python package at `src/<import_name>/`. Prime Agent installs it into the persistent Python kernel and exposes it by import name, so the model can call it directly, inspect it with `help()`, or use any console scripts the skill declares.Place in `~/.prime/agent/skills/`, `~/.agents/skills/`, `.prime/agent/skills/`, or `.agents/skills/` (from `cwd` up through parent directories) or a [Prime Agent package](#prime-agent-packages) to share with others. See [docs/skills.md](docs/skills.md).@@ -659,7 +659,7 @@ prime-agent --model sonnet:high "Solve this complex problem"# Limit model cyclingprime-agent --models "claude-*,gpt-4o"-# Restrict to the built-in IPython tool+# Restrict to the built-in Python REPL toolprime-agent --tools ipython -p "Review the code"# High thinking level@@ -684,7 +684,7 @@ prime-agent --thinking high "Solve this complex problem"| `PRIME_API_KEY` | Prime Inference API key; also used for trace sharing if it has `agent_traces` scope || `PRIME_AGENT_TRACES_API_KEY` | Prime API key used only for opt-in trace sharing || `PRIME_AGENT_TRACES_BASE_URL` | Override the Prime Agent trace upload API base URL |-| `PRIME_AGENT_KERNEL_PYTHON` | Use an existing Python environment with `ipykernel` instead of auto-bootstrapping `~/.prime/agent/kernel-venv` |+| `PRIME_AGENT_KERNEL_PYTHON` | Use an existing Python environment with `prime-agent-runtime` instead of auto-bootstrapping `~/.prime/agent/kernel-venv` || `VISUAL`, `EDITOR` | External editor for Ctrl+G |The remaining `PI_*` variables in this table are compatibility names still read by the current runtime. They do not change the application name, command, or default `~/.prime/agent` configuration path.diff --git a/packages/coding-agent/docs/acp.md b/packages/coding-agent/docs/acp.mdindex bb56ad6cc7..4f1db9679b 100644--- a/packages/coding-agent/docs/acp.md+++ b/packages/coding-agent/docs/acp.md@@ -64,11 +64,11 @@ Session activity arrives as `session/update` notifications:| tool finishes | `tool_call_update` (`completed` / `failed`) || shell output | `tool_call` plus incremental `tool_call_update` |-IPython is Prime Agent's model-facing tool, so a cell is a `tool_call` of kind `execute` whose `rawInput` carries the cell source.+The Python REPL is Prime Agent's model-facing tool, so a cell is a `tool_call` of kind `execute` whose `rawInput` carries the cell source.## Prime Agent extensions-Prime Agent has capabilities ACP has no field for: subagents, autonomous quality gates, goals, heartbeats, continual-harness refinement, compaction, and rich IPython output. These travel in a reverse-domain `_meta` envelope:+Prime Agent has capabilities ACP has no field for: subagents, autonomous quality gates, goals, heartbeats, continual-harness refinement, compaction, and rich kernel output. These travel in a reverse-domain `_meta` envelope:```json{diff --git a/packages/coding-agent/docs/architecture.md b/packages/coding-agent/docs/architecture.mdindex 65b9c91bb6..9b6a235d80 100644--- a/packages/coding-agent/docs/architecture.md+++ b/packages/coding-agent/docs/architecture.md@@ -16,7 +16,7 @@ flowchart LRruntime["AgentSessionRuntime"]root["Root AgentSession"]scheduler["Scheduler"]- kernel["Root IPython kernel"]+ kernel["Root Python kernel"]children["RLM child runtimes<br/>session + optional kernel"]runtime --> root@@ -44,7 +44,7 @@ flowchart LR- The supervisor owns discovery, routing, attachments, worker health, and cross-agent message delivery.- Each worker owns one root runtime, its scheduler, kernels, and all descendants below that root.- `AgentSession` owns provider calls, queues, tools, compaction, goals, child lifecycles, and transcript writes.-- IPython is the model-facing control environment. Typed host requests return authoritative operations to the TypeScript session.+- The Python REPL is the model-facing control environment. Typed host requests return authoritative operations to the TypeScript session.Workers and kernels are separate processes for lifecycle and failure containment, not security sandboxes. They normally run with the same operating-system permissions as the client.@@ -58,7 +58,7 @@ sequenceDiagramparticipant W as Session workerparticipant A as AgentSessionparticipant P as Model provider- participant K as IPython kernel+ participant K as Python kernelparticipant D as Session storageU->>C: prompt, steer, or follow-up@@ -66,8 +66,8 @@ sequenceDiagramS->>W: route to active sessionW->>A: enqueue promptA->>P: stream model request- P-->>A: text or IPython tool call- opt IPython tool call+ P-->>A: text or Python tool call+ opt Python tool callA->>K: execute Pythonalt Typed host requestK->>A: request host operation@@ -89,5 +89,5 @@ From the session queue onward, the same execution and persistence path is used w- [Agent Connection Architecture](agent-connection.md) explains the client/runtime boundary, snapshots, replay, and reconnect behavior.- [Daemon Architecture](daemon.md) covers process ownership, leases, scheduling, backpressure, and crash recovery.-- [RLM Runtime Architecture](rlm-runtime.md) follows IPython host requests and recursive child execution.+- [RLM Runtime Architecture](rlm-runtime.md) follows kernel host requests and recursive child execution.- [Long-Running and Background Agents](long-running-agents.md) shows how detached sessions, messages, goals, and scheduled work share the worker runtime.diff --git a/packages/coding-agent/docs/extensions.md b/packages/coding-agent/docs/extensions.mdindex 02804a445c..4fd2912808 100644--- a/packages/coding-agent/docs/extensions.md+++ b/packages/coding-agent/docs/extensions.md@@ -1524,7 +1524,7 @@ const active = pi.getActiveTools();const all = pi.getAllTools();// [{// name: "ipython",-// description: "Execute Python code in a persistent IPython kernel...",+// description: "Execute Python code in a persistent Python REPL...",// parameters: ...,// sourceInfo: { path: "<builtin:ipython>", source: "builtin", scope: "temporary", origin: "top-level" }// }, ...]diff --git a/packages/coding-agent/docs/index.md b/packages/coding-agent/docs/index.mdindex 847fd73b63..96fb32160e 100644--- a/packages/coding-agent/docs/index.md+++ b/packages/coding-agent/docs/index.md@@ -1,6 +1,6 @@# Prime Agent Documentation-Prime Agent is an RLM-native coding and research harness built around a persistent IPython kernel, recursive subagents, durable sessions, and a multi-process local runtime. It began as a hard fork of pi-mono, but Prime Agent is now the product, CLI, install source, and development repository.+Prime Agent is an RLM-native coding and research harness built around a persistent Python REPL kernel, recursive subagents, durable sessions, and a multi-process local runtime. It began as a hard fork of pi-mono, but Prime Agent is now the product, CLI, install source, and development repository.## Quick Start@@ -72,4 +72,4 @@ Public releases are currently installed from versioned release artifacts. The in- [Architecture overview](architecture.md) - system topology and end-to-end prompt flow.- [Daemon Architecture](daemon.md) - supervisor, catalog, worker, lifecycle, and recovery details.- [Agent Connection Architecture](agent-connection.md) - client/runtime connection boundary.-- [RLM Runtime Architecture](rlm-runtime.md) - ZeroMQ kernel transport and recursive subagent execution.+- [RLM Runtime Architecture](rlm-runtime.md) - stdio kernel transport and recursive subagent execution.diff --git a/packages/coding-agent/docs/long-running-agents.md b/packages/coding-agent/docs/long-running-agents.mdindex 2ec0a36e9e..436a40d447 100644--- a/packages/coding-agent/docs/long-running-agents.md+++ b/packages/coding-agent/docs/long-running-agents.md@@ -18,7 +18,7 @@ flowchart TDpolicy["Continuation policy"]queue["Session prompt queue"]session["AgentSession"]- kernel["Persistent IPython kernel"]+ kernel["Persistent Python kernel"]children["RLM child sessions"]heartbeat --> queue@@ -44,7 +44,7 @@ The client can detach at any point. The resident worker continues to own the que## Daemon-Backed Sessions-Normal interactive sessions run in resident worker processes managed by a local supervisor. The worker owns the root session, its IPython kernel, scheduled jobs, and RLM descendants.+Normal interactive sessions run in resident worker processes managed by a local supervisor. The worker owns the root session, its Python kernel, scheduled jobs, and RLM descendants.Closing the terminal UI detaches the client; it does not stop the worker. List and reconnect to active agents with:@@ -76,7 +76,7 @@ The daemon routes direct messages between active sessions and retained daemon-baprime-agent send <agent> "Please verify the latest migration"```-From the IPython kernel, use the preloaded `agent_message` Python skill:+From the Python kernel, use the preloaded `agent_message` Python skill:```pythonroster = await agent_message.list_agents()@@ -227,7 +227,7 @@ Goals and autonomous mode are complementary but different:## Compaction and Continuity-Automatic compaction handles context growth during long tasks. On overflow or near the configured threshold, Prime Agent summarizes older messages, retains recent context, and continues. The IPython kernel persists through compaction, so variables, imports, helper functions, and task state remain available.+Automatic compaction handles context growth during long tasks. On overflow or near the configured threshold, Prime Agent summarizes older messages, retains recent context, and continues. The Python kernel persists through compaction, so variables, imports, helper functions, and task state remain available.The agent can inspect or request compaction programmatically:diff --git a/packages/coding-agent/docs/mcp-integrations.md b/packages/coding-agent/docs/mcp-integrations.mdindex e8d85c87d2..4991cecab5 100644--- a/packages/coding-agent/docs/mcp-integrations.md+++ b/packages/coding-agent/docs/mcp-integrations.md@@ -5,7 +5,7 @@ Connect external services (Linear, Notion, …) to Prime Agent over theConsistent with Prime Agent's single-tool design, MCP integrations are **not**exposed as new agent tools. Each integration is a [Python-backed skill](skills.md)-that the model imports and calls from the IPython kernel:+that the model imports and calls from the Python kernel:```pythonimport linear@@ -123,7 +123,7 @@ to the user settings file:}```-The generic `mcp` module is pre-imported in IPython. Server and tool names are+The generic `mcp` module is pre-imported in the Python REPL. Server and tool names arepassed through unchanged:```pythondiff --git a/packages/coding-agent/docs/quickstart.md b/packages/coding-agent/docs/quickstart.mdindex 95fd940eaa..e55a8375b5 100644--- a/packages/coding-agent/docs/quickstart.md+++ b/packages/coding-agent/docs/quickstart.md@@ -71,13 +71,13 @@ Once Prime Agent starts, type a request and press Enter:Summarize this repository and tell me how to run its checks.```-Prime Agent gives the model one built-in tool, `ipython`. The long-lived kernel is a control environment for reading and editing files, running project commands, inspecting data, retaining Python state, and invoking installed skills. The kernel runtime is bootstrapped automatically on first use; set `PRIME_AGENT_KERNEL_PYTHON` to use an existing Python environment with `ipykernel`.+Prime Agent gives the model one built-in tool, `ipython`. The long-lived kernel is a control environment for reading and editing files, running project commands, inspecting data, retaining Python state, and invoking installed skills. The kernel runtime is bootstrapped automatically on first use; set `PRIME_AGENT_KERNEL_PYTHON` to use an existing Python environment with `prime-agent-runtime`.Prime Agent runs in your current working directory and can modify files there. Use git or another checkpointing workflow if you want easy rollback.## Recursive Subagents-Recursive subagents are a built-in Prime Agent capability. The model spawns independent work from IPython with `await rlm("subtask")`; each call returns at admission with a child handle and never returns the answer. Children send requested results as explicit `agent_message` replies to the parent or write them to files. Child agents use the same TypeScript agent runtime, providers, tools, skills, and session machinery as the parent.+Recursive subagents are a built-in Prime Agent capability. The model spawns independent work from the Python REPL with `await rlm("subtask")`; each call returns at admission with a child handle and never returns the answer. Children send requested results as explicit `agent_message` replies to the parent or write them to files. Child agents use the same TypeScript agent runtime, providers, tools, skills, and session machinery as the parent.You can prompt the model to use that capability directly:@@ -127,7 +127,7 @@ In interactive mode:!npm run lint```-The command output is sent to the model. Use `!!command` to run a command without adding its output to model context. During agent work, the model normally runs project commands from the IPython control environment with a `%%bash` cell.+The command output is sent to the model. Use `!!command` to run a command without adding its output to model context. During agent work, the model normally runs project commands from the Python REPL with `bash()`.### Switch Modelsdiff --git a/packages/coding-agent/docs/rlm-runtime.md b/packages/coding-agent/docs/rlm-runtime.mdindex 332ea3f03b..63625ccbc9 100644--- a/packages/coding-agent/docs/rlm-runtime.md+++ b/packages/coding-agent/docs/rlm-runtime.md@@ -1,22 +1,22 @@# RLM Runtime Architecture-Prime Agent gives each agent session a persistent IPython kernel and a native recursive sub-agent interface. The Python `rlm` package is a model-facing shim; the TypeScript host owns child execution, persistence, usage accounting, and lifecycle.+Prime Agent gives each agent session a persistent Python REPL kernel and a native recursive sub-agent interface. The Python `rlm` package is a model-facing shim; the TypeScript host owns child execution, persistence, usage accounting, and lifecycle.## Architecture```mermaidflowchart TD- session["AgentSession · TypeScript<br/>IPython tool + host request handlers"]- manager["KernelManager · TypeScript<br/>execution + comm dispatch"]- kernel["IPython kernel process · Python"]+ session["AgentSession · TypeScript<br/>Python REPL tool + host request handlers"]+ manager["ReplKernelManager · TypeScript<br/>execution + host-request dispatch"]+ kernel["REPL runtime process · Python"]runtime["prime-agent-runtime<br/>rlm module + Python skills"]code["Model-executed Python code"]session -->|"owns"| manager- manager <-->|"Jupyter protocol over ZeroMQ"| kernel+ manager <-->|"JSON lines over stdio"| kernelkernel --> runtime --> codecode -->|"rlm.run · goal.* · agent_message.*"| runtime- runtime -->|"comm target: host.request"| manager+ runtime -->|"host_request events"| managermanager -->|"typed dispatch"| session```@@ -27,7 +27,7 @@ handle = await rlm("inspect the API", name="api-reviewer")print(handle.rlm_child_id, handle.name, handle.session_dir, handle.model)```-the call travels through a Jupyter comm target named `host.request`. `KernelManager` dispatches request type `rlm.run` to the parent `AgentSession`, which starts a child through the same TypeScript agent machinery as the parent. The call returns over the comm immediately after task admission with a child handle; it never waits for or returns the child's answer. Results arrive only through explicit `agent_message` replies or files.+the call travels as a `host_request` event over the runtime's stdio protocol. `ReplKernelManager` dispatches request type `rlm.run` to the parent `AgentSession`, which starts a child through the same TypeScript agent machinery as the parent. The call returns over the same bridge immediately after task admission with a child handle; it never waits for or returns the child's answer. Results arrive only through explicit `agent_message` replies or files.The same bridge supports other typed host requests. Bundled Python skills such as `goal` call `rlm.host_request("goal.get", ...)`; state and policy remain in the TypeScript host.@@ -37,18 +37,18 @@ The same bridge supports other typed host requests. Bundled Python skills such asequenceDiagramparticipant M as Parent modelparticipant H as Parent AgentSession- participant K as IPython kernel+ participant K as Python kernelparticipant C as Child AgentSessionparticipant P as Model provider- M->>H: IPython tool call+ M->>H: Python tool callH->>K: execute await rlm("inspect the API")- K->>H: host.request · rlm.run+ K->>H: host_request · rlm.runH->>H: check depth and resolve modelH->>H: admit child task and update registryH-->>K: RLMSpawnHandleK-->>H: tool output- H-->>M: IPython result+ H-->>M: Python resultH->>C: create child runtime and promptloop Child agent loopC->>P: stream model request@@ -63,7 +63,7 @@ sequenceDiagram| Component | Responsibility ||---|---|-| `src/core/kernel/index.ts` | ZeroMQ sockets, Jupyter framing, execution, comm dispatch, interrupt, and shutdown. |+| `src/core/kernel/repl-manager.ts` | Runtime process, stdio protocol, execution, host-request dispatch, interrupt, and shutdown. || `src/core/tools/ipython.ts` | Agent tool wrapper, lazy kernel provisioning, namespace bootstrap, and output shaping. || `src/core/agent-session.ts` | RLM policy, child creation, registry, usage attribution, cancellation, and goal handlers. || `src/core/rlm-runtime.ts` | Typed request/spawn-handle validation for `rlm.run`, model discovery, list, and delete. |@@ -73,44 +73,32 @@ The Python side does not call providers or implement an agent loop.## Kernel Lifecycle-The kernel is created lazily on first IPython use. Python resolution is:+The kernel is created lazily on first Python REPL use. Python resolution is:-1. `PRIME_AGENT_KERNEL_PYTHON`, when it can import `ipykernel`;+1. `PRIME_AGENT_KERNEL_PYTHON`, when it has a current `prime-agent-runtime`;2. `~/.prime/agent/kernel-venv/bin/python`, bootstrapped with `uv`; or3. the XDG data location when `~/.prime` is not writable.-The managed environment includes Python 3.11, `ipykernel`, and `prime-agent-runtime`. A bootstrap marker detects stale environments.+The managed environment includes Python 3.11, `prime-agent-runtime`, `dill`, and the default Python packages. A bootstrap marker detects stale environments.-Startup creates a temporary Jupyter connection file with loopback TCP ports and an HMAC key, starts `python -m ipykernel_launcher`, connects shell, IOPub, and control sockets, waits for subscription propagation, and probes readiness with `kernel_info_request`.+Startup spawns `python -m rlm.repl` and exchanges newline-delimited JSON over stdio: the runtime announces itself with a single `ready` event, then requests and events flow one JSON object per line (see `prime-agent-runtime/src/rlm/repl.md`).-The manager owns the child process, connection directory, ZeroMQ sockets, and a bounded stderr tail. Shutdown sends `shutdown_request`, closes sockets, terminates the process as a fallback, and removes temporary connection data. Persistent sessions may snapshot the kernel namespace into their session artifact directory for revival.+The manager owns the child process and a bounded stderr tail. Shutdown sends a `shutdown` request, waits for the process to exit, and terminates it as a fallback. Persistent sessions may snapshot the kernel namespace into their session artifact directory for revival.-## Jupyter Transport+## Stdio Transport-Prime Agent uses three channels:+Requests flow to the runtime on stdin and events return on stdout, one JSON object per line:```text-shell execute_request, execute_reply, kernel_info_request-iopub stdout, stderr, results, errors, status, comm_open-control interrupt, shutdown, and host-request replies during execution+requests execute, interrupt, host_reply, snapshot, restore, list_names, shutdown+events ready, stdout, stderr, result, display, host_request, error, done```-Messages use normal Jupyter multipart framing:+Output events carry the id of the cell that was running when the bytes were produced; asyncio tasks keep their spawning cell's id even after that cell finishes, so detached work is attributed correctly.-```text-<IDS|MSG>-signature-header-parent_header-metadata-content-```--JSON frames are signed with HMAC-SHA256. Ordinary output is accepted only when `parent_header.msg_id` matches the active execution. Comm messages are handled before that filter because asynchronous Python tasks can open comms after their scheduling cell returns to idle.+Calls to `ReplKernelManager.execute()` are serialized. One kernel has one shared namespace and does not run two ordinary Python cells concurrently. RLM child agents can still run concurrently because each delegation uses a distinct host request and child runtime.-Calls to `KernelManager.execute()` are serialized. One kernel has one shared namespace and does not run two ordinary IPython cells concurrently. RLM child agents can still run concurrently because each delegation uses a distinct comm and child runtime.--## Why Host-Request Responses Use the Control Channel+## Host-Request Event FlowA running cell can await task admission:@@ -118,9 +106,7 @@ A running cell can await task admission:handle = await rlm("subtask")```-IPython processes shell messages serially. Sending the admission response on the shell channel would deadlock: the active `execute_request` cannot finish until the response arrives, while the kernel will not process that shell response until the request finishes.--The Python shim therefore registers comm handlers on the control channel, and the host sends admission responses there. Future completion is scheduled with `loop.call_soon_threadsafe()` because the control handler may run on another thread. Child answers do not use this response path; they arrive later through explicit `agent_message` replies or files.+The runtime ships the call to the host as a `host_request` event and keeps its event loop free while awaiting the reply. The host dispatches the typed request and answers with a `host_reply` request carrying the same id, so a cell can block on admission without stalling other runtime work. Child answers do not use this response path; they arrive later through explicit `agent_message` replies or files.## Python API@@ -136,10 +122,9 @@ host_request(request_type: str, payload: dict | None = None)RLMSpawnHandleRLMModelRLMSubagent-TokenUsage```-The IPython bootstrap places the callable `rlm` object in the user namespace, so these are equivalent:+The kernel bootstrap places the callable `rlm` object in the user namespace, so these are equivalent:```pythonawait rlm("subtask")@@ -249,7 +234,7 @@ Exact artifact files are created only when their features are used. Non-persiste## Trust Boundary-IPython executes model-generated Python and shell-magics with the worker's OS permissions. The kernel boundary isolates protocol and lifecycle concerns; it is not a security sandbox. Installed Python packages, skills, and extensions are trusted code. Use an external sandbox or restricted execution environment when the workspace or generated code is untrusted.+The REPL runtime process executes model-generated Python and `bash()` commands with the worker's OS permissions. The process boundary isolates protocol and lifecycle concerns; it is not a security sandbox. Installed Python packages, skills, and extensions are trusted code. Use an external sandbox or restricted execution environment when the workspace or generated code is untrusted.Provider credentials are resolved by the TypeScript host. The bounded model catalog crosses into Python as metadata; the full auth store does not.@@ -257,14 +242,14 @@ Provider credentials are resolved by the TypeScript host. The bounded model cata| Failure | Behavior ||---|---|-| Managed runtime is missing | Kernel bootstrap rebuilds it; a custom Python without `rlm` fails clearly when recursion is called. |-| Depth limit reached | Python raises before opening a comm; the host checks again. |+| Managed runtime is missing | Kernel bootstrap rebuilds it; a custom `PRIME_AGENT_KERNEL_PYTHON` without a current `prime-agent-runtime` is rejected at kernel startup. |+| Depth limit reached | The host rejects the `rlm.run` request; the error reply raises in Python. || Unsupported options | Host rejects the request. || Requested model unavailable | Spawn fails instead of substituting another model. |-| Shell-channel comm reply | Deadlock risk; current replies use control. |+| Host connection closed | Pending `host_request` calls fail with `RuntimeError` so awaiting cells unblock. || Child cancellation | Host aborts the child and removes failed/cancelled registry entries. || Parent teardown | Active descendants are cancelled and their runtimes are closed. |## Focused Validation-From the repository root, the implementation is covered by focused kernel, recursion, context-tree, daemon RLM, and runtime tests. When changing child creation or accounting, include `agent-session-recursion.test.ts`; when changing comm transport, include the kernel comm tests; when changing daemon retention, include the daemon RLM lifecycle tests.+From the repository root, the implementation is covered by focused kernel, recursion, context-tree, daemon RLM, and runtime tests. When changing child creation or accounting, include `agent-session-recursion.test.ts`; when changing the stdio runtime protocol, include the `repl-kernel-*.test.ts` suites; when changing daemon retention, include the daemon RLM lifecycle tests.diff --git a/packages/coding-agent/docs/rlm.md b/packages/coding-agent/docs/rlm.mdindex efd7bb5ca7..7d558073b4 100644--- a/packages/coding-agent/docs/rlm.md+++ b/packages/coding-agent/docs/rlm.md@@ -1,6 +1,6 @@# RLM Programming Model-Prime Agent is built around a recursive language model (RLM) runtime: the model works inside a persistent Python control environment and composes capabilities as code. Provider calls, session persistence, child lifecycles, scheduling, and safety policy remain in the TypeScript host; IPython is the model-facing programming surface.+Prime Agent is built around a recursive language model (RLM) runtime: the model works inside a persistent Python control environment and composes capabilities as code. Provider calls, session persistence, child lifecycles, scheduling, and safety policy remain in the TypeScript host; the Python REPL is the model-facing programming surface.## RLM Loop@@ -8,14 +8,14 @@ Prime Agent is built around a recursive language model (RLM) runtime: the modelflowchart LRtask["Task + working context"]parent["Parent model"]- kernel["Persistent IPython kernel"]+ kernel["Persistent Python kernel"]data["Files · data · shell commands"]skills["Python-backed skills"]children["rlm(...) child agents"]answer["Answer or next turn"]task --> parent- parent -->|"IPython call"| kernel+ parent -->|"Python call"| kernelkernel <-->|"inspect · search · transform"| datakernel <-->|"call functions"| skillskernel -->|"spawn focused work"| children@@ -41,14 +41,14 @@ config_files = list(Path(".").rglob("*.toml"))large_files = [path for path in config_files if path.stat().st_size > 10_000]```-Run a project's normal commands through its own environment from an IPython cell:+Run a project's normal commands through its own environment with `bash()`:-```bash-%%bash-npm run check+```python+result = await bash("npm run check")+print(result.output)```-Each `%%bash` cell is a temporary subshell, while Python state and `%cd` changes persist in the kernel. Prime Agent extensions may intentionally add custom tools, but the built-in RLM design does not require a separate model tool for every capability.+Each `bash()` call is its own process, while Python state, `os.chdir(...)`, and `os.environ[...]` changes persist in the kernel and apply to later `bash()` calls. Prime Agent extensions may intentionally add custom tools, but the built-in RLM design does not require a separate model tool for every capability.### 2. Subagents are native RLM calls@@ -140,6 +140,6 @@ This keeps credentials, provider execution, transcript writes, worker routing, a## Trust Model-The IPython kernel runs model-generated Python and project commands with the worker's operating-system permissions. It is a durable control environment, not a security sandbox. Review third-party Python skills and use an external sandbox or restricted environment for untrusted repositories and instructions.+The Python kernel runs model-generated Python and project commands with the worker's operating-system permissions. It is a durable control environment, not a security sandbox. Review third-party Python skills and use an external sandbox or restricted environment for untrusted repositories and instructions.For implementation details, see [RLM Runtime Architecture](rlm-runtime.md).diff --git a/packages/coding-agent/docs/skills.md b/packages/coding-agent/docs/skills.mdindex 2ed4500e10..ef41c05f27 100644--- a/packages/coding-agent/docs/skills.md+++ b/packages/coding-agent/docs/skills.md@@ -4,7 +4,7 @@Skills are self-contained capability packages that Prime Agent loads on demand. A skill provides specialized workflows, setup instructions, helper scripts, and reference documentation for specific tasks.-Prime Agent implements the [Agent Skills standard](https://agentskills.io/specification), warning about violations but remaining lenient. It also supports Python-backed skills: a superset of markdown skills that install Python packages into the persistent IPython kernel.+Prime Agent implements the [Agent Skills standard](https://agentskills.io/specification), warning about violations but remaining lenient. It also supports Python-backed skills: a superset of markdown skills that install Python packages into the persistent Python kernel.## Table of Contents@@ -71,7 +71,7 @@ export PRIME_AGENT_WEBSEARCH_NUM_RESULTS=5A `SERPER_API_KEY` in the environment, if set, takes precedence over the stored key.-Once loaded, the model can call it directly in the IPython kernel by import name:+Once loaded, the model can call it directly in the Python kernel by import name:```pythonprint(await websearch("latest Prime Agent release"))@@ -140,7 +140,7 @@ Skills with `disable-model-invocation: true` are hidden from the startup skill l## Python-Backed Skills-A Python-backed skill uses the same `SKILL.md` metadata and invocation behavior as a markdown skill, but also provides a Python package for the IPython kernel.+A Python-backed skill uses the same `SKILL.md` metadata and invocation behavior as a markdown skill, but also provides a Python package for the Python kernel.```web-search/@@ -157,7 +157,7 @@ Detection rules:- the import name is the skill name with hyphens converted to underscores- `src/<import_name>/__init__.py` must exist-For `web-search`, Prime Agent exposes `web_search` in IPython. If the module defines `run()`, the module is wrapped as an async callable:+For `web-search`, Prime Agent exposes `web_search` in the Python REPL. If the module defines `run()`, the module is wrapped as an async callable:```pythonawait web_search("prime agent skills")@@ -167,7 +167,7 @@ help(web_search)Python skills are installed editable into the kernel venv during kernel setup. By default this is `~/.prime/agent/kernel-venv`; set `PRIME_AGENT_KERNEL_VENV` to override it. If `pyproject.toml` changes, Prime Agent rebuilds the kernel venv so dependency changes are picked up.-If you set `PRIME_AGENT_KERNEL_PYTHON`, Prime Agent does not install packages into that environment. The Python must already have `ipykernel`, `prime-agent-runtime`, and the default runtime packages installed. Missing Python skill imports are disabled with a warning and calling the skill raises a `RuntimeError`.+If you set `PRIME_AGENT_KERNEL_PYTHON`, Prime Agent does not install packages into that environment. The Python must already have a current `prime-agent-runtime` and the default runtime packages installed. Missing Python skill imports are disabled with a warning and calling the skill raises a `RuntimeError`.### Optional CLI Command@@ -219,7 +219,7 @@ To force the creation workflow explicitly, invoke the built-in skill command:Tell the agent three things:1. **Scope:** use `.prime/agent/skills/<name>/` for a project skill committed with the repository, or `~/.prime/agent/skills/<name>/` for a personal skill.-2. **Kind:** ask for a markdown skill when the capability is primarily instructions; ask for a Python-backed skill when the agent should call reusable functionality from IPython.+2. **Kind:** ask for a markdown skill when the capability is primarily instructions; ask for a Python-backed skill when the agent should call reusable functionality from the Python REPL.3. **Contract:** describe the intended Python call, inputs, output, dependencies, credentials, and verification behavior.The agent should create `SKILL.md` in both cases. For a Python-backed skill it should also create `pyproject.toml` and `src/<import_name>/__init__.py`, expose a documented callable, and verify that the package imports in the kernel.diff --git a/packages/coding-agent/docs/usage.md b/packages/coding-agent/docs/usage.mdindex 3884659334..3d68af75bd 100644--- a/packages/coding-agent/docs/usage.md+++ b/packages/coding-agent/docs/usage.md@@ -2,7 +2,7 @@This page collects day-to-day usage details that do not fit on the quickstart page.-Prime Agent is built around one model-facing tool: a persistent IPython kernel. The kernel retains Python state across turns and acts as a control environment for file operations, project commands, installed Python skills, MCP-backed skills, and recursive subagents. The TypeScript host remains responsible for provider calls, session state, tool execution, scheduling, and child-agent lifecycles.+Prime Agent is built around one model-facing tool: a persistent Python REPL kernel. The kernel retains Python state across turns and acts as a control environment for file operations, project commands, installed Python skills, MCP-backed skills, and recursive subagents. The TypeScript host remains responsible for provider calls, session state, tool execution, scheduling, and child-agent lifecycles.## Interactive Mode@@ -104,7 +104,7 @@ See [Sessions](sessions.md) and [Compaction](compaction.md) for details.Normal interactive sessions are persistent agents backed by isolated worker processes. Closing the TUI detaches the client; use `prime-agent agents`, `prime-agent list`, or `prime-agent attach <agent>` to find and reattach to running work. `prime-agent stop <agent>` stops one root agent, while `prime-agent shutdown` stops all workers and the local supervisor.-Within a session, the model can delegate through the `rlm` callable already available in IPython:+Within a session, the model can delegate through the `rlm` callable already available in the Python REPL:```python# Spawn independent children. Each call returns at admission with a child handle,@@ -343,7 +343,7 @@ prime-agent --model sonnet:high "Solve this complex problem"# Limit model cyclingprime-agent --models "claude-*,gpt-4o"-# Restrict to the built-in IPython tool+# Restrict to the built-in Python REPL toolprime-agent --tools ipython -p "Review the code"```@@ -362,14 +362,14 @@ prime-agent --tools ipython -p "Review the code"| `PRIME_API_KEY` | Prime Inference API key; also used for trace sharing when it has `agent_traces` scope || `PRIME_AGENT_TRACES_API_KEY` | Prime API key used only for opt-in trace sharing || `PRIME_AGENT_TRACES_BASE_URL` | Override the Prime Agent trace upload API base URL |-| `PRIME_AGENT_KERNEL_PYTHON` | Use an existing Python environment with `ipykernel` instead of bootstrapping `~/.prime/agent/kernel-venv` |+| `PRIME_AGENT_KERNEL_PYTHON` | Use an existing Python environment with `prime-agent-runtime` instead of bootstrapping `~/.prime/agent/kernel-venv` || `VISUAL`, `EDITOR` | External editor for Ctrl+G |The remaining `PI_*` variables are compatibility names still read by the current runtime. They do not change the application name, command, or default `~/.prime/agent` configuration path.## Design Principles-Prime Agent keeps the model-facing tool surface small while making the IPython runtime powerful and composable. The built-in `ipython` tool provides durable state, project command execution, Python skills, MCP-backed integrations, and the native `rlm` delegation API without presenting each capability as a separate model tool.+Prime Agent keeps the model-facing tool surface small while making the Python REPL runtime powerful and composable. The built-in `ipython` tool provides durable state, project command execution, Python skills, MCP-backed integrations, and the native `rlm` delegation API without presenting each capability as a separate model tool.Recursive subagents are a core capability, not an optional extension. The TypeScript host owns every parent and child agent loop so recursion uses the same provider, session, tool, skill, scheduling, usage-accounting, and recovery infrastructure. The Python `rlm` package is a thin host bridge rather than a separate agent implementation.diff --git a/packages/coding-agent/package.json b/packages/coding-agent/package.jsonindex b08a8fb77c..78f9b6c97a 100644--- a/packages/coding-agent/package.json+++ b/packages/coding-agent/package.json@@ -1,7 +1,7 @@{"name": "@earendil-works/pi-coding-agent","version": "0.8.1",- "description": "Coding agent CLI with IPython-backed tools and session management",+ "description": "Coding agent CLI with a persistent Python REPL kernel and session management","type": "module","piConfig": {"name": "prime-agent",@@ -44,7 +44,7 @@"postinstall": "node postinstall.cjs","prepublishOnly": "npm run clean && npm run build","bundle": "node scripts/bundle.mjs",- "test:kernel": "vitest --run --no-file-parallelism --tagsFilter kernel-heavy test/acp-kernel-features.test.ts test/acp-cold-cli.test.ts test/kernel-goal-skill.test.ts test/kernel-state-roundtrip.test.ts test/kernel-mcp-shutdown.test.ts"+ "test:kernel": "vitest --run --no-file-parallelism --tagsFilter kernel-heavy test/acp-kernel-features.test.ts test/acp-cold-cli.test.ts test/kernel-goal-skill.test.ts test/repl-kernel-state-roundtrip.test.ts test/repl-kernel-mcp-shutdown.test.ts"},"dependencies": {"@agentclientprotocol/sdk": "^1.3.0",@@ -68,8 +68,7 @@"typebox": "^1.3.9","undici": "^7.29.0","uuid": "^14.0.0",- "yaml": "^2.9.0",- "zeromq": "^6.1.2"+ "yaml": "^2.9.0"},"overrides": {"rimraf": "6.1.2",diff --git a/packages/coding-agent/scripts/bundle.mjs b/packages/coding-agent/scripts/bundle.mjsindex 8d4155f8f2..c14d432123 100644--- a/packages/coding-agent/scripts/bundle.mjs+++ b/packages/coding-agent/scripts/bundle.mjs@@ -40,7 +40,7 @@ await build({platform: "node",// Native or interop-sensitive packages stay external; they resolve from// node_modules at runtime (and are loaded via createRequire/lazily anyway).- external: ["zeromq", "koffi", "undici", "@silvia-odwyer/photon-node", "@mariozechner/clipboard"],+ external: ["koffi", "undici", "@silvia-odwyer/photon-node", "@mariozechner/clipboard"],define: { __PI_BUNDLED__: "true", __PI_BUILD_ID__: JSON.stringify(buildId) },banner: {js: "import { createRequire as __piBundleCreateRequire } from 'node:module'; const require = __piBundleCreateRequire(import.meta.url);",diff --git a/packages/coding-agent/skills/agent-message/src/agent_message/__init__.py b/packages/coding-agent/skills/agent-message/src/agent_message/__init__.pyindex 24106e6e64..294c0a686e 100644--- a/packages/coding-agent/skills/agent-message/src/agent_message/__init__.py+++ b/packages/coding-agent/skills/agent-message/src/agent_message/__init__.py@@ -1,14 +1,13 @@"""Prime Agent session-to-session messaging skill.All routing and sender identity live in the TypeScript daemon. These functions-only call the host bridge exposed inside the Prime Agent IPython kernel.+only call the host bridge exposed inside the Prime Agent kernel."""from __future__ import annotationsfrom typing import Any, Literal-from IPython.display import displayfrom rlm import host_requestReceiverRole = Literal["parent", "sibling", "child"]@@ -69,6 +68,8 @@ async def send(def _emit_sent_message(receipt: dict[str, Any], receiver_role: str | None = None) -> None:try:+ from rlm import emit+label = ("Agent message queued"if receipt.get("deliveryStatus") == "queued"@@ -77,12 +78,11 @@ def _emit_sent_message(receipt: dict[str, Any], receiver_role: str | None = Nonedisplay_receipt = dict(receipt)if receiver_role in ("parent", "sibling", "child"):display_receipt["receiverRole"] = receiver_role- display(+ emit({_MESSAGE_DISPLAY_MIME: display_receipt,"text/plain": label,- },- raw=True,+ })except Exception:passdiff --git a/packages/coding-agent/skills/agent-observe/src/agent_observe/__init__.py b/packages/coding-agent/skills/agent-observe/src/agent_observe/__init__.pyindex a7ad5552b8..96030446f7 100644--- a/packages/coding-agent/skills/agent-observe/src/agent_observe/__init__.py+++ b/packages/coding-agent/skills/agent-observe/src/agent_observe/__init__.py@@ -1,7 +1,7 @@"""Read-only Prime Agent session observation skill.All session lookup and data access live in the TypeScript daemon. These-functions only call the host bridge exposed inside the Prime Agent IPython+functions only call the host bridge exposed inside the Prime Agent Pythonkernel."""diff --git a/packages/coding-agent/skills/attach-image/SKILL.md b/packages/coding-agent/skills/attach-image/SKILL.mdindex 8c3fb8bcfa..db6c10faf1 100644--- a/packages/coding-agent/skills/attach-image/SKILL.md+++ b/packages/coding-agent/skills/attach-image/SKILL.md@@ -32,7 +32,7 @@ compute over it. Use `attach_image` when you need to *see* the image.## Usage-Call the prepared `attach_image` import directly in the IPython kernel:+Call the prepared `attach_image` import directly in the Python kernel:```pythonprint(await attach_image("diagram.png"))diff --git a/packages/coding-agent/skills/attach-image/src/attach_image/attach_image.py b/packages/coding-agent/skills/attach-image/src/attach_image/attach_image.pyindex 692e568b6d..785e44066d 100644--- a/packages/coding-agent/skills/attach-image/src/attach_image/attach_image.py+++ b/packages/coding-agent/skills/attach-image/src/attach_image/attach_image.py@@ -192,15 +192,14 @@ def _resize_image(filepath: Path, mime_type: str, size: int, dimensions: tuple[idef _emit_attachment(filepath: Path, mime_type: str, size: int, dimensions: tuple[int, int]) -> str | None:- from IPython.display import display+ from rlm import emitdata_b64, emitted_mime_type, resize_note = _resize_image(filepath, mime_type, size, dimensions)- display(+ emit({_ATTACHMENT_DISPLAY_MIME: {"mime_type": emitted_mime_type, "data": data_b64, "path": str(filepath)},"text/plain": f"Loaded image into context: {filepath}",- },- raw=True,+ })return resize_notediff --git a/packages/coding-agent/skills/compact/SKILL.md b/packages/coding-agent/skills/compact/SKILL.mdindex 4a5d2e0207..b4e6dc6787 100644--- a/packages/coding-agent/skills/compact/SKILL.md+++ b/packages/coding-agent/skills/compact/SKILL.md@@ -1,6 +1,6 @@---name: compact-description: Check context usage and compact the conversation from IPython. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.+description: Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.---# Compact@@ -8,7 +8,7 @@ description: Check context usage and compact the conversation from IPython. UseCompaction replaces older conversation history with a dense summary, freeingcontext so long-running work can continue. The implementation lives in thehost (the same one behind the user's `/compact` command); this skill is the-kernel-side interface to it. Call it directly from IPython:+kernel-side interface to it. Call it directly from the Python REPL:```pythonawait compact.status()@@ -32,7 +32,7 @@ await compact.run("keep the failing test names and the migration checklist")- Compaction never runs mid-cell. A scheduled compaction runs when thecurrent turn ends; the harness then resumes you automatically with thesummary plus recent messages, and you continue the task.-- The IPython kernel persists through compaction — variables, imports, and+- The Python kernel persists through compaction — variables, imports, andhelpers you defined all remain available.- Compact at a natural boundary when context usage is high and substantialwork remains, instead of becoming terse or returning to the user early.diff --git a/packages/coding-agent/skills/compact/src/compact/__init__.py b/packages/coding-agent/skills/compact/src/compact/__init__.pyindex 685749b3ed..b84d643b6a 100644--- a/packages/coding-agent/skills/compact/src/compact/__init__.py+++ b/packages/coding-agent/skills/compact/src/compact/__init__.py@@ -2,7 +2,7 @@Compaction runs host-side (the same implementation as /compact); thesefunctions are thin typed wrappers over the generic host bridge-(`rlm.host_request`). They only work inside the Prime Agent IPython kernel.+(`rlm.host_request`). They only work inside the Prime Agent Python kernel."""from __future__ import annotationsdiff --git a/packages/coding-agent/skills/edit/SKILL.md b/packages/coding-agent/skills/edit/SKILL.mdindex bb7d1ee89c..febcdcb987 100644--- a/packages/coding-agent/skills/edit/SKILL.md+++ b/packages/coding-agent/skills/edit/SKILL.md@@ -1,6 +1,6 @@---name: edit-description: Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the IPython kernel instead of rewriting the whole file.+description: Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.---# Editdiff --git a/packages/coding-agent/skills/edit/src/edit/__init__.py b/packages/coding-agent/skills/edit/src/edit/__init__.pyindex e3e0e01465..b286048b1a 100644--- a/packages/coding-agent/skills/edit/src/edit/__init__.py+++ b/packages/coding-agent/skills/edit/src/edit/__init__.py@@ -50,11 +50,11 @@ _DIFF_DISPLAY_MIME = "application/vnd.prime-agent.diff+json"def _emit_diff(path: str, old_str: str, new_str: str, start_line: int) -> None:- """Stream a diff to the host via display_data; best-effort outside IPython."""+ """Stream a diff to the host as a display event; best-effort outside the kernel."""try:- from IPython.display import display+ from rlm import emit- display(+ emit({_DIFF_DISPLAY_MIME: {"path": path,@@ -63,8 +63,7 @@ def _emit_diff(path: str, old_str: str, new_str: str, start_line: int) -> None:"start_line": start_line,},"text/plain": f"Edited {path}",- },- raw=True,+ })except Exception:passdiff --git a/packages/coding-agent/skills/goal/SKILL.md b/packages/coding-agent/skills/goal/SKILL.mdindex 55b475bb9e..4f0650993c 100644--- a/packages/coding-agent/skills/goal/SKILL.md+++ b/packages/coding-agent/skills/goal/SKILL.md@@ -1,6 +1,6 @@---name: goal-description: Manage the persistent thread goal from IPython. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.+description: Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.---# Goal@@ -8,7 +8,7 @@ description: Manage the persistent thread goal from IPython. Use to read goal stThe thread goal is a persistent objective the harness keeps re-prompting you topursue across turns until it is complete. Goal state (status, token budget,usage accounting) lives in the host; this skill is the kernel-side interface to-it. Call it directly from IPython:+it. Call it directly from the Python REPL:```pythonawait goal.get()diff --git a/packages/coding-agent/skills/goal/src/goal/__init__.py b/packages/coding-agent/skills/goal/src/goal/__init__.pyindex 891e0bfbda..5bdd3730c1 100644--- a/packages/coding-agent/skills/goal/src/goal/__init__.py+++ b/packages/coding-agent/skills/goal/src/goal/__init__.py@@ -2,7 +2,7 @@All goal state lives in the TypeScript host; these functions are thin typedwrappers over the generic host bridge (`rlm.host_request`). They only work-inside the Prime Agent IPython kernel.+inside the Prime Agent Python kernel."""from __future__ import annotationsdiff --git a/packages/coding-agent/skills/linear/SKILL.md b/packages/coding-agent/skills/linear/SKILL.mdindex a5247546c3..9d81714e75 100644--- a/packages/coding-agent/skills/linear/SKILL.md+++ b/packages/coding-agent/skills/linear/SKILL.md@@ -5,7 +5,7 @@ description: Read and write Linear issues, projects, cycles, comments, and more# Linear-Talk to Linear through its official hosted MCP server from the IPython kernel.+Talk to Linear through its official hosted MCP server from the Python kernel.## Setupdiff --git a/packages/coding-agent/skills/notion/SKILL.md b/packages/coding-agent/skills/notion/SKILL.mdindex 2978376f28..cdc553cc30 100644--- a/packages/coding-agent/skills/notion/SKILL.md+++ b/packages/coding-agent/skills/notion/SKILL.md@@ -5,7 +5,7 @@ description: Search Notion and read/create/update pages and databases via Notion# Notion-Talk to Notion through its official hosted MCP server from the IPython kernel.+Talk to Notion through its official hosted MCP server from the Python kernel.## Setupdiff --git a/packages/coding-agent/skills/refine/SKILL.md b/packages/coding-agent/skills/refine/SKILL.mdindex 3d5c83f4e6..210bfa66f8 100644--- a/packages/coding-agent/skills/refine/SKILL.md+++ b/packages/coding-agent/skills/refine/SKILL.md@@ -1,6 +1,6 @@---name: refine-description: Trigger continual harness refinement from IPython. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.+description: Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.---# Refine@@ -9,7 +9,7 @@ Refinement analyzes the conversation trajectory and applies small, evidence-backupdates to the continual harness (prompts, memories, skills, subagent specs).The implementation lives in the host (the same one behind the user's `/refine`command); this skill is the kernel-side interface to it. Call it directly from-IPython:+the Python REPL:```pythonawait refine.status()diff --git a/packages/coding-agent/skills/refine/src/refine/__init__.py b/packages/coding-agent/skills/refine/src/refine/__init__.pyindex 5c50a37c54..85695e57b3 100644--- a/packages/coding-agent/skills/refine/src/refine/__init__.py+++ b/packages/coding-agent/skills/refine/src/refine/__init__.py@@ -2,7 +2,7 @@Refinement runs host-side (the same implementation as /refine); thesefunctions are thin typed wrappers over the generic host bridge-(`rlm.host_request`). They only work inside the Prime Agent IPython kernel.+(`rlm.host_request`). They only work inside the Prime Agent Python kernel."""from __future__ import annotationsdiff --git a/packages/coding-agent/skills/rlm-heartbeat/SKILL.md b/packages/coding-agent/skills/rlm-heartbeat/SKILL.mdindex 995f744c91..98b3c7cbdf 100644--- a/packages/coding-agent/skills/rlm-heartbeat/SKILL.md+++ b/packages/coding-agent/skills/rlm-heartbeat/SKILL.md@@ -1,6 +1,6 @@---name: rlm-heartbeat-description: Manage agent-owned RLM heartbeats from IPython. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.+description: Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.---# RLM Heartbeat@@ -9,7 +9,7 @@ RLM heartbeats are internal recurring prompts for the current agent session.They are separate from the user's visible `/heartbeat`: this skill cannot read,replace, pause, resume, or clear that user-level heartbeat.-Call directly from IPython:+Call directly from the Python REPL:```pythonawait rlm_heartbeat.create("check test progress", interval="5m", label="tests")diff --git a/packages/coding-agent/skills/rlm-heartbeat/src/rlm_heartbeat/__init__.py b/packages/coding-agent/skills/rlm-heartbeat/src/rlm_heartbeat/__init__.pyindex 1f57d5f7b3..36c1244f07 100644--- a/packages/coding-agent/skills/rlm-heartbeat/src/rlm_heartbeat/__init__.py+++ b/packages/coding-agent/skills/rlm-heartbeat/src/rlm_heartbeat/__init__.py@@ -2,7 +2,7 @@All heartbeat state lives in the TypeScript host; these functions are thintyped wrappers over the generic host bridge (`rlm.host_request`). They only-work inside the Prime Agent IPython kernel.+work inside the Prime Agent Python kernel."""from __future__ import annotationsdiff --git a/packages/coding-agent/skills/skill-creator/SKILL.md b/packages/coding-agent/skills/skill-creator/SKILL.mdindex 2bbb7ea964..1ab78edd21 100644--- a/packages/coding-agent/skills/skill-creator/SKILL.md+++ b/packages/coding-agent/skills/skill-creator/SKILL.md@@ -1,6 +1,6 @@---name: skill-creator-description: Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the IPython kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.+description: Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.---# Skill Creator@@ -10,7 +10,7 @@ A skill is a directory with a `SKILL.md` file (YAML frontmatter + markdown instr| Kind | What it is | When to use ||---|---|---|| markdown | `SKILL.md` plus optional scripts, references, and assets | Workflows, CLI recipes, domain knowledge, multi-step instructions |-| python | A markdown skill that also ships a Python package installed into the agent's persistent IPython kernel | Capabilities that are naturally one Python call: API wrappers, fetchers, converters, computations |+| python | A markdown skill that also ships a Python package installed into the agent's persistent Python kernel | Capabilities that are naturally one Python call: API wrappers, fetchers, converters, computations |Before writing a Python-backed skill, read [references/python-skills.md](references/python-skills.md) for the package contract.diff --git a/packages/coding-agent/skills/skill-creator/references/python-skills.md b/packages/coding-agent/skills/skill-creator/references/python-skills.mdindex 6d388ba2c3..fe0ce1b477 100644--- a/packages/coding-agent/skills/skill-creator/references/python-skills.md+++ b/packages/coding-agent/skills/skill-creator/references/python-skills.md@@ -1,6 +1,6 @@# Python-Backed Skills-A Python-backed skill is a regular markdown skill that also ships a Python package. Prime Agent installs the package editable into the kernel venv (`~/.prime/agent/kernel-venv` by default, `PRIME_AGENT_KERNEL_VENV` to override) and exposes it in the persistent IPython kernel, so the agent can call it directly instead of shelling out.+A Python-backed skill is a regular markdown skill that also ships a Python package. Prime Agent installs the package editable into the kernel venv (`~/.prime/agent/kernel-venv` by default, `PRIME_AGENT_KERNEL_VENV` to override) and exposes it in the persistent Python kernel, so the agent can call it directly instead of shelling out.## Detection Contractdiff --git a/packages/coding-agent/skills/websearch/SKILL.md b/packages/coding-agent/skills/websearch/SKILL.mdindex 1a47737786..e919f5e41b 100644--- a/packages/coding-agent/skills/websearch/SKILL.md+++ b/packages/coding-agent/skills/websearch/SKILL.md@@ -23,7 +23,7 @@ Optional overrides (environment variables):## Usage-Call the prepared `websearch` import directly in the IPython kernel:+Call the prepared `websearch` import directly in the Python kernel:```pythonprint(await websearch("latest Prime Agent release"))diff --git a/packages/coding-agent/src/cli/command-registry.ts b/packages/coding-agent/src/cli/command-registry.tsindex fef133355e..e1c37e126c 100644--- a/packages/coding-agent/src/cli/command-registry.ts+++ b/packages/coding-agent/src/cli/command-registry.ts@@ -312,7 +312,7 @@ export function formatTopLevelHelp(): string {const commands = COMMAND_SPECS.filter((spec) => spec.path.length === 1);const commandWidth = Math.max(...commands.map((spec) => spec.path[0]!.length));const options = TOP_LEVEL_OPTION_GROUPS.map((group) => formatOptionGroup(group.heading, group.options)).join("\n\n");- return `${APP_NAME} - AI coding assistant with an IPython tool+ return `${APP_NAME} - AI coding assistant with a Python REPL toolUsage:${APP_NAME} [options] [@files...] [message...]diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 2025bc9464..9b0f660219 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -404,7 +404,7 @@ export interface AgentSessionConfig {allowedToolNames?: string[];/*** Whether the built-in long-running goals feature is available: the bundled- * goal skill in the IPython kernel, its goal.* host handlers, and /goal.+ * goal skill in the Python kernel, its goal.* host handlers, and /goal.* Default: true.*/includeGoals?: boolean;@@ -2028,7 +2028,7 @@ export class AgentSession {}/**- * Goals are pursued through the IPython goal skill, so the only tool the+ * Goals are pursued through the kernel goal skill, so the only tool the* model needs is ipython. Force-activate it (including into a live* continuation context) so the model can always reach `goal.complete()`.*/@@ -2923,7 +2923,7 @@ export class AgentSession {}/**- * Handle a goal.* request from the IPython kernel host bridge (the bundled+ * Handle a goal.* request from the Python kernel host bridge (the bundled* goal skill). All goal state stays host-side; the kernel only sees the* serialized snake_case response.*/@@ -3856,7 +3856,7 @@ export class AgentSession {* Call this when completely done with the session.*//**- * Async teardown for graceful quit/switch: await the IPython kernel's dispose+ * Async teardown for graceful quit/switch: await the Python kernel's dispose* (which flushes a final namespace snapshot) before the synchronous dispose, so* the latest state reaches disk instead of racing process exit.*/@@ -7245,7 +7245,7 @@ export class AgentSession {: "";const content = ["<ipython_state>",- `Your IPython kernel persisted through compaction; its remaining variables, imports, and helpers are still available.${prunedDetail}${detail}`,+ `Your Python kernel persisted through compaction; its remaining variables, imports, and helpers are still available.${prunedDetail}${detail}`,"</ipython_state>",].join("\n");const message = {@@ -7272,11 +7272,11 @@ export class AgentSession {const lines = ["<ipython_state_restored>"];if (result.restored.length > 0) {lines.push(- `Your IPython kernel state was revived from your previous session. These names are available again: ${result.restored.join(", ")}.`,+ `Your Python kernel state was revived from your previous session. These names are available again: ${result.restored.join(", ")}.`,);} else {lines.push(- "Your previous IPython kernel state could not be revived; the kernel is starting fresh, so re-create any variables, imports, or loaded data you need.",+ "Your previous Python kernel state could not be revived; the kernel is starting fresh, so re-create any variables, imports, or loaded data you need.",);}if (result.failed.length > 0) {diff --git a/packages/coding-agent/src/core/compaction/compaction.ts b/packages/coding-agent/src/core/compaction/compaction.tsindex 5716c5e699..cdda5ed080 100644--- a/packages/coding-agent/src/core/compaction/compaction.ts+++ b/packages/coding-agent/src/core/compaction/compaction.ts@@ -448,7 +448,7 @@ Use this EXACT format:Keep each section concise. Preserve exact file paths, function names, and error messages.`;const KERNEL_PERSIST_SUMMARY_NOTE =- "Note: the IPython kernel keeps running after this summary — every Python variable, import, and helper you defined stays available. The cells that defined them won't appear above, so record in the summary any names worth remembering so you reuse them instead of redefining them.";+ "Note: the Python kernel keeps running after this summary — every Python variable, import, and helper you defined stays available. The cells that defined them won't appear above, so record in the summary any names worth remembering so you reuse them instead of redefining them.";const UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.diff --git a/packages/coding-agent/src/core/goals.ts b/packages/coding-agent/src/core/goals.tsindex dca8b391d8..339775de9f 100644--- a/packages/coding-agent/src/core/goals.ts+++ b/packages/coding-agent/src/core/goals.ts@@ -37,7 +37,7 @@ export type SerializedGoal = {updated_at?: number;};-/** Reply payload for goal.* host requests from the IPython kernel. */+/** Reply payload for goal.* host requests from the Python kernel. */export type GoalHostResponse = {goal: SerializedGoal | null;remaining_tokens: number | null;diff --git a/packages/coding-agent/src/core/kernel/boot-gate.ts b/packages/coding-agent/src/core/kernel/boot-gate.tsindex 3fe2211edd..f7e56ad4f0 100644--- a/packages/coding-agent/src/core/kernel/boot-gate.ts+++ b/packages/coding-agent/src/core/kernel/boot-gate.ts@@ -1,45 +1,29 @@import { cpus } from "node:os";import { Semaphore } from "../../utils/semaphore.js";-import { isForkServerEnabled } from "./fork-server.js";// Above core count because boots are IO-bound (cold imports), but capped so a-// fan-out can't thrash the FS past the port-resolve window.+// fan-out can't thrash the FS past the ready-handshake window.const DEFAULT_KERNEL_BOOT_CONCURRENCY = Math.min(16, Math.max(4, (cpus().length || 4) * 2));const MAX_KERNEL_BOOT_CONCURRENCY = 64;-// Fork-per-child is ~ms and bypasses the FS, so we can admit well past the-// direct-spawn cap. But fork only removes the *import* cost — every admitted-// kernel still starts a live ioloop + heartbeat thread + rlm bootstrap, and-// letting all N do that at once trips the ready timeout (measured: 256 collapses-// to ~28% boot at N=200; core*4 holds 100%). So the gate stays a real bound.-// Explicit env overrides may go higher than the auto default, but not unbounded —-// past this the live-kernel startup storm regresses boot rate.-const FORKSERVER_KERNEL_BOOT_CONCURRENCY_MAX = 128;-const FORKSERVER_KERNEL_BOOT_CONCURRENCY = Math.min(- FORKSERVER_KERNEL_BOOT_CONCURRENCY_MAX,- Math.max(32, (cpus().length || 4) * 4),-);export function resolveKernelBootConcurrency(): number {const raw = process.env.PRIME_AGENT_MAX_CONCURRENT_KERNEL_BOOTS;- const fallback = isForkServerEnabled() ? FORKSERVER_KERNEL_BOOT_CONCURRENCY : DEFAULT_KERNEL_BOOT_CONCURRENCY;if (raw === undefined || !/^\d+$/.test(raw)) {- return fallback;+ return DEFAULT_KERNEL_BOOT_CONCURRENCY;}const parsed = Number.parseInt(raw, 10);// A malformed or out-of-range value (incl. 0, e.g. "00") falls back to the// default rather than mis-bounding the gate or throwing at module load.if (parsed < 1) {- return fallback;+ return DEFAULT_KERNEL_BOOT_CONCURRENCY;}// An explicit override may exceed the auto default (that's its purpose), but is- // still clamped: the FS-contention cap on direct spawn, a looser backstop on fork.- const max = isForkServerEnabled() ? FORKSERVER_KERNEL_BOOT_CONCURRENCY_MAX : MAX_KERNEL_BOOT_CONCURRENCY;- return Math.min(max, parsed);+ // still clamped by the FS-contention cap.+ return Math.min(MAX_KERNEL_BOOT_CONCURRENCY, parsed);}-// Resolved lazily on first boot, not at module load, so the fork-server flag is-// honored whenever it is set before the first kernel starts — not just if it-// happened to be set at import time.+// Resolved lazily on first boot so an env override set before the first kernel+// starts is honored — not just one set at import time.let kernelBootSemaphore: Semaphore | undefined;export function withKernelBootPermit<T>(boot: () => Promise<T>, signal?: AbortSignal): Promise<T> {diff --git a/packages/coding-agent/src/core/kernel/bootstrap.ts b/packages/coding-agent/src/core/kernel/bootstrap.tsindex ac73b943eb..268411b59d 100644--- a/packages/coding-agent/src/core/kernel/bootstrap.ts+++ b/packages/coding-agent/src/core/kernel/bootstrap.ts@@ -11,9 +11,8 @@ import { fileURLToPath } from "node:url";import { getPackageDir } from "../../config.js";import type { PythonSkillRuntimeInfo } from "../skills.js";-const BOOTSTRAP_SCHEMA = 8;+const BOOTSTRAP_SCHEMA = 9;const PYTHON_VERSION = "3.11";-const IPYKERNEL_REQUIREMENT = "ipykernel";const RUNTIME_REQUIREMENT = "prime-agent-runtime";// Serializes the kernel's user namespace so it can be revived across session// resume. Internal-only; intentionally not surfaced to the model as an import.@@ -51,7 +50,7 @@ const REQUIRED_HARNESS_METHODS = ["delete_prompt_note","record_refinement",];-const RUNTIME_READY_CHECK = `import inspect; import rlm; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ${JSON.stringify(REQUIRED_HARNESS_METHODS)}; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert hasattr(rlm, 'run'); assert callable(rlm); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm); assert callable(rlm.host_request); assert callable(rlm.find_models); assert callable(rlm.rlm.find_models); assert hasattr(rlm, 'harness'); assert hasattr(rlm, 'get_harness_state'); assert hasattr(rlm.rlm, 'harness'); assert hasattr(rlm.rlm, 'get_harness_state'); assert all(callable(getattr(_harness, _method, None)) for _harness in (rlm.harness, rlm.rlm.harness) for _method in _harness_methods); assert 'reference' in HarnessEntry.__dataclass_fields__; assert 'scope' in HarnessEntry.__dataclass_fields__; assert 'reference' in inspect.signature(rlm.harness.create_skill).parameters; assert 'reference' in inspect.signature(rlm.harness.update_skill).parameters; assert 'global_' in inspect.signature(rlm.harness.create_memory).parameters; assert 'global_' in inspect.signature(rlm.get_harness_state).parameters; assert not hasattr(rlm, 'background'); assert not hasattr(rlm.rlm, 'background'); from rlm.bash import BashHandle, BashResult; assert callable(rlm.bash); assert all(callable(getattr(BashHandle, _m, None)) for _m in ('tail', 'output', 'poll', 'kill')); assert {'exit_code', 'output', 'duration'} <= set(BashResult.__dataclass_fields__)`;+const RUNTIME_READY_CHECK = `import inspect; import rlm; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ${JSON.stringify(REQUIRED_HARNESS_METHODS)}; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert hasattr(rlm, 'run'); assert callable(rlm); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm); assert callable(rlm.host_request); assert callable(rlm.find_models); assert callable(rlm.rlm.find_models); assert hasattr(rlm, 'harness'); assert hasattr(rlm, 'get_harness_state'); assert hasattr(rlm.rlm, 'harness'); assert hasattr(rlm.rlm, 'get_harness_state'); assert all(callable(getattr(_harness, _method, None)) for _harness in (rlm.harness, rlm.rlm.harness) for _method in _harness_methods); assert 'reference' in HarnessEntry.__dataclass_fields__; assert 'scope' in HarnessEntry.__dataclass_fields__; assert 'reference' in inspect.signature(rlm.harness.create_skill).parameters; assert 'reference' in inspect.signature(rlm.harness.update_skill).parameters; assert 'global_' in inspect.signature(rlm.harness.create_memory).parameters; assert 'global_' in inspect.signature(rlm.get_harness_state).parameters; assert not hasattr(rlm, 'background'); assert not hasattr(rlm.rlm, 'background'); from rlm.bash import BashHandle, BashResult; assert callable(rlm.bash); assert all(callable(getattr(BashHandle, _m, None)) for _m in ('tail', 'output', 'poll', 'kill')); assert {'exit_code', 'output', 'duration'} <= set(BashResult.__dataclass_fields__); import rlm.repl as _repl; assert callable(_repl.main); assert callable(_repl.emit); assert callable(_repl.host_request); assert callable(_repl.is_active); assert _repl.PROTOCOL_VERSION == 2; assert callable(rlm.emit); assert not hasattr(rlm, 'HOST_COMM_TARGET'); assert not hasattr(mcp, 'install_shutdown_hook')`;const BOOTSTRAP_VERSION_FILE = ".bootstrap-version";const BOOTSTRAP_LOCK_NAME = ".bootstrap.lock";const BOOTSTRAP_LOCK_RETRY_MS = 100;@@ -76,7 +75,6 @@ interface BootstrapPythonSkill {interface BootstrapVersion {schema: number;- ipykernel?: string;runtime?: string;snapshot?: string;extraUvArgs?: string[];@@ -365,7 +363,7 @@ async function resolveWritableKernelVenvDir(): Promise<string> {return fallback;} catch (fallbackError) {throw new Error(- `couldn't create kernel venv directory at ${primary} or ${fallback}; set PRIME_AGENT_KERNEL_PYTHON to a python with ipykernel installed. ${errorMessage(fallbackError)}`,+ `couldn't create kernel venv directory at ${primary} or ${fallback}; set PRIME_AGENT_KERNEL_PYTHON to a python with a current prime-agent-runtime installed. ${errorMessage(fallbackError)}`,);}}@@ -398,10 +396,6 @@ async function pythonImports(python: string, moduleName: string): Promise<boolea}}-async function hasIpykernel(python: string): Promise<boolean> {- return pythonImports(python, "ipykernel");-}-async function hasPrimeAgentRuntime(python: string): Promise<boolean> {try {await run(python, ["-c", RUNTIME_READY_CHECK], { stdio: "ignore" });@@ -586,7 +580,6 @@ async function readBootstrapVersion(venv: string): Promise<BootstrapVersion | nu}return {schema: parsed.schema,- ipykernel: typeof parsed.ipykernel === "string" ? parsed.ipykernel : undefined,runtime: typeof parsed.runtime === "string" ? parsed.runtime : undefined,snapshot: typeof parsed.snapshot === "string" ? parsed.snapshot : undefined,extraUvArgs,@@ -633,7 +626,6 @@ function bootstrapVersionCurrent(function bootstrapBaseVersionCurrent(version: BootstrapVersion | null, runtimeIdentity: string): boolean {return (version?.schema === BOOTSTRAP_SCHEMA &&- version.ipykernel === IPYKERNEL_REQUIREMENT &&version.runtime === runtimeIdentity &&version.snapshot === STATE_SNAPSHOT_REQUIREMENT &&extraUvArgsMatch(version.extraUvArgs, DEFAULT_RLM_EXTRA_UV_ARGS)@@ -647,7 +639,6 @@ async function writeBootstrapVersion(): Promise<void> {const version: BootstrapVersion = {schema: BOOTSTRAP_SCHEMA,- ipykernel: IPYKERNEL_REQUIREMENT,runtime: runtimeIdentity,snapshot: STATE_SNAPSHOT_REQUIREMENT,extraUvArgs: DEFAULT_RLM_EXTRA_UV_ARGS,@@ -737,7 +728,6 @@ async function bootstrapVenv("install","--python",python,- IPYKERNEL_REQUIREMENT,runtimeRequirement,STATE_SNAPSHOT_REQUIREMENT,...DEFAULT_RLM_EXTRA_UV_ARGS,@@ -825,7 +815,6 @@ async function syncPythonSkills(async function kernelBaseReady(python: string, venv: string, runtimeIdentity: string): Promise<boolean> {return (- (await hasIpykernel(python)) &&(await hasPrimeAgentRuntime(python)) &&bootstrapBaseVersionCurrent(await readBootstrapVersion(venv), runtimeIdentity));@@ -838,7 +827,6 @@ async function kernelReady(pythonSkills: readonly BootstrapPythonSkill[],): Promise<boolean> {return (- (await hasIpykernel(python)) &&(await hasPrimeAgentRuntime(python)) &&bootstrapVersionCurrent(await readBootstrapVersion(venv), runtimeIdentity, pythonSkills));@@ -847,8 +835,8 @@ async function kernelReady(function formatBootstrapFailure(error: unknown): Error {return new Error(`Failed to set up the Python kernel runtime. ${errorMessage(error)}\n` +- "First-time setup needs internet to install uv, Python, ipykernel, prime-agent-runtime, and default Python packages; once set up, prime-agent runs offline. " +- "Set PRIME_AGENT_KERNEL_PYTHON to a Python with ipykernel, a current prime-agent-runtime, and default Python packages installed to skip auto-bootstrap.",+ "First-time setup needs internet to install uv, Python, prime-agent-runtime, and default Python packages; once set up, prime-agent runs offline. " ++ "Set PRIME_AGENT_KERNEL_PYTHON to a Python with a current prime-agent-runtime and default Python packages installed to skip auto-bootstrap.",);}@@ -860,7 +848,6 @@ async function ensureKernelPythonUncached(if (override) {const python = path.resolve(expandHome(override));const missing: string[] = [];- if (!(await hasIpykernel(python))) missing.push("ipykernel");if (!(await hasPrimeAgentRuntime(python))) {missing.push("a current prime-agent-runtime with callable rlm.run, rlm.host_request, and explicit harness CRUD methods",diff --git a/packages/coding-agent/src/core/kernel/fork-server-script.ts b/packages/coding-agent/src/core/kernel/fork-server-script.tsdeleted file mode 100644index a6e286d0f9..0000000000--- a/packages/coding-agent/src/core/kernel/fork-server-script.ts+++ /dev/null@@ -1,243 +0,0 @@-// The Python "kernel forkserver": a long-lived template process that pays the-// ~1.2s IPython/ipykernel/rlm import cost once, then forks a ready-to-run kernel-// per request in ~ms. Children inherit the imported module objects via-// copy-on-write, bypassing the (slow, virtiofs-backed) per-file import path.-//-// Embedded as a string rather than shipped as a package asset so it can never be-// missing from a release layout (see the built-in-skills packaging gap). Run via-// `python -c <this> <control-socket-path> [<history-bound>]`.-//-// Protocol (newline-delimited JSON over the unix socket, forkserver is the client):-// -> { "id": <n>, "connectionPath": "<abs path>" } spawn request from Node-// -> { "id": <n>, "kill": <fork-id>, "signal": "TERM"|"KILL" } kill a forked child-// -> { "id": <n>, "alive": <fork-id> } liveness query for a child-// <- { "type": "ready" } once, after imports finish-// <- { "id": <n>, "pid": <pid> } fork succeeded-// <- { "id": <n>, "error": "<message>" } fork failed-// <- { "id": <n>, "outcome": "signaled"|"already-exited"|"unknown-pid" } kill reply-// <- { "id": <n>, "alive": true|false } alive reply-//-// Kill/alive are keyed by the never-reused fork request id, so a handle can only-// name the one child incarnation it forked (a recycled pid can't alias), and the-// forkserver signals only its own un-reaped children — POSIX-race-free.-export const FORK_SERVER_SCRIPT = String.raw`-import gc-import json-import os-import signal-import socket-import sys-import threading-import time--# fork id -> [pid, alive]; _pid_to_id holds un-reaped, un-evicted children only.-# Only the main thread mutates these (the SIGCHLD handler runs between its bytecodes).-_children = {}-_pid_to_id = {}-# FIFO history bound; kill/alive for an evicted id fail closed.-_history_bound = 4096---def _reap_children(*_args):- # Reap every exited child so disposed kernels never linger as zombies. Wired to- # SIGCHLD so reaping happens on child exit, not only when the next request wakes- # the accept loop. Safe under PEP 475: the interrupted socket read auto-retries.- try:- while True:- pid, _status = os.waitpid(-1, os.WNOHANG)- if pid == 0:- break- child_id = _pid_to_id.pop(pid, None)- if child_id is not None:- _children[child_id][1] = False- except ChildProcessError:- pass---def _watch_parent(original_ppid):- # A SIGKILLed owner can't close our socket while a forked child still holds the- # fd; poll ppid so the forkserver dies with its owner regardless.- while True:- if os.getppid() != original_ppid:- os._exit(1)- time.sleep(1.0)---def _import_template():- # Everything a kernel touches at import time. Paid once; shared COW by children.- import IPython # noqa: F401- import ipykernel # noqa: F401- import ipykernel.kernelapp # noqa: F401- import jupyter_client # noqa: F401- import nest_asyncio # noqa: F401- try:- import rlm # noqa: F401- except Exception:- # rlm may not import cleanly outside a live kernel namespace; the Node-side- # bootstrap cell wires it up per-child regardless. Preloading is a best-effort- # speedup, not a correctness requirement.- pass---def _run_child(connection_path, cwd, env):- # We are the forked child; become the ipykernel server on the given connection.- from ipykernel.kernelapp import IPKernelApp-- # Drop the inherited SIGCHLD reaper so it can't interfere with ipykernel's own- # child/signal handling.- signal.signal(signal.SIGCHLD, signal.SIG_DFL)-- # cwd/env are per-kernel and applied here (not at template import), so all- # kernels can share one warm template regardless of their working dir / env.- if env:- os.environ.update(env)- if cwd:- # Don't swallow a bad cwd: direct spawn fails fast on ENOENT, so match that- # (the OSError propagates, the child exits non-zero, Node falls back).- os.chdir(cwd)-- # Drop any singleton the template happened to build so the child owns a fresh- # instance (and, critically, a jupyter_client Session created in *this* pid;- # a Session inherited from the template silently drops messages via check_pid).- IPKernelApp.clear_instance()- # Watch our real parent (the forkserver): ipykernel distrusts a handle that- # differs from getppid(), and its pid-1 fallback breaks under subreapers.- app = IPKernelApp.instance(- connection_file=connection_path,- parent_handle=os.getppid(),- )- # initialize() binds the 5 ZMQ ports, writes the resolved ports back into- # connection.json, and starts the heartbeat thread + ioloop — all post-fork,- # so no thread/loop/socket is ever inherited across the fork boundary.- app.initialize([])- app.start()---def _serve(control_path):- sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- sock.connect(control_path)- control_fd = sock.fileno()-- # Block SIGCHLD before spawning the watcher so it inherits the blocked mask;- # otherwise the kernel could deliver SIGCHLD there while the main thread is masked.- signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGCHLD})-- # Compare against the original ppid (not ==1) so this holds under subreapers.- # Threads aren't inherited across fork, so children never carry this watcher.- threading.Thread(target=_watch_parent, args=(os.getppid(),), daemon=True).start()-- # Reap forked kernels as they exit, independent of the request loop.- signal.signal(signal.SIGCHLD, _reap_children)- # Unblock after handler install; the main thread's mask is now authoritative.- signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGCHLD})-- _import_template()- # Freeze the heap so the cyclic GC doesn't write to (and thus COW-copy) the- # shared module pages, keeping memory genuinely shared across children.- gc.freeze()-- f = sock.makefile("rwb", buffering=0)- f.write(json.dumps({"type": "ready"}).encode() + b"\n")- f.flush()-- while True:- # Belt-and-suspenders: the SIGCHLD handler is the primary reaper, but sweep- # again each turn in case a signal was missed (coalesced) while handling one.- _reap_children()-- line = f.readline()- if not line:- break- try:- req = json.loads(line)- except ValueError:- continue- req_id = req.get("id")-- kill_id = req.get("kill")- if kill_id is not None:- # Blocked across check+kill: an alive entry then means an un-reaped- # own child (zombie-pinned pid), so os.kill is race-free.- signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGCHLD})- try:- entry = _children.get(kill_id)- if entry is None:- outcome = "unknown-pid"- elif not entry[1]:- outcome = "already-exited"- else:- sig = signal.SIGKILL if req.get("signal") == "KILL" else signal.SIGTERM- try:- os.kill(entry[0], sig)- outcome = "signaled"- except ProcessLookupError:- outcome = "already-exited"- finally:- signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGCHLD})- f.write(json.dumps({"id": req_id, "outcome": outcome}).encode() + b"\n")- f.flush()- continue-- alive_id = req.get("alive")- if alive_id is not None:- entry = _children.get(alive_id)- f.write(json.dumps({"id": req_id, "alive": bool(entry and entry[1])}).encode() + b"\n")- f.flush()- continue-- connection_path = req.get("connectionPath")- cwd = req.get("cwd")- env = req.get("env")-- # Blocked across fork+bookkeeping: a fast-exiting child could otherwise- # be reaped before its registry entry exists, recording a stale pid as alive.- signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGCHLD})- try:- pid = os.fork()- except OSError as exc:- signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGCHLD})- f.write(json.dumps({"id": req_id, "error": str(exc)}).encode() + b"\n")- f.flush()- continue-- if pid == 0:- # The child inherits the blocked mask; the kernel needs SIGCHLD.- signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGCHLD})- # Shed every inherited fd tied to the control channel, then run.- try:- sock.close()- f.close()- except Exception:- pass- try:- os.close(control_fd)- except OSError:- pass- try:- _run_child(connection_path, cwd, env)- except BaseException as exc: # never return to the accept loop- sys.stderr.write("forked kernel failed: %r\n" % (exc,))- os._exit(1)- os._exit(0)-- # Parent: stay pristine (no loop/threads/ZMQ ever) so the next fork is clean.- _children[req_id] = [pid, True]- _pid_to_id[pid] = req_id- # FIFO-evict only exited entries: dropping a live child would make its- # liveness read false and its kill unroutable — the exact leak this- # forkserver exists to prevent. Live entries are bounded by real kernels.- if len(_children) > _history_bound:- for evicted_id in [i for i, e in _children.items() if not e[1]]:- if len(_children) <= _history_bound:- break- _children.pop(evicted_id)- signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGCHLD})- f.write(json.dumps({"id": req_id, "pid": pid}).encode() + b"\n")- f.flush()---if __name__ == "__main__":- if len(sys.argv) > 2:- _history_bound = int(sys.argv[2])- _serve(sys.argv[1])-`;diff --git a/packages/coding-agent/src/core/kernel/fork-server.ts b/packages/coding-agent/src/core/kernel/fork-server.tsdeleted file mode 100644index a6c1240d74..0000000000--- a/packages/coding-agent/src/core/kernel/fork-server.ts+++ /dev/null@@ -1,432 +0,0 @@-// Node-side client for the Python kernel forkserver (see fork-server-script.ts).-// One forkserver process per (python, cwd, env) profile, spawned lazily and kept-// alive for the agent process. Each KernelManager asks it to fork a kernel onto a-// connection file instead of paying a full `python -m ipykernel_launcher` cold boot.-//-// Everything degrades to direct spawn: if the forkserver is disabled, unavailable,-// or a spawn request fails/times out, callers catch ForkServerUnavailable and fall-// back to the existing path, so correctness never depends on fork.-import { type ChildProcess, spawn } from "node:child_process";-import { mkdtempSync, rmSync } from "node:fs";-import { createServer, type Server, type Socket } from "node:net";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { registerSessionResourceCleanup } from "@earendil-works/pi-ai";-import { recordOrphanProcessState } from "../orphan-process-journal.js";-import { FORK_SERVER_SCRIPT } from "./fork-server-script.js";--const READY_TIMEOUT_MS = 30_000;-const SPAWN_TIMEOUT_MS = 10_000;-const STDERR_TAIL_MAX = 4096;--// Vars the Python interpreter consumes at startup (before any user code runs), so-// they can't be honored post-fork via os.environ.update — the forked child inherits-// the template's already-initialized sys.path / site config. A kernel overriding any-// of these to a value the template didn't launch with must take the direct-spawn-// path. We treat the entire PYTHON* family as startup-affecting rather than-// enumerating individual vars: the set is large and version-dependent, and a false-// positive merely (safely) routes a kernel to direct spawn. Plus the non-PYTHON*-// startup vars that also steer interpreter/site resolution.-const INTERPRETER_STARTUP_ENV_EXACT = ["VIRTUAL_ENV", "CONDA_PREFIX", "__PYVENV_LAUNCHER__"];--function affectsInterpreterStartup(key: string): boolean {- return key.startsWith("PYTHON") || INTERPRETER_STARTUP_ENV_EXACT.includes(key);-}--export class ForkServerUnavailable extends Error {- /** True for a request timeout: the forkserver may just be stalled (e.g. mid-fork), not gone. */- readonly timedOut: boolean;-- constructor(message: string, opts?: { timedOut?: boolean }) {- super(message);- this.name = "ForkServerUnavailable";- this.timedOut = opts?.timedOut ?? false;- }-}--// On by default on Linux (fork-without-exec is unsafe on macOS);-// PRIME_AGENT_KERNEL_FORKSERVER=0 opts out.-export function isForkServerEnabled(): boolean {- if (process.platform !== "linux") return false;- return process.env.PRIME_AGENT_KERNEL_FORKSERVER !== "0";-}--// A forkserver template is defined solely by the interpreter — the imported-// module graph doesn't depend on cwd/env. Those are per-kernel and applied in the-// forked child, so every kernel for a given python shares ONE template.-interface ForkServerParams {- python: string;- // Registry-history bound override (argv[2] to the script); tests only.- historyBound?: number;-}--interface SpawnParams {- connectionPath: string;- cwd?: string;- // Mirrors process.env shape; undefined values are dropped when JSON-serialized- // to the child, matching how spawn() treats them on the direct path.- env?: Record<string, string | undefined>;-}--export type ForkedKernelKillSignal = "TERM" | "KILL";-export type ForkedKernelKillOutcome = "signaled" | "already-exited" | "unknown-pid";--/**- * Handle to a forkserver-forked kernel: signaling/liveness go through the- * forkserver by fork request id, never process.kill (see the protocol header- * in fork-server-script.ts). `pid` exists for journal writes only.- */-export interface ForkedKernelHandle {- readonly pid: number;- kill(signal: ForkedKernelKillSignal): Promise<ForkedKernelKillOutcome>;- isAlive(): Promise<boolean>;-}--interface ForkServerReply {- id: number;- pid?: number;- error?: string;- outcome?: string;- alive?: boolean;-}--type PendingRequest = {- resolve: (msg: ForkServerReply) => void;- reject: (err: Error) => void;- timer: ReturnType<typeof setTimeout>;-};--// Exported for protocol-level tests (which construct it directly, bypassing the-// isForkServerEnabled platform gate); production entry stays forkKernel().-export class ForkServer {- private readonly params: ForkServerParams;- // The env the template process was launched with, snapshotted at construction so- // it exactly matches what the template's interpreter imported with. The- // startup-env guard compares against THIS, not live process.env, so a later- // mutation of process.env can't make a stale template look compatible.- private readonly launchEnv: NodeJS.ProcessEnv;- private proc?: ChildProcess;- private server?: Server;- private conn?: Socket;- private socketDir?: string;- private readyPromise?: Promise<void>;- private failReady?: (err: Error) => void;- private buffer = "";- // Rolling tail of forkserver stderr. Forked children inherit this fd, so a- // child's import/startup traceback lands here; surfaced in error messages.- private stderrTail = "";- private nextId = 1;- private readonly pending = new Map<number, PendingRequest>();- // Request ids whose caller timed out; a late pid reply for one is an orphan to kill.- private readonly abandoned = new Set<number>();- private dead = false;-- constructor(params: ForkServerParams) {- this.params = params;- // Snapshot now and launch the template with this same object, so the guard's- // comparison uses exactly the env the interpreter imported with.- this.launchEnv = { ...process.env };- }-- get isDead(): boolean {- return this.dead;- }-- /**- * True if `env` overrides an interpreter-startup var to a value the template- * didn't launch with — such a kernel can't be forked (sys.path is baked in at- * import), so the caller must direct-spawn it.- */- needsStartupEnvNotInTemplate(env: SpawnParams["env"]): boolean {- if (!env) return false;- return Object.keys(env).some((k) => affectsInterpreterStartup(k) && env[k] !== this.launchEnv[k]);- }-- private async ensureReady(): Promise<void> {- if (this.dead) throw new ForkServerUnavailable("forkserver is dead");- if (!this.readyPromise) {- this.readyPromise = this.start().catch((err) => {- this.markDead();- throw err instanceof ForkServerUnavailable ? err : new ForkServerUnavailable(String(err));- });- }- return this.readyPromise;- }-- private start(): Promise<void> {- this.socketDir = mkdtempSync(join(tmpdir(), "prime-agent-forkserver-"));- const socketPath = join(this.socketDir, "control.sock");-- return new Promise<void>((resolve, reject) => {- const server = createServer();- this.server = server;-- let settled = false;- const readyTimer = setTimeout(() => {- if (settled) return;- settled = true;- reject(new ForkServerUnavailable(`forkserver did not become ready within ${READY_TIMEOUT_MS}ms`));- }, READY_TIMEOUT_MS);-- // Lets markDead() fail a still-pending start (interpreter crashed / socket- // closed before "ready") instead of waiting out the full ready timeout.- this.failReady = (err) => {- if (settled) return;- settled = true;- clearTimeout(readyTimer);- reject(err instanceof ForkServerUnavailable ? err : new ForkServerUnavailable(String(err)));- };-- server.on("connection", (socket) => {- this.conn = socket;- socket.setEncoding("utf8");- socket.on("data", (chunk: string) => this.onData(chunk));- socket.on("close", () => this.markDead());- socket.on("error", () => this.markDead());- });-- server.on("error", (err) => {- if (settled) return;- settled = true;- clearTimeout(readyTimer);- reject(new ForkServerUnavailable(`forkserver control socket failed: ${err.message}`));- });-- // Buffered until the "ready" line; flip the promise from there.- this.onReady = () => {- if (settled) return;- settled = true;- clearTimeout(readyTimer);- resolve();- };-- server.listen(socketPath, () => {- // The template only imports; its own cwd/env are irrelevant since each- // forked child applies the per-kernel cwd/env itself. Inherit the daemon's.- const args = ["-c", FORK_SERVER_SCRIPT, socketPath];- if (this.params.historyBound !== undefined) args.push(String(this.params.historyBound));- const proc = spawn(this.params.python, args, {- env: this.launchEnv,- stdio: ["ignore", "ignore", "pipe"],- });- this.proc = proc;- if (proc.pid !== undefined) recordOrphanProcessState(proc.pid, true);- proc.stderr?.on("data", (buf: Buffer) => {- this.stderrTail = `${this.stderrTail}${buf.toString()}`.slice(-STDERR_TAIL_MAX);- });- proc.on("error", () => this.markDead());- proc.on("exit", () => this.markDead());- });- });- }-- private onReady: () => void = () => {};-- private onData(chunk: string): void {- this.buffer += chunk;- for (let idx = this.buffer.indexOf("\n"); idx !== -1; idx = this.buffer.indexOf("\n")) {- const line = this.buffer.slice(0, idx);- this.buffer = this.buffer.slice(idx + 1);- if (!line.trim()) continue;- let msg: ForkServerReply & { type?: string };- try {- msg = JSON.parse(line);- } catch {- continue;- }- if (msg.type === "ready") {- this.onReady();- continue;- }- if (typeof msg.id !== "number") continue;- const p = this.pending.get(msg.id);- if (!p) {- // A fork the caller already abandoned (timed out): nobody owns it,- // so have the forkserver kill it.- if (this.abandoned.delete(msg.id) && typeof msg.pid === "number") {- void this.killChild(msg.id, "TERM").catch(() => {});- }- continue;- }- this.pending.delete(msg.id);- clearTimeout(p.timer);- p.resolve(msg);- }- }-- private request(payload: Record<string, unknown>, opts?: { abandonOnTimeout?: boolean }): Promise<ForkServerReply> {- if (this.dead || !this.conn) {- return Promise.reject(new ForkServerUnavailable("forkserver connection unavailable"));- }- const id = this.nextId++;- return new Promise<ForkServerReply>((resolve, reject) => {- const timer = setTimeout(() => {- this.pending.delete(id);- // A spawn may still land after we give up; remember the id so its late- // pid reply gets the orphan killed instead of leaked.- if (opts?.abandonOnTimeout) this.abandoned.add(id);- reject(- new ForkServerUnavailable(`forkserver request timed out after ${SPAWN_TIMEOUT_MS}ms`, {- timedOut: true,- }),- );- }, SPAWN_TIMEOUT_MS);- this.pending.set(id, { resolve, reject, timer });- this.conn?.write(`${JSON.stringify({ id, ...payload })}\n`);- });- }-- async spawnKernel(spawn: SpawnParams): Promise<ForkedKernelHandle> {- await this.ensureReady();- const msg = await this.request(- { connectionPath: spawn.connectionPath, cwd: spawn.cwd, env: spawn.env },- { abandonOnTimeout: true },- );- if (typeof msg.pid !== "number") {- throw new ForkServerUnavailable(this.withStderr(msg.error ?? "forkserver fork failed"));- }- const pid = msg.pid;- const forkId = msg.id;- return {- pid,- kill: (signal) => this.killChild(forkId, signal),- isAlive: () => this.isChildAlive(forkId),- };- }-- async killChild(forkId: number, signal: ForkedKernelKillSignal): Promise<ForkedKernelKillOutcome> {- const msg = await this.request({ kill: forkId, signal });- const outcome = msg.outcome;- if (outcome === "signaled" || outcome === "already-exited" || outcome === "unknown-pid") {- return outcome;- }- throw new ForkServerUnavailable(`forkserver kill reply malformed: ${JSON.stringify(msg)}`);- }-- async isChildAlive(forkId: number): Promise<boolean> {- const msg = await this.request({ alive: forkId });- return msg.alive === true;- }-- private withStderr(message: string): string {- const tail = this.stderrTail.trim();- return tail ? `${message}\nforkserver stderr:\n${tail}` : message;- }-- /** Reject any in-flight ensureReady/spawnKernel callers so none wait out a timeout. */- private rejectPending(reason: string): void {- this.failReady?.(new ForkServerUnavailable(reason));- for (const p of this.pending.values()) {- clearTimeout(p.timer);- p.reject(new ForkServerUnavailable(reason));- }- this.pending.clear();- }-- private markDead(): void {- this.dispose(this.withStderr("forkserver died"));- }-- dispose(reason = "forkserver disposed"): void {- if (this.dead) return;- // Flip `dead` at entry so the close/exit events our own teardown triggers- // don't re-enter. Pending callers are rejected directly here (not deferred to- // those events), so this early flag flip can't strand them on a timeout.- this.dead = true;- this.rejectPending(reason);- // Best-effort teardown: each resource may already be gone.- try {- this.conn?.destroy();- } catch {- // Already destroyed.- }- try {- this.server?.close();- } catch {- // Already closed.- }- const proc = this.proc;- if (proc) {- // Inactive only when the pid is soundly ours at write time (handle saw the- // exit, or handle-based kill delivered); otherwise leave the record active.- const observedExit = proc.exitCode !== null || proc.signalCode !== null;- let delivered = false;- try {- delivered = proc.kill("SIGTERM");- } catch {- // Already exited.- }- if (proc.pid !== undefined && (observedExit || delivered)) recordOrphanProcessState(proc.pid, false);- }- if (this.socketDir) {- try {- rmSync(this.socketDir, { recursive: true, force: true });- } catch {- // Leave the socket dir for OS tmp cleanup.- }- this.socketDir = undefined;- }- }-}--// Keyed by interpreter only: cwd/env are per-kernel (applied in the child), so all-// kernels for a given python share ONE warm template.-const servers = new Map<string, ForkServer>();-let cleanupRegistered = false;--function keyFor(params: ForkServerParams): string {- return params.python;-}--function registerForkServerCleanupOnce(): void {- if (cleanupRegistered) return;- cleanupRegistered = true;- // A forkserver is process-lived and shared across sessions, so per-session- // cleanup must not yank the warm template from other live sessions — only a full- // process shutdown (no sessionId) disposes it here.- registerSessionResourceCleanup((sessionId) => {- if (!sessionId) disposeAllForkServers();- });- // cleanupSessionResources(undefined) is never called on exit, so also tear the- // forkserver down directly on process teardown or it leaks as an orphan.- process.once("exit", disposeAllForkServers);- for (const signal of ["SIGINT", "SIGTERM", "beforeExit"] as const) {- process.once(signal, () => disposeAllForkServers());- }-}--/**- * Fork a kernel onto `spawn.connectionPath` from the shared template for this- * interpreter, applying `spawn.cwd`/`spawn.env` in the forked child. Throws- * ForkServerUnavailable if forking is disabled or fails — callers fall back to- * direct spawn. Returns a handle whose kill/liveness go through the forkserver.- */-export async function forkKernel(python: string, spawn: SpawnParams): Promise<ForkedKernelHandle> {- if (!isForkServerEnabled()) throw new ForkServerUnavailable("forkserver disabled");- registerForkServerCleanupOnce();- const key = keyFor({ python });- let server = servers.get(key);- if (!server || server.isDead) {- server = new ForkServer({ python });- servers.set(key, server);- }- // Compare against the template's own launch env (not live process.env): a kernel- // overriding an interpreter-startup var to a value the template didn't import- // with can't be forked — defer to direct spawn rather than boot with wrong sys.path.- if (server.needsStartupEnvNotInTemplate(spawn.env)) {- throw new ForkServerUnavailable("kernel overrides interpreter-startup env; using direct spawn");- }- try {- return await server.spawnKernel(spawn);- } catch (err) {- // Only evict if the map still points at this dead instance: a concurrent- // caller may have already replaced it with a fresh live server under this key.- if (server.isDead && servers.get(key) === server) servers.delete(key);- throw err instanceof ForkServerUnavailable ? err : new ForkServerUnavailable(String(err));- }-}--export function disposeAllForkServers(): void {- for (const server of servers.values()) server.dispose();- servers.clear();-}diff --git a/packages/coding-agent/src/core/kernel/index.ts b/packages/coding-agent/src/core/kernel/index.tsindex 3bf9254b21..bf27e24777 100644--- a/packages/coding-agent/src/core/kernel/index.ts+++ b/packages/coding-agent/src/core/kernel/index.ts@@ -1,1857 +1,2 @@-import { type ChildProcess, spawn } from "node:child_process";-import { createHmac, randomBytes } from "node:crypto";-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { setTimeout as sleep } from "node:timers/promises";-import { registerSessionResourceCleanup } from "@earendil-works/pi-ai";-import { v4 as uuid } from "uuid";-import { Dealer, Subscriber } from "zeromq";-import { reapKernelOrphanProcesses, recordOrphanProcessState } from "../orphan-process-journal.js";-import { ensureKernelPython, type KernelBootstrapProgressHandler, type KernelPythonSkill } from "./bootstrap.js";-import { type ForkedKernelHandle, ForkServerUnavailable, forkKernel, isForkServerEnabled } from "./fork-server.js";-import {- buildListNamesCode,- buildRestoreCode,- buildSnapshotCode,- DEFAULT_SNAPSHOT_MAX_BYTES,- DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES,- parseListNamesResult,- parseRestoreResult,- parseSnapshotResult,- type RestoreResult,- type SnapshotResult,-} from "./state-snapshot.js";--const DELIM = Buffer.from("<IDS|MSG>");-const PROTOCOL_VERSION = "5.3";-// Generous backstop for a kernel that is alive but wedged: crashes are detected-// within one 25ms poll via the exit handler, warm boots return in under a second,-// and a cold first boot after a venv (re)provision may legitimately need tens of-// seconds of imports before it binds ports and answers the ready probe.-const PORTS_RESOLVE_TIMEOUT_MS = 30_000;-const READY_TIMEOUT_MS = 30_000;-// Loopback PUB/SUB subscription propagation is usually sub-ms, but keep a small guard before first execute.-const IOPUB_SUBSCRIBE_DELAY_MS = 50;-const DEFAULT_MAX_OUTPUT_CHARS = 65536;-const HOST_REQUEST_DISPOSE_TIMEOUT_MS = 5000;-const KERNEL_SHUTDOWN_TIMEOUT_MS = 5000;-const DEFAULT_SNAPSHOT_DEBOUNCE_MS = 1500;-// How often to poll a forked kernel's pid for unexpected death.-const FORKED_LIVENESS_POLL_MS = 1000;-// Snapshot/restore cells can be large to (de)serialize; give them room beyond the user cap.-const SNAPSHOT_MAX_OUTPUT_CHARS = 1_000_000;-// Cap how long a graceful dispose waits on the final snapshot; the debounced-// on-disk copy is the fallback if this is exceeded.-const SNAPSHOT_DISPOSE_TIMEOUT_MS = 5000;-const SNAPSHOT_EXECUTION_TIMEOUT_MS = 5000;-const KERNEL_ABORT_GRACE_MS = 1000;-const KERNEL_BUSY_REUSE_WAIT_MS = 5000;-const KERNEL_BUSY_INTERRUPT_INTERVAL_MS = 500;-const MAX_LATE_SENT_AGENT_MESSAGE_HANDLERS = 256;-const KERNEL_BUSY_AFTER_INTERRUPT_MESSAGE =- "IPython kernel is still running the previously interrupted cell. Wait and try again, or kill the IPython kernel to start fresh.";--export class KernelBusyAfterInterruptError extends Error {- constructor() {- super(KERNEL_BUSY_AFTER_INTERRUPT_MESSAGE);- this.name = "KernelBusyAfterInterruptError";- }-}--/** Comm target the kernel-side `rlm.host_request` shim opens for typed host requests. */-export const HOST_COMM_TARGET = "host.request";--/**- * Handles one typed request from Python code running in the kernel.- * The returned record is sent back verbatim as the comm reply payload.- *- * This legacy unary compatibility alias remains the dispatcher and registration- * contract while context-aware handlers are staged separately below.- */-export type HostRequestHandler = (payload: Record<string, unknown>) => Promise<Record<string, unknown>>;--/**- * Per-call authority supplied by the host-request dispatcher.- * `requestId` is an opaque host-minted correlation token and `isCurrent()`- * lets an implementation reject work after its authority is revoked.- */-export interface HostRequestContext {- readonly requestId: string;- readonly generation: number;- readonly signal: AbortSignal;- isCurrent(): boolean;-}--const hostRequestHandlerBrand = Symbol("hostRequestHandler");--/** A context-aware implementation that must receive dispatcher authority. */-export type HostRequestHandlerImplementation = (- payload: Record<string, unknown>,- context: HostRequestContext,-) => Promise<Record<string, unknown>>;--/** A factory-minted, context-aware host-request handler capability. */-type HostRequestHandlerCapability = HostRequestHandlerImplementation & { readonly [hostRequestHandlerBrand]: true };--/** Runtime provenance cannot be recreated by copying the nominal symbol property. */-const factoryCreatedHostRequestHandlers = new WeakSet<object>();--function assertGenuineHostRequestContext(context: unknown): asserts context is HostRequestContext {- if (- typeof context !== "object" ||- context === null ||- typeof (context as HostRequestContext).requestId !== "string" ||- !(context as HostRequestContext).requestId ||- !Number.isSafeInteger((context as HostRequestContext).generation) ||- typeof (context as HostRequestContext).isCurrent !== "function" ||- typeof (context as HostRequestContext).signal !== "object" ||- (context as HostRequestContext).signal === null ||- typeof (context as HostRequestContext).signal.aborted !== "boolean" ||- typeof (context as HostRequestContext).signal.addEventListener !== "function"- ) {- throw new Error("host request context is invalid");- }-}--/**- * Creates a branded wrapper rather than mutating its implementation. Both its- * generic shape and runtime arity reject unary callbacks before they can run.- */-export function createHostRequestHandler<T extends HostRequestHandlerImplementation>(- implementation: T,- ..._unaryRejection: Parameters<T> extends [unknown, unknown, ...unknown[]]- ? []- : ["host request handlers must accept payload and context"]-): HostRequestHandlerCapability {- if (implementation.length < 2) throw new Error("host request handlers must accept payload and context");- const handler = async (payload: Record<string, unknown>, context: HostRequestContext) => {- assertGenuineHostRequestContext(context);- return implementation(payload, context);- };- factoryCreatedHostRequestHandlers.add(handler);- return Object.defineProperty(handler, hostRequestHandlerBrand, { value: true }) as HostRequestHandlerCapability;-}--/** Reject copied-symbol and raw-function forgeries before they observe authenticated payloads. */-export function assertHostRequestHandler(value: unknown): asserts value is HostRequestHandlerCapability {- if (- typeof value !== "function" ||- (value as Partial<HostRequestHandlerCapability>)[hostRequestHandlerBrand] !== true ||- !factoryCreatedHostRequestHandlers.has(value)- ) {- throw new Error("host request handler is not a dispatcher-created capability");- }-}--/** Host request handlers keyed by request type (e.g. "rlm.run", "goal.complete"). */-export type HostRequestHandlers = Record<string, HostRequestHandler>;--/** Where and how to persist the kernel's user namespace so it survives resume. */-export interface KernelSnapshotConfig {- /** Absolute path for the dill payload. */- path: string;- /** Absolute path for the JSON manifest written alongside the payload. */- manifestPath: string;- /** Maximum aggregate snapshot size. Default 256 MiB. */- maxBytes?: number;- /** Maximum serialized size of one variable. Default 16 MiB. */- maxVariableBytes?: number;- /** Debounce window for the auto-snapshot after a successful execution. Default 1500 ms. */- debounceMs?: number;-}--export interface KernelManagerOptions {- /** Python interpreter that has `ipykernel` available. Defaults to the auto-bootstrapped kernel. */- python?: string;- cwd?: string;- env?: Record<string, string>;- sessionId?: string;- hostHandlers?: HostRequestHandlers;- pythonSkills?: readonly KernelPythonSkill[];- /** Persist/revive the user namespace across kernel restarts and session resume. */- snapshot?: KernelSnapshotConfig;- /** Default: "prime-agent". */- username?: string;-}--export interface KernelStartOptions {- onBootstrapProgress?: KernelBootstrapProgressHandler;- signal?: AbortSignal;-}--export interface ExecuteOptions {- /** Aborting interrupts the kernel via the control channel. */- signal?: AbortSignal;- onStream?: (chunk: string, name: "stdout" | "stderr") => void;- onLateSentAgentMessage?: (message: KernelSentAgentMessage) => void;- /** Cap stdout / stderr / result at this many characters. Default 65536. */- maxOutputChars?: number;- /** Synthetic host cell (snapshot/restore/list); excluded from lastCellCode attribution. */- internal?: boolean;-}--/** MIME tag the `edit` skill emits diff payloads under, via `display_data`. */-export const DIFF_DISPLAY_MIME = "application/vnd.prime-agent.diff+json";--/** MIME tag the `attach-image` skill emits media payloads under, via `display_data`. */-export const ATTACHMENT_DISPLAY_MIME = "application/vnd.prime-agent.attachment+json";--/** MIME tag the `agent-message` skill emits after sending a message. */-export const AGENT_MESSAGE_DISPLAY_MIME = "application/vnd.prime-agent.agent-message+json";--/**- * Hard ceiling on a single attachment's base64 payload, a defensive guard- * against a runaway direct `display_data` emit. The `attach-image` skill caps- * its own images well under this (see `_MAX_IMAGE_BYTES`), so a skill-produced- * attachment is never dropped here — only a non-skill emit can hit this.- */-const MAX_ATTACHMENT_DATA_CHARS = 10_000_000;--/** One file edit, captured from a {@link DIFF_DISPLAY_MIME} display payload. */-export interface KernelDiffDisplay {- path: string;- oldStr: string;- newStr: string;- /** 1-based line where `oldStr` begins in the file, for absolute line numbers. */- startLine?: number;-}--/** One media attachment, captured from an {@link ATTACHMENT_DISPLAY_MIME} display payload. */-export interface KernelAttachment {- mimeType: string;- /** base64-encoded bytes. */- data: string;- /** Source path, surfaced to the TUI renderer. */- path?: string;-}--export interface KernelSentAgentMessage {- id: string;- message: string;- deliveryStatus: "delivered" | "queued";- receiverRole?: "parent" | "sibling" | "child";- target: {- activeSessionId: string;- sessionId: string;- sessionName?: string;- };-}--export interface ExecuteResult {- stdout: string;- stderr: string;- /** Last `execute_result` payload (text/plain), if the cell produced one. */- result?: string;- /** Diffs emitted via display_data, in order. */- diffs?: KernelDiffDisplay[];- /** Media attachments emitted via display_data, in order. */- attachments?: KernelAttachment[];- /** Agent messages sent from this cell, in order. */- sentAgentMessages?: KernelSentAgentMessage[];- status: "ok" | "error" | "aborted";- error?: { ename: string; evalue: string; traceback: string[] };- durationMs: number;-}--/** Parse a {@link DIFF_DISPLAY_MIME} payload, tolerating malformed input. */-function parseDiffDisplay(payload: unknown): KernelDiffDisplay | undefined {- if (!isRecord(payload)) {- return undefined;- }- const { path, old_str: oldStr, new_str: newStr, start_line: startLine } = payload;- if (typeof path !== "string" || typeof oldStr !== "string" || typeof newStr !== "string") {- return undefined;- }- return { path, oldStr, newStr, startLine: typeof startLine === "number" ? startLine : undefined };-}--/**- * Parse an {@link ATTACHMENT_DISPLAY_MIME} payload. Malformed payloads are- * tolerantly ignored (`undefined`); a well-formed payload exceeding- * {@link MAX_ATTACHMENT_DATA_CHARS} is reported as `"oversized"` so the caller- * can fail the cell loudly rather than silently dropping the image.- */-function parseAttachmentDisplay(payload: unknown): KernelAttachment | "oversized" | undefined {- if (!isRecord(payload)) {- return undefined;- }- const { mime_type: mimeType, data, path } = payload;- if (typeof mimeType !== "string" || typeof data !== "string") {- return undefined;- }- if (data.length > MAX_ATTACHMENT_DATA_CHARS) {- return "oversized";- }- return { mimeType, data, path: typeof path === "string" ? path : undefined };-}--function parseSentAgentMessage(payload: unknown): KernelSentAgentMessage | undefined {- if (!isRecord(payload) || !isRecord(payload.target)) {- return undefined;- }- const { id, message, deliveryStatus, receiverRole, target } = payload;- const { activeSessionId, sessionId, sessionName } = target;- if (- typeof id !== "string" ||- typeof message !== "string" ||- (deliveryStatus !== "delivered" && deliveryStatus !== "queued") ||- typeof activeSessionId !== "string" ||- typeof sessionId !== "string"- ) {- return undefined;- }- return {- id,- message,- deliveryStatus,- ...(receiverRole === "parent" || receiverRole === "sibling" || receiverRole === "child" ? { receiverRole } : {}),- target: {- activeSessionId,- sessionId,- ...(typeof sessionName === "string" ? { sessionName } : {}),- },- };-}--function createKernelStartupAbortError(): Error {- return new Error("Kernel startup aborted");-}--function raceStartupWithAbort<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {- if (!signal) {- return promise;- }- if (signal.aborted) {- return Promise.reject(createKernelStartupAbortError());- }- return new Promise<T>((resolve, reject) => {- let settled = false;- const cleanup = () => signal.removeEventListener("abort", abort);- const abort = () => {- if (settled) {- return;- }- settled = true;- cleanup();- reject(createKernelStartupAbortError());- };- signal.addEventListener("abort", abort, { once: true });- promise.then(- (value) => {- if (settled) {- return;- }- settled = true;- cleanup();- resolve(value);- },- (error: unknown) => {- if (settled) {- return;- }- settled = true;- cleanup();- reject(error);- },- );- });-}--interface ConnectionInfo {- ip: string;- transport: "tcp";- shell_port: number;- iopub_port: number;- stdin_port: number;- control_port: number;- hb_port: number;- signature_scheme: "hmac-sha256";- key: string;- kernel_name: string;-}--interface JupyterMessage {- header: {- msg_id: string;- session: string;- username: string;- date: string;- msg_type: string;- version: string;- };- parent_header: Record<string, unknown>;- metadata: Record<string, unknown>;- content: Record<string, unknown>;-}--interface ActiveExecution {- requestMsgId: string;- /** Source of the cell currently executing; surfaced to rlm.run spawns. */- code: string;- started: number;- maxChars: number;- opts: ExecuteOptions;- stdout: string;- stderr: string;- stdoutTruncated: boolean;- stderrTruncated: boolean;- result?: string;- diffs: KernelDiffDisplay[];- attachments: KernelAttachment[];- sentAgentMessages: KernelSentAgentMessage[];- error?: ExecuteResult["error"];- status: ExecuteResult["status"];- settled: boolean;- resolve: (result: ExecuteResult) => void;- reject: (error: Error) => void;-}--interface Deferred<T> {- promise: Promise<T>;- resolve: (value: T) => void;- reject: (error: Error) => void;-}--function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === "object" && value !== null && !Array.isArray(value);-}--function errorMessage(error: unknown): string {- return error instanceof Error ? error.message : String(error);-}--function createDeferred<T>(): Deferred<T> {- let resolve!: (value: T) => void;- let reject!: (error: Error) => void;- const promise = new Promise<T>((promiseResolve, promiseReject) => {- resolve = promiseResolve;- reject = promiseReject;- });- return { promise, resolve, reject };-}--function buildMessage(- msgType: string,- content: Record<string, unknown>,- session: string,- username: string,-): JupyterMessage {- return {- header: {- msg_id: uuid(),- session,- username,- date: new Date().toISOString(),- msg_type: msgType,- version: PROTOCOL_VERSION,- },- parent_header: {},- metadata: {},- content,- };-}--function sign(parts: Buffer[], key: string): Buffer {- const hmac = createHmac("sha256", key);- for (const p of parts) hmac.update(p);- return Buffer.from(hmac.digest("hex"));-}--function encode(msg: JupyterMessage, key: string): Buffer[] {- const parts = [- Buffer.from(JSON.stringify(msg.header)),- Buffer.from(JSON.stringify(msg.parent_header)),- Buffer.from(JSON.stringify(msg.metadata)),- Buffer.from(JSON.stringify(msg.content)),- ];- return [DELIM, sign(parts, key), ...parts];-}--function decode(frames: Buffer[]): JupyterMessage | null {- let i = 0;- while (i < frames.length && !frames[i].equals(DELIM)) i++;- if (i + 5 >= frames.length) return null;- try {- return {- header: JSON.parse(frames[i + 2].toString()),- parent_header: JSON.parse(frames[i + 3].toString()),- metadata: JSON.parse(frames[i + 4].toString()),- content: JSON.parse(frames[i + 5].toString()),- };- } catch {- return null;- }-}--const CONNECTION_PORT_KEYS = ["shell_port", "iopub_port", "stdin_port", "control_port", "hb_port"] as const;--function hasResolvedPorts(info: ConnectionInfo): boolean {- return CONNECTION_PORT_KEYS.every((key) => Number.isInteger(info[key]) && info[key] > 0);-}--function parseConnectionInfo(value: unknown): ConnectionInfo | null {- if (!isRecord(value)) return null;- if (value.ip !== "127.0.0.1") return null;- if (value.transport !== "tcp") return null;- if (value.signature_scheme !== "hmac-sha256") return null;- if (typeof value.key !== "string") return null;- const shellPort = value.shell_port;- const iopubPort = value.iopub_port;- const stdinPort = value.stdin_port;- const controlPort = value.control_port;- const hbPort = value.hb_port;- if (typeof shellPort !== "number" || !Number.isInteger(shellPort)) return null;- if (typeof iopubPort !== "number" || !Number.isInteger(iopubPort)) return null;- if (typeof stdinPort !== "number" || !Number.isInteger(stdinPort)) return null;- if (typeof controlPort !== "number" || !Number.isInteger(controlPort)) return null;- if (typeof hbPort !== "number" || !Number.isInteger(hbPort)) return null;- const kernelName = typeof value.kernel_name === "string" ? value.kernel_name : "python3";- return {- ip: value.ip,- transport: value.transport,- shell_port: shellPort,- iopub_port: iopubPort,- stdin_port: stdinPort,- control_port: controlPort,- hb_port: hbPort,- signature_scheme: value.signature_scheme,- key: value.key,- kernel_name: kernelName,- };-}--function readConnectionInfo(path: string): ConnectionInfo | null {- try {- return parseConnectionInfo(JSON.parse(readFileSync(path, "utf8")));- } catch {- return null;- }-}--function makeConnection(): { info: ConnectionInfo; path: string; tempDir: string } {- const info: ConnectionInfo = {- ip: "127.0.0.1",- transport: "tcp",- shell_port: 0,- iopub_port: 0,- stdin_port: 0,- control_port: 0,- hb_port: 0,- signature_scheme: "hmac-sha256",- key: randomBytes(16).toString("hex"),- kernel_name: "python3",- };- const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-kernel-"));- const path = join(tempDir, "connection.json");- writeFileSync(path, JSON.stringify(info, null, 2), { mode: 0o600 });- return { info, path, tempDir };-}--const liveKernels = new Set<KernelManager>();-let signalHandlersInstalled = false;--registerSessionResourceCleanup((sessionId) => {- for (const k of liveKernels) {- if (!sessionId || k.ownerSessionId === sessionId) {- void k.dispose();- }- }-});--function installSignalHandlersOnce(): void {- if (signalHandlersInstalled) return;- signalHandlersInstalled = true;-- const asyncShutdown = async (): Promise<void> => {- // These paths can await, so flush the namespace snapshot before tearing down.- await Promise.allSettled([...liveKernels].map((k) => k.shutdown({ snapshot: true })));- };-- // `beforeExit` and signal handlers can await async cleanup. `exit`- // can only do sync work (Node won't run pending microtasks past it),- // so it falls back to `disposeSync()` which kills the child synchronously.- process.on("beforeExit", () => {- void asyncShutdown();- });- process.on("SIGINT", () => {- void asyncShutdown().finally(() => process.exit(130));- });- process.on("SIGTERM", () => {- void asyncShutdown().finally(() => process.exit(143));- });- process.on("exit", () => {- for (const k of liveKernels) k.disposeSync();- });-}--export class KernelManager {- private readonly options: Pick<- KernelManagerOptions,- "python" | "cwd" | "env" | "sessionId" | "hostHandlers" | "pythonSkills" | "snapshot"- > &- Required<Pick<KernelManagerOptions, "username">>;- private readonly session = uuid();- private readonly commTargets = new Map<string, string>();- private readonly handledHostRequestCommIds = new Set<string>();- private kernel?: ChildProcess;- // Set instead of `kernel` for forkserver-forked kernels (not our child):- // signaling/liveness go through the forkserver, never process.kill.- private forkedKernel?: ForkedKernelHandle;- /** Polls a forked kernel for death (no "exit" event on a non-child). */- private forkedLivenessTimer?: ReturnType<typeof globalThis.setInterval>;- private forkedLivenessProbeInFlight = false;- private shell?: Dealer;- private iopub?: Subscriber;- private control?: Dealer;- private iopubPumpPromise?: Promise<void>;- private controlPumpPromise?: Promise<void>;- private readonly pendingControlReplies = new Map<string, (message: JupyterMessage) => void>();- private connection?: ConnectionInfo;- private tempDir?: string;- private kernelStderr = "";- /** Serializes execute() calls — Jupyter shell channel is request/reply. */- private executionQueue: Promise<unknown> = Promise.resolve();- private activeExecution?: ActiveExecution;- private readonly activeExecutionIdleWaiters = new Set<() => void>();- private readonly lateSentAgentMessageHandlers = new Map<string, (message: KernelSentAgentMessage) => void>();- // Source of the most recently started cell, retained after it finishes so- // rlm.run spawns from detached asyncio tasks (cell already idle) can still- // attribute their spawning program.- private lastCellCode?: string;- private readonly inFlightHostRequests = new Set<Promise<void>>();- private state: "idle" | "starting" | "running" | "shutdown" = "idle";- /** Bumped by every teardown so a stale in-flight doStart can never touch a newer kernel. */- private startGeneration = 0;- /** Memoized so concurrent callers all await the same in-flight startup. */- private startPromise?: Promise<void>;- /** Pending debounced auto-snapshot, if one has been scheduled. */- private snapshotTimer?: ReturnType<typeof globalThis.setTimeout>;-- constructor(options: KernelManagerOptions) {- this.options = {- python: options.python,- cwd: options.cwd,- env: options.env,- sessionId: options.sessionId,- hostHandlers: options.hostHandlers,- pythonSkills: options.pythonSkills,- snapshot: options.snapshot,- username: options.username ?? "prime-agent",- };- }-- get ownerSessionId(): string | undefined {- return this.options.sessionId;- }-- private appendKernelDiagnostic(message: string): void {- this.kernelStderr += `[kernel] ${message.endsWith("\n") ? message : `${message}\n`}`;- }-- async start(options: KernelStartOptions = {}): Promise<void> {- if (options.signal?.aborted) {- throw createKernelStartupAbortError();- }- if (!this.startPromise) {- const startPromise = this.doStart({ onBootstrapProgress: options.onBootstrapProgress }).catch((error) => {- // Only clear our own memoization: a stale start must not evict a newer one.- if (this.startPromise === startPromise) this.startPromise = undefined;- throw error;- });- this.startPromise = startPromise;- }- return raceStartupWithAbort(this.startPromise, options.signal);- }-- private async doStart(startOptions: KernelStartOptions): Promise<void> {- if (this.state !== "idle") return;- const generation = ++this.startGeneration;- this.state = "starting";- installSignalHandlersOnce();- // Tracked from the moment startup begins so session cleanup and signal- // handlers can dispose a kernel that is still booting.- liveKernels.add(this);-- let python: string;- try {- python =- this.options.python ??- (await ensureKernelPython({- pythonSkills: this.options.pythonSkills,- onProgress: startOptions.onBootstrapProgress,- }));- if (this.startStale(generation)) throw new Error("Kernel start superseded");- this.options.python = python;- } catch (error) {- if (this.startStale(generation)) throw error; // never touch a newer start's state- liveKernels.delete(this);- if ((this.state as string) !== "shutdown") this.state = "idle";- throw error;- }-- if ((this.state as string) === "shutdown") {- throw new Error("Kernel was disposed during startup");- }-- let connection = makeConnection();- this.tempDir = connection.tempDir;-- // Fast path: fork a pre-imported kernel from the forkserver. Any failure- // (disabled, unavailable, fork error) degrades to the direct-spawn path so- // correctness never depends on fork.- let forked = false;- if (isForkServerEnabled()) {- try {- const handle = await forkKernel(python, {- connectionPath: connection.path,- cwd: this.options.cwd,- // Applied fresh in the child (the template's env snapshot may be stale).- // No JPY_PARENT_PID: forked children watch the forkserver by getppid().- env: { ...process.env, ...this.options.env, PRIME_AGENT_KERNEL_OWNER_PID: String(process.pid) },- });- if (this.startStale(generation)) {- // Nobody owns this kernel; the protocol kill is id-keyed and safe.- void handle.kill("TERM").catch(() => {});- throw new Error("Kernel start superseded");- }- this.forkedKernel = handle;- recordOrphanProcessState(handle.pid, true);- forked = true;- } catch (err) {- if (this.startStale(generation)) throw err; // never touch a newer start's state- if (!(err instanceof ForkServerUnavailable)) throw err;- this.appendKernelDiagnostic(`forkserver unavailable, spawning directly: ${err.message}`);- this.forkedKernel = undefined;- // A fork request that times out or loses its pid reply may still have- // forked a child that binds the ports in this connection file. Mint a- // fresh connection for the direct spawn so a possible orphan can never- // collide with it (write the same file / re-bind the same ports).- try {- rmSync(connection.tempDir, { recursive: true, force: true });- } catch {- // Leave temporary kernel files for OS cleanup.- }- // A failed fork may leave stale ports; retry with a fresh connection file.- connection = makeConnection();- this.tempDir = connection.tempDir;- }- }-- if (!forked) {- const kernel = spawn(python, ["-m", "ipykernel_launcher", "-f", connection.path], {- cwd: this.options.cwd,- // ipykernel's parent poller exits the kernel if this pid dies (covers SIGKILL of the owner).- env: {- ...process.env,- ...this.options.env,- JPY_PARENT_PID: String(process.pid),- PRIME_AGENT_KERNEL_OWNER_PID: String(process.pid),- },- stdio: ["ignore", "pipe", "pipe"],- });- this.kernel = kernel;- if (kernel.pid !== undefined) recordOrphanProcessState(kernel.pid, true);-- kernel.stderr?.on("data", (buf: Buffer) => {- const s = buf.toString();- this.kernelStderr += s;- });-- kernel.on("error", (err) => {- if (this.kernel !== kernel) return;- this.appendKernelDiagnostic(`spawn error: ${err.message}`);- this.state = "shutdown";- liveKernels.delete(this);- this.cleanupResources();- });-- kernel.on("exit", (code, signal) => {- if (this.kernel !== kernel) return;- if (this.state !== "shutdown") {- this.appendKernelDiagnostic(`unexpected exit code=${code} signal=${signal}`);- }- this.state = "shutdown";- liveKernels.delete(this);- this.cleanupResources();- });- }-- const connectionPath = connection.path;- let conn: ConnectionInfo;- try {- conn = await this.waitForResolvedConnection(connectionPath);- if (this.startStale(generation)) throw new Error("Kernel start superseded");- this.connection = conn;- } catch (e) {- if (this.startStale(generation)) throw e; // never tear down a newer start's kernel- const canRetryStartup = (this.state as string) !== "shutdown";- // Only the call that performed the cleanup may resurrect to idle; a- // concurrent kill()/teardown owns the state otherwise.- if ((await this.shutdown()) && canRetryStartup) this.state = "idle";- throw e;- }-- this.shell = new Dealer();- this.iopub = new Subscriber();- this.control = new Dealer();- this.shell.connect(`${conn.transport}://${conn.ip}:${conn.shell_port}`);- this.iopub.connect(`${conn.transport}://${conn.ip}:${conn.iopub_port}`);- this.control.connect(`${conn.transport}://${conn.ip}:${conn.control_port}`);- this.iopub.subscribe("");- this.startControlPump();-- // ZMQ PUB/SUB slow-joiner: give the subscription a brief chance to reach the kernel before first execute.- await sleep(IOPUB_SUBSCRIBE_DELAY_MS);- if (this.startStale(generation)) throw new Error("Kernel start superseded");- this.startIopubPump();-- try {- await this.probeReady();- if (this.startStale(generation)) throw new Error("Kernel start superseded");- } catch (e) {- if (this.startStale(generation)) throw e; // never tear down a newer start's kernel- const canRetryStartup = (this.state as string) !== "shutdown";- // Only the call that performed the cleanup may resurrect to idle; a- // concurrent kill()/teardown owns the state otherwise.- if ((await this.shutdown()) && canRetryStartup) this.state = "idle";- throw e;- }-- this.state = "running";- this.startForkedLivenessMonitor();- }-- /** True when a teardown (or newer start) superseded the start that captured `generation`. */- private startStale(generation: number): boolean {- return generation !== this.startGeneration;- }-- // No "exit" event fires for a non-child; poll the forkserver so a mid-run- // death tears down like the direct-spawn exit handler.- private startForkedLivenessMonitor(): void {- if (!this.forkedKernel) return;- this.forkedLivenessTimer = globalThis.setInterval(() => {- void this.checkForkedKernelDeath();- }, FORKED_LIVENESS_POLL_MS);- this.forkedLivenessTimer.unref?.();- }-- private async checkForkedKernelDeath(): Promise<void> {- if (this.state !== "running" || this.forkedLivenessProbeInFlight) return;- const probed = this.forkedKernel;- this.forkedLivenessProbeInFlight = true;- try {- if (!(await this.forkedKernelDead(probed))) return;- } finally {- this.forkedLivenessProbeInFlight = false;- }- // Re-check after the await: teardown or a restart may have raced this poll.- if (this.state !== "running" || this.forkedKernel !== probed) return;- this.appendKernelDiagnostic("forked kernel exited unexpectedly");- this.state = "shutdown";- liveKernels.delete(this);- this.cleanupResources();- }-- // Liveness from the forkserver's reap table; a pid-0 probe would race reuse.- // `timeoutMs` bounds the probe (timeout counts as alive so the caller's own- // deadline decides); without it the protocol request timeout applies.- private async forkedKernelDead(probed: ForkedKernelHandle | undefined, timeoutMs?: number): Promise<boolean> {- if (!probed) return false;- try {- const alive = probed.isAlive();- if (timeoutMs === undefined) return !(await alive);- alive.catch(() => {}); // absorb a rejection that lands after the race is lost- return !(await Promise.race([alive, sleep(timeoutMs, true, { ref: false })]));- } catch (error) {- // A timeout is unknown liveness, not proven death (the forkserver may just be stalled in a slow fork).- if (error instanceof ForkServerUnavailable && error.timedOut) return false;- // Forkserver gone: its kernels' parent_handle watchdogs exit them too.- return true;- }- }-- private async waitForResolvedConnection(connectionPath: string): Promise<ConnectionInfo> {- const startedAt = Date.now();- while (Date.now() - startedAt < PORTS_RESOLVE_TIMEOUT_MS) {- const remainingBudget = PORTS_RESOLVE_TIMEOUT_MS - (Date.now() - startedAt);- if (- (this.state as string) === "shutdown" ||- (await this.forkedKernelDead(this.forkedKernel, remainingBudget))- ) {- const tail = this.kernelStderr.slice(-1024);- throw new Error(`Kernel exited before resolving ports. stderr:\n${tail || "(empty)"}`);- }-- const info = readConnectionInfo(connectionPath);- if (info && hasResolvedPorts(info)) {- return info;- }-- await sleep(25);- }-- const tail = this.kernelStderr.slice(-1024);- throw new Error(- `Kernel did not resolve connection ports within ${PORTS_RESOLVE_TIMEOUT_MS}ms. stderr tail:\n${tail || "(empty)"}`,- );- }-- private async probeReady(): Promise<void> {- const conn = this.connection!;- const shell = this.shell!;-- const msg = buildMessage("kernel_info_request", {}, this.session, this.options.username);- const requestMsgId = msg.header.msg_id;- await this.translateSocketClosure(shell.send(encode(msg, conn.key)));-- const startedAt = Date.now();- while (Date.now() - startedAt < READY_TIMEOUT_MS) {- const remainingBudget = READY_TIMEOUT_MS - (Date.now() - startedAt);- if (- (this.state as string) === "shutdown" ||- (await this.forkedKernelDead(this.forkedKernel, remainingBudget))- ) {- const tail = this.kernelStderr.slice(-1024);- throw new Error(`Kernel exited during startup. stderr:\n${tail || "(empty)"}`);- }-- const remaining = READY_TIMEOUT_MS - (Date.now() - startedAt);- const winner = await Promise.race([- this.translateSocketClosure(shell.receive()).then((frames) => ({ kind: "frames" as const, frames })),- sleep(remaining).then(() => ({ kind: "timeout" as const })),- ]);- if (winner.kind === "timeout") break;-- const incoming = decode(winner.frames);- if (- incoming?.header.msg_type === "kernel_info_reply" &&- (incoming.parent_header as { msg_id?: string }).msg_id === requestMsgId- ) {- return;- }- }- const tail = this.kernelStderr.slice(-1024);- throw new Error(- `Kernel did not respond to kernel_info_request within ${READY_TIMEOUT_MS}ms. stderr tail:\n${tail || "(empty)"}`,- );- }-- /**- * A zmq operation interrupted by socket teardown rejects with the raw libzmq- * EAGAIN text ("Operation was not possible or timed out"); surface the kernel- * lifecycle instead so callers see an actionable, retriable failure.- */- private async translateSocketClosure<T>(operation: Promise<T>): Promise<T> {- try {- return await operation;- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- if (message.includes("not possible or timed out") || message.includes("Socket is closed")) {- const tail = this.kernelStderr.slice(-1024);- throw new Error(- `IPython kernel channel closed while ${this.state === "starting" ? "starting up" : "communicating"} (retriable). stderr tail:\n${tail || "(empty)"}`,- );- }- throw error;- }- }-- async execute(code: string, opts: ExecuteOptions = {}): Promise<ExecuteResult> {- const result = await this.enqueueExecute(code, opts);- // Refresh the on-disk snapshot after real work so a later resume (or a- // crash before graceful shutdown) revives the most recent namespace.- if (result.status === "ok") {- this.scheduleSnapshot();- }- return result;- }-- /** Queue and run a cell, serializing against all other executions. */- private async enqueueExecute(- code: string,- opts: ExecuteOptions,- executionTimeoutMs?: number,- ): Promise<ExecuteResult> {- if (opts.signal?.aborted) {- return { stdout: "", stderr: "", status: "aborted", durationMs: 0 };- }- await this.start({ signal: opts.signal });- if ((this.state as string) === "shutdown") {- throw new Error("Kernel has been shut down");- }-- const prev = this.executionQueue;- let resolveNext: () => void = () => {};- this.executionQueue = new Promise<void>((r) => {- resolveNext = r;- });- await prev;-- const started = Date.now();- let executionTimeout: ReturnType<typeof globalThis.setTimeout> | undefined;- try {- await this.waitForActiveExecutionToClearForReuse(opts.signal);- if (opts.signal?.aborted) {- return { stdout: "", stderr: "", status: "aborted", durationMs: Date.now() - started };- }- if ((this.state as string) === "shutdown") {- throw new Error("Kernel has been shut down");- }- if (executionTimeoutMs === undefined) {- return await this.executeInner(code, opts, started);- }-- const controller = new AbortController();- executionTimeout = globalThis.setTimeout(() => controller.abort(), executionTimeoutMs);- executionTimeout.unref?.();- const signal = opts.signal ? AbortSignal.any([opts.signal, controller.signal]) : controller.signal;- return await this.executeInner(code, { ...opts, signal }, started);- } finally {- if (executionTimeout) globalThis.clearTimeout(executionTimeout);- resolveNext();- }- }-- private async executeInner(code: string, opts: ExecuteOptions, started: number): Promise<ExecuteResult> {- const conn = this.connection!;- const shell = this.shell!;- const maxChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;-- const msg = buildMessage(- "execute_request",- {- code,- silent: false,- store_history: true,- user_expressions: {},- allow_stdin: false,- stop_on_error: true,- },- this.session,- this.options.username,- );- const requestMsgId = msg.header.msg_id;-- if (opts.signal?.aborted) {- return { stdout: "", stderr: "", status: "aborted", durationMs: Date.now() - started };- }- if (this.activeExecution) {- throw new Error("Kernel already has an active execution");- }-- const result = createDeferred<ExecuteResult>();- const execution: ActiveExecution = {- requestMsgId,- code,- started,- maxChars,- opts,- stdout: "",- stderr: "",- stdoutTruncated: false,- stderrTruncated: false,- diffs: [],- attachments: [],- sentAgentMessages: [],- status: "ok",- settled: false,- resolve: result.resolve,- reject: result.reject,- };- let abortTimer: ReturnType<typeof globalThis.setTimeout> | undefined;- const clearAbortTimer = () => {- if (abortTimer) {- globalThis.clearTimeout(abortTimer);- abortTimer = undefined;- }- };- const forceAbort = () => {- if (this.activeExecution !== execution) {- return;- }- execution.status = "aborted";- this.resolveExecution(execution, { clearActive: false });- };- const onAbort = () => {- void this.interrupt().catch(() => undefined);- clearAbortTimer();- abortTimer = globalThis.setTimeout(forceAbort, KERNEL_ABORT_GRACE_MS);- if (abortTimer && typeof abortTimer === "object" && "unref" in abortTimer) {- abortTimer.unref();- }- };-- try {- this.activeExecution = execution;- opts.signal?.addEventListener("abort", onAbort, { once: true });- if (opts.signal?.aborted) {- onAbort();- }- if (!opts.internal) {- this.lastCellCode = code;- }- try {- const sendPromise = this.translateSocketClosure(shell.send(encode(msg, conn.key)));- sendPromise.catch(() => undefined);- await Promise.race([sendPromise, result.promise.then(() => undefined)]);- if (this.activeExecution === execution && execution.status !== "aborted") {- await sendPromise;- }- } catch (error) {- if (this.activeExecution === execution) {- this.activeExecution = undefined;- }- throw error instanceof Error ? error : new Error(String(error));- }- return await result.promise;- } finally {- clearAbortTimer();- opts.signal?.removeEventListener("abort", onAbort);- }- }-- private startControlPump(): void {- if (this.controlPumpPromise) return;- this.controlPumpPromise = this.runControlPump();- }-- private async runControlPump(): Promise<void> {- const control = this.control;- if (!control) return;- try {- for await (const frames of control) {- const incoming = decode(frames);- if (!incoming) continue;- const parentMessageId = (incoming.parent_header as { msg_id?: string }).msg_id;- if (!parentMessageId) continue;- this.pendingControlReplies.get(parentMessageId)?.(incoming);- }- } catch (error) {- if ((this.state as string) !== "shutdown") {- this.appendKernelDiagnostic(`control pump failed: ${errorMessage(error)}`);- }- } finally {- if (this.control === control) this.controlPumpPromise = undefined;- }- }-- private waitForControlReply(- requestMessageId: string,- messageType: string,- timeoutMs: number,- ): { promise: Promise<void>; cancel: () => void } {- let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;- let settled = false;- const cleanup = () => {- if (timeout) globalThis.clearTimeout(timeout);- timeout = undefined;- this.pendingControlReplies.delete(requestMessageId);- };- const promise = new Promise<void>((resolve, reject) => {- this.pendingControlReplies.set(requestMessageId, (incoming) => {- if (incoming.header.msg_type !== messageType || settled) return;- settled = true;- cleanup();- resolve();- });- timeout = globalThis.setTimeout(() => {- if (settled) return;- settled = true;- cleanup();- reject(new Error(`Kernel did not reply to ${messageType} within ${timeoutMs}ms`));- }, timeoutMs);- timeout.unref?.();- });- return {- promise,- cancel: () => {- if (settled) return;- settled = true;- cleanup();- },- };- }-- private startIopubPump(): void {- if (this.iopubPumpPromise) {- return;- }- this.iopubPumpPromise = this.runIopubPump();- }-- private async runIopubPump(): Promise<void> {- const iopub = this.iopub;- if (!iopub) {- return;- }-- try {- for await (const frames of iopub) {- const incoming = decode(frames);- if (!incoming) continue;- const t = incoming.header.msg_type;- if (t === "comm_open" || t === "comm_msg" || t === "comm_close") {- this.handleCommMessage(incoming);- continue;- }- this.handleExecutionMessage(incoming);- }- } catch (error) {- if ((this.state as string) !== "shutdown") {- this.appendKernelDiagnostic(`iopub pump failed: ${errorMessage(error)}`);- this.rejectActiveExecution(new Error(`Kernel IOPub channel failed: ${errorMessage(error)}`));- }- } finally {- if (this.iopub === iopub) {- this.iopubPumpPromise = undefined;- }- }- }-- private handleExecutionMessage(incoming: JupyterMessage): void {- const execution = this.activeExecution;- const parentMessageId = (incoming.parent_header as { msg_id?: string }).msg_id;- if (!execution || parentMessageId !== execution.requestMsgId) {- if (incoming.header.msg_type === "display_data" || incoming.header.msg_type === "update_display_data") {- const content = incoming.content as { data?: Record<string, unknown> };- this.dispatchLateSentAgentMessage(parentMessageId, content.data?.[AGENT_MESSAGE_DISPLAY_MIME]);- }- return;- }-- const t = incoming.header.msg_type;- if (execution.settled && (t === "display_data" || t === "update_display_data")) {- const content = incoming.content as { data?: Record<string, unknown> };- if (this.dispatchLateSentAgentMessage(parentMessageId, content.data?.[AGENT_MESSAGE_DISPLAY_MIME])) {- return;- }- }- if (t === "stream") {- const c = incoming.content as { name: "stdout" | "stderr"; text: string };- if (c.name === "stdout") {- if (execution.stdout.length < execution.maxChars) {- execution.stdout += c.text;- if (execution.stdout.length > execution.maxChars) {- execution.stdout = execution.stdout.slice(0, execution.maxChars);- execution.stdoutTruncated = true;- }- }- } else if (c.name === "stderr") {- if (execution.stderr.length < execution.maxChars) {- execution.stderr += c.text;- if (execution.stderr.length > execution.maxChars) {- execution.stderr = execution.stderr.slice(0, execution.maxChars);- execution.stderrTruncated = true;- }- }- }- execution.opts.onStream?.(c.text, c.name);- } else if (t === "execute_result") {- const c = incoming.content as { data: Record<string, string> };- if (c.data["text/plain"]) execution.result = c.data["text/plain"];- } else if (t === "display_data" || t === "update_display_data") {- const c = incoming.content as { data?: Record<string, unknown> };- const diff = parseDiffDisplay(c.data?.[DIFF_DISPLAY_MIME]);- if (diff) execution.diffs.push(diff);- const attachment = parseAttachmentDisplay(c.data?.[ATTACHMENT_DISPLAY_MIME]);- if (attachment === "oversized") {- execution.stderr += `${execution.stderr ? "\n" : ""}attachment dropped: exceeds ${MAX_ATTACHMENT_DATA_CHARS} base64 chars`;- execution.status = "error";- } else if (attachment) {- execution.attachments.push(attachment);- }- const sentAgentMessage = parseSentAgentMessage(c.data?.[AGENT_MESSAGE_DISPLAY_MIME]);- if (sentAgentMessage) execution.sentAgentMessages.push(sentAgentMessage);- } else if (t === "error") {- const c = incoming.content as { ename: string; evalue: string; traceback: string[] };- execution.error = c;- execution.status = "error";- } else if (t === "status") {- const c = incoming.content as { execution_state: string };- if (c.execution_state === "idle") {- this.finishActiveExecution(execution);- }- }- }-- private finishActiveExecution(execution: ActiveExecution): void {- if (this.activeExecution !== execution) {- return;- }- this.resolveExecution(execution, { clearActive: true });- }-- private resolveExecution(execution: ActiveExecution, options: { clearActive: boolean }): void {- const didClearActive = options.clearActive && this.activeExecution === execution;- if (options.clearActive && this.activeExecution === execution) {- this.activeExecution = undefined;- }- if (!execution.settled) {- execution.settled = true;- if (execution.opts.onLateSentAgentMessage) {- this.registerLateSentAgentMessageHandler(execution.requestMsgId, execution.opts.onLateSentAgentMessage);- }-- let stdout = execution.stdout;- let stderr = execution.stderr;- let result = execution.result;- let status = execution.status;- if (execution.stdoutTruncated) stdout += `\n[... output truncated at ${execution.maxChars} chars ...]`;- if (execution.stderrTruncated) stderr += `\n[... output truncated at ${execution.maxChars} chars ...]`;- if (result !== undefined && result.length > execution.maxChars) {- result = `${result.slice(0, execution.maxChars)}\n[... output truncated at ${execution.maxChars} chars ...]`;- }-- if (execution.opts.signal?.aborted) status = "aborted";-- execution.resolve({- stdout,- stderr,- result,- diffs: execution.diffs.length > 0 ? execution.diffs : undefined,- attachments: execution.attachments.length > 0 ? execution.attachments : undefined,- sentAgentMessages: execution.sentAgentMessages.length > 0 ? execution.sentAgentMessages : undefined,- error: execution.error,- status,- durationMs: Date.now() - execution.started,- });- }- if (didClearActive) {- this.notifyActiveExecutionIdle();- }- }-- private dispatchLateSentAgentMessage(parentMessageId: string | undefined, value: unknown): boolean {- const sentAgentMessage = parseSentAgentMessage(value);- if (!sentAgentMessage || !parentMessageId) {- return false;- }- const handler = this.lateSentAgentMessageHandlers.get(parentMessageId);- if (!handler) {- return false;- }- this.lateSentAgentMessageHandlers.delete(parentMessageId);- this.lateSentAgentMessageHandlers.set(parentMessageId, handler);- handler(sentAgentMessage);- return true;- }-- private registerLateSentAgentMessageHandler(- requestMessageId: string,- handler: (message: KernelSentAgentMessage) => void,- ): void {- this.lateSentAgentMessageHandlers.set(requestMessageId, handler);- while (this.lateSentAgentMessageHandlers.size > MAX_LATE_SENT_AGENT_MESSAGE_HANDLERS) {- const oldestRequestMessageId = this.lateSentAgentMessageHandlers.keys().next().value;- if (oldestRequestMessageId === undefined) {- break;- }- this.lateSentAgentMessageHandlers.delete(oldestRequestMessageId);- }- }-- private rejectActiveExecution(error: Error): void {- const execution = this.activeExecution;- if (!execution) {- return;- }- this.activeExecution = undefined;- execution.reject(error);- this.notifyActiveExecutionIdle();- }-- private notifyActiveExecutionIdle(): void {- for (const resolve of this.activeExecutionIdleWaiters) {- resolve();- }- this.activeExecutionIdleWaiters.clear();- }-- private waitForActiveExecutionToClear(signal: AbortSignal | undefined, timeoutMs: number): Promise<boolean> {- if (!this.activeExecution) {- return Promise.resolve(true);- }- return new Promise<boolean>((resolve) => {- let settled = false;- let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;- const finish = (cleared: boolean) => {- if (settled) {- return;- }- settled = true;- if (timeout) {- globalThis.clearTimeout(timeout);- }- this.activeExecutionIdleWaiters.delete(onIdle);- signal?.removeEventListener("abort", onAbort);- resolve(cleared);- };- const onIdle = () => finish(true);- const onAbort = () => finish(false);- this.activeExecutionIdleWaiters.add(onIdle);- signal?.addEventListener("abort", onAbort, { once: true });- timeout = globalThis.setTimeout(() => finish(false), timeoutMs);- if (timeout && typeof timeout === "object" && "unref" in timeout) {- timeout.unref();- }- });- }-- private async waitForActiveExecutionToClearForReuse(signal?: AbortSignal): Promise<void> {- const started = Date.now();- while (this.activeExecution && Date.now() - started < KERNEL_BUSY_REUSE_WAIT_MS) {- if ((this.state as string) === "shutdown") {- throw new Error("Kernel has been shut down");- }- void this.interrupt().catch(() => undefined);- const remaining = KERNEL_BUSY_REUSE_WAIT_MS - (Date.now() - started);- const cleared = await this.waitForActiveExecutionToClear(- signal,- Math.max(1, Math.min(KERNEL_BUSY_INTERRUPT_INTERVAL_MS, remaining)),- );- if (cleared || signal?.aborted) {- return;- }- }- if (this.activeExecution) {- throw new KernelBusyAfterInterruptError();- }- }-- private handleCommMessage(incoming: JupyterMessage): void {- const msgType = incoming.header.msg_type;- const content = incoming.content;- const commId = content.comm_id;- if (typeof commId !== "string") {- return;- }-- if (msgType === "comm_close") {- this.commTargets.delete(commId);- this.handledHostRequestCommIds.delete(commId);- return;- }-- if (msgType === "comm_open") {- const targetName = content.target_name;- if (typeof targetName !== "string") {- return;- }- this.commTargets.set(commId, targetName);- if (targetName === HOST_COMM_TARGET) {- this.startHostRequestFromComm(commId, content.data);- }- return;- }-- const targetName = this.commTargets.get(commId);- if (msgType === "comm_msg" && targetName === HOST_COMM_TARGET) {- this.startHostRequestFromComm(commId, content.data);- }- }-- private startHostRequestFromComm(commId: string, data: unknown): void {- if (this.handledHostRequestCommIds.has(commId)) {- return;- }- this.handledHostRequestCommIds.add(commId);-- const task = (async () => {- try {- const result = await this.handleHostRequest(data);- try {- await this.sendCommMessage(commId, { status: "ok", ...result });- } catch (replyError) {- this.appendKernelDiagnostic(- `failed to send host request ok reply for comm ${commId}: ${errorMessage(replyError)}`,- );- }- } catch (error) {- this.appendKernelDiagnostic(`host request failed for comm ${commId}: ${errorMessage(error)}`);- try {- await this.sendCommMessage(commId, { status: "error", error: errorMessage(error) });- } catch (replyError) {- this.appendKernelDiagnostic(- `failed to send host request error reply for comm ${commId}: ${errorMessage(replyError)}`,- );- }- }- })();- this.inFlightHostRequests.add(task);- void task.finally(() => {- this.inFlightHostRequests.delete(task);- });- }-- private async handleHostRequest(data: unknown): Promise<Record<string, unknown>> {- if (!isRecord(data)) {- throw new Error("host request payload must be an object");- }- if (typeof data.type !== "string" || data.type.length === 0) {- throw new Error("host request payload must have a string type");- }-- const handler = this.options.hostHandlers?.[data.type];- if (!handler) {- throw new Error(`host request type "${data.type}" is not available in this session`);- }- // Tag the request with the cell that triggered it. A blocking call is still- // the in-flight execution; detached spawns (asyncio.create_task) fire after- // the scheduling cell goes idle, so fall back to that last cell's source.- const cellSourceCode = this.activeExecution?.code ?? this.lastCellCode;- return handler({ ...data, cellSourceCode });- }-- private async sendCommMessage(commId: string, data: Record<string, unknown>): Promise<void> {- const channel = this.control ?? this.shell;- if (!channel || !this.connection) {- throw new Error("Kernel channel is not connected");- }- const msg = buildMessage("comm_msg", { comm_id: commId, data }, this.session, this.options.username);- await channel.send(encode(msg, this.connection.key));- }-- private async interrupt(): Promise<void> {- if (!this.control || !this.connection) return;- const msg = buildMessage("interrupt_request", {}, this.session, this.options.username);- await this.control.send(encode(msg, this.connection.key));- }-- private cleanupResources(killSignal: NodeJS.Signals = "SIGTERM"): void {- this.startGeneration++; // any teardown invalidates in-flight starts- this.clearSnapshotTimer();- this.lateSentAgentMessageHandlers.clear();- if (this.forkedLivenessTimer) {- globalThis.clearInterval(this.forkedLivenessTimer);- this.forkedLivenessTimer = undefined;- }- this.rejectActiveExecution(new Error("Kernel has been shut down"));- this.shell?.close();- this.iopub?.close();- this.control?.close();- this.pendingControlReplies.clear();- this.shell = undefined;- this.iopub = undefined;- this.control = undefined;- this.iopubPumpPromise = undefined;- this.controlPumpPromise = undefined;- if (this.kernel) {- const directPid = this.kernel.pid;- let signaled = false;- try {- signaled = this.kernel.kill(killSignal);- } catch {- // The kernel has already exited.- }- // Same rule as the forked branch below: inactive only when the signal proved the pid still ours.- if (directPid !== undefined && signaled) recordOrphanProcessState(directPid, false);- // A killed/crashed kernel cannot run its own shutdown hook, so the host- // reaps the bash() process groups it journaled under this kernel pid.- if (directPid !== undefined) reapKernelOrphanProcesses(directPid);- } else if (this.forkedKernel) {- const forked = this.forkedKernel;- // The journal is raw-pid keyed, so inactive is written only on "signaled"- // — the one outcome proving the pid still named our un-reaped child. Any- // other outcome leaves the record stale-active: the reaper's startId check- // neutralizes it, while a wrong inactive write could mask a sibling's- // record for a reused pid.- void forked- .kill(killSignal === "SIGKILL" ? "KILL" : "TERM")- .then((outcome) => {- if (outcome === "signaled") recordOrphanProcessState(forked.pid, false);- // Reap again: bash children journaled while the async kill was in flight.- reapKernelOrphanProcesses(forked.pid);- })- .catch(() => this.appendKernelDiagnostic("forkserver kill unconfirmed; leaving orphan record active"));- // Same reaping as the direct branch: bash() children journaled under this kernel pid.- reapKernelOrphanProcesses(forked.pid);- }- this.kernel = undefined;- this.forkedKernel = undefined;- this.connection = undefined;- if (this.tempDir) {- try {- rmSync(this.tempDir, { recursive: true, force: true });- } catch {- // Leave temporary kernel files for OS cleanup.- }- }- this.tempDir = undefined;- this.startPromise = undefined;- }-- private async waitForKernelExit(): Promise<void> {- const kernel = this.kernel;- if (kernel) {- if (kernel.exitCode !== null || kernel.signalCode !== null) return;- await new Promise<void>((resolve) => kernel.once("exit", () => resolve()));- return;- }- const forked = this.forkedKernel;- if (!forked) return;- while (this.forkedKernel === forked && !(await this.forkedKernelDead(forked))) {- await sleep(25);- }- }-- private async waitForHostRequestsToSettle(tasks: Promise<void>[], timeoutMs: number): Promise<void> {- let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;- const timeoutPromise = new Promise<"timeout">((resolve) => {- timeout = globalThis.setTimeout(() => resolve("timeout"), timeoutMs);- if (timeout && typeof timeout === "object" && "unref" in timeout) {- timeout.unref();- }- });-- const result = await Promise.race([Promise.allSettled(tasks).then(() => "settled" as const), timeoutPromise]);- if (timeout) {- globalThis.clearTimeout(timeout);- }- if (result === "timeout") {- this.appendKernelDiagnostic(- `timed out waiting ${timeoutMs}ms for ${tasks.length} host request task(s) during dispose`,- );- }- }-- /** Resolves true when this call performed the cleanup (false: a concurrent teardown won). */- async shutdown(opts: { snapshot?: boolean } = {}): Promise<boolean> {- if (this.state === "shutdown") {- liveKernels.delete(this);- this.cleanupResources();- return true;- }- // Captured before any await: teardowns and newer starts bump the counter.- const generation = this.startGeneration;- // Best-effort final flush (bounded) before teardown — used by signal handlers- // so a SIGINT/SIGTERM exit doesn't lose work the debounced snapshot hasn't saved.- if (opts.snapshot) {- await this.flushSnapshotForDispose();- if (this.startStale(generation)) return false; // superseded mid-flush: the newer owner already cleaned this kernel- }- this.state = "shutdown";- liveKernels.delete(this);-- let replyWait: { promise: Promise<void>; cancel: () => void } | undefined;- let shutdownTimer: ReturnType<typeof globalThis.setTimeout> | undefined;- let performedCleanup = false;- const shutdownDeadline = new Promise<never>((_resolve, reject) => {- shutdownTimer = globalThis.setTimeout(- () => reject(new Error(`Kernel did not shut down within ${KERNEL_SHUTDOWN_TIMEOUT_MS}ms`)),- KERNEL_SHUTDOWN_TIMEOUT_MS,- );- shutdownTimer.unref?.();- });- try {- if (this.control && this.connection) {- const msg = buildMessage("shutdown_request", { restart: false }, this.session, this.options.username);- replyWait = this.waitForControlReply(msg.header.msg_id, "shutdown_reply", KERNEL_SHUTDOWN_TIMEOUT_MS);- const send = this.control.send(encode(msg, this.connection.key));- send.catch(() => undefined);- // A kernel that exits without delivering shutdown_reply must not stall the deadline.- const kernelExit = this.waitForKernelExit();- const gracefulReply = Promise.all([send, replyWait.promise]);- // Abandoned by the race, a late send failure must not reject unhandled.- gracefulReply.catch(() => undefined);- await Promise.race([gracefulReply, kernelExit, shutdownDeadline]);- await Promise.race([kernelExit, shutdownDeadline]);- }- } catch (error) {- this.appendKernelDiagnostic(- `graceful shutdown failed (killing instead): ${error instanceof Error ? error.message : String(error)}`,- );- } finally {- if (shutdownTimer) globalThis.clearTimeout(shutdownTimer);- replyWait?.cancel();- // A superseded shutdown must not tear down the newer start's sockets. Ownership is decided- // here, before cleanupResources bumps the generation and would misread this call as superseded.- if (!this.startStale(generation)) {- this.cleanupResources();- performedCleanup = true;- }- }-- return performedCleanup;- }-- async restart(): Promise<void> {- const prev = this.executionQueue;- let resolveNext: () => void = () => {};- this.executionQueue = new Promise<void>((r) => {- resolveNext = r;- });- await prev;-- try {- await this.shutdown();- this.state = "idle";- this.kernelStderr = "";- await this.start();- } finally {- resolveNext();- }- }-- async kill(): Promise<void> {- this.state = "shutdown";- liveKernels.delete(this);- this.cleanupResources("SIGKILL");- }-- /**- * Serialize the user namespace to disk (best-effort, per-variable). No-op when- * the kernel isn't running or no snapshot target was configured. Never throws.- */- async snapshotState(): Promise<SnapshotResult | null> {- return this.captureSnapshot();- }-- /** Persist the namespace, then remove variables above the per-variable cap. */- async pruneOversizedVariables(): Promise<SnapshotResult | null> {- return this.captureSnapshot({ executionTimeoutMs: SNAPSHOT_EXECUTION_TIMEOUT_MS, pruneOversized: true });- }-- private async captureSnapshot(- options: { executionTimeoutMs?: number; pruneOversized?: boolean } = {},- ): Promise<SnapshotResult | null> {- const cfg = this.options.snapshot;- if (!cfg || !this.isRunning) return null;- const code = buildSnapshotCode(- cfg.path,- cfg.manifestPath,- cfg.maxBytes ?? DEFAULT_SNAPSHOT_MAX_BYTES,- cfg.maxVariableBytes ?? DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES,- options.pruneOversized,- );- try {- const r = await this.enqueueExecute(- code,- { maxOutputChars: SNAPSHOT_MAX_OUTPUT_CHARS, internal: true },- options.executionTimeoutMs,- );- if (r.status !== "ok") {- this.appendKernelDiagnostic(- `state snapshot ${r.status === "aborted" ? "timed out" : "failed"}: ${r.error?.evalue ?? r.stderr}`,- );- return null;- }- return parseSnapshotResult(r.stdout, cfg.path);- } catch (error) {- this.appendKernelDiagnostic(`state snapshot error: ${errorMessage(error)}`);- return null;- }- }-- /**- * Revive a previously snapshotted namespace into the kernel. Call right after- * start() and before the runtime bootstrap, which then refreshes live handles- * (rlm, skills) over anything restored. Never throws.- */- async restoreState(): Promise<RestoreResult | null> {- const cfg = this.options.snapshot;- if (!cfg) return null;- const code = buildRestoreCode(cfg.path);- try {- const r = await this.enqueueExecute(code, { maxOutputChars: SNAPSHOT_MAX_OUTPUT_CHARS, internal: true });- if (r.status !== "ok") {- this.appendKernelDiagnostic(`state restore failed: ${r.error?.evalue ?? r.stderr}`);- return null;- }- return parseRestoreResult(r.stdout, cfg.path);- } catch (error) {- this.appendKernelDiagnostic(`state restore error: ${errorMessage(error)}`);- return null;- }- }-- /** Live user-defined top-level names, or null if the kernel isn't running. Never throws. */- async listNamespaceNames(signal?: AbortSignal): Promise<string[] | null> {- if (!this.isRunning) return null;- try {- const r = await this.enqueueExecute(buildListNamesCode(), {- maxOutputChars: SNAPSHOT_MAX_OUTPUT_CHARS,- internal: true,- signal,- });- if (r.status !== "ok") {- this.appendKernelDiagnostic(`namespace listing failed: ${r.error?.evalue ?? r.stderr}`);- return null;- }- return parseListNamesResult(r.stdout);- } catch (error) {- this.appendKernelDiagnostic(`namespace listing error: ${errorMessage(error)}`);- return null;- }- }-- private scheduleSnapshot(): void {- const cfg = this.options.snapshot;- if (!cfg) return;- if (this.snapshotTimer) clearTimeout(this.snapshotTimer);- this.snapshotTimer = globalThis.setTimeout(() => {- this.snapshotTimer = undefined;- void this.captureSnapshot({ executionTimeoutMs: SNAPSHOT_EXECUTION_TIMEOUT_MS });- }, cfg.debounceMs ?? DEFAULT_SNAPSHOT_DEBOUNCE_MS);- if (this.snapshotTimer && typeof this.snapshotTimer === "object" && "unref" in this.snapshotTimer) {- this.snapshotTimer.unref();- }- }-- private clearSnapshotTimer(): void {- if (this.snapshotTimer) {- clearTimeout(this.snapshotTimer);- this.snapshotTimer = undefined;- }- }-- /** Best-effort final snapshot before a graceful dispose, bounded by a timeout. */- private async flushSnapshotForDispose(): Promise<void> {- if (!this.options.snapshot || !this.isRunning) return;- let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;- const guard = new Promise<void>((resolve) => {- timeout = globalThis.setTimeout(resolve, SNAPSHOT_DISPOSE_TIMEOUT_MS);- if (timeout && typeof timeout === "object" && "unref" in timeout) timeout.unref();- });- try {- await Promise.race([this.snapshotState().then(() => undefined), guard]);- } finally {- if (timeout) clearTimeout(timeout);- }- }-- /** Graceful cleanup. Waits briefly for in-flight host request handlers before closing sockets. */- dispose(): Promise<void> {- return (async () => {- // Captured before any await: teardowns and newer starts bump the counter.- const generation = this.startGeneration;- // Final namespace flush while the kernel is still live (session end / reload).- await this.flushSnapshotForDispose();- if (this.startStale(generation)) return; // superseded mid-flush: the newer owner already cleaned this kernel- this.state = "shutdown";- liveKernels.delete(this);- const inFlightHostRequests = [...this.inFlightHostRequests];- // TODO: plumb AbortSignal through AgentSession.prompt so disposal can cancel long-running child loops.- try {- if (inFlightHostRequests.length > 0) {- await this.waitForHostRequestsToSettle(inFlightHostRequests, HOST_REQUEST_DISPOSE_TIMEOUT_MS);- }- } finally {- if (!this.startStale(generation)) this.cleanupResources(); // else: superseded, the newer owner already cleaned- }- })();- }-- /** Synchronous best-effort cleanup. Safe to call from `process.on('exit')`. */- disposeSync(): void {- this.state = "shutdown";- liveKernels.delete(this);- // TODO: replace this best-effort hard-exit path if Node exposes an awaitable process-exit cleanup hook.- this.cleanupResources();- }-- get isRunning(): boolean {- return this.state === "running";- }-}+export { ReplKernelManager } from "./repl-manager.js";+export * from "./shared.js";diff --git a/packages/coding-agent/src/core/kernel/repl-manager.ts b/packages/coding-agent/src/core/kernel/repl-manager.tsnew file mode 100644index 0000000000..28c39c3f0d--- /dev/null+++ b/packages/coding-agent/src/core/kernel/repl-manager.ts@@ -0,0 +1,1188 @@+// Kernel client for the REPL runtime: the kernel is a JSON-lines subprocess+// (`python -m rlm.repl`) — requests on stdin, events on stdout, stderr kept as+// a diagnostics tail. The protocol is documented in prime-agent-runtime/src/rlm/repl.md.+import { type ChildProcess, spawn } from "node:child_process";+import { StringDecoder } from "node:string_decoder";+import { v4 as uuid } from "uuid";+import { reapKernelOrphanProcesses, recordOrphanProcessState } from "../orphan-process-journal.js";+import { ensureKernelPython } from "./bootstrap.js";+import {+ AGENT_MESSAGE_DISPLAY_MIME,+ ATTACHMENT_DISPLAY_MIME,+ createDeferred,+ createKernelStartupAbortError,+ DEFAULT_MAX_OUTPUT_CHARS,+ DEFAULT_SNAPSHOT_DEBOUNCE_MS,+ DIFF_DISPLAY_MIME,+ type ExecuteOptions,+ type ExecuteResult,+ errorMessage,+ HOST_REQUEST_DISPOSE_TIMEOUT_MS,+ installSignalHandlersOnce,+ isRecord,+ KERNEL_ABORT_GRACE_MS,+ KERNEL_BUSY_INTERRUPT_INTERVAL_MS,+ KERNEL_BUSY_REUSE_WAIT_MS,+ KERNEL_SHUTDOWN_TIMEOUT_MS,+ type KernelAttachment,+ KernelBusyAfterInterruptError,+ type KernelDiffDisplay,+ type KernelManagerOptions,+ type KernelSentAgentMessage,+ type KernelStartOptions,+ liveKernels,+ MAX_ATTACHMENT_DATA_CHARS,+ MAX_LATE_SENT_AGENT_MESSAGE_HANDLERS,+ parseAttachmentDisplay,+ parseDiffDisplay,+ parseSentAgentMessage,+ raceStartupWithAbort,+ SNAPSHOT_DISPOSE_TIMEOUT_MS,+ SNAPSHOT_EXECUTION_TIMEOUT_MS,+} from "./shared.js";+import {+ DEFAULT_SNAPSHOT_MAX_BYTES,+ DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES,+ type RestoreResult,+ type SnapshotResult,+} from "./state-snapshot.js";++const REPL_PROTOCOL_VERSION = 2;+const READY_TIMEOUT_MS = 30_000;+// Runtime-minted host-request ids never repeat; the bound only guards a+// misbehaving runtime from growing the dedup set forever.+const MAX_HANDLED_HOST_REQUEST_IDS = 1024;+// Cap for unattributed background output buffered between and during cells.+const MAX_BACKGROUND_OUTPUT_CHARS = 64 * 1024;++/** ExecuteResult plus the raw fields of the request's `done` event (state ops). */+interface InternalExecuteResult extends ExecuteResult {+ doneFields?: Record<string, unknown>;+}++interface ActiveExecution {+ requestId: string;+ /** Source of the cell currently executing; surfaced to rlm.run spawns. */+ code: string;+ started: number;+ maxChars: number;+ opts: ExecuteOptions;+ stdout: string;+ stderr: string;+ stdoutTruncated: boolean;+ stderrTruncated: boolean;+ result?: string;+ diffs: KernelDiffDisplay[];+ attachments: KernelAttachment[];+ sentAgentMessages: KernelSentAgentMessage[];+ /** Stream text without this execution's id: user threads, other cells' leftovers, raw fd writes. */+ backgroundOutput: string;+ backgroundOutputTruncated: boolean;+ error?: ExecuteResult["error"];+ status: ExecuteResult["status"];+ doneFields?: Record<string, unknown>;+ settled: boolean;+ resolve: (result: InternalExecuteResult) => void;+ reject: (error: Error) => void;+}++function asStringArray(value: unknown): string[] {+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : [];+}++function asReasonArray(value: unknown): { name: string; reason: string }[] {+ if (!Array.isArray(value)) return [];+ return value.flatMap((entry) => {+ if (isRecord(entry) && typeof entry.name === "string") {+ return [{ name: entry.name, reason: typeof entry.reason === "string" ? entry.reason : "" }];+ }+ return [];+ });+}++export class ReplKernelManager {+ private readonly options: Pick<+ KernelManagerOptions,+ "python" | "cwd" | "env" | "sessionId" | "hostHandlers" | "pythonSkills" | "snapshot"+ >;+ private readonly handledHostRequestIds = new Set<string>();+ private child?: ChildProcess;+ private readyDeferred?: ReturnType<typeof createDeferred<number>>;+ private kernelStderr = "";+ /** Serializes execute() calls — the runtime runs one request at a time. */+ private executionQueue: Promise<unknown> = Promise.resolve();+ private activeExecution?: ActiveExecution;+ private readonly activeExecutionIdleWaiters = new Set<() => void>();+ private readonly lateSentAgentMessageHandlers = new Map<string, (message: KernelSentAgentMessage) => void>();+ /** Resolvers for done events outside the active execution (the shutdown reply). */+ private readonly pendingDoneWaiters = new Map<string, () => void>();+ // Source of the most recently started cell, retained after it finishes so+ // rlm.run spawns from detached asyncio tasks (cell already idle) can still+ // attribute their spawning program.+ private lastCellCode?: string;+ /** Unattributed stream text that arrived between cells; surfaced on the next execution. */+ private pendingBackgroundOutput = "";+ private pendingBackgroundOutputTruncated = false;+ private readonly inFlightHostRequests = new Set<Promise<void>>();+ private state: "idle" | "starting" | "running" | "shutdown" = "idle";+ /** Bumped by every teardown so a stale in-flight doStart can never touch a newer kernel. */+ private startGeneration = 0;+ /** Generation whose graceful shutdown() owns the teardown, so the exit handler must not run it. */+ private gracefulShutdownGeneration?: number;+ /** Memoized so concurrent callers all await the same in-flight startup. */+ private startPromise?: Promise<void>;+ /** Pending debounced auto-snapshot, if one has been scheduled. */+ private snapshotTimer?: ReturnType<typeof globalThis.setTimeout>;++ constructor(options: KernelManagerOptions) {+ this.options = {+ python: options.python,+ cwd: options.cwd,+ env: options.env,+ sessionId: options.sessionId,+ hostHandlers: options.hostHandlers,+ pythonSkills: options.pythonSkills,+ snapshot: options.snapshot,+ };+ }++ get ownerSessionId(): string | undefined {+ return this.options.sessionId;+ }++ private appendKernelDiagnostic(message: string): void {+ this.kernelStderr += `[kernel] ${message.endsWith("\n") ? message : `${message}\n`}`;+ }++ async start(options: KernelStartOptions = {}): Promise<void> {+ if (options.signal?.aborted) {+ throw createKernelStartupAbortError();+ }+ if (!this.startPromise) {+ const startPromise = this.doStart({ onBootstrapProgress: options.onBootstrapProgress }).catch((error) => {+ // Only clear our own memoization: a stale start must not evict a newer one.+ if (this.startPromise === startPromise) this.startPromise = undefined;+ throw error;+ });+ this.startPromise = startPromise;+ }+ return raceStartupWithAbort(this.startPromise, options.signal);+ }++ private async doStart(startOptions: KernelStartOptions): Promise<void> {+ if (this.state !== "idle") return;+ const generation = ++this.startGeneration;+ this.state = "starting";+ installSignalHandlersOnce();+ // Tracked from the moment startup begins so session cleanup and signal+ // handlers can dispose a kernel that is still booting.+ liveKernels.add(this);++ let python: string;+ try {+ python =+ this.options.python ??+ (await ensureKernelPython({+ pythonSkills: this.options.pythonSkills,+ onProgress: startOptions.onBootstrapProgress,+ }));+ if (this.startStale(generation)) throw new Error("Kernel start superseded");+ this.options.python = python;+ } catch (error) {+ if (this.startStale(generation)) throw error; // never touch a newer start's state+ liveKernels.delete(this);+ if ((this.state as string) !== "shutdown") this.state = "idle";+ throw error;+ }++ if ((this.state as string) === "shutdown") {+ throw new Error("Kernel was disposed during startup");+ }++ const child = spawn(python, ["-m", "rlm.repl"], {+ cwd: this.options.cwd,+ // bash.py journals its process groups under this pid so the host can+ // reap them if the runtime dies without running its shutdown hook.+ env: {+ ...process.env,+ ...this.options.env,+ PRIME_AGENT_KERNEL_OWNER_PID: String(process.pid),+ },+ stdio: ["pipe", "pipe", "pipe"],+ });+ this.child = child;+ if (child.pid !== undefined) recordOrphanProcessState(child.pid, true);+ this.readyDeferred = createDeferred<number>();+ this.wireChild(child);++ try {+ const protocol = await this.waitForReady(child);+ if (this.startStale(generation)) throw new Error("Kernel start superseded");+ if (protocol !== REPL_PROTOCOL_VERSION) {+ throw new Error(+ `Kernel runtime speaks protocol ${protocol}, expected ${REPL_PROTOCOL_VERSION}. ` ++ "Update prime-agent-runtime in the kernel Python (PRIME_AGENT_KERNEL_PYTHON) to match this prime-agent.",+ );+ }+ } catch (e) {+ if (this.startStale(generation)) throw e; // never tear down a newer start's kernel+ const canRetryStartup = (this.state as string) !== "shutdown";+ // Only the call that performed the cleanup may resurrect to idle; a+ // concurrent kill()/teardown owns the state otherwise.+ if ((await this.shutdown()) && canRetryStartup) this.state = "idle";+ throw e;+ }++ this.state = "running";+ }++ /** True when a teardown (or newer start) superseded the start that captured `generation`. */+ private startStale(generation: number): boolean {+ return generation !== this.startGeneration;+ }++ private wireChild(child: ChildProcess): void {+ const decoder = new StringDecoder("utf8");+ let buffered = "";+ child.stdout?.on("data", (buf: Buffer) => {+ if (this.child !== child) return;+ buffered += decoder.write(buf);+ let newline = buffered.indexOf("\n");+ while (newline !== -1) {+ const line = buffered.slice(0, newline);+ buffered = buffered.slice(newline + 1);+ newline = buffered.indexOf("\n");+ if (!line.trim()) continue;+ let event: unknown;+ try {+ event = JSON.parse(line);+ } catch {+ this.appendKernelDiagnostic(`unparseable protocol line: ${line.slice(0, 200)}`);+ continue;+ }+ if (isRecord(event)) this.handleEvent(event);+ }+ });++ child.stderr?.on("data", (buf: Buffer) => {+ this.kernelStderr += buf.toString();+ });++ child.on("error", (err) => {+ if (this.child !== child) return;+ this.appendKernelDiagnostic(`spawn error: ${err.message}`);+ this.state = "shutdown";+ liveKernels.delete(this);+ // Fail a pending start() promptly instead of letting it ride out the+ // ready timeout. cleanupResources clears readyDeferred, so reject first;+ // a late error after ready resolved is a no-op on the settled promise.+ this.readyDeferred?.reject(err);+ this.cleanupResources();+ });++ child.on("exit", (code, signal) => {+ if (this.child !== child) return;+ if (this.state !== "shutdown") {+ this.appendKernelDiagnostic(`unexpected exit code=${code} signal=${signal}`);+ }+ this.state = "shutdown";+ liveKernels.delete(this);+ // This exit is part of an in-flight graceful shutdown(): that call owns the+ // teardown and runs cleanupResources itself. Cleaning up here would bump the+ // generation and misread the owning shutdown as superseded.+ if (this.gracefulShutdownGeneration === this.startGeneration) return;+ this.cleanupResources();+ });+ }++ private async waitForReady(child: ChildProcess): Promise<number> {+ const ready = this.readyDeferred;+ if (!ready) throw new Error("Kernel ready state is missing");+ let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;+ let onExit: (() => void) | undefined;+ try {+ return await new Promise<number>((resolve, reject) => {+ ready.promise.then(resolve, reject);+ onExit = () => {+ const tail = this.kernelStderr.slice(-1024);+ reject(new Error(`Kernel exited before ready. stderr:\n${tail || "(empty)"}`));+ };+ if (child.exitCode !== null || child.signalCode !== null) {+ onExit();+ return;+ }+ child.once("exit", onExit);+ timeout = globalThis.setTimeout(() => {+ const tail = this.kernelStderr.slice(-1024);+ reject(+ new Error(+ `Kernel did not become ready within ${READY_TIMEOUT_MS}ms. stderr tail:\n${tail || "(empty)"}`,+ ),+ );+ }, READY_TIMEOUT_MS);+ timeout.unref?.();+ });+ } finally {+ if (timeout) globalThis.clearTimeout(timeout);+ if (onExit) child.removeListener("exit", onExit);+ }+ }++ /** Write one JSON-lines request frame; resolves when the OS accepted the bytes. */+ private writeLine(request: Record<string, unknown>): Promise<void> {+ const stdin = this.child?.stdin;+ if (!stdin || stdin.destroyed) {+ return Promise.reject(new Error("Kernel stdin is not connected"));+ }+ return new Promise<void>((resolve, reject) => {+ stdin.write(`${JSON.stringify(request)}\n`, (error) => {+ if (error) reject(error);+ else resolve();+ });+ });+ }++ private handleEvent(event: Record<string, unknown>): void {+ const type = event.event;+ if (type === "ready") {+ this.readyDeferred?.resolve(typeof event.protocol === "number" ? event.protocol : -1);+ return;+ }+ if (type === "host_request") {+ if (typeof event.id === "string") this.startHostRequest(event.id, event.data);+ return;+ }++ const id = typeof event.id === "string" ? event.id : undefined;+ const execution = this.activeExecution;+ if (!execution || id !== execution.requestId) {+ if (type === "display" && isRecord(event.data)) {+ this.dispatchLateSentAgentMessage(id, event.data[AGENT_MESSAGE_DISPLAY_MIME]);+ } else if (type === "stdout" || type === "stderr") {+ // Unowned output (null id, or another cell's id): never merge it into+ // the active cell's streams; buffer it as background output instead.+ this.appendBackgroundOutput(typeof event.text === "string" ? event.text : "");+ } else if (type === "done" && id) {+ const waiter = this.pendingDoneWaiters.get(id);+ this.pendingDoneWaiters.delete(id);+ waiter?.();+ } else if (type === "error" && id === undefined) {+ this.appendKernelDiagnostic(`protocol error: ${String(event.evalue ?? "")}`);+ }+ return;+ }++ if (execution.settled && type === "display" && isRecord(event.data)) {+ if (this.dispatchLateSentAgentMessage(id, event.data[AGENT_MESSAGE_DISPLAY_MIME])) {+ return;+ }+ }+ if (type === "stdout" || type === "stderr") {+ const text = typeof event.text === "string" ? event.text : "";+ if (type === "stdout") {+ if (execution.stdout.length < execution.maxChars) {+ execution.stdout += text;+ if (execution.stdout.length > execution.maxChars) {+ execution.stdout = execution.stdout.slice(0, execution.maxChars);+ execution.stdoutTruncated = true;+ }+ }+ } else {+ if (execution.stderr.length < execution.maxChars) {+ execution.stderr += text;+ if (execution.stderr.length > execution.maxChars) {+ execution.stderr = execution.stderr.slice(0, execution.maxChars);+ execution.stderrTruncated = true;+ }+ }+ }+ execution.opts.onStream?.(text, type);+ } else if (type === "result") {+ if (typeof event.text === "string") execution.result = event.text;+ } else if (type === "display") {+ const data = isRecord(event.data) ? event.data : {};+ const diff = parseDiffDisplay(data[DIFF_DISPLAY_MIME]);+ if (diff) execution.diffs.push(diff);+ const attachment = parseAttachmentDisplay(data[ATTACHMENT_DISPLAY_MIME]);+ if (attachment === "oversized") {+ execution.stderr += `${execution.stderr ? "\n" : ""}attachment dropped: exceeds ${MAX_ATTACHMENT_DATA_CHARS} base64 chars`;+ execution.status = "error";+ } else if (attachment) {+ execution.attachments.push(attachment);+ }+ const sentAgentMessage = parseSentAgentMessage(data[AGENT_MESSAGE_DISPLAY_MIME]);+ if (sentAgentMessage) execution.sentAgentMessages.push(sentAgentMessage);+ } else if (type === "error") {+ execution.error = {+ ename: typeof event.ename === "string" ? event.ename : "Error",+ evalue: typeof event.evalue === "string" ? event.evalue : "",+ traceback: asStringArray(event.traceback),+ };+ execution.status = "error";+ } else if (type === "done") {+ execution.doneFields = event;+ if (event.status !== "ok" && execution.status === "ok") {+ execution.status = "error";+ // State requests report failures as a done reason without an error event.+ if (!execution.error && typeof event.reason === "string") {+ execution.error = { ename: "KernelError", evalue: event.reason, traceback: [] };+ }+ }+ this.finishActiveExecution(execution);+ }+ }++ async execute(code: string, opts: ExecuteOptions = {}): Promise<ExecuteResult> {+ const result = await this.enqueueExecute(code, opts);+ // Refresh the on-disk snapshot after real work so a later resume (or a+ // crash before graceful shutdown) revives the most recent namespace.+ if (result.status === "ok") {+ this.scheduleSnapshot();+ }+ return result;+ }++ /** Queue and run a cell, serializing against all other executions. */+ private async enqueueExecute(+ code: string,+ opts: ExecuteOptions,+ executionTimeoutMs?: number,+ ): Promise<InternalExecuteResult> {+ return this.enqueueRequest({ type: "execute", code }, code, opts, executionTimeoutMs);+ }++ /** Queue one protocol request (execute or state op) behind every other request. */+ private async enqueueRequest(+ requestFields: Record<string, unknown> & { type: string },+ code: string,+ opts: ExecuteOptions,+ executionTimeoutMs?: number,+ ): Promise<InternalExecuteResult> {+ if (opts.signal?.aborted) {+ return { stdout: "", stderr: "", status: "aborted", durationMs: 0 };+ }+ await this.start({ signal: opts.signal });+ if ((this.state as string) === "shutdown") {+ throw new Error("Kernel has been shut down");+ }++ const prev = this.executionQueue;+ let resolveNext: () => void = () => {};+ this.executionQueue = new Promise<void>((r) => {+ resolveNext = r;+ });+ await prev;++ const started = Date.now();+ let executionTimeout: ReturnType<typeof globalThis.setTimeout> | undefined;+ try {+ await this.waitForActiveExecutionToClearForReuse(opts.signal);+ if (opts.signal?.aborted) {+ return { stdout: "", stderr: "", status: "aborted", durationMs: Date.now() - started };+ }+ if ((this.state as string) === "shutdown") {+ throw new Error("Kernel has been shut down");+ }+ if (executionTimeoutMs === undefined) {+ return await this.executeInner(requestFields, code, opts, started);+ }++ const controller = new AbortController();+ executionTimeout = globalThis.setTimeout(() => controller.abort(), executionTimeoutMs);+ executionTimeout.unref?.();+ const signal = opts.signal ? AbortSignal.any([opts.signal, controller.signal]) : controller.signal;+ return await this.executeInner(requestFields, code, { ...opts, signal }, started);+ } finally {+ if (executionTimeout) globalThis.clearTimeout(executionTimeout);+ resolveNext();+ }+ }++ private async executeInner(+ requestFields: Record<string, unknown> & { type: string },+ code: string,+ opts: ExecuteOptions,+ started: number,+ ): Promise<InternalExecuteResult> {+ const maxChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;+ const requestId = uuid();++ if (opts.signal?.aborted) {+ return { stdout: "", stderr: "", status: "aborted", durationMs: Date.now() - started };+ }+ if (this.activeExecution) {+ throw new Error("Kernel already has an active execution");+ }++ const result = createDeferred<InternalExecuteResult>();+ const execution: ActiveExecution = {+ requestId,+ code,+ started,+ maxChars,+ opts,+ stdout: "",+ stderr: "",+ stdoutTruncated: false,+ stderrTruncated: false,+ diffs: [],+ attachments: [],+ sentAgentMessages: [],+ backgroundOutput: this.pendingBackgroundOutput,+ backgroundOutputTruncated: this.pendingBackgroundOutputTruncated,+ status: "ok",+ settled: false,+ resolve: result.resolve,+ reject: result.reject,+ };+ this.pendingBackgroundOutput = "";+ this.pendingBackgroundOutputTruncated = false;+ let abortTimer: ReturnType<typeof globalThis.setTimeout> | undefined;+ const clearAbortTimer = () => {+ if (abortTimer) {+ globalThis.clearTimeout(abortTimer);+ abortTimer = undefined;+ }+ };+ const forceAbort = () => {+ if (this.activeExecution !== execution) {+ return;+ }+ execution.status = "aborted";+ // The execution stays active until its done event arrives; clearing it+ // early would let a new cell race the interrupted one (see busy-after-interrupt).+ this.resolveExecution(execution, { clearActive: false });+ };+ const onAbort = () => {+ void this.interrupt().catch(() => undefined);+ clearAbortTimer();+ abortTimer = globalThis.setTimeout(forceAbort, KERNEL_ABORT_GRACE_MS);+ if (abortTimer && typeof abortTimer === "object" && "unref" in abortTimer) {+ abortTimer.unref();+ }+ };++ try {+ this.activeExecution = execution;+ opts.signal?.addEventListener("abort", onAbort, { once: true });+ if (opts.signal?.aborted) {+ onAbort();+ }+ if (!opts.internal) {+ this.lastCellCode = code;+ }+ try {+ const sendPromise = this.writeLine({ ...requestFields, id: requestId });+ sendPromise.catch(() => undefined);+ await Promise.race([sendPromise, result.promise.then(() => undefined)]);+ if (this.activeExecution === execution && execution.status !== "aborted") {+ await sendPromise;+ }+ } catch (error) {+ if (this.activeExecution === execution) {+ this.activeExecution = undefined;+ }+ throw error instanceof Error ? error : new Error(String(error));+ }+ return await result.promise;+ } finally {+ clearAbortTimer();+ opts.signal?.removeEventListener("abort", onAbort);+ }+ }++ private appendBackgroundOutput(text: string): void {+ if (!text) return;+ const execution = this.activeExecution;+ if (execution) {+ if (execution.backgroundOutput.length >= MAX_BACKGROUND_OUTPUT_CHARS) {+ execution.backgroundOutputTruncated = true;+ return;+ }+ execution.backgroundOutput += text;+ if (execution.backgroundOutput.length > MAX_BACKGROUND_OUTPUT_CHARS) {+ execution.backgroundOutput = execution.backgroundOutput.slice(0, MAX_BACKGROUND_OUTPUT_CHARS);+ execution.backgroundOutputTruncated = true;+ }+ return;+ }+ if (this.pendingBackgroundOutput.length >= MAX_BACKGROUND_OUTPUT_CHARS) {+ this.pendingBackgroundOutputTruncated = true;+ return;+ }+ this.pendingBackgroundOutput += text;+ if (this.pendingBackgroundOutput.length > MAX_BACKGROUND_OUTPUT_CHARS) {+ this.pendingBackgroundOutput = this.pendingBackgroundOutput.slice(0, MAX_BACKGROUND_OUTPUT_CHARS);+ this.pendingBackgroundOutputTruncated = true;+ }+ }++ private finishActiveExecution(execution: ActiveExecution): void {+ if (this.activeExecution !== execution) {+ return;+ }+ this.resolveExecution(execution, { clearActive: true });+ }++ private resolveExecution(execution: ActiveExecution, options: { clearActive: boolean }): void {+ const didClearActive = options.clearActive && this.activeExecution === execution;+ if (options.clearActive && this.activeExecution === execution) {+ this.activeExecution = undefined;+ }+ if (!execution.settled) {+ execution.settled = true;+ if (execution.opts.onLateSentAgentMessage) {+ this.registerLateSentAgentMessageHandler(execution.requestId, execution.opts.onLateSentAgentMessage);+ }++ let stdout = execution.stdout;+ let stderr = execution.stderr;+ let result = execution.result;+ let status = execution.status;+ if (execution.stdoutTruncated) stdout += `\n[... output truncated at ${execution.maxChars} chars ...]`;+ if (execution.stderrTruncated) stderr += `\n[... output truncated at ${execution.maxChars} chars ...]`;+ if (result !== undefined && result.length > execution.maxChars) {+ result = `${result.slice(0, execution.maxChars)}\n[... output truncated at ${execution.maxChars} chars ...]`;+ }++ if (execution.opts.signal?.aborted) status = "aborted";++ let backgroundOutput = execution.backgroundOutput;+ if (execution.backgroundOutputTruncated) {+ backgroundOutput += `\n[... background output truncated at ${MAX_BACKGROUND_OUTPUT_CHARS} chars ...]`;+ }++ execution.resolve({+ stdout,+ stderr,+ result,+ diffs: execution.diffs.length > 0 ? execution.diffs : undefined,+ attachments: execution.attachments.length > 0 ? execution.attachments : undefined,+ sentAgentMessages: execution.sentAgentMessages.length > 0 ? execution.sentAgentMessages : undefined,+ backgroundOutput: backgroundOutput.length > 0 ? backgroundOutput : undefined,+ error: execution.error,+ status,+ durationMs: Date.now() - execution.started,+ doneFields: execution.doneFields,+ });+ }+ if (didClearActive) {+ this.notifyActiveExecutionIdle();+ }+ }++ private dispatchLateSentAgentMessage(requestId: string | undefined, value: unknown): boolean {+ const sentAgentMessage = parseSentAgentMessage(value);+ if (!sentAgentMessage || !requestId) {+ return false;+ }+ const handler = this.lateSentAgentMessageHandlers.get(requestId);+ if (!handler) {+ return false;+ }+ this.lateSentAgentMessageHandlers.delete(requestId);+ this.lateSentAgentMessageHandlers.set(requestId, handler);+ handler(sentAgentMessage);+ return true;+ }++ private registerLateSentAgentMessageHandler(+ requestId: string,+ handler: (message: KernelSentAgentMessage) => void,+ ): void {+ this.lateSentAgentMessageHandlers.set(requestId, handler);+ while (this.lateSentAgentMessageHandlers.size > MAX_LATE_SENT_AGENT_MESSAGE_HANDLERS) {+ const oldestRequestId = this.lateSentAgentMessageHandlers.keys().next().value;+ if (oldestRequestId === undefined) {+ break;+ }+ this.lateSentAgentMessageHandlers.delete(oldestRequestId);+ }+ }++ private rejectActiveExecution(error: Error): void {+ const execution = this.activeExecution;+ if (!execution) {+ return;+ }+ this.activeExecution = undefined;+ execution.reject(error);+ this.notifyActiveExecutionIdle();+ }++ private notifyActiveExecutionIdle(): void {+ for (const resolve of this.activeExecutionIdleWaiters) {+ resolve();+ }+ this.activeExecutionIdleWaiters.clear();+ }++ private waitForActiveExecutionToClear(signal: AbortSignal | undefined, timeoutMs: number): Promise<boolean> {+ if (!this.activeExecution) {+ return Promise.resolve(true);+ }+ return new Promise<boolean>((resolve) => {+ let settled = false;+ let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;+ const finish = (cleared: boolean) => {+ if (settled) {+ return;+ }+ settled = true;+ if (timeout) {+ globalThis.clearTimeout(timeout);+ }+ this.activeExecutionIdleWaiters.delete(onIdle);+ signal?.removeEventListener("abort", onAbort);+ resolve(cleared);+ };+ const onIdle = () => finish(true);+ const onAbort = () => finish(false);+ this.activeExecutionIdleWaiters.add(onIdle);+ signal?.addEventListener("abort", onAbort, { once: true });+ timeout = globalThis.setTimeout(() => finish(false), timeoutMs);+ if (timeout && typeof timeout === "object" && "unref" in timeout) {+ timeout.unref();+ }+ });+ }++ private async waitForActiveExecutionToClearForReuse(signal?: AbortSignal): Promise<void> {+ const started = Date.now();+ while (this.activeExecution && Date.now() - started < KERNEL_BUSY_REUSE_WAIT_MS) {+ if ((this.state as string) === "shutdown") {+ throw new Error("Kernel has been shut down");+ }+ void this.interrupt().catch(() => undefined);+ const remaining = KERNEL_BUSY_REUSE_WAIT_MS - (Date.now() - started);+ const cleared = await this.waitForActiveExecutionToClear(+ signal,+ Math.max(1, Math.min(KERNEL_BUSY_INTERRUPT_INTERVAL_MS, remaining)),+ );+ if (cleared || signal?.aborted) {+ return;+ }+ }+ if (this.activeExecution) {+ throw new KernelBusyAfterInterruptError();+ }+ }++ private startHostRequest(requestId: string, data: unknown): void {+ if (this.handledHostRequestIds.has(requestId)) {+ return;+ }+ this.handledHostRequestIds.add(requestId);+ while (this.handledHostRequestIds.size > MAX_HANDLED_HOST_REQUEST_IDS) {+ const oldest = this.handledHostRequestIds.values().next().value;+ if (oldest === undefined) break;+ this.handledHostRequestIds.delete(oldest);+ }++ const task = (async () => {+ try {+ const result = await this.handleHostRequest(data);+ try {+ await this.writeLine({ type: "host_reply", id: requestId, data: { status: "ok", ...result } });+ } catch (replyError) {+ this.appendKernelDiagnostic(+ `failed to send host request ok reply for ${requestId}: ${errorMessage(replyError)}`,+ );+ }+ } catch (error) {+ this.appendKernelDiagnostic(`host request failed for ${requestId}: ${errorMessage(error)}`);+ try {+ await this.writeLine({+ type: "host_reply",+ id: requestId,+ data: { status: "error", error: errorMessage(error) },+ });+ } catch (replyError) {+ this.appendKernelDiagnostic(+ `failed to send host request error reply for ${requestId}: ${errorMessage(replyError)}`,+ );+ }+ }+ })();+ this.inFlightHostRequests.add(task);+ void task.finally(() => {+ this.inFlightHostRequests.delete(task);+ });+ }++ private async handleHostRequest(data: unknown): Promise<Record<string, unknown>> {+ if (!isRecord(data)) {+ throw new Error("host request payload must be an object");+ }+ if (typeof data.type !== "string" || data.type.length === 0) {+ throw new Error("host request payload must have a string type");+ }++ const handler = this.options.hostHandlers?.[data.type];+ if (!handler) {+ throw new Error(`host request type "${data.type}" is not available in this session`);+ }+ // Tag the request with the cell that triggered it. A blocking call is still+ // the in-flight execution; detached spawns (asyncio.create_task) fire after+ // the scheduling cell goes idle, so fall back to that last cell's source.+ const cellSourceCode = this.activeExecution?.code ?? this.lastCellCode;+ return handler({ ...data, cellSourceCode });+ }++ private async interrupt(): Promise<void> {+ const requestId = this.activeExecution?.requestId;+ if (!requestId) return;+ await this.writeLine({ type: "interrupt", id: requestId });+ }++ private cleanupResources(killSignal: NodeJS.Signals = "SIGTERM"): void {+ this.startGeneration++; // any teardown invalidates in-flight starts+ this.clearSnapshotTimer();+ this.lateSentAgentMessageHandlers.clear();+ this.pendingDoneWaiters.clear();+ // Stale pre-teardown background output must not surface after a restart.+ this.pendingBackgroundOutput = "";+ this.pendingBackgroundOutputTruncated = false;+ this.rejectActiveExecution(new Error("Kernel has been shut down"));+ const child = this.child;+ this.child = undefined;+ this.readyDeferred = undefined;+ if (child) {+ child.stdin?.destroy();+ child.stdout?.destroy();+ child.stderr?.destroy();+ const pid = child.pid;+ let signaled = false;+ try {+ signaled = child.kill(killSignal);+ } catch {+ // The kernel has already exited.+ }+ // Inactive only when the signal proved the pid still named our un-reaped child.+ if (pid !== undefined && signaled) recordOrphanProcessState(pid, false);+ // A killed/crashed kernel cannot run its own shutdown hook, so the host+ // reaps the bash() process groups it journaled under this kernel pid.+ if (pid !== undefined) reapKernelOrphanProcesses(pid);+ }+ this.startPromise = undefined;+ }++ private async waitForKernelExit(): Promise<void> {+ const child = this.child;+ if (!child) return;+ if (child.exitCode !== null || child.signalCode !== null) return;+ await new Promise<void>((resolve) => child.once("exit", () => resolve()));+ }++ private async waitForHostRequestsToSettle(tasks: Promise<void>[], timeoutMs: number): Promise<void> {+ let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;+ const timeoutPromise = new Promise<"timeout">((resolve) => {+ timeout = globalThis.setTimeout(() => resolve("timeout"), timeoutMs);+ if (timeout && typeof timeout === "object" && "unref" in timeout) {+ timeout.unref();+ }+ });++ const result = await Promise.race([Promise.allSettled(tasks).then(() => "settled" as const), timeoutPromise]);+ if (timeout) {+ globalThis.clearTimeout(timeout);+ }+ if (result === "timeout") {+ this.appendKernelDiagnostic(+ `timed out waiting ${timeoutMs}ms for ${tasks.length} host request task(s) during dispose`,+ );+ }+ }++ /** Resolves true when this call performed the cleanup (false: a concurrent teardown won). */+ async shutdown(opts: { snapshot?: boolean } = {}): Promise<boolean> {+ if (this.state === "shutdown") {+ liveKernels.delete(this);+ this.cleanupResources();+ return true;+ }+ // Captured before any await: teardowns and newer starts bump the counter.+ const generation = this.startGeneration;+ // Best-effort final flush (bounded) before teardown — used by signal handlers+ // so a SIGINT/SIGTERM exit doesn't lose work the debounced snapshot hasn't saved.+ if (opts.snapshot) {+ await this.flushSnapshotForDispose();+ if (this.startStale(generation)) return false; // superseded mid-flush: the newer owner already cleaned this kernel+ }+ this.state = "shutdown";+ liveKernels.delete(this);+ // Claim the teardown: our own child's exit handler must not run cleanupResources+ // (which bumps the generation and would misread this call as superseded). A+ // concurrent kill()/dispose() still bumps the generation and supersedes us.+ this.gracefulShutdownGeneration = generation;++ let shutdownTimer: ReturnType<typeof globalThis.setTimeout> | undefined;+ let doneWaiterId: string | undefined;+ let performedCleanup = false;+ const shutdownDeadline = new Promise<never>((_resolve, reject) => {+ shutdownTimer = globalThis.setTimeout(+ () => reject(new Error(`Kernel did not shut down within ${KERNEL_SHUTDOWN_TIMEOUT_MS}ms`)),+ KERNEL_SHUTDOWN_TIMEOUT_MS,+ );+ shutdownTimer.unref?.();+ });+ try {+ if (this.child?.stdin && !this.child.stdin.destroyed) {+ const requestId = uuid();+ doneWaiterId = requestId;+ const doneReply = new Promise<void>((resolve) => {+ this.pendingDoneWaiters.set(requestId, resolve);+ });+ const send = this.writeLine({ type: "shutdown", id: requestId });+ send.catch(() => undefined);+ // A kernel that exits without delivering its shutdown done must not stall the deadline.+ const kernelExit = this.waitForKernelExit();+ const gracefulReply = Promise.all([send, doneReply]);+ // Abandoned by the race, a late send failure must not reject unhandled.+ gracefulReply.catch(() => undefined);+ await Promise.race([gracefulReply, kernelExit, shutdownDeadline]);+ await Promise.race([kernelExit, shutdownDeadline]);+ }+ } catch (error) {+ this.appendKernelDiagnostic(+ `graceful shutdown failed (killing instead): ${error instanceof Error ? error.message : String(error)}`,+ );+ } finally {+ if (shutdownTimer) globalThis.clearTimeout(shutdownTimer);+ if (doneWaiterId) this.pendingDoneWaiters.delete(doneWaiterId);+ if (this.gracefulShutdownGeneration === generation) this.gracefulShutdownGeneration = undefined;+ // A superseded shutdown must not tear down the newer start's kernel. Ownership is decided+ // here, before cleanupResources bumps the generation and would misread this call as superseded.+ if (!this.startStale(generation)) {+ this.cleanupResources();+ performedCleanup = true;+ }+ }++ return performedCleanup;+ }++ async restart(): Promise<void> {+ const prev = this.executionQueue;+ let resolveNext: () => void = () => {};+ this.executionQueue = new Promise<void>((r) => {+ resolveNext = r;+ });+ await prev;++ try {+ const performedCleanup = await this.shutdown();+ if (!performedCleanup) return;+ this.state = "idle";+ this.kernelStderr = "";+ await this.start();+ } finally {+ resolveNext();+ }+ }++ async kill(): Promise<void> {+ this.state = "shutdown";+ liveKernels.delete(this);+ this.cleanupResources("SIGKILL");+ }++ /**+ * Serialize the user namespace to disk (best-effort, per-variable). No-op when+ * the kernel isn't running or no snapshot target was configured. Never throws.+ */+ async snapshotState(): Promise<SnapshotResult | null> {+ return this.captureSnapshot();+ }++ /** Persist the namespace, then remove variables above the per-variable cap. */+ async pruneOversizedVariables(): Promise<SnapshotResult | null> {+ return this.captureSnapshot({ executionTimeoutMs: SNAPSHOT_EXECUTION_TIMEOUT_MS, pruneOversized: true });+ }++ private async captureSnapshot(+ options: { executionTimeoutMs?: number; pruneOversized?: boolean } = {},+ ): Promise<SnapshotResult | null> {+ const cfg = this.options.snapshot;+ if (!cfg || !this.isRunning) return null;+ try {+ const r = await this.enqueueRequest(+ {+ type: "snapshot",+ path: cfg.path,+ manifest_path: cfg.manifestPath,+ max_bytes: cfg.maxBytes ?? DEFAULT_SNAPSHOT_MAX_BYTES,+ max_variable_bytes: cfg.maxVariableBytes ?? DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES,+ prune_oversized: options.pruneOversized ?? false,+ },+ "",+ { internal: true },+ options.executionTimeoutMs,+ );+ if (r.status !== "ok" || !r.doneFields) {+ this.appendKernelDiagnostic(+ `state snapshot ${r.status === "aborted" ? "timed out" : "failed"}: ${r.error?.evalue ?? r.stderr}`,+ );+ return null;+ }+ const pruned = asStringArray(r.doneFields.pruned);+ return {+ saved: asStringArray(r.doneFields.saved),+ skipped: asReasonArray(r.doneFields.skipped),+ pruned: pruned.length > 0 ? pruned : undefined,+ bytes: typeof r.doneFields.bytes === "number" ? r.doneFields.bytes : 0,+ path: cfg.path,+ };+ } catch (error) {+ this.appendKernelDiagnostic(`state snapshot error: ${errorMessage(error)}`);+ return null;+ }+ }++ /**+ * Revive a previously snapshotted namespace into the kernel. Call right after+ * start() and before the runtime bootstrap, which then refreshes live handles+ * (rlm, skills) over anything restored. Never throws.+ */+ async restoreState(): Promise<RestoreResult | null> {+ const cfg = this.options.snapshot;+ if (!cfg) return null;+ try {+ const r = await this.enqueueRequest({ type: "restore", path: cfg.path }, "", { internal: true });+ if (r.status !== "ok" || !r.doneFields) {+ this.appendKernelDiagnostic(`state restore failed: ${r.error?.evalue ?? r.stderr}`);+ return null;+ }+ return {+ restored: asStringArray(r.doneFields.restored),+ failed: asReasonArray(r.doneFields.failed),+ path: cfg.path,+ };+ } catch (error) {+ this.appendKernelDiagnostic(`state restore error: ${errorMessage(error)}`);+ return null;+ }+ }++ /** Live user-defined top-level names, or null if the kernel isn't running. Never throws. */+ async listNamespaceNames(signal?: AbortSignal): Promise<string[] | null> {+ if (!this.isRunning) return null;+ try {+ const r = await this.enqueueRequest({ type: "list_names" }, "", { internal: true, signal });+ if (r.status !== "ok" || !r.doneFields) {+ this.appendKernelDiagnostic(`namespace listing failed: ${r.error?.evalue ?? r.stderr}`);+ return null;+ }+ return asStringArray(r.doneFields.names);+ } catch (error) {+ this.appendKernelDiagnostic(`namespace listing error: ${errorMessage(error)}`);+ return null;+ }+ }++ private scheduleSnapshot(): void {+ const cfg = this.options.snapshot;+ if (!cfg) return;+ if (this.snapshotTimer) clearTimeout(this.snapshotTimer);+ this.snapshotTimer = globalThis.setTimeout(() => {+ this.snapshotTimer = undefined;+ void this.captureSnapshot({ executionTimeoutMs: SNAPSHOT_EXECUTION_TIMEOUT_MS });+ }, cfg.debounceMs ?? DEFAULT_SNAPSHOT_DEBOUNCE_MS);+ if (this.snapshotTimer && typeof this.snapshotTimer === "object" && "unref" in this.snapshotTimer) {+ this.snapshotTimer.unref();+ }+ }++ private clearSnapshotTimer(): void {+ if (this.snapshotTimer) {+ clearTimeout(this.snapshotTimer);+ this.snapshotTimer = undefined;+ }+ }++ /** Best-effort final snapshot before a graceful dispose, bounded by a timeout. */+ private async flushSnapshotForDispose(): Promise<void> {+ if (!this.options.snapshot || !this.isRunning) return;+ let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;+ const guard = new Promise<void>((resolve) => {+ timeout = globalThis.setTimeout(resolve, SNAPSHOT_DISPOSE_TIMEOUT_MS);+ if (timeout && typeof timeout === "object" && "unref" in timeout) timeout.unref();+ });+ try {+ await Promise.race([this.snapshotState().then(() => undefined), guard]);+ } finally {+ if (timeout) clearTimeout(timeout);+ }+ }++ /** Graceful cleanup. Waits briefly for in-flight host request handlers before killing the child. */+ dispose(): Promise<void> {+ return (async () => {+ // Captured before any await: teardowns and newer starts bump the counter.+ const generation = this.startGeneration;+ // Final namespace flush while the kernel is still live (session end / reload).+ await this.flushSnapshotForDispose();+ if (this.startStale(generation)) return; // superseded mid-flush: the newer owner already cleaned this kernel+ this.state = "shutdown";+ liveKernels.delete(this);+ // Claim the teardown so the child's exit handler does not run+ // cleanupResources mid-dispose (same contract as shutdown()).+ this.gracefulShutdownGeneration = generation;+ const inFlightHostRequests = [...this.inFlightHostRequests];+ try {+ if (inFlightHostRequests.length > 0) {+ await this.waitForHostRequestsToSettle(inFlightHostRequests, HOST_REQUEST_DISPOSE_TIMEOUT_MS);+ }+ if (!this.startStale(generation)) {+ // Bounded protocol shutdown first: the runtime's shutdown branch+ // closes MCP servers and kills live bash() process groups, which+ // a bare hard-kill would leak until the orphan reaper runs.+ await this.requestProtocolShutdown(KERNEL_SHUTDOWN_TIMEOUT_MS);+ }+ } finally {+ if (this.gracefulShutdownGeneration === generation) this.gracefulShutdownGeneration = undefined;+ if (!this.startStale(generation)) this.cleanupResources(); // else: superseded, the newer owner already cleaned+ }+ })();+ }++ /** Best-effort bounded protocol shutdown; the caller's hard kill remains the backstop. */+ private async requestProtocolShutdown(timeoutMs: number): Promise<void> {+ const stdin = this.child?.stdin;+ if (!stdin || stdin.destroyed) return;+ const requestId = uuid();+ let timer: ReturnType<typeof globalThis.setTimeout> | undefined;+ try {+ const doneReply = new Promise<void>((resolve) => {+ this.pendingDoneWaiters.set(requestId, resolve);+ });+ const send = this.writeLine({ type: "shutdown", id: requestId });+ send.catch(() => undefined);+ const kernelExit = this.waitForKernelExit();+ const deadline = new Promise<void>((resolve) => {+ timer = globalThis.setTimeout(resolve, timeoutMs);+ timer.unref?.();+ });+ const gracefulReply = Promise.all([send, doneReply]).then(() => undefined);+ gracefulReply.catch(() => undefined);+ await Promise.race([gracefulReply, kernelExit, deadline]);+ await Promise.race([kernelExit, deadline]);+ } catch {+ // Best-effort: cleanupResources still hard-kills the child.+ } finally {+ if (timer) globalThis.clearTimeout(timer);+ this.pendingDoneWaiters.delete(requestId);+ }+ }++ /** Synchronous best-effort cleanup. Safe to call from `process.on('exit')`. */+ disposeSync(): void {+ this.state = "shutdown";+ liveKernels.delete(this);+ this.cleanupResources();+ }++ get isRunning(): boolean {+ return this.state === "running";+ }+}diff --git a/packages/coding-agent/src/core/kernel/shared.ts b/packages/coding-agent/src/core/kernel/shared.tsnew file mode 100644index 0000000000..bdaec97126--- /dev/null+++ b/packages/coding-agent/src/core/kernel/shared.ts@@ -0,0 +1,401 @@+import { registerSessionResourceCleanup } from "@earendil-works/pi-ai";+import type { KernelBootstrapProgressHandler, KernelPythonSkill } from "./bootstrap.js";+import type { RestoreResult, SnapshotResult } from "./state-snapshot.js";++export const DEFAULT_MAX_OUTPUT_CHARS = 65536;+export const HOST_REQUEST_DISPOSE_TIMEOUT_MS = 5000;+export const KERNEL_SHUTDOWN_TIMEOUT_MS = 5000;+export const DEFAULT_SNAPSHOT_DEBOUNCE_MS = 1500;+// Cap how long a graceful dispose waits on the final snapshot; the debounced+// on-disk copy is the fallback if this is exceeded.+export const SNAPSHOT_DISPOSE_TIMEOUT_MS = 5000;+export const SNAPSHOT_EXECUTION_TIMEOUT_MS = 5000;+export const KERNEL_ABORT_GRACE_MS = 1000;+export const KERNEL_BUSY_REUSE_WAIT_MS = 5000;+export const KERNEL_BUSY_INTERRUPT_INTERVAL_MS = 500;+export const MAX_LATE_SENT_AGENT_MESSAGE_HANDLERS = 256;+const KERNEL_BUSY_AFTER_INTERRUPT_MESSAGE =+ "The Python kernel is still running the previously interrupted cell. Wait and try again, or kill the kernel to start fresh.";++export class KernelBusyAfterInterruptError extends Error {+ constructor() {+ super(KERNEL_BUSY_AFTER_INTERRUPT_MESSAGE);+ this.name = "KernelBusyAfterInterruptError";+ }+}++/**+ * Handles one typed request from Python code running in the kernel.+ * The returned record is sent back verbatim as the reply payload.+ *+ * The unary form is the dispatcher and registration contract; context-aware+ * handlers are declared separately below.+ */+export type HostRequestHandler = (payload: Record<string, unknown>) => Promise<Record<string, unknown>>;++/**+ * Per-call authority supplied by the host-request dispatcher.+ * `requestId` is an opaque host-minted correlation token and `isCurrent()`+ * lets an implementation reject work after its authority is revoked.+ */+export interface HostRequestContext {+ readonly requestId: string;+ readonly generation: number;+ readonly signal: AbortSignal;+ isCurrent(): boolean;+}++const hostRequestHandlerBrand = Symbol("hostRequestHandler");++/** A context-aware implementation that must receive dispatcher authority. */+export type HostRequestHandlerImplementation = (+ payload: Record<string, unknown>,+ context: HostRequestContext,+) => Promise<Record<string, unknown>>;++/** A factory-minted, context-aware host-request handler capability. */+type HostRequestHandlerCapability = HostRequestHandlerImplementation & { readonly [hostRequestHandlerBrand]: true };++/** Runtime provenance cannot be recreated by copying the nominal symbol property. */+const factoryCreatedHostRequestHandlers = new WeakSet<object>();++function assertGenuineHostRequestContext(context: unknown): asserts context is HostRequestContext {+ if (+ typeof context !== "object" ||+ context === null ||+ typeof (context as HostRequestContext).requestId !== "string" ||+ !(context as HostRequestContext).requestId ||+ !Number.isSafeInteger((context as HostRequestContext).generation) ||+ typeof (context as HostRequestContext).isCurrent !== "function" ||+ typeof (context as HostRequestContext).signal !== "object" ||+ (context as HostRequestContext).signal === null ||+ typeof (context as HostRequestContext).signal.aborted !== "boolean" ||+ typeof (context as HostRequestContext).signal.addEventListener !== "function"+ ) {+ throw new Error("host request context is invalid");+ }+}++/**+ * Creates a branded wrapper rather than mutating its implementation. Both its+ * generic shape and runtime arity reject unary callbacks before they can run.+ */+export function createHostRequestHandler<T extends HostRequestHandlerImplementation>(+ implementation: T,+ ..._unaryRejection: Parameters<T> extends [unknown, unknown, ...unknown[]]+ ? []+ : ["host request handlers must accept payload and context"]+): HostRequestHandlerCapability {+ if (implementation.length < 2) throw new Error("host request handlers must accept payload and context");+ const handler = async (payload: Record<string, unknown>, context: HostRequestContext) => {+ assertGenuineHostRequestContext(context);+ return implementation(payload, context);+ };+ factoryCreatedHostRequestHandlers.add(handler);+ return Object.defineProperty(handler, hostRequestHandlerBrand, { value: true }) as HostRequestHandlerCapability;+}++/** Reject copied-symbol and raw-function forgeries before they observe authenticated payloads. */+export function assertHostRequestHandler(value: unknown): asserts value is HostRequestHandlerCapability {+ if (+ typeof value !== "function" ||+ (value as Partial<HostRequestHandlerCapability>)[hostRequestHandlerBrand] !== true ||+ !factoryCreatedHostRequestHandlers.has(value)+ ) {+ throw new Error("host request handler is not a dispatcher-created capability");+ }+}++/** Host request handlers keyed by request type (e.g. "rlm.run", "goal.complete"). */+export type HostRequestHandlers = Record<string, HostRequestHandler>;++/** Where and how to persist the kernel's user namespace so it survives resume. */+export interface KernelSnapshotConfig {+ /** Absolute path for the dill payload. */+ path: string;+ /** Absolute path for the JSON manifest written alongside the payload. */+ manifestPath: string;+ /** Maximum aggregate snapshot size. Default 256 MiB. */+ maxBytes?: number;+ /** Maximum serialized size of one variable. Default 16 MiB. */+ maxVariableBytes?: number;+ /** Debounce window for the auto-snapshot after a successful execution. Default 1500 ms. */+ debounceMs?: number;+}++export interface KernelManagerOptions {+ /** Python interpreter with the kernel runtime available. Defaults to the auto-bootstrapped kernel. */+ python?: string;+ cwd?: string;+ env?: Record<string, string>;+ sessionId?: string;+ hostHandlers?: HostRequestHandlers;+ pythonSkills?: readonly KernelPythonSkill[];+ /** Persist/revive the user namespace across kernel restarts and session resume. */+ snapshot?: KernelSnapshotConfig;+}++export interface KernelStartOptions {+ onBootstrapProgress?: KernelBootstrapProgressHandler;+ signal?: AbortSignal;+}++export interface ExecuteOptions {+ /** Aborting interrupts the kernel out-of-band. */+ signal?: AbortSignal;+ onStream?: (chunk: string, name: "stdout" | "stderr") => void;+ onLateSentAgentMessage?: (message: KernelSentAgentMessage) => void;+ /** Cap stdout / stderr / result at this many characters. Default 65536. */+ maxOutputChars?: number;+ /** Synthetic host cell (snapshot/restore/list); excluded from lastCellCode attribution. */+ internal?: boolean;+}++/** MIME tag the `edit` skill emits diff payloads under. */+export const DIFF_DISPLAY_MIME = "application/vnd.prime-agent.diff+json";++/** MIME tag the `attach-image` skill emits media payloads under. */+export const ATTACHMENT_DISPLAY_MIME = "application/vnd.prime-agent.attachment+json";++/** MIME tag the `agent-message` skill emits after sending a message. */+export const AGENT_MESSAGE_DISPLAY_MIME = "application/vnd.prime-agent.agent-message+json";++/**+ * Hard ceiling on a single attachment's base64 payload, a defensive guard+ * against a runaway direct display emit. The `attach-image` skill caps+ * its own images well under this (see `_MAX_IMAGE_BYTES`), so a skill-produced+ * attachment is never dropped here — only a non-skill emit can hit this.+ */+export const MAX_ATTACHMENT_DATA_CHARS = 10_000_000;++/** One file edit, captured from a {@link DIFF_DISPLAY_MIME} display payload. */+export interface KernelDiffDisplay {+ path: string;+ oldStr: string;+ newStr: string;+ /** 1-based line where `oldStr` begins in the file, for absolute line numbers. */+ startLine?: number;+}++/** One media attachment, captured from an {@link ATTACHMENT_DISPLAY_MIME} display payload. */+export interface KernelAttachment {+ mimeType: string;+ /** base64-encoded bytes. */+ data: string;+ /** Source path, surfaced to the TUI renderer. */+ path?: string;+}++export interface KernelSentAgentMessage {+ id: string;+ message: string;+ deliveryStatus: "delivered" | "queued";+ receiverRole?: "parent" | "sibling" | "child";+ target: {+ activeSessionId: string;+ sessionId: string;+ sessionName?: string;+ };+}++export interface ExecuteResult {+ stdout: string;+ stderr: string;+ /** Text of the cell's trailing expression value, if the cell produced one. */+ result?: string;+ /** Diffs emitted via display events, in order. */+ diffs?: KernelDiffDisplay[];+ /** Media attachments emitted via display events, in order. */+ attachments?: KernelAttachment[];+ /** Agent messages sent from this cell, in order. */+ sentAgentMessages?: KernelSentAgentMessage[];+ /** Output that arrived without this cell's id (user threads, other cells' leftovers, raw fd writes). */+ backgroundOutput?: string;+ status: "ok" | "error" | "aborted";+ error?: { ename: string; evalue: string; traceback: string[] };+ durationMs: number;+}++/** Parse a {@link DIFF_DISPLAY_MIME} payload, tolerating malformed input. */+export function parseDiffDisplay(payload: unknown): KernelDiffDisplay | undefined {+ if (!isRecord(payload)) {+ return undefined;+ }+ const { path, old_str: oldStr, new_str: newStr, start_line: startLine } = payload;+ if (typeof path !== "string" || typeof oldStr !== "string" || typeof newStr !== "string") {+ return undefined;+ }+ return { path, oldStr, newStr, startLine: typeof startLine === "number" ? startLine : undefined };+}++/**+ * Parse an {@link ATTACHMENT_DISPLAY_MIME} payload. Malformed payloads are+ * tolerantly ignored (`undefined`); a well-formed payload exceeding+ * {@link MAX_ATTACHMENT_DATA_CHARS} is reported as `"oversized"` so the caller+ * can fail the cell loudly rather than silently dropping the image.+ */+export function parseAttachmentDisplay(payload: unknown): KernelAttachment | "oversized" | undefined {+ if (!isRecord(payload)) {+ return undefined;+ }+ const { mime_type: mimeType, data, path } = payload;+ if (typeof mimeType !== "string" || typeof data !== "string") {+ return undefined;+ }+ if (data.length > MAX_ATTACHMENT_DATA_CHARS) {+ return "oversized";+ }+ return { mimeType, data, path: typeof path === "string" ? path : undefined };+}++export function parseSentAgentMessage(payload: unknown): KernelSentAgentMessage | undefined {+ if (!isRecord(payload) || !isRecord(payload.target)) {+ return undefined;+ }+ const { id, message, deliveryStatus, receiverRole, target } = payload;+ const { activeSessionId, sessionId, sessionName } = target;+ if (+ typeof id !== "string" ||+ typeof message !== "string" ||+ (deliveryStatus !== "delivered" && deliveryStatus !== "queued") ||+ typeof activeSessionId !== "string" ||+ typeof sessionId !== "string"+ ) {+ return undefined;+ }+ return {+ id,+ message,+ deliveryStatus,+ ...(receiverRole === "parent" || receiverRole === "sibling" || receiverRole === "child" ? { receiverRole } : {}),+ target: {+ activeSessionId,+ sessionId,+ ...(typeof sessionName === "string" ? { sessionName } : {}),+ },+ };+}++export function createKernelStartupAbortError(): Error {+ return new Error("Kernel startup aborted");+}++export function raceStartupWithAbort<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {+ if (!signal) {+ return promise;+ }+ if (signal.aborted) {+ return Promise.reject(createKernelStartupAbortError());+ }+ return new Promise<T>((resolve, reject) => {+ let settled = false;+ const cleanup = () => signal.removeEventListener("abort", abort);+ const abort = () => {+ if (settled) {+ return;+ }+ settled = true;+ cleanup();+ reject(createKernelStartupAbortError());+ };+ signal.addEventListener("abort", abort, { once: true });+ promise.then(+ (value) => {+ if (settled) {+ return;+ }+ settled = true;+ cleanup();+ resolve(value);+ },+ (error: unknown) => {+ if (settled) {+ return;+ }+ settled = true;+ cleanup();+ reject(error);+ },+ );+ });+}++export interface Deferred<T> {+ promise: Promise<T>;+ resolve: (value: T) => void;+ reject: (error: Error) => void;+}++export function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++export function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++export function createDeferred<T>(): Deferred<T> {+ let resolve!: (value: T) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<T>((promiseResolve, promiseReject) => {+ resolve = promiseResolve;+ reject = promiseReject;+ });+ return { promise, resolve, reject };+}++/** Public surface every kernel client exposes to the provisioner and session layer. */+export interface KernelClient {+ readonly ownerSessionId: string | undefined;+ readonly isRunning: boolean;+ start(options?: KernelStartOptions): Promise<void>;+ execute(code: string, opts?: ExecuteOptions): Promise<ExecuteResult>;+ shutdown(opts?: { snapshot?: boolean }): Promise<boolean>;+ restart(): Promise<void>;+ kill(): Promise<void>;+ dispose(): Promise<void>;+ disposeSync(): void;+ snapshotState(): Promise<SnapshotResult | null>;+ pruneOversizedVariables(): Promise<SnapshotResult | null>;+ restoreState(): Promise<RestoreResult | null>;+ listNamespaceNames(signal?: AbortSignal): Promise<string[] | null>;+}++// One registry serves every client kind; two parallel registries would+// double-install process signal handlers.+export const liveKernels = new Set<KernelClient>();+let signalHandlersInstalled = false;++registerSessionResourceCleanup((sessionId) => {+ for (const k of liveKernels) {+ if (!sessionId || k.ownerSessionId === sessionId) {+ void k.dispose();+ }+ }+});++export function installSignalHandlersOnce(): void {+ if (signalHandlersInstalled) return;+ signalHandlersInstalled = true;++ const asyncShutdown = async (): Promise<void> => {+ // These paths can await, so flush the namespace snapshot before tearing down.+ await Promise.allSettled([...liveKernels].map((k) => k.shutdown({ snapshot: true })));+ };++ // `beforeExit` and signal handlers can await async cleanup. `exit`+ // can only do sync work (Node won't run pending microtasks past it),+ // so it falls back to `disposeSync()` which kills the child synchronously.+ process.on("beforeExit", () => {+ void asyncShutdown();+ });+ process.on("SIGINT", () => {+ void asyncShutdown().finally(() => process.exit(130));+ });+ process.on("SIGTERM", () => {+ void asyncShutdown().finally(() => process.exit(143));+ });+ process.on("exit", () => {+ for (const k of liveKernels) k.disposeSync();+ });+}diff --git a/packages/coding-agent/src/core/kernel/state-snapshot.ts b/packages/coding-agent/src/core/kernel/state-snapshot.tsindex 5da948e132..61a7972620 100644--- a/packages/coding-agent/src/core/kernel/state-snapshot.ts+++ b/packages/coding-agent/src/core/kernel/state-snapshot.ts@@ -1,6 +1,7 @@-// Serialize the IPython kernel's user namespace so it can be revived when a-// session resumes. The kernel is otherwise spawned fresh on resume, leaving the-// model believing it still has access to variables/imports it defined earlier.+// Locations and result shapes for the kernel's persisted user namespace, which+// is revived when a session resumes. The kernel is otherwise spawned fresh on+// resume, leaving the model believing it still has access to variables/imports+// it defined earlier.//// Snapshotting is best-effort and per-variable: each top-level name is pickled// with `dill` independently, so a single unpicklable object (open file, socket,@@ -15,9 +16,6 @@ export const DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES = 16 * 1024 * 1024;/** Base filename for the kernel snapshot within a session's artifact directory. */const KERNEL_STATE_BASENAME = "kernel-state";-/** Marker the Python helpers print so the host can recover the JSON result line. */-const RESULT_MARKER = "__PRIME_AGENT_KERNEL_STATE__";-export interface SnapshotResult {/** Top-level names successfully serialized into the payload. */saved: string[];@@ -47,311 +45,3 @@ export function snapshotPathIn(artifactDir: string): string {export function manifestPathIn(artifactDir: string): string {return join(artifactDir, `${KERNEL_STATE_BASENAME}.json`);}--/** Render a JS string as a Python string literal (JSON's escaping is a valid subset). */-function pyStr(value: string): string {- return JSON.stringify(value);-}--/**- * Python that serializes the user namespace to `outPath` (atomic write) and a- * sibling `.json` manifest, then prints a single marker line with the result.- */-export function buildSnapshotCode(- outPath: string,- manifestPath: string,- maxBytes: number,- maxVariableBytes = DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES,- pruneOversized = false,-): string {- // All builtins are sourced via the locally-imported _b alias so the helper keeps- // working even when the user namespace shadows names like list/open/print/len.- return `-def _prime_agent_snapshot_state():- import builtins as _b, io, json, os, sys, datetime- try:- import dill- except _b.Exception as _err:- _b.print(${pyStr(RESULT_MARKER)} + json.dumps({"error": "dill unavailable: " + _b.str(_err)}))- return- dill.settings["recurse"] = True-- ip = None- try:- ip = get_ipython() # noqa: F821 (injected by IPython)- except _b.Exception:- ip = None- ns = ip.user_ns if ip is not None else _b.globals()- hidden = _b.set(_b.getattr(ip, "user_ns_hidden", {}) or {}) if ip is not None else _b.set()- # rlm, mcp, bash, and asyncio are re-created by the kernel bootstrap on- # every start; never snapshot them.- always_skip = {"rlm", "mcp", "bash", "asyncio", "In", "Out", "get_ipython", "exit", "quit", "open"}-- class SnapshotSizeLimitExceeded(_b.Exception):- pass-- class SnapshotBuffer(io.BytesIO):- def __init__(self, limit):- io.BytesIO.__init__(self)- self.limit = limit-- def write(self, chunk):- if self.tell() + _b.len(chunk) > self.limit:- raise SnapshotSizeLimitExceeded()- return io.BytesIO.write(self, chunk)-- payload = {}- skipped = []- oversized = []- total = 0- identify_oversized = ${pruneOversized ? "True" : "False"}- for name in _b.list(ns.keys()):- # Skip internals (dunder/underscore), IPython-injected names, and live- # handles. A name matching a builtin (e.g. "list") is a user shadow worth- # keeping — builtins themselves are not enumerated as user_ns keys.- if name.startswith("_") or name in hidden or name in always_skip:- continue- value = ns[name]- remaining = ${maxBytes} - total- buffer_limit = ${maxVariableBytes} if identify_oversized else _b.min(${maxVariableBytes}, remaining)- buffer = SnapshotBuffer(buffer_limit)- # Modules are pickled by reference and re-imported on restore.- try:- dill.dump(value, buffer)- blob = buffer.getvalue()- except SnapshotSizeLimitExceeded:- if not identify_oversized and remaining < ${maxVariableBytes}:- skipped.append({"name": name, "reason": "exceeds aggregate snapshot size cap"})- else:- skipped.append({"name": name, "reason": "exceeds per-variable snapshot size cap"})- oversized.append(name)- continue- except _b.Exception as _err:- skipped.append({"name": name, "reason": _b.type(_err).__name__ + ": " + _b.str(_err)[:200]})- continue- if total + _b.len(blob) > ${maxBytes}:- skipped.append({"name": name, "reason": "exceeds aggregate snapshot size cap"})- continue- payload[name] = blob- total += _b.len(blob)-- os.makedirs(os.path.dirname(${pyStr(outPath)}), exist_ok=True)- tmp = ${pyStr(outPath)} + ".tmp"- try:- with _b.open(tmp, "wb") as fh:- dill.dump(payload, fh)- os.replace(tmp, ${pyStr(outPath)})- except _b.Exception as _err:- try:- os.remove(tmp)- except _b.Exception:- pass- _b.print(${pyStr(RESULT_MARKER)} + json.dumps({"error": "write failed: " + _b.str(_err)}))- return-- bytes_written = os.path.getsize(${pyStr(outPath)})- saved = _b.sorted(payload.keys())- pruned = _b.sorted(name for name in oversized if name in ns) if ${pruneOversized ? "True" : "False"} else []- manifest = {- "version": 1,- "savedNames": saved,- "skipped": skipped,- "pruned": pruned,- "bytes": bytes_written,- "pythonVersion": sys.version.split()[0],- "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),- }- try:- with _b.open(${pyStr(manifestPath)}, "w") as fh:- json.dump(manifest, fh)- except _b.Exception:- pass- pruned_ids = {_b.id(ns[name]) for name in pruned}- while True:- try:- for name in pruned:- if name in ns:- del ns[name]- output_cache = ns.get("Out")- if _b.isinstance(output_cache, _b.dict):- for key in _b.list(output_cache.keys()):- if _b.id(output_cache[key]) in pruned_ids:- del output_cache[key]- for name in hidden:- if name in ns and _b.id(ns[name]) in pruned_ids:- del ns[name]- break- except _b.KeyboardInterrupt:- # Deletion is idempotent. Finish the short critical section so a- # snapshot timeout cannot leave only some purge candidates live.- continue- _b.print(${pyStr(RESULT_MARKER)} + json.dumps({"saved": saved, "skipped": skipped, "pruned": pruned, "bytes": bytes_written}))---try:- _prime_agent_snapshot_state()-finally:- del _prime_agent_snapshot_state-`.trim();-}--/**- * Python that loads the payload at `inPath` (if present) into the user namespace,- * reviving each name independently, then prints a single marker line with the result.- * Tolerant of a missing or corrupt file: reports an empty restore, never raises.- */-export function buildRestoreCode(inPath: string): string {- // Builtins via the local _b alias so a shadowed name in the user namespace- // (list/open/print/…) can't break the restore path.- return `-def _prime_agent_restore_state():- import builtins as _b, json, os, sys- if not os.path.exists(${pyStr(inPath)}):- _b.print(${pyStr(RESULT_MARKER)} + json.dumps({"restored": [], "failed": []}))- return- try:- import dill- except _b.Exception as _err:- _b.print(${pyStr(RESULT_MARKER)} + json.dumps({"restored": [], "failed": [], "error": "dill unavailable: " + _b.str(_err)}))- return-- try:- with _b.open(${pyStr(inPath)}, "rb") as fh:- payload = dill.load(fh)- except _b.Exception as _err:- _b.print(${pyStr(RESULT_MARKER)} + json.dumps({"restored": [], "failed": [], "error": "load failed: " + _b.str(_err)}))- return- if not _b.isinstance(payload, _b.dict):- _b.print(${pyStr(RESULT_MARKER)} + json.dumps({"restored": [], "failed": [], "error": "corrupt snapshot: not a dict"}))- return-- ip = None- try:- ip = get_ipython() # noqa: F821- except _b.Exception:- ip = None- ns = ip.user_ns if ip is not None else _b.globals()-- restored = []- failed = []- for name, blob in payload.items():- try:- ns[name] = dill.loads(blob)- restored.append(name)- except _b.Exception as _err:- failed.append({"name": name, "reason": _b.type(_err).__name__ + ": " + _b.str(_err)[:200]})- _b.print(${pyStr(RESULT_MARKER)} + json.dumps({"restored": _b.sorted(restored), "failed": failed}))---try:- _prime_agent_restore_state()-finally:- del _prime_agent_restore_state-`.trim();-}--/** Marker-line list of live user-defined names, filtered like the snapshot. Never raises. */-export function buildListNamesCode(): string {- return `-def _prime_agent_list_state_names():- import builtins as _b, json- ip = None- try:- ip = get_ipython() # noqa: F821 (injected by IPython)- except _b.Exception:- ip = None- ns = ip.user_ns if ip is not None else _b.globals()- hidden = _b.set(_b.getattr(ip, "user_ns_hidden", {}) or {}) if ip is not None else _b.set()- always_skip = {"rlm", "mcp", "bash", "asyncio", "In", "Out", "get_ipython", "exit", "quit", "open"}- names = []- for name in _b.list(ns.keys()):- if name.startswith("_") or name in hidden or name in always_skip:- continue- names.append(name)- _b.print(${pyStr(RESULT_MARKER)} + json.dumps({"names": _b.sorted(names)}))---try:- _prime_agent_list_state_names()-finally:- del _prime_agent_list_state_names-`.trim();-}--interface RawListNames {- names?: unknown;- error?: unknown;-}--interface RawSnapshot {- saved?: unknown;- skipped?: unknown;- pruned?: unknown;- bytes?: unknown;- error?: unknown;-}--interface RawRestore {- restored?: unknown;- failed?: unknown;- error?: unknown;-}--function asStringArray(value: unknown): string[] {- return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : [];-}--function asReasonArray(value: unknown): { name: string; reason: string }[] {- if (!Array.isArray(value)) return [];- return value.flatMap((entry) => {- if (entry && typeof entry === "object" && typeof (entry as { name?: unknown }).name === "string") {- const { name, reason } = entry as { name: string; reason?: unknown };- return [{ name, reason: typeof reason === "string" ? reason : "" }];- }- return [];- });-}--/** Pull the marker line out of cell stdout and parse it, or null if absent/invalid. */-function parseMarkerLine<T>(stdout: string): T | null {- const index = stdout.lastIndexOf(RESULT_MARKER);- if (index === -1) return null;- const rest = stdout.slice(index + RESULT_MARKER.length);- const line = rest.split("\n", 1)[0]?.trim();- if (!line) return null;- try {- return JSON.parse(line) as T;- } catch {- return null;- }-}--export function parseSnapshotResult(stdout: string, path: string): SnapshotResult | null {- const raw = parseMarkerLine<RawSnapshot>(stdout);- if (!raw || raw.error) return null;- const pruned = asStringArray(raw.pruned);- return {- saved: asStringArray(raw.saved),- skipped: asReasonArray(raw.skipped),- pruned: pruned.length > 0 ? pruned : undefined,- bytes: typeof raw.bytes === "number" ? raw.bytes : 0,- path,- };-}--export function parseRestoreResult(stdout: string, path: string): RestoreResult | null {- const raw = parseMarkerLine<RawRestore>(stdout);- if (!raw || raw.error) return null;- return {- restored: asStringArray(raw.restored),- failed: asReasonArray(raw.failed),- path,- };-}--/** Sorted list of live user-defined names, or null if the marker was absent/invalid. */-export function parseListNamesResult(stdout: string): string[] | null {- const raw = parseMarkerLine<RawListNames>(stdout);- if (!raw || raw.error) return null;- return asStringArray(raw.names);-}diff --git a/packages/coding-agent/src/core/prompts/rlm.ts b/packages/coding-agent/src/core/prompts/rlm.tsindex c4e619306c..d5d13ba374 100644--- a/packages/coding-agent/src/core/prompts/rlm.ts+++ b/packages/coding-agent/src/core/prompts/rlm.ts@@ -27,26 +27,26 @@ const SIMPLIFIED_TECHNICAL_ENGLISH_PROMPT = ["Treat this as clarity guidance, not a claim of formal ASD-STE100 compliance. Preserve a user-requested format, tone, terminology, and necessary precision.",].join("\n");-const IPYTHON_CONTROL_PROMPT = [- "IPython is the agent's long-lived notebook: a persistent control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.",+const REPL_CONTROL_PROMPT = [+ "The `ipython` tool is a persistent Python REPL — the agent's long-lived control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Top-level `await` works directly. Use it to keep intermediate variables, inspect and transform outputs, and write small helper functions. Compaction removes individual variables whose serialized form exceeds 16 MiB; keep large source data on disk and reload it when needed.","",- "Do not assume IPython is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use IPython to coordinate the process and analyze what comes back.",+ "Python is the orchestration language: use Python for loops, conditionals, parsing, and state. Use `bash()` to invoke programs, not to write shell programs — no shell loops or heredocs; do those in Python.","",- "When running shell commands from IPython, use `%%bash` cells. If you use `%%bash`, it must be the first line of the code cell: no comments, spaces, blank lines, imports, or Python statements before it. Avoid `!cmd` shell escapes for project commands so shell behavior is explicit and multi-line commands share one shell context.",+ "Do not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.","",- "`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working; `%%bash` remains the way to run quick inline shell with cell-visible output.",+ "`bash(command)` starts a shell command in the background and returns a handle immediately: `h = bash('npm test')`. Use `h.pid` / `h.running` for liveness, `h.tail(n)` / `h.output()` for combined stdout+stderr so far, `h.poll()` for a non-blocking result, `h.kill()` to terminate (SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive), and `await h` (or `await bash('cmd')`) for the completed result with exit_code, output, and duration. Prefer bash() for long-running commands so the turn keeps working.","",- "Important: do not install dependencies into the IPython kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.",+ "Important: do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Treat failures from that native environment as the relevant result.","","Use Python for reading, searching, and editing files — it gives you reusable variables you can slice, filter, and act on without re-reading. Always assign read/search results to named variables so you can revisit them later.","",- "Each `%%bash` cell runs in a throw-away subshell, so shell-level state (`cd`, `export`, `source`, shell variables) does NOT carry to later cells. Keep dependent shell steps inside one `%%bash` cell when they need shared shell state, or use kernel-level equivalents that survive across calls: `%cd <dir>` for the working directory and `os.environ['VAR'] = '...'` (or `%env VAR=...`) for environment variables — these apply to all subsequent `%%bash` calls.",+ "Each `bash()` call is its own process, so shell state does not persist between calls; use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables — both persist in the REPL and apply to later `bash()` calls.","",- "Python state in the kernel, by contrast, persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.",+ "Python state in the kernel persists across cells: named variables, helper functions, classes, imports, notes, parsed outputs, and helper data structures all remain available in every later turn. Tool calls are themselves Python `await` expressions, so their return values can be bound to variables and composed into program logic just like any other call.","","Continual harness state is available as `rlm.harness` and `rlm.get_harness_state()`. CRUD calls are local to this Prime Agent session by default: `rlm.harness.create_memory(...)`, `rlm.harness.update_memory(...)`, `rlm.harness.delete_memory(...)`, `rlm.harness.create_skill(...)`, `rlm.harness.update_skill(...)`, `rlm.harness.delete_skill(...)`, `rlm.harness.create_subagent(...)`, `rlm.harness.update_subagent(...)`, `rlm.harness.delete_subagent(...)`, `rlm.harness.create_prompt_note(...)`, `rlm.harness.update_prompt_note(...)`, `rlm.harness.delete_prompt_note(...)`, plus `rlm.harness.record_refinement(...)` and `rlm.harness.overview()`. Use `global_=True` only for stable cross-session lessons; Python reserves `global`, so literal `global=True` is invalid syntax.","",- "Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, IPython kernel, and native call interface exposed to the model.",+ "Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.","","RLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a reusable delegation spec with `await rlm('sub-task')`; admission returns a child handle immediately. Results arrive only through an available messaging capability or files, never as an `rlm()` return value. Do not invent non-native wrappers such as `call_skill(...)` or `run_subagent(...)`.",].join("\n");@@ -128,7 +128,7 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {}if (hasIpython && installedSkills.includes("edit")) {skillLines.push(- "For targeted existing-file edits, prefer the pre-imported async `edit` skill from IPython: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.",+ "For targeted existing-file edits, prefer the pre-imported async `edit` skill from the REPL: `old = '''...'''; new = '''...'''; await edit(path=\"pkg/file.py\", old_str=old, new_str=new)`. Use exact old/new strings; if the text contains triple double quotes, use triple single-quoted variables or build `old`/`new` from inspected file slices.",);}}@@ -174,7 +174,7 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {}if (hasIpython) {- parts.push("", IPYTHON_CONTROL_PROMPT);+ parts.push("", REPL_CONTROL_PROMPT);if (installedSkills.includes("refine")) {parts.push("",diff --git a/packages/coding-agent/src/core/refinement/refinement.ts b/packages/coding-agent/src/core/refinement/refinement.tsindex 8b0c2d89a0..76cc701556 100644--- a/packages/coding-agent/src/core/refinement/refinement.ts+++ b/packages/coding-agent/src/core/refinement/refinement.ts@@ -129,7 +129,7 @@ The continual harness is the persistent, editable set of prompt notes, memories,skills, and subagent specs that lets Prime Agent improve reusable behavioroutside the token history.Use "continual harness" for that persistent artifact layer; keep "RLM" for the-runtime, IPython kernel, and native call interface that executes those artifacts.+runtime, Python REPL kernel, and native call interface that executes those artifacts.Continual harness components:- prompt: supplemental prompt notes only. The base system prompt is immutable and MUST NOT be rewritten.@@ -455,10 +455,10 @@ export function formatHarnessStateForPrompt(: "When to refine the continual harness: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep continual harness edits small and evidence-backed.","",includeIpythonExamples- ? "Call contract: read each installed Python skill's SKILL.md and call its documented module function in IPython; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm('sub-task')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries."+ ? "Call contract: read each installed Python skill's SKILL.md and call its documented module function in the Python REPL; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Spawn a continual harness subagent spec by composing a concise task prompt and calling `handle = await rlm('sub-task')`; admission returns immediately with `rlm_child_id`, `name`, `session_dir`, and `model`, never the child's answer. Results arrive only through explicit `agent_message` replies or files; children reply with `await agent_message.send(message, receiver_role='parent')`. Use `await rlm.list_subagents()` to recover direct child handles and `await agent_message.send(..., receiver_role='child', receiver_name=handle.name)` for follow-ups. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.": options.includeShellExamples- ? "Call contract: use installed skills as shell commands when available (for example `<skill_import> ...`). Continual harness entries are routing/context hints only in sessions without IPython; do not use Python `await`, `asyncio`, or `rlm` examples unless the prompt also documents an IPython kernel."- : "Call contract: continual harness entries are routing/context hints only in sessions without IPython or shell access; do not use Python `await`, `asyncio`, `rlm`, or shell skill commands unless the prompt also documents those interfaces.",+ ? "Call contract: use installed skills as shell commands when available (for example `<skill_import> ...`). Continual harness entries are routing/context hints only in sessions without the Python REPL; do not use Python `await`, `asyncio`, or `rlm` examples unless the prompt also documents a Python kernel."+ : "Call contract: continual harness entries are routing/context hints only in sessions without the Python REPL or shell access; do not use Python `await`, `asyncio`, `rlm`, or shell skill commands unless the prompt also documents those interfaces.","",];@@ -470,7 +470,7 @@ export function formatHarnessStateForPrompt(totalEntries += entries.length;// Render subagent specs as a task-shaped roster the model can match against — the// analogue of Claude Code's agent-type menu — rather than a bare count. In- // IPython sessions, include the native `rlm` invocation hint.+ // REPL sessions, include the native `rlm` invocation hint.if (kind === "subagent" && entries.length > 0 && includeIpythonExamples) {lines.push(`${kind}: ${entries.length} (invoke a spec by turning it into a concise task prompt and spawning with \`await rlm('<task>')\`; admission returns a child handle, never the answer)`,diff --git a/packages/coding-agent/src/core/rlm-runtime.ts b/packages/coding-agent/src/core/rlm-runtime.tsindex 9ad98857ee..976b7b040d 100644--- a/packages/coding-agent/src/core/rlm-runtime.ts+++ b/packages/coding-agent/src/core/rlm-runtime.ts@@ -233,7 +233,7 @@ export interface CreateRlmSubagentRuntimeOptions {rlmDepth: number;rlmMaxDepth: number;rlmParentNodeId: string;- /** Source of the IPython cell that spawned this subagent, for display. */+ /** Source of the Python cell that spawned this subagent, for display. */spawnCode?: string;/** Publish the session to the parent before a host makes the runtime addressable. */onSessionPublished?: (session: AgentSession) => void;diff --git a/packages/coding-agent/src/core/skills.ts b/packages/coding-agent/src/core/skills.tsindex 9ed0875628..d8b2bd28cf 100644--- a/packages/coding-agent/src/core/skills.ts+++ b/packages/coding-agent/src/core/skills.ts@@ -450,7 +450,7 @@ export function formatSkillsForPrompt(skills: Skill[]): string {const lines = ["\n\nThe following skills provide specialized instructions for specific tasks.","Use ipython to inspect a skill's file when the task matches its description.",- "Skills with a python_import are prepared in the persistent IPython kernel when available and can be called directly by that import name.",+ "Skills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.","When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.","","<available_skills>",diff --git a/packages/coding-agent/src/core/system-prompt.ts b/packages/coding-agent/src/core/system-prompt.tsindex e274a34ef7..a4cc0ec236 100644--- a/packages/coding-agent/src/core/system-prompt.ts+++ b/packages/coding-agent/src/core/system-prompt.ts@@ -186,7 +186,7 @@ function formatGenericMcpGuidance(servers: string[] | undefined): string {return ["# Generic MCP Connections","",- "Generic MCP connections are accessed through the pre-imported Python `mcp` object in IPython, not as top-level native tool namespaces or installed Python skills.",+ "Generic MCP connections are accessed through the pre-imported Python `mcp` object in the Python REPL, not as top-level native tool namespaces or installed Python skills.",`Enabled generic MCP servers: ${enabledServers.map((server) => `\`${server}\``).join(", ")}.`,...enabledServers.map((server) =>diff --git a/packages/coding-agent/src/core/tools/ipython-cell-code.ts b/packages/coding-agent/src/core/tools/ipython-cell-code.tsindex 9dfbfd552d..0dc3c3356a 100644--- a/packages/coding-agent/src/core/tools/ipython-cell-code.ts+++ b/packages/coding-agent/src/core/tools/ipython-cell-code.ts@@ -1,10 +1,6 @@-const BASH_CELL_MAGIC_PATTERN = /^((?:[ \t]*\r?\n)*)([ \t]*)%%bash\b([^\r\n]*)(\r?\n|$)/;+const BASH_CELL_MAGIC_PATTERN = /^(?:[ \t]*\r?\n)*[ \t]*%%bash\b[^\r\n]*(?:\r?\n|$)/;export interface ParsedIpythonBashCell {- leadingWhitespace: string;- indent: string;- magicArguments: string;- lineBreak: string;body: string;}@@ -13,11 +9,5 @@ export function parseIpythonBashCell(code: string): ParsedIpythonBashCell | undeif (!match) {return undefined;}- return {- leadingWhitespace: match[1] ?? "",- indent: match[2] ?? "",- magicArguments: match[3] ?? "",- lineBreak: match[4] ?? "",- body: code.slice(match[0].length),- };+ return { body: code.slice(match[0].length) };}diff --git a/packages/coding-agent/src/core/tools/ipython.ts b/packages/coding-agent/src/core/tools/ipython.tsindex 6ec1eed9ee..50933ea1c2 100644--- a/packages/coding-agent/src/core/tools/ipython.ts+++ b/packages/coding-agent/src/core/tools/ipython.ts@@ -12,41 +12,35 @@ import {type HostRequestHandlers,type KernelAttachment,KernelBusyAfterInterruptError,+ type KernelClient,type KernelDiffDisplay,- KernelManager,type KernelSentAgentMessage,+ ReplKernelManager,} from "../kernel/index.js";import { manifestPathIn, type RestoreResult, snapshotPathIn } from "../kernel/state-snapshot.js";import type { PythonSkillRuntimeInfo } from "../skills.js";-import { parseIpythonBashCell } from "./ipython-cell-code.js";import { wrapToolDefinition } from "./tool-definition-wrapper.js";-const RLM_BOOTSTRAP_BASE_CODE = `+const RLM_BOOTSTRAP_HEADER_CODE = `import asyncioimport os as _prime_agent_os_prime_agent_os.environ["NO_COLOR"] = "1"-get_ipython().colors = "nocolor"--try:- import nest_asyncio as _prime_agent_nest_asyncio- _prime_agent_nest_asyncio.apply()-except Exception:- pass+`.trim();+const RLM_BOOTSTRAP_RUNTIME_CODE = `try:import rlm as _prime_agent_rlm_modulerlm = _prime_agent_rlm_module.rlmbash = _prime_agent_rlm_module.bashimport rlm.mcp as mcp- mcp.install_shutdown_hook()except Exception as _prime_agent_rlm_error:_PRIME_AGENT_RLM_IMPORT_ERROR = str(_prime_agent_rlm_error)class _PrimeAgentMissingRlm:def _raise_missing(self):raise RuntimeError(- "prime-agent-runtime is not installed in this IPython kernel. "+ "prime-agent-runtime is not installed in this kernel. ""Remove ~/.prime/agent/kernel-venv so prime-agent can rebuild it, or set ""PRIME_AGENT_KERNEL_PYTHON to a kernel environment with prime-agent-runtime installed. "f"Import error: {_PRIME_AGENT_RLM_IMPORT_ERROR}"@@ -74,13 +68,14 @@ except Exception as _prime_agent_rlm_error:`.trim();export function buildRlmBootstrapCode(pythonSkills: readonly PythonSkillRuntimeInfo[] = []): string {+ const baseCode = [RLM_BOOTSTRAP_HEADER_CODE, RLM_BOOTSTRAP_RUNTIME_CODE].join("\n\n");const importNames = [...new Set(pythonSkills.map((skill) => skill.importName))];if (importNames.length === 0) {- return RLM_BOOTSTRAP_BASE_CODE;+ return baseCode;}return `-${RLM_BOOTSTRAP_BASE_CODE}+${baseCode}import importlib as _prime_agent_importlibimport inspect as _prime_agent_inspect@@ -102,7 +97,7 @@ class _PrimeAgentUnavailableSkill:async def run(self, *args, **kwargs):raise RuntimeError(- f"Python skill {self.__name__} is unavailable in this IPython kernel. "+ f"Python skill {self.__name__} is unavailable in this kernel. "f"Import error: {self._prime_agent_import_error}")@@ -149,25 +144,25 @@ for _prime_agent_skill_name in ${JSON.stringify(importNames)}:const ipythonSchema = Type.Object({code: Type.String({description:- "Python scratchpad code or `%%bash` shell cells to execute in the agent kernel. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports.",+ "Python code to execute in the persistent Python REPL. Use the target project's own environment for project imports, tests, scripts, CLIs, and dependency checks instead of direct kernel imports.",}),});const BUSY_KERNEL_WAIT_CHOICE = "Wait and preserve state";const BUSY_KERNEL_KILL_CHOICE = "Kill kernel and restart";const BUSY_KERNEL_PROMPT = [- "Interrupted IPython cell is still running",- "Ctrl+C sent an interrupt, but the previous cell has not stopped yet. A new IPython command cannot start until it finishes.",- "Waiting preserves the current kernel state. Killing restarts IPython and loses in-memory variables, imports, and running tasks.",+ "Interrupted Python cell is still running",+ "Ctrl+C sent an interrupt, but the previous cell has not stopped yet. A new command cannot start until it finishes.",+ "Waiting preserves the current kernel state. Killing restarts the kernel and loses in-memory variables, imports, and running tasks.",].join("\n");const KERNEL_RESTART_NOTICE = ["<ipython_kernel_reset>",- "The IPython kernel was restarted after a previous interrupted cell kept running. Variables, imports, async tasks, and open resources from before the restart are no longer available; recreate them before using them.",+ "The Python kernel was restarted after a previous interrupted cell kept running. Variables, imports, async tasks, and open resources from before the restart are no longer available; recreate them before using them.","</ipython_kernel_reset>",].join("\n");function createAbortError(): Error {- return new Error("IPython execution aborted");+ return new Error("Python execution aborted");}function raceWithAbort<T>(promise: Promise<T>, signal: AbortSignal | undefined, onAbort?: () => void): Promise<T> {@@ -258,7 +253,9 @@ export interface IpythonToolDetails {stdout?: string;stderr?: string;result?: string;- /** Diffs streamed from file edits, rendered by the IPython cell. */+ /** Output that arrived without this cell's id (threads, other cells' leftovers), shown separately from stdout. */+ backgroundOutput?: string;+ /** Diffs streamed from file edits, rendered by the cell view. */diffs?: KernelDiffDisplay[];/** Media attachments loaded into context (e.g. by the attach-image skill). */attachments?: KernelAttachment[];@@ -274,12 +271,12 @@ export interface IpythonToolDetails {}export interface IpythonToolOptions {- /** Python override. Must have `ipykernel` installed. */+ /** Python override. Must have prime-agent-runtime installed. */python?: string;env?: Record<string, string>;- /** Command prefix prepended to every %%bash cell. */+ /** Command prefix prepended to every bash() command. */commandPrefix?: string;- /** Optional explicit shell path for bare %%bash cells. */+ /** Shell used by bash(). */shellPath?: string;sessionId?: string;/** Typed host request handlers for the kernel↔host bridge (rlm.run, goal.*, …). */@@ -290,8 +287,8 @@ export interface IpythonToolOptions {/** Resolves before this kernel starts — e.g. the previous provisioner's dispose, so a* /reload's old-kernel snapshot flush can't race the new kernel's restore. */readyGate?: Promise<unknown>;- /** Filled with the live KernelManager after the first kernel start; cleared on construction. */- kernelManagerRef?: { current?: KernelManager };+ /** Filled with the live kernel client after the first kernel start; cleared on construction. */+ kernelManagerRef?: { current?: KernelClient };/*** Fires once per kernel start when a previous session's namespace was revived* (some names restored or some failed), so the session can tell the model.@@ -302,39 +299,16 @@ export interface IpythonToolOptions {provisioner?: IpythonKernelProvisioner;}-function quoteScriptMagicArgument(value: string): string {- return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\"'\"'")}'`;-}--function applyShellSettingsToBashMagicCell(- code: string,- options: Pick<IpythonToolOptions, "commandPrefix" | "shellPath"> | undefined,-): string {- const commandPrefix = options?.commandPrefix;- const shellPath = options?.shellPath?.trim();- if (!commandPrefix && !shellPath) return code;-- const bashCell = parseIpythonBashCell(code);- if (!bashCell) return code;-- const firstLine =- shellPath && bashCell.magicArguments.trim().length === 0- ? `${bashCell.indent}%%script ${quoteScriptMagicArgument(shellPath)}`- : `${bashCell.indent}%%bash${bashCell.magicArguments}`;- const nextBody = commandPrefix ? `${commandPrefix}${bashCell.body ? `\n${bashCell.body}` : ""}` : bashCell.body;- return `${bashCell.leadingWhitespace}${firstLine}${bashCell.lineBreak || "\n"}${nextBody}`;-}-/**- * Owns the lazy create+start+runtime-bootstrap of one session's IPython kernel.+ * Owns the lazy create+start+runtime-bootstrap of one session's Python kernel.** Concurrent ensure() calls await the same in-flight startup, a failed startup* clears the memo so the next call retries fresh, and progress listeners can* attach mid-flight (a tool call racing a background prewarm()).*/export class IpythonKernelProvisioner {- private managerPromise?: Promise<KernelManager>;- private startedManager?: KernelManager;+ private managerPromise?: Promise<KernelClient>;+ private startedManager?: KernelClient;private readonly startupListeners = new Set<KernelBootstrapProgressHandler>();private lastStartupMessage?: string;private _lastRestore?: RestoreResult;@@ -350,7 +324,7 @@ export class IpythonKernelProvisioner {}/** The kernel manager, once a startup has completed successfully. */- get manager(): KernelManager | undefined {+ get manager(): KernelClient | undefined {return this.startedManager;}@@ -419,7 +393,7 @@ export class IpythonKernelProvisioner {}}- ensure(onProgress?: KernelBootstrapProgressHandler, signal?: AbortSignal): Promise<KernelManager> {+ ensure(onProgress?: KernelBootstrapProgressHandler, signal?: AbortSignal): Promise<KernelClient> {if (signal?.aborted) {return Promise.reject(createAbortError());}@@ -473,7 +447,7 @@ export class IpythonKernelProvisioner {}}- private async startKernel(signal?: AbortSignal): Promise<KernelManager> {+ private async startKernel(signal?: AbortSignal): Promise<KernelClient> {const startupAbort = createLinkedAbortSignal([this.disposeController.signal, signal]);const startupSignal = startupAbort.signal;// Wait for a previous provisioner (e.g. on /reload) to finish disposing — and@@ -492,10 +466,10 @@ export class IpythonKernelProvisioner {// without bash, where the runtime's teaching error fires instead).const shellPath = resolveKernelBashShell(this.options?.shellPath);const commandPrefix = this.options?.commandPrefix;- const m = new KernelManager({+ const m = new ReplKernelManager({python: this.options?.python,cwd: this.cwd,- // bash() reads these so it applies the same shell settings as %%bash cells.+ // bash() reads these to pick its shell and command prefix.env: {...this.options?.env,...(shellPath ? { PRIME_AGENT_BASH_SHELL: shellPath } : {}),@@ -513,7 +487,7 @@ export class IpythonKernelProvisioner {try {// Emitted synchronously (before the permit await) so a listener attaching// mid-flight can replay the current stage.- this.emitStartupProgress("Starting IPython kernel...");+ this.emitStartupProgress("Starting Python kernel...");// Only the process spawn + port resolve contends for OS resources under a// fan-out, and it is bounded by start()'s own timeouts — so the permit// covers only start(). Restore/bootstrap run per-kernel afterwards and are@@ -531,22 +505,22 @@ export class IpythonKernelProvisioner {// then overwrites live handles (rlm, skills) on top of anything restored.if (snapshotDir) {const snapshotExisted = existsSync(snapshotPathIn(snapshotDir));- this.emitStartupProgress("Restoring IPython state...");+ this.emitStartupProgress("Restoring Python state...");const restore = await raceWithAbort(m.restoreState(), startupSignal);if (snapshotExisted) {pendingRestore = restore ?? { restored: [], failed: [], path: snapshotPathIn(snapshotDir) };}}- this.emitStartupProgress("Preparing IPython runtime...");+ this.emitStartupProgress("Preparing Python runtime...");const bootstrap = await m.execute(buildRlmBootstrapCode(this.options?.pythonSkills), {signal: startupSignal,});if (bootstrap.status !== "ok") {const details = [bootstrap.stderr, bootstrap.error?.traceback.join("\n")].filter(Boolean).join("\n");- throw new Error(`Failed to initialize rlm runtime in the IPython kernel:\n${details}`);+ throw new Error(`Failed to initialize rlm runtime in the Python kernel:\n${details}`);}} catch (error) {- // Never leak the kernel's ZMQ sockets / temp dir if startup fails after spawn.+ // Never leak the kernel process if startup fails after spawn.void m.dispose();throw error;}@@ -616,11 +590,11 @@ async function executeWithBusyKernelChoice(}const action = await chooseBusyKernelAction(ctx, signal);if (action === "wait") {- onWorkingMessage("Waiting for IPython kernel...");+ onWorkingMessage("Waiting for Python kernel...");continue;}if (action === "kill") {- onWorkingMessage("Restarting IPython kernel...");+ onWorkingMessage("Restarting Python kernel...");await provisioner.kill();kernelRestarted = true;continue;@@ -648,8 +622,8 @@ export function createIpythonToolDefinition(name: "ipython",label: "ipython",description:- "Execute Python scratchpad code and `%%bash` shell cells in a persistent IPython kernel. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.",- promptSnippet: "ipython - persistent agent notebook for Python scratchpad code and %%bash orchestration",+ "Execute Python code in a persistent Python REPL. Top-level `await` is supported. Variables, imports, and loaded data persist across calls, and are revived on a best-effort basis when a session is resumed (objects that cannot be serialized are dropped and reported). Run shell commands with `bash('cmd')` / `await bash('cmd')`. Project imports, tests, scripts, CLIs, and dependency checks should run through the target project's own environment.",+ promptSnippet: "ipython - persistent Python REPL for code, state, and bash() orchestration",// The kernel is single-threaded — pi must not run two ipython calls in parallel within a batch.executionMode: "sequential",parameters: ipythonSchema,@@ -668,12 +642,11 @@ export function createIpythonToolDefinition(};try {- const code = applyShellSettingsToBashMagicCell(params.code, options);const { result: r, kernelRestarted } = await executeWithBusyKernelChoice(provisioner,reportStartupProgress,toolCallId,- code,+ params.code,signal,(chunk) => {onUpdate?.({@@ -692,6 +665,9 @@ export function createIpythonToolDefinition(if (r.status === "error" && r.error) {text += (text ? "\n" : "") + r.error.traceback.join("\n");}+ if (r.backgroundOutput) {+ text += `${text ? "\n" : ""}[background output (unattributed)]\n${r.backgroundOutput}`;+ }if (kernelRestarted) {text = text ? `${KERNEL_RESTART_NOTICE}\n\n${text}` : KERNEL_RESTART_NOTICE;}@@ -708,6 +684,7 @@ export function createIpythonToolDefinition(stdout: r.stdout,stderr: r.stderr,result: r.result,+ backgroundOutput: r.backgroundOutput,diffs: r.diffs,attachments: r.attachments,sentAgentMessages: r.sentAgentMessages,diff --git a/packages/coding-agent/src/modes/acp/acp-events.ts b/packages/coding-agent/src/modes/acp/acp-events.tsindex 85c8c5686e..e48374c381 100644--- a/packages/coding-agent/src/modes/acp/acp-events.ts+++ b/packages/coding-agent/src/modes/acp/acp-events.ts@@ -19,7 +19,7 @@ export interface AcpSessionUpdate {[key: string]: unknown;}-/** prime-agent's model-facing tool is IPython; bash is the secondary escape hatch. */+/** prime-agent's model-facing tool is the Python REPL; bash is the secondary escape hatch. */export const IPYTHON_TOOL_NAME = "ipython";export function acpToolKind(toolName: string): AcpToolKind {@@ -64,7 +64,7 @@ function assistantDeltaUpdates(event: AssistantMessageEvent, messageId: string):return [];}-/** Extract the IPython cell source so a client can show what is executing. */+/** Extract the Python cell source so a client can show what is executing. */function ipythonCellSource(args: unknown): string | undefined {if (!args || typeof args !== "object") return undefined;const code = (args as { code?: unknown }).code;@@ -91,7 +91,7 @@ function toolResultText(result: unknown): string | undefined {}/**- * Rich IPython output that ACP has no content type for.+ * Rich kernel output that ACP has no content type for.** The ipython tool reports media and diffs under `details` (images additionally* ride along as ACP image content blocks); mirror those exact fields rather than@@ -161,7 +161,7 @@ export function acpUpdatesForSessionEvent({sessionUpdate: "tool_call",toolCallId: event.toolCallId,- title: event.toolName === IPYTHON_TOOL_NAME ? "IPython cell" : event.toolName,+ title: event.toolName === IPYTHON_TOOL_NAME ? "Python cell" : event.toolName,kind: acpToolKind(event.toolName),status: "in_progress" satisfies AcpToolStatus,rawInput: cell !== undefined ? { code: cell } : event.args,diff --git a/packages/coding-agent/src/modes/acp/acp-meta.ts b/packages/coding-agent/src/modes/acp/acp-meta.tsindex 1918616da2..acb1dd6444 100644--- a/packages/coding-agent/src/modes/acp/acp-meta.ts+++ b/packages/coding-agent/src/modes/acp/acp-meta.ts@@ -1,6 +1,6 @@/*** Namespaced `_meta` payloads for prime-agent capabilities that ACP has no- * native concept for (IPython cell semantics, RLM subagents, autonomous gates,+ * native concept for (Python cell semantics, RLM subagents, autonomous gates,* goals, heartbeats, continual harness state).** ACP reserves `_meta` on capability objects, notifications, tool calls, anddiff --git a/packages/coding-agent/src/modes/agents-view/agents-view-state.ts b/packages/coding-agent/src/modes/agents-view/agents-view-state.tsindex 50b7ad1138..b29531360b 100644--- a/packages/coding-agent/src/modes/agents-view/agents-view-state.ts+++ b/packages/coding-agent/src/modes/agents-view/agents-view-state.ts@@ -798,7 +798,7 @@ interface SpawnCodeGroup {children: MutableAgentsViewRow[];}-// Subagents spawned by the same IPython cell share its source; group them so+// Subagents spawned by the same Python cell share its source; group them so// each spawn cell renders once, above the subagents it launched. Different turns// produce different cells and therefore distinct groups. Insertion order follows// each cell's first subagent so groups read top-to-bottom in spawn order.diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.tsindex 73dc116ba5..49b5a16dc7 100644--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts@@ -69,7 +69,7 @@ export interface SessionSummary {rlmChildId?: string;repliedSinceTask?: boolean;rlmParentNodeId?: string;- /** Source of the IPython cell that spawned this subagent, for display. */+ /** Source of the Python cell that spawned this subagent, for display. */spawnCode?: string;modelFallbackMessage?: string;diagnostics?: AgentSessionRuntimeDiagnostic[];diff --git a/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts b/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.tsindex eec0e2428d..6893496870 100644--- a/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts@@ -127,7 +127,7 @@ export class InjectedPromptMessageComponent extends Container {}if (this.message.customType === IPYTHON_STATE_RESTORED_CUSTOM_TYPE) {const details = this.message.details as IpythonStateRestoredDetails | undefined;- const label = details?.restored === false ? "Started fresh IPython kernel" : "Restored IPython kernel state";+ const label = details?.restored === false ? "Started fresh Python kernel" : "Restored Python kernel state";return `${theme.fg("accent", "◆")} ${theme.fg("muted", label)}`;}if (diff --git a/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts b/packages/coding-agent/src/modes/interactive/components/ipython-cell.tsindex 14699deb77..aed22eba42 100644--- a/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts+++ b/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts@@ -67,6 +67,7 @@ interface IpythonDetails {stdout?: string;stderr?: string;result?: string;+ backgroundOutput?: string;diffs?: DiffDisplay[];sentAgentMessages?: SentAgentMessageDisplay[];error?: IpythonErrorDetails;@@ -147,6 +148,7 @@ function readDetails(details: unknown): IpythonDetails {stdout: typeof record.stdout === "string" ? record.stdout : undefined,stderr: typeof record.stderr === "string" ? record.stderr : undefined,result: typeof record.result === "string" ? record.result : undefined,+ backgroundOutput: typeof record.backgroundOutput === "string" ? record.backgroundOutput : undefined,diffs: readDiffDisplays(record.diffs),sentAgentMessages: readSentAgentMessages(record.sentAgentMessages),error,@@ -446,7 +448,7 @@ export class IPythonCellComponent implements Component {const hasDiffs = (details.diffs?.length ?? 0) > 0;const sentMessages = details.sentAgentMessages ?? [];const result = isAgentMessageReceipt(details.result, sentMessages) ? undefined : details.result;- const structured = [details.stdout, details.stderr, result]+ const structured = [details.stdout, details.stderr, result, details.backgroundOutput].filter((value): value is string => typeof value === "string" && value.trim().length > 0).join("\n");const blocksText = textFromBlocks(this.state.content);@@ -591,6 +593,14 @@ export class IPythonCellComponent implements Component {this.renderOutputText(lines, width, normalizeErrorDetails(text), this.state.isError ? "err" : "out");}+ // Without structured fields the fallback content text above already contains the appended background block.+ const backgroundOutput =+ hasStructuredOutput && details.backgroundOutput?.trim() ? details.backgroundOutput : undefined;+ if (backgroundOutput) {+ // Suppresses the placeholders below when background output is the cell's only output; rendered after the traceback to match the model-facing order.+ renderedTextOutput = true;+ }+if (!renderedTextOutput && this.state.isPartial) {startOutput();this.addWrapped(lines, OUTPUT_INDENT, theme.fg("muted", "waiting for output..."), width);@@ -622,6 +632,12 @@ export class IPythonCellComponent implements Component {this.renderTraceback(lines, width, traceback.traceback);}+ if (backgroundOutput) {+ startOutput();+ this.addWrapped(lines, OUTPUT_INDENT, theme.fg("muted", "background output (unattributed)"), width);+ this.renderOutputText(lines, width, normalizeErrorDetails(backgroundOutput), "err");+ }+if (imageCount > 0) {startOutput();const text = this.state.showImagesdiff --git a/packages/coding-agent/src/modes/interactive/feature-hints.ts b/packages/coding-agent/src/modes/interactive/feature-hints.tsindex 17d387fddb..c4ffbad4b3 100644--- a/packages/coding-agent/src/modes/interactive/feature-hints.ts+++ b/packages/coding-agent/src/modes/interactive/feature-hints.ts@@ -76,7 +76,7 @@ export const FEATURE_HINTS: readonly FeatureHintDefinition[] = [},{id: "persistent-ipython",- getText: () => "Compaction removes IPython variables over 16 MiB; smaller state persists.",+ getText: () => "Compaction removes kernel variables over 16 MiB; smaller state persists.",},{id: "context-usage",diff --git a/packages/coding-agent/test/acp-events.test.ts b/packages/coding-agent/test/acp-events.test.tsindex 6942d9bfeb..8ba1d59602 100644--- a/packages/coding-agent/test/acp-events.test.ts+++ b/packages/coding-agent/test/acp-events.test.ts@@ -85,7 +85,7 @@ describe("ACP session event mapping", () => {{sessionUpdate: "tool_call",toolCallId: "call-1",- title: "IPython cell",+ title: "Python cell",kind: "execute",status: "in_progress",rawInput: { code: "print(1)" },diff --git a/packages/coding-agent/test/acp-kernel-features.test.ts b/packages/coding-agent/test/acp-kernel-features.test.tsindex de7660888a..e333d382e6 100644--- a/packages/coding-agent/test/acp-kernel-features.test.ts+++ b/packages/coding-agent/test/acp-kernel-features.test.ts@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";import { getBundledSkillsDir } from "../src/config.js";-import type { KernelManager } from "../src/core/kernel/index.js";+import type { KernelClient } from "../src/core/kernel/index.js";import type { PythonSkillRuntimeInfo } from "../src/core/skills.js";import { IpythonKernelProvisioner } from "../src/core/tools/ipython.js";import { acpUpdatesForSessionEvent } from "../src/modes/acp/acp-events.js";@@ -13,7 +13,7 @@ import type { AgentConnectionSessionEvent } from "../src/modes/agent-connection//*** Real-kernel verification for ACP mode.*- * These tests boot an actual IPython kernel (no API key, no network) to prove+ * These tests boot an actual Python kernel (no API key, no network) to prove* the capabilities ACP mode claims to preserve genuinely work, and that the* resulting output is representable over ACP. Mapper-level unit tests cannot* show that a kernel round trip still holds state or that harness CRUD runs.@@ -42,7 +42,7 @@ function toolEndEvent(toolCallId: string, output: string, isError = false): Agen} as AgentConnectionSessionEvent;}-describe("ACP mode over a real IPython kernel", () => {+describe("ACP mode over a real Python kernel", () => {let tempDir: string;let provisioner: IpythonKernelProvisioner | undefined;@@ -57,7 +57,7 @@ describe("ACP mode over a real IPython kernel", () => {rmSync(tempDir, { recursive: true, force: true });});- it("keeps IPython state across cells and represents each cell as an ACP execute call", {+ it("keeps Python state across cells and represents each cell as an ACP execute call", {tags: ["kernel-heavy"],timeout: 180_000,}, async () => {@@ -65,7 +65,7 @@ describe("ACP mode over a real IPython kernel", () => {// is shared, and a skill-less kernel here can leave a later skill-dependent// test with an unsynced venv when files run concurrently.provisioner = new IpythonKernelProvisioner(tempDir, { pythonSkills: [AGENT_MESSAGE_SKILL] });- const manager: KernelManager = await provisioner.ensure();+ const manager: KernelClient = await provisioner.ensure();const first = await manager.execute("acp_state = 41\nprint('set')");expect(first.status).toBe("ok");diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex 4b5b7b9e29..2c373352ba 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -1,6 +1,5 @@-import { spawnSync } from "node:child_process";import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";-import { homedir, tmpdir } from "node:os";+import { tmpdir } from "node:os";import { basename, dirname, join } from "node:path";import { setTimeout as sleep } from "node:timers/promises";import { Agent, type AgentMessage, type StreamFn } from "@earendil-works/pi-agent-core";@@ -22,7 +21,7 @@ import {import { AgentSession } from "../src/core/agent-session.js";import { AuthStorage } from "../src/core/auth-storage.js";import type { LoadExtensionsResult } from "../src/core/extensions/index.js";-import { type HostRequestHandlers, KernelManager } from "../src/core/kernel/index.js";+import { type HostRequestHandlers, ReplKernelManager } from "../src/core/kernel/index.js";import { convertToLlm } from "../src/core/messages.js";import { ModelRegistry } from "../src/core/model-registry.js";import {@@ -92,23 +91,6 @@ function streamAnswer(text: string): ReturnType<typeof createAssistantMessageEvereturn stream;}-interface TestCommMessage {- header: { msg_type: string };- parent_header: Record<string, unknown>;- metadata: Record<string, unknown>;- content: Record<string, unknown>;-}--interface KernelCommTestApi {- handleCommMessage(incoming: TestCommMessage): void;- sendCommMessage(commId: string, data: Record<string, unknown>): Promise<void>;-}--interface CapturedCommReply {- commId: string;- data: Record<string, unknown>;-}-interface InspectableRlmRun {id: string;prompt?: string;@@ -146,73 +128,6 @@ interface InspectableRlmSession {_reapDeletedRlmSubagentRuntimesAfterCompaction(): Promise<void>;}-interface KernelPumpTestApi {- iopub: AsyncIterable<Buffer[]> & { close(): void };- startIopubPump(): void;-}--interface KernelExecuteTestApi {- start: () => Promise<void>;- state: "idle" | "starting" | "running" | "shutdown";- activeExecution?: unknown;- shell?: {- send(frames: Buffer[]): Promise<void>;- close(): void;- };- connection?: {- ip: string;- transport: "tcp";- shell_port: number;- iopub_port: number;- stdin_port: number;- control_port: number;- hb_port: number;- signature_scheme: "hmac-sha256";- key: string;- kernel_name: string;- };-}--function rlmCommOpenData(commId: string, data: Record<string, unknown>): TestCommMessage {- return {- header: { msg_type: "comm_open" },- parent_header: {},- metadata: {},- content: {- comm_id: commId,- target_name: "host.request",- data,- },- };-}--function rlmCommOpen(commId: string, prompt: string, kwargs: Record<string, unknown> = {}): TestCommMessage {- return rlmCommOpenData(commId, { type: "rlm.run", prompt, kwargs });-}--function encodeTestMessage(message: TestCommMessage): Buffer[] {- return [- Buffer.from("<IDS|MSG>"),- Buffer.from(""),- Buffer.from(JSON.stringify(message.header)),- Buffer.from(JSON.stringify(message.parent_header)),- Buffer.from(JSON.stringify(message.metadata)),- Buffer.from(JSON.stringify(message.content)),- ];-}--function asyncFrames(frames: Buffer[][]): AsyncIterable<Buffer[]> & { close(): void } {- return {- close: () => {},- async *[Symbol.asyncIterator]() {- for (const frame of frames) {- await sleep(0);- yield frame;- }- },- };-}-async function waitFor(condition: () => boolean): Promise<void> {const deadline = Date.now() + 1000;while (!condition()) {@@ -223,14 +138,6 @@ async function waitFor(condition: () => boolean): Promise<void> {}}-async function expectSettlesWithin(promise: Promise<void>, timeoutMs: number): Promise<void> {- const result = await Promise.race([- promise.then(() => "settled" as const),- sleep(timeoutMs).then(() => "timeout" as const),- ]);- expect(result).toBe("settled");-}-function findLastMessage(messages: readonly AgentMessage[],predicate: (message: AgentMessage) => boolean,@@ -2765,24 +2672,6 @@ describe("AgentSession rlm recursion", () => {expect(child.rlmMaxDepth).toBe(3);});- it("lets a stale kernel depth cap defer to the live host gate", () => {- const python =- process.env.PRIME_AGENT_KERNEL_PYTHON ?? join(homedir(), ".prime", "agent", "kernel-venv", "bin", "python");- const runtime = join(process.cwd(), "..", "..", "prime-agent-runtime", "src");- const probe = spawnSync(- python,- ["-c", "import asyncio, rlm; rlm.Comm = None; asyncio.run(rlm.run('raised live cap'))"],- {- env: { ...process.env, PYTHONPATH: runtime, RLM_DEPTH: "1", RLM_MAX_DEPTH: "1" },- encoding: "utf8",- },- );-- expect(probe.status).not.toBe(0);- expect(probe.stderr).toContain("Jupyter comm support is unavailable in this kernel");- expect(probe.stderr).not.toContain("RLM recursion depth limit reached");- });-it("rejects child creation at the configured recursion depth cap", async () => {const root = createSession({ depth: 1, maxDepth: 1 });@@ -3975,122 +3864,9 @@ describe("AgentSession rlm recursion", () => {await waitFor(() => rootRun.status === "done");});- it("runs parallel rlm comm requests independently", async () => {- let active = 0;- let maxActive = 0;- let started = 0;- let releaseChildren: () => void = () => {};- const release = new Promise<void>((resolve) => {- releaseChildren = resolve;- });- const replies: CapturedCommReply[] = [];- const manager = new KernelManager({- python: process.execPath,- hostHandlers: {- "rlm.run": createRlmRunHostHandler(async ({ prompt }) => {- active++;- started++;- maxActive = Math.max(maxActive, active);- await release;- active--;- return {- answer: `answer:${prompt}`,- usage: { prompt_tokens: 1, completion_tokens: 1 },- turns: 1,- session_dir: null,- model: "test/model",- };- }),- },- });-- try {- const kernel = manager as unknown as KernelCommTestApi;- kernel.sendCommMessage = async (commId, data) => {- replies.push({ commId, data });- };-- kernel.handleCommMessage(rlmCommOpen("comm-a", "first"));- kernel.handleCommMessage(rlmCommOpen("comm-b", "second"));-- await waitFor(() => started === 2);- expect(maxActive).toBe(2);-- releaseChildren();- await waitFor(() => replies.length === 2);-- const byCommId = new Map(replies.map((reply) => [reply.commId, reply.data]));- expect(byCommId.get("comm-a")).toEqual({- status: "ok",- answer: "answer:first",- usage: { prompt_tokens: 1, completion_tokens: 1 },- turns: 1,- session_dir: null,- model: "test/model",- });- expect(byCommId.get("comm-b")).toEqual({- status: "ok",- answer: "answer:second",- usage: { prompt_tokens: 1, completion_tokens: 1 },- turns: 1,- session_dir: null,- model: "test/model",- });- } finally {- await manager.dispose();- }- });-- it("handles rlm comm requests from the iopub pump outside active execution", async () => {- const replies: CapturedCommReply[] = [];- let promptSeen = "";- const manager = new KernelManager({- python: process.execPath,- hostHandlers: {- "rlm.run": createRlmRunHostHandler(async ({ prompt }) => {- promptSeen = prompt;- return {- answer: `answer:${prompt}`,- usage: { prompt_tokens: 1, completion_tokens: 1 },- turns: 1,- session_dir: null,- model: "test/model",- };- }),- },- });-- try {- const kernel = manager as unknown as KernelCommTestApi & KernelPumpTestApi;- kernel.sendCommMessage = async (commId, data) => {- replies.push({ commId, data });- };- kernel.iopub = asyncFrames([encodeTestMessage(rlmCommOpen("comm-detached", "detached child"))]);-- kernel.startIopubPump();-- await waitFor(() => replies.length === 1);-- expect(promptSeen).toBe("detached child");- expect(replies[0]).toEqual({- commId: "comm-detached",- data: {- status: "ok",- answer: "answer:detached child",- usage: { prompt_tokens: 1, completion_tokens: 1 },- turns: 1,- session_dir: null,- model: "test/model",- },- });- } finally {- await manager.dispose();- }- });-it("handles rlm calls from asyncio tasks after the scheduling cell is idle", async () => {const prompts: string[] = [];- const manager = new KernelManager({+ const manager = new ReplKernelManager({cwd: tempDir,hostHandlers: {"rlm.run": createRlmRunHostHandler(async ({ prompt }) => {@@ -4133,134 +3909,6 @@ print(_result.name)await manager.dispose();}});-- it("clears active execution when execute_request send fails", async () => {- const manager = new KernelManager({ python: process.execPath });- const kernel = manager as unknown as KernelExecuteTestApi;- const sendError = new Error("send failed");- kernel.start = async () => {};- kernel.state = "running";- kernel.shell = {- send: async (_frames: Buffer[]) => {- throw sendError;- },- close: () => {},- };- kernel.connection = {- ip: "127.0.0.1",- transport: "tcp",- shell_port: 1,- iopub_port: 2,- stdin_port: 3,- control_port: 4,- hb_port: 5,- signature_scheme: "hmac-sha256",- key: "",- kernel_name: "python3",- };-- try {- await expect(manager.execute("print('hello')")).rejects.toThrow("send failed");- expect(kernel.activeExecution).toBeUndefined();- } finally {- await manager.dispose();- }- });-- it("rejects removed background rlm comm request types", async () => {- const replies: CapturedCommReply[] = [];- const manager = new KernelManager({- python: process.execPath,- hostHandlers: {- "rlm.run": createRlmRunHostHandler(async () => ({- answer: "unused",- usage: { prompt_tokens: 1, completion_tokens: 1 },- turns: 1,- session_dir: null,- model: "test/model",- })),- },- });-- try {- const kernel = manager as unknown as KernelCommTestApi;- kernel.sendCommMessage = async (commId, data) => {- replies.push({ commId, data });- };-- kernel.handleCommMessage(rlmCommOpenData("comm-bg", { type: "background", prompt: "slow", kwargs: {} }));-- await waitFor(() => replies.length === 1);-- expect(replies[0]).toEqual({- commId: "comm-bg",- data: {- status: "error",- error: 'host request type "background" is not available in this session',- },- });- } finally {- await manager.dispose();- }- });-- it("waits for in-flight rlm comm work during dispose and buffers failures", async () => {- let started = false;- let handlerSettled = false;- let released = false;- let releaseChild: () => void = () => {};- const release = new Promise<void>((resolve) => {- releaseChild = () => {- if (released) return;- released = true;- resolve();- };- });- const manager = new KernelManager({- python: process.execPath,- hostHandlers: {- "rlm.run": createRlmRunHostHandler(async () => {- started = true;- try {- await release;- throw new Error("child failed after dispose");- } finally {- handlerSettled = true;- }- }),- },- });- const stderrSpy = vi.spyOn(process.stderr, "write").mockImplementation(() => true);-- try {- const kernel = manager as unknown as KernelCommTestApi;-- kernel.handleCommMessage(rlmCommOpen("comm-dispose", "slow child"));-- await waitFor(() => started);- const disposePromise = manager.dispose();- let disposeSettled = false;- const trackedDispose = disposePromise.then(() => {- disposeSettled = true;- });-- await sleep(25);- expect(disposeSettled).toBe(false);-- releaseChild();- await expectSettlesWithin(trackedDispose, 1000);- expect(handlerSettled).toBe(true);-- const kernelStderr = (manager as unknown as { kernelStderr: string }).kernelStderr;- expect(kernelStderr).toContain("[kernel] host request failed for comm comm-dispose");- expect(kernelStderr).toContain("[kernel] failed to send host request error reply for comm comm-dispose");- expect(stderrSpy).not.toHaveBeenCalled();- } finally {- releaseChild();- await manager.dispose();- stderrSpy.mockRestore();- }- });});interface InspectableRlmDirSession {diff --git a/packages/coding-agent/test/agent-session-services.test.ts b/packages/coding-agent/test/agent-session-services.test.tsindex c6e38c878f..81a2414a34 100644--- a/packages/coding-agent/test/agent-session-services.test.ts+++ b/packages/coding-agent/test/agent-session-services.test.ts@@ -148,7 +148,7 @@ describe("createAgentSessionFromServices", () => {try {const initialPrompt = session.systemPrompt;expect(initialPrompt).toContain(- "Generic MCP connections are accessed through the pre-imported Python `mcp` object in IPython, not as top-level native tool namespaces or installed Python skills.",+ "Generic MCP connections are accessed through the pre-imported Python `mcp` object in the Python REPL, not as top-level native tool namespaces or installed Python skills.",);expect(initialPrompt).toContain("Enabled generic MCP servers: `filesystem`, `zebra`.");expect(initialPrompt).toContain('await mcp.list_tools("filesystem")');diff --git a/packages/coding-agent/test/boot-gate.test.ts b/packages/coding-agent/test/boot-gate.test.tsindex 1bb16a21d1..795d3db907 100644--- a/packages/coding-agent/test/boot-gate.test.ts+++ b/packages/coding-agent/test/boot-gate.test.ts@@ -2,12 +2,10 @@ import { afterEach, describe, expect, it } from "vitest";import { resolveKernelBootConcurrency } from "../src/core/kernel/boot-gate.js";const ENV = "PRIME_AGENT_MAX_CONCURRENT_KERNEL_BOOTS";-const FORK_ENV = "PRIME_AGENT_KERNEL_FORKSERVER";describe("resolveKernelBootConcurrency", () => {afterEach(() => {delete process.env[ENV];- delete process.env[FORK_ENV];});it("never returns a value below 1 (so the semaphore can't throw at load)", () => {@@ -17,20 +15,10 @@ describe("resolveKernelBootConcurrency", () => {}});- it("honors a clean positive integer, clamped to the direct-spawn max", () => {- process.env[FORK_ENV] = "0"; // direct-spawn path (forkserver is default-on)+ it("honors a clean positive integer, clamped to the max", () => {process.env[ENV] = "8";expect(resolveKernelBootConcurrency()).toBe(8);process.env[ENV] = "999999";expect(resolveKernelBootConcurrency()).toBe(64);});-- it("raises the ceiling on the forkserver path (linux, default on)", () => {- if (process.platform !== "linux") return;- const auto = resolveKernelBootConcurrency();- expect(auto).toBeGreaterThanOrEqual(32);- expect(auto).toBeLessThanOrEqual(128);- process.env[ENV] = "999999";- expect(resolveKernelBootConcurrency()).toBe(128);- });});diff --git a/packages/coding-agent/test/compaction.test.ts b/packages/coding-agent/test/compaction.test.tsindex 75bc7273c0..ea8a280bb9 100644--- a/packages/coding-agent/test/compaction.test.ts+++ b/packages/coding-agent/test/compaction.test.ts@@ -181,7 +181,7 @@ describe("buildSummarizationPrompt", () => {expect(prompt).not.toContain("<user-instructions>");expect(prompt).toContain("## Goal");// The kernel keeps running across compaction — the note must not claim a wipe.- expect(prompt).toContain("IPython kernel keeps running");+ expect(prompt).toContain("Python kernel keeps running");expect(prompt).not.toMatch(/wiped|restarted/);});@@ -190,7 +190,7 @@ describe("buildSummarizationPrompt", () => {expect(prompt).toContain("<user-instructions>");expect(prompt).toContain("focus on the auth refactor, remember the migration command");expect(prompt).toContain("</user-instructions>");- expect(prompt.indexOf("</user-instructions>")).toBeLessThan(prompt.indexOf("IPython kernel"));+ expect(prompt.indexOf("</user-instructions>")).toBeLessThan(prompt.indexOf("Python kernel"));});it("uses the update template when a previous summary exists", () => {diff --git a/packages/coding-agent/test/extension-selector.test.ts b/packages/coding-agent/test/extension-selector.test.tsindex ea45133ee3..88a704f318 100644--- a/packages/coding-agent/test/extension-selector.test.ts+++ b/packages/coding-agent/test/extension-selector.test.ts@@ -21,9 +21,9 @@ describe("ExtensionSelectorComponent", () => {it("renders a multiline prompt with compact option rows", () => {const selector = new ExtensionSelectorComponent([- "Interrupted IPython cell is still running",+ "Interrupted Python cell is still running","Ctrl+C sent an interrupt, but the previous cell has not stopped yet.",- "Waiting preserves the current kernel state. Killing restarts IPython and loses in-memory variables.",+ "Waiting preserves the current kernel state. Killing restarts the kernel and loses in-memory variables.",].join("\n"),["Wait and preserve state", "Kill kernel and restart"],vi.fn(),@@ -37,14 +37,14 @@ describe("ExtensionSelectorComponent", () => {const waitIndex = outputLines.findIndex((line) => line.includes("Wait and preserve state"));const killIndex = outputLines.findIndex((line) => line.includes("Kill kernel and restart"));- expect(output).toContain("Interrupted IPython cell is still running");+ expect(output).toContain("Interrupted Python cell is still running");expect(output).toContain("Ctrl+C sent an interrupt");expect(output).toContain("Waiting preserves the current kernel state");expect(waitIndex).toBeGreaterThan(-1);expect(killIndex).toBe(waitIndex + 1);expectTrailingBackground(- lines.find((line) => line.includes("Interrupted IPython cell is still running")),- "Interrupted IPython cell is still running",+ lines.find((line) => line.includes("Interrupted Python cell is still running")),+ "Interrupted Python cell is still running",);expectTrailingBackground(lines[waitIndex], "Wait and preserve state");expectTrailingBackground(lines[killIndex], "Kill kernel and restart");diff --git a/packages/coding-agent/test/interactive-mode-feature-hints.test.ts b/packages/coding-agent/test/interactive-mode-feature-hints.test.tsindex d37628873f..3fa36d9fc3 100644--- a/packages/coding-agent/test/interactive-mode-feature-hints.test.ts+++ b/packages/coding-agent/test/interactive-mode-feature-hints.test.ts@@ -92,7 +92,7 @@ describe("feature hint deck", () => {expect(textById.get("agent-messaging")).toContain("message each other");expect(textById.get("goal")).toContain("/goal");expect(textById.get("refine")).toContain("/refine");- expect(textById.get("persistent-ipython")).toContain("IPython");+ expect(textById.get("persistent-ipython")).toContain("kernel variables");expect(textById.get("context-usage")).toContain("/context");expect(textById.get("session-fork")).toContain("/fork");expect(textById.get("compaction")).toContain("/compact");diff --git a/packages/coding-agent/test/ipython-bootstrap.test.ts b/packages/coding-agent/test/ipython-bootstrap.test.tsindex 17358a3bf8..1b8dadb2e8 100644--- a/packages/coding-agent/test/ipython-bootstrap.test.ts+++ b/packages/coding-agent/test/ipython-bootstrap.test.ts@@ -1,12 +1,12 @@import { spawnSync } from "node:child_process";import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";import { homedir, tmpdir } from "node:os";-import { join } from "node:path";+import { join, resolve } from "node:path";import { afterAll, describe, expect, it } from "vitest";-import { KernelManager } from "../src/core/kernel/index.js";+import { ReplKernelManager } from "../src/core/kernel/index.js";import { buildRlmBootstrapCode } from "../src/core/tools/ipython.js";-describe("IPython RLM bootstrap", () => {+describe("RLM bootstrap", () => {it("pre-imports asyncio so the prompt's subagent patterns work without a manual import", () => {expect(buildRlmBootstrapCode()).toMatch(/^import asyncio$/m);});@@ -30,6 +30,10 @@ describe("IPython RLM bootstrap", () => {expect(code).toContain("rlm._raise_missing()");});+ it("does not install a kernel shutdown hook (the runtime closes MCP on shutdown itself)", () => {+ expect(buildRlmBootstrapCode()).not.toContain("install_shutdown_hook");+ });+it("guards Python skill imports so a broken skill does not abort bootstrap", () => {const code = buildRlmBootstrapCode([{@@ -47,15 +51,18 @@ describe("IPython RLM bootstrap", () => {});});-/** Find a python that can launch an ipykernel, or null to skip. */+/** Find a python with a current rlm runtime, or null to skip. */function resolveKernelPython(): string | null {const candidates = [process.env.PRIME_AGENT_KERNEL_PYTHON,+ resolve(__dirname, "..", "..", "..", "prime-agent-runtime", ".venv", "bin", "python"),join(homedir(), ".prime", "agent", "kernel-venv", "bin", "python"),].filter((p): p is string => Boolean(p));for (const python of candidates) {if (!existsSync(python)) continue;- const check = spawnSync(python, ["-c", "import ipykernel"], { encoding: "utf8" });+ const check = spawnSync(python, ["-c", "import rlm.repl, rlm; assert callable(rlm.emit)"], {+ encoding: "utf8",+ });if (check.status === 0) return python;}return null;@@ -64,7 +71,7 @@ function resolveKernelPython(): string | null {const python = resolveKernelPython();const describeIfKernel = python ? describe : describe.skip;-describeIfKernel("IPython RLM bootstrap (real kernel)", () => {+describeIfKernel("RLM bootstrap (real kernel)", () => {const dir = mkdtempSync(join(tmpdir(), "prime-agent-bootstrap-"));afterAll(() => {@@ -72,7 +79,7 @@ describeIfKernel("IPython RLM bootstrap (real kernel)", () => {});it("binds asyncio in the user namespace", async () => {- const manager = new KernelManager({ python: python as string, cwd: dir });+ const manager = new ReplKernelManager({ python: python as string, cwd: dir });try {await manager.start();const bootstrap = await manager.execute(buildRlmBootstrapCode());@@ -82,9 +89,9 @@ describeIfKernel("IPython RLM bootstrap (real kernel)", () => {expect(result.status).toBe("ok");expect(result.stdout).toContain("Task");- const bashResult = await manager.execute('%%bash\nprintf %s "$NO_COLOR"');- expect(bashResult.status).toBe("ok");- expect(bashResult.stdout).toBe("1");+ const envResult = await manager.execute('import os\nprint(os.environ["NO_COLOR"])');+ expect(envResult.status).toBe("ok");+ expect(envResult.stdout.trim()).toBe("1");} finally {await manager.dispose();}@@ -98,7 +105,7 @@ describeIfKernel("IPython RLM bootstrap (real kernel)", () => {writeFileSync(join(firstDir, "same.txt"), "old");writeFileSync(join(secondDir, "same.txt"), "old");const editSkillRoot = join(process.cwd(), "skills", "edit");- const manager = new KernelManager({+ const manager = new ReplKernelManager({python: python as string,cwd: dir,env: { PYTHONPATH: join(editSkillRoot, "src") },diff --git a/packages/coding-agent/test/ipython-cell-background-output.test.ts b/packages/coding-agent/test/ipython-cell-background-output.test.tsnew file mode 100644index 0000000000..3588e2e549--- /dev/null+++ b/packages/coding-agent/test/ipython-cell-background-output.test.ts@@ -0,0 +1,130 @@+import { beforeAll, describe, expect, it } from "vitest";+import { IPythonCellComponent } from "../src/modes/interactive/components/ipython-cell.js";+import { initTheme } from "../src/modes/interactive/theme/theme.js";++function stripAnsi(text: string): string {+ return text.replace(/\x1b\[[0-9;]*m/g, "");+}++function renderCell(state: ConstructorParameters<typeof IPythonCellComponent>[0]): string {+ return stripAnsi(new IPythonCellComponent(state).render(80).join("\n"));+}++function countOccurrences(haystack: string, needle: string): number {+ return haystack.split(needle).length - 1;+}++describe("IPythonCellComponent background output rendering", () => {+ beforeAll(() => {+ initTheme("dark");+ });++ it("renders background-only output with a label instead of 'no output'", () => {+ const out = renderCell({+ code: "run_thread()",+ content: [{ type: "text", text: "[background output (unattributed)]\norphan-line" }],+ details: { status: "ok", durationMs: 1, stdout: "", stderr: "", backgroundOutput: "orphan-line" },+ executionStarted: true,+ argsComplete: true,+ expanded: true,+ });++ expect(countOccurrences(out, "orphan-line")).toBe(1);+ expect(out).toContain("background output (unattributed)");+ expect(out).not.toContain("no output");+ });++ it("renders stdout before background output, each exactly once", () => {+ const out = renderCell({+ code: "run_thread()",+ content: [{ type: "text", text: "main-line\n[background output (unattributed)]\nbg-line" }],+ details: { status: "ok", durationMs: 1, stdout: "main-line", stderr: "", backgroundOutput: "bg-line" },+ executionStarted: true,+ argsComplete: true,+ expanded: true,+ });++ expect(countOccurrences(out, "main-line")).toBe(1);+ expect(countOccurrences(out, "bg-line")).toBe(1);+ const lines = out.split("\n");+ const stdoutIndex = lines.findIndex((line) => line.includes("main-line"));+ const labelIndex = lines.findIndex((line) => line.includes("background output (unattributed)"));+ expect(stdoutIndex).toBeGreaterThanOrEqual(0);+ expect(labelIndex).toBeGreaterThan(stdoutIndex);+ });++ it("renders old structured details without a background label", () => {+ const out = renderCell({+ code: "print('x')",+ content: [{ type: "text", text: "plain" }],+ details: { status: "ok", stdout: "plain" },+ executionStarted: true,+ argsComplete: true,+ expanded: true,+ });++ expect(countOccurrences(out, "plain")).toBe(1);+ expect(out).not.toContain("background output");+ });++ it("renders unstructured old details via the content fallback exactly once", () => {+ const out = renderCell({+ code: "run_thread()",+ content: [{ type: "text", text: "main-line\n[background output (unattributed)]\nbg-line" }],+ details: {},+ executionStarted: true,+ argsComplete: true,+ expanded: true,+ });++ expect(countOccurrences(out, "main-line")).toBe(1);+ expect(countOccurrences(out, "bg-line")).toBe(1);+ expect(countOccurrences(out, "background output (unattributed)")).toBe(1);+ });++ it("renders the traceback before background output on error cells, each exactly once", () => {+ const out = renderCell({+ code: "run_thread(); boom()",+ content: [+ {+ type: "text",+ text: "Traceback line\nNameError: boom\n[background output (unattributed)]\nbg-line",+ },+ ],+ details: {+ status: "error",+ durationMs: 1,+ stdout: "",+ stderr: "",+ backgroundOutput: "bg-line",+ error: { ename: "NameError", evalue: "boom", traceback: ["Traceback line", "NameError: boom"] },+ },+ executionStarted: true,+ argsComplete: true,+ isError: true,+ expanded: true,+ });++ expect(countOccurrences(out, "bg-line")).toBe(1);+ expect(countOccurrences(out, "background output (unattributed)")).toBe(1);+ expect(countOccurrences(out, "NameError: boom")).toBe(1);+ const lines = out.split("\n");+ const tracebackIndex = lines.findIndex((line) => line.includes("NameError: boom"));+ const labelIndex = lines.findIndex((line) => line.includes("background output (unattributed)"));+ expect(tracebackIndex).toBeGreaterThanOrEqual(0);+ expect(labelIndex).toBeGreaterThan(tracebackIndex);+ });++ it("counts background lines in the collapsed output line count", () => {+ const out = renderCell({+ code: "run_thread()",+ content: [{ type: "text", text: "main-line\n[background output (unattributed)]\nbg-line" }],+ details: { status: "ok", durationMs: 1, stdout: "main-line", stderr: "", backgroundOutput: "bg-line" },+ executionStarted: true,+ argsComplete: true,+ expanded: false,+ });++ expect(out).toContain("\u2193 2 lines");+ });+});diff --git a/packages/coding-agent/test/ipython-provisioner.test.ts b/packages/coding-agent/test/ipython-provisioner.test.tsindex b243879d20..9935cdce9e 100644--- a/packages/coding-agent/test/ipython-provisioner.test.ts+++ b/packages/coding-agent/test/ipython-provisioner.test.ts@@ -2,25 +2,19 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, wrimport { tmpdir } from "node:os";import { join } from "node:path";import { cleanupSessionResources } from "@earendil-works/pi-ai";-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { ExtensionContext } from "../src/core/extensions/types.js";import type { KernelBootstrapProgressHandler } from "../src/core/kernel/bootstrap.js";-import { type ExecuteResult, KernelBusyAfterInterruptError, KernelManager } from "../src/core/kernel/index.js";+import {+ type ExecuteResult,+ KernelBusyAfterInterruptError,+ type KernelClient,+ ReplKernelManager,+} from "../src/core/kernel/index.js";import { createIpythonToolDefinition, IpythonKernelProvisioner } from "../src/core/tools/ipython.js";let tempDir = "";-// These tests count spawns of a stub python; the default-on forkserver adds an-// extra spawn + ready handshake the stub never answers, so pin direct-spawn.-const savedForkFlag = process.env.PRIME_AGENT_KERNEL_FORKSERVER;-beforeAll(() => {- process.env.PRIME_AGENT_KERNEL_FORKSERVER = "0";-});-afterAll(() => {- if (savedForkFlag === undefined) delete process.env.PRIME_AGENT_KERNEL_FORKSERVER;- else process.env.PRIME_AGENT_KERNEL_FORKSERVER = savedForkFlag;-});-function writeFakePython(opts: { sleepSeconds?: number } = {}): { python: string; countRuns: () => number } {const python = join(tempDir, "python");const countFile = join(tempDir, "runs");@@ -97,8 +91,8 @@ describe("IpythonKernelProvisioner", () => {const { python, countRuns } = writeFakePython();const provisioner = new IpythonKernelProvisioner(tempDir, { python });- await expect(provisioner.ensure()).rejects.toThrow(/Kernel exited before resolving ports/);- await expect(provisioner.ensure()).rejects.toThrow(/Kernel exited before resolving ports/);+ await expect(provisioner.ensure()).rejects.toThrow(/Kernel exited before ready/);+ await expect(provisioner.ensure()).rejects.toThrow(/Kernel exited before ready/);expect(countRuns()).toBe(2);});@@ -123,7 +117,7 @@ describe("IpythonKernelProvisioner", () => {provisioner.prewarm();const messages: string[] = [];const joined = provisioner.ensure((message) => messages.push(message));- expect(messages).toContain("Starting IPython kernel...");+ expect(messages).toContain("Starting Python kernel...");await expect(joined).rejects.toThrow();});@@ -162,7 +156,7 @@ describe("IpythonKernelProvisioner", () => {const started = provisioner.ensure(undefined, controller.signal);controller.abort();- await expect(started).rejects.toThrow("IPython execution aborted");+ await expect(started).rejects.toThrow("Python execution aborted");release();await new Promise((r) => setTimeout(r, 50));@@ -196,11 +190,11 @@ describe("IpythonKernelProvisioner", () => {it("does not dispose a running kernel when an ensure caller is aborted", async () => {const provisioner = new IpythonKernelProvisioner(tempDir, {});const dispose = vi.fn(async () => {});- const manager = { dispose, isRunning: true } as unknown as KernelManager;+ const manager = { dispose, isRunning: true } as unknown as KernelClient;Object.assign(provisioner as unknown as {- managerPromise: Promise<KernelManager>;- startedManager: KernelManager;+ managerPromise: Promise<KernelClient>;+ startedManager: KernelClient;},{managerPromise: Promise.resolve(manager),@@ -210,7 +204,7 @@ describe("IpythonKernelProvisioner", () => {const controller = new AbortController();controller.abort();- await expect(provisioner.ensure(undefined, controller.signal)).rejects.toThrow("IPython execution aborted");+ await expect(provisioner.ensure(undefined, controller.signal)).rejects.toThrow("Python execution aborted");expect(dispose).not.toHaveBeenCalled();expect(provisioner.manager).toBe(manager);});@@ -219,10 +213,10 @@ describe("IpythonKernelProvisioner", () => {const provisioner = new IpythonKernelProvisioner(tempDir, {});Object.assign(provisioner as unknown as {- managerPromise: Promise<KernelManager>;+ managerPromise: Promise<KernelClient>;},{- managerPromise: new Promise<KernelManager>(() => {}),+ managerPromise: new Promise<KernelClient>(() => {}),},);const controller = new AbortController();@@ -238,38 +232,28 @@ describe("IpythonKernelProvisioner", () => {expect(internals.startupListeners.has(onProgress)).toBe(false);});- it("applies shell settings to bash cells after leading blank lines", async () => {- const execute = vi.fn<KernelManager["execute"]>().mockResolvedValueOnce(okExecuteResult());- const manager = { execute } as unknown as KernelManager;+ it("surfaces backgroundOutput in details without changing model content", async () => {+ const execute = vi+ .fn<KernelClient["execute"]>()+ .mockResolvedValueOnce({ ...okExecuteResult(), backgroundOutput: "bg-line" });+ const manager = { execute } as unknown as KernelClient;const ensure = vi.fn(async () => manager);const kill = vi.fn(async () => {});const provisioner = { ensure, kill } as unknown as IpythonKernelProvisioner;- const tool = createIpythonToolDefinition(tempDir, {- provisioner,- commandPrefix: "export TEST_PREFIX=1",- shellPath: "/custom/bash",- });+ const tool = createIpythonToolDefinition(tempDir, { provisioner });- await tool.execute(- "tool-call",- { code: "\n \r\n\t%%bash\r\necho body" },- undefined,- undefined,- {} as ExtensionContext,- );+ const result = await tool.execute("tool-call", { code: "x = 1" }, undefined, undefined, {} as ExtensionContext);- expect(execute).toHaveBeenCalledWith(- "\n \r\n\t%%script /custom/bash\r\nexport TEST_PREFIX=1\necho body",- expect.objectContaining({ signal: undefined, onStream: expect.any(Function) }),- );+ expect(result.details.backgroundOutput).toBe("bg-line");+ expect(result.content).toEqual([{ type: "text", text: "ok\n[background output (unattributed)]\nbg-line" }]);});it("lets the user wait when an interrupted kernel is still busy", async () => {const execute = vi- .fn<KernelManager["execute"]>()+ .fn<KernelClient["execute"]>().mockRejectedValueOnce(new KernelBusyAfterInterruptError()).mockResolvedValueOnce(okExecuteResult());- const manager = { execute } as unknown as KernelManager;+ const manager = { execute } as unknown as KernelClient;const ensure = vi.fn(async () => manager);const kill = vi.fn(async () => {});const provisioner = { ensure, kill } as unknown as IpythonKernelProvisioner;@@ -290,17 +274,17 @@ describe("IpythonKernelProvisioner", () => {signal: undefined,},);- expect(setWorkingMessage).toHaveBeenCalledWith("Waiting for IPython kernel...");+ expect(setWorkingMessage).toHaveBeenCalledWith("Waiting for Python kernel...");expect(setWorkingMessage).toHaveBeenLastCalledWith(undefined);});it("lets the user kill and restart a busy interrupted kernel", async () => {const busyManager = {- execute: vi.fn<KernelManager["execute"]>().mockRejectedValueOnce(new KernelBusyAfterInterruptError()),- } as unknown as KernelManager;+ execute: vi.fn<KernelClient["execute"]>().mockRejectedValueOnce(new KernelBusyAfterInterruptError()),+ } as unknown as KernelClient;const freshManager = {- execute: vi.fn<KernelManager["execute"]>().mockResolvedValueOnce(okExecuteResult()),- } as unknown as KernelManager;+ execute: vi.fn<KernelClient["execute"]>().mockResolvedValueOnce(okExecuteResult()),+ } as unknown as KernelClient;const ensure = vi.fn(async () => {return ensure.mock.calls.length === 1 ? busyManager : freshManager;});@@ -321,7 +305,7 @@ describe("IpythonKernelProvisioner", () => {expect(ensure).toHaveBeenCalledTimes(2);expect(kill).toHaveBeenCalledTimes(1);expect(freshManager.execute).toHaveBeenCalledWith("x = 1", expect.objectContaining({ signal: undefined }));- expect(setWorkingMessage).toHaveBeenCalledWith("Restarting IPython kernel...");+ expect(setWorkingMessage).toHaveBeenCalledWith("Restarting Python kernel...");expect(setWorkingMessage).toHaveBeenLastCalledWith(undefined);});@@ -342,7 +326,7 @@ describe("IpythonKernelProvisioner", () => {});});-describe("KernelManager session cleanup during startup", () => {+describe("ReplKernelManager session cleanup during startup", () => {beforeEach(() => {tempDir = mkdtempSync(join(tmpdir(), "prime-agent-kernel-cleanup-"));});@@ -356,16 +340,16 @@ describe("KernelManager session cleanup during startup", () => {it("disposes a kernel that is still booting when its session is cleaned up", async () => {const python = join(tempDir, "python");- // Never writes connection ports - stays in the booting phase until killed.+ // Never emits the ready line - stays in the booting phase until killed.writeFileSync(python, ["#!/bin/sh", "sleep 30", ""].join("\n"));chmodSync(python, 0o755);const sessionId = `provisioner-test-${Date.now()}`;- const manager = new KernelManager({ python, cwd: tempDir, sessionId });+ const manager = new ReplKernelManager({ python, cwd: tempDir, sessionId });try {const startup = manager.start();cleanupSessionResources(sessionId);- await expect(startup).rejects.toThrow(/Kernel exited before resolving ports|disposed during startup/);+ await expect(startup).rejects.toThrow(/Kernel exited before ready|disposed during startup/);expect(manager.isRunning).toBe(false);} finally {await manager.dispose();diff --git a/packages/coding-agent/test/kernel-abort.test.ts b/packages/coding-agent/test/kernel-abort.test.tsdeleted file mode 100644index 4afe24d364..0000000000--- a/packages/coding-agent/test/kernel-abort.test.ts+++ /dev/null@@ -1,365 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vitest";-import { AGENT_MESSAGE_DISPLAY_MIME, KernelManager, type KernelSentAgentMessage } from "../src/core/kernel/index.js";--async function waitForCalls(mock: { mock: { calls: unknown[][] } }, count: number): Promise<void> {- for (let i = 0; i < 20; i++) {- if (mock.mock.calls.length >= count) {- return;- }- await Promise.resolve();- }- expect(mock.mock.calls.length).toBeGreaterThanOrEqual(count);-}--describe("KernelManager abort handling", () => {- afterEach(() => {- vi.useRealTimers();- });-- it("does not poison startup after a caller starts with an aborted signal", async () => {- const manager = new KernelManager({ cwd: process.cwd() });- let startCount = 0;- Object.assign(- manager as unknown as {- doStart: () => Promise<void>;- },- {- doStart: async () => {- startCount++;- },- },- );- const controller = new AbortController();- controller.abort();-- await expect(manager.start({ signal: controller.signal })).rejects.toThrow("Kernel startup aborted");- await expect(manager.start()).resolves.toBeUndefined();- expect(startCount).toBe(1);- });-- it("does not cancel shared startup when one waiting caller aborts", async () => {- const manager = new KernelManager({ cwd: process.cwd() });- let releaseStart: () => void = () => {};- let startCount = 0;- Object.assign(- manager as unknown as {- doStart: () => Promise<void>;- },- {- doStart: async () => {- startCount++;- await new Promise<void>((resolve) => {- releaseStart = resolve;- });- },- },- );- const controller = new AbortController();-- const firstStart = manager.start({ signal: controller.signal });- const secondStart = manager.start();- controller.abort();-- await expect(firstStart).rejects.toThrow("Kernel startup aborted");- releaseStart();- await expect(secondStart).resolves.toBeUndefined();- expect(startCount).toBe(1);- });-- it("settles an aborted execution when the kernel never reports idle", async () => {- vi.useFakeTimers();- const manager = new KernelManager({ cwd: process.cwd() });- const shellSend = vi.fn(async (_frames: Buffer[]) => {});- const controlSend = vi.fn(async (_frames: Buffer[]) => {});- const kernelKill = vi.fn((_signal?: NodeJS.Signals | number) => true);- Object.assign(- manager as unknown as {- state: "running";- connection: {- ip: "127.0.0.1";- transport: "tcp";- shell_port: number;- iopub_port: number;- stdin_port: number;- control_port: number;- hb_port: number;- signature_scheme: "hmac-sha256";- key: string;- kernel_name: string;- };- shell: { send: (frames: Buffer[]) => Promise<void>; close: () => void };- control: { send: (frames: Buffer[]) => Promise<void>; close: () => void };- kernel: { kill: (signal?: NodeJS.Signals | number) => boolean };- start: () => Promise<void>;- },- {- state: "running",- connection: {- ip: "127.0.0.1",- transport: "tcp",- shell_port: 1,- iopub_port: 2,- stdin_port: 3,- control_port: 4,- hb_port: 5,- signature_scheme: "hmac-sha256",- key: "test-key",- kernel_name: "python3",- },- shell: { send: shellSend, close: vi.fn() },- control: { send: controlSend, close: vi.fn() },- kernel: { kill: kernelKill },- start: async () => {},- },- );- const controller = new AbortController();- const lateSentAgentMessages: KernelSentAgentMessage[] = [];-- const executePromise = manager.execute("while True: pass", {- signal: controller.signal,- onLateSentAgentMessage: (message) => lateSentAgentMessages.push(message),- });- await waitForCalls(shellSend, 1);- expect(shellSend).toHaveBeenCalledTimes(1);-- controller.abort();- await vi.advanceTimersByTimeAsync(1000);-- await expect(executePromise).resolves.toMatchObject({ status: "aborted" });- expect(controlSend).toHaveBeenCalled();- expect(kernelKill).not.toHaveBeenCalled();-- const internals = manager as unknown as {- activeExecution?: { requestMsgId: string };- handleExecutionMessage: (incoming: {- header: { msg_type: string };- parent_header: Record<string, unknown>;- metadata: Record<string, unknown>;- content: Record<string, unknown>;- }) => void;- };- const activeExecution = internals.activeExecution;- expect(activeExecution).toBeDefined();- if (!activeExecution) {- throw new Error("Expected active execution to remain until kernel idle");- }- internals.handleExecutionMessage({- header: { msg_type: "display_data" },- parent_header: { msg_id: activeExecution.requestMsgId },- metadata: {},- content: {- data: {- [AGENT_MESSAGE_DISPLAY_MIME]: {- id: "agentmsg-after-abort",- message: "still sent",- deliveryStatus: "delivered",- target: { activeSessionId: "beta", sessionId: "session-beta" },- },- },- },- });- expect(lateSentAgentMessages).toEqual([- {- id: "agentmsg-after-abort",- message: "still sent",- deliveryStatus: "delivered",- target: { activeSessionId: "beta", sessionId: "session-beta" },- },- ]);- const secondExecutePromise = manager.execute("x = 1");- await Promise.resolve();- expect(shellSend).toHaveBeenCalledTimes(1);-- internals.handleExecutionMessage({- header: { msg_type: "status" },- parent_header: { msg_id: activeExecution.requestMsgId },- metadata: {},- content: { execution_state: "idle" },- });- await waitForCalls(shellSend, 2);- expect(shellSend).toHaveBeenCalledTimes(2);-- const secondExecution = internals.activeExecution;- expect(secondExecution).toBeDefined();- if (!secondExecution) {- throw new Error("Expected second execution to start after previous cell went idle");- }- internals.handleExecutionMessage({- header: { msg_type: "status" },- parent_header: { msg_id: secondExecution.requestMsgId },- metadata: {},- content: { execution_state: "idle" },- });- await expect(secondExecutePromise).resolves.toMatchObject({ status: "ok" });-- manager.disposeSync();- expect(kernelKill).toHaveBeenCalledWith("SIGTERM");- });-- it("settles an aborted execution when shell send never resolves", async () => {- vi.useFakeTimers();- const manager = new KernelManager({ cwd: process.cwd() });- const shellSend = vi.fn((_frames: Buffer[]) => new Promise<void>(() => {}));- const controlSend = vi.fn(async (_frames: Buffer[]) => {});- Object.assign(- manager as unknown as {- state: "running";- connection: {- ip: "127.0.0.1";- transport: "tcp";- shell_port: number;- iopub_port: number;- stdin_port: number;- control_port: number;- hb_port: number;- signature_scheme: "hmac-sha256";- key: string;- kernel_name: string;- };- shell: { send: (frames: Buffer[]) => Promise<void>; close: () => void };- control: { send: (frames: Buffer[]) => Promise<void>; close: () => void };- start: () => Promise<void>;- },- {- state: "running",- connection: {- ip: "127.0.0.1",- transport: "tcp",- shell_port: 1,- iopub_port: 2,- stdin_port: 3,- control_port: 4,- hb_port: 5,- signature_scheme: "hmac-sha256",- key: "test-key",- kernel_name: "python3",- },- shell: { send: shellSend, close: vi.fn() },- control: { send: controlSend, close: vi.fn() },- start: async () => {},- },- );- const controller = new AbortController();-- const executePromise = manager.execute("while True: pass", { signal: controller.signal });- await waitForCalls(shellSend, 1);- controller.abort();- await vi.advanceTimersByTimeAsync(1000);-- await expect(executePromise).resolves.toMatchObject({ status: "aborted" });- expect(controlSend).toHaveBeenCalled();- });-- it("fails a later execution fast when the interrupted cell never idles", async () => {- vi.useFakeTimers();- const manager = new KernelManager({ cwd: process.cwd() });- const shellSend = vi.fn(async (_frames: Buffer[]) => {});- const controlSend = vi.fn(async (_frames: Buffer[]) => {});- Object.assign(- manager as unknown as {- state: "running";- connection: {- ip: "127.0.0.1";- transport: "tcp";- shell_port: number;- iopub_port: number;- stdin_port: number;- control_port: number;- hb_port: number;- signature_scheme: "hmac-sha256";- key: string;- kernel_name: string;- };- shell: { send: (frames: Buffer[]) => Promise<void>; close: () => void };- control: { send: (frames: Buffer[]) => Promise<void>; close: () => void };- start: () => Promise<void>;- },- {- state: "running",- connection: {- ip: "127.0.0.1",- transport: "tcp",- shell_port: 1,- iopub_port: 2,- stdin_port: 3,- control_port: 4,- hb_port: 5,- signature_scheme: "hmac-sha256",- key: "test-key",- kernel_name: "python3",- },- shell: { send: shellSend, close: vi.fn() },- control: { send: controlSend, close: vi.fn() },- start: async () => {},- },- );- const controller = new AbortController();-- const executePromise = manager.execute("while True: pass", { signal: controller.signal });- await waitForCalls(shellSend, 1);- controller.abort();- await vi.advanceTimersByTimeAsync(1000);- await expect(executePromise).resolves.toMatchObject({ status: "aborted" });-- const secondExecutePromise = manager.execute("x = 1");- const secondExecuteExpectation = expect(secondExecutePromise).rejects.toThrow(- "IPython kernel is still running the previously interrupted cell",- );- await Promise.resolve();- await vi.advanceTimersByTimeAsync(5000);-- await secondExecuteExpectation;- expect(shellSend).toHaveBeenCalledTimes(1);- expect(controlSend).toHaveBeenCalled();- manager.disposeSync();- });-- it("starts the snapshot timeout after earlier kernel work finishes", async () => {- vi.useFakeTimers();- const manager = new KernelManager({- cwd: process.cwd(),- snapshot: { path: "/tmp/test-state.dill", manifestPath: "/tmp/test-state.json" },- });- let releaseQueue: () => void = () => {};- const previousExecution = new Promise<void>((resolve) => {- releaseQueue = resolve;- });- const executeInner = vi.fn(- async (_code: string, opts: { signal?: AbortSignal }) =>- await new Promise<{ stdout: string; stderr: string; status: "aborted"; durationMs: number }>((resolve) => {- opts.signal?.addEventListener(- "abort",- () => resolve({ stdout: "", stderr: "", status: "aborted", durationMs: 5000 }),- { once: true },- );- }),- );- Object.assign(- manager as unknown as {- state: "running";- executionQueue: Promise<void>;- executeInner: typeof executeInner;- start: () => Promise<void>;- },- { state: "running", executionQueue: previousExecution, executeInner, start: async () => {} },- );-- const snapshot = (- manager as unknown as {- captureSnapshot: (options?: { executionTimeoutMs?: number }) => Promise<unknown>;- }- ).captureSnapshot({ executionTimeoutMs: 5000 });- await vi.advanceTimersByTimeAsync(5000);- expect(executeInner).not.toHaveBeenCalled();-- releaseQueue();- await waitForCalls(executeInner, 1);- const signal = executeInner.mock.calls[0]?.[1].signal;- expect(signal?.aborted).toBe(false);- await vi.advanceTimersByTimeAsync(4999);- expect(signal?.aborted).toBe(false);- await vi.advanceTimersByTimeAsync(1);- expect(signal?.aborted).toBe(true);- await expect(snapshot).resolves.toBeNull();- });-});diff --git a/packages/coding-agent/test/kernel-agent-message-skill.test.ts b/packages/coding-agent/test/kernel-agent-message-skill.test.tsindex 5e75b8883c..f7cd4ac3be 100644--- a/packages/coding-agent/test/kernel-agent-message-skill.test.ts+++ b/packages/coding-agent/test/kernel-agent-message-skill.test.ts@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";import { getBundledSkillsDir } from "../src/config.js";-import { KernelManager, type KernelSentAgentMessage } from "../src/core/kernel/index.js";+import { type KernelSentAgentMessage, ReplKernelManager } from "../src/core/kernel/index.js";import type { PythonSkillRuntimeInfo } from "../src/core/skills.js";import { IpythonKernelProvisioner } from "../src/core/tools/ipython.js";@@ -266,7 +266,7 @@ background_send = asyncio.create_task(send_later())`,});it("bounds retained handlers for late sent messages", async () => {- const manager = new KernelManager({ cwd: tempDir });+ const manager = new ReplKernelManager({ cwd: tempDir });const host = manager as unknown as LateHandlerRetentionHost;const handler = () => {};diff --git a/packages/coding-agent/test/kernel-attach-image-skill.test.ts b/packages/coding-agent/test/kernel-attach-image-skill.test.tsindex 6ece9e3ba2..b4915102c9 100644--- a/packages/coding-agent/test/kernel-attach-image-skill.test.ts+++ b/packages/coding-agent/test/kernel-attach-image-skill.test.ts@@ -263,8 +263,8 @@ except ValueError as error:provisioner = new IpythonKernelProvisioner(tempDir, { pythonSkills: [] });const manager = await provisioner.ensure();const result = await manager.execute(`-from IPython.display import display-display({"application/vnd.prime-agent.attachment+json": {"mime_type": "image/png", "data": "A" * 10_000_001}}, raw=True)+from rlm import emit+emit({"application/vnd.prime-agent.attachment+json": {"mime_type": "image/png", "data": "A" * 10_000_001}})print("done")`);diff --git a/packages/coding-agent/test/kernel-bootstrap.test.ts b/packages/coding-agent/test/kernel-bootstrap.test.tsindex eeb2fc0d15..cda17807c4 100644--- a/packages/coding-agent/test/kernel-bootstrap.test.ts+++ b/packages/coding-agent/test/kernel-bootstrap.test.ts@@ -29,8 +29,7 @@ function writeBootstrapVersion(venv: string, pythonSkills: readonly KernelPythonwriteFileSync(join(venv, ".bootstrap-version"),`${JSON.stringify({- schema: 8,- ipykernel: "ipykernel",+ schema: 9,runtime: runtimeIdentity,snapshot: "dill",extraUvArgs: DEFAULT_RLM_EXTRA_UV_ARGS,@@ -121,7 +120,7 @@ function installFakeUv(): string {"#!/bin/sh",'if [ "$1" = "-c" ]; then',' case "$2" in',- ' "import ipykernel"|"import rlm") exit 0 ;;',+ ' "import rlm") exit 0 ;;',...extraImportCases,' *"_harness_methods"*) exit 0 ;;'," *) exit 1 ;;",@@ -174,7 +173,7 @@ describe("kernel bootstrap", () => {expect(getKernelVenvDir()).toBe(venv);});- it("bootstraps a missing venv with uv, ipykernel, prime-agent-runtime, and default extra packages", async () => {+ it("bootstraps a missing venv with uv, prime-agent-runtime, and default extra packages", async () => {const logPath = installFakeUv();const venv = join(tempDir, "kernel-venv");process.env.PRIME_AGENT_KERNEL_VENV = venv;@@ -185,7 +184,7 @@ describe("kernel bootstrap", () => {expect(log).toContain("python install 3.11");expect(log).toContain(`venv ${venv} --python 3.11 --seed`);expect(log).toContain("pip install --python");- expect(log).toContain("ipykernel");+ expect(log).not.toContain("ipykernel");expect(log).toContain("prime-agent-runtime");expect(log).toContain("dill");for (const uvArg of DEFAULT_RLM_EXTRA_UV_ARGS) {@@ -193,8 +192,7 @@ describe("kernel bootstrap", () => {}const version = JSON.parse(readFileSync(join(venv, ".bootstrap-version"), "utf8"));expect(version).toEqual({- schema: 8,- ipykernel: "ipykernel",+ schema: 9,runtime: runtimeIdentity,snapshot: "dill",extraUvArgs: DEFAULT_RLM_EXTRA_UV_ARGS,@@ -317,7 +315,7 @@ version = "0.1.0"const python = join(venv, "bin", "python");const pythonSkill = createPythonSkill();mkdirSync(join(venv, "bin"), { recursive: true });- writeFakePython(python, ["ipykernel", "rlm", ...DEFAULT_RLM_EXTRA_IMPORT_NAMES]);+ writeFakePython(python, ["rlm", ...DEFAULT_RLM_EXTRA_IMPORT_NAMES]);writeBootstrapVersion(venv, [pythonSkill]);writeFileSync(pythonSkill.pyprojectPath,@@ -380,12 +378,11 @@ dependencies = ["httpx"]const python = join(venv, "bin", "python");const pythonSkill = createPythonSkill();mkdirSync(join(venv, "bin"), { recursive: true });- writeFakePython(python, ["ipykernel", "rlm", ...DEFAULT_RLM_EXTRA_IMPORT_NAMES]);+ writeFakePython(python, ["rlm", ...DEFAULT_RLM_EXTRA_IMPORT_NAMES]);writeFileSync(join(venv, ".bootstrap-version"),`${JSON.stringify({schema: 4,- ipykernel: "ipykernel",runtime: "prime-agent-runtime",extraUvArgs: DEFAULT_RLM_EXTRA_UV_ARGS,pythonSkills: [@@ -420,7 +417,7 @@ dependencies = ["httpx"]const venv = join(tempDir, "kernel-venv");const python = join(venv, "bin", "python");mkdirSync(join(venv, "bin"), { recursive: true });- writeFakePython(python, ["ipykernel", "rlm", ...DEFAULT_RLM_EXTRA_IMPORT_NAMES]);+ writeFakePython(python, ["rlm", ...DEFAULT_RLM_EXTRA_IMPORT_NAMES]);writeBootstrapVersion(venv);process.env.PRIME_AGENT_KERNEL_VENV = venv;@@ -432,12 +429,11 @@ dependencies = ["httpx"]const venv = join(tempDir, "kernel-venv");const python = join(venv, "bin", "python");mkdirSync(join(venv, "bin"), { recursive: true });- writeFakePython(python, ["ipykernel", "rlm", ...DEFAULT_RLM_EXTRA_IMPORT_NAMES]);+ writeFakePython(python, ["rlm", ...DEFAULT_RLM_EXTRA_IMPORT_NAMES]);writeFileSync(join(venv, ".bootstrap-version"),`${JSON.stringify({- schema: 8,- ipykernel: "ipykernel",+ schema: 9,runtime: "sha256:stale",snapshot: "dill",extraUvArgs: DEFAULT_RLM_EXTRA_UV_ARGS,@@ -464,7 +460,7 @@ dependencies = ["httpx"]"#!/bin/sh",'if [ "$1" = "-c" ]; then',' case "$2" in',- ' "import ipykernel"|"import rlm") exit 0 ;;',+ ' "import rlm") exit 0 ;;'," *) exit 1 ;;"," esac","fi",@@ -494,7 +490,7 @@ dependencies = ["httpx"]it("uses PRIME_AGENT_KERNEL_PYTHON as an override contract", async () => {const overridePython = join(tempDir, "override-python");- writeFakePython(overridePython, ["ipykernel", "rlm", ...DEFAULT_RLM_EXTRA_IMPORT_NAMES]);+ writeFakePython(overridePython, ["rlm", ...DEFAULT_RLM_EXTRA_IMPORT_NAMES]);process.env.PRIME_AGENT_KERNEL_PYTHON = overridePython;await expect(ensureKernelPython()).resolves.toBe(overridePython);@@ -503,7 +499,7 @@ dependencies = ["httpx"]it("allows PRIME_AGENT_KERNEL_PYTHON missing Python skill imports", async () => {const overridePython = join(tempDir, "override-python");const pythonSkill = createPythonSkill();- writeFakePython(overridePython, ["ipykernel", "rlm", ...DEFAULT_RLM_EXTRA_IMPORT_NAMES]);+ writeFakePython(overridePython, ["rlm", ...DEFAULT_RLM_EXTRA_IMPORT_NAMES]);process.env.PRIME_AGENT_KERNEL_PYTHON = overridePython;await expect(ensureKernelPython({ pythonSkills: [pythonSkill] })).resolves.toBe(overridePython);@@ -511,11 +507,7 @@ dependencies = ["httpx"]it("rejects PRIME_AGENT_KERNEL_PYTHON missing default extra packages", async () => {const overridePython = join(tempDir, "override-python");- writeFakePython(overridePython, [- "ipykernel",- "rlm",- ...DEFAULT_RLM_EXTRA_IMPORT_NAMES.filter((name) => name !== "yaml"),- ]);+ writeFakePython(overridePython, ["rlm", ...DEFAULT_RLM_EXTRA_IMPORT_NAMES.filter((name) => name !== "yaml")]);process.env.PRIME_AGENT_KERNEL_PYTHON = overridePython;await expect(ensureKernelPython()).rejects.toThrow(/default Python packages \(yaml \(PyYAML\)\)/);@@ -523,7 +515,7 @@ dependencies = ["httpx"]it("rejects PRIME_AGENT_KERNEL_PYTHON with a stale rlm runtime", async () => {const overridePython = join(tempDir, "override-python");- writeFakePython(overridePython, ["ipykernel"]);+ writeFakePython(overridePython, ["dill"]);process.env.PRIME_AGENT_KERNEL_PYTHON = overridePython;await expect(ensureKernelPython()).rejects.toThrow(/current prime-agent-runtime with callable rlm\.run/);@@ -537,7 +529,7 @@ dependencies = ["httpx"]"#!/bin/sh",'if [ "$1" = "-c" ]; then',' case "$2" in',- ' "import ipykernel"|"import rlm") exit 0 ;;',+ ' "import rlm") exit 0 ;;',' *"_harness_methods"*) exit 1 ;;'," *\"assert not hasattr(rlm.rlm, 'background')\"*) exit 0 ;;"," *) exit 1 ;;",@@ -557,6 +549,6 @@ dependencies = ["httpx"]writeFakePython(overridePython, []);process.env.PRIME_AGENT_KERNEL_PYTHON = overridePython;- await expect(ensureKernelPython()).rejects.toThrow(/missing ipykernel/);+ await expect(ensureKernelPython()).rejects.toThrow(/PRIME_AGENT_KERNEL_PYTHON points to a Python missing/);});});diff --git a/packages/coding-agent/test/kernel-fork-server-protocol.test.ts b/packages/coding-agent/test/kernel-fork-server-protocol.test.tsdeleted file mode 100644index 3967132779..0000000000--- a/packages/coding-agent/test/kernel-fork-server-protocol.test.ts+++ /dev/null@@ -1,366 +0,0 @@-import { spawnSync } from "node:child_process";-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";-import { homedir, tmpdir } from "node:os";-import { join } from "node:path";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { type ForkedKernelHandle, ForkServer, ForkServerUnavailable } from "../src/core/kernel/fork-server.js";-import { ORPHAN_PROCESS_JOURNAL_ENV } from "../src/core/orphan-process-journal.js";--// Drives the REAL Python forkserver script through the REAL ForkServer class.-// Stub Python modules stand in for IPython/ipykernel so the forked child stays-// alive without a real kernel — fork itself is safe here even on macOS because-// the child never touches the frameworks that make fork-without-exec unsafe.-const STUB_KERNELAPP = [- "import os",- "import time",- "",- "",- "class IPKernelApp:",- " @classmethod",- " def clear_instance(cls):",- " pass",- "",- " @classmethod",- " def instance(cls, **_kwargs):",- " return cls()",- "",- " def initialize(self, _argv):",- " pass",- "",- " def start(self):",- " # Env knob: lets tests fork a child that exits immediately (the",- " # per-kernel env is applied in the child before start()).",- " if os.environ.get('STUB_KERNEL_EXIT'):",- " return",- " while True:",- " time.sleep(1)",- "",-].join("\n");--function writeStubModules(dir: string): void {- writeFileSync(join(dir, "IPython.py"), "");- writeFileSync(join(dir, "jupyter_client.py"), "");- writeFileSync(join(dir, "nest_asyncio.py"), "");- const ipykernelDir = join(dir, "ipykernel");- mkdirSync(ipykernelDir);- writeFileSync(join(ipykernelDir, "__init__.py"), "");- writeFileSync(join(ipykernelDir, "kernelapp.py"), STUB_KERNELAPP);-}--function killQuietly(pid: number | undefined): void {- if (pid === undefined) return;- try {- process.kill(pid, "SIGKILL");- } catch {- // Already exited.- }-}--const havePython3 = process.platform !== "win32" && spawnSync("python3", ["-V"]).status === 0;-const describeIf = havePython3 ? describe : describe.skip;--describeIf("forkserver kill/liveness protocol (stub python)", () => {- let tempDir = "";- let server: ForkServer | undefined;- let savedPythonPath: string | undefined;- const leakedPids: number[] = [];-- beforeEach(() => {- tempDir = mkdtempSync(join(tmpdir(), "prime-agent-forkserver-proto-"));- const stubDir = join(tempDir, "stubs");- mkdirSync(stubDir);- writeStubModules(stubDir);- // launchEnv is snapshotted at ForkServer construction, so the template- // imports the stubs.- savedPythonPath = process.env.PYTHONPATH;- process.env.PYTHONPATH = stubDir;- server = new ForkServer({ python: "python3" });- });-- afterEach(() => {- if (savedPythonPath === undefined) delete process.env.PYTHONPATH;- else process.env.PYTHONPATH = savedPythonPath;- server?.dispose();- server = undefined;- // The stub app ignores parent_handle, so leak-proof the test itself.- for (const pid of leakedPids.splice(0)) killQuietly(pid);- rmSync(tempDir, { recursive: true, force: true });- });-- async function spawnStubKernel(- target: ForkServer = server!,- env?: Record<string, string | undefined>,- ): Promise<ForkedKernelHandle> {- const handle = await target.spawnKernel({ connectionPath: join(tempDir, "conn.json"), env });- leakedPids.push(handle.pid);- return handle;- }-- it("kills its own child through the protocol and observes the reap", async () => {- const handle = await spawnStubKernel();- expect(await handle.isAlive()).toBe(true);- expect(await handle.kill("TERM")).toBe("signaled");- await vi.waitFor(async () => {- expect(await handle.isAlive()).toBe(false);- });- // OS-level confirmation (test-side observation only, never a signal path).- await vi.waitFor(() => {- expect(() => process.kill(handle.pid, 0)).toThrow();- });- }, 15_000);-- it("reports already-exited after reap and fails closed on an unknown fork id", async () => {- const handle = await spawnStubKernel();- expect(await handle.kill("TERM")).toBe("signaled");- await vi.waitFor(async () => {- expect(await handle.kill("TERM")).toBe("already-exited");- });- // A fork id the forkserver never issued: nothing may be signaled.- expect(await server!.killChild(999_999, "TERM")).toBe("unknown-pid");- expect(await server!.isChildAlive(999_999)).toBe(false);- }, 15_000);-- it("liveness reflects the reap table on external child death", async () => {- const handle = await spawnStubKernel();- expect(await handle.isAlive()).toBe(true);- // External death (not via the protocol): proves the SIGCHLD reaper drives- // the registry independently of the kill path.- process.kill(handle.pid, "SIGTERM");- await vi.waitFor(async () => {- expect(await handle.isAlive()).toBe(false);- });- }, 15_000);-- it("kill outcomes stay correct while sibling children churn and get reaped", async () => {- // Regression for the SIGCHLD-in-watcher-thread race: external deaths storm- // the reaper while kill requests are in flight; every reply must still match- // the child's true state (no false "signaled" for a freed pid).- const keep = await Promise.all([spawnStubKernel(), spawnStubKernel(), spawnStubKernel()]);- const churn = await Promise.all([spawnStubKernel(), spawnStubKernel(), spawnStubKernel()]);- for (const handle of churn) process.kill(handle.pid, "SIGKILL");- const outcomes = await Promise.all(keep.map((handle) => handle.kill("TERM")));- expect(outcomes).toEqual(["signaled", "signaled", "signaled"]);- for (const handle of churn) {- await vi.waitFor(async () => {- expect(await handle.kill("TERM")).toBe("already-exited");- });- }- }, 15_000);-- it("a fast-exiting child never lands alive; its handle stays already-exited across new forks", async () => {- // STUB_KERNEL_EXIT makes the forked child return from start() immediately,- // so it can be reaped as early as the OS allows relative to the parent-side- // registry insertion — the SIGCHLD-blocked fork bookkeeping must still- // record it under its own id and mark exactly that entry not-alive.- const fast = await spawnStubKernel(server!, { STUB_KERNEL_EXIT: "1" });- await vi.waitFor(async () => {- expect(await fast.isAlive()).toBe(false);- });- expect(await fast.kill("TERM")).toBe("already-exited");- // Id-keying invariant: a later fork gets a fresh id (even if the OS reuses- // the pid, which we can't force), and the old handle's answers don't change.- const next = await spawnStubKernel();- expect(await next.isAlive()).toBe(true);- expect(await fast.isAlive()).toBe(false);- expect(await fast.kill("TERM")).toBe("already-exited");- expect(await next.kill("TERM")).toBe("signaled");- }, 15_000);-- it("evicted registry entries fail closed (unknown-pid/false), recent ones stay answerable", async () => {- // A tiny history bound (argv[2] to the script) makes FIFO eviction reachable.- const bounded = new ForkServer({ python: "python3", historyBound: 2 });- try {- const oldest = await spawnStubKernel(bounded, { STUB_KERNEL_EXIT: "1" });- await vi.waitFor(async () => {- expect(await oldest.kill("TERM")).toBe("already-exited");- });- const middle = await spawnStubKernel(bounded, { STUB_KERNEL_EXIT: "1" });- const newest = await spawnStubKernel(bounded, { STUB_KERNEL_EXIT: "1" });- // Three entries against a bound of 2: the oldest id has been evicted.- expect(await oldest.kill("TERM")).toBe("unknown-pid");- expect(await oldest.isAlive()).toBe(false);- for (const handle of [middle, newest]) {- await vi.waitFor(async () => {- expect(await handle.kill("TERM")).toBe("already-exited");- });- expect(await handle.isAlive()).toBe(false);- }- } finally {- bounded.dispose();- }- }, 15_000);-- it("keeps live entries answerable past the history bound and evicts only exited ones", async () => {- // A live child must never be evicted: an evicted-live entry would read- // dead to the liveness monitor and be unroutable for kill — the exact- // orphan leak this forkserver exists to prevent.- const bounded = new ForkServer({ python: "python3", historyBound: 2 });- try {- const oldest = await spawnStubKernel(bounded);- expect(await oldest.isAlive()).toBe(true);- const middle = await spawnStubKernel(bounded);- const newest = await spawnStubKernel(bounded);- // Three live entries against a bound of 2: none may be evicted.- expect(await oldest.isAlive()).toBe(true);- expect(await middle.isAlive()).toBe(true);- expect(await newest.isAlive()).toBe(true);- // Once dead entries exist, the next fork sweeps them out instead.- expect(await oldest.kill("TERM")).toBe("signaled");- expect(await middle.kill("TERM")).toBe("signaled");- await vi.waitFor(async () => {- expect(await oldest.isAlive()).toBe(false);- expect(await middle.isAlive()).toBe(false);- });- const extra = await spawnStubKernel(bounded);- // Bound 2 with two dead entries: both are evicted, the live ones stay.- expect(await oldest.kill("TERM")).toBe("unknown-pid");- expect(await middle.kill("TERM")).toBe("unknown-pid");- expect(await newest.isAlive()).toBe(true);- expect(await extra.isAlive()).toBe(true);- expect(await newest.kill("TERM")).toBe("signaled");- expect(await extra.kill("TERM")).toBe("signaled");- } finally {- bounded.dispose();- }- }, 15_000);-- it("handle kill/isAlive reject with ForkServerUnavailable when the server is dead", async () => {- const handle = await spawnStubKernel();- server!.dispose();- await expect(handle.kill("TERM")).rejects.toBeInstanceOf(ForkServerUnavailable);- await expect(handle.isAlive()).rejects.toBeInstanceOf(ForkServerUnavailable);- }, 15_000);-- describe("forkserver orphan journal", () => {- let journalPath = "";- const savedJournal = process.env[ORPHAN_PROCESS_JOURNAL_ENV];-- interface JournalRecord {- pid: number;- active: boolean;- }-- function readJournal(): JournalRecord[] {- if (!existsSync(journalPath)) return [];- return readFileSync(journalPath, "utf8")- .split("\n")- .filter(Boolean)- .map((line) => JSON.parse(line) as JournalRecord);- }-- beforeEach(() => {- journalPath = join(tempDir, "orphans.jsonl");- process.env[ORPHAN_PROCESS_JOURNAL_ENV] = journalPath;- });-- afterEach(() => {- if (savedJournal === undefined) delete process.env[ORPHAN_PROCESS_JOURNAL_ENV];- else process.env[ORPHAN_PROCESS_JOURNAL_ENV] = savedJournal;- });-- it("disposing a live forkserver delivers the kill and writes inactive", async () => {- await spawnStubKernel();- const records = readJournal();- expect(records).toHaveLength(1);- expect(records[0]).toMatchObject({ active: true });- server!.dispose();- const after = readJournal();- expect(after).toHaveLength(2);- expect(after[1]).toMatchObject({ pid: records[0]!.pid, active: false });- }, 15_000);-- it("a forkserver exit observed by the handle writes inactive", async () => {- await spawnStubKernel();- const forkserverPid = readJournal()[0]!.pid;- process.kill(forkserverPid, "SIGKILL");- // The exit event drives markDead → dispose with the exit already observed.- await vi.waitFor(() => {- const records = readJournal();- expect(records).toHaveLength(2);- expect(records[1]).toMatchObject({ pid: forkserverPid, active: false });- });- }, 15_000);-- it("a never-started forkserver writes no journal records on dispose", () => {- const idle = new ForkServer({ python: "python3" });- idle.dispose();- expect(readJournal()).toHaveLength(0);- });-- it("an unconfirmed kill with no observed exit leaves no inactive record", () => {- const unconfirmed = new ForkServer({ python: "python3" });- const internals = unconfirmed as unknown as {- proc?: { pid?: number; exitCode: number | null; signalCode: string | null; kill(): boolean };- };- internals.proc = { pid: 424242, exitCode: null, signalCode: null, kill: () => false };- unconfirmed.dispose();- expect(readJournal().some((r) => r.pid === 424242)).toBe(false);- });- });-});--function resolveKernelPython(): string | null {- const candidates = [- process.env.PRIME_AGENT_KERNEL_PYTHON,- join(homedir(), ".prime", "agent", "kernel-venv", "bin", "python"),- ].filter((p): p is string => Boolean(p));- for (const python of candidates) {- if (!existsSync(python)) continue;- const check = spawnSync(python, ["-c", "import ipykernel"], { encoding: "utf8" });- if (check.status === 0) return python;- }- return null;-}--const kernelPython = resolveKernelPython();-// Real ipykernel fork round-trip is linux-only: on darwin the forked child dies-// immediately (fork-without-exec is unsafe there), matching isForkServerEnabled.-const describeIfRealKernel = process.platform === "linux" && kernelPython ? describe : describe.skip;--describeIfRealKernel("forkserver kill/liveness protocol (real kernel)", { tags: ["kernel-heavy"] }, () => {- it("forks a real ipykernel, resolves ports, kills it via the protocol", async () => {- const dir = mkdtempSync(join(tmpdir(), "prime-agent-forkserver-real-"));- const connectionPath = join(dir, "connection.json");- writeFileSync(- connectionPath,- JSON.stringify({- ip: "127.0.0.1",- transport: "tcp",- shell_port: 0,- iopub_port: 0,- stdin_port: 0,- control_port: 0,- hb_port: 0,- signature_scheme: "hmac-sha256",- key: "test-key",- kernel_name: "python3",- }),- { mode: 0o600 },- );- const server = new ForkServer({ python: kernelPython! });- let pid: number | undefined;- try {- const handle = await server.spawnKernel({ connectionPath });- pid = handle.pid;- await vi.waitFor(- () => {- const info = JSON.parse(readFileSync(connectionPath, "utf8")) as { shell_port: number };- expect(info.shell_port).toBeGreaterThan(0);- },- { timeout: 20_000, interval: 250 },- );- expect(await handle.isAlive()).toBe(true);- expect(await handle.kill("TERM")).toBe("signaled");- await vi.waitFor(- async () => {- expect(await handle.isAlive()).toBe(false);- },- { timeout: 20_000, interval: 250 },- );- } finally {- server.dispose();- killQuietly(pid);- rmSync(dir, { recursive: true, force: true });- }- }, 60_000);-});diff --git a/packages/coding-agent/test/kernel-fork-server.test.ts b/packages/coding-agent/test/kernel-fork-server.test.tsdeleted file mode 100644index 4310326cab..0000000000--- a/packages/coding-agent/test/kernel-fork-server.test.ts+++ /dev/null@@ -1,47 +0,0 @@-import { afterEach, describe, expect, it } from "vitest";-import { ForkServerUnavailable, forkKernel, isForkServerEnabled } from "../src/core/kernel/fork-server.js";--const FORK_ENV = "PRIME_AGENT_KERNEL_FORKSERVER";--describe("fork-server gating", () => {- afterEach(() => {- delete process.env[FORK_ENV];- });-- it("is on by default on linux, opt-out via the flag", () => {- delete process.env[FORK_ENV];- expect(isForkServerEnabled()).toBe(process.platform === "linux");- process.env[FORK_ENV] = "0";- expect(isForkServerEnabled()).toBe(false);- process.env[FORK_ENV] = "1";- expect(isForkServerEnabled()).toBe(process.platform === "linux");- });-- it("rejects with ForkServerUnavailable when opted out so callers fall back", async () => {- process.env[FORK_ENV] = "0";- await expect(forkKernel("python3", { connectionPath: "/tmp/nope/connection.json" })).rejects.toBeInstanceOf(- ForkServerUnavailable,- );- });-- it("degrades to ForkServerUnavailable when the interpreter can't start", async () => {- if (process.platform !== "linux") return;- await expect(- forkKernel("/nonexistent/python-binary", { connectionPath: "/tmp/nope/connection.json" }),- ).rejects.toBeInstanceOf(ForkServerUnavailable);- }, 15_000);-- it("falls back to direct spawn for any PYTHON* startup-env override", async () => {- if (process.platform !== "linux") return;- // The guard treats the whole PYTHON* family as startup-affecting, so even a var- // not explicitly enumerated diverts to direct spawn (no var can be "missed").- for (const key of ["PYTHONPATH", "PYTHONUSERBASE", "PYTHONDONTWRITEBYTECODE"]) {- await expect(- forkKernel("python3", {- connectionPath: "/tmp/nope/connection.json",- env: { [key]: "/some/custom/value" },- }),- ).rejects.toBeInstanceOf(ForkServerUnavailable);- }- });-});diff --git a/packages/coding-agent/test/kernel-parent-watchdog.test.ts b/packages/coding-agent/test/kernel-parent-watchdog.test.tsdeleted file mode 100644index 565b312ee7..0000000000--- a/packages/coding-agent/test/kernel-parent-watchdog.test.ts+++ /dev/null@@ -1,548 +0,0 @@-import { spawn, spawnSync } from "node:child_process";-import { EventEmitter } from "node:events";-import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";-import { homedir, tmpdir } from "node:os";-import { join } from "node:path";-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";-import { type ForkedKernelHandle, ForkServerUnavailable } from "../src/core/kernel/fork-server.js";-import { KernelManager } from "../src/core/kernel/index.js";-import { ORPHAN_PROCESS_JOURNAL_ENV } from "../src/core/orphan-process-journal.js";--const forkKernelMock = vi.hoisted(() => vi.fn());-const forkEnabledMock = vi.hoisted(() => vi.fn(() => false));--vi.mock("../src/core/kernel/fork-server.js", async (importOriginal) => {- const original = await importOriginal<typeof import("../src/core/kernel/fork-server.js")>();- return { ...original, forkKernel: forkKernelMock, isForkServerEnabled: forkEnabledMock };-});--let tempDir = "";-const savedForkFlag = process.env.PRIME_AGENT_KERNEL_FORKSERVER;-const savedJournalPath = process.env[ORPHAN_PROCESS_JOURNAL_ENV];--beforeAll(() => {- process.env.PRIME_AGENT_KERNEL_FORKSERVER = "0";-});-afterAll(() => {- if (savedForkFlag === undefined) delete process.env.PRIME_AGENT_KERNEL_FORKSERVER;- else process.env.PRIME_AGENT_KERNEL_FORKSERVER = savedForkFlag;-});--function writeFakePython(script: string[]): string {- const python = join(tempDir, "python");- writeFileSync(python, script.join("\n"));- chmodSync(python, 0o755);- return python;-}--interface JournalRecord {- pid: number;- ownerPid: number;- active: boolean;-}--function readJournalRecords(path: string): JournalRecord[] {- return readFileSync(path, "utf8")- .split("\n")- .filter(Boolean)- .map((line) => JSON.parse(line) as JournalRecord);-}--describe("kernel parent watchdog", () => {- beforeEach(() => {- tempDir = mkdtempSync(join(tmpdir(), "prime-agent-kernel-watchdog-"));- });-- afterEach(() => {- forkEnabledMock.mockReturnValue(false);- forkKernelMock.mockReset();- if (savedJournalPath === undefined) delete process.env[ORPHAN_PROCESS_JOURNAL_ENV];- else process.env[ORPHAN_PROCESS_JOURNAL_ENV] = savedJournalPath;- if (tempDir) {- rmSync(tempDir, { recursive: true, force: true });- tempDir = "";- }- });-- it("direct spawn sets JPY_PARENT_PID and journals the kernel pid", async () => {- const envDump = join(tempDir, "kernel-env");- const python = writeFakePython(["#!/bin/sh", `env > "${envDump}"`, "exit 42", ""]);- const journalPath = join(tempDir, "orphans.jsonl");- process.env[ORPHAN_PROCESS_JOURNAL_ENV] = journalPath;- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});- const manager = new KernelManager({ python, cwd: tempDir });-- try {- await expect(manager.execute("x")).rejects.toThrow(/Kernel exited before resolving ports/);- } finally {- errorSpy.mockRestore();- await manager.dispose();- }-- expect(readFileSync(envDump, "utf8")).toMatch(new RegExp(`^JPY_PARENT_PID=${process.pid}$`, "m"));-- // Self-exited child: the handle-based kill signals nothing, so the record must stay active.- await vi.waitFor(() => {- const records = readJournalRecords(journalPath);- expect(records).toHaveLength(1);- expect(records[0]?.ownerPid).toBe(process.pid);- expect(records[0]?.active).toBe(true);- });- });-- it("writes the inactive journal record only on a signaled forkserver kill outcome", async () => {- const journalPath = join(tempDir, "orphans.jsonl");- process.env[ORPHAN_PROCESS_JOURNAL_ENV] = journalPath;- forkEnabledMock.mockReturnValue(true);- const killMock = vi.fn(async (): Promise<"signaled"> => "signaled");- forkKernelMock.mockResolvedValue({- pid: 999999,- isAlive: async () => false,- kill: killMock,- });- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});- const manager = new KernelManager({ python: "/nonexistent/python", cwd: tempDir });-- try {- await expect(manager.execute("x")).rejects.toThrow(/Kernel exited before resolving ports/);- } finally {- errorSpy.mockRestore();- await manager.dispose();- }-- await vi.waitFor(() => {- expect(killMock).toHaveBeenCalledTimes(1);- expect(killMock).toHaveBeenCalledWith("TERM");- const records = readJournalRecords(journalPath);- expect(records).toHaveLength(2);- expect(records[0]).toMatchObject({ pid: 999999, active: true });- expect(records[1]).toMatchObject({ pid: 999999, active: false });- });- });-- it("leaves the journal record active on an already-exited kill outcome (pid may be reused)", async () => {- const journalPath = join(tempDir, "orphans.jsonl");- process.env[ORPHAN_PROCESS_JOURNAL_ENV] = journalPath;- forkEnabledMock.mockReturnValue(true);- const killMock = vi.fn(async (): Promise<"already-exited"> => "already-exited");- forkKernelMock.mockResolvedValue({- pid: 999999,- isAlive: async () => false,- kill: killMock,- });- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});- const manager = new KernelManager({ python: "/nonexistent/python", cwd: tempDir });-- try {- await expect(manager.execute("x")).rejects.toThrow(/Kernel exited before resolving ports/);- } finally {- errorSpy.mockRestore();- await manager.dispose();- }-- await vi.waitFor(() => expect(killMock).toHaveBeenCalledTimes(1));- // Let the resolved kill settle: no inactive record may ever follow.- await new Promise((resolve) => setTimeout(resolve, 200));- const records = readJournalRecords(journalPath);- expect(records).toHaveLength(1);- expect(records[0]).toMatchObject({ pid: 999999, active: true });- });-- it("leaves the journal record active and never signals the pid when the kill is unconfirmed", async () => {- const journalPath = join(tempDir, "orphans.jsonl");- process.env[ORPHAN_PROCESS_JOURNAL_ENV] = journalPath;- forkEnabledMock.mockReturnValue(true);- const killMock = vi.fn(async (): Promise<never> => {- throw new ForkServerUnavailable("dead");- });- forkKernelMock.mockResolvedValue({- pid: 999999,- isAlive: async () => {- throw new ForkServerUnavailable("dead");- },- kill: killMock,- });- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});- const killSpy = vi.spyOn(process, "kill");- const manager = new KernelManager({ python: "/nonexistent/python", cwd: tempDir });-- try {- await expect(manager.execute("x")).rejects.toThrow(/Kernel exited before resolving ports/);- await manager.dispose();- await vi.waitFor(() => expect(killMock).toHaveBeenCalled());- // Let the rejected kill settle: no inactive record may ever follow.- await new Promise((resolve) => setTimeout(resolve, 200));- const records = readJournalRecords(journalPath);- expect(records).toHaveLength(1);- expect(records[0]).toMatchObject({ pid: 999999, active: true });- expect(killSpy.mock.calls.some((call) => call[0] === 999999)).toBe(false);- } finally {- killSpy.mockRestore();- errorSpy.mockRestore();- await manager.dispose();- }- });-- it("leaves the direct-spawn journal record active when the kill signals nothing", async () => {- const journalPath = join(tempDir, "orphans.jsonl");- process.env[ORPHAN_PROCESS_JOURNAL_ENV] = journalPath;- const manager = new KernelManager({ python: "/nonexistent/python", cwd: tempDir });- const internals = manager as unknown as {- kernel?: { pid?: number; kill(signal: string): boolean };- cleanupResources(): void;- };-- try {- internals.kernel = { pid: 999999, kill: () => false };- internals.cleanupResources();-- const records = existsSync(journalPath) ? readJournalRecords(journalPath) : [];- expect(records.some((r) => r.pid === 999999 && !r.active)).toBe(false);- } finally {- await manager.dispose();- }- });-- it("maps SIGKILL to the forkserver KILL signal", async () => {- forkEnabledMock.mockReturnValue(true);- const isAliveMock = vi.fn(async () => true);- const killMock = vi.fn(async (): Promise<"signaled"> => "signaled");- forkKernelMock.mockResolvedValue({ pid: 999999, isAlive: isAliveMock, kill: killMock });- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});- const manager = new KernelManager({ python: "/nonexistent/python", cwd: tempDir });-- try {- const execution = manager.execute("x");- execution.catch(() => {});- // The startup poll calls isAlive only after the handle is assigned, so- // kill() below is guaranteed to reach the forked branch.- await vi.waitFor(() => expect(isAliveMock).toHaveBeenCalled());- await manager.kill();- expect(killMock).toHaveBeenCalledWith("KILL");- await expect(execution).rejects.toThrow();- } finally {- errorSpy.mockRestore();- await manager.dispose();- }- });-- it("a stale liveness probe resumed after restart never tears down the new kernel", async () => {- const journalPath = join(tempDir, "orphans.jsonl");- process.env[ORPHAN_PROCESS_JOURNAL_ENV] = journalPath;- let resolveProbe: (alive: boolean) => void = () => {};- const killA = vi.fn(async (): Promise<"signaled"> => "signaled");- const killB = vi.fn(async (): Promise<"signaled"> => "signaled");- const handleA: ForkedKernelHandle = {- pid: 111111,- isAlive: () =>- new Promise<boolean>((resolve) => {- resolveProbe = resolve;- }),- kill: killA,- };- const handleB: ForkedKernelHandle = { pid: 222222, isAlive: async () => true, kill: killB };- const manager = new KernelManager({ python: "/nonexistent/python", cwd: tempDir });- const internals = manager as unknown as {- state: string;- forkedKernel?: ForkedKernelHandle;- checkForkedKernelDeath(): Promise<void>;- };-- try {- internals.state = "running";- internals.forkedKernel = handleA;- const probe = internals.checkForkedKernelDeath();- // A restart completes while the probe is in flight: the manager is- // "running" again, but on a different kernel.- internals.forkedKernel = handleB;- resolveProbe(false);- await probe;-- expect(internals.state).toBe("running");- expect(killB).not.toHaveBeenCalled();- const records = existsSync(journalPath) ? readJournalRecords(journalPath) : [];- expect(records.some((r) => r.pid === handleB.pid && !r.active)).toBe(false);- } finally {- internals.forkedKernel = undefined;- internals.state = "idle";- await manager.dispose();- }- });-- it("a timed-out liveness probe never tears down a possibly-healthy kernel", async () => {- const kill = vi.fn(async (): Promise<"signaled"> => "signaled");- const handle: ForkedKernelHandle = {- pid: 111111,- isAlive: async () => {- throw new ForkServerUnavailable("forkserver request timed out after 10000ms", { timedOut: true });- },- kill,- };- const manager = new KernelManager({ python: "/nonexistent/python", cwd: tempDir });- const internals = manager as unknown as {- state: string;- forkedKernel?: ForkedKernelHandle;- checkForkedKernelDeath(): Promise<void>;- };-- try {- internals.state = "running";- internals.forkedKernel = handle;- await internals.checkForkedKernelDeath();-- expect(internals.state).toBe("running");- expect(kill).not.toHaveBeenCalled();- } finally {- internals.forkedKernel = undefined;- internals.state = "idle";- await manager.dispose();- }- });-- it("a stale doStart resumed after a concurrent teardown never touches the new kernel", async () => {- const journalPath = join(tempDir, "orphans.jsonl");- process.env[ORPHAN_PROCESS_JOURNAL_ENV] = journalPath;- forkEnabledMock.mockReturnValue(true);- let resolveFork: (handle: ForkedKernelHandle) => void = () => {};- const killA = vi.fn(async (): Promise<"signaled"> => "signaled");- const killB = vi.fn(async (): Promise<"signaled"> => "signaled");- const handleA: ForkedKernelHandle = { pid: 111111, isAlive: async () => true, kill: killA };- const handleB: ForkedKernelHandle = { pid: 222222, isAlive: async () => true, kill: killB };- forkKernelMock.mockReturnValue(- new Promise<ForkedKernelHandle>((resolve) => {- resolveFork = resolve;- }),- );- const manager = new KernelManager({ python: "/nonexistent/python", cwd: tempDir });- const internals = manager as unknown as { state: string; forkedKernel?: ForkedKernelHandle };-- try {- // Start A blocks inside `await forkKernel(...)`.- const staleStart = manager.start();- staleStart.catch(() => {});- await vi.waitFor(() => expect(forkKernelMock).toHaveBeenCalledTimes(1));-- // A concurrent restart tears the starting kernel down (bumping the start- // generation) and brings up a new running kernel B.- await manager.kill();- internals.state = "running";- internals.forkedKernel = handleB;-- // The stale doStart resumes with handle A: it must fail without touching B.- resolveFork(handleA);- await expect(staleStart).rejects.toThrow(/Kernel start superseded/);-- expect(internals.state).toBe("running");- expect(internals.forkedKernel).toBe(handleB);- expect(killB).not.toHaveBeenCalled();- // A is reclaimed via its own handle, never journaled.- await vi.waitFor(() => expect(killA).toHaveBeenCalledWith("TERM"));- const records = existsSync(journalPath) ? readJournalRecords(journalPath) : [];- expect(records.some((r) => r.pid === handleA.pid)).toBe(false);- } finally {- internals.forkedKernel = undefined;- internals.state = "idle";- await manager.dispose();- }- });-- it("a shutdown superseded by a concurrent kill reports not-owner so recovery cannot resurrect to idle", async () => {- const manager = new KernelManager({ python: "/nonexistent-python", cwd: tmpdir() });- const internals = manager as unknown as {- state: string;- connection: unknown;- control: unknown;- kernel: unknown;- shutdown(): Promise<boolean>;- kill(): Promise<void>;- };- internals.state = "starting";- internals.connection = { key: "" };- // A live kernel handle keeps waitForKernelExit parked so the send actually blocks the shutdown.- const kernel = Object.assign(new EventEmitter(), { exitCode: null, signalCode: null, kill: () => true });- internals.kernel = kernel;- let releaseSend: () => void = () => {};- internals.control = {- send: () => new Promise<void>((resolve) => (releaseSend = resolve)),- close: () => {},- };- const shutdownResult = internals.shutdown();- await new Promise((resolve) => setTimeout(resolve, 10)); // park in the control send- await internals.kill(); // concurrent teardown wins ownership- releaseSend();- kernel.emit("exit", 0, null);- expect(await shutdownResult).toBe(false); // recovery must not set idle- expect(internals.state).toBe("shutdown");- });-- it("a stale shutdown parked in its control-send await never cleans up a successor kernel", async () => {- const journalPath = join(tempDir, "orphans.jsonl");- process.env[ORPHAN_PROCESS_JOURNAL_ENV] = journalPath;- let releaseSend: () => void = () => {};- const parkedSend = new Promise<void>((resolve) => {- releaseSend = resolve;- });- const killA = vi.fn(async (): Promise<"signaled"> => "signaled");- const killB = vi.fn(async (): Promise<"signaled"> => "signaled");- const handleA: ForkedKernelHandle = { pid: 111111, isAlive: async () => true, kill: killA };- const handleB: ForkedKernelHandle = { pid: 222222, isAlive: async () => true, kill: killB };- const manager = new KernelManager({ python: "/nonexistent/python", cwd: tempDir });- const internals = manager as unknown as {- state: string;- forkedKernel?: ForkedKernelHandle;- control?: { send(frames: Buffer[]): Promise<void>; close(): void };- connection?: { ip: string; transport: string; control_port: number; key: string };- startPromise?: Promise<void>;- };-- try {- // Kernel A is running with a control channel whose send parks forever- // until released — shutdown() will suspend inside its await window- // after having synchronously set state = "shutdown".- internals.state = "running";- internals.forkedKernel = handleA;- internals.control = { send: () => parkedSend, close: () => {} };- internals.connection = { ip: "127.0.0.1", transport: "tcp", control_port: 1, key: "test-key" };- const staleShutdown = manager.shutdown();-- // While A's shutdown is parked, a concurrent teardown reclaims A (this is- // the cleanup restart() reaches via shutdown's already-shutdown fast path)- // and a new start brings up kernel B.- await manager.kill();- internals.state = "running";- internals.forkedKernel = handleB;- const startPromiseB = Promise.resolve();- internals.startPromise = startPromiseB;-- // A's stale shutdown resumes: it must not clean up B or clear B's start.- releaseSend();- await staleShutdown;-- expect(internals.state).toBe("running");- expect(internals.forkedKernel).toBe(handleB);- expect(killB).not.toHaveBeenCalled();- expect(internals.startPromise).toBe(startPromiseB);- // A was reclaimed by kill(); B must never gain an inactive journal record.- await vi.waitFor(() => expect(killA).toHaveBeenCalledWith("KILL"));- const records = existsSync(journalPath) ? readJournalRecords(journalPath) : [];- expect(records.some((r) => r.pid === handleB.pid && !r.active)).toBe(false);- } finally {- internals.forkedKernel = undefined;- internals.startPromise = undefined;- internals.state = "idle";- await manager.dispose();- }- });-- it("a hung liveness probe resolves alive once its budget expires", async () => {- const manager = new KernelManager({ python: "/nonexistent/python", cwd: tempDir });- const internals = manager as unknown as {- forkedKernelDead(probed: ForkedKernelHandle, timeoutMs?: number): Promise<boolean>;- };- const handle: ForkedKernelHandle = {- pid: 999999,- isAlive: () => new Promise<boolean>(() => {}),- kill: async () => "signaled",- };-- try {- const started = Date.now();- // Unknown is not death, and the caller's budget bounds the wait.- await expect(internals.forkedKernelDead(handle, 250)).resolves.toBe(false);- expect(Date.now() - started).toBeLessThan(5_000);- } finally {- await manager.dispose();- }- });-- it("fork request env does not carry JPY_PARENT_PID (forked children watch the forkserver)", async () => {- const python = writeFakePython(["#!/bin/sh", "exit 42", ""]);- forkEnabledMock.mockReturnValue(true);- forkKernelMock.mockRejectedValue(new ForkServerUnavailable("test"));- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});- const manager = new KernelManager({ python, cwd: tempDir });-- try {- await expect(manager.execute("x")).rejects.toThrow(/Kernel exited before resolving ports/);- } finally {- errorSpy.mockRestore();- await manager.dispose();- }-- expect(forkKernelMock).toHaveBeenCalledTimes(1);- const spawnParams = forkKernelMock.mock.calls[0]?.[1] as { env?: Record<string, string | undefined> };- expect(spawnParams.env?.JPY_PARENT_PID).toBeUndefined();- });-});--function resolveKernelPython(): string | null {- const candidates = [- process.env.PRIME_AGENT_KERNEL_PYTHON,- join(homedir(), ".prime", "agent", "kernel-venv", "bin", "python"),- ].filter((p): p is string => Boolean(p));- for (const python of candidates) {- if (!existsSync(python)) continue;- const check = spawnSync(python, ["-c", "import ipykernel"], { encoding: "utf8" });- if (check.status === 0) return python;- }- return null;-}--const kernelPython = resolveKernelPython();-const describeIf = kernelPython && process.platform !== "win32" ? describe : describe.skip;--describeIf("kernel outlives-owner watchdog (real kernel)", { tags: ["kernel-heavy"] }, () => {- it("kernel exits after its owner is SIGKILLed", async () => {- const dir = mkdtempSync(join(tmpdir(), "prime-agent-watchdog-int-"));- const pidFile = join(dir, "kernel.pid");- const connectionFile = join(dir, "connection.json");- // The owner must be a separate killable process; it replicates KernelManager's- // exact spawn line (T1 above proves the manager emits that env).- const ownerScript = [- `const { spawn } = require("node:child_process");`,- `const { writeFileSync } = require("node:fs");`,- `const k = spawn(${JSON.stringify(kernelPython)}, ["-m", "ipykernel_launcher", "-f", ${JSON.stringify(connectionFile)}], {`,- ` env: { ...process.env, JPY_PARENT_PID: String(process.pid) },`,- ` stdio: "ignore",`,- `});`,- `writeFileSync(${JSON.stringify(pidFile)}, String(k.pid));`,- `setInterval(() => {}, 1000);`,- ].join("\n");- const owner = spawn(process.execPath, ["-e", ownerScript], { stdio: ["ignore", "ignore", "inherit"] });- let kernelPid = 0;-- try {- await vi.waitFor(- () => {- kernelPid = Number(readFileSync(pidFile, "utf8"));- expect(kernelPid).toBeGreaterThan(0);- expect(() => process.kill(kernelPid, 0)).not.toThrow();- },- { timeout: 20_000, interval: 500 },- );-- owner.kill("SIGKILL");-- await vi.waitFor(- () => {- expect(() => process.kill(kernelPid, 0)).toThrow();- },- { timeout: 20_000, interval: 500 },- );- } finally {- if (kernelPid > 0) {- try {- process.kill(kernelPid, "SIGKILL");- } catch {- // Already exited (the expected outcome).- }- }- try {- owner.kill("SIGKILL");- } catch {- // Already exited.- }- rmSync(dir, { recursive: true, force: true });- }- }, 30_000);-});diff --git a/packages/coding-agent/test/kernel-shutdown.test.ts b/packages/coding-agent/test/kernel-shutdown.test.tsdeleted file mode 100644index 3f002ffb3e..0000000000--- a/packages/coding-agent/test/kernel-shutdown.test.ts+++ /dev/null@@ -1,143 +0,0 @@-import { EventEmitter } from "node:events";-import { readFileSync } from "node:fs";-import { resolve } from "node:path";-import { describe, expect, it, vi } from "vitest";-import { KernelManager } from "../src/core/kernel/index.js";--type TestMessage = {- header: { msg_type: string };- parent_header: { msg_id: string };- metadata: Record<string, unknown>;- content: Record<string, unknown>;-};--type ShutdownInternals = {- state: "running";- connection: { key: string };- control: { send: (frames: Buffer[]) => Promise<void>; close: () => void };- kernel: EventEmitter & {- exitCode: number | null;- signalCode: NodeJS.Signals | null;- kill: (signal?: NodeJS.Signals | number) => boolean;- };- pendingControlReplies: Map<string, (message: TestMessage) => void>;-};--function shutdownReply(parentMessageId: string, msgType = "shutdown_reply"): TestMessage {- return {- header: { msg_type: msgType },- parent_header: { msg_id: parentMessageId },- metadata: {},- content: { status: "ok", restart: false },- };-}--function configuredManager(onSend: (internals: ShutdownInternals) => void | Promise<void>): {- manager: KernelManager;- internals: ShutdownInternals;-} {- const manager = new KernelManager({ cwd: process.cwd() });- const internals = manager as unknown as ShutdownInternals;- const kernel = Object.assign(new EventEmitter(), {- exitCode: null,- signalCode: null,- kill: vi.fn(() => true),- });- Object.assign(internals, {- state: "running",- connection: { key: "test-key" },- control: {- send: vi.fn(async () => onSend(internals)),- close: vi.fn(),- },- kernel,- });- return { manager, internals };-}--describe("KernelManager graceful shutdown", () => {- it("bounds a stuck control send with the aggregate shutdown deadline", async () => {- vi.useFakeTimers();- try {- const { manager, internals } = configuredManager(() => new Promise<void>(() => {}));- const shutdown = manager.shutdown();- await vi.advanceTimersByTimeAsync(5_000);- await shutdown;- expect(internals.kernel).toBeUndefined();- } finally {- vi.useRealTimers();- }- });-- it("does not finish shutdown before the control send settles", async () => {- let finishSend: (() => void) | undefined;- const sendBlocked = new Promise<void>((resolve) => {- finishSend = resolve;- });- const { manager, internals } = configuredManager(async (state) => {- const [requestMessageId, dispatch] = [...state.pendingControlReplies.entries()][0] ?? [];- if (!requestMessageId || !dispatch) throw new Error("missing shutdown reply listener");- dispatch(shutdownReply(requestMessageId));- await sendBlocked;- state.kernel.exitCode = 0;- state.kernel.emit("exit", 0, null);- });-- let finished = false;- const shutdown = manager.shutdown().then(() => {- finished = true;- });- await new Promise((resolve) => globalThis.setTimeout(resolve, 0));- expect(finished).toBe(false);- finishSend?.();- await shutdown;- expect(internals.pendingControlReplies.size).toBe(0);- });-- it("finishes promptly when the kernel exits without sending shutdown_reply", async () => {- const { manager, internals } = configuredManager((state) => {- state.kernel.exitCode = 0;- state.kernel.emit("exit", 0, null);- });- vi.useFakeTimers();- try {- const shutdown = manager.shutdown();- await vi.advanceTimersByTimeAsync(100);- // True = this call performed the cleanup: startup-failure recovery relies on it to resurrect to idle.- await expect(shutdown).resolves.toBe(true);- expect(internals.kernel).toBeUndefined();- } finally {- vi.useRealTimers();- }- });-- it("waits for the matching shutdown reply and removes its listener", async () => {- const { manager, internals } = configuredManager(async (state) => {- const [requestMessageId, dispatch] = [...state.pendingControlReplies.entries()][0] ?? [];- expect(requestMessageId).toBeTypeOf("string");- expect(dispatch).toBeTypeOf("function");- if (!requestMessageId || !dispatch) throw new Error("missing shutdown reply listener");- dispatch(shutdownReply("unrelated"));- dispatch(shutdownReply(requestMessageId, "interrupt_reply"));- expect(state.pendingControlReplies.size).toBe(1);- dispatch(shutdownReply(requestMessageId));- queueMicrotask(() => {- state.kernel.exitCode = 0;- state.kernel.emit("exit", 0, null);- });- });-- await manager.shutdown();-- expect(internals.pendingControlReplies.size).toBe(0);- expect(internals.kernel).toBeUndefined();- });-- it("keeps the kernel MCP close budget strictly inside the host shutdown deadline", () => {- const source = readFileSync(resolve(__dirname, "../../../prime-agent-runtime/src/rlm/mcp.py"), "utf8");- const match = source.match(/^_SHUTDOWN_TIMEOUT = ([\d.]+)$/m);- expect(match).not.toBeNull();- // +1s dispatch slack in mcp.py close(); the sum must undercut the host's 5s kill deadline.- expect((Number(match![1]) + 1) * 1000).toBeLessThan(5000);- });-});diff --git a/packages/coding-agent/test/kernel-socket-closure.test.ts b/packages/coding-agent/test/kernel-socket-closure.test.tsdeleted file mode 100644index 22b96da906..0000000000--- a/packages/coding-agent/test/kernel-socket-closure.test.ts+++ /dev/null@@ -1,38 +0,0 @@-import { describe, expect, it } from "vitest";-import { KernelManager } from "../src/core/kernel/index.js";--type Translator = {- translateSocketClosure<T>(this: unknown, operation: Promise<T>): Promise<T>;-};--function makeManager(state: string, stderr = ""): KernelManager {- const manager = Object.create(KernelManager.prototype) as KernelManager;- Object.assign(manager, { state, kernelStderr: stderr, options: {} });- return manager;-}--const translate = (KernelManager.prototype as unknown as Translator).translateSocketClosure;--describe("KernelManager zmq closure translation", () => {- it("passes successful operations through untouched", async () => {- await expect(translate.call(makeManager("running"), Promise.resolve("frames"))).resolves.toBe("frames");- });-- it("rethrows unrelated errors verbatim", async () => {- await expect(translate.call(makeManager("running"), Promise.reject(new Error("boom")))).rejects.toThrow("boom");- });-- it("translates the raw libzmq EAGAIN text during startup into a retriable kernel error", async () => {- const rejection = Promise.reject(new Error("Operation was not possible or timed out"));- await expect(translate.call(makeManager("starting", "ImportError: mcp"), rejection)).rejects.toThrow(- /IPython kernel channel closed while starting up \(retriable\)[\s\S]*ImportError: mcp/,- );- });-- it("translates a closed-socket rejection outside startup", async () => {- const rejection = Promise.reject(new Error("Socket is closed"));- await expect(translate.call(makeManager("running"), rejection)).rejects.toThrow(- /IPython kernel channel closed while communicating \(retriable\)/,- );- });-});diff --git a/packages/coding-agent/test/kernel-startup.test.ts b/packages/coding-agent/test/kernel-startup.test.tsdeleted file mode 100644index 225d571394..0000000000--- a/packages/coding-agent/test/kernel-startup.test.ts+++ /dev/null@@ -1,41 +0,0 @@-import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { KernelManager } from "../src/core/kernel/index.js";--let tempDir = "";--function writeExecutable(filePath: string, content: string): void {- writeFileSync(filePath, content);- chmodSync(filePath, 0o755);-}--describe("KernelManager startup", () => {- beforeEach(() => {- tempDir = mkdtempSync(join(tmpdir(), "prime-agent-kernel-startup-"));- });-- afterEach(() => {- if (tempDir) {- rmSync(tempDir, { recursive: true, force: true });- tempDir = "";- }- });-- it("surfaces kernels that exit before resolving ports", async () => {- const python = join(tempDir, "python");- writeExecutable(python, ["#!/bin/sh", 'echo "fake kernel died before binding" >&2', "exit 42", ""].join("\n"));- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});- const manager = new KernelManager({ python, cwd: tempDir });-- try {- await expect(manager.execute("print(1)")).rejects.toThrow(- /Kernel exited before resolving ports[\s\S]*fake kernel died before binding/,- );- } finally {- errorSpy.mockRestore();- await manager.dispose();- }- });-});diff --git a/packages/coding-agent/test/kernel-state-roundtrip.test.ts b/packages/coding-agent/test/kernel-state-roundtrip.test.tsdeleted file mode 100644index 0c9b3c2eef..0000000000--- a/packages/coding-agent/test/kernel-state-roundtrip.test.ts+++ /dev/null@@ -1,248 +0,0 @@-import { spawnSync } from "node:child_process";-import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";-import { homedir, tmpdir } from "node:os";-import { join } from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";-import { KernelManager } from "../src/core/kernel/index.js";--function resolveKernelPython(): string | null {- const candidates = [- process.env.PRIME_AGENT_KERNEL_PYTHON,- join(homedir(), ".prime", "agent", "kernel-venv", "bin", "python"),- ].filter((p): p is string => Boolean(p));- for (const python of candidates) {- if (!existsSync(python)) continue;- const check = spawnSync(python, ["-c", "import ipykernel, dill"], { encoding: "utf8" });- if (check.status === 0) return python;- }- return null;-}--const python = resolveKernelPython();-const describeIfKernel = python ? describe : describe.skip;--describeIfKernel("kernel state snapshot round-trip (real kernel)", { tags: ["kernel-heavy"] }, () => {- let dir = "";- let snapshotPath = "";- let manifestPath = "";-- beforeAll(() => {- dir = mkdtempSync(join(tmpdir(), "prime-agent-state-roundtrip-"));- snapshotPath = join(dir, "session.dill");- manifestPath = join(dir, "session.json");- });-- afterAll(() => {- if (dir) rmSync(dir, { recursive: true, force: true });- });-- function newManager(): KernelManager {- return new KernelManager({- python: python as string,- cwd: dir,- snapshot: { path: snapshotPath, manifestPath },- });- }-- it("saves picklable names, reports unpicklable ones, then revives them in a fresh kernel", async () => {- const writer = newManager();- try {- await writer.execute("x = 42");- await writer.execute("df = [1, 2, 3]");- await writer.execute("def double(n):\n return n * 2");- await writer.execute("gen = (n for n in range(3))");-- const snap = await writer.snapshotState();- expect(snap).not.toBeNull();- expect(snap?.saved).toEqual(expect.arrayContaining(["x", "df", "double"]));- expect(snap?.skipped.map((s) => s.name)).toContain("gen");- expect(existsSync(snapshotPath)).toBe(true);- expect(existsSync(manifestPath)).toBe(true);- } finally {- await writer.dispose();- }-- const reader = newManager();- try {- const restore = await reader.restoreState();- expect(restore?.restored).toEqual(expect.arrayContaining(["x", "df", "double"]));- expect(restore?.failed.map((f) => f.name) ?? []).not.toContain("x");-- const echo = await reader.execute("print(x, double(x), sum(df))");- expect(echo.stdout.trim()).toBe("42 84 6");- } finally {- await reader.dispose();- }- }, 60_000);-- it("treats a missing snapshot as an empty restore (clean start)", async () => {- const freshDir = mkdtempSync(join(tmpdir(), "prime-agent-state-empty-"));- const manager = new KernelManager({- python: python as string,- cwd: freshDir,- snapshot: { path: join(freshDir, "missing.dill"), manifestPath: join(freshDir, "missing.json") },- });- try {- const restore = await manager.restoreState();- expect(restore).toEqual({ restored: [], failed: [], path: join(freshDir, "missing.dill") });- } finally {- await manager.dispose();- rmSync(freshDir, { recursive: true, force: true });- }- }, 60_000);-- it("snapshots and revives user variables that shadow builtins", async () => {- const dir = mkdtempSync(join(tmpdir(), "prime-agent-state-shadow-"));- const path = join(dir, "shadow.dill");- const cfg = { path, manifestPath: join(dir, "shadow.json") };- const writer = new KernelManager({ python: python as string, cwd: dir, snapshot: cfg });- try {- await writer.execute("list = [10, 20]\nprint = 'shadowed'\nid = 99");- const snap = await writer.snapshotState();- expect(snap).not.toBeNull();- expect(snap?.saved).toEqual(expect.arrayContaining(["list", "print", "id"]));- } finally {- await writer.dispose();- }-- const reader = new KernelManager({ python: python as string, cwd: dir, snapshot: cfg });- try {- const restore = await reader.restoreState();- expect(restore?.restored).toEqual(expect.arrayContaining(["list", "print", "id"]));- } finally {- await reader.dispose();- rmSync(dir, { recursive: true, force: true });- }- }, 60_000);-- it("treats a corrupt (non-dict) snapshot as no restore without throwing", async () => {- const badDir = mkdtempSync(join(tmpdir(), "prime-agent-state-corrupt-"));- const badPath = join(badDir, "corrupt.dill");- const manager = new KernelManager({- python: python as string,- cwd: badDir,- snapshot: { path: badPath, manifestPath: join(badDir, "corrupt.json") },- });- try {- await manager.execute(`import dill\nopen(${JSON.stringify(badPath)}, "wb").write(dill.dumps([1, 2, 3]))`);- const restore = await manager.restoreState();- expect(restore).toBeNull();- const echo = await manager.execute("print('alive')");- expect(echo.stdout.trim()).toBe("alive");- } finally {- await manager.dispose();- rmSync(badDir, { recursive: true, force: true });- }- }, 60_000);-- it("lists live user-defined names, filtering internals and live handles", async () => {- const listDir = mkdtempSync(join(tmpdir(), "prime-agent-state-list-"));- const manager = new KernelManager({ python: python as string, cwd: listDir });- try {- expect(await manager.listNamespaceNames()).toBeNull();- await manager.execute("alpha = 1\ndef helper(n):\n return n\n_hidden = 2\nrlm = object()");- const names = await manager.listNamespaceNames();- expect(names).toEqual(expect.arrayContaining(["alpha", "helper"]));- expect(names).not.toContain("_hidden");- expect(names).not.toContain("rlm");- } finally {- await manager.dispose();- rmSync(listDir, { recursive: true, force: true });- }- }, 60_000);-- it("caps each variable without reducing the aggregate snapshot budget", async () => {- const boundedDir = mkdtempSync(join(tmpdir(), "prime-agent-state-bounded-"));- const manager = new KernelManager({- python: python as string,- cwd: boundedDir,- snapshot: {- path: join(boundedDir, "bounded.dill"),- manifestPath: join(boundedDir, "bounded.json"),- maxBytes: 10 * 1024,- maxVariableBytes: 8 * 1024,- },- });- try {- await manager.execute(`pickle_count = 0-class _Counted:- def __reduce__(self):- global pickle_count- pickle_count += 1- return (dict, ())-large_records = [_Counted() for _ in range(100_000)]-large_text = "x" * 16_384-small_text_one = "a" * 4_000-small_text_two = "b" * 4_000-aggregate_only = "c" * 4_000-late_small = "d" * 1_000`);- await manager.execute("large_text");-- const snapshot = await manager.snapshotState();- expect(snapshot?.skipped.map(({ name }) => name)).toEqual(- expect.arrayContaining(["large_records", "large_text", "aggregate_only"]),- );- expect(snapshot?.saved).toEqual(expect.arrayContaining(["small_text_one", "small_text_two", "late_small"]));- expect(await manager.listNamespaceNames()).toEqual(expect.arrayContaining(["large_records", "large_text"]));-- const compacted = await manager.pruneOversizedVariables();- expect(compacted?.pruned).toEqual(expect.arrayContaining(["large_records", "large_text"]));- const remaining = await manager.listNamespaceNames();- expect(remaining).toEqual(- expect.arrayContaining(["small_text_one", "small_text_two", "aggregate_only", "late_small"]),- );- expect(remaining).not.toContain("large_records");- expect(remaining).not.toContain("large_text");- const outputCache = await manager.execute(- "print(any(isinstance(value, str) and len(value) == 16_384 for value in Out.values()))",- );- expect(outputCache.stdout.trim()).toBe("False");- const count = await manager.execute("print(pickle_count)");- expect(Number(count.stdout.trim())).toBeLessThan(100_000);- } finally {- await manager.dispose();- rmSync(boundedDir, { recursive: true, force: true });- }- }, 60_000);-- it("keeps oversized variables when the compaction snapshot cannot be written", async () => {- const failedDir = mkdtempSync(join(tmpdir(), "prime-agent-state-prune-failure-"));- const blocker = join(failedDir, "not-a-directory");- writeFileSync(blocker, "block snapshot parent");- const manager = new KernelManager({- python: python as string,- cwd: failedDir,- snapshot: {- path: join(blocker, "state.dill"),- manifestPath: join(blocker, "state.json"),- maxBytes: 64 * 1024,- maxVariableBytes: 8 * 1024,- },- });- try {- await manager.execute('large_text = "x" * 16_384');- expect(await manager.pruneOversizedVariables()).toBeNull();- expect(await manager.listNamespaceNames()).toContain("large_text");- } finally {- await manager.dispose();- rmSync(failedDir, { recursive: true, force: true });- }- }, 60_000);-- it("auto-snapshots after a successful execution (debounced)", async () => {- const autoDir = mkdtempSync(join(tmpdir(), "prime-agent-state-auto-"));- const autoPath = join(autoDir, "auto.dill");- const manager = new KernelManager({- python: python as string,- cwd: autoDir,- snapshot: { path: autoPath, manifestPath: join(autoDir, "auto.json"), debounceMs: 50 },- });- try {- await manager.execute("auto_var = 'persisted'");- await expect.poll(() => existsSync(autoPath), { timeout: 10_000 }).toBe(true);- } finally {- await manager.dispose();- rmSync(autoDir, { recursive: true, force: true });- }- }, 60_000);-});diff --git a/packages/coding-agent/test/kernel-state-snapshot.test.ts b/packages/coding-agent/test/kernel-state-snapshot.test.tsindex af934fe1d8..f50bbdf78a 100644--- a/packages/coding-agent/test/kernel-state-snapshot.test.ts+++ b/packages/coding-agent/test/kernel-state-snapshot.test.ts@@ -1,17 +1,6 @@import { join } from "node:path";import { describe, expect, it } from "vitest";-import {- buildRestoreCode,- buildSnapshotCode,- DEFAULT_SNAPSHOT_MAX_BYTES,- DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES,- manifestPathIn,- parseRestoreResult,- parseSnapshotResult,- snapshotPathIn,-} from "../src/core/kernel/state-snapshot.js";--const MARKER = "__PRIME_AGENT_KERNEL_STATE__";+import { manifestPathIn, snapshotPathIn } from "../src/core/kernel/state-snapshot.js";describe("kernel state snapshot paths", () => {it("places snapshot + manifest inside the session artifact directory", () => {@@ -20,96 +9,3 @@ describe("kernel state snapshot paths", () => {expect(manifestPathIn(artifactDir)).toBe(join(artifactDir, "kernel-state.json"));});});--describe("parseSnapshotResult", () => {- it("parses a valid marker line", () => {- const stdout = `${MARKER}${JSON.stringify({- saved: ["x", "y"],- skipped: [{ name: "sock", reason: "TypeError: cannot pickle" }],- pruned: ["large_text"],- bytes: 1234,- })}\n`;- const result = parseSnapshotResult(stdout, "/tmp/s.dill");- expect(result).toEqual({- saved: ["x", "y"],- skipped: [{ name: "sock", reason: "TypeError: cannot pickle" }],- pruned: ["large_text"],- bytes: 1234,- path: "/tmp/s.dill",- });- });-- it("ignores stdout printed before the marker line", () => {- const stdout = `some earlier print output\n${MARKER}${JSON.stringify({ saved: ["a"], skipped: [], bytes: 7 })}`;- expect(parseSnapshotResult(stdout, "/tmp/s.dill")?.saved).toEqual(["a"]);- });-- it("returns null when the marker is absent", () => {- expect(parseSnapshotResult("no marker here", "/tmp/s.dill")).toBeNull();- });-- it("returns null when the payload reports an error", () => {- const stdout = `${MARKER}${JSON.stringify({ error: "dill unavailable" })}`;- expect(parseSnapshotResult(stdout, "/tmp/s.dill")).toBeNull();- });-- it("returns null on malformed JSON", () => {- expect(parseSnapshotResult(`${MARKER}{not json`, "/tmp/s.dill")).toBeNull();- });-- it("tolerates missing fields", () => {- const result = parseSnapshotResult(`${MARKER}{}`, "/tmp/s.dill");- expect(result).toEqual({ saved: [], skipped: [], bytes: 0, path: "/tmp/s.dill" });- });-});--describe("parseRestoreResult", () => {- it("parses restored and failed names", () => {- const stdout = `${MARKER}${JSON.stringify({- restored: ["df", "model"],- failed: [{ name: "conn", reason: "TypeError" }],- })}`;- expect(parseRestoreResult(stdout, "/tmp/s.dill")).toEqual({- restored: ["df", "model"],- failed: [{ name: "conn", reason: "TypeError" }],- path: "/tmp/s.dill",- });- });-- it("returns null when the marker is absent", () => {- expect(parseRestoreResult("", "/tmp/s.dill")).toBeNull();- });-- it("returns null when the payload reports an error", () => {- expect(parseRestoreResult(`${MARKER}${JSON.stringify({ error: "load failed" })}`, "/tmp/s.dill")).toBeNull();- });-});--describe("buildSnapshotCode", () => {- const code = buildSnapshotCode("/state/sess.dill", "/state/sess.json", DEFAULT_SNAPSHOT_MAX_BYTES);-- it("embeds the output, manifest paths, and the byte cap", () => {- expect(code).toContain('"/state/sess.dill"');- expect(code).toContain('"/state/sess.json"');- expect(code).toContain(String(DEFAULT_SNAPSHOT_MAX_BYTES));- expect(code).toContain(String(DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES));- });-- it("uses dill, an atomic write, and skips internal handles", () => {- expect(code).toContain("import dill");- expect(code).toContain("os.replace");- expect(code).toContain("except _b.KeyboardInterrupt");- expect(code).toContain('"rlm"');- expect(code).toContain(`print(${JSON.stringify(MARKER)}`);- });-});--describe("buildRestoreCode", () => {- const code = buildRestoreCode("/state/sess.dill");-- it("embeds the input path and no-ops when the file is missing", () => {- expect(code).toContain('"/state/sess.dill"');- expect(code).toContain("os.path.exists");- expect(code).toContain("dill.loads");- });-});diff --git a/packages/coding-agent/test/repl-kernel-abort.test.ts b/packages/coding-agent/test/repl-kernel-abort.test.tsnew file mode 100644index 0000000000..6187e4fa95--- /dev/null+++ b/packages/coding-agent/test/repl-kernel-abort.test.ts@@ -0,0 +1,381 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ AGENT_MESSAGE_DISPLAY_MIME,+ type KernelSentAgentMessage,+ ReplKernelManager,+} from "../src/core/kernel/index.js";++async function waitForCalls(mock: { mock: { calls: unknown[][] } }, count: number): Promise<void> {+ for (let i = 0; i < 20; i++) {+ if (mock.mock.calls.length >= count) {+ return;+ }+ await Promise.resolve();+ }+ expect(mock.mock.calls.length).toBeGreaterThanOrEqual(count);+}++type ReplInternals = {+ state: string;+ writeLine: (request: Record<string, unknown>) => Promise<void>;+ start: () => Promise<void>;+ handleEvent: (event: Record<string, unknown>) => void;+ activeExecution?: { requestId: string };+ child?: { kill: (signal?: NodeJS.Signals | number) => boolean; pid?: number; stdin?: unknown };+};++function runningManagerWith(writeLine: (request: Record<string, unknown>) => Promise<void>): {+ manager: ReplKernelManager;+ internals: ReplInternals;+ kernelKill: ReturnType<typeof vi.fn>;+} {+ const manager = new ReplKernelManager({ cwd: process.cwd() });+ const kernelKill = vi.fn((_signal?: NodeJS.Signals | number) => true);+ const internals = manager as unknown as ReplInternals;+ Object.assign(internals, {+ state: "running",+ writeLine,+ start: async () => {},+ child: { kill: kernelKill, pid: undefined, stdin: undefined },+ });+ return { manager, internals, kernelKill };+}++describe("ReplKernelManager abort handling", () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it("does not poison startup after a caller starts with an aborted signal", async () => {+ const manager = new ReplKernelManager({ cwd: process.cwd() });+ let startCount = 0;+ Object.assign(+ manager as unknown as {+ doStart: () => Promise<void>;+ },+ {+ doStart: async () => {+ startCount++;+ },+ },+ );+ const controller = new AbortController();+ controller.abort();++ await expect(manager.start({ signal: controller.signal })).rejects.toThrow("Kernel startup aborted");+ await expect(manager.start()).resolves.toBeUndefined();+ expect(startCount).toBe(1);+ });++ it("does not cancel shared startup when one waiting caller aborts", async () => {+ const manager = new ReplKernelManager({ cwd: process.cwd() });+ let releaseStart: () => void = () => {};+ let startCount = 0;+ Object.assign(+ manager as unknown as {+ doStart: () => Promise<void>;+ },+ {+ doStart: async () => {+ startCount++;+ await new Promise<void>((resolve) => {+ releaseStart = resolve;+ });+ },+ },+ );+ const controller = new AbortController();++ const firstStart = manager.start({ signal: controller.signal });+ const secondStart = manager.start();+ controller.abort();++ await expect(firstStart).rejects.toThrow("Kernel startup aborted");+ releaseStart();+ await expect(secondStart).resolves.toBeUndefined();+ expect(startCount).toBe(1);+ });++ it("settles an aborted execution when the runtime never sends done", async () => {+ vi.useFakeTimers();+ const writeLine = vi.fn(async (_request: Record<string, unknown>) => {});+ const { manager, internals, kernelKill } = runningManagerWith(writeLine);+ const controller = new AbortController();+ const lateSentAgentMessages: KernelSentAgentMessage[] = [];++ const executePromise = manager.execute("while True: pass", {+ signal: controller.signal,+ onLateSentAgentMessage: (message) => lateSentAgentMessages.push(message),+ });+ await waitForCalls(writeLine, 1);+ expect(writeLine).toHaveBeenCalledTimes(1);+ expect(writeLine.mock.calls[0]?.[0]).toMatchObject({ type: "execute" });++ controller.abort();+ await vi.advanceTimersByTimeAsync(1000);++ await expect(executePromise).resolves.toMatchObject({ status: "aborted" });+ // The abort listener interrupted the runtime out-of-band.+ expect(writeLine.mock.calls.some((call) => (call[0] as { type?: string }).type === "interrupt")).toBe(true);+ expect(kernelKill).not.toHaveBeenCalled();++ const activeExecution = internals.activeExecution;+ expect(activeExecution).toBeDefined();+ if (!activeExecution) {+ throw new Error("Expected active execution to remain until the runtime's done");+ }+ // A late display event for the aborted cell still dispatches the sent message.+ internals.handleEvent({+ event: "display",+ id: activeExecution.requestId,+ data: {+ [AGENT_MESSAGE_DISPLAY_MIME]: {+ id: "agentmsg-after-abort",+ message: "still sent",+ deliveryStatus: "delivered",+ target: { activeSessionId: "beta", sessionId: "session-beta" },+ },+ },+ });+ expect(lateSentAgentMessages).toEqual([+ {+ id: "agentmsg-after-abort",+ message: "still sent",+ deliveryStatus: "delivered",+ target: { activeSessionId: "beta", sessionId: "session-beta" },+ },+ ]);+ // The next execute waits for the stale cell's done before sending.+ const secondExecutePromise = manager.execute("x = 1");+ await Promise.resolve();+ expect(writeLine.mock.calls.filter((call) => (call[0] as { type?: string }).type === "execute")).toHaveLength(1);++ internals.handleEvent({ event: "done", id: activeExecution.requestId, status: "error" });+ await vi.waitFor(() => {+ expect(writeLine.mock.calls.filter((call) => (call[0] as { type?: string }).type === "execute")).toHaveLength(+ 2,+ );+ });++ const secondExecution = internals.activeExecution;+ expect(secondExecution).toBeDefined();+ if (!secondExecution) {+ throw new Error("Expected second execution to start after the stale cell settled");+ }+ internals.handleEvent({ event: "done", id: secondExecution.requestId, status: "ok" });+ await expect(secondExecutePromise).resolves.toMatchObject({ status: "ok" });++ manager.disposeSync();+ expect(kernelKill).toHaveBeenCalledWith("SIGTERM");+ });++ it("settles an aborted execution when the stdin write never resolves", async () => {+ vi.useFakeTimers();+ const interruptWrites: Record<string, unknown>[] = [];+ const writeLine = vi.fn((request: Record<string, unknown>) => {+ if (request.type === "interrupt") {+ interruptWrites.push(request);+ return Promise.resolve();+ }+ return new Promise<void>(() => {});+ });+ const { manager } = runningManagerWith(writeLine);+ const controller = new AbortController();++ const executePromise = manager.execute("while True: pass", { signal: controller.signal });+ await waitForCalls(writeLine, 1);+ controller.abort();+ await vi.advanceTimersByTimeAsync(1000);++ await expect(executePromise).resolves.toMatchObject({ status: "aborted" });+ expect(interruptWrites.length).toBeGreaterThan(0);+ });++ it("fails a later execution fast when the interrupted cell never settles", async () => {+ vi.useFakeTimers();+ const writeLine = vi.fn(async (_request: Record<string, unknown>) => {});+ const { manager } = runningManagerWith(writeLine);+ const controller = new AbortController();++ const executePromise = manager.execute("while True: pass", { signal: controller.signal });+ await waitForCalls(writeLine, 1);+ controller.abort();+ await vi.advanceTimersByTimeAsync(1000);+ await expect(executePromise).resolves.toMatchObject({ status: "aborted" });++ const secondExecutePromise = manager.execute("x = 1");+ const secondExecuteExpectation = expect(secondExecutePromise).rejects.toThrow(+ "The Python kernel is still running the previously interrupted cell",+ );+ await Promise.resolve();+ await vi.advanceTimersByTimeAsync(5000);++ await secondExecuteExpectation;+ expect(writeLine.mock.calls.filter((call) => (call[0] as { type?: string }).type === "execute")).toHaveLength(1);+ expect(writeLine.mock.calls.some((call) => (call[0] as { type?: string }).type === "interrupt")).toBe(true);+ manager.disposeSync();+ });++ it("starts the snapshot timeout after earlier kernel work finishes", async () => {+ vi.useFakeTimers();+ const manager = new ReplKernelManager({+ cwd: process.cwd(),+ snapshot: { path: "/tmp/test-state.dill", manifestPath: "/tmp/test-state.json" },+ });+ let releaseQueue: () => void = () => {};+ const previousExecution = new Promise<void>((resolve) => {+ releaseQueue = resolve;+ });+ const executeInner = vi.fn(+ async (+ _requestFields: Record<string, unknown>,+ _code: string,+ opts: { signal?: AbortSignal },+ ): Promise<{ stdout: string; stderr: string; status: "aborted"; durationMs: number }> =>+ await new Promise((resolve) => {+ opts.signal?.addEventListener(+ "abort",+ () => resolve({ stdout: "", stderr: "", status: "aborted", durationMs: 5000 }),+ { once: true },+ );+ }),+ );+ Object.assign(+ manager as unknown as {+ state: "running";+ executionQueue: Promise<void>;+ executeInner: typeof executeInner;+ start: () => Promise<void>;+ },+ { state: "running", executionQueue: previousExecution, executeInner, start: async () => {} },+ );++ const snapshot = (+ manager as unknown as {+ captureSnapshot: (options?: { executionTimeoutMs?: number }) => Promise<unknown>;+ }+ ).captureSnapshot({ executionTimeoutMs: 5000 });+ await vi.advanceTimersByTimeAsync(5000);+ expect(executeInner).not.toHaveBeenCalled();++ releaseQueue();+ await waitForCalls(executeInner, 1);+ const signal = executeInner.mock.calls[0]?.[2].signal;+ expect(signal?.aborted).toBe(false);+ await vi.advanceTimersByTimeAsync(4999);+ expect(signal?.aborted).toBe(false);+ await vi.advanceTimersByTimeAsync(1);+ expect(signal?.aborted).toBe(true);+ await expect(snapshot).resolves.toBeNull();+ });++ it("routes null-id and stale-id stream events into backgroundOutput, not stdout", async () => {+ const writeLine = vi.fn(async (_request: Record<string, unknown>) => {});+ const { manager, internals } = runningManagerWith(writeLine);++ const executePromise = manager.execute("print('own')");+ await waitForCalls(writeLine, 1);+ const execution = internals.activeExecution;+ expect(execution).toBeDefined();+ if (!execution) {+ throw new Error("Expected an active execution");+ }++ internals.handleEvent({ event: "stdout", id: execution.requestId, text: "own\n" });+ internals.handleEvent({ event: "stdout", id: null, text: "SECRET-null\n" });+ internals.handleEvent({ event: "stdout", id: "stale-cell", text: "SECRET-stale\n" });+ internals.handleEvent({ event: "done", id: execution.requestId, status: "ok" });++ const result = await executePromise;+ expect(result.stdout).toBe("own\n");+ expect(result.stdout).not.toContain("SECRET");+ expect(result.backgroundOutput).toBe("SECRET-null\nSECRET-stale\n");+ manager.disposeSync();+ });++ it("carries between-cell background output into the next execution's result", async () => {+ const writeLine = vi.fn(async (_request: Record<string, unknown>) => {});+ const { manager, internals } = runningManagerWith(writeLine);++ // No active execution: null-id output parks as pending background output.+ internals.handleEvent({ event: "stdout", id: null, text: "between-cells\n" });++ const executePromise = manager.execute("x = 1");+ await waitForCalls(writeLine, 1);+ const execution = internals.activeExecution;+ expect(execution).toBeDefined();+ if (!execution) {+ throw new Error("Expected an active execution");+ }+ internals.handleEvent({ event: "done", id: execution.requestId, status: "ok" });++ const result = await executePromise;+ expect(result.stdout).toBe("");+ expect(result.backgroundOutput).toBe("between-cells\n");+ manager.disposeSync();+ });++ it("dispose writes a protocol shutdown request before hard-killing the child", async () => {+ const writeLine = vi.fn(async (_request: Record<string, unknown>) => {});+ const { manager, internals } = runningManagerWith(writeLine);+ const killSignals: (NodeJS.Signals | number | undefined)[] = [];+ internals.child = {+ kill: (signal?: NodeJS.Signals | number) => {+ killSignals.push(signal);+ return true;+ },+ pid: undefined,+ stdin: { destroyed: false, destroy: () => undefined },+ };++ await manager.dispose();+ const types = writeLine.mock.calls.map((call) => (call[0] as { type?: string }).type);+ expect(types).toContain("shutdown");+ expect(killSignals).toContain("SIGTERM");+ });++ it("drops stale between-cell background output on kernel teardown", async () => {+ const writeLine = vi.fn(async (_request: Record<string, unknown>) => {});+ const { manager, internals } = runningManagerWith(writeLine);++ internals.handleEvent({ event: "stdout", id: null, text: "pre-restart-leftover\n" });+ manager.disposeSync();++ // Simulate the restarted kernel: a new execution must start clean.+ Object.assign(internals, { state: "running", start: async () => {} });+ const executePromise = manager.execute("x = 1");+ await waitForCalls(writeLine, 1);+ const execution = internals.activeExecution;+ expect(execution).toBeDefined();+ if (!execution) {+ throw new Error("Expected an active execution");+ }+ internals.handleEvent({ event: "done", id: execution.requestId, status: "ok" });++ const result = await executePromise;+ expect(result.backgroundOutput).toBeUndefined();+ manager.disposeSync();+ });++ it("marks between-cell background output as truncated once the pending cap is hit", async () => {+ const writeLine = vi.fn(async (_request: Record<string, unknown>) => {});+ const { manager, internals } = runningManagerWith(writeLine);++ // Overflow the pending buffer while idle; nothing more arrives during the cell.+ internals.handleEvent({ event: "stdout", id: null, text: "x".repeat(70 * 1024) });++ const executePromise = manager.execute("x = 1");+ await waitForCalls(writeLine, 1);+ const execution = internals.activeExecution;+ expect(execution).toBeDefined();+ if (!execution) {+ throw new Error("Expected an active execution");+ }+ internals.handleEvent({ event: "done", id: execution.requestId, status: "ok" });++ const result = await executePromise;+ expect(result.backgroundOutput).toContain("background output truncated at");+ expect(result.backgroundOutput?.length).toBeLessThan(70 * 1024);+ manager.disposeSync();+ });+});diff --git a/packages/coding-agent/test/repl-kernel-execute.test.ts b/packages/coding-agent/test/repl-kernel-execute.test.tsnew file mode 100644index 0000000000..d8c4023e5a--- /dev/null+++ b/packages/coding-agent/test/repl-kernel-execute.test.ts@@ -0,0 +1,164 @@+import { spawnSync } from "node:child_process";+import { existsSync, mkdtempSync, rmSync } from "node:fs";+import { homedir, tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import {+ AGENT_MESSAGE_DISPLAY_MIME,+ ATTACHMENT_DISPLAY_MIME,+ DIFF_DISPLAY_MIME,+ type HostRequestHandlers,+ ReplKernelManager,+} from "../src/core/kernel/index.js";++function resolveReplPython(): string | null {+ const candidates = [+ process.env.PRIME_AGENT_KERNEL_PYTHON,+ resolve(__dirname, "..", "..", "..", "prime-agent-runtime", ".venv", "bin", "python"),+ join(homedir(), ".prime", "agent", "kernel-venv", "bin", "python"),+ ].filter((p): p is string => Boolean(p));+ for (const python of candidates) {+ if (!existsSync(python)) continue;+ const check = spawnSync(python, ["-c", "import rlm.repl, dill"], { encoding: "utf8" });+ if (check.status === 0) return python;+ }+ return null;+}++const python = resolveReplPython();+const describeIf = python ? describe : describe.skip;++describeIf("ReplKernelManager execute (real runtime)", () => {+ let dir = "";+ let manager: ReplKernelManager | undefined;++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "prime-agent-repl-execute-"));+ });++ afterEach(async () => {+ await manager?.dispose();+ manager = undefined;+ if (dir) {+ rmSync(dir, { recursive: true, force: true });+ dir = "";+ }+ });++ it("streams stdout/stderr, returns results, and persists state across cells", async () => {+ manager = new ReplKernelManager({ python: python as string, cwd: dir });+ const chunks: { name: string; text: string }[] = [];+ const first = await manager.execute("import sys\nx = 21\nprint('to-out')\nsys.stderr.write('to-err\\n')", {+ onStream: (chunk, name) => chunks.push({ name, text: chunk }),+ });+ expect(first.status).toBe("ok");+ expect(first.stdout).toContain("to-out");+ expect(first.stderr).toContain("to-err");+ expect(chunks.some((c) => c.name === "stdout" && c.text.includes("to-out"))).toBe(true);++ const second = await manager.execute("x * 2");+ expect(second.status).toBe("ok");+ expect(second.result).toBe("42");+ }, 30_000);++ it("reports cell errors with a clean traceback", async () => {+ manager = new ReplKernelManager({ python: python as string, cwd: dir });+ const r = await manager.execute("def boom():\n raise ValueError('nope')\nboom()");+ expect(r.status).toBe("error");+ expect(r.error?.ename).toBe("ValueError");+ expect(r.error?.evalue).toBe("nope");+ expect(r.error?.traceback.join("")).toContain("raise ValueError('nope')");+ }, 30_000);++ it("parses emitted display payloads into diffs, attachments, and sent messages", async () => {+ manager = new ReplKernelManager({ python: python as string, cwd: dir });+ const code = [+ "from rlm import emit",+ `emit({${JSON.stringify(DIFF_DISPLAY_MIME)}: {"path": "/tmp/f.py", "old_str": "a", "new_str": "b", "start_line": 3}})`,+ `emit({${JSON.stringify(ATTACHMENT_DISPLAY_MIME)}: {"mime_type": "image/png", "data": "aGVsbG8=", "path": "/tmp/i.png"}})`,+ `emit({${JSON.stringify(AGENT_MESSAGE_DISPLAY_MIME)}: {"id": "m1", "message": "hi", "deliveryStatus": "delivered", "receiverRole": "parent", "target": {"activeSessionId": "a", "sessionId": "s"}}})`,+ ].join("\n");+ const r = await manager.execute(code);+ expect(r.status).toBe("ok");+ expect(r.diffs).toEqual([{ path: "/tmp/f.py", oldStr: "a", newStr: "b", startLine: 3 }]);+ expect(r.attachments).toEqual([{ mimeType: "image/png", data: "aGVsbG8=", path: "/tmp/i.png" }]);+ expect(r.sentAgentMessages).toEqual([+ {+ id: "m1",+ message: "hi",+ deliveryStatus: "delivered",+ receiverRole: "parent",+ target: { activeSessionId: "a", sessionId: "s" },+ },+ ]);+ }, 30_000);++ it("round-trips host requests through hostHandlers, including error replies", async () => {+ const hostHandlers: HostRequestHandlers = {+ "test.echo": async (payload) => ({ echoed: payload.value, cell: payload.cellSourceCode }),+ "test.fail": async () => {+ throw new Error("handler exploded");+ },+ };+ manager = new ReplKernelManager({ python: python as string, cwd: dir, hostHandlers });++ const ok = await manager.execute(+ "import rlm\nreply = await rlm.host_request('test.echo', {'value': 7})\nreply['echoed']",+ );+ expect(ok.status).toBe("ok");+ expect(ok.result).toBe("7");++ const cellSource = await manager.execute("reply['cell']");+ expect(cellSource.status).toBe("ok");+ expect(cellSource.result).toContain("test.echo");++ const failed = await manager.execute("import rlm\nawait rlm.host_request('test.fail')");+ expect(failed.status).toBe("error");+ expect(failed.error?.ename).toBe("RuntimeError");+ expect(failed.error?.evalue).toBe("handler exploded");++ const unknown = await manager.execute("import rlm\nawait rlm.host_request('test.unknown')");+ expect(unknown.status).toBe("error");+ expect(unknown.error?.evalue).toContain('host request type "test.unknown" is not available');+ }, 30_000);++ it("dispose sends the protocol shutdown so live bash children die with the kernel", async () => {+ manager = new ReplKernelManager({ python: python as string, cwd: dir });+ const r = await manager.execute("from rlm import bash\nh = bash('sleep 600')\nh.pid");+ expect(r.status).toBe("ok");+ const pid = Number(r.result);+ expect(Number.isInteger(pid)).toBe(true);+ await manager.dispose();+ let alive = true;+ for (let i = 0; i < 100; i++) {+ try {+ process.kill(pid, 0);+ } catch {+ alive = false;+ break;+ }+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ expect(alive).toBe(false);+ }, 30_000);++ it("surfaces unattributed background output separately from cell stdout", async () => {+ manager = new ReplKernelManager({ python: python as string, cwd: dir });+ const first = await manager.execute(+ [+ "import threading, time",+ "def late():",+ " time.sleep(0.5)",+ " print('SECRET-thread', flush=True)",+ "threading.Thread(target=late, daemon=True).start()",+ ].join("\n"),+ );+ expect(first.status).toBe("ok");++ const second = await manager.execute("import time\ntime.sleep(1.0)\nprint('own-output')");+ expect(second.status).toBe("ok");+ expect(second.stdout).toContain("own-output");+ expect(second.stdout).not.toContain("SECRET-thread");+ expect(second.backgroundOutput ?? "").toContain("SECRET-thread");+ }, 30_000);+});diff --git a/packages/coding-agent/test/kernel-mcp-shutdown.test.ts b/packages/coding-agent/test/repl-kernel-mcp-shutdown.test.tssimilarity index 78%rename from packages/coding-agent/test/kernel-mcp-shutdown.test.tsrename to packages/coding-agent/test/repl-kernel-mcp-shutdown.test.tsindex fd53c948aa..ca5545c7b2 100644--- a/packages/coding-agent/test/kernel-mcp-shutdown.test.ts+++ b/packages/coding-agent/test/repl-kernel-mcp-shutdown.test.ts@@ -1,9 +1,9 @@import { spawnSync } from "node:child_process";-import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { homedir, tmpdir } from "node:os";import { join, resolve } from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";-import { KernelManager } from "../src/core/kernel/index.js";+import { ReplKernelManager } from "../src/core/kernel/index.js";const runtimePython = resolve("../../prime-agent-runtime/.venv/bin/python");const fallbackPython = join(homedir(), ".prime", "agent", "kernel-venv", "bin", "python");@@ -11,7 +11,7 @@ const fallbackPython = join(homedir(), ".prime", "agent", "kernel-venv", "bin",function resolveKernelPython(): string | null {for (const python of [process.env.PRIME_AGENT_KERNEL_PYTHON, runtimePython, fallbackPython]) {if (!python || !existsSync(python)) continue;- const check = spawnSync(python, ["-c", "import ipykernel, mcp, rlm"], { encoding: "utf8" });+ const check = spawnSync(python, ["-c", "import rlm.repl, mcp, rlm"], { encoding: "utf8" });if (check.status === 0) return python;}return null;@@ -56,13 +56,13 @@ async function waitForExit(pid: number, timeoutMs: number): Promise<boolean> {return !pidExists(pid);}-describeIfKernel("real IPython MCP shutdown", { tags: ["kernel-heavy"] }, () => {+describeIfKernel("real REPL kernel MCP shutdown", { tags: ["kernel-heavy"] }, () => {let dir = "";let fixture = "";let pidFile = "";beforeAll(() => {- dir = mkdtempSync(join(tmpdir(), "prime-agent-mcp-shutdown-"));+ dir = mkdtempSync(join(tmpdir(), "prime-agent-repl-mcp-shutdown-"));fixture = join(dir, "stdio_server.py");pidFile = join(dir, "stdio.pid");writeFileSync(fixture, MCP_SERVER);@@ -72,8 +72,8 @@ describeIfKernel("real IPython MCP shutdown", { tags: ["kernel-heavy"] }, () =>if (dir) rmSync(dir, { recursive: true, force: true });});- it("closes a stdio MCP child on control-channel shutdown without an AnyIO cross-task error", async () => {- let manager: KernelManager | undefined = new KernelManager({+ it("closes a stdio MCP child on graceful shutdown", async () => {+ let manager: ReplKernelManager | undefined = new ReplKernelManager({python: python as string,cwd: resolve("../../prime-agent-runtime"),hostHandlers: {@@ -86,11 +86,11 @@ describeIfKernel("real IPython MCP shutdown", { tags: ["kernel-heavy"] }, () =>});try {const opened = await manager.execute(- "import rlm.mcp as mcp; mcp.install_shutdown_hook(); tools = await mcp.list_tools('fixture'); [t['name'] for t in tools]",+ "import rlm.mcp as mcp; tools = await mcp.list_tools('fixture'); [t['name'] for t in tools]",);expect(opened.status, opened.stderr || opened.error?.traceback.join("\n")).toBe("ok");expect(opened.result).toContain("fixture.echo");- const childPid = Number(await import("node:fs/promises").then(({ readFile }) => readFile(pidFile, "utf8")));+ const childPid = Number(readFileSync(pidFile, "utf8"));expect(pidExists(childPid)).toBe(true);await manager.shutdown();diff --git a/packages/coding-agent/test/repl-kernel-parent-watchdog.test.ts b/packages/coding-agent/test/repl-kernel-parent-watchdog.test.tsnew file mode 100644index 0000000000..f7f375ad68--- /dev/null+++ b/packages/coding-agent/test/repl-kernel-parent-watchdog.test.ts@@ -0,0 +1,408 @@+import { spawn, spawnSync } from "node:child_process";+import { EventEmitter } from "node:events";+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { homedir, tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type * as kernelBootstrap from "../src/core/kernel/bootstrap.js";+import { ReplKernelManager } from "../src/core/kernel/index.js";+import { ORPHAN_PROCESS_JOURNAL_ENV } from "../src/core/orphan-process-journal.js";++const ensureKernelPythonMock = vi.hoisted(() => vi.fn());++vi.mock("../src/core/kernel/bootstrap.js", async (importOriginal) => {+ const original = await importOriginal<typeof kernelBootstrap>();+ return { ...original, ensureKernelPython: ensureKernelPythonMock };+});++let tempDir = "";+const savedJournalPath = process.env[ORPHAN_PROCESS_JOURNAL_ENV];++function writeFakePython(script: string[]): string {+ const python = join(tempDir, "python");+ writeFileSync(python, script.join("\n"));+ chmodSync(python, 0o755);+ return python;+}++interface JournalRecord {+ pid: number;+ ownerPid: number;+ active: boolean;+}++function readJournalRecords(path: string): JournalRecord[] {+ return readFileSync(path, "utf8")+ .split("\n")+ .filter(Boolean)+ .map((line) => JSON.parse(line) as JournalRecord);+}++describe("repl kernel parent watchdog", () => {+ beforeEach(() => {+ tempDir = mkdtempSync(join(tmpdir(), "prime-agent-repl-watchdog-"));+ });++ afterEach(() => {+ ensureKernelPythonMock.mockReset();+ if (savedJournalPath === undefined) delete process.env[ORPHAN_PROCESS_JOURNAL_ENV];+ else process.env[ORPHAN_PROCESS_JOURNAL_ENV] = savedJournalPath;+ if (tempDir) {+ rmSync(tempDir, { recursive: true, force: true });+ tempDir = "";+ }+ });++ it("spawn sets PRIME_AGENT_KERNEL_OWNER_PID and journals the kernel pid", async () => {+ const envDump = join(tempDir, "kernel-env");+ const python = writeFakePython(["#!/bin/sh", `env > "${envDump}"`, "exit 42", ""]);+ const journalPath = join(tempDir, "orphans.jsonl");+ process.env[ORPHAN_PROCESS_JOURNAL_ENV] = journalPath;+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const manager = new ReplKernelManager({ python, cwd: tempDir });++ try {+ await expect(manager.execute("x")).rejects.toThrow(/Kernel exited before ready/);+ } finally {+ errorSpy.mockRestore();+ await manager.dispose();+ }++ expect(readFileSync(envDump, "utf8")).toMatch(new RegExp(`^PRIME_AGENT_KERNEL_OWNER_PID=${process.pid}$`, "m"));++ // Self-exited child: the kill signals nothing, so the record must stay active.+ await vi.waitFor(() => {+ const records = readJournalRecords(journalPath);+ expect(records).toHaveLength(1);+ expect(records[0]?.ownerPid).toBe(process.pid);+ expect(records[0]?.active).toBe(true);+ });+ });++ it("leaves the journal record active when the kill signals nothing", async () => {+ const journalPath = join(tempDir, "orphans.jsonl");+ process.env[ORPHAN_PROCESS_JOURNAL_ENV] = journalPath;+ const manager = new ReplKernelManager({ python: "/nonexistent/python", cwd: tempDir });+ const internals = manager as unknown as {+ child?: { pid?: number; kill(signal: string): boolean };+ cleanupResources(): void;+ };++ try {+ internals.child = { pid: 999999, kill: () => false };+ internals.cleanupResources();++ const records = existsSync(journalPath) ? readJournalRecords(journalPath) : [];+ expect(records.some((r) => r.pid === 999999 && !r.active)).toBe(false);+ } finally {+ await manager.dispose();+ }+ });++ it("writes the inactive journal record when a signaled kill proves ownership", async () => {+ const journalPath = join(tempDir, "orphans.jsonl");+ process.env[ORPHAN_PROCESS_JOURNAL_ENV] = journalPath;+ const manager = new ReplKernelManager({ python: "/nonexistent/python", cwd: tempDir });+ const internals = manager as unknown as {+ child?: { pid?: number; kill(signal: string): boolean };+ cleanupResources(signal?: NodeJS.Signals): void;+ };++ try {+ internals.child = { pid: 999999, kill: () => true };+ internals.cleanupResources("SIGKILL");++ const records = readJournalRecords(journalPath);+ expect(records.some((r) => r.pid === 999999 && !r.active)).toBe(true);+ } finally {+ await manager.dispose();+ }+ });++ it("a stale doStart resumed after a concurrent teardown never touches the new kernel", async () => {+ const journalPath = join(tempDir, "orphans.jsonl");+ process.env[ORPHAN_PROCESS_JOURNAL_ENV] = journalPath;+ let resolvePython: (python: string) => void = () => {};+ ensureKernelPythonMock.mockReturnValue(+ new Promise<string>((resolve) => {+ resolvePython = resolve;+ }),+ );+ const manager = new ReplKernelManager({ cwd: tempDir });+ const internals = manager as unknown as {+ state: string;+ child?: { pid?: number; kill(signal: string): boolean };+ };+ const killB = vi.fn(() => true);+ const childB = { pid: 222222, kill: killB };++ try {+ // Start A blocks inside `await ensureKernelPython(...)`.+ const staleStart = manager.start();+ staleStart.catch(() => {});+ await vi.waitFor(() => expect(ensureKernelPythonMock).toHaveBeenCalledTimes(1));++ // A concurrent teardown bumps the start generation and brings up a new+ // running kernel B.+ await manager.kill();+ internals.state = "running";+ internals.child = childB;++ // The stale doStart resumes: it must fail without touching B or spawning.+ resolvePython("/nonexistent/python");+ await expect(staleStart).rejects.toThrow(/Kernel start superseded/);++ expect(internals.state).toBe("running");+ expect(internals.child).toBe(childB);+ expect(killB).not.toHaveBeenCalled();+ const records = existsSync(journalPath) ? readJournalRecords(journalPath) : [];+ expect(records.some((r) => r.pid === childB.pid)).toBe(false);+ } finally {+ internals.child = undefined;+ internals.state = "idle";+ await manager.dispose();+ }+ });++ it("a shutdown superseded by a concurrent kill reports not-owner so recovery cannot resurrect to idle", async () => {+ const manager = new ReplKernelManager({ python: "/nonexistent-python", cwd: tmpdir() });+ const internals = manager as unknown as {+ state: string;+ child: unknown;+ writeLine: (request: Record<string, unknown>) => Promise<void>;+ shutdown(): Promise<boolean>;+ kill(): Promise<void>;+ };+ internals.state = "starting";+ // A live child handle keeps waitForKernelExit parked so the send actually blocks the shutdown.+ const child = Object.assign(new EventEmitter(), {+ exitCode: null,+ signalCode: null,+ kill: () => true,+ pid: undefined,+ stdin: { destroyed: false, destroy: () => {} },+ stdout: { destroy: () => {} },+ stderr: { destroy: () => {} },+ });+ internals.child = child;+ let releaseSend: () => void = () => {};+ internals.writeLine = () =>+ new Promise<void>((resolve) => {+ releaseSend = resolve;+ });+ const shutdownResult = internals.shutdown();+ await new Promise((resolve) => setTimeout(resolve, 10)); // park in the stdin write+ await internals.kill(); // concurrent teardown wins ownership+ releaseSend();+ child.emit("exit", 0, null);+ expect(await shutdownResult).toBe(false); // recovery must not set idle+ expect(internals.state).toBe("shutdown");+ });++ it("a stale shutdown parked in its stdin-write await never cleans up a successor kernel", async () => {+ const journalPath = join(tempDir, "orphans.jsonl");+ process.env[ORPHAN_PROCESS_JOURNAL_ENV] = journalPath;+ let releaseSend: () => void = () => {};+ const parkedSend = new Promise<void>((resolve) => {+ releaseSend = resolve;+ });+ const killA = vi.fn(() => true);+ const killB = vi.fn(() => true);+ const childA = Object.assign(new EventEmitter(), {+ exitCode: null,+ signalCode: null,+ kill: killA,+ pid: 111111,+ stdin: { destroyed: false, destroy: () => {} },+ stdout: { destroy: () => {} },+ stderr: { destroy: () => {} },+ });+ const childB = Object.assign(new EventEmitter(), {+ exitCode: null,+ signalCode: null,+ kill: killB,+ pid: 222222,+ stdin: { destroyed: false, destroy: () => {} },+ stdout: { destroy: () => {} },+ stderr: { destroy: () => {} },+ });+ const manager = new ReplKernelManager({ python: "/nonexistent/python", cwd: tempDir });+ const internals = manager as unknown as {+ state: string;+ child?: unknown;+ writeLine: (request: Record<string, unknown>) => Promise<void>;+ startPromise?: Promise<void>;+ };++ try {+ // Kernel A is running with a stdin write that parks forever until+ // released — shutdown() will suspend inside its await window after+ // having synchronously set state = "shutdown".+ internals.state = "running";+ internals.child = childA;+ internals.writeLine = () => parkedSend;+ const staleShutdown = manager.shutdown();++ // While A's shutdown is parked, a concurrent teardown reclaims A and a+ // new start brings up kernel B.+ await manager.kill();+ internals.state = "running";+ internals.child = childB;+ const startPromiseB = Promise.resolve();+ internals.startPromise = startPromiseB;++ // A's stale shutdown resumes: it must not clean up B or clear B's start.+ releaseSend();+ await staleShutdown;++ expect(internals.state).toBe("running");+ expect(internals.child).toBe(childB);+ expect(killB).not.toHaveBeenCalled();+ expect(internals.startPromise).toBe(startPromiseB);+ // A was reclaimed by kill(); B must never gain an inactive journal record.+ expect(killA).toHaveBeenCalledWith("SIGKILL");+ const records = existsSync(journalPath) ? readJournalRecords(journalPath) : [];+ expect(records.some((r) => r.pid === childB.pid && !r.active)).toBe(false);+ } finally {+ internals.child = undefined;+ internals.startPromise = undefined;+ internals.state = "idle";+ await manager.dispose();+ }+ });+});++function resolveReplPython(): string | null {+ const candidates = [+ process.env.PRIME_AGENT_KERNEL_PYTHON,+ resolve(__dirname, "..", "..", "..", "prime-agent-runtime", ".venv", "bin", "python"),+ join(homedir(), ".prime", "agent", "kernel-venv", "bin", "python"),+ ].filter((p): p is string => Boolean(p));+ for (const python of candidates) {+ if (!existsSync(python)) continue;+ const check = spawnSync(python, ["-c", "import rlm.repl"], { encoding: "utf8" });+ if (check.status === 0) return python;+ }+ return null;+}++const replPython = resolveReplPython();+const describeIf = replPython && process.platform !== "win32" ? describe : describe.skip;++describeIf("repl runtime outlives-owner watchdog (real runtime)", { tags: ["kernel-heavy"] }, () => {+ it("runtime exits after its owner is SIGKILLed (stdin EOF watchdog)", async () => {+ const dir = mkdtempSync(join(tmpdir(), "prime-agent-repl-watchdog-int-"));+ const pidFile = join(dir, "runtime.pid");+ // The owner must be a separate killable process; it replicates the+ // manager's exact spawn line: piped stdin, so owner death delivers EOF.+ const ownerScript = [+ `const { spawn } = require("node:child_process");`,+ `const { writeFileSync } = require("node:fs");`,+ `const k = spawn(${JSON.stringify(replPython)}, ["-m", "rlm.repl"], {`,+ ` env: { ...process.env, PRIME_AGENT_KERNEL_OWNER_PID: String(process.pid) },`,+ ` stdio: ["pipe", "ignore", "ignore"],`,+ `});`,+ `writeFileSync(${JSON.stringify(pidFile)}, String(k.pid));`,+ `setInterval(() => {}, 1000);`,+ ].join("\n");+ const owner = spawn(process.execPath, ["-e", ownerScript], { stdio: ["ignore", "ignore", "inherit"] });+ let runtimePid = 0;++ try {+ await vi.waitFor(+ () => {+ runtimePid = Number(readFileSync(pidFile, "utf8"));+ expect(runtimePid).toBeGreaterThan(0);+ expect(() => process.kill(runtimePid, 0)).not.toThrow();+ },+ { timeout: 20_000, interval: 500 },+ );++ owner.kill("SIGKILL");++ await vi.waitFor(+ () => {+ expect(() => process.kill(runtimePid, 0)).toThrow();+ },+ { timeout: 20_000, interval: 500 },+ );+ } finally {+ if (runtimePid > 0) {+ try {+ process.kill(runtimePid, "SIGKILL");+ } catch {+ // Already exited (the expected outcome).+ }+ }+ try {+ owner.kill("SIGKILL");+ } catch {+ // Already exited.+ }+ rmSync(dir, { recursive: true, force: true });+ }+ }, 30_000);++ it("runtime exits after owner death even while a non-yielding cell holds the loop", async () => {+ const dir = mkdtempSync(join(tmpdir(), "prime-agent-repl-watchdog-busy-"));+ const pidFile = join(dir, "runtime.pid");+ const busyFile = join(dir, "busy.marker");+ // The cell marks the file, then spins synchronously: the asyncio loop is+ // monopolized, so the stdin-EOF shutdown can never run — only the+ // watchdog thread can take the runtime down.+ const busyRequest = JSON.stringify({+ type: "execute",+ id: "busy-cell",+ code: `open(${JSON.stringify(busyFile)}, "w").write("busy")\nwhile True: pass`,+ });+ const ownerScript = [+ `const { spawn } = require("node:child_process");`,+ `const { writeFileSync } = require("node:fs");`,+ `const k = spawn(${JSON.stringify(replPython)}, ["-m", "rlm.repl"], {`,+ ` env: { ...process.env, PRIME_AGENT_KERNEL_OWNER_PID: String(process.pid) },`,+ ` stdio: ["pipe", "ignore", "ignore"],`,+ `});`,+ `writeFileSync(${JSON.stringify(pidFile)}, String(k.pid));`,+ `k.stdin.write(${JSON.stringify(`${busyRequest}\n`)});`,+ `setInterval(() => {}, 1000);`,+ ].join("\n");+ const owner = spawn(process.execPath, ["-e", ownerScript], { stdio: ["ignore", "ignore", "inherit"] });+ let runtimePid = 0;++ try {+ await vi.waitFor(+ () => {+ runtimePid = Number(readFileSync(pidFile, "utf8"));+ expect(runtimePid).toBeGreaterThan(0);+ expect(() => process.kill(runtimePid, 0)).not.toThrow();+ // The marker proves the busy cell has entered its spin.+ expect(existsSync(busyFile)).toBe(true);+ },+ { timeout: 20_000, interval: 500 },+ );++ owner.kill("SIGKILL");++ await vi.waitFor(+ () => {+ expect(() => process.kill(runtimePid, 0)).toThrow();+ },+ { timeout: 20_000, interval: 500 },+ );+ } finally {+ if (runtimePid > 0) {+ try {+ process.kill(runtimePid, "SIGKILL");+ } catch {+ // Already exited (the expected outcome).+ }+ }+ try {+ owner.kill("SIGKILL");+ } catch {+ // Already exited.+ }+ rmSync(dir, { recursive: true, force: true });+ }+ }, 30_000);+});diff --git a/packages/coding-agent/test/repl-kernel-shutdown.test.ts b/packages/coding-agent/test/repl-kernel-shutdown.test.tsnew file mode 100644index 0000000000..afdf78b1bb--- /dev/null+++ b/packages/coding-agent/test/repl-kernel-shutdown.test.ts@@ -0,0 +1,227 @@+import { EventEmitter } from "node:events";+import { readFileSync } from "node:fs";+import { resolve } from "node:path";+import { describe, expect, it, vi } from "vitest";+import { type HostRequestHandlers, ReplKernelManager } from "../src/core/kernel/index.js";++type ShutdownInternals = {+ state: "running";+ writeLine: (request: Record<string, unknown>) => Promise<void>;+ handleEvent: (event: Record<string, unknown>) => void;+ wireChild: (child: ShutdownInternals["child"]) => void;+ pendingDoneWaiters: Map<string, () => void>;+ inFlightHostRequests: Set<Promise<void>>;+ child: EventEmitter & {+ exitCode: number | null;+ signalCode: NodeJS.Signals | null;+ kill: (signal?: NodeJS.Signals | number) => boolean;+ pid?: number;+ stdin: { destroyed: boolean; destroy: () => void };+ stdout?: { destroy: () => void; on: (event: string, listener: (...args: unknown[]) => void) => void };+ stderr?: { destroy: () => void; on: (event: string, listener: (...args: unknown[]) => void) => void };+ };+};++function configuredManager(+ onSend: (request: Record<string, unknown>, internals: ShutdownInternals) => void | Promise<void>,+ hostHandlers?: HostRequestHandlers,+): {+ manager: ReplKernelManager;+ internals: ShutdownInternals;+} {+ const manager = new ReplKernelManager({ cwd: process.cwd(), hostHandlers });+ const internals = manager as unknown as ShutdownInternals;+ const child = Object.assign(new EventEmitter(), {+ exitCode: null,+ signalCode: null,+ kill: vi.fn(() => true),+ pid: undefined,+ stdin: { destroyed: false, destroy: vi.fn() },+ stdout: { destroy: vi.fn(), on: vi.fn() },+ stderr: { destroy: vi.fn(), on: vi.fn() },+ });+ Object.assign(internals, {+ state: "running",+ writeLine: vi.fn(async (request: Record<string, unknown>) => onSend(request, internals)),+ child,+ });+ // Attach the real exit/error handlers so teardown-ownership races are exercised.+ internals.wireChild(child);+ return { manager, internals };+}++describe("ReplKernelManager graceful shutdown", () => {+ it("bounds a stuck stdin write with the aggregate shutdown deadline", async () => {+ vi.useFakeTimers();+ try {+ const { manager, internals } = configuredManager(() => new Promise<void>(() => {}));+ const shutdown = manager.shutdown();+ await vi.advanceTimersByTimeAsync(5_000);+ await shutdown;+ expect(internals.child).toBeUndefined();+ } finally {+ vi.useRealTimers();+ }+ });++ it("does not finish shutdown before the stdin write settles", async () => {+ let finishSend: (() => void) | undefined;+ const sendBlocked = new Promise<void>((resolve) => {+ finishSend = resolve;+ });+ const { manager, internals } = configuredManager(async (request, state) => {+ state.handleEvent({ event: "done", id: request.id, status: "ok" });+ await sendBlocked;+ state.child.exitCode = 0;+ state.child.emit("exit", 0, null);+ });++ let finished = false;+ const shutdown = manager.shutdown().then(() => {+ finished = true;+ });+ await new Promise((resolve) => globalThis.setTimeout(resolve, 0));+ expect(finished).toBe(false);+ finishSend?.();+ await shutdown;+ expect(internals.pendingDoneWaiters.size).toBe(0);+ });++ it("finishes promptly when the runtime exits without a shutdown done", async () => {+ const { manager, internals } = configuredManager((_request, state) => {+ state.child.exitCode = 0;+ state.child.emit("exit", 0, null);+ });+ vi.useFakeTimers();+ try {+ const shutdown = manager.shutdown();+ await vi.advanceTimersByTimeAsync(100);+ // True = this call performed the cleanup: startup-failure recovery relies on it to resurrect to idle.+ await expect(shutdown).resolves.toBe(true);+ expect(internals.child).toBeUndefined();+ } finally {+ vi.useRealTimers();+ }+ });++ it("settles an in-flight host request before dispose tears the kernel down", async () => {+ let releaseHandler: (() => void) | undefined;+ const handlerBlocked = new Promise<void>((resolve) => {+ releaseHandler = resolve;+ });+ const sentReplies: Record<string, unknown>[] = [];+ const { manager, internals } = configuredManager(+ async (request) => {+ if (request.type === "host_reply") sentReplies.push(request);+ },+ {+ "test.slow": async () => {+ await handlerBlocked;+ return { answer: 42 };+ },+ },+ );++ internals.handleEvent({ event: "host_request", id: "hr-1", data: { type: "test.slow" } });+ expect(internals.inFlightHostRequests.size).toBe(1);++ const dispose = manager.dispose();+ releaseHandler?.();+ await dispose;++ expect(internals.inFlightHostRequests.size).toBe(0);+ expect(sentReplies).toEqual([{ type: "host_reply", id: "hr-1", data: { status: "ok", answer: 42 } }]);+ expect(internals.child).toBeUndefined();+ });++ it("shutdown during an in-flight host request leaves no dangling task once the handler settles", async () => {+ let releaseHandler: (() => void) | undefined;+ const handlerBlocked = new Promise<void>((resolve) => {+ releaseHandler = resolve;+ });+ const { manager, internals } = configuredManager(+ (request, state) => {+ if (request.type !== "shutdown") return;+ state.handleEvent({ event: "done", id: request.id, status: "ok" });+ state.child.exitCode = 0;+ state.child.emit("exit", 0, null);+ },+ {+ "test.slow": async () => {+ await handlerBlocked;+ return { answer: 42 };+ },+ },+ );++ internals.handleEvent({ event: "host_request", id: "hr-1", data: { type: "test.slow" } });+ const tracked = [...internals.inFlightHostRequests];+ expect(tracked).toHaveLength(1);++ await manager.shutdown();+ expect(internals.child).toBeUndefined();++ // The reply write fails against the torn-down child; the task must still settle.+ releaseHandler?.();+ await Promise.all(tracked);+ expect(internals.inFlightHostRequests.size).toBe(0);+ });++ it("restart after a graceful shutdown starts the kernel again", async () => {+ const { manager, internals } = configuredManager((request, state) => {+ if (request.type !== "shutdown") return;+ state.handleEvent({ event: "done", id: request.id, status: "ok" });+ // The runtime exits after acking shutdown; the exit handler must not+ // steal teardown ownership from the in-flight graceful shutdown().+ state.child.exitCode = 0;+ state.child.emit("exit", 0, null);+ });+ const start = vi.spyOn(manager, "start").mockResolvedValue(undefined);++ await manager.restart();++ expect(internals.child).toBeUndefined();+ expect(start).toHaveBeenCalledTimes(1);+ });++ it("restart does not resurrect a kernel a concurrent kill superseded", async () => {+ const { manager } = configuredManager((_request, state) => {+ // A concurrent kill supersedes the in-flight graceful shutdown.+ void manager.kill();+ state.child.emit("exit", null, "SIGKILL");+ });+ const start = vi.spyOn(manager, "start").mockResolvedValue(undefined);++ await manager.restart();++ expect(start).not.toHaveBeenCalled();+ });++ it("waits for the matching shutdown done and removes its waiter", async () => {+ const { manager, internals } = configuredManager(async (request, state) => {+ expect(request.type).toBe("shutdown");+ expect(request.id).toBeTypeOf("string");+ // An unrelated done must not release the shutdown waiter.+ state.handleEvent({ event: "done", id: "unrelated", status: "ok" });+ expect(state.pendingDoneWaiters.size).toBe(1);+ state.handleEvent({ event: "done", id: request.id, status: "ok" });+ queueMicrotask(() => {+ state.child.exitCode = 0;+ state.child.emit("exit", 0, null);+ });+ });++ await manager.shutdown();++ expect(internals.pendingDoneWaiters.size).toBe(0);+ expect(internals.child).toBeUndefined();+ });++ it("keeps the kernel MCP close budget strictly inside the host shutdown deadline", () => {+ const source = readFileSync(resolve(__dirname, "../../../prime-agent-runtime/src/rlm/mcp.py"), "utf8");+ const match = source.match(/^_SHUTDOWN_TIMEOUT = ([\d.]+)$/m);+ expect(match).not.toBeNull();+ // +1s dispatch slack in mcp.py close(); the sum must undercut the host's 5s kill deadline.+ expect((Number(match![1]) + 1) * 1000).toBeLessThan(5000);+ });+});diff --git a/packages/coding-agent/test/repl-kernel-startup.test.ts b/packages/coding-agent/test/repl-kernel-startup.test.tsnew file mode 100644index 0000000000..0ecd04ea72--- /dev/null+++ b/packages/coding-agent/test/repl-kernel-startup.test.ts@@ -0,0 +1,93 @@+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ReplKernelManager } from "../src/core/kernel/index.js";++let tempDir = "";++function writeExecutable(filePath: string, content: string): void {+ writeFileSync(filePath, content);+ chmodSync(filePath, 0o755);+}++describe("ReplKernelManager startup", () => {+ beforeEach(() => {+ tempDir = mkdtempSync(join(tmpdir(), "prime-agent-repl-startup-"));+ });++ afterEach(() => {+ if (tempDir) {+ rmSync(tempDir, { recursive: true, force: true });+ tempDir = "";+ }+ });++ it("surfaces kernels that exit before ready with the stderr tail", async () => {+ const python = join(tempDir, "python");+ writeExecutable(python, ["#!/bin/sh", 'echo "fake runtime died before ready" >&2', "exit 42", ""].join("\n"));+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const manager = new ReplKernelManager({ python, cwd: tempDir });++ try {+ await expect(manager.execute("print(1)")).rejects.toThrow(+ /Kernel exited before ready[\s\S]*fake runtime died before ready/,+ );+ } finally {+ errorSpy.mockRestore();+ await manager.dispose();+ }+ });++ it("fails a runtime announcing an unexpected protocol version", async () => {+ const python = join(tempDir, "python");+ writeExecutable(+ python,+ ["#!/bin/sh", `echo '{"event":"ready","protocol":1,"python":"3.13.0"}'`, "exec sleep 60", ""].join("\n"),+ );+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const manager = new ReplKernelManager({ python, cwd: tempDir });++ try {+ await expect(manager.execute("print(1)")).rejects.toThrow(/speaks protocol 1, expected 2/);+ } finally {+ errorSpy.mockRestore();+ await manager.dispose();+ }+ });++ it("rejects promptly when the kernel process fails to spawn", async () => {+ const python = join(tempDir, "does-not-exist");+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const manager = new ReplKernelManager({ python, cwd: tempDir });++ try {+ // Without prompt rejection this would ride out the 30s ready timeout.+ await expect(manager.start()).rejects.toThrow(/ENOENT/);+ } finally {+ errorSpy.mockRestore();+ await manager.dispose();+ }+ });++ it("times out a runtime that never sends ready", async () => {+ vi.useFakeTimers();+ const python = join(tempDir, "python");+ writeExecutable(python, ["#!/bin/sh", "exec sleep 120", ""].join("\n"));+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const manager = new ReplKernelManager({ python, cwd: tempDir });++ try {+ const startPromise = manager.start();+ const expectation = expect(startPromise).rejects.toThrow(/did not become ready within 30000ms/);+ await vi.advanceTimersByTimeAsync(30_000);+ // The failure path runs a graceful shutdown bounded by its own deadline.+ await vi.advanceTimersByTimeAsync(5_000);+ await expectation;+ } finally {+ vi.useRealTimers();+ errorSpy.mockRestore();+ await manager.dispose();+ }+ });+});diff --git a/packages/coding-agent/test/repl-kernel-state-roundtrip.test.ts b/packages/coding-agent/test/repl-kernel-state-roundtrip.test.tsnew file mode 100644index 0000000000..130ea1364b--- /dev/null+++ b/packages/coding-agent/test/repl-kernel-state-roundtrip.test.ts@@ -0,0 +1,194 @@+import { spawnSync } from "node:child_process";+import { existsSync, mkdtempSync, rmSync } from "node:fs";+import { homedir, tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { ReplKernelManager } from "../src/core/kernel/index.js";++function resolveReplPython(): string | null {+ const candidates = [+ process.env.PRIME_AGENT_KERNEL_PYTHON,+ resolve(__dirname, "..", "..", "..", "prime-agent-runtime", ".venv", "bin", "python"),+ join(homedir(), ".prime", "agent", "kernel-venv", "bin", "python"),+ ].filter((p): p is string => Boolean(p));+ for (const python of candidates) {+ if (!existsSync(python)) continue;+ const check = spawnSync(python, ["-c", "import rlm.repl, dill"], { encoding: "utf8" });+ if (check.status === 0) return python;+ }+ return null;+}++const python = resolveReplPython();+const describeIfKernel = python ? describe : describe.skip;++describeIfKernel("repl kernel state snapshot round-trip (real runtime)", { tags: ["kernel-heavy"] }, () => {+ let dir = "";+ let snapshotPath = "";+ let manifestPath = "";++ beforeAll(() => {+ dir = mkdtempSync(join(tmpdir(), "prime-agent-repl-roundtrip-"));+ snapshotPath = join(dir, "session.dill");+ manifestPath = join(dir, "session.json");+ });++ afterAll(() => {+ if (dir) rmSync(dir, { recursive: true, force: true });+ });++ function newManager(): ReplKernelManager {+ return new ReplKernelManager({+ python: python as string,+ cwd: dir,+ snapshot: { path: snapshotPath, manifestPath },+ });+ }++ it("saves picklable names, reports unpicklable ones, then revives them in a fresh runtime", async () => {+ const writer = newManager();+ try {+ await writer.execute("x = 42");+ await writer.execute("df = [1, 2, 3]");+ await writer.execute("def double(n):\n return n * 2");+ await writer.execute("gen = (n for n in range(3))");++ const snap = await writer.snapshotState();+ expect(snap).not.toBeNull();+ expect(snap?.saved).toEqual(expect.arrayContaining(["x", "df", "double"]));+ expect(snap?.skipped.map((s) => s.name)).toContain("gen");+ expect(existsSync(snapshotPath)).toBe(true);+ expect(existsSync(manifestPath)).toBe(true);+ } finally {+ await writer.dispose();+ }++ const reader = newManager();+ try {+ const restore = await reader.restoreState();+ expect(restore?.restored).toEqual(expect.arrayContaining(["df", "double", "x"]));+ expect(restore?.failed.map((f) => f.name) ?? []).not.toContain("x");++ const echo = await reader.execute("print(x, double(x), sum(df))");+ expect(echo.stdout.trim()).toBe("42 84 6");+ } finally {+ await reader.dispose();+ }+ }, 60_000);++ it("treats a missing snapshot as an empty restore (clean start)", async () => {+ const freshDir = mkdtempSync(join(tmpdir(), "prime-agent-repl-state-empty-"));+ const manager = new ReplKernelManager({+ python: python as string,+ cwd: freshDir,+ snapshot: { path: join(freshDir, "missing.dill"), manifestPath: join(freshDir, "missing.json") },+ });+ try {+ const restore = await manager.restoreState();+ expect(restore).toEqual({ restored: [], failed: [], path: join(freshDir, "missing.dill") });+ } finally {+ await manager.dispose();+ rmSync(freshDir, { recursive: true, force: true });+ }+ }, 60_000);++ it("restores a snapshot artifact containing IPython-injected blobs, skipping those names", async () => {+ // Synthesize the artifact shape an IPython-kernel snapshot writes: a dict of+ // dill blobs including In/Out/get_ipython entries.+ const ipythonArtifactDir = mkdtempSync(join(tmpdir(), "prime-agent-repl-ipython-artifact-"));+ const ipythonArtifactPath = join(ipythonArtifactDir, "kernel-state.dill");+ const buildScript = [+ "import dill",+ "dill.settings['recurse'] = True",+ "payload = {",+ " 'kept_number': dill.dumps(41),",+ " 'kept_text': dill.dumps('hello'),",+ " 'In': dill.dumps(['print(1)']),",+ " 'Out': dill.dumps({1: 'x'}),",+ " 'get_ipython': dill.dumps(None),",+ "}",+ `with open(${JSON.stringify(ipythonArtifactPath)}, "wb") as fh:`,+ " dill.dump(payload, fh)",+ ].join("\n");+ const build = spawnSync(python as string, ["-c", buildScript], { encoding: "utf8" });+ expect(build.status).toBe(0);++ const manager = new ReplKernelManager({+ python: python as string,+ cwd: ipythonArtifactDir,+ snapshot: { path: ipythonArtifactPath, manifestPath: join(ipythonArtifactDir, "kernel-state.json") },+ });+ try {+ const restore = await manager.restoreState();+ expect(restore?.restored).toEqual(["kept_number", "kept_text"]);+ expect(restore?.failed).toEqual([]);+ const echo = await manager.execute("print(kept_number + 1, kept_text, 'In' in dir(), 'Out' in dir())");+ expect(echo.stdout.trim()).toBe("42 hello False False");+ } finally {+ await manager.dispose();+ rmSync(ipythonArtifactDir, { recursive: true, force: true });+ }+ }, 60_000);++ it("lists live user-defined names, filtering internals and live handles", async () => {+ const listDir = mkdtempSync(join(tmpdir(), "prime-agent-repl-state-list-"));+ const manager = new ReplKernelManager({ python: python as string, cwd: listDir });+ try {+ expect(await manager.listNamespaceNames()).toBeNull();+ await manager.execute("alpha = 1\ndef helper(n):\n return n\n_hidden = 2\nrlm = object()");+ const names = await manager.listNamespaceNames();+ expect(names).toEqual(expect.arrayContaining(["alpha", "helper"]));+ expect(names).not.toContain("_hidden");+ expect(names).not.toContain("rlm");+ } finally {+ await manager.dispose();+ rmSync(listDir, { recursive: true, force: true });+ }+ }, 60_000);++ it("prunes oversized variables via a compaction snapshot", async () => {+ const boundedDir = mkdtempSync(join(tmpdir(), "prime-agent-repl-state-bounded-"));+ const manager = new ReplKernelManager({+ python: python as string,+ cwd: boundedDir,+ snapshot: {+ path: join(boundedDir, "bounded.dill"),+ manifestPath: join(boundedDir, "bounded.json"),+ maxBytes: 10 * 1024,+ maxVariableBytes: 8 * 1024,+ },+ });+ try {+ await manager.execute('small_text = "a" * 100\nlarge_text = "x" * 16_384');+ const snapshot = await manager.snapshotState();+ expect(snapshot?.skipped.map(({ name }) => name)).toContain("large_text");+ expect(snapshot?.saved).toContain("small_text");++ const compacted = await manager.pruneOversizedVariables();+ expect(compacted?.pruned).toEqual(["large_text"]);+ const remaining = await manager.listNamespaceNames();+ expect(remaining).toContain("small_text");+ expect(remaining).not.toContain("large_text");+ } finally {+ await manager.dispose();+ rmSync(boundedDir, { recursive: true, force: true });+ }+ }, 60_000);++ it("auto-snapshots after a successful execution (debounced)", async () => {+ const autoDir = mkdtempSync(join(tmpdir(), "prime-agent-repl-state-auto-"));+ const autoPath = join(autoDir, "auto.dill");+ const manager = new ReplKernelManager({+ python: python as string,+ cwd: autoDir,+ snapshot: { path: autoPath, manifestPath: join(autoDir, "auto.json"), debounceMs: 50 },+ });+ try {+ await manager.execute("auto_var = 'persisted'");+ await expect.poll(() => existsSync(autoPath), { timeout: 10_000 }).toBe(true);+ } finally {+ await manager.dispose();+ rmSync(autoDir, { recursive: true, force: true });+ }+ }, 60_000);+});diff --git a/packages/coding-agent/test/sdk-session-manager.test.ts b/packages/coding-agent/test/sdk-session-manager.test.tsindex 005d2bde8e..4f96a0debe 100644--- a/packages/coding-agent/test/sdk-session-manager.test.ts+++ b/packages/coding-agent/test/sdk-session-manager.test.ts@@ -82,7 +82,7 @@ describe("createAgentSession session manager defaults", () => {const ipythonTool = session.agent.state.tools.find((tool) => tool.name === "ipython");expect(ipythonTool).toBeTruthy();- const result = await ipythonTool!.execute("test", { code: "%%bash\npwd" });+ const result = await ipythonTool!.execute("test", { code: "import os\nprint(os.getcwd())" });const output = result.content.filter((item): item is { type: "text"; text: string } => item.type === "text").map((item) => item.text)@@ -91,5 +91,5 @@ describe("createAgentSession session manager defaults", () => {expect(realpathSync(output.trim())).toBe(realpathSync(sessionCwd));session.dispose();- });+ }, 120_000);});diff --git a/packages/coding-agent/test/suite/daemon-serialized-refine-process.test.ts b/packages/coding-agent/test/suite/daemon-serialized-refine-process.test.tsindex 74efd6fa92..6b25ce1178 100644--- a/packages/coding-agent/test/suite/daemon-serialized-refine-process.test.ts+++ b/packages/coding-agent/test/suite/daemon-serialized-refine-process.test.ts@@ -90,7 +90,6 @@ async function runCli([ENV_AGENT_DIR]: options.agentDir,PI_SKIP_VERSION_CHECK: "1",PRIME_AGENT_INTERNAL_LEGACY_OWNED_WORKER_FRONTEND: "0",- PRIME_AGENT_KERNEL_FORKSERVER: "0",RLM_DEPTH: "0",// The test deliberately RE-INJECTS the worker role env var// (via options.environment, applied last) to prove thediff --git a/packages/coding-agent/test/suite/regressions/4428-remove-legacy-pi-mono-tools.test.ts b/packages/coding-agent/test/suite/regressions/4428-remove-legacy-pi-mono-tools.test.tsindex eb3b26c3fa..c565b6da4e 100644--- a/packages/coding-agent/test/suite/regressions/4428-remove-legacy-pi-mono-tools.test.ts+++ b/packages/coding-agent/test/suite/regressions/4428-remove-legacy-pi-mono-tools.test.ts@@ -107,7 +107,7 @@ describe("regression #4428: remove legacy pi-mono built-in tools", () => {session.dispose();});- it("applies shell settings to ipython bash cells", async () => {+ it("applies shell settings to bash() commands in the REPL", async () => {const shellPath = join(tempDir, "custom-shell.sh");writeFileSync(shellPath, "#!/bin/sh\nprintf 'custom-shell\\n'\nexec /bin/sh \"$@\"\n");chmodSync(shellPath, 0o755);@@ -138,15 +138,26 @@ describe("regression #4428: remove legacy pi-mono built-in tools", () => {const ipythonTool = session.agent.state.tools.find((tool) => tool.name === "ipython");expect(ipythonTool).toBeTruthy();- const result = await ipythonTool!.execute("tool-1", { code: "%%bash\necho body" });- const output = result.content+ // %%bash cells fail as plain Python syntax errors instead of running.+ const rejected = await ipythonTool!.execute("tool-0", { code: "%%bash\necho body" });+ expect(rejected.details).toMatchObject({ status: "error" });+ const rejectedText = rejected.content.filter((item): item is { type: "text"; text: string } => item.type === "text").map((item) => item.text).join("");+ expect(rejectedText).toContain("SyntaxError");+ // bash() picks up the configured shell and command prefix from the tool environment.+ const result = await ipythonTool!.execute("tool-1", {+ code: "print((await bash('echo body')).output)",+ });+ const output = result.content+ .filter((item): item is { type: "text"; text: string } => item.type === "text")+ .map((item) => item.text)+ .join("");expect(output).toContain("custom-shell\nprefix-from-settings\nbody");} finally {await session.disposeAsync();}- });+ }, 120_000);});diff --git a/packages/coding-agent/test/suite/regressions/4529-leading-newline-bash-cell.test.ts b/packages/coding-agent/test/suite/regressions/4529-leading-newline-bash-cell.test.tsindex f13fa907d3..7789e4c831 100644--- a/packages/coding-agent/test/suite/regressions/4529-leading-newline-bash-cell.test.ts+++ b/packages/coding-agent/test/suite/regressions/4529-leading-newline-bash-cell.test.ts@@ -33,13 +33,7 @@ describe("ENG-4529 leading newline before %%bash", () => {});it("parses blank lines, indentation, arguments, and CRLF before the bash body", () => {- expect(parseIpythonBashCell(" \r\n\t\r\n %%bash --noprofile\r\necho ok")).toEqual({- leadingWhitespace: " \r\n\t\r\n",- indent: " ",- magicArguments: " --noprofile",- lineBreak: "\r\n",- body: "echo ok",- });+ expect(parseIpythonBashCell(" \r\n\t\r\n %%bash --noprofile\r\necho ok")).toEqual({ body: "echo ok" });expect(parseIpythonBashCell("\nprint('python')")).toBeUndefined();});diff --git a/packages/coding-agent/test/suite/regressions/4530-ipython-state-restore-message.test.ts b/packages/coding-agent/test/suite/regressions/4530-ipython-state-restore-message.test.tsindex 2336b2eb9f..85a7359a88 100644--- a/packages/coding-agent/test/suite/regressions/4530-ipython-state-restore-message.test.ts+++ b/packages/coding-agent/test/suite/regressions/4530-ipython-state-restore-message.test.ts@@ -116,10 +116,10 @@ describe("ENG-4530 IPython state restore message", () => {}const component = new InjectedPromptMessageComponent(restoreMessage);- expect(render(component)).toContain("◆ Restored IPython kernel state");+ expect(render(component)).toContain("◆ Restored Python kernel state");expect(render(component)).not.toContain("alpha");component.setExpanded(true);- expect(render(component)).toContain("◆ Restored IPython kernel state");+ expect(render(component)).toContain("◆ Restored Python kernel state");expect(render(component)).not.toContain("ipython_state_restored");expect(render(component)).not.toContain("alpha");});@@ -170,7 +170,7 @@ describe("ENG-4530 IPython state restore message", () => {};const component = new InjectedPromptMessageComponent(message);- expect(render(component)).toContain("◆ Started fresh IPython kernel");+ expect(render(component)).toContain("◆ Started fresh Python kernel");component.setExpanded(true);expect(render(component)).not.toContain("restore details");});diff --git a/packages/coding-agent/test/system-prompt.test.ts b/packages/coding-agent/test/system-prompt.test.tsindex 4417eaa709..ca39619eb1 100644--- a/packages/coding-agent/test/system-prompt.test.ts+++ b/packages/coding-agent/test/system-prompt.test.ts@@ -45,8 +45,8 @@ describe("buildRlmPrompt", () => {expect(prompt).toContain("Installed Python skill modules (pre-imported): `websearch`.");expect(prompt).toContain("A callable `rlm` is already in your global namespace");- expect(prompt).toContain("IPython is the agent's long-lived notebook");- expect(prompt).toContain("Each `%%bash` cell runs in a throw-away subshell");+ expect(prompt).toContain("persistent Python REPL");+ expect(prompt).toContain("Python is the orchestration language");});test("discovers requested models through a bounded authenticated host search", () => {@@ -71,7 +71,7 @@ describe("buildRlmPrompt", () => {allowRecursion: false,});- expect(prompt).not.toContain("IPython is the agent's long-lived notebook");+ expect(prompt).not.toContain("persistent Python REPL");});test("keeps shell skill command guidance when ipython is inactive", () => {@@ -159,7 +159,7 @@ describe("buildRlmPrompt", () => {}});- test("documents the %%bash first-line rule when ipython is active", () => {+ test("documents the bash() orchestration contract when ipython is active", () => {const prompt = buildRlmPrompt({cwd: "/repo",messagesPath: "/repo/.pi/sessions/session.jsonl",@@ -167,7 +167,7 @@ describe("buildRlmPrompt", () => {allowRecursion: false,});- expect(prompt).toContain("it must be the first line of the code cell");+ expect(prompt).toContain("Use `bash()` to invoke programs, not to write shell programs");});test("documents preferring Python for reading and searching files when ipython is active", () => {@@ -472,7 +472,7 @@ describe("buildSystemPrompt", () => {expect(prompt).toContain("# Continual Harness State");expect(prompt).toContain("Call contract: use installed skills as shell commands");expect(prompt).toContain("subagent: 1");- expect(prompt).not.toContain("IPython is the agent's long-lived notebook");+ expect(prompt).not.toContain("persistent Python REPL");expect(prompt).not.toContain("Default to non-blocking subagents");expect(prompt).not.toContain("agent_observe.list_agents");expect(prompt).not.toContain("asyncio.create_task");@@ -516,7 +516,7 @@ describe("buildSystemPrompt", () => {});expect(prompt).toContain("# Continual Harness State");- expect(prompt).toContain("without IPython or shell access");+ expect(prompt).toContain("without the Python REPL or shell access");expect(prompt).not.toContain("use installed skills as shell commands");expect(prompt).not.toContain("<skill_import> ...");expect(prompt).not.toContain("asyncio.create_task");@@ -679,9 +679,9 @@ describe("createIpythonToolDefinition", () => {test("describes project checks as target-environment work", () => {const tool = createIpythonToolDefinition("/repo");- expect(tool.description).toContain("Python scratchpad code");+ expect(tool.description).toContain("persistent Python REPL");expect(tool.description).toContain("target project's own environment");- expect(tool.promptSnippet).toContain("%%bash orchestration");+ expect(tool.promptSnippet).toContain("bash() orchestration");const codeSchema = tool.parameters.properties.code;const codeDescription ="description" in codeSchema && typeof codeSchema.description === "string" ? codeSchema.description : "";diff --git a/packages/coding-agent/vitest.config.ts b/packages/coding-agent/vitest.config.tsindex 73a0dae79b..04ec6693a4 100644--- a/packages/coding-agent/vitest.config.ts+++ b/packages/coding-agent/vitest.config.ts@@ -19,7 +19,7 @@ export default defineConfig({},{name: "kernel-heavy",- description: "Boots a real IPython kernel and syncs skills into the shared venv",+ description: "Boots a real Python kernel and syncs skills into the shared venv",},],// Kernel-heavy tests are excluded from the default sharded run: several filesdiff --git a/prime-agent-runtime/pyproject.toml b/prime-agent-runtime/pyproject.tomlindex f09b3a9cda..b258c68990 100644--- a/prime-agent-runtime/pyproject.toml+++ b/prime-agent-runtime/pyproject.toml@@ -4,12 +4,13 @@ version = "0.1.0"description = "Kernel-side runtime shim for Prime Agent recursion"requires-python = ">=3.11"dependencies = [- "ipykernel","mcp>=2,<3",- "nest-asyncio","tyro",]+[dependency-groups]+dev = ["dill"]+[build-system]requires = ["hatchling"]build-backend = "hatchling.build"diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.pyindex ada3f4bb20..43d054d9be 100644--- a/prime-agent-runtime/src/rlm/__init__.py+++ b/prime-agent-runtime/src/rlm/__init__.py@@ -2,7 +2,6 @@from __future__ import annotations-import asyncioimport sysimport typesfrom dataclasses import dataclass@@ -12,19 +11,6 @@ from typing import Anyfrom .bash import BashHandle, BashResult, bashfrom .harness import HarnessEntry, HarnessScope, HarnessState, RefinementEvent, get_harness_state-try:- from ipykernel.comm import Comm-except Exception: # pragma: no cover - depends on ipykernel version- Comm = None # type: ignore[assignment]--try:- from IPython import get_ipython-except Exception: # pragma: no cover - only available in kernels- get_ipython = None # type: ignore[assignment]--HOST_COMM_TARGET = "host.request"--@dataclass(frozen=True)class RLMSpawnHandle:rlm_child_id: str@@ -51,20 +37,6 @@ class RLMSubagent:status: str-def _install_control_comm_handlers() -> None:- """Let comm replies arrive on the control channel during an execute_request."""- if get_ipython is None:- return- shell = get_ipython()- kernel = getattr(shell, "kernel", None)- comm_manager = getattr(kernel, "comm_manager", None)- control_handlers = getattr(kernel, "control_handlers", None)- if comm_manager is None or not isinstance(control_handlers, dict):- return- control_handlers.setdefault("comm_msg", comm_manager.comm_msg)- control_handlers.setdefault("comm_close", comm_manager.comm_close)--def _spawn_handle_from_payload(payload: Any) -> RLMSpawnHandle:if not isinstance(payload, dict):raise RuntimeError("rlm.run returned an invalid spawn handle")@@ -82,6 +54,15 @@ def _spawn_handle_from_payload(payload: Any) -> RLMSpawnHandle:)+def _parse_host_reply(request_type: str, reply: dict[str, Any]) -> dict[str, Any]:+ status = reply.get("status")+ if status == "ok":+ return {k: v for k, v in reply.items() if k != "status"}+ if status == "error":+ raise RuntimeError(str(reply.get("error") or f"host request {request_type} failed"))+ raise RuntimeError(f"host request {request_type} returned unexpected status: {status!r}")++async def host_request(request_type: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:"""Send a typed request to the Prime Agent host and await its reply.@@ -94,56 +75,18 @@ async def host_request(request_type: str, payload: dict[str, Any] | None = None)raise TypeError("request_type must be a non-empty str")if payload is not None and not isinstance(payload, dict):raise TypeError(f"payload must be a dict or None, got {type(payload).__name__}")- if Comm is None:- raise RuntimeError("Jupyter comm support is unavailable in this kernel")- _install_control_comm_handlers()-- loop = asyncio.get_running_loop()- future: asyncio.Future[dict[str, Any]] = loop.create_future()- comm = Comm(target_name=HOST_COMM_TARGET, primary=False)-- def _on_msg(msg: dict[str, Any]) -> None:- content = msg.get("content", {})- reply = content.get("data", {}) if isinstance(content, dict) else {}- if not isinstance(reply, dict):- return-- status = reply.get("status")- if status == "ok":- def _resolve_result() -> None:- if not future.done():- future.set_result({k: v for k, v in reply.items() if k != "status"})- comm.close()-- loop.call_soon_threadsafe(_resolve_result)- return- if status == "error":- message = reply.get("error") or f"host request {request_type} failed"- def _resolve_error() -> None:- if not future.done():- future.set_exception(RuntimeError(str(message)))- comm.close()-- loop.call_soon_threadsafe(_resolve_error)- return-- unexpected = f"host request {request_type} returned unexpected status: {status!r}"- def _resolve_unexpected() -> None:- if not future.done():- future.set_exception(RuntimeError(unexpected))- comm.close()-- loop.call_soon_threadsafe(_resolve_unexpected)-- comm.on_msg(_on_msg)+ from . import repl+# request_type goes last so a payload "type" key cannot reroute the request.- comm.open(data={**(payload or {}), "type": request_type})- try:- return await future- finally:- if not future.done():- future.cancel()- comm.close()+ reply = await repl.host_request({**(payload or {}), "type": request_type})+ return _parse_host_reply(request_type, reply)+++def emit(data: dict[str, Any]) -> None:+ """Ship one display event (dict of MIME type -> JSON payload) to the host."""+ from . import repl++ repl.emit(data)async def run(prompt: str, **kwargs: Any) -> RLMSpawnHandle:@@ -241,15 +184,13 @@ async def delete_subagent(target: str | RLMSubagent) -> RLMSubagent:class _HarnessProxy:"""Resolve the harness state against the current environment on every access.- The kernel forkserver preimports rlm in a template process before per-session- env vars exist; a state bound at import time would freeze that (env-less)- resolution into every forked kernel. Resolving per access picks up the env- applied after fork. Resolution must never raise (a failure inside the kernel- namespace would take down the kernel). When the local store is genuinely- unconfigured (no session env, e.g. --no-session) reads see an empty view but- local writes raise instructively instead of vanishing on kernel exit; any- other resolution failure degrades to a shared in-memory store until local- resolution starts succeeding.+ Session env vars may be applied after import, so a state bound at import+ time could freeze an env-less resolution. Resolution must never raise (a+ failure inside the kernel namespace would take down the kernel). When the+ local store is genuinely unconfigured (no session env, e.g. --no-session)+ reads see an empty view but local writes raise instructively instead of+ vanishing on kernel exit; any other resolution failure degrades to a shared+ in-memory store until local resolution starts succeeding."""_fallback: HarnessState | None = None@@ -335,6 +276,7 @@ __all__ = ["RefinementEvent","bash","delete_subagent",+ "emit","find_models","get_harness_state","harness",diff --git a/prime-agent-runtime/src/rlm/bash.py b/prime-agent-runtime/src/rlm/bash.pyindex fbdc223dff..4de0b49938 100644--- a/prime-agent-runtime/src/rlm/bash.py+++ b/prime-agent-runtime/src/rlm/bash.py@@ -617,7 +617,7 @@ def bash(command: str) -> BashHandle:def _shell() -> str:- # Read per call: the forkserver applies session env after the fork.+ # Read per call so env changes made in the REPL apply to later commands.override = os.environ.get("PRIME_AGENT_BASH_SHELL")if override:if not os.path.isabs(override):@@ -825,20 +825,3 @@ def _install_shutdown_hook() -> None:return_hook_installed = Trueatexit.register(_kill_live_handles)- try:- kernel = get_ipython().kernel # type: ignore[name-defined]- except (AttributeError, NameError):- return- if getattr(kernel, "_prime_agent_bash_shutdown", False):- return- original = kernel.do_shutdown-- async def do_shutdown(restart: bool):- _kill_live_handles()- result = original(restart)- if hasattr(result, "__await__"):- return await result- return result-- kernel.do_shutdown = do_shutdown- kernel._prime_agent_bash_shutdown = Truediff --git a/prime-agent-runtime/src/rlm/mcp.py b/prime-agent-runtime/src/rlm/mcp.pyindex 13ac0b94d6..bc6ecb642e 100644--- a/prime-agent-runtime/src/rlm/mcp.py+++ b/prime-agent-runtime/src/rlm/mcp.py@@ -7,7 +7,6 @@ import hashlibimport ioimport osimport re-import sysimport threadingimport timefrom contextlib import AsyncExitStack@@ -657,27 +656,3 @@ def _seconds(value: Any, default: float) -> float:def _strings(value: Any) -> bool:return isinstance(value, list) and all(isinstance(item, str) for item in value)---def install_shutdown_hook() -> None:- try:- kernel = get_ipython().kernel # type: ignore[name-defined]- except (AttributeError, NameError):- return- if getattr(kernel, "_prime_agent_mcp_shutdown", False):- return- _registry.bind_owner()- original = kernel.do_shutdown-- async def do_shutdown(restart: bool):- try:- await close()- except BaseException as exc:- print(f"Prime Agent MCP shutdown failed: {type(exc).__name__}: {exc}", file=sys.stderr)- result = original(restart)- if hasattr(result, "__await__"):- return await result- return result-- kernel.do_shutdown = do_shutdown- kernel._prime_agent_mcp_shutdown = Truediff --git a/prime-agent-runtime/src/rlm/repl.md b/prime-agent-runtime/src/rlm/repl.mdnew file mode 100644index 0000000000..506e4ea9db--- /dev/null+++ b/prime-agent-runtime/src/rlm/repl.md@@ -0,0 +1,168 @@+# REPL runtime protocol++`python -m rlm.repl` starts a CPython REPL runtime that executes code cells in+one persistent `__main__` namespace on a single asyncio event loop. The wire+format is newline-delimited JSON: one object per line, UTF-8, no other framing.+The current protocol version is `2`; the runtime announces it in the `ready`+event.++## Channels++- Requests arrive on fd 0 (stdin).+- Events leave on a private dup of the original fd 1, made before anything else+ runs. Every frame is one locked write sequence, so frames never interleave.+- Python-level writes through `sys.stdout`/`sys.stderr` are intercepted at+ write time, tagged with the writing context's cell id, and shipped straight+ to the protocol.+- fds 1 and 2 are redirected into pipes at startup; pump threads read them and+ ship the bytes as `stdout`/`stderr` events with `id: null` — raw fd bytes+ (`os.write`, `sys.stdout.buffer.write`, C extensions, subprocesses) are never+ attributed to a cell.+ Neither channel can corrupt protocol framing. Ordering is preserved within+ each channel, not across them.+- fd 0 is rebound to `/dev/null` after the reader thread takes it, so user+ `input()` sees EOF instead of consuming protocol frames.++## Requests++| Request | Fields |+|---|---|+| `execute` | `{"type":"execute","id":str,"code":str}` |+| `interrupt` | `{"type":"interrupt","id"?:str}` — no reply |+| `host_reply` | `{"type":"host_reply","id":str,"data":{...}}` — no reply |+| `snapshot` | `{"type":"snapshot","id":str,"path":str,"manifest_path":str,"max_bytes"?:int,"max_variable_bytes"?:int,"prune_oversized"?:bool}` |+| `restore` | `{"type":"restore","id":str,"path":str}` |+| `list_names` | `{"type":"list_names","id":str}` |+| `shutdown` | `{"type":"shutdown","id"?:str}` |++Requests other than `interrupt` and `host_reply` run strictly in order, one at+a time. A malformed line+produces `{"event":"error","id":null,"ename":"ProtocolError",...}` and the+runtime keeps serving. Closing stdin is equivalent to `shutdown`.++## Events++- `{"event":"ready","protocol":2,"python":"3.13.11"}` — sent once at startup;+ the handshake. No banner precedes it.+- `{"event":"stdout"|"stderr","id":str|null,"text":str}` — captured output.+ `id` is the cell whose Python execution context performed the write; asyncio+ tasks inherit the spawning cell's id (even after that cell finished). `null`+ for user threads, raw fd writes (`os.write`, C extensions, subprocesses),+ and anything else without provable ownership — bytes read from the fd pipes+ are never attributed to a cell.+- `{"event":"result","id":str,"text":str}` — `repr` of the cell's trailing+ expression when the body ends in an expression whose value is not `None`.+ The value is also bound to `_` in the namespace.+- `{"event":"display","id":str|null,"data":{mime:payload,...}}` — one dict of+ MIME type to JSON payload, shipped verbatim from `emit()`. `id` rides task+ context: an asyncio task spawned by a cell keeps that cell's id even after+ the cell finishes; user threads emit `null`.+- `{"event":"host_request","id":str,"data":{...}}` — one typed request from+ runtime code to the host; the host answers with a `host_reply` request+ carrying the same id.+- `{"event":"error","id":str|null,"ename":str,"evalue":str,"traceback":[str,...]}`+- `{"event":"done","id":str,"status":"ok"|"error"}` — exactly one per id'd+ request, always after all of that request's other events. A snapshot `done`+ adds `saved`, `skipped`, `pruned`, `bytes`; a restore `done` adds `restored`,+ `failed`; a `list_names` `done` adds `names`; a failed snapshot/restore adds+ `reason`. Restoring a missing file reports `status:"ok"` with empty+ `restored`/`failed` lists and `reason:"snapshot not found"`.++Before a cell's `done`, the runtime drains both channels: tagged Python-level+writes ship synchronously from the writing thread, and the fd pipes are fenced+with a marker byte sequence awaited in the pumps, so every byte the cell wrote+synchronously — including direct fd writes — precedes its `done`. Ordering+between a cell's Python-level writes and its raw fd writes is not guaranteed+(two channels).++## Execution++Cells compile with `PyCF_ALLOW_TOP_LEVEL_AWAIT` and run as tasks on the+persistent event loop, so `await` works at top level and background tasks+created by a cell keep running between cells. Each cell's source is registered+in `linecache` under `<cell-N>`, so tracebacks show the offending source line.+Tracebacks are plain `traceback` formatting with the runtime's own frames+stripped, keeping cell and library frames; no colors, no decoration.++## Interrupt++`{"type":"interrupt"}` raises `KeyboardInterrupt` in the running cell. Without+an `id` the interrupt applies to the running request, or — when none is running+yet — to the next queued one; with an `id` it applies to that request only.+An interrupt that arrives before its request starts executing is parked and+delivered the moment the request becomes active, so `execute` + `interrupt`+written back-to-back still interrupts the cell. A request stays+interrupt-targetable until its `done` event is emitted: this covers the+post-run trailing-expression `repr` and output drain. Interrupts for finished+or unknown requests are dropped.++Delivery: the reader thread sends SIGINT to the main thread (also the loop+thread); the handler asks asyncio which task's step the signal interrupted.+On Windows (no `signal.pthread_kill`) the reader instead cancels the active+cell task on the loop, so await-suspended cells interrupt normally but cells+blocked in synchronous code cannot be broken (best-effort parity):++- The active cell's own task is mid-step (sync bytecode such as a `time.sleep`+ loop, or a blocking syscall such as `selectors.select()` woken by EINTR):+ the handler raises `KeyboardInterrupt` directly and it propagates out of the+ cell task.+- The loop is idle in `select()` (the cell is suspended at an `await`) or a+ different task — a background task or the runtime itself — is mid-step:+ raising there would land in the wrong context, so the handler cancels the+ active cell task and the runtime reports the cancellation as a+ `KeyboardInterrupt`. When the mid-step task is a background task, the+ handler also raises `KeyboardInterrupt` into it: a background task blocked+ in synchronous code occupies the only thread, so it receives the+ `KeyboardInterrupt` (and dies with it) to unblock the loop and let the+ cancel take effect. Limitation: the interrupt lands at the await point as a+ cancellation, so user code catching `KeyboardInterrupt` around an `await`+ does not intercept it.++Both paths end with an `error` event (`ename` `KeyboardInterrupt`) and+`done` with `status:"error"`; the runtime keeps serving. When nothing is+running or queued, SIGINT and interrupt requests are ignored.++## Display bridge++`from rlm.repl import emit` inside a cell (or any user thread) ships a+`display` event. `emit(data)` takes one non-empty dict keyed by MIME type+strings; the dict is forwarded verbatim as the event's `data`.++## Host bridge++`await rlm.repl.host_request(data)` ships a `host_request` event with a+runtime-minted id and awaits the matching `host_reply`, returning its `data`+dict verbatim. Replies are routed on the reader thread like `interrupt` —+never through the request queue, since the awaiting cell is itself the+in-flight execute. Replies for unknown ids, or for a request whose awaiting+cell was cancelled, are dropped. `rlm.repl.is_active()` reports whether the+process is serving the protocol (importing the module does not count).++## Snapshot / restore++`snapshot` serializes the user namespace with `dill` (recurse mode), one name+at a time: `_`-prefixed names and+`{rlm, mcp, bash, asyncio, In, Out, get_ipython, exit, quit, open}` are always+skipped; a name whose pickle exceeds `max_variable_bytes` or would push the+total over `max_bytes` is skipped and reported. With `prune_oversized`, only+names exceeding the per-variable cap (`max_variable_bytes`) are also deleted+from the namespace and listed in `pruned`; names skipped for the aggregate+`max_bytes` cap are reported in `skipped` but kept in the namespace. The+payload is written atomically (tmp file + `os.replace`) and a JSON manifest+(`version`, `savedNames`, `skipped`, `pruned`, `bytes`, `pythonVersion`,+`timestamp`) is written to `manifest_path`. A manifest write failure fails the+snapshot (and nothing is pruned).++`restore` loads the payload and revives each name independently; a missing+file yields an ok empty restore with `reason:"snapshot not found"`, a corrupt+file fails with a `reason`, and per-name failures are listed in `failed`.+Names `In`, `Out`, and `get_ipython` in a payload are never restored. `dill` is imported lazily; when unavailable, snapshot and restore+fail with `status:"error"` and a `reason`.++`list_names` replies with `done` carrying `names`: the sorted user-defined+top-level names under the same filter the snapshot applies.++## Shutdown++`shutdown` (or stdin EOF) kills live `rlm.bash` child process groups, replies+`done` (when the request carried an id), stops the loop, and exits 0.diff --git a/prime-agent-runtime/src/rlm/repl.py b/prime-agent-runtime/src/rlm/repl.pynew file mode 100644index 0000000000..d2648279ef--- /dev/null+++ b/prime-agent-runtime/src/rlm/repl.py@@ -0,0 +1,1165 @@+"""Minimal CPython REPL runtime speaking newline-delimited JSON over stdio.++Entry point: ``python -m rlm.repl``. The protocol is documented in repl.md+next to this file. Cells execute with top-level await in one persistent+``__main__`` namespace on a single asyncio event loop.+"""++from __future__ import annotations++import ast+import asyncio+import codecs+import contextvars+import ctypes+import inspect+import io+import json+import linecache+import os+import platform+import signal+import sys+import tempfile+import threading+import time+import traceback+import types+import uuid+from collections.abc import Awaitable, Callable+from typing import Any++from .bash import _kill_live_handles++PROTOCOL_VERSION = 2++DEFAULT_SNAPSHOT_MAX_BYTES = 256 * 1024 * 1024+DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES = 16 * 1024 * 1024++# Names the session bootstrap re-creates on every start; never snapshotted.+_ALWAYS_SKIP = {"rlm", "mcp", "bash", "asyncio", "In", "Out", "get_ipython", "exit", "quit", "open"}+# IPython-injected names that may appear in a snapshot payload; never restored.+_RESTORE_SKIP = {"In", "Out", "get_ipython"}++_protocol_fd: int = -1+_write_lock = threading.Lock()+_loop: asyncio.AbstractEventLoop | None = None+_serve_task: asyncio.Task[Any] | None = None+# Attribution rides task context: asyncio tasks copy it at creation, so a+# detached task spawned by a cell keeps writing under that cell's id after+# the cell finishes. Threads start with a fresh context and emit id null.+_current_cell: contextvars.ContextVar[str | None] = contextvars.ContextVar("_current_cell", default=None)+_active: dict[str, Any] = {"task": None, "rid": None, "interrupted": False}+_cell_counter = 0+_pending_host: dict[str, "asyncio.Future[dict[str, Any]]"] = {}+# Set on the loop thread once stdin hits EOF or a shutdown request arrives; no+# host reply can arrive after that, so waiting (and future) host_request calls fail.+_host_closed = False++# Interrupt bookkeeping shared between the reader thread and the loop thread.+_interrupt_lock = threading.Lock()+_inflight: set[str] = set()+_pending_interrupts: dict[str, Any] = {"ids": set(), "any": False}+_sigint_target: str | None = None+_finishing_rid: str | None = None+_handoff_interrupted = False+++def _send(event: dict[str, Any]) -> None:+ """Write one protocol frame; the locked single write keeps frames atomic."""+ data = (json.dumps(event, separators=(",", ":")) + "\n").encode()+ with _write_lock:+ view = memoryview(data)+ try:+ while view:+ view = view[os.write(_protocol_fd, view) :]+ except OSError:+ pass+++def emit(data: dict[str, Any]) -> None:+ """Ship one display event carrying a dict of MIME type -> JSON payload.++ Thread-safe; the event is tagged with the cell running at call time.+ """+ if not isinstance(data, dict) or not data or not all(isinstance(k, str) for k in data):+ raise TypeError("emit() requires a non-empty dict keyed by MIME type strings")+ # Strict-dumps validation: default allow_nan=True would let NaN/Infinity+ # serialize as non-JSON text and tear the host's protocol framing (a+ # non-serializable value already raises in _send before any bytes are+ # written, so NaN is the only corruption vector). Payloads are small, so+ # the throwaway serialization here is cheap; _send re-serializes.+ json.dumps(data, allow_nan=False)+ _send({"event": "display", "id": _current_cell.get(), "data": data})+++def is_active() -> bool:+ """True when this process serves the repl protocol (not merely imported)."""+ return _protocol_fd >= 0+++async def host_request(data: dict[str, Any]) -> dict[str, Any]:+ """Send one typed request to the host and await its raw reply dict."""+ if _loop is None:+ raise RuntimeError("repl runtime is not serving")+ if _host_closed:+ raise RuntimeError("host connection closed; host_request cannot be answered")+ rid = uuid.uuid4().hex+ future: asyncio.Future[dict[str, Any]] = _loop.create_future()+ _pending_host[rid] = future+ try:+ _send({"event": "host_request", "id": rid, "data": data})+ return await future+ finally:+ _pending_host.pop(rid, None)+++def _fail_pending_host_requests() -> None:+ """Loop-thread half of teardown: no host reply can arrive anymore, so every+ awaiting cell must unblock or the queued shutdown would never be served."""+ global _host_closed+ _host_closed = True+ for future in _pending_host.values():+ if not future.done():+ future.set_exception(RuntimeError("host connection closed; host_request cannot be answered"))+++def _resolve_host_reply(rid: str, data: dict[str, Any]) -> None:+ """Reader-thread half of the host bridge; late/unknown replies are dropped."""+ assert _loop is not None++ def deliver() -> None:+ future = _pending_host.get(rid)+ if future is not None and not future.done():+ future.set_result(data)++ _loop.call_soon_threadsafe(deliver)+++class _Pump:+ """Reads one captured-output pipe and ships its bytes as stream events."""++ def __init__(self, read_fd: int, write_fd: int, stream: str) -> None:+ self._read_fd = read_fd+ # Private write end: a cell closing/reclaiming fd 1/2 cannot hijack drain tokens.+ self._token_fd = os.dup(write_fd)+ self._stream = stream+ self._decoder = codecs.getincrementaldecoder("utf-8")("replace")+ self._lock = threading.Lock()+ self._watch: tuple[bytes, threading.Event] | None = None+ self._buf = b""+ self._thread = threading.Thread(target=self._run, daemon=True)+ self._thread.start()++ def drain(self) -> None:+ """Block until every byte written to the fd so far has been shipped."""+ token = b"\xff<drain:" + uuid.uuid4().hex.encode() + b">\xff"+ seen = threading.Event()+ with self._lock:+ self._watch = (token, seen)+ try:+ os.write(self._token_fd, token)+ # Backstop only: a dead pump (read end closed under it) can never set seen.+ while not seen.wait(0.1):+ if not self._thread.is_alive():+ return+ except OSError:+ return+ finally:+ with self._lock:+ self._watch = None++ def _run(self) -> None:+ while True:+ try:+ chunk = os.read(self._read_fd, 65536)+ except OSError:+ break+ if not chunk:+ break+ self._feed(chunk)++ def _feed(self, chunk: bytes) -> None:+ data = self._buf + chunk+ self._buf = b""+ with self._lock:+ watch = self._watch+ if watch is None:+ self._emit(data)+ return+ token, seen = watch+ while True:+ i = data.find(token)+ if i == -1:+ break+ self._emit(data[:i])+ self._finish_decode()+ seen.set()+ data = data[i + len(token) :]+ # Hold back a tail that could be the start of a token split across reads.+ hold = 0+ for k in range(min(len(data), len(token) - 1), 0, -1):+ if data.endswith(token[:k]):+ hold = k+ break+ if hold:+ self._buf = data[len(data) - hold :]+ data = data[: len(data) - hold]+ self._emit(data)++ def _emit(self, data: bytes) -> None:+ if not data:+ return+ text = self._decoder.decode(data)+ if text:+ # Raw fd bytes have no provable owner (os.write, C extensions,+ # subprocesses, threads from earlier cells): never credit a cell.+ _send({"event": self._stream, "id": None, "text": text})++ def _finish_decode(self) -> None:+ text = self._decoder.decode(b"", final=True)+ self._decoder = codecs.getincrementaldecoder("utf-8")("replace")+ if text:+ _send({"event": self._stream, "id": None, "text": text})+++class _TaggedBuffer(io.RawIOBase):+ """Binary proxy for _TaggedWriter.buffer: bytes go to the raw fd channel.++ Byte ownership cannot be proven at this layer, so buffer writes ride the+ captured pipe and surface as id:null stream events (drained before done+ like any other raw fd write).+ """++ def __init__(self, fallback_fd: int) -> None:+ self._fallback_fd = fallback_fd++ def write(self, data: Any) -> int:+ # memoryview (unlike bytes()) rejects int, matching a real buffer's TypeError.+ view = memoryview(data).cast("B")+ total = len(view)+ # Pipe writes can be short for payloads above the pipe capacity.+ while view:+ view = view[os.write(self._fallback_fd, view) :]+ return total++ def flush(self) -> None:+ pass++ def fileno(self) -> int:+ return self._fallback_fd++ def writable(self) -> bool:+ return True+++class _TaggedWriter(io.TextIOBase):+ """sys.stdout/sys.stderr replacement tagging writes with the writer's cell id.++ Python-level writes carry write-time provenance from the _current_cell+ contextvar (asyncio tasks inherit the spawning cell's id; user threads see+ None) and ship straight to the protocol, bypassing the fd pipe. fileno()+ and .buffer expose the captured pipe so subprocesses, C-level writers, and+ sys.stdout.buffer.write() keep working through the raw channel+ (null-attributed).+ """++ def __init__(self, stream: str, fallback_fd: int) -> None:+ self._stream = stream+ self._fallback_fd = fallback_fd+ self._buffer = _TaggedBuffer(fallback_fd)++ def write(self, text: str) -> int:+ if not isinstance(text, str):+ raise TypeError(f"write() argument must be str, not {type(text).__name__}")+ if text:+ _send({"event": self._stream, "id": _current_cell.get(), "text": text})+ return len(text)++ def flush(self) -> None:+ pass++ def fileno(self) -> int:+ return self._fallback_fd++ def writable(self) -> bool:+ return True++ @property+ def buffer(self) -> _TaggedBuffer:+ return self._buffer++ @property+ def encoding(self) -> str:+ return "utf-8"++ @property+ def errors(self) -> str:+ return "replace"+++def _consume_task_exception(task: asyncio.Task[Any]) -> None:+ """Retrieve a killed task's exception so no never-retrieved noise is logged."""+ if not task.cancelled():+ task.exception()+++def _sigint_handler(signum: int, frame: types.FrameType | None) -> None:+ global _handoff_interrupted+ task = _active["task"]+ # No lock (the main thread may hold it): the rid equality revalidates the+ # target so a SIGINT delayed past its request's finish cannot hit a later cell.+ if task is None or task.done() or _active["rid"] != _sigint_target:+ if _sigint_target is not None and _sigint_target == _active["rid"]:+ # Handoff: the task is done but _run_guarded's finally has not run+ # yet, so the main thread may be inside loop internals where raising+ # would kill the serve loop. Record it; the finishing phase consumes it.+ _handoff_interrupted = True+ return+ # Post-run repr/drain is synchronous main-thread work: raise into it.+ # The equality revalidation drops a SIGINT delayed past the done send.+ if _sigint_target is not None and _sigint_target == _finishing_rid:+ raise KeyboardInterrupt+ return+ _active["interrupted"] = True+ # Handler runs in the main (loop) thread: current_task is whose step the signal interrupted.+ running = asyncio.current_task(_loop) if _loop is not None else None+ if running is task:+ # The active request's own step (sync bytecode or an EINTR-woken syscall): raise into it.+ raise KeyboardInterrupt+ # Loop idle in select() or another task mid-step: cancel the active task (same thread, safe).+ task.cancel()+ if running is not None and running is not _serve_task:+ # A background task blocked in sync code occupies the only thread and would keep the+ # cancel from ever running: raise into it to unwind its step; it dies with the KI.+ running.add_done_callback(_consume_task_exception)+ raise KeyboardInterrupt+++def _request_interrupt(target: str | None) -> None:+ """Deliver an interrupt now, or park it for the request it targets.++ Runs on the reader thread. Without a target id the interrupt applies to+ the running request, else to the next queued one; with a target id it+ applies to that request only. A request finishing its post-run repr/drain+ is still interrupted (never parked: parking would hit the NEXT request).+ Interrupts for finished or unknown requests are dropped.+ """+ global _sigint_target+ with _interrupt_lock:+ task = _active["task"]+ rid = _active["rid"]+ if rid is not None and (target is None or target == rid):+ # Active, or in the done-task handoff before _run_guarded's finally:+ # either way the rid still owns the interrupt (parking here would+ # leak it onto the next request); the handler decides delivery.+ _sigint_target = rid+ elif _finishing_rid is not None and (target is None or target == _finishing_rid):+ _sigint_target = _finishing_rid+ elif target is not None:+ if target in _inflight:+ _pending_interrupts["ids"].add(target)+ return+ elif _inflight:+ _pending_interrupts["any"] = True+ return+ else:+ return+ # SIGINT must land on the main thread, where cells execute. Windows has no+ # signal.pthread_kill: fall back to cancelling the active task on the loop+ # (sync-blocked cells and the finishing repr/drain cannot be broken there;+ # best-effort parity).+ if hasattr(signal, "pthread_kill"):+ signal.pthread_kill(threading.main_thread().ident, signal.SIGINT)+ if _loop is not None:+ # Wake the selector so a cancel scheduled by the handler runs promptly.+ _loop.call_soon_threadsafe(lambda: None)+ return+ if _loop is not None:++ def cancel_active() -> None:+ current = _active["task"]+ if current is task and current is not None and not current.done():+ _active["interrupted"] = True+ current.cancel()++ _loop.call_soon_threadsafe(cancel_active)+++def _consume_pending_interrupt(rid: str) -> bool:+ """Check-and-clear any interrupt parked for this request."""+ pending = _pending_interrupts["any"] or rid in _pending_interrupts["ids"]+ _pending_interrupts["any"] = False+ _pending_interrupts["ids"].discard(rid)+ return pending+++def _consume_handoff_interrupt() -> bool:+ """Check-and-clear an interrupt that landed in the done-task handoff."""+ global _handoff_interrupted+ with _interrupt_lock:+ pending = _handoff_interrupted+ _handoff_interrupted = False+ return pending+++def _finish_locked(rid: str) -> None:+ """Drop a finished request; a parked untargeted interrupt survives while others are inflight."""+ global _finishing_rid, _handoff_interrupted, _sigint_target+ if _finishing_rid == rid:+ # An unconsumed handoff interrupt dies with its request (state requests+ # have no cancellable post-run work); it must never hit the next request.+ _finishing_rid = None+ _handoff_interrupted = False+ if _sigint_target == rid:+ # The target dies with its request: a later request reusing this id must+ # not match a stale target when a delayed/external SIGINT arrives.+ _sigint_target = None+ _inflight.discard(rid)+ _pending_interrupts["ids"].discard(rid)+ if not _inflight:+ _pending_interrupts["any"] = False+++def _finish_request(rid: str) -> None:+ with _interrupt_lock:+ _finish_locked(rid)+++_RUNTIME_FILE = __file__+++def _cell_stack(stack: traceback.StackSummary) -> traceback.StackSummary | None:+ """Frames from the first cell frame on, minus runtime-internal frames.++ Returns None when no cell frame exists (e.g. a compile-time SyntaxError).+ """+ start = next((i for i, f in enumerate(stack) if f.filename.startswith("<cell-")), None)+ if start is None:+ return None+ return traceback.StackSummary.from_list([f for f in stack[start:] if f.filename != _RUNTIME_FILE])+++def _safe_str(exc: BaseException) -> str:+ try:+ return str(exc)+ except BaseException: # noqa: BLE001 - a broken __str__ must not kill the runtime+ return "<exception str() failed>"+++def _error_event(cell_id: str, exc: BaseException) -> dict[str, Any]:+ # No cell frame (e.g. SyntaxError): exception-only keeps filename, source, and caret.+ te = traceback.TracebackException.from_exception(exc)+ stack = _cell_stack(te.stack)+ if stack is None:+ lines = traceback.format_exception_only(type(exc), exc)+ else:+ te.stack = stack+ lines = list(te.format())+ return {+ "event": "error",+ "id": cell_id,+ "ename": type(exc).__name__,+ "evalue": _safe_str(exc),+ "traceback": lines,+ }+++def _interrupt_event(cell_id: str, exc: BaseException) -> dict[str, Any]:+ """Report a cancelled await-suspended cell as a KeyboardInterrupt."""+ stack = _cell_stack(traceback.extract_tb(exc.__traceback__))+ lines = []+ if stack:+ lines = ["Traceback (most recent call last):\n"]+ lines.extend(stack.format())+ lines.append("KeyboardInterrupt\n")+ return {"event": "error", "id": cell_id, "ename": "KeyboardInterrupt", "evalue": "", "traceback": lines}+++def _compile_cell(code: str, filename: str) -> tuple[list[types.CodeType], bool]:+ """Compile a cell; a trailing expression compiles separately in eval mode."""+ linecache.cache[filename] = (len(code), None, code.splitlines(keepends=True), filename)+ tree = ast.parse(code, filename)+ trailing: ast.Expression | None = None+ if tree.body and isinstance(tree.body[-1], ast.Expr):+ trailing = ast.Expression(tree.body.pop().value)+ flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT+ codes: list[types.CodeType] = []+ if tree.body:+ codes.append(compile(tree, filename, "exec", flags=flags, dont_inherit=True))+ if trailing is not None:+ codes.append(compile(trailing, filename, "eval", flags=flags, dont_inherit=True))+ return codes, trailing is not None+++async def _run_codes(codes: list[types.CodeType], ns: dict[str, Any]) -> Any:+ value: Any = None+ for code_obj in codes:+ value = eval(code_obj, ns) # noqa: S307 - executing the model's cell is the runtime's job+ if code_obj.co_flags & inspect.CO_COROUTINE:+ value = await value+ return value+++async def _run_guarded(task: asyncio.Task[Any], rid: str) -> tuple[str, Any, dict[str, Any] | None]:+ """Await a request task; returns (status, value, error event or None)."""+ with _interrupt_lock:+ _active["interrupted"] = False+ _active["rid"] = rid+ _active["task"] = task+ if _consume_pending_interrupt(rid):+ # Interrupt parked before activation: cancel before the first step.+ _active["interrupted"] = True+ task.cancel()+ try:+ value = await task+ return "ok", value, None+ except asyncio.CancelledError as exc:+ if _active["interrupted"]:+ return "error", None, _interrupt_event(rid, exc)+ return "error", None, _error_event(rid, exc)+ except BaseException as exc: # noqa: BLE001 - every cell failure becomes an error event+ return "error", None, _error_event(rid, exc)+ finally:+ with _interrupt_lock:+ global _finishing_rid+ # The rid stays inflight and interrupt-targetable through the+ # post-run repr/drain; the handler closes the window via _finish_request.+ # Set before clearing _active: the lock-free handler must always see+ # the rid in one of the two slots, never a torn in-between state.+ _finishing_rid = rid+ _active["task"] = None+ _active["rid"] = None+++async def _handle_execute(req: dict[str, Any], ns: dict[str, Any]) -> None:+ global _cell_counter+ cell_id = req["id"]+ _cell_counter += 1+ filename = f"<cell-{_cell_counter}>"+ # The cell task (created below) copies this context, so writes made from+ # the cell and from asyncio tasks it spawns carry this cell's id.+ token = _current_cell.set(cell_id)+ try:+ codes, has_trailing = _compile_cell(req["code"], filename)+ assert _loop is not None+ task = _loop.create_task(_run_codes(codes, ns))+ status, value, error = await _run_guarded(task, cell_id)+ result_text: str | None = None+ try:+ if _consume_handoff_interrupt() and status == "ok":+ # SIGINT landed between the task's completion and the finishing+ # phase: it targeted this request, so cancel its remaining work.+ status, error = "error", _error_event(cell_id, KeyboardInterrupt())+ if status == "ok" and has_trailing and value is not None:+ try:+ ns["_"] = value+ result_text = repr(value)+ except BaseException as exc: # noqa: BLE001 - a broken __repr__ is a cell error+ status, error = "error", _error_event(cell_id, exc)+ _drain_output()+ finally:+ # Close the interrupt window before the protocol sends so a+ # handler-raised KeyboardInterrupt can never tear a frame mid-_send.+ _finish_request(cell_id)+ if result_text is not None:+ _send({"event": "result", "id": cell_id, "text": result_text})+ if error is not None:+ _send(error)+ _send({"event": "done", "id": cell_id, "status": status})+ finally:+ _current_cell.reset(token)+++def _drain_output() -> None:+ # Per-stream, and ValueError too: a cell may close sys.stdout/sys.stderr, and+ # flushing a closed file raises ValueError, or rebind them to a flush-less+ # object (AttributeError); neither may kill the serve loop nor skip flushing+ # the other stream.+ for stream in (sys.stdout, sys.stderr):+ try:+ stream.flush()+ except (OSError, ValueError, AttributeError):+ pass+ _pump_out.drain()+ _pump_err.drain()+++class _SnapshotSizeLimitExceeded(Exception):+ pass+++class _SnapshotBuffer:+ def __init__(self, limit: int) -> None:+ import io++ self._buf = io.BytesIO()+ self._limit = limit++ def write(self, chunk: bytes) -> int:+ if self._buf.tell() + len(chunk) > self._limit:+ raise _SnapshotSizeLimitExceeded()+ return self._buf.write(chunk)++ def getvalue(self) -> bytes:+ return self._buf.getvalue()+++def _snapshot_state(+ ns: dict[str, Any],+ path: str,+ manifest_path: str,+ max_bytes: int,+ max_variable_bytes: int,+ prune_oversized: bool,+ committed: list[dict[str, Any]] | None = None,+) -> dict[str, Any]:+ import datetime++ try:+ import dill+ except Exception as err: # noqa: BLE001 - dill is provisioned by the host, not a hard dep+ return {"error": f"dill unavailable: {err}"}+ dill.settings["recurse"] = True++ payload: dict[str, bytes] = {}+ skipped: list[dict[str, str]] = []+ oversized: list[str] = []+ total = 0+ missing = object()+ for name in list(ns.keys()):+ if name.startswith("_") or name in _ALWAYS_SKIP:+ continue+ value = ns.get(name, missing)+ if value is missing:+ # A background thread deleted the name after the key listing.+ skipped.append({"name": name, "reason": "deleted during snapshot"})+ continue+ remaining = max_bytes - total+ limit = max_variable_bytes if prune_oversized else min(max_variable_bytes, remaining)+ buffer = _SnapshotBuffer(limit)+ try:+ dill.dump(value, buffer)+ blob = buffer.getvalue()+ except _SnapshotSizeLimitExceeded:+ if not prune_oversized and remaining < max_variable_bytes:+ skipped.append({"name": name, "reason": "exceeds aggregate snapshot size cap"})+ else:+ skipped.append({"name": name, "reason": "exceeds per-variable snapshot size cap"})+ oversized.append(name)+ continue+ except Exception as err: # noqa: BLE001 - one unpicklable name must not abort the snapshot+ skipped.append({"name": name, "reason": f"{type(err).__name__}: {_safe_str(err)[:200]}"})+ continue+ if total + len(blob) > max_bytes:+ skipped.append({"name": name, "reason": "exceeds aggregate snapshot size cap"})+ continue+ payload[name] = blob+ total += len(blob)++ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)+ temps: list[str] = []++ def stage_temp(target: str, mode: str):+ # Unique same-directory temps: a fixed '.tmp' name could alias the other+ # final path (clobbering it) or collide with a concurrent snapshot.+ fd, name = tempfile.mkstemp(+ dir=os.path.dirname(target) or ".", prefix=os.path.basename(target) + ".", suffix=".tmp"+ )+ temps.append(name)+ try:+ return os.fdopen(fd, mode), name+ except BaseException:+ os.close(fd) # fdopen never took ownership: the raw fd would leak+ raise++ def discard_temps() -> None:+ for stale in temps:+ try:+ os.remove(stale)+ except OSError:+ pass++ # Stage both temps before replacing anything: any failure up to the first+ # replace leaves the previous payload+manifest pair fully intact.+ stage = "write"+ parked: list[int] = []+ handler_installed = False+ previous = None+ try:+ try:+ def serialize(candidate: dict[str, bytes]) -> bytes | None:+ buffer = _SnapshotBuffer(max_bytes)+ try:+ dill.dump(candidate, buffer)+ except _SnapshotSizeLimitExceeded:+ return None+ return buffer.getvalue()++ serialized_payload = serialize(payload)+ if serialized_payload is None:+ items = list(payload.items())+ serialized_payload = serialize({})+ if serialized_payload is None:+ return {"error": "write failed: snapshot exceeds aggregate snapshot size cap"}+ # Keep the largest insertion-order prefix whose complete pickle fits.+ # Prefix pickle size is monotonic because each prefix only adds a string key and bytes value.+ low, high = 0, len(items) - 1+ while low < high:+ mid = (low + high + 1) // 2+ candidate = serialize(dict(items[:mid]))+ if candidate is None:+ high = mid - 1+ else:+ low = mid+ serialized_payload = candidate+ for name, _ in items[low:]:+ skipped.append({"name": name, "reason": "exceeds aggregate snapshot size cap"})+ payload = dict(items[:low])++ fh, tmp = stage_temp(path, "wb")+ with fh:+ fh.write(serialized_payload)+ bytes_written = len(serialized_payload)+ saved = sorted(payload.keys())+ pruned = sorted(name for name in oversized if name in ns) if prune_oversized else []+ manifest = {+ "version": 1,+ "savedNames": saved,+ "skipped": skipped,+ "pruned": pruned,+ "bytes": bytes_written,+ "pythonVersion": sys.version.split()[0],+ "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),+ }+ stage = "manifest write"+ fh, manifest_tmp = stage_temp(manifest_path, "w")+ with fh:+ json.dump(manifest, fh)+ except BaseException as err: # noqa: BLE001 - Exception -> error dict, rest propagates+ if not isinstance(err, Exception):+ raise # e.g. KeyboardInterrupt: clean up (outer finally), then propagate+ return {"error": f"{stage} failed: {err}"}++ # A SIGINT-raised KeyboardInterrupt anywhere from the first commit through the+ # last cleanup removal would desync payload/manifest/namespace or misreport a+ # committed snapshot: park SIGINT until the end; it is consumed, see below.+ previous = signal.signal(signal.SIGINT, lambda signum, frame: parked.append(signum))+ handler_installed = True+ try:+ os.replace(tmp, path)+ except OSError as err:+ return {"error": f"write failed: {err}"}+ try:+ os.replace(manifest_tmp, manifest_path)+ except OSError as err:+ # Fail before the prune deletions so a bad manifest path never destroys state.+ return {"error": f"manifest write failed: {err}"}+ for name in pruned:+ ns.pop(name, None)+ result = {"saved": saved, "skipped": skipped, "pruned": pruned, "bytes": bytes_written}+ # Publish while still parked: a later KeyboardInterrupt into this task finds the committed result (see _handle_state).+ if committed is not None:+ committed.append(result)+ finally:+ # The one guaranteed cleanup point (unique owned names: after a successful+ # commit the renamed temps no longer exist, so this is a no-op). It runs with+ # SIGINT still parked; the nested finally makes the restore the guaranteed+ # last action even when cleanup itself fails.+ try:+ discard_temps()+ finally:+ if handler_installed:+ signal.signal(signal.SIGINT, previous)+ # The parked SIGINT is consumed, not re-raised: with the manifest committed and+ # the namespace pruned, the destructive snapshot has succeeded, and re-raising+ # would misreport it as failed and risk the host discarding the only copy of+ # the pruned variables. The interrupt targeted this now-complete request.+ return result+++def _restore_state(+ ns: dict[str, Any], path: str, committed: list[dict[str, Any]] | None = None+) -> dict[str, Any]:+ if not os.path.exists(path):+ return {"restored": [], "failed": [], "reason": "snapshot not found"}+ try:+ import dill+ except Exception as err: # noqa: BLE001+ return {"error": f"dill unavailable: {err}"}+ try:+ with open(path, "rb") as fh:+ payload = dill.load(fh)+ except Exception as err: # noqa: BLE001 - a corrupt snapshot yields an empty restore+ return {"error": f"load failed: {_safe_str(err)}"}+ if not isinstance(payload, dict):+ return {"error": "corrupt snapshot: not a dict"}++ staged: dict[str, Any] = {}+ failed: list[dict[str, str]] = []+ for name, blob in payload.items():+ if name in _RESTORE_SKIP:+ continue+ try:+ staged[name] = dill.loads(blob)+ except Exception as err: # noqa: BLE001 - revive every other name regardless+ failed.append({"name": name, "reason": f"{type(err).__name__}: {_safe_str(err)[:200]}"})+ result = {"restored": sorted(staged), "failed": failed}+ # Park SIGINT across the whole apply so it is all-or-nothing; the parked interrupt is consumed by the commit (as in snapshot).+ previous = signal.signal(signal.SIGINT, lambda signum, frame: None)+ try:+ for name, value in staged.items():+ ns[name] = value+ # Publish while still parked: a later KeyboardInterrupt into this task finds the committed result (see _handle_state).+ if committed is not None:+ committed.append(result)+ finally:+ signal.signal(signal.SIGINT, previous)+ return result+++async def _handle_state(req: dict[str, Any], ns: dict[str, Any]) -> None:+ """Run snapshot/restore as an interruptible task and reply in the done event."""+ rid = req["id"]+ committed: list[dict[str, Any]] = []++ async def run() -> dict[str, Any]:+ if req["type"] == "snapshot":+ prune = req.get("prune_oversized", False)+ if not isinstance(prune, bool):+ return {"error": "prune_oversized must be a boolean"}+ for field in ("max_bytes", "max_variable_bytes"):+ # Any present value must be a non-negative int; a JSON null is not a valid way to ask+ # for the default, and a negative cap would prune every user variable from ns.+ if field in req and (+ isinstance(req[field], bool) or not isinstance(req[field], int) or req[field] < 0+ ):+ return {"error": f"{field} must be a non-negative integer"}+ # realpath resolves symlinks, so aliased paths cannot silently clobber the payload.+ if os.path.realpath(req["path"]) == os.path.realpath(req["manifest_path"]):+ return {"error": "path and manifest_path must differ"}+ return _snapshot_state(+ ns,+ req["path"],+ req["manifest_path"],+ req.get("max_bytes", DEFAULT_SNAPSHOT_MAX_BYTES),+ req.get("max_variable_bytes", DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES),+ prune,+ committed,+ )+ return _restore_state(ns, req["path"], committed)++ assert _loop is not None+ task = _loop.create_task(run())+ outcome: tuple[str, Any, dict[str, Any] | None] | None = None+ try:+ outcome = await _run_guarded(task, rid)+ _finish_request(rid) # no post-run repr/drain: close the interrupt window now+ except KeyboardInterrupt:+ # A finishing-targeted SIGINT can raise anywhere between _run_guarded's+ # finally publishing _finishing_rid and _finish_request clearing it; the+ # handler only raises once _finishing_rid is set, so the task is already+ # complete (destructively so for a pruning snapshot). Consume the+ # interrupt and report the task's real outcome; escaping to the backstop+ # would misreport a committed snapshot as failed.+ _finish_request(rid)+ if outcome is None:+ # The KeyboardInterrupt pre-empted _run_guarded's return: recover+ # the completed task's outcome with _run_guarded's failure mapping.+ try:+ outcome = ("ok", task.result(), None)+ except asyncio.CancelledError as exc:+ event = _interrupt_event(rid, exc) if _active["interrupted"] else _error_event(rid, exc)+ outcome = ("error", None, event)+ except BaseException as exc: # noqa: BLE001 - every request failure becomes an error event+ outcome = ("error", None, _error_event(rid, exc))+ status, result, error = outcome+ if (+ committed+ and _active["interrupted"]+ and error is not None+ and error.get("ename") == "KeyboardInterrupt"+ ):+ # Recover only a protocol interrupt that landed after the commit; a user KeyboardInterrupt keeps interrupted reporting.+ status, result, error = "ok", committed[0], None+ if status != "ok":+ reason = "interrupted" if error and error.get("ename") == "KeyboardInterrupt" else (+ f"{error.get('ename')}: {error.get('evalue')}" if error else "failed"+ )+ _send({"event": "done", "id": rid, "status": "error", "reason": reason})+ return+ if "error" in result:+ _send({"event": "done", "id": rid, "status": "error", "reason": result["error"]})+ return+ _send({"event": "done", "id": rid, "status": "ok", **result})+++def _list_names(ns: dict[str, Any]) -> list[str]:+ """User-defined top-level names, filtered like the snapshot."""+ # Non-string keys (globals()[1] = 1) are not user-listable names.+ return sorted(+ name for name in ns if isinstance(name, str) and not name.startswith("_") and name not in _ALWAYS_SKIP+ )+++async def _handle_list_names(req: dict[str, Any], ns: dict[str, Any]) -> None:+ _send({"event": "done", "id": req["id"], "status": "ok", "names": _list_names(ns)})+++async def _handle_request(+ handler: Callable[[dict[str, Any], dict[str, Any]], Awaitable[None]],+ req: dict[str, Any],+ ns: dict[str, Any],+) -> None:+ # Backstop: one broken request (e.g. RecursionError in compile) fails alone, never the serve loop.+ try:+ await handler(req, ns)+ except BaseException as exc: # noqa: BLE001 - any per-request failure becomes error+done+ rid = req["id"]+ with _interrupt_lock:+ # Only a still-inflight request (never reached _run_guarded, e.g. compile+ # failure) owns a parked interrupt; after _run_guarded finished it, a parked+ # "any" belongs to the next request and must survive.+ if rid in _inflight:+ _consume_pending_interrupt(rid)+ _finish_locked(rid)+ _send(_error_event(rid, exc))+ _send({"event": "done", "id": rid, "status": "error"})+++async def _serve(queue: asyncio.Queue[dict[str, Any]], ns: dict[str, Any]) -> None:+ while True:+ req = await queue.get()+ # A cell (or a snapshot-restored prior handler) may have rebound SIGINT; the+ # protocol handler must own it before each request. Mid-cell rebinds remain+ # that cell's own problem for that cell only.+ signal.signal(signal.SIGINT, _sigint_handler)+ rtype = req.get("type")+ if rtype == "shutdown":+ rid = req.get("id")+ # MCP children must close before the loop dies; close() is internally bounded under the host's 5s deadline.+ mcp_mod = sys.modules.get("rlm.mcp")+ if mcp_mod is not None:+ try:+ await mcp_mod.close()+ except BaseException as exc:+ print(f"MCP shutdown failed: {type(exc).__name__}: {exc}", file=sys.stderr)+ # Kill live bash children now; atexit would wait on parked executor threads.+ _kill_live_handles()+ if isinstance(rid, str):+ _send({"event": "done", "id": rid, "status": "ok"})+ return+ if rtype == "execute":+ await _handle_request(_handle_execute, req, ns)+ elif rtype in ("snapshot", "restore"):+ await _handle_request(_handle_state, req, ns)+ elif rtype == "list_names":+ await _handle_request(_handle_list_names, req, ns)+++_REQUIRED_FIELDS = {+ "execute": ("id", "code"),+ "snapshot": ("id", "path", "manifest_path"),+ "restore": ("id", "path"),+ "list_names": ("id",),+ "shutdown": (),+}+++def _protocol_error(message: str) -> None:+ _send({"event": "error", "id": None, "ename": "ProtocolError", "evalue": message, "traceback": []})+++def _handle_request_line(raw: bytes, queue: asyncio.Queue[dict[str, Any]]) -> None:+ assert _loop is not None+ req = json.loads(raw)+ if not isinstance(req, dict):+ raise ValueError("request is not a JSON object")+ rtype = req.get("type")+ if rtype == "interrupt":+ if "id" in req and not isinstance(req["id"], str):+ _protocol_error("interrupt request id must be a string")+ return+ _request_interrupt(req.get("id"))+ return+ if rtype == "host_reply":+ # Bypass the FIFO queue: the awaiting cell IS the in-flight+ # execute, so a queued reply would deadlock behind it.+ rid = req.get("id")+ data = req.get("data")+ if isinstance(rid, str) and isinstance(data, dict):+ _resolve_host_reply(rid, data)+ else:+ _protocol_error("host_reply request needs string id and dict data")+ return+ if not isinstance(rtype, str) or rtype not in _REQUIRED_FIELDS:+ _protocol_error(f"unknown request type: {rtype!r}")+ return+ missing = [f for f in _REQUIRED_FIELDS[rtype] if not isinstance(req.get(f), str)]+ if missing:+ _protocol_error(f"{rtype} request needs string fields: {', '.join(missing)}")+ return+ if rtype in ("execute", "snapshot", "restore"):+ with _interrupt_lock:+ # A reused in-flight id would corrupt interrupt/finish bookkeeping.+ duplicate = req["id"] in _inflight+ if not duplicate:+ _inflight.add(req["id"])+ # The protocol write can block on backpressure: never send under the lock.+ if duplicate:+ _protocol_error(f"duplicate in-flight request id: {req['id']!r}")+ return+ if rtype == "shutdown":+ # No host reply follows a shutdown; a cell awaiting host_request+ # must fail now or it would block _serve from ever consuming this.+ _loop.call_soon_threadsafe(_fail_pending_host_requests)+ _loop.call_soon_threadsafe(queue.put_nowait, req)+++def _read_requests(stdin_fd: int, queue: asyncio.Queue[dict[str, Any]]) -> None:+ assert _loop is not None+ with os.fdopen(stdin_fd, "rb") as stream:+ for raw in stream:+ raw = raw.strip()+ if not raw:+ continue+ try:+ # The whole per-line handling sits inside the backstop: hostile+ # input (RecursionError from pathological nesting, unhashable+ # field types, ...) must never kill the reader thread.+ _handle_request_line(raw, queue)+ except BaseException as err: # noqa: BLE001+ _protocol_error(f"{type(err).__name__}: {_safe_str(err)}")+ # Host closed stdin: shut the runtime down.+ _loop.call_soon_threadsafe(_fail_pending_host_requests)+ _loop.call_soon_threadsafe(queue.put_nowait, {"type": "shutdown"})+++def _resolve_owner_pid() -> int:+ raw = os.environ.get("PRIME_AGENT_KERNEL_OWNER_PID", "")+ try:+ owner = int(raw)+ except ValueError:+ owner = 0+ return owner if owner > 0 else os.getppid()+++def _owner_alive_posix(owner: int, initial_ppid: int) -> bool:+ # Reparenting is the race-free parent-death signal when the owner is the+ # parent; the kill-0 probe covers an env-designated non-parent owner.+ if initial_ppid == owner and os.getppid() != initial_ppid:+ return False+ try:+ os.kill(owner, 0)+ except ProcessLookupError:+ return False+ except OSError:+ pass # EPERM etc.: alive but unprobeable+ return True+++def _wait_owner_windows(owner: int) -> None:+ # Blocks until the owner exits. os.kill(pid, 0) on Windows TERMINATES the+ # target, so a SYNCHRONIZE handle wait is the only sound probe.+ from ctypes import wintypes++ SYNCHRONIZE = 0x00100000+ INFINITE = 0xFFFFFFFF+ k32 = ctypes.WinDLL("kernel32", use_last_error=True)+ k32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]+ k32.OpenProcess.restype = wintypes.HANDLE+ k32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]+ k32.WaitForSingleObject.restype = wintypes.DWORD+ k32.CloseHandle.argtypes = [wintypes.HANDLE]+ k32.CloseHandle.restype = wintypes.BOOL+ handle = k32.OpenProcess(SYNCHRONIZE, False, owner)+ if not handle:+ return # already gone (or unprobeable): exit rather than run ownerless+ try:+ k32.WaitForSingleObject(handle, INFINITE)+ finally:+ k32.CloseHandle(handle)+++def _owner_watchdog(owner: int, initial_ppid: int) -> None:+ if os.name == "nt":+ _wait_owner_windows(owner)+ else:+ while _owner_alive_posix(owner, initial_ppid):+ time.sleep(1.0)+ # Event-loop-independent by design: a synchronous cell monopolizes the+ # loop, so the queued EOF shutdown can never run; hard-exit from here.+ try:+ _kill_live_handles()+ except BaseException: # noqa: BLE001+ pass+ os._exit(1)+++def _start_owner_watchdog() -> None:+ threading.Thread(+ target=_owner_watchdog, args=(_resolve_owner_pid(), os.getppid()), daemon=True+ ).start()+++_pump_out: _Pump+_pump_err: _Pump+++def _setup_fds() -> int:+ """Reserve stdout for the protocol; route fds 1/2 through captured pipes."""+ global _protocol_fd, _pump_out, _pump_err+ _protocol_fd = os.dup(1)+ os.set_inheritable(_protocol_fd, False)+ out_r, out_w = os.pipe()+ err_r, err_w = os.pipe()+ os.dup2(out_w, 1)+ os.dup2(err_w, 2)+ os.close(out_w)+ os.close(err_w)+ sys.stdout = _TaggedWriter("stdout", fallback_fd=os.dup(1))+ sys.stderr = _TaggedWriter("stderr", fallback_fd=os.dup(2))+ stdin_fd = os.dup(0)+ devnull = os.open(os.devnull, os.O_RDONLY)+ os.dup2(devnull, 0)+ os.close(devnull)+ sys.stdin = open(os.devnull, "r") # user input() sees EOF, never protocol frames+ _pump_out = _Pump(out_r, 1, "stdout")+ _pump_err = _Pump(err_r, 2, "stderr")+ return stdin_fd+++def main() -> None:+ global _loop, _serve_task+ stdin_fd = _setup_fds()+ _start_owner_watchdog()++ # Alias the executing module so an in-cell `from rlm.repl import emit`+ # binds the live module, not a second copy.+ sys.modules.setdefault("rlm.repl", sys.modules[__name__])+ # A real __main__ module makes dill pickle user functions/classes by value.+ user_module = types.ModuleType("__main__")+ user_module.__dict__["__builtins__"] = __builtins__+ sys.modules["__main__"] = user_module++ _loop = asyncio.new_event_loop()+ asyncio.set_event_loop(_loop)+ queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue()+ signal.signal(signal.SIGINT, _sigint_handler)+ threading.Thread(target=_read_requests, args=(stdin_fd, queue), daemon=True).start()++ _send({"event": "ready", "protocol": PROTOCOL_VERSION, "python": platform.python_version()})++ _serve_task = _loop.create_task(_serve(queue, user_module.__dict__))+ # A KeyboardInterrupt escaping a cell or background task stops+ # run_until_complete; the interrupt is already recorded, so resume serving.+ while not _serve_task.done():+ try:+ _loop.run_until_complete(_serve_task)+ except KeyboardInterrupt:+ continue+ _loop.close()+++if __name__ == "__main__":+ main()diff --git a/prime-agent-runtime/test/test_mcp.py b/prime-agent-runtime/test/test_mcp.pyindex 2ff1999752..a548404979 100644--- a/prime-agent-runtime/test/test_mcp.py+++ b/prime-agent-runtime/test/test_mcp.py@@ -683,42 +683,6 @@ class McpRegistryTest(unittest.TestCase):run(scenario())- def test_shutdown_hook_supports_synchronous_kernel_handler(self):- class Kernel:- def __init__(self):- self._prime_agent_mcp_shutdown = False-- def do_shutdown(self, restart):- return {"status": "ok", "restart": restart}-- kernel = Kernel()- shell = SimpleNamespace(kernel=kernel)-- async def scenario():- with mock.patch.object(mcp, "get_ipython", create=True, return_value=shell):- mcp.install_shutdown_hook()- with mock.patch.object(mcp, "close", mock.AsyncMock()) as close:- self.assertEqual(await kernel.do_shutdown(False), {"status": "ok", "restart": False})- close.assert_awaited_once()-- run(scenario())-- def test_shutdown_hook_runs_kernel_handler_when_mcp_close_fails(self):- original = mock.AsyncMock(return_value={"status": "ok", "restart": False})- kernel = SimpleNamespace(_prime_agent_mcp_shutdown=False, do_shutdown=original)- shell = SimpleNamespace(kernel=kernel)-- async def scenario():- with mock.patch.object(mcp, "get_ipython", create=True, return_value=shell):- mcp.install_shutdown_hook()- with mock.patch.object(mcp, "close", mock.AsyncMock(side_effect=TimeoutError("close deadline"))):- with mock.patch("sys.stderr", new_callable=io.StringIO) as stderr:- self.assertEqual(await kernel.do_shutdown(False), {"status": "ok", "restart": False})- self.assertIn("MCP shutdown failed: TimeoutError: close deadline", stderr.getvalue())- original.assert_awaited_once_with(False)-- run(scenario())-def test_close_waits_for_inflight_startup(self):started = asyncio.Event()release = asyncio.Event()diff --git a/prime-agent-runtime/test/test_repl.py b/prime-agent-runtime/test/test_repl.pynew file mode 100644index 0000000000..ca73371a74--- /dev/null+++ b/prime-agent-runtime/test/test_repl.py@@ -0,0 +1,2011 @@+from __future__ import annotations++import asyncio+import json+import os+import queue+import signal+import subprocess+import sys+import tempfile+import threading+import time+import unittest+from unittest import mock++SRC = os.path.join(os.path.dirname(__file__), "..", "src")++_EOF = object()+++class ReplProcess:+ """Drives one `python -m rlm.repl` subprocess over the JSON-lines protocol."""++ def __init__(self, env: dict[str, str] | None = None) -> None:+ env = {+ **os.environ,+ "PYTHONPATH": SRC + os.pathsep + os.environ.get("PYTHONPATH", ""),+ **(env or {}),+ }+ self.spawned_at = time.monotonic()+ self.proc = subprocess.Popen(+ [sys.executable, "-m", "rlm.repl"],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ text=True,+ env=env,+ )+ self.raw_lines: list[str] = []+ self._lines: queue.Queue[object] = queue.Queue()+ threading.Thread(target=self._read_lines, daemon=True).start()++ def _read_lines(self) -> None:+ assert self.proc.stdout is not None+ try:+ for line in self.proc.stdout:+ self._lines.put(line)+ except ValueError:+ pass # stdout closed by close() while the thread was blocked on it+ self._lines.put(_EOF)++ def read_event(self, timeout: float = 30.0) -> dict:+ try:+ line = self._lines.get(timeout=timeout)+ except queue.Empty:+ raise TimeoutError("timed out waiting for a protocol event") from None+ if line is _EOF:+ raise EOFError("runtime closed its protocol stream")+ assert isinstance(line, str)+ self.raw_lines.append(line)+ return json.loads(line)++ def ready(self) -> tuple[dict, float]:+ event = self.read_event()+ return event, (time.monotonic() - self.spawned_at) * 1000++ def send(self, request: dict) -> None:+ assert self.proc.stdin is not None+ self.proc.stdin.write(json.dumps(request) + "\n")+ self.proc.stdin.flush()++ def send_raw(self, line: str) -> None:+ assert self.proc.stdin is not None+ self.proc.stdin.write(line + "\n")+ self.proc.stdin.flush()++ def execute(self, rid: str, code: str) -> list[dict]:+ self.send({"type": "execute", "id": rid, "code": code})+ return self.until_done(rid)++ def until_done(self, rid: str) -> list[dict]:+ events = []+ while True:+ event = self.read_event()+ events.append(event)+ if event.get("event") == "done" and event.get("id") == rid:+ return events++ def shutdown(self) -> int:+ self.send({"type": "shutdown", "id": "__shutdown__"})+ self.until_done("__shutdown__")+ return self.proc.wait(timeout=10)++ def close(self) -> None:+ if self.proc.poll() is None:+ self.proc.kill()+ self.proc.wait(timeout=10)+ for stream in (self.proc.stdin, self.proc.stdout):+ if stream is not None:+ stream.close()+++def stream_text(events: list[dict], stream: str) -> str:+ return "".join(e["text"] for e in events if e.get("event") == stream)+++def one(events: list[dict], kind: str) -> dict | None:+ matches = [e for e in events if e.get("event") == kind]+ return matches[0] if matches else None+++class ReplTest(unittest.TestCase):+ def setUp(self) -> None:+ self.repl = ReplProcess()+ self.addCleanup(self.repl.close)+ self.ready_event, self.ready_ms = self.repl.ready()++ def test_ready_handshake_and_startup_time(self):+ self.assertEqual(self.ready_event["event"], "ready")+ self.assertEqual(self.ready_event["protocol"], 2)+ major, minor = sys.version_info[:2]+ self.assertTrue(self.ready_event["python"].startswith(f"{major}.{minor}."))+ # Loose bound for loaded CI machines; still catches an order-of-magnitude regression.+ print(f"\n[startup] spawn -> ready: {self.ready_ms:.0f} ms")+ self.assertLess(self.ready_ms, 500)++ def test_result_echo(self):+ events = self.repl.execute("a", "1+1")+ self.assertEqual(one(events, "result")["text"], "2")+ self.assertEqual(one(events, "done")["status"], "ok")++ events = self.repl.execute("b", "x = 5")+ self.assertIsNone(one(events, "result"))++ events = self.repl.execute("c", "None")+ self.assertIsNone(one(events, "result"))++ events = self.repl.execute("d", "_ + 40")+ self.assertEqual(one(events, "result")["text"], "42")++ def test_stdout_stderr_and_direct_fd_writes(self):+ code = "\n".join(+ [+ "import os, sys",+ "print('py-out')",+ "sys.stderr.write('py-err\\n')",+ "os.write(1, b'fd-out\\n')",+ "os.write(2, b'fd-err\\n')",+ ]+ )+ events = self.repl.execute("io", code)+ out = stream_text(events, "stdout")+ err = stream_text(events, "stderr")+ self.assertIn("py-out", out)+ self.assertIn("fd-out", out)+ self.assertIn("py-err", err)+ self.assertIn("fd-err", err)+ # Python-level writes carry the cell id; raw fd bytes are never attributed.+ for event in events:+ if event.get("event") not in ("stdout", "stderr"):+ continue+ if "py-" in event["text"]:+ self.assertEqual(event["id"], "io")+ if "fd-" in event["text"]:+ self.assertIsNone(event["id"])+ # done arrives last, after every byte the cell wrote.+ self.assertEqual(events[-1]["event"], "done")++ def test_top_level_await(self):+ events = self.repl.execute("tla", "import asyncio\nawait asyncio.sleep(0)\n'ok'")+ self.assertEqual(one(events, "result")["text"], "'ok'")+ self.assertEqual(one(events, "done")["status"], "ok")++ def test_background_task_persists_across_cells(self):+ setup = "\n".join(+ [+ "import asyncio",+ "acc = []",+ "async def tick():",+ " while True:",+ " acc.append(1)",+ " await asyncio.sleep(0.01)",+ "task = asyncio.create_task(tick())",+ ]+ )+ self.assertEqual(one(self.repl.execute("bg1", setup), "done")["status"], "ok")+ events = self.repl.execute("bg2", "import asyncio\nawait asyncio.sleep(0.2)\nlen(acc)")+ count = int(one(events, "result")["text"])+ self.assertGreater(count, 1)+ events = self.repl.execute("bg3", "task.cancel()\nimport asyncio\nawait asyncio.sleep(0.05)\nlen(acc)")+ self.assertEqual(one(events, "done")["status"], "ok")++ def test_output_after_done_carries_null_id(self):+ with tempfile.TemporaryDirectory() as tmp:+ trigger = os.path.join(tmp, "go")+ code = "\n".join(+ [+ "import os, threading, time",+ "def late():",+ f" while not os.path.exists({trigger!r}):",+ " time.sleep(0.01)",+ " print('late-output', flush=True)",+ "threading.Thread(target=late, daemon=True).start()",+ ]+ )+ events = self.repl.execute("late", code)+ self.assertEqual(one(events, "done")["status"], "ok")+ # `done` is the last event carrying this cell's id.+ tagged = [e for e in events if e.get("id") == "late"]+ self.assertEqual(tagged[-1]["event"], "done")+ # Release the background writer only after `done` was observed; its+ # between-cell output must be emitted with a null id.+ with open(trigger, "w"):+ pass+ deadline = time.monotonic() + 5+ late_events: list[dict] = []+ while time.monotonic() < deadline:+ try:+ event = self.repl.read_event(timeout=0.5)+ except TimeoutError:+ continue+ late_events.append(event)+ if event.get("event") == "stdout" and "late-output" in event["text"]:+ break+ self.assertIn("late-output", stream_text(late_events, "stdout"))+ for event in late_events:+ self.assertIsNone(event.get("id"))++ def test_background_thread_and_fd_output_during_later_cell_is_null(self):+ # Cross-cell misattribution repro: a thread and a direct fd write from+ # cell1 land while cell2 runs; neither may carry cell2's id.+ code = "\n".join(+ [+ "import os, threading, time",+ "def late_print():",+ " time.sleep(0.6)",+ " print('SECRET-py', flush=True)",+ "def late_fd():",+ " time.sleep(0.7)",+ " os.write(1, b'SECRET-fd\\n')",+ "threading.Thread(target=late_print, daemon=True).start()",+ "threading.Thread(target=late_fd, daemon=True).start()",+ ]+ )+ events = self.repl.execute("cell1", code)+ self.assertEqual(one(events, "done")["status"], "ok")+ events = self.repl.execute("cell2", "import time\ntime.sleep(1.2)")+ self.assertEqual(one(events, "done")["status"], "ok")+ # The SECRET lines may land during cell2 or right after; scan until both seen.+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ text = stream_text(events, "stdout")+ if "SECRET-py" in text and "SECRET-fd" in text:+ break+ try:+ events.append(self.repl.read_event(timeout=0.5))+ except TimeoutError:+ continue+ for event in events:+ if event.get("event") == "stdout" and "SECRET" in event["text"]:+ self.assertIsNone(event["id"])+ text = stream_text(events, "stdout")+ self.assertIn("SECRET-py", text)+ self.assertIn("SECRET-fd", text)++ def test_cell_own_direct_fd_write_is_null_but_arrives_before_done(self):+ events = self.repl.execute("rawfd", "import os\nos.write(1, b'raw\\n')\nprint('tagged')")+ done_index = next(i for i, e in enumerate(events) if e.get("event") == "done")+ raw = next(e for e in events if e.get("event") == "stdout" and "raw" in e["text"])+ self.assertIsNone(raw["id"])+ self.assertLess(events.index(raw), done_index)+ tagged = next(e for e in events if e.get("event") == "stdout" and "tagged" in e["text"])+ self.assertEqual(tagged["id"], "rawfd")++ def test_drain_finalizes_incomplete_raw_utf8_before_done(self):+ first = self.repl.execute("partial-utf8", "import os\nos.write(1, b'\\xe2\\x82')")+ replacement = next(e for e in first if e.get("event") == "stdout")+ self.assertEqual(replacement["text"], "\ufffd")+ self.assertLess(first.index(replacement), first.index(one(first, "done")))++ second = self.repl.execute("continuation-utf8", "os.write(1, b'\\xac')")+ self.assertEqual(stream_text(second, "stdout"), "\ufffd")+ self.assertNotIn("€", stream_text(second, "stdout"))++ def test_hostile_deeply_nested_json_line_does_not_kill_reader(self):+ # json.loads raises RecursionError on pathological nesting; the reader+ # thread must survive and keep serving.+ self.repl.send_raw("[" * 100_000)+ error = self.repl.read_event()+ self.assertEqual(error["event"], "error")+ self.assertEqual(error["ename"], "ProtocolError")+ follow = self.repl.execute("after-hostile", "1+1")+ self.assertEqual(one(follow, "result")["text"], "2")+ self.assertEqual(one(follow, "done")["status"], "ok")++ def test_unhashable_request_type_does_not_kill_reader(self):+ self.repl.send({"type": []})+ error = self.repl.read_event()+ self.assertEqual(error["event"], "error")+ self.assertEqual(error["ename"], "ProtocolError")+ self.repl.send({"type": {"x": 1}, "id": 5})+ error = self.repl.read_event()+ self.assertEqual(error["ename"], "ProtocolError")+ follow = self.repl.execute("after-unhashable", "1+1")+ self.assertEqual(one(follow, "result")["text"], "2")+ self.assertEqual(one(follow, "done")["status"], "ok")++ def test_duplicate_inflight_id_rejected_and_original_still_interruptible(self):+ self.repl.send({"type": "execute", "id": "dup", "code": "import time\nwhile True:\n time.sleep(0.05)"})+ time.sleep(0.3)+ self.repl.send({"type": "execute", "id": "dup", "code": "print('imposter')"})+ error = self.repl.read_event()+ self.assertEqual(error["event"], "error")+ self.assertEqual(error["ename"], "ProtocolError")+ self.assertIn("duplicate", error["evalue"])+ # The original request is unaffected and its targeted interrupt still lands.+ self.repl.send({"type": "interrupt", "id": "dup"})+ events = self.repl.until_done("dup")+ self.assertEqual(one(events, "error")["ename"], "KeyboardInterrupt")+ self.assertEqual(one(events, "done")["status"], "error")+ self.assertNotIn("imposter", stream_text(events, "stdout"))+ follow = self.repl.execute("after-dup", "1+1")+ self.assertEqual(one(follow, "result")["text"], "2")++ def test_large_buffer_write_survives_short_pipe_writes(self):+ # 256 KiB exceeds the 64 KiB pipe capacity; the binary proxy must loop+ # until every byte is written.+ code = "\n".join(+ [+ "import sys",+ "n = sys.stdout.buffer.write(b'x' * 262144)",+ "sys.stdout.buffer.flush()",+ "print('wrote', n)",+ ]+ )+ events = self.repl.execute("bigbuf", code)+ self.assertEqual(one(events, "done")["status"], "ok")+ raw = "".join(+ e["text"] for e in events if e.get("event") == "stdout" and e.get("id") is None+ )+ self.assertEqual(raw.count("x"), 262144)+ # Cross-channel ordering is not guaranteed: raw x-chunks may interleave+ # between print()'s tagged fragments, so join only the tagged channel.+ tagged = "".join(+ e["text"] for e in events if e.get("event") == "stdout" and e.get("id") == "bigbuf"+ )+ self.assertIn("wrote 262144", tagged)++ def test_interrupt_without_pthread_kill_cancels_awaited_cell(self):+ # Windows fallback seam: with pthread_kill absent the reader cancels+ # the active task on the loop; an await-suspended cell still interrupts.+ code = "\n".join(+ [+ "import signal",+ "if hasattr(signal, 'pthread_kill'):",+ " del signal.pthread_kill",+ "import asyncio",+ "await asyncio.sleep(30)",+ ]+ )+ self.repl.send({"type": "execute", "id": "nokill", "code": code})+ time.sleep(0.4)+ self.repl.send({"type": "interrupt"})+ events = self.repl.until_done("nokill")+ error = one(events, "error")+ self.assertEqual(error["ename"], "KeyboardInterrupt")+ self.assertEqual(one(events, "done")["status"], "error")++ def test_stdout_buffer_write_works_and_surfaces_as_null(self):+ # Libraries write bytes via sys.stdout.buffer; the tagged writer must+ # expose a working buffer whose bytes surface (null-attributed) before done.+ events = self.repl.execute(+ "bufw", "import sys\nsys.stdout.buffer.write(b'buffer-bytes\\n')\nsys.stdout.buffer.flush()"+ )+ self.assertEqual(one(events, "done")["status"], "ok")+ buffered = next(e for e in events if e.get("event") == "stdout" and "buffer-bytes" in e["text"])+ self.assertIsNone(buffered["id"])+ self.assertLess(events.index(buffered), events.index(one(events, "done")))++ def test_stdout_buffer_write_rejects_int(self):+ # A real stdout.buffer raises TypeError for ints; bytes(5) would emit five NULs.+ events = self.repl.execute("bufint", "import sys\nsys.stdout.buffer.write(5)")+ self.assertEqual(one(events, "error")["ename"], "TypeError")+ self.assertEqual(one(events, "done")["status"], "error")++ def test_asyncio_task_output_keeps_spawning_cell_id(self):+ code = "\n".join(+ [+ "import asyncio",+ "async def late():",+ " await asyncio.sleep(0.3)",+ " print('task-output', flush=True)",+ "_t = asyncio.create_task(late())",+ ]+ )+ events = self.repl.execute("spawn", code)+ self.assertEqual(one(events, "done")["status"], "ok")+ events = self.repl.execute("next", "import asyncio\nawait asyncio.sleep(0.6)")+ late = next(e for e in events if e.get("event") == "stdout" and "task-output" in e["text"])+ self.assertEqual(late["id"], "spawn")++ def test_interrupted_await_bash_leaves_no_side_effects(self):+ # One-shot `await bash(...)` (the %%bash-rewrite pattern) must not leak+ # the command past an interrupt.+ with tempfile.TemporaryDirectory() as tmp:+ marker = os.path.join(tmp, "marker")+ code = f"from rlm import bash\nr = await bash('sleep 1.5 && touch {marker}')"+ self.repl.send({"type": "execute", "id": "ibash", "code": code})+ time.sleep(0.4)+ self.repl.send({"type": "interrupt"})+ events = self.repl.until_done("ibash")+ error = one(events, "error")+ self.assertEqual(error["ename"], "KeyboardInterrupt")+ self.assertEqual(one(events, "done")["status"], "error")+ time.sleep(1.6)+ self.assertFalse(os.path.exists(marker))++ def _interrupt_after_running(self, rid: str, code: str) -> list[dict]:+ self.repl.send({"type": "execute", "id": rid, "code": code})+ # Give the cell time to enter its blocking region before interrupting.+ time.sleep(0.4)+ self.repl.send({"type": "interrupt"})+ return self.repl.until_done(rid)++ def test_interrupt_sync_blocking(self):+ events = self._interrupt_after_running(+ "sync", "import time\nwhile True:\n time.sleep(0.05)"+ )+ error = one(events, "error")+ self.assertEqual(error["ename"], "KeyboardInterrupt")+ self.assertNotIn("repl.py", "".join(error["traceback"]))+ self.assertEqual(one(events, "done")["status"], "error")+ follow = self.repl.execute("after-sync", "1+1")+ self.assertEqual(one(follow, "result")["text"], "2")++ def test_interrupt_survives_cell_rebinding_sigint(self):+ # A cell that ignores SIGINT must not break protocol interrupts for later cells.+ events = self.repl.execute(+ "rebind", "import signal\nsignal.signal(signal.SIGINT, signal.SIG_IGN)"+ )+ self.assertEqual(one(events, "done")["status"], "ok")+ events = self._interrupt_after_running(+ "sync-after-rebind", "import time\nwhile True:\n time.sleep(0.05)"+ )+ error = one(events, "error")+ self.assertEqual(error["ename"], "KeyboardInterrupt")+ self.assertEqual(one(events, "done")["status"], "error")+ follow = self.repl.execute("after-rebind", "5+5")+ self.assertEqual(one(follow, "result")["text"], "10")++ def test_interrupt_await_suspended(self):+ events = self._interrupt_after_running(+ "await", "import asyncio\nawait asyncio.sleep(1e9)"+ )+ error = one(events, "error")+ self.assertEqual(error["ename"], "KeyboardInterrupt")+ self.assertIn("await asyncio.sleep(1e9)", "".join(error["traceback"]))+ self.assertEqual(one(events, "done")["status"], "error")+ follow = self.repl.execute("after-await", "2+2")+ self.assertEqual(one(follow, "result")["text"], "4")++ def test_interrupt_sync_blocked_in_selectors(self):+ events = self._interrupt_after_running(+ "sel", "import selectors\ns = selectors.DefaultSelector()\ns.select()"+ )+ error = one(events, "error")+ self.assertEqual(error["ename"], "KeyboardInterrupt")+ self.assertNotIn("repl.py", "".join(error["traceback"]))+ self.assertEqual(one(events, "done")["status"], "error")+ follow = self.repl.execute("after-sel", "3+3")+ self.assertEqual(one(follow, "result")["text"], "6")++ def test_interrupt_await_with_loop_hogging_background_task(self):+ # A sync-blocked background task hogs the only thread; the interrupt kills it+ # so the foreground cancel can take effect.+ code = "\n".join(+ [+ "import asyncio, time",+ "async def hog():",+ " while True:",+ " time.sleep(0.05)",+ "hog_task = asyncio.create_task(hog())",+ "await asyncio.sleep(1e9)",+ ]+ )+ events = self._interrupt_after_running("fg", code)+ error = one(events, "error")+ self.assertEqual(error["ename"], "KeyboardInterrupt")+ self.assertEqual(one(events, "done")["status"], "error")+ follow = self.repl.execute("hog-fate", "type(hog_task.exception()).__name__")+ self.assertEqual(one(follow, "result")["text"], "'KeyboardInterrupt'")+ follow = self.repl.execute("after-hog", "7+7")+ self.assertEqual(one(follow, "result")["text"], "14")++ def test_interrupt_written_back_to_back_with_execute(self):+ execute = json.dumps({"type": "execute", "id": "race", "code": "import asyncio\nawait asyncio.sleep(1e9)"})+ interrupt = json.dumps({"type": "interrupt"})+ assert self.repl.proc.stdin is not None+ self.repl.proc.stdin.write(execute + "\n" + interrupt + "\n")+ self.repl.proc.stdin.flush()+ events = self.repl.until_done("race")+ error = one(events, "error")+ self.assertEqual(error["ename"], "KeyboardInterrupt")+ self.assertEqual(one(events, "done")["status"], "error")+ follow = self.repl.execute("after-race", "5+5")+ self.assertEqual(one(follow, "result")["text"], "10")++ def test_stale_target_from_finished_interrupt_ignores_later_sigint_on_reused_id(self):+ # A targeted interrupt completes "reuse"; a later request reusing the id+ # must not be cancelled by a delayed/external SIGINT that only matches+ # the stale target of the finished request.+ events = self._interrupt_after_running("reuse", "import time\nwhile True:\n time.sleep(0.05)")+ self.assertEqual(one(events, "error")["ename"], "KeyboardInterrupt")+ self.repl.send({"type": "execute", "id": "reuse", "code": "import time\ntime.sleep(1.5)\nprint('survived')"})+ time.sleep(0.4) # let the cell enter its sleep before the stray SIGINT+ os.kill(self.repl.proc.pid, signal.SIGINT)+ events = self.repl.until_done("reuse")+ self.assertIsNone(one(events, "error"))+ self.assertEqual(one(events, "done")["status"], "ok")+ self.assertIn("survived", stream_text(events, "stdout"))++ def test_interrupt_during_slow_repr_cancels_finishing_request(self):+ # The cell body finishes instantly; the interrupt lands while the+ # trailing-expression repr is sleeping (post-run finishing window).+ code = "\n".join(+ [+ "import time",+ "class SlowRepr:",+ " def __repr__(self):",+ " time.sleep(600)",+ " return 'late'",+ "SlowRepr()",+ ]+ )+ events = self._interrupt_after_running("slowrepr", code)+ error = one(events, "error")+ self.assertEqual(error["ename"], "KeyboardInterrupt")+ self.assertEqual(one(events, "done")["status"], "error")+ follow = self.repl.execute("after-slowrepr", "1+1")+ self.assertEqual(one(follow, "result")["text"], "2")++ def test_traceback_clean_with_source_line(self):+ code = "def boom():\n raise ValueError('nope')\nboom()"+ events = self.repl.execute("tb", code)+ error = one(events, "error")+ self.assertEqual(error["ename"], "ValueError")+ self.assertEqual(error["evalue"], "nope")+ text = "".join(error["traceback"])+ self.assertIn("<cell-", text)+ self.assertIn("raise ValueError('nope')", text)+ self.assertNotIn("repl.py", text)+ self.assertNotIn("\x1b[", text)++ def test_syntax_error(self):+ events = self.repl.execute("syn", "def broken(:\n pass")+ error = one(events, "error")+ self.assertEqual(error["ename"], "SyntaxError")+ text = "".join(error["traceback"])+ self.assertIn("<cell-", text)+ self.assertNotIn("repl.py", text)+ self.assertNotIn("ast.py", text)+ self.assertEqual(one(events, "done")["status"], "error")++ def test_snapshot_restore_roundtrip(self):+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "kernel-state.dill")+ manifest_path = os.path.join(tmp, "kernel-state.json")+ setup = "\n".join(+ [+ "import socket",+ "x = 41",+ "def bump(n):",+ " return n + 1",+ "sock = socket.socket()",+ ]+ )+ self.assertEqual(one(self.repl.execute("s1", setup), "done")["status"], "ok")+ self.repl.send({"type": "snapshot", "id": "s2", "path": path, "manifest_path": manifest_path})+ done = one(self.repl.until_done("s2"), "done")+ self.assertEqual(done["status"], "ok")+ self.assertEqual(sorted(done["saved"]), ["bump", "socket", "x"])+ self.assertEqual([s["name"] for s in done["skipped"]], ["sock"])+ self.assertNotIn("asyncio", done["saved"])+ self.assertEqual(+ sorted(os.listdir(tmp)), ["kernel-state.dill", "kernel-state.json"]+ ) # no temp files survive a successful commit+ with open(manifest_path) as fh:+ manifest = json.load(fh)+ self.assertEqual(manifest["version"], 1)+ self.assertEqual(manifest["savedNames"], done["saved"])+ self.assertEqual(manifest["bytes"], done["bytes"])+ self.assertIn("pythonVersion", manifest)+ self.assertIn("timestamp", manifest)++ fresh = ReplProcess()+ self.addCleanup(fresh.close)+ fresh.ready()+ fresh.send({"type": "restore", "id": "r1", "path": path})+ done = one(fresh.until_done("r1"), "done")+ self.assertEqual(done["status"], "ok")+ self.assertEqual(sorted(done["restored"]), ["bump", "socket", "x"])+ events = fresh.execute("r2", "bump(x)")+ self.assertEqual(one(events, "result")["text"], "42")+ self.assertEqual(fresh.shutdown(), 0)++ def test_restore_skips_ipython_injected_names(self):+ import dill++ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "kernel-state.dill")+ payload = {+ "kept": dill.dumps(7),+ "In": dill.dumps(["cell"]),+ "Out": dill.dumps({1: "x"}),+ "get_ipython": dill.dumps(None),+ }+ with open(path, "wb") as fh:+ dill.dump(payload, fh)+ self.repl.send({"type": "restore", "id": "r", "path": path})+ done = one(self.repl.until_done("r"), "done")+ self.assertEqual(done["status"], "ok")+ self.assertEqual(done["restored"], ["kept"])+ events = self.repl.execute("chk", "'In' in dir()")+ self.assertEqual(one(events, "result")["text"], "False")++ def test_snapshot_prune_oversized(self):+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "kernel-state.dill")+ manifest_path = os.path.join(tmp, "kernel-state.json")+ self.repl.execute("p1", "small = 1\nbig = b'x' * 100_000")+ self.repl.send(+ {+ "type": "snapshot",+ "id": "p2",+ "path": path,+ "manifest_path": manifest_path,+ "max_variable_bytes": 1024,+ "prune_oversized": True,+ }+ )+ done = one(self.repl.until_done("p2"), "done")+ self.assertEqual(done["status"], "ok")+ self.assertEqual(done["saved"], ["small"])+ self.assertEqual(done["pruned"], ["big"])+ events = self.repl.execute("p3", "'big' in dir()")+ self.assertEqual(one(events, "result")["text"], "False")++ def test_emit_display(self):+ payloads = {+ "application/vnd.prime-agent.diff+json": {+ "path": "/tmp/file.py",+ "old_str": "a",+ "new_str": "b",+ "start_line": 3,+ },+ "application/vnd.prime-agent.attachment+json": {+ "mime_type": "image/png",+ "data": "aGVsbG8=",+ "path": "/tmp/img.png",+ },+ "application/vnd.prime-agent.agent-message+json": {+ "id": "agentmsg_1",+ "message": "hi",+ "deliveryStatus": "delivered",+ "receiverRole": "parent",+ "target": {"sessionId": "s1"},+ },+ }+ for i, (mime, payload) in enumerate(payloads.items()):+ code = "\n".join(+ [+ "from rlm.repl import emit",+ f"emit({{ {mime!r}: {payload!r}, 'text/plain': 'label' }})",+ ]+ )+ events = self.repl.execute(f"emit{i}", code)+ display = one(events, "display")+ self.assertIsNotNone(display)+ self.assertEqual(display["data"][mime], payload)+ self.assertEqual(display["data"]["text/plain"], "label")+ self.assertEqual(display["id"], f"emit{i}")++ def test_emit_nan_payload_errors_in_cell_and_keeps_framing(self):+ # NaN would serialize as non-JSON text and tear protocol framing;+ # emit() must raise in the caller's cell instead.+ code = "from rlm.repl import emit\nemit({'application/json': float('nan')})"+ events = self.repl.execute("emit-nan", code)+ self.assertEqual(one(events, "error")["ename"], "ValueError")+ self.assertEqual(one(events, "done")["status"], "error")+ self.assertIsNone(one(events, "display"))+ follow = self.repl.execute("after-emit-nan", "1+1")+ self.assertEqual(one(follow, "result")["text"], "2")+ self.assertEqual(one(follow, "done")["status"], "ok")++ def test_bash_integration(self):+ events = self.repl.execute(+ "sh1", "from rlm import bash\nresult = await bash('echo repl-bash')\nresult.output.strip()"+ )+ self.assertEqual(one(events, "result")["text"], "'repl-bash'")++ events = self.repl.execute(+ "sh2", "handle = bash('sleep 600')\nhandle.pid"+ )+ pid = int(one(events, "result")["text"])+ self.assertEqual(self.repl.shutdown(), 0)+ # Shutdown kills live bash process groups; the sleep must be gone.+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return+ time.sleep(0.05)+ self.fail(f"bash child {pid} survived runtime shutdown")++ def test_protocol_framing_under_noise(self):+ setup = "\n".join(+ [+ "import os, threading",+ "stop = threading.Event()",+ "def spam():",+ " while not stop.is_set():",+ " os.write(1, b'noise-' * 64 + b'\\n')",+ "threading.Thread(target=spam, daemon=True).start()",+ ]+ )+ self.assertEqual(one(self.repl.execute("n0", setup), "done")["status"], "ok")+ for i in range(5):+ events = self.repl.execute(f"n{i + 1}", f"{i} * 10")+ self.assertEqual(one(events, "result")["text"], str(i * 10))+ self.repl.execute("n-stop", "stop.set()")+ # Every protocol line parsed as JSON (until_done would have raised+ # otherwise); noise text only ever arrived inside stdout events.+ for line in self.repl.raw_lines:+ event = json.loads(line)+ if "noise-" in line:+ self.assertEqual(event["event"], "stdout")++ def test_malformed_request_line(self):+ self.repl.send_raw("{not json")+ event = self.repl.read_event()+ self.assertEqual(event["event"], "error")+ self.assertEqual(event["ename"], "ProtocolError")+ self.assertIsNone(event["id"])+ events = self.repl.execute("ok", "'alive'")+ self.assertEqual(one(events, "result")["text"], "'alive'")++ def test_list_names(self):+ self.repl.execute("ln1", "alpha = 1\ndef helper(n):\n return n\n_hidden = 2\nrlm = object()")+ self.repl.send({"type": "list_names", "id": "ln2"})+ done = one(self.repl.until_done("ln2"), "done")+ self.assertEqual(done["status"], "ok")+ self.assertIn("alpha", done["names"])+ self.assertIn("helper", done["names"])+ self.assertNotIn("_hidden", done["names"])+ self.assertNotIn("rlm", done["names"])+ self.assertEqual(done["names"], sorted(done["names"]))++ def test_list_names_skips_non_string_keys(self):+ self.repl.execute("lnk1", "globals()[1] = 1\nbeta = 2")+ self.repl.send({"type": "list_names", "id": "lnk2"})+ done = one(self.repl.until_done("lnk2"), "done")+ self.assertEqual(done["status"], "ok")+ self.assertIn("beta", done["names"])+ self.assertNotIn(1, done["names"])+ events = self.repl.execute("lnk3", "'alive'")+ self.assertEqual(one(events, "result")["text"], "'alive'")++ def test_host_request_round_trip(self):+ code = "\n".join(+ [+ "from rlm.repl import host_request",+ "reply = await host_request({'type': 'demo', 'value': 7})",+ "reply",+ ]+ )+ self.repl.send({"type": "execute", "id": "hr", "code": code})+ request = self.repl.read_event()+ while request.get("event") != "host_request":+ request = self.repl.read_event()+ self.assertEqual(request["data"], {"type": "demo", "value": 7})+ self.repl.send({"type": "host_reply", "id": request["id"], "data": {"status": "ok", "answer": 42}})+ events = self.repl.until_done("hr")+ self.assertEqual(one(events, "result")["text"], "{'status': 'ok', 'answer': 42}")+ self.assertEqual(one(events, "done")["status"], "ok")++ def test_host_reply_for_unknown_id_dropped(self):+ self.repl.send({"type": "host_reply", "id": "no-such-request", "data": {"status": "ok"}})+ events = self.repl.execute("ok", "'alive'")+ self.assertEqual(one(events, "result")["text"], "'alive'")++ def test_host_request_cancelled_cell_drops_pending_future(self):+ code = "\n".join(+ [+ "from rlm.repl import host_request",+ "await host_request({'type': 'never-answered'})",+ ]+ )+ self.repl.send({"type": "execute", "id": "hr-cancel", "code": code})+ request = self.repl.read_event()+ while request.get("event") != "host_request":+ request = self.repl.read_event()+ self.repl.send({"type": "interrupt"})+ events = self.repl.until_done("hr-cancel")+ self.assertEqual(one(events, "error")["ename"], "KeyboardInterrupt")+ # A reply arriving after the cancel must be dropped, not crash the runtime.+ self.repl.send({"type": "host_reply", "id": request["id"], "data": {"status": "ok"}})+ follow = self.repl.execute("after-cancel", "8+8")+ self.assertEqual(one(follow, "result")["text"], "16")++ def test_display_from_detached_task_keeps_cell_id(self):+ code = "\n".join(+ [+ "import asyncio",+ "from rlm.repl import emit",+ "async def later():",+ " await asyncio.sleep(0.2)",+ " emit({'text/plain': 'late'})",+ "detached = asyncio.create_task(later())",+ ]+ )+ self.assertEqual(one(self.repl.execute("det", code), "done")["status"], "ok")+ self.assertEqual(one(self.repl.execute("idle", "1"), "done")["status"], "ok")+ display = self.repl.read_event()+ while display.get("event") != "display":+ display = self.repl.read_event()+ self.assertEqual(display["id"], "det")+ self.assertEqual(display["data"], {"text/plain": "late"})++ def test_shutdown_clean_exit(self):+ self.assertEqual(self.repl.shutdown(), 0)++ def test_shutdown_after_mcp_import_exits_cleanly(self):+ events = self.repl.execute("mcp-import", "import rlm.mcp")+ self.assertEqual(one(events, "done")["status"], "ok")+ self.assertEqual(self.repl.shutdown(), 0)++ def _start_pending_host_request(self) -> None:+ code = "\n".join(+ [+ "from rlm.repl import host_request",+ "await host_request({'type': 'never-answered'})",+ ]+ )+ self.repl.send({"type": "execute", "id": "hr-pending", "code": code})+ request = self.repl.read_event()+ while request.get("event") != "host_request":+ request = self.repl.read_event()++ def test_stdin_eof_with_pending_host_request_exits(self):+ self._start_pending_host_request()+ assert self.repl.proc.stdin is not None+ self.repl.proc.stdin.close()+ self.assertEqual(self.repl.proc.wait(timeout=10), 0)++ def test_shutdown_with_pending_host_request_exits(self):+ self._start_pending_host_request()+ self.repl.send({"type": "shutdown", "id": "__shutdown__"})+ events = self.repl.until_done("hr-pending")+ self.assertEqual(one(events, "error")["ename"], "RuntimeError")+ self.repl.until_done("__shutdown__")+ self.assertEqual(self.repl.proc.wait(timeout=10), 0)+++ def test_interrupt_with_non_string_id_is_protocol_error(self):+ self.repl.send({"type": "execute", "id": "busy", "code": "import asyncio\nawait asyncio.sleep(0.6)\n'done'"})+ time.sleep(0.2)+ self.repl.send({"type": "interrupt", "id": 123})+ events = self.repl.until_done("busy")+ protocol_errors = [e for e in events if e.get("ename") == "ProtocolError"]+ self.assertEqual(len(protocol_errors), 1)+ self.assertIn("interrupt request id must be a string", protocol_errors[0]["evalue"])+ # The running cell was not interrupted by the malformed request.+ self.assertEqual(one(events, "result")["text"], "'done'")+ self.assertEqual(one(events, "done")["status"], "ok")++ def test_snapshot_rejects_non_boolean_and_non_integer_options(self):+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "kernel-state.dill")+ manifest_path = os.path.join(tmp, "kernel-state.json")+ self.repl.execute("v1", "big = b'x' * 100_000")+ self.repl.send(+ {+ "type": "snapshot",+ "id": "v2",+ "path": path,+ "manifest_path": manifest_path,+ "max_variable_bytes": 1024,+ "prune_oversized": "false",+ }+ )+ done = one(self.repl.until_done("v2"), "done")+ self.assertEqual(done["status"], "error")+ self.assertIn("boolean", done["reason"])+ events = self.repl.execute("v3", "'big' in dir()")+ self.assertEqual(one(events, "result")["text"], "True")++ self.repl.send(+ {"type": "snapshot", "id": "v4", "path": path, "manifest_path": manifest_path, "max_bytes": "10"}+ )+ done = one(self.repl.until_done("v4"), "done")+ self.assertEqual(done["status"], "error")+ self.assertIn("max_bytes must be a non-negative integer", done["reason"])++ # An explicit JSON null is present-but-invalid, not "use the default".+ self.repl.send(+ {"type": "snapshot", "id": "v5", "path": path, "manifest_path": manifest_path, "max_bytes": None}+ )+ done = one(self.repl.until_done("v5"), "done")+ self.assertEqual(done["status"], "error")+ self.assertIn("max_bytes must be a non-negative integer", done["reason"])++ self.repl.send(+ {+ "type": "snapshot",+ "id": "v6",+ "path": path,+ "manifest_path": manifest_path,+ "max_variable_bytes": None,+ }+ )+ done = one(self.repl.until_done("v6"), "done")+ self.assertEqual(done["status"], "error")+ self.assertIn("max_variable_bytes must be a non-negative integer", done["reason"])++ # A negative cap with prune_oversized would delete every user variable: reject it+ # before the snapshot runs, leaving the namespace untouched.+ self.repl.send(+ {+ "type": "snapshot",+ "id": "v7",+ "path": path,+ "manifest_path": manifest_path,+ "max_variable_bytes": -1,+ "prune_oversized": True,+ }+ )+ done = one(self.repl.until_done("v7"), "done")+ self.assertEqual(done["status"], "error")+ self.assertIn("max_variable_bytes must be a non-negative integer", done["reason"])+ events = self.repl.execute("v8", "'big' in dir()")+ self.assertEqual(one(events, "result")["text"], "True")++ def test_snapshot_rejects_identical_path_and_manifest_path(self):+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "kernel-state.dill")+ self.repl.send({"type": "snapshot", "id": "sp1", "path": path, "manifest_path": path})+ done = one(self.repl.until_done("sp1"), "done")+ self.assertEqual(done["status"], "error")+ self.assertEqual(done["reason"], "path and manifest_path must differ")+ self.assertFalse(os.path.exists(path))++ def test_exception_with_broken_str_reported_safely(self):+ code = "\n".join(+ [+ "class Broken(Exception):",+ " def __str__(self):",+ " raise RuntimeError('nope')",+ "raise Broken()",+ ]+ )+ events = self.repl.execute("brk", code)+ error = one(events, "error")+ self.assertEqual(error["ename"], "Broken")+ self.assertEqual(error["evalue"], "<exception str() failed>")+ self.assertEqual(one(events, "done")["status"], "error")+ follow = self.repl.execute("after-brk", "1+1")+ self.assertEqual(one(follow, "result")["text"], "2")++ def test_snapshot_manifest_write_failure_fails_without_pruning(self):+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "kernel-state.dill")+ manifest_path = os.path.join(tmp, "missing-dir", "kernel-state.json")+ self.repl.execute("m1", "big = b'x' * 100_000")+ self.repl.send(+ {+ "type": "snapshot",+ "id": "m2",+ "path": path,+ "manifest_path": manifest_path,+ "max_variable_bytes": 1024,+ "prune_oversized": True,+ }+ )+ done = one(self.repl.until_done("m2"), "done")+ self.assertEqual(done["status"], "error")+ self.assertTrue(done["reason"].startswith("manifest write failed"))+ events = self.repl.execute("m3", "'big' in dir()")+ self.assertEqual(one(events, "result")["text"], "True")++ def test_closed_stdio_cell_still_completes_and_serves_next(self):+ # Closing sys.stdout/sys.stderr must not kill the serve loop: done still+ # arrives and the runtime keeps serving cells.+ events = self.repl.execute("close-io", "import sys\nsys.stdout.close()\nsys.stderr.close()")+ self.assertEqual(one(events, "done")["status"], "ok")+ follow = self.repl.execute("after-close", "1+1")+ self.assertEqual(one(follow, "result")["text"], "2")+ self.assertEqual(one(follow, "done")["status"], "ok")++ def test_compile_crash_reports_error_and_serves_next(self):+ # A compile-phase crash outside SyntaxError/ValueError (RecursionError or+ # MemoryError depending on build) must fail the one cell, not the runtime.+ events = self.repl.execute("deep", "a" + ".b" * 100000)+ self.assertIsNotNone(one(events, "error"))+ self.assertEqual(one(events, "done")["status"], "error")+ follow = self.repl.execute("after-deep", "1+1")+ self.assertEqual(one(follow, "result")["text"], "2")+ self.assertEqual(one(follow, "done")["status"], "ok")++ def test_rebound_stdout_without_flush_still_completes(self):+ # Rebinding sys.stdout/sys.stderr to flush-less objects must not kill drain.+ events = self.repl.execute("rebind-io", "import sys\nsys.stdout = None\nsys.stderr = None")+ self.assertEqual(one(events, "done")["status"], "ok")+ follow = self.repl.execute("after-rebind", "1+1")+ self.assertEqual(one(follow, "result")["text"], "2")+ self.assertEqual(one(follow, "done")["status"], "ok")++ def test_closed_fds_reclaimed_by_files_still_completes(self):+ # A cell closing fds 1/2 with open() reclaiming the numbers must not wedge+ # drain: tokens go through a private dup, so done still arrives.+ code = "\n".join(+ [+ "import os",+ "os.close(1)",+ "os.close(2)",+ "a = open(os.devnull, 'w')",+ "b = open(os.devnull, 'w')",+ ]+ )+ events = self.repl.execute("reclaim-fds", code)+ self.assertEqual(one(events, "done")["status"], "ok")+ # print() writes via sys.stdout's own dup, so the event must arrive and drain stays exact.+ follow = self.repl.execute("after-reclaim", "print('hi')")+ self.assertEqual(stream_text(follow, "stdout"), "hi\n")+ self.assertEqual(one(follow, "done")["status"], "ok")++ def test_restore_missing_snapshot_is_ok_with_reason(self):+ with tempfile.TemporaryDirectory() as tmp:+ self.repl.send({"type": "restore", "id": "r0", "path": os.path.join(tmp, "absent.dill")})+ done = one(self.repl.until_done("r0"), "done")+ self.assertEqual(done["status"], "ok")+ self.assertEqual(done["restored"], [])+ self.assertEqual(done["failed"], [])+ self.assertEqual(done["reason"], "snapshot not found")+++class FinishRequestTest(unittest.TestCase):+ """In-process checks of the parked-interrupt bookkeeping on request finish."""++ def setUp(self) -> None:+ import rlm.repl as repl_module++ self.repl_module = repl_module+ self.addCleanup(self._reset)++ def _reset(self) -> None:+ self.repl_module._inflight.clear()+ self.repl_module._pending_interrupts["ids"].clear()+ self.repl_module._pending_interrupts["any"] = False+ self.repl_module._finishing_rid = None+ self.repl_module._handoff_interrupted = False+ self.repl_module._sigint_target = None+ self.repl_module._active.update({"task": None, "rid": None, "interrupted": False})++ def test_parked_any_survives_while_another_request_is_inflight(self):+ repl = self.repl_module+ repl._inflight.update({"a", "b"})+ repl._pending_interrupts["any"] = True+ repl._finish_request("a")+ self.assertTrue(repl._pending_interrupts["any"])+ repl._finish_request("b")+ self.assertFalse(repl._pending_interrupts["any"])++ def test_compile_error_consumes_parked_untargeted_interrupt(self):+ # An untargeted interrupt parked while a compile-broken request was+ # inflight belongs to that request: its compile-error finish must+ # consume it even while another request is still inflight, so the+ # interrupt cannot leak onto the next cell.+ repl = self.repl_module+ repl._inflight.update({"bad", "other"})+ repl._pending_interrupts["any"] = True+ asyncio.run(repl._handle_request(repl._handle_execute, {"id": "bad", "code": "def broken(:\n pass"}, {}))+ self.assertFalse(repl._pending_interrupts["any"])+ self.assertNotIn("bad", repl._inflight)+ self.assertIn("other", repl._inflight)++ def test_post_run_error_leaves_parked_interrupt_for_next_request(self):+ # Once _run_guarded finished a request (_finish_locked already ran), a+ # later exception in the same handler must not consume an untargeted+ # interrupt parked for the still-inflight next request.+ repl = self.repl_module++ async def finished_then_broken(req, ns):+ repl._finish_request(req["id"]) # simulate _run_guarded completion+ repl._pending_interrupts["any"] = True # parked while "other" is inflight+ raise RuntimeError("post-execution failure")++ repl._inflight.update({"done", "other"})+ asyncio.run(repl._handle_request(finished_then_broken, {"id": "done"}, {}))+ self.assertTrue(repl._pending_interrupts["any"])+ self.assertIn("other", repl._inflight)++ def test_sigint_in_post_run_guarded_window_reports_snapshot_ok(self):+ # A finishing-targeted SIGINT between _run_guarded's return and+ # _finish_request raises KeyboardInterrupt into _handle_state; the+ # completed destructive snapshot must still report done status ok.+ import signal+ from unittest import mock++ repl = self.repl_module+ real_run_guarded = repl._run_guarded++ async def run_guarded_then_sigint(task, rid):+ outcome = await real_run_guarded(task, rid)+ with repl._interrupt_lock:+ repl._sigint_target = rid+ # Synchronous SIGINT in the post-run window: the handler sees+ # _sigint_target == _finishing_rid and raises right here.+ signal.raise_signal(signal.SIGINT)+ return outcome++ previous = signal.signal(signal.SIGINT, repl._sigint_handler)+ self.addCleanup(signal.signal, signal.SIGINT, previous)+ previous_loop = repl._loop+ self.addCleanup(setattr, repl, "_loop", previous_loop)+ sent = []+ ns = {"big": b"x" * 100_000}++ with tempfile.TemporaryDirectory() as tmp:+ req = {+ "type": "snapshot",+ "id": "snap",+ "path": os.path.join(tmp, "kernel-state.dill"),+ "manifest_path": os.path.join(tmp, "kernel-state.json"),+ "max_variable_bytes": 1024,+ "prune_oversized": True,+ }++ async def main():+ repl._loop = asyncio.get_running_loop()+ repl._inflight.add("snap")+ await repl._handle_request(repl._handle_state, req, ns)++ with mock.patch.object(repl, "_run_guarded", run_guarded_then_sigint):+ with mock.patch.object(repl, "_send", sent.append):+ asyncio.run(main())++ done = next(e for e in sent if e.get("event") == "done")+ self.assertEqual(done["status"], "ok")+ self.assertEqual(done["pruned"], ["big"])+ # The prune ran (destructive success) and the request is fully finished.+ self.assertEqual(ns, {})+ self.assertNotIn("snap", repl._inflight)++ def test_protocol_interrupt_during_restore_commit_is_consumed_and_next_request_runs(self):+ # A protocol interrupt (_request_interrupt -> SIGINT on the main thread)+ # landing while the restore applies its staged names is consumed: the+ # restore reports done ok with every name applied, and a following+ # request runs normally with no interrupt bleed.+ import signal+ from unittest import mock++ repl = self.repl_module+ previous = signal.signal(signal.SIGINT, repl._sigint_handler)+ self.addCleanup(signal.signal, signal.SIGINT, previous)+ previous_loop = repl._loop+ self.addCleanup(setattr, repl, "_loop", previous_loop)+ sent = []++ class InterruptOnFirstSet(dict):+ def __setitem__(self, key, value):+ super().__setitem__(key, value)+ if len(self) == 1:+ repl._request_interrupt("restore")++ ns = InterruptOnFirstSet()+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "kernel-state.dill")+ manifest = os.path.join(tmp, "kernel-state.json")+ snap = repl._snapshot_state({"a": 1, "b": 2}, path, manifest, 1 << 20, 1 << 20, False)+ self.assertNotIn("error", snap)++ async def main():+ repl._loop = asyncio.get_running_loop()+ repl._inflight.add("restore")+ await repl._handle_request(repl._handle_state, {"type": "restore", "id": "restore", "path": path}, ns)+ repl._inflight.add("next")+ await repl._handle_request(repl._handle_execute, {"id": "next", "code": "checked = 1 + 1"}, {})++ with mock.patch.object(repl, "_send", sent.append):+ with mock.patch.object(repl, "_drain_output", lambda: None):+ asyncio.run(main())++ done_restore = next(e for e in sent if e.get("event") == "done" and e["id"] == "restore")+ self.assertEqual(done_restore["status"], "ok")+ self.assertEqual(done_restore["restored"], ["a", "b"])+ self.assertEqual(dict(ns), {"a": 1, "b": 2})+ done_next = next(e for e in sent if e.get("event") == "done" and e["id"] == "next")+ self.assertEqual(done_next["status"], "ok")+ self.assertIsNone(repl._sigint_target)+ self.assertFalse(repl._pending_interrupts["any"])+ self.assertFalse(repl._pending_interrupts["ids"])++ @staticmethod+ def _run_resuming(coro):+ # Mimic main(): a KI escaping a task stops run_until_complete; the+ # runtime resumes the loop and serving continues.+ loop = asyncio.new_event_loop()+ try:+ outer = loop.create_task(coro)+ while not outer.done():+ try:+ loop.run_until_complete(outer)+ except KeyboardInterrupt:+ continue+ finally:+ loop.close()++ def test_protocol_interrupt_after_restore_returned_before_task_done_reports_ok(self):+ # The interrupt raises into the state task AFTER _restore_state returned+ # but before the task completes; every binding is committed, so the+ # request must report ok from the committed box, not interrupted.+ import signal+ from unittest import mock++ repl = self.repl_module+ previous = signal.signal(signal.SIGINT, repl._sigint_handler)+ self.addCleanup(signal.signal, signal.SIGINT, previous)+ previous_loop = repl._loop+ self.addCleanup(setattr, repl, "_loop", previous_loop)+ sent = []+ real_restore = repl._restore_state++ def restore_then_interrupt(*args, **kwargs):+ result = real_restore(*args, **kwargs)+ repl._sigint_target = "restore"+ repl._sigint_handler(signal.SIGINT, None) # raises into the still-running task+ return result++ ns: dict = {}+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "kernel-state.dill")+ manifest = os.path.join(tmp, "kernel-state.json")+ snap = repl._snapshot_state({"a": 1, "b": 2}, path, manifest, 1 << 20, 1 << 20, False)+ self.assertNotIn("error", snap)++ async def main():+ repl._loop = asyncio.get_running_loop()+ repl._inflight.add("restore")+ await repl._handle_request(repl._handle_state, {"type": "restore", "id": "restore", "path": path}, ns)+ repl._inflight.add("next")+ await repl._handle_request(repl._handle_execute, {"id": "next", "code": "checked = 1 + 1"}, {})++ with mock.patch.object(repl, "_restore_state", restore_then_interrupt):+ with mock.patch.object(repl, "_send", sent.append):+ with mock.patch.object(repl, "_drain_output", lambda: None):+ self._run_resuming(main())++ done_restore = next(e for e in sent if e.get("event") == "done" and e["id"] == "restore")+ self.assertEqual(done_restore["status"], "ok")+ self.assertEqual(done_restore["restored"], ["a", "b"])+ self.assertEqual(ns, {"a": 1, "b": 2})+ done_next = next(e for e in sent if e.get("event") == "done" and e["id"] == "next")+ self.assertEqual(done_next["status"], "ok")+ self.assertIsNone(repl._sigint_target)+ self.assertFalse(repl._pending_interrupts["any"])+ self.assertFalse(repl._pending_interrupts["ids"])++ def test_nonprotocol_keyboardinterrupt_after_committed_restore_is_not_recovered(self):+ # A user-originated KeyboardInterrupt (no _sigint_handler provenance:+ # _active["interrupted"] stays False) after the restore committed must+ # keep the interrupted error, not be converted to snapshot success.+ from unittest import mock++ repl = self.repl_module+ previous_loop = repl._loop+ self.addCleanup(setattr, repl, "_loop", previous_loop)+ sent = []+ real_restore = repl._restore_state++ def restore_then_user_interrupt(*args, **kwargs):+ real_restore(*args, **kwargs) # fills the committed box+ raise KeyboardInterrupt("nonprotocol")++ ns: dict = {}+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "kernel-state.dill")+ manifest = os.path.join(tmp, "kernel-state.json")+ snap = repl._snapshot_state({"a": 1, "b": 2}, path, manifest, 1 << 20, 1 << 20, False)+ self.assertNotIn("error", snap)++ async def main():+ repl._loop = asyncio.get_running_loop()+ repl._inflight.add("restore")+ await repl._handle_request(repl._handle_state, {"type": "restore", "id": "restore", "path": path}, ns)++ with mock.patch.object(repl, "_restore_state", restore_then_user_interrupt):+ with mock.patch.object(repl, "_send", sent.append):+ with mock.patch.object(repl, "_drain_output", lambda: None):+ self._run_resuming(main())++ done = next(e for e in sent if e.get("event") == "done" and e["id"] == "restore")+ self.assertEqual(done["status"], "error")+ self.assertEqual(done["reason"], "interrupted")++ def test_protocol_interrupt_after_destructive_snapshot_returned_reports_ok(self):+ # Same post-return window for snapshot: the pruning commit already ran,+ # so the interrupt must not misreport the destructive snapshot as failed.+ import signal+ from unittest import mock++ repl = self.repl_module+ previous = signal.signal(signal.SIGINT, repl._sigint_handler)+ self.addCleanup(signal.signal, signal.SIGINT, previous)+ previous_loop = repl._loop+ self.addCleanup(setattr, repl, "_loop", previous_loop)+ sent = []+ real_snapshot = repl._snapshot_state++ def snapshot_then_interrupt(*args, **kwargs):+ result = real_snapshot(*args, **kwargs)+ repl._sigint_target = "snap"+ repl._sigint_handler(signal.SIGINT, None) # raises into the still-running task+ return result++ ns = {"small": 1, "big": "x" * 100000}+ with tempfile.TemporaryDirectory() as tmp:+ req = {+ "type": "snapshot",+ "id": "snap",+ "path": os.path.join(tmp, "kernel-state.dill"),+ "manifest_path": os.path.join(tmp, "kernel-state.json"),+ "prune_oversized": True,+ "max_variable_bytes": 1024,+ }++ async def main():+ repl._loop = asyncio.get_running_loop()+ repl._inflight.add("snap")+ await repl._handle_request(repl._handle_state, req, ns)++ with mock.patch.object(repl, "_snapshot_state", snapshot_then_interrupt):+ with mock.patch.object(repl, "_send", sent.append):+ self._run_resuming(main())++ done = next(e for e in sent if e.get("event") == "done" and e["id"] == "snap")+ self.assertEqual(done["status"], "ok")+ self.assertEqual(done["saved"], ["small"])+ self.assertEqual(done["pruned"], ["big"])+ self.assertEqual(ns, {"small": 1})+ self.assertIsNone(repl._sigint_target)++ def test_untargeted_interrupt_in_done_task_handoff_is_not_parked(self):+ # The cell task is done but _run_guarded's finally has not run yet+ # (_active still names the rid, _finishing_rid is unset). An untargeted+ # interrupt in that handoff belongs to THIS request: it must be recorded+ # for its finishing phase, never parked where the next request eats it.+ import signal++ repl = self.repl_module++ class DoneTask:+ def done(self):+ return True++ def cancel(self):+ raise AssertionError("a done task must not be cancelled")++ repl._inflight.update({"handoff", "other"})+ repl._active.update({"task": DoneTask(), "rid": "handoff", "interrupted": False})+ previous = signal.signal(signal.SIGINT, repl._sigint_handler)+ self.addCleanup(signal.signal, signal.SIGINT, previous)+ repl._request_interrupt(None)+ deadline = time.monotonic() + 5+ while not repl._handoff_interrupted and time.monotonic() < deadline:+ time.sleep(0.01)+ self.assertEqual(repl._sigint_target, "handoff")+ self.assertFalse(repl._pending_interrupts["any"])+ self.assertTrue(repl._consume_handoff_interrupt())+ self.assertFalse(repl._handoff_interrupted)+ self.assertIn("other", repl._inflight)+++class SnapshotPruneShieldTest(unittest.TestCase):+ """The prune-deletion window must not be split by a SIGINT-raised KeyboardInterrupt."""++ def test_sigint_mid_prune_is_consumed_after_all_deletions_ran(self):+ import signal++ sys.path.insert(0, SRC)+ self.addCleanup(sys.path.remove, SRC)+ from rlm.repl import _snapshot_state++ class SigintOnFirstPop(dict):+ fired = False++ def pop(self, key, default=None):+ if not self.fired:+ self.fired = True+ # Synchronous SIGINT on the main thread: lands exactly mid-loop.+ signal.raise_signal(signal.SIGINT)+ return super().pop(key, default)++ ns = SigintOnFirstPop(big1=b"x" * 100_000, big2=b"y" * 100_000)+ with tempfile.TemporaryDirectory() as tmp:+ result = _snapshot_state(+ ns,+ os.path.join(tmp, "kernel-state.dill"),+ os.path.join(tmp, "kernel-state.json"),+ max_bytes=1 << 20,+ max_variable_bytes=1024,+ prune_oversized=True,+ )+ # The parked SIGINT is consumed: the committed snapshot reports success.+ self.assertEqual(result["pruned"], ["big1", "big2"])+ self.assertNotIn("error", result)+ # Both deletions ran: ns matches the manifest.+ self.assertEqual(dict(ns), {})++ def test_sigint_after_manifest_commit_before_deletions_is_consumed(self):+ import signal+ from unittest import mock++ sys.path.insert(0, SRC)+ self.addCleanup(sys.path.remove, SRC)+ from rlm.repl import _snapshot_state++ real_replace = os.replace++ ns = {"big1": b"x" * 100_000, "big2": b"y" * 100_000}+ with tempfile.TemporaryDirectory() as tmp:+ manifest_path = os.path.join(tmp, "kernel-state.json")++ def replace_then_sigint(src, dst):+ real_replace(src, dst)+ # Synchronous SIGINT right after the manifest commit, before any deletion.+ if dst == manifest_path:+ signal.raise_signal(signal.SIGINT)++ with mock.patch("os.replace", replace_then_sigint):+ result = _snapshot_state(+ ns,+ os.path.join(tmp, "kernel-state.dill"),+ manifest_path,+ max_bytes=1 << 20,+ max_variable_bytes=1024,+ prune_oversized=True,+ )+ # The parked SIGINT is consumed: the committed destructive snapshot+ # reports success instead of surfacing KeyboardInterrupt.+ self.assertEqual(result["pruned"], ["big1", "big2"])+ self.assertNotIn("error", result)+ # The deletions still ran: ns is consistent with the committed manifest.+ self.assertEqual(ns, {})+ with open(manifest_path) as fh:+ self.assertEqual(json.load(fh)["pruned"], ["big1", "big2"])+++class RestoreApplyShieldTest(unittest.TestCase):+ """The restore assignment loop must not be split by a SIGINT-raised KeyboardInterrupt."""++ def _write_snapshot(self, tmp: str, source: dict[str, object]) -> str:+ path = os.path.join(tmp, "kernel-state.dill")+ from rlm.repl import _snapshot_state++ result = _snapshot_state(+ source,+ path,+ os.path.join(tmp, "kernel-state.json"),+ max_bytes=1 << 20,+ max_variable_bytes=1 << 20,+ prune_oversized=False,+ )+ self.assertNotIn("error", result)+ return path++ def setUp(self):+ sys.path.insert(0, SRC)+ self.addCleanup(sys.path.remove, SRC)++ class SigintOnNthSet(dict):+ """Fires one synchronous SIGINT right after its Nth assignment."""++ def __init__(self, fire_on: int) -> None:+ super().__init__()+ self.fire_on = fire_on+ self.calls = 0++ def __setitem__(self, key, value):+ super().__setitem__(key, value)+ self.calls += 1+ if self.calls == self.fire_on:+ signal.raise_signal(signal.SIGINT)++ def test_sigint_during_staging_leaves_namespace_unchanged(self):+ import dill++ from rlm.repl import _restore_state++ real_loads = dill.loads+ calls = {"n": 0}++ def loads_then_sigint(blob):+ calls["n"] += 1+ if calls["n"] == 2:+ # Synchronous SIGINT mid-deserialize: nothing may have touched ns yet.+ signal.raise_signal(signal.SIGINT)+ return real_loads(blob)++ with tempfile.TemporaryDirectory() as tmp:+ path = self._write_snapshot(tmp, {"a": 1, "b": 2})+ ns = {"a": "old", "unrelated": "keep"}+ with mock.patch.object(dill, "loads", loads_then_sigint):+ with self.assertRaises(KeyboardInterrupt):+ _restore_state(ns, path)+ # The old namespace is byte-identical: no partial old/new mixture.+ self.assertEqual(ns, {"a": "old", "unrelated": "keep"})++ def test_sigint_mid_apply_is_consumed_and_all_names_applied(self):+ from rlm.repl import _restore_state++ with tempfile.TemporaryDirectory() as tmp:+ path = self._write_snapshot(tmp, {"a": 1, "b": 2})+ ns = self.SigintOnNthSet(fire_on=1)+ result = _restore_state(ns, path)+ # The parked SIGINT is consumed: the committed restore reports success.+ self.assertNotIn("error", result)+ self.assertEqual(result["restored"], ["a", "b"])+ self.assertEqual(dict(ns), {"a": 1, "b": 2})++ def test_sigint_after_last_apply_is_consumed(self):+ from rlm.repl import _restore_state++ with tempfile.TemporaryDirectory() as tmp:+ path = self._write_snapshot(tmp, {"a": 1, "b": 2})+ ns = self.SigintOnNthSet(fire_on=2)+ result = _restore_state(ns, path)+ self.assertNotIn("error", result)+ self.assertEqual(result["restored"], ["a", "b"])+ self.assertEqual(dict(ns), {"a": 1, "b": 2})++ def _restore_with_sigint_at_unpark(self):+ """Real unparking swap, then the newly restored handler fires immediately."""+ from rlm.repl import _restore_state++ real_signal = signal.signal+ state = {"calls": 0, "fired": False}++ def swap_then_fire(sig, handler):+ prev = real_signal(sig, handler)+ state["calls"] += 1+ if state["calls"] == 2:+ # A SIGINT delivered while parked but first seen after the swap+ # runs the restored raising handler inside _restore_state's tail.+ state["fired"] = True+ handler(sig, None)+ return prev++ committed: list = []+ with tempfile.TemporaryDirectory() as tmp:+ path = self._write_snapshot(tmp, {"a": 1, "b": 2})+ ns: dict = {}+ with mock.patch("signal.signal", swap_then_fire):+ with self.assertRaises(KeyboardInterrupt):+ _restore_state(ns, path, committed)+ self.assertTrue(state["fired"])+ return committed, ns++ def test_sigint_at_handler_restoration_publishes_committed_result(self):+ # Every binding is applied by unpark time: the KeyboardInterrupt escapes+ # this frame, but the filled box lets _handle_state report success.+ previous = signal.signal(signal.SIGINT, signal.default_int_handler)+ self.addCleanup(signal.signal, signal.SIGINT, previous)+ committed, ns = self._restore_with_sigint_at_unpark()+ self.assertEqual(committed[0]["restored"], ["a", "b"])+ self.assertEqual(ns, {"a": 1, "b": 2})+ self.assertIs(signal.getsignal(signal.SIGINT), signal.default_int_handler)++ def test_sigint_at_handler_restoration_with_non_default_prior_handler(self):+ fired = []++ def prior(signum, frame):+ fired.append(signum)+ raise KeyboardInterrupt++ previous = signal.signal(signal.SIGINT, prior)+ self.addCleanup(signal.signal, signal.SIGINT, previous)+ committed, ns = self._restore_with_sigint_at_unpark()+ self.assertEqual(committed[0]["restored"], ["a", "b"])+ self.assertEqual(ns, {"a": 1, "b": 2})+ self.assertEqual(fired, [signal.SIGINT])+ self.assertIs(signal.getsignal(signal.SIGINT), prior)++ def test_handler_restored_and_no_interrupt_bleed(self):+ from rlm.repl import _restore_state++ original = signal.getsignal(signal.SIGINT)+ with tempfile.TemporaryDirectory() as tmp:+ path = self._write_snapshot(tmp, {"a": 1, "b": 2})+ ns = self.SigintOnNthSet(fire_on=1)+ result = _restore_state(ns, path)+ self.assertNotIn("error", result)+ self.assertIs(signal.getsignal(signal.SIGINT), original)+ # Nothing parked bleeds into later work: a fresh SIGINT raises normally.+ with self.assertRaises(KeyboardInterrupt):+ signal.raise_signal(signal.SIGINT)+++class SnapshotTempCleanupTest(unittest.TestCase):+ def test_keyboard_interrupt_during_payload_write_removes_temp_file(self):+ from unittest import mock as unittest_mock++ sys.path.insert(0, SRC)+ self.addCleanup(sys.path.remove, SRC)+ import dill++ from rlm.repl import _snapshot_state++ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "kernel-state.dill")++ real_dump = dill.dump++ def interrupted_dump(payload, fh):+ if isinstance(payload, dict): # the complete payload, not a per-variable value+ fh.write(b"partial")+ raise KeyboardInterrupt+ return real_dump(payload, fh)++ with unittest_mock.patch.object(dill, "dump", interrupted_dump):+ with self.assertRaises(KeyboardInterrupt):+ _snapshot_state(+ {"x": 1},+ path,+ os.path.join(tmp, "manifest.json"),+ max_bytes=1 << 20,+ max_variable_bytes=1 << 20,+ prune_oversized=False,+ )+ self.assertEqual(os.listdir(tmp), []) # no temp (or final) files survive++ def test_name_deleted_by_background_thread_mid_snapshot_is_skipped(self):+ sys.path.insert(0, SRC)+ self.addCleanup(sys.path.remove, SRC)+ from rlm.repl import _snapshot_state++ class RacyNs(dict):+ # Simulates a background thread deleting "gone" between the key+ # listing and the per-name lookup.+ def keys(self):+ yield from ("gone", "kept")++ ns = RacyNs(kept=1)+ with tempfile.TemporaryDirectory() as tmp:+ result = _snapshot_state(+ ns,+ os.path.join(tmp, "kernel-state.dill"),+ os.path.join(tmp, "manifest.json"),+ max_bytes=1 << 20,+ max_variable_bytes=1 << 20,+ prune_oversized=False,+ )+ self.assertNotIn("error", result)+ self.assertEqual(result["saved"], ["kept"])+ self.assertEqual(result["skipped"], [{"name": "gone", "reason": "deleted during snapshot"}])++++class SnapshotPairConsistencyTest(unittest.TestCase):+ # Direct fault injection into _snapshot_state: portable and deterministic+ # (chmod-based injection breaks as root and has different Windows semantics).+ def setUp(self):+ sys.path.insert(0, SRC)+ self.addCleanup(sys.path.remove, SRC)+ from rlm.repl import _snapshot_state++ self.snapshot = _snapshot_state+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ self.dir = tmp.name+ self.path = os.path.join(self.dir, "kernel-state.dill")+ self.manifest_path = os.path.join(self.dir, "kernel-state.json")++ def _snap(self, ns, path=None, manifest_path=None, **kw):+ args = dict(max_bytes=1 << 20, max_variable_bytes=1 << 20, prune_oversized=False)+ args.update(kw)+ return self.snapshot(ns, path or self.path, manifest_path or self.manifest_path, **args)++ def _old_pair(self, path=None, manifest_path=None):+ self.assertNotIn("error", self._snap({"keep": 1}, path, manifest_path))+ with open(path or self.path, "rb") as fh:+ payload = fh.read()+ with open(manifest_path or self.manifest_path, "rb") as fh:+ manifest = fh.read()+ return payload, manifest++ def _assert_pair(self, old_payload, old_manifest, path=None, manifest_path=None):+ with open(path or self.path, "rb") as fh:+ self.assertEqual(fh.read(), old_payload)+ with open(manifest_path or self.manifest_path, "rb") as fh:+ self.assertEqual(fh.read(), old_manifest)++ def _assert_only_pair_files(self, directory=None):+ self.assertEqual(+ sorted(os.listdir(directory or self.dir)),+ ["kernel-state.dill", "kernel-state.json"],+ )++ def test_complete_payload_respects_aggregate_size_cap(self):+ name = "x" * 10_000+ result = self._snap({name: 1}, max_bytes=128, max_variable_bytes=128)+ self.assertEqual(result["saved"], [])+ self.assertEqual(result["skipped"], [{"name": name, "reason": "exceeds aggregate snapshot size cap"}])+ self.assertLessEqual(result["bytes"], 128)+ self._assert_only_pair_files()++ def test_near_cap_payload_skips_tail_instead_of_failing_snapshot(self):+ import dill++ dill.settings["recurse"] = True+ source = {"a": "first", "b": "second"}+ blobs = {name: dill.dumps(value) for name, value in source.items()}+ cap = len(dill.dumps(blobs)) - 1+ self.assertLessEqual(sum(map(len, blobs.values())), cap)+ self.assertLessEqual(len(dill.dumps({"a": blobs["a"]})), cap)++ result = self._snap(source, max_bytes=cap, max_variable_bytes=cap)+ self.assertEqual(result["saved"], ["a"])+ self.assertEqual(result["skipped"], [{"name": "b", "reason": "exceeds aggregate snapshot size cap"}])+ self.assertLessEqual(result["bytes"], cap)+ with open(self.path, "rb") as fh:+ self.assertEqual(list(dill.load(fh)), ["a"])++ def test_zero_size_cap_writes_no_empty_payload_overhead(self):+ result = self._snap({}, max_bytes=0, max_variable_bytes=0)+ self.assertEqual(result, {"error": "write failed: snapshot exceeds aggregate snapshot size cap"})+ self.assertEqual(os.listdir(self.dir), [])++ def test_manifest_write_failure_preserves_prior_pair(self):+ old_payload, old_manifest = self._old_pair()+ ns = {"keep": 1, "big": b"x" * 100_000}+ with mock.patch("json.dump", side_effect=OSError("disk full")):+ result = self._snap(ns, max_variable_bytes=1024, prune_oversized=True)+ self.assertTrue(result["error"].startswith("manifest write failed"))+ self._assert_pair(old_payload, old_manifest)+ self._assert_only_pair_files()+ self.assertIn("big", ns) # not pruned++ def test_payload_replace_failure_preserves_prior_pair(self):+ old_payload, old_manifest = self._old_pair()+ real_replace = os.replace++ def failing_replace(src, dst):+ if dst == self.path:+ raise OSError("rename failed")+ return real_replace(src, dst)++ with mock.patch("os.replace", failing_replace):+ result = self._snap({"keep": 2})+ self.assertTrue(result["error"].startswith("write failed"))+ self._assert_pair(old_payload, old_manifest)+ self._assert_only_pair_files()++ def test_payload_write_failure_returns_error_dict_and_cleans_temp(self):+ old_payload, old_manifest = self._old_pair()+ real_fdopen = os.fdopen++ class FailingWrite:+ def __init__(self, fh):+ self.fh = fh++ def __enter__(self):+ return self++ def __exit__(self, *args):+ self.fh.close()++ def write(self, data):+ raise OSError("disk full")++ def fdopen(fd, mode):+ fh = real_fdopen(fd, mode)+ return FailingWrite(fh) if mode == "wb" else fh++ with mock.patch("os.fdopen", side_effect=fdopen):+ result = self._snap({"keep": 2})+ self.assertTrue(result["error"].startswith("write failed"))+ self._assert_pair(old_payload, old_manifest)+ self._assert_only_pair_files()++ def test_keyboard_interrupt_between_stages_cleans_temps(self):+ old_payload, old_manifest = self._old_pair()+ with mock.patch("json.dump", side_effect=KeyboardInterrupt):+ with self.assertRaises(KeyboardInterrupt):+ self._snap({"keep": 2})+ self._assert_pair(old_payload, old_manifest)+ self._assert_only_pair_files()++ def test_sigint_after_payload_replace_is_parked_and_consumed(self):+ # SIGINT is parked from before the payload replace through the deletions.+ real_replace = os.replace+ ns = {"keep": 1, "big": b"x" * 100_000}++ def replace_then_sigint(src, dst):+ real_replace(src, dst)+ if dst == self.path:+ signal.raise_signal(signal.SIGINT)++ with mock.patch("os.replace", replace_then_sigint):+ result = self._snap(ns, max_variable_bytes=1024, prune_oversized=True)+ self.assertNotIn("error", result)+ self.assertEqual(result["pruned"], ["big"])+ self.assertNotIn("big", ns) # the prune still ran; the SIGINT was consumed+ self._assert_only_pair_files()+ with open(self.manifest_path) as fh:+ self.assertEqual(json.load(fh)["pruned"], ["big"])++ def test_signal_install_failure_propagates_and_cleans_temps(self):+ # A SIGINT-handler install failure (e.g. off-main-thread) must not leak temps.+ old_payload, old_manifest = self._old_pair()+ with mock.patch("signal.signal", side_effect=ValueError("main thread only")):+ with self.assertRaises(ValueError):+ self._snap({"keep": 2})+ self._assert_pair(old_payload, old_manifest)+ self._assert_only_pair_files()++ def test_fdopen_failure_closes_raw_fd_and_removes_temp(self):+ old_payload, old_manifest = self._old_pair()+ real_mkstemp = tempfile.mkstemp+ seen = {}++ def spy_mkstemp(**kwargs):+ seen["fd"], seen["name"] = real_mkstemp(**kwargs)+ return seen["fd"], seen["name"]++ with mock.patch("tempfile.mkstemp", spy_mkstemp):+ with mock.patch("os.fdopen", side_effect=OSError("bad fd")):+ result = self._snap({"keep": 2})+ self.assertTrue(result["error"].startswith("write failed"))+ with self.assertRaises(OSError):+ os.fstat(seen["fd"]) # the raw mkstemp fd was closed+ self.assertFalse(os.path.exists(seen["name"]))+ self._assert_pair(old_payload, old_manifest)+ self._assert_only_pair_files()++ def test_manifest_replace_failure_leaves_new_payload_old_manifest(self):+ # The documented unavoidable failure state between the two renames.+ old_payload, old_manifest = self._old_pair()+ ns = {"keep": 2, "big": b"x" * 100_000}+ real_replace = os.replace++ def failing_manifest_replace(src, dst):+ if dst == self.manifest_path:+ raise OSError("rename failed")+ return real_replace(src, dst)++ with mock.patch("os.replace", failing_manifest_replace):+ result = self._snap(ns, max_variable_bytes=1024, prune_oversized=True)+ self.assertTrue(result["error"].startswith("manifest write failed"))+ with open(self.path, "rb") as fh:+ self.assertNotEqual(fh.read(), old_payload) # new payload committed+ with open(self.manifest_path, "rb") as fh:+ self.assertEqual(fh.read(), old_manifest) # old manifest intact+ self._assert_only_pair_files()+ self.assertIn("big", ns) # not pruned++ def test_sigint_during_final_temp_cleanup_is_parked_and_consumed(self):+ # The handler must stay parked through discard_temps and restore last.+ original = signal.getsignal(signal.SIGINT)+ real_remove = os.remove+ fired = []+ ns = {"keep": 1, "big": b"x" * 100_000}++ def remove_then_sigint(name):+ if not fired:+ fired.append(name)+ signal.raise_signal(signal.SIGINT)+ return real_remove(name)++ with mock.patch("os.remove", remove_then_sigint):+ result = self._snap(ns, max_variable_bytes=1024, prune_oversized=True)+ self.assertNotIn("error", result) # no KeyboardInterrupt escaped+ self.assertEqual(result["pruned"], ["big"])+ self.assertNotIn("big", ns) # pruning completed+ self.assertTrue(fired) # the SIGINT really fired during cleanup+ self.assertIs(signal.getsignal(signal.SIGINT), original) # handler restored+ self._assert_only_pair_files()++ def test_cleanup_failure_still_restores_sigint_handler(self):+ # A non-OSError from cleanup (e.g. an audit hook) must not skip the restore.+ original = signal.getsignal(signal.SIGINT)+ with mock.patch("os.remove", side_effect=RuntimeError("audit hook")):+ with self.assertRaisesRegex(RuntimeError, "audit hook"):+ self._snap({"keep": 1})+ self.assertIs(signal.getsignal(signal.SIGINT), original)++ def test_aliased_temp_style_names_never_clobber_the_pair(self):+ # Regression: fixed path+'.tmp' temp names aliased the OTHER final path.+ layouts = (+ ("kernel-state.dill", "kernel-state.dill.tmp"), # manifest == payload + '.tmp'+ ("kernel-state.json.tmp", "kernel-state.json"), # payload == manifest + '.tmp'+ )+ for payload_name, manifest_name in layouts:+ with self.subTest(payload=payload_name, manifest=manifest_name):+ d = tempfile.mkdtemp(dir=self.dir)+ path = os.path.join(d, payload_name)+ manifest_path = os.path.join(d, manifest_name)+ old_payload, old_manifest = self._old_pair(path, manifest_path)+ with mock.patch("json.dump", side_effect=OSError("disk full")):+ result = self._snap({"keep": 2}, path, manifest_path)+ self.assertTrue(result["error"].startswith("manifest write failed"))+ self._assert_pair(old_payload, old_manifest, path, manifest_path)+ self.assertEqual(sorted(os.listdir(d)), sorted([payload_name, manifest_name]))+ # A plain success with aliased names must clobber neither file.+ self.assertNotIn("error", self._snap({"keep": 2}, path, manifest_path))+ with open(path, "rb") as fh:+ self.assertNotEqual(fh.read(), old_payload) # new payload committed+ with open(manifest_path) as fh:+ self.assertEqual(json.load(fh)["savedNames"], ["keep"])+ self.assertEqual(sorted(os.listdir(d)), sorted([payload_name, manifest_name]))+++class OwnerWatchdogTest(unittest.TestCase):+ def test_owner_watchdog_exits_busy_runtime(self):+ # The reproduced F4 scenario: stdin stays open (no EOF shutdown), a+ # synchronous cell monopolizes the loop, and only the watchdog thread+ # can notice the owner's death and exit the runtime.+ owner = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(300)"])+ try:+ repl = ReplProcess(env={"PRIME_AGENT_KERNEL_OWNER_PID": str(owner.pid)})+ self.addCleanup(repl.close)+ repl.ready()+ repl.send({"type": "execute", "id": "busy", "code": "while True: pass"})+ time.sleep(1.0) # let the busy cell start monopolizing the loop+ self.assertIsNone(repl.proc.poll())+ owner.kill()+ owner.wait(timeout=10)+ self.assertEqual(repl.proc.wait(timeout=15), 1)+ finally:+ if owner.poll() is None:+ owner.kill()+ owner.wait(timeout=10)++ def test_resolve_owner_pid_falls_back_to_ppid(self):+ sys.path.insert(0, SRC)+ self.addCleanup(sys.path.remove, SRC)+ import rlm.repl as repl_module++ with mock.patch.dict(os.environ, {"PRIME_AGENT_KERNEL_OWNER_PID": "4242"}):+ self.assertEqual(repl_module._resolve_owner_pid(), 4242)+ for raw in (None, "", "garbage", "0", "-7"):+ env = {} if raw is None else {"PRIME_AGENT_KERNEL_OWNER_PID": raw}+ with mock.patch.dict(os.environ, env, clear=False):+ if raw is None:+ os.environ.pop("PRIME_AGENT_KERNEL_OWNER_PID", None)+ self.assertEqual(repl_module._resolve_owner_pid(), os.getppid())++ def test_owner_watchdog_windows_waits_on_process_handle(self):+ sys.path.insert(0, SRC)+ self.addCleanup(sys.path.remove, SRC)+ import rlm.repl as repl_module++ from ctypes import wintypes++ calls: list[tuple] = []++ class FakeFunction:+ def __init__(self, name, result):+ self.name = name+ self.result = result+ self.argtypes = None+ self.restype = None++ def __call__(self, *args):+ calls.append((self.name, *args))+ return self.result++ class FakeKernel32:+ def __init__(self, open_result=1234):+ self.OpenProcess = FakeFunction("OpenProcess", open_result)+ self.WaitForSingleObject = FakeFunction("WaitForSingleObject", 0)+ self.CloseHandle = FakeFunction("CloseHandle", 1)++ k32 = FakeKernel32()+ with mock.patch.object(repl_module.ctypes, "WinDLL", create=True, return_value=k32):+ repl_module._wait_owner_windows(777)+ self.assertEqual(+ calls,+ [+ ("OpenProcess", 0x00100000, False, 777),+ ("WaitForSingleObject", 1234, 0xFFFFFFFF),+ ("CloseHandle", 1234),+ ],+ )+ self.assertEqual(k32.OpenProcess.argtypes, [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD])+ self.assertIs(k32.OpenProcess.restype, wintypes.HANDLE)+ self.assertEqual(k32.WaitForSingleObject.argtypes, [wintypes.HANDLE, wintypes.DWORD])+ self.assertIs(k32.WaitForSingleObject.restype, wintypes.DWORD)+ self.assertEqual(k32.CloseHandle.argtypes, [wintypes.HANDLE])+ self.assertIs(k32.CloseHandle.restype, wintypes.BOOL)++ calls.clear()+ with mock.patch.object(+ repl_module.ctypes, "WinDLL", create=True, return_value=FakeKernel32(open_result=0)+ ):+ repl_module._wait_owner_windows(778)+ self.assertEqual(calls, [("OpenProcess", 0x00100000, False, 778)])+++if __name__ == "__main__":+ unittest.main()diff --git a/prime-agent-runtime/uv.lock b/prime-agent-runtime/uv.lockindex d37c8bec89..8ddb052340 100644--- a/prime-agent-runtime/uv.lock+++ b/prime-agent-runtime/uv.lock@@ -29,24 +29,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" },]-[[package]]-name = "appnope"-version = "0.1.4"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/35/5d/752690df9ef5b76e169e68d6a129fa6d08a7100ca7f754c89495db3c6019/appnope-0.1.4.tar.gz", hash = "sha256:1de3860566df9caf38f01f86f65e0e13e379af54f9e4bee1e66b48f2efffd1ee", size = 4170, upload-time = "2024-02-06T09:43:11.258Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/81/29/5ecc3a15d5a33e31b26c11426c45c501e439cb865d0bff96315d86443b78/appnope-0.1.4-py2.py3-none-any.whl", hash = "sha256:502575ee11cd7a28c0205f379b525beefebab9d161b7c964670864014ed7213c", size = 4321, upload-time = "2024-02-06T09:43:09.663Z" },-]--[[package]]-name = "asttokens"-version = "3.0.2"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/25/1e/faf0f247f6f881b98fc4d6d07e14085cb89d13665084e6d6ac1dc2c03d0b/asttokens-3.0.2.tar.gz", hash = "sha256:3ecdbd8f2cc195f53ccada3a613538bb5f9ef6f6869129f13e03c30a677b8fe2", size = 63136, upload-time = "2026-07-12T03:31:49.084Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/d4/2b/04b8a15f3a1c77bc79ddf5c73875327f34b4fa75982df2b76e45e402d364/asttokens-3.0.2-py3-none-any.whl", hash = "sha256:9da13157f5b28becde0bd374fc677dcd3c290614264eff096f167c469cd9f933", size = 28702, upload-time = "2026-07-12T03:31:47.542Z" },-]-[[package]]name = "attrs"version = "26.1.0"@@ -175,15 +157,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },]-[[package]]-name = "comm"-version = "0.2.3"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/4c/13/7d740c5849255756bc17888787313b61fd38a0a8304fc4f073dfc46122aa/comm-0.2.3.tar.gz", hash = "sha256:2dc8048c10962d55d7ad693be1e7045d891b7ce8d999c97963a5e3e99c055971", size = 6319, upload-time = "2025-07-25T14:02:04.452Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/60/97/891a0971e1e4a8c5d2b20bbe0e524dc04548d2307fee33cdeba148fd4fc7/comm-0.2.3-py3-none-any.whl", hash = "sha256:c615d91d75f7f04f095b30d1c1711babd43bdc6419c1be9886a85f2f4e489417", size = 7294, upload-time = "2025-07-25T14:02:02.896Z" },-]-[[package]]name = "cryptography"version = "50.0.0"@@ -241,28 +214,12 @@ wheels = [][[package]]-name = "debugpy"-version = "1.8.21"+name = "dill"+version = "0.4.1"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/f2/aa/12037145b7a56eaa5b29b41872f7a21b538e807e13f32c4d3c46e59be084/debugpy-1.8.21.tar.gz", hash = "sha256:a3c53278e84c94e11bd87c53970ec391d1a67396c8b22609fcac576520e611a6", size = 1697577, upload-time = "2026-06-01T19:30:35.156Z" }+sdist = { url = "https://files.pythonhosted.org/packages/81/e1/56027a71e31b02ddc53c7d65b01e68edf64dea2932122fe7746a516f75d5/dill-0.4.1.tar.gz", hash = "sha256:423092df4182177d4d8ba8290c8a5b640c66ab35ec7da59ccfa00f6fa3eea5fa", size = 187315, upload-time = "2026-01-19T02:36:56.85Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/89/fb/cbf306d6e07a313a91e7171a98669054502840931432c227cfd505ee367f/debugpy-1.8.21-cp311-cp311-macosx_15_0_universal2.whl", hash = "sha256:da456226c7b4c69e35dbe35dcee6623d912000a77816db7856a41af1c72a0264", size = 2203120, upload-time = "2026-06-01T19:30:43.964Z" },- { url = "https://files.pythonhosted.org/packages/aa/57/aa739bd4ad2cbf96aeb1b20b56918ddd5ae4c28b68709bfcd327f02123ee/debugpy-1.8.21-cp311-cp311-manylinux_2_34_x86_64.whl", hash = "sha256:f68b891688e61bdc08b8d364d919ff0051e0b94657b39dcd027bc3173edb7cdc", size = 3059958, upload-time = "2026-06-01T19:30:45.622Z" },- { url = "https://files.pythonhosted.org/packages/a8/31/453d2c9a23d133fe2c8ec7ca1d816ded52a913487fe3ffef7c01b4b706af/debugpy-1.8.21-cp311-cp311-win32.whl", hash = "sha256:f843a8b08c2edeaf9b1582eed4f25441af21a297c22ff16bf76a662557aa9c9e", size = 5236515, upload-time = "2026-06-01T19:30:47.461Z" },- { url = "https://files.pythonhosted.org/packages/60/94/6660de2f2d7bf388f229335ba4637646eebabdbf38564cb439a95a9193c9/debugpy-1.8.21-cp311-cp311-win_amd64.whl", hash = "sha256:84c564d8cc701d41843b29a92814c1f1bef6798724ca9d675c284ad9f6a547d7", size = 5256138, upload-time = "2026-06-01T19:30:49.113Z" },- { url = "https://files.pythonhosted.org/packages/a2/df/bf625547431a9cadc9f4cbfeda38866e2b17f6aed147b625377e87834449/debugpy-1.8.21-cp312-cp312-macosx_15_0_universal2.whl", hash = "sha256:9f96713896f39c3dff0ee841f47320c3f2983d33c341e009361bb0ebc79adc4e", size = 2483609, upload-time = "2026-06-01T19:30:50.794Z" },- { url = "https://files.pythonhosted.org/packages/bf/09/59324b903599031ff9faaec1758292409f6561a0ec2492fe4b703327705a/debugpy-1.8.21-cp312-cp312-manylinux_2_34_x86_64.whl", hash = "sha256:c193d474f0a211191f2b4449d2d06157c689013035bd952f3b617e0ef422b176", size = 3968900, upload-time = "2026-06-01T19:30:52.341Z" },- { url = "https://files.pythonhosted.org/packages/14/cd/27f65b805d7fe005c44e1a36b9183ecdfbcdbf9d3e721a5115d461ecc7ee/debugpy-1.8.21-cp312-cp312-win32.whl", hash = "sha256:4743373c1cac7f9e74a1b9915bf1dbe0e900eca657ffb170ae07ac8363205ae9", size = 5336340, upload-time = "2026-06-01T19:30:54.047Z" },- { url = "https://files.pythonhosted.org/packages/77/1d/c84e30c0c674184948b66f076ab271c01d940618a2824c23cd035a27bc20/debugpy-1.8.21-cp312-cp312-win_amd64.whl", hash = "sha256:bd7ba9dd3daa7c2f942c6ca8d4695a16bf9ac16b63615261c7982bc74f7ed20c", size = 5374751, upload-time = "2026-06-01T19:30:55.891Z" },- { url = "https://files.pythonhosted.org/packages/77/6b/d817e1f8cc77aa055d37fba092e0febfdff40fe652d8d53d4cd7a86ad98d/debugpy-1.8.21-cp313-cp313-macosx_15_0_universal2.whl", hash = "sha256:13678151fc401e2d68c9880b91e28714f797d40422994572b24560ef80910a88", size = 2477398, upload-time = "2026-06-01T19:30:57.644Z" },- { url = "https://files.pythonhosted.org/packages/48/57/412421516afc3055fa577516f00beec3d663f9b0ab330639547ae6c57720/debugpy-1.8.21-cp313-cp313-manylinux_2_34_x86_64.whl", hash = "sha256:ecbd158386c31ffe71d46f72d44d56e66331ab9b16cad649156d514368f23ab2", size = 3962096, upload-time = "2026-06-01T19:30:59.235Z" },- { url = "https://files.pythonhosted.org/packages/c1/62/2c616337cf6ba7b07ebbc97f02c6c945a8e2f76b365e33ee809c32ee36d1/debugpy-1.8.21-cp313-cp313-win32.whl", hash = "sha256:2c2ae706dec41d99a9ca1f7ebc987a83e65578363be6f6b3ac9067504917fae1", size = 5336288, upload-time = "2026-06-01T19:31:00.79Z" },- { url = "https://files.pythonhosted.org/packages/f8/99/9175103392f84c4b1bf7622888cdc68da07f0ff7d9e581266428f6776033/debugpy-1.8.21-cp313-cp313-win_amd64.whl", hash = "sha256:aa648733047443eb1d07682c4ef287d36a54507b643ffdf38b09a3ef002c72a0", size = 5376567, upload-time = "2026-06-01T19:31:02.56Z" },- { url = "https://files.pythonhosted.org/packages/ce/3d/f4bbb323a548bfab2af3d6b4ffd9bf22636e55956a1285d317a1de643aad/debugpy-1.8.21-cp314-cp314-macosx_15_0_universal2.whl", hash = "sha256:9bb2a685287a2ac9b181cde89edcec64845cb51de7faaa75badb9a698bc24782", size = 2477209, upload-time = "2026-06-01T19:31:04.157Z" },- { url = "https://files.pythonhosted.org/packages/8c/2d/6e7ec524984a1702777868de49a4c53202bddac2a432a76a093469587750/debugpy-1.8.21-cp314-cp314-manylinux_2_34_x86_64.whl", hash = "sha256:3d6922439bf33fd38a3e2c447869ebc7b97da5cd3d329ff1ef9bc06c4903437e", size = 3927115, upload-time = "2026-06-01T19:31:05.863Z" },- { url = "https://files.pythonhosted.org/packages/97/47/d1aa6d64005a98a9144647d99306b419396f9ad7bf1d73c119e17a81fb4d/debugpy-1.8.21-cp314-cp314-win32.whl", hash = "sha256:15d4963bd5ffa48f0da0947fd06757fa7621945048a14ad7705431566d3c0e7c", size = 5336724, upload-time = "2026-06-01T19:31:07.711Z" },- { url = "https://files.pythonhosted.org/packages/5f/67/b905b90d163af11878c1af8abafa4a25206335e112e284e413454543a6da/debugpy-1.8.21-cp314-cp314-win_amd64.whl", hash = "sha256:fe0744a12353406de0ae8ccff0d0a4a666f00801a3db8fd04e7a5f761cd520e8", size = 5373803, upload-time = "2026-06-01T19:31:09.469Z" },- { url = "https://files.pythonhosted.org/packages/95/51/67e7cf11a53e40694f720457d5b3a1cdaaa3d5a9a633e482f225456b93ff/debugpy-1.8.21-py2.py3-none-any.whl", hash = "sha256:b1e37d333663c8851516a47364ef473da127f9caebe4417e6df6f5825a7e9a92", size = 5352888, upload-time = "2026-06-01T19:31:25.186Z" },+ { url = "https://files.pythonhosted.org/packages/1e/77/dc8c558f7593132cf8fefec57c4f60c83b16941c574ac5f619abb3ae7933/dill-0.4.1-py3-none-any.whl", hash = "sha256:1e1ce33e978ae97fcfcff5638477032b801c46c7c65cf717f95fbc2248f79a9d", size = 120019, upload-time = "2026-01-19T02:36:55.663Z" },][[package]]@@ -274,15 +231,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/a7/5f/ed01f9a3cdffbd5a008556fc7b2a08ddb1cc6ace7effa7340604b1d16699/docstring_parser-0.18.0-py3-none-any.whl", hash = "sha256:b3fcbed555c47d8479be0796ef7e19c2670d428d72e96da63f3a40122860374b", size = 22484, upload-time = "2026-04-14T04:09:18.638Z" },]-[[package]]-name = "executing"-version = "2.2.1"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/cc/28/c14e053b6762b1044f34a13aab6859bbf40456d37d23aa286ac24cfd9a5d/executing-2.2.1.tar.gz", hash = "sha256:3632cc370565f6648cc328b32435bd120a1e4ebb20c77e3fdde9a13cd1e533c4", size = 1129488, upload-time = "2025-09-01T09:48:10.866Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl", hash = "sha256:760643d3452b4d777d295bb167ccc74c64a81df23fb5e08eff250c425a4b2017", size = 28317, upload-time = "2025-09-01T09:48:08.5Z" },-]-[[package]]name = "h11"version = "0.16.0"@@ -340,76 +288,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/57/b0/0e52c878c53f245edd3a11020f20979b3f490f245af532c7cae3027754b5/idna-3.19-py3-none-any.whl", hash = "sha256:815e7be7a7806d54abb586dc943addc79e8b2ee16915059658cbeff4b1b43bf4", size = 68550, upload-time = "2026-08-18T05:14:22.343Z" },]-[[package]]-name = "ipykernel"-version = "7.3.0"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "appnope", marker = "sys_platform == 'darwin'" },- { name = "comm" },- { name = "debugpy" },- { name = "ipython" },- { name = "jupyter-client" },- { name = "jupyter-core" },- { name = "matplotlib-inline" },- { name = "nest-asyncio2" },- { name = "packaging" },- { name = "psutil" },- { name = "pyzmq" },- { name = "tornado" },- { name = "traitlets" },-]-sdist = { url = "https://files.pythonhosted.org/packages/3d/c4/e4a38f579de4225a561305666f7541cdabb30075def2aa1ac17bd73c1fb5/ipykernel-7.3.0.tar.gz", hash = "sha256:9acaaaf97d16355166e4085afe9d225bfbdf2b7ef520f9df3be8f2b248275e09", size = 184899, upload-time = "2026-06-10T08:41:25.481Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/3d/02/77b271f5dc58bfbc0b577c877b2365d1ffea2afe66a80c13f2312820348c/ipykernel-7.3.0-py3-none-any.whl", hash = "sha256:897eb64da762549ef610698fca5e9675195ec6ac8ec7f19d81ce1ca20c876057", size = 120583, upload-time = "2026-06-10T08:41:23.648Z" },-]--[[package]]-name = "ipython"-version = "9.16.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "colorama", marker = "sys_platform == 'win32'" },- { name = "ipython-pygments-lexers" },- { name = "jedi" },- { name = "matplotlib-inline" },- { name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },- { name = "prompt-toolkit" },- { name = "psutil", marker = "sys_platform != 'cygwin' and sys_platform != 'emscripten'" },- { name = "pygments" },- { name = "stack-data" },- { name = "traitlets" },- { name = "typing-extensions", marker = "python_full_version < '3.12'" },-]-sdist = { url = "https://files.pythonhosted.org/packages/06/96/b150fe7e25a5a29ae9ac1374e71488639605d39a1ea4abb74c9ce33af235/ipython-9.16.1.tar.gz", hash = "sha256:5a3d1f9a47ff216d6cf9cf863124f6a2c1a198d1354c546a4d24a370a283b64c", size = 4515302, upload-time = "2026-08-03T08:36:15.571Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/bc/8e/1239df488393d61076653bfb29f759d0f60cab8e030abdf7c17c31539b51/ipython-9.16.1-py3-none-any.whl", hash = "sha256:4acae635506f6d352d94c4899a19d5f85f8bc4d230932342dca556fdab1c69b4", size = 625974, upload-time = "2026-08-03T08:36:13.654Z" },-]--[[package]]-name = "ipython-pygments-lexers"-version = "1.1.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "pygments" },-]-sdist = { url = "https://files.pythonhosted.org/packages/ef/4c/5dd1d8af08107f88c7f741ead7a40854b8ac24ddf9ae850afbcf698aa552/ipython_pygments_lexers-1.1.1.tar.gz", hash = "sha256:09c0138009e56b6854f9535736f4171d855c8c08a563a0dcd8022f78355c7e81", size = 8393, upload-time = "2025-01-17T11:24:34.505Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/d9/33/1f075bf72b0b747cb3288d011319aaf64083cf2efef8354174e3ed4540e2/ipython_pygments_lexers-1.1.1-py3-none-any.whl", hash = "sha256:a9462224a505ade19a605f71f8fa63c2048833ce50abc86768a0d81d876dc81c", size = 8074, upload-time = "2025-01-17T11:24:33.271Z" },-]--[[package]]-name = "jedi"-version = "0.20.0"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "parso" },-]-sdist = { url = "https://files.pythonhosted.org/packages/46/b7/a3635f6a2d7cf5b5dd98064fc1d5fbbafcb25477bcea204a3a92145d158b/jedi-0.20.0.tar.gz", hash = "sha256:c3f4ccbd276696f4b19c54618d4fb18f9fc24b0aef02acf704b23f487daa1011", size = 3119416, upload-time = "2026-05-01T23:38:47.814Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/9a/93/242e2eab5fe682ffcb8b0084bde703a41d51e17ee0f3a31ff0d9d813620a/jedi-0.20.0-py2.py3-none-any.whl", hash = "sha256:7bdd9c2634f56713299976f4cbd59cb3fa92165cc5e05ea811fb253480728b67", size = 4884812, upload-time = "2026-05-01T23:38:43.919Z" },-]-[[package]]name = "jsonschema"version = "4.26.0"@@ -437,48 +315,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" },]-[[package]]-name = "jupyter-client"-version = "8.9.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "jupyter-core" },- { name = "python-dateutil" },- { name = "pyzmq" },- { name = "tornado" },- { name = "traitlets" },- { name = "typing-extensions" },-]-sdist = { url = "https://files.pythonhosted.org/packages/7d/dc/5512503b088997c2250b8bf18258fba9d9ce5ead641183700960d3c9d342/jupyter_client-8.9.1.tar.gz", hash = "sha256:a58f730dd9e728ba16ba1d62ebccf7ffe1ebbdbce4e95cfae941b7321ae1f4fa", size = 359256, upload-time = "2026-06-09T13:15:01.033Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/3f/6f/56d39bf385c5c27988aebaf0c18a2a17e960575740100973511018bd904e/jupyter_client-8.9.1-py3-none-any.whl", hash = "sha256:0b7a295bc46e8751e9adae84781f726c851c1d911bd793edc4a3bde942e3da81", size = 109828, upload-time = "2026-06-09T13:14:58.835Z" },-]--[[package]]-name = "jupyter-core"-version = "5.9.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "platformdirs" },- { name = "traitlets" },-]-sdist = { url = "https://files.pythonhosted.org/packages/02/49/9d1284d0dc65e2c757b74c6687b6d319b02f822ad039e5c512df9194d9dd/jupyter_core-5.9.1.tar.gz", hash = "sha256:4d09aaff303b9566c3ce657f580bd089ff5c91f5f89cf7d8846c3cdf465b5508", size = 89814, upload-time = "2025-10-16T19:19:18.444Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/e7/e7/80988e32bf6f73919a113473a604f5a8f09094de312b9d52b79c2df7612b/jupyter_core-5.9.1-py3-none-any.whl", hash = "sha256:ebf87fdc6073d142e114c72c9e29a9d7ca03fad818c5d300ce2adc1fb0743407", size = 29032, upload-time = "2025-10-16T19:19:16.783Z" },-]--[[package]]-name = "matplotlib-inline"-version = "0.2.2"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "traitlets" },-]-sdist = { url = "https://files.pythonhosted.org/packages/bd/c0/9f7c9a46090390368a4d7bcb76bb87a4a36c421e4c0792cdb53486ffac7a/matplotlib_inline-0.2.2.tar.gz", hash = "sha256:72f3fe8fce36b70d4a5b612f899090cd0401deddc4ea90e1572b9f4bfb058c79", size = 8150, upload-time = "2026-05-08T17:33:33.49Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/41/09/5b161152e2d90f7b87f781c2e1267494aef9c32498df793f73ad0a0a494a/matplotlib_inline-0.2.2-py3-none-any.whl", hash = "sha256:3c821cf1c209f59fb2d2d64abbf5b23b67bcb2210d663f9918dd851c6da1fcf6", size = 9534, upload-time = "2026-05-08T17:33:32.055Z" },-]-[[package]]name = "mcp"version = "2.0.0"@@ -517,24 +353,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/f5/4c/c78d78c3d52b0ac594ad7cc8ef5972adfe070e3597a8a4c6ce0cd39196ea/mcp_types-2.0.0-py3-none-any.whl", hash = "sha256:6b2de797ca2797f568b79529e1b25948e34de511bcc0bd82fef1039a6d1b8eb0", size = 69649, upload-time = "2026-07-28T13:45:30.713Z" },]-[[package]]-name = "nest-asyncio"-version = "1.6.0"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/83/f8/51569ac65d696c8ecbee95938f89d4abf00f47d58d48f6fbabfe8f0baefe/nest_asyncio-1.6.0.tar.gz", hash = "sha256:6f172d5449aca15afd6c646851f4e31e02c598d553a667e38cafa997cfec55fe", size = 7418, upload-time = "2024-01-21T14:25:19.227Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/a0/c4/c2971a3ba4c6103a3d10c4b0f24f461ddc027f0f09763220cf35ca1401b3/nest_asyncio-1.6.0-py3-none-any.whl", hash = "sha256:87af6efd6b5e897c81050477ef65c62e2b2f35d51703cae01aff2905b1852e1c", size = 5195, upload-time = "2024-01-21T14:25:17.223Z" },-]--[[package]]-name = "nest-asyncio2"-version = "1.7.2"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/b4/73/731debf26e27e0a0323d7bda270dc2f634b398e38f040a09da1f4351d0aa/nest_asyncio2-1.7.2.tar.gz", hash = "sha256:1921d70b92cc4612c374928d081552efb59b83d91b2b789d935c665fa01729a8", size = 14743, upload-time = "2026-02-13T00:34:04.386Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/c5/3c/3179b85b0e1c3659f0369940200cd6d0fa900e6cefcc7ea0bc6dd0e29ffb/nest_asyncio2-1.7.2-py3-none-any.whl", hash = "sha256:f5dfa702f3f81f6a03857e9a19e2ba578c0946a4ad417b4c50a24d7ba641fe01", size = 7843, upload-time = "2026-02-13T00:34:02.691Z" },-]-[[package]]name = "opentelemetry-api"version = "1.44.0"@@ -547,121 +365,28 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ca/6f/a04e900f465ff3221ccc395522503e2d10e79fa21f2723c8e177aae1e0d1/opentelemetry_api-1.44.0-py3-none-any.whl", hash = "sha256:94b98c893a91b88657eaac1e3ba89618cdb85be6918196705354f34728b2cdef", size = 60018, upload-time = "2026-07-16T15:25:11.657Z" },]-[[package]]-name = "packaging"-version = "26.3"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" },-]--[[package]]-name = "parso"-version = "0.8.7"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/30/4b/90c937815137d43ce71ba043cd3566221e9df6b9c805f24b5d138c9d40a7/parso-0.8.7.tar.gz", hash = "sha256:eaaac4c9fdd5e9e8852dc778d2d7405897ec510f2a298071453e5e3a07914bb1", size = 401824, upload-time = "2026-05-01T23:13:02.138Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/99/5d/8268b644392ee874ee82a635cd0df1773de230bde356c38de28e298392cc/parso-0.8.7-py2.py3-none-any.whl", hash = "sha256:a8926eb2a1b915486941fdbd31e86a4baf88fe8c210f25f2f35ecec5b574ca1c", size = 107025, upload-time = "2026-05-01T23:12:58.867Z" },-]--[[package]]-name = "pexpect"-version = "4.9.0"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "ptyprocess" },-]-sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772, upload-time = "2023-11-25T06:56:14.81Z" },-]--[[package]]-name = "platformdirs"-version = "4.11.3"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/b8/d7/e7bfbc86e9f99ff7807e24de7703f032e9c9ba80bb355cf26e0e9bc5a75e/platformdirs-4.11.3.tar.gz", hash = "sha256:66a73d38a849810252df809a3d8bcbda8e26f6c189920e7535ad608a48dbb5ab", size = 33050, upload-time = "2026-08-13T22:43:27.52Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/19/a9/c34aebedd3a4c9afe5101b1b8713710b3fec18087c8a36c35d2f909861bd/platformdirs-4.11.3-py3-none-any.whl", hash = "sha256:5ed065d443751de711da036041a7a214122efc4a4de393b3f4137ba5576540e7", size = 23491, upload-time = "2026-08-13T22:43:26.121Z" },-]-[[package]]name = "prime-agent-runtime"version = "0.1.0"source = { editable = "." }dependencies = [- { name = "ipykernel" },{ name = "mcp" },- { name = "nest-asyncio" },{ name = "tyro" },]+[package.dev-dependencies]+dev = [+ { name = "dill" },+]+[package.metadata]requires-dist = [- { name = "ipykernel" },{ name = "mcp", specifier = ">=2,<3" },- { name = "nest-asyncio" },{ name = "tyro" },]-[[package]]-name = "prompt-toolkit"-version = "3.0.53"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "wcwidth" },-]-sdist = { url = "https://files.pythonhosted.org/packages/7d/ea/39b988c938f75cb75d7045b5c69f8bfed47ee2152c8837fb403de29d6fb8/prompt_toolkit-3.0.53.tar.gz", hash = "sha256:9ec8a0ad96d5c56148b3f914aa79c1564c3fde5d2e6b876e7bc327e353cf8fa6", size = 435492, upload-time = "2026-07-26T20:56:14.758Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/54/6f/84908cad2d6aa5144abcf7b42709fe4fdb459bc640ec7ac5786e7693dabc/prompt_toolkit-3.0.53-py3-none-any.whl", hash = "sha256:01c0891d7f9237d5e339f7d3e42cdae80b7534abb1c7c0e3352efba6231492f2", size = 392288, upload-time = "2026-07-26T20:56:12.512Z" },-]--[[package]]-name = "psutil"-version = "7.2.2"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/51/08/510cbdb69c25a96f4ae523f733cdc963ae654904e8db864c07585ef99875/psutil-7.2.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:2edccc433cbfa046b980b0df0171cd25bcaeb3a68fe9022db0979e7aa74a826b", size = 130595, upload-time = "2026-01-28T18:14:57.293Z" },- { url = "https://files.pythonhosted.org/packages/d6/f5/97baea3fe7a5a9af7436301f85490905379b1c6f2dd51fe3ecf24b4c5fbf/psutil-7.2.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e78c8603dcd9a04c7364f1a3e670cea95d51ee865e4efb3556a3a63adef958ea", size = 131082, upload-time = "2026-01-28T18:14:59.732Z" },- { url = "https://files.pythonhosted.org/packages/37/d6/246513fbf9fa174af531f28412297dd05241d97a75911ac8febefa1a53c6/psutil-7.2.2-cp313-cp313t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1a571f2330c966c62aeda00dd24620425d4b0cc86881c89861fbc04549e5dc63", size = 181476, upload-time = "2026-01-28T18:15:01.884Z" },- { url = "https://files.pythonhosted.org/packages/b8/b5/9182c9af3836cca61696dabe4fd1304e17bc56cb62f17439e1154f225dd3/psutil-7.2.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:917e891983ca3c1887b4ef36447b1e0873e70c933afc831c6b6da078ba474312", size = 184062, upload-time = "2026-01-28T18:15:04.436Z" },- { url = "https://files.pythonhosted.org/packages/16/ba/0756dca669f5a9300d0cbcbfae9a4c30e446dfc7440ffe43ded5724bfd93/psutil-7.2.2-cp313-cp313t-win_amd64.whl", hash = "sha256:ab486563df44c17f5173621c7b198955bd6b613fb87c71c161f827d3fb149a9b", size = 139893, upload-time = "2026-01-28T18:15:06.378Z" },- { url = "https://files.pythonhosted.org/packages/1c/61/8fa0e26f33623b49949346de05ec1ddaad02ed8ba64af45f40a147dbfa97/psutil-7.2.2-cp313-cp313t-win_arm64.whl", hash = "sha256:ae0aefdd8796a7737eccea863f80f81e468a1e4cf14d926bd9b6f5f2d5f90ca9", size = 135589, upload-time = "2026-01-28T18:15:08.03Z" },- { url = "https://files.pythonhosted.org/packages/81/69/ef179ab5ca24f32acc1dac0c247fd6a13b501fd5534dbae0e05a1c48b66d/psutil-7.2.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:eed63d3b4d62449571547b60578c5b2c4bcccc5387148db46e0c2313dad0ee00", size = 130664, upload-time = "2026-01-28T18:15:09.469Z" },- { url = "https://files.pythonhosted.org/packages/7b/64/665248b557a236d3fa9efc378d60d95ef56dd0a490c2cd37dafc7660d4a9/psutil-7.2.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7b6d09433a10592ce39b13d7be5a54fbac1d1228ed29abc880fb23df7cb694c9", size = 131087, upload-time = "2026-01-28T18:15:11.724Z" },- { url = "https://files.pythonhosted.org/packages/d5/2e/e6782744700d6759ebce3043dcfa661fb61e2fb752b91cdeae9af12c2178/psutil-7.2.2-cp314-cp314t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1fa4ecf83bcdf6e6c8f4449aff98eefb5d0604bf88cb883d7da3d8d2d909546a", size = 182383, upload-time = "2026-01-28T18:15:13.445Z" },- { url = "https://files.pythonhosted.org/packages/57/49/0a41cefd10cb7505cdc04dab3eacf24c0c2cb158a998b8c7b1d27ee2c1f5/psutil-7.2.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e452c464a02e7dc7822a05d25db4cde564444a67e58539a00f929c51eddda0cf", size = 185210, upload-time = "2026-01-28T18:15:16.002Z" },- { url = "https://files.pythonhosted.org/packages/dd/2c/ff9bfb544f283ba5f83ba725a3c5fec6d6b10b8f27ac1dc641c473dc390d/psutil-7.2.2-cp314-cp314t-win_amd64.whl", hash = "sha256:c7663d4e37f13e884d13994247449e9f8f574bc4655d509c3b95e9ec9e2b9dc1", size = 141228, upload-time = "2026-01-28T18:15:18.385Z" },- { url = "https://files.pythonhosted.org/packages/f2/fc/f8d9c31db14fcec13748d373e668bc3bed94d9077dbc17fb0eebc073233c/psutil-7.2.2-cp314-cp314t-win_arm64.whl", hash = "sha256:11fe5a4f613759764e79c65cf11ebdf26e33d6dd34336f8a337aa2996d71c841", size = 136284, upload-time = "2026-01-28T18:15:19.912Z" },- { url = "https://files.pythonhosted.org/packages/e7/36/5ee6e05c9bd427237b11b3937ad82bb8ad2752d72c6969314590dd0c2f6e/psutil-7.2.2-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486", size = 129090, upload-time = "2026-01-28T18:15:22.168Z" },- { url = "https://files.pythonhosted.org/packages/80/c4/f5af4c1ca8c1eeb2e92ccca14ce8effdeec651d5ab6053c589b074eda6e1/psutil-7.2.2-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979", size = 129859, upload-time = "2026-01-28T18:15:23.795Z" },- { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560, upload-time = "2026-01-28T18:15:25.976Z" },- { url = "https://files.pythonhosted.org/packages/63/65/37648c0c158dc222aba51c089eb3bdfa238e621674dc42d48706e639204f/psutil-7.2.2-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e", size = 156997, upload-time = "2026-01-28T18:15:27.794Z" },- { url = "https://files.pythonhosted.org/packages/8e/13/125093eadae863ce03c6ffdbae9929430d116a246ef69866dad94da3bfbc/psutil-7.2.2-cp36-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8", size = 148972, upload-time = "2026-01-28T18:15:29.342Z" },- { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" },- { url = "https://files.pythonhosted.org/packages/b4/90/e2159492b5426be0c1fef7acba807a03511f97c5f86b3caeda6ad92351a7/psutil-7.2.2-cp37-abi3-win_amd64.whl", hash = "sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988", size = 137737, upload-time = "2026-01-28T18:15:33.849Z" },- { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" },-]--[[package]]-name = "ptyprocess"-version = "0.7.0"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/20/e5/16ff212c1e452235a90aeb09066144d0c5a6a8c0834397e03f5224495c4e/ptyprocess-0.7.0.tar.gz", hash = "sha256:5c5d0a3b48ceee0b48485e0c26037c0acd7d29765ca3fbb5cb3831d347423220", size = 70762, upload-time = "2020-12-28T15:15:30.155Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/22/a6/858897256d0deac81a172289110f31629fc4cee19b6f01283303e18c8db3/ptyprocess-0.7.0-py2.py3-none-any.whl", hash = "sha256:4b41f3967fce3af57cc7e94b888626c18bf37a083e3651ca8feeb66d492fef35", size = 13993, upload-time = "2020-12-28T15:15:28.35Z" },-]--[[package]]-name = "pure-eval"-version = "0.2.3"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/cd/05/0a34433a064256a578f1783a10da6df098ceaa4a57bbeaa96a6c0352786b/pure_eval-0.2.3.tar.gz", hash = "sha256:5f4e983f40564c576c7c8635ae88db5956bb2229d7e9237d03b3c0b0190eaf42", size = 19752, upload-time = "2024-07-21T12:58:21.801Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/8e/37/efad0257dc6e593a18957422533ff0f87ede7c9c6ea010a2177d738fb82f/pure_eval-0.2.3-py3-none-any.whl", hash = "sha256:1db8e35b67b3d218d818ae653e27f06c3aa420901fa7b081ca98cbedc874e0d0", size = 11842, upload-time = "2024-07-21T12:58:20.04Z" },-]+[package.metadata.requires-dev]+dev = [{ name = "dill" }][[package]]name = "pycparser"@@ -789,15 +514,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/4b/2d/69abac8f838090bbecd5df894befb2c2619e7996a98ddb949db9f3b93225/pydantic_core-2.46.4-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:d51026d73fcfd93610abc7b27789c26b313920fcfb20e27462d74a7f8b06e983", size = 2193071, upload-time = "2026-05-06T13:38:08.682Z" },]-[[package]]-name = "pygments"-version = "2.21.0"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" },-]-[[package]]name = "pyjwt"version = "2.13.0"@@ -812,18 +528,6 @@ crypto = [{ name = "cryptography" },]-[[package]]-name = "python-dateutil"-version = "2.9.0.post0"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "six" },-]-sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },-]-[[package]]name = "python-multipart"version = "0.0.32"@@ -855,64 +559,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/23/ed/4532e9388e65fa16b46776ef47ad631a64eda1631884488af707666350ed/pywin32-312-cp315-cp315-win_arm64.whl", hash = "sha256:a8597d28f267b39074aef51fa593530082b39cbe5a074226096857b1fed2dfb9", size = 6840337, upload-time = "2026-06-04T07:49:57.531Z" },]-[[package]]-name = "pyzmq"-version = "27.1.0"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "cffi", marker = "implementation_name == 'pypy'" },-]-sdist = { url = "https://files.pythonhosted.org/packages/04/0b/3c9baedbdf613ecaa7aa07027780b8867f57b6293b6ee50de316c9f3222b/pyzmq-27.1.0.tar.gz", hash = "sha256:ac0765e3d44455adb6ddbf4417dcce460fc40a05978c08efdf2948072f6db540", size = 281750, upload-time = "2025-09-08T23:10:18.157Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/06/5d/305323ba86b284e6fcb0d842d6adaa2999035f70f8c38a9b6d21ad28c3d4/pyzmq-27.1.0-cp311-cp311-macosx_10_15_universal2.whl", hash = "sha256:226b091818d461a3bef763805e75685e478ac17e9008f49fce2d3e52b3d58b86", size = 1333328, upload-time = "2025-09-08T23:07:45.946Z" },- { url = "https://files.pythonhosted.org/packages/bd/a0/fc7e78a23748ad5443ac3275943457e8452da67fda347e05260261108cbc/pyzmq-27.1.0-cp311-cp311-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:0790a0161c281ca9723f804871b4027f2e8b5a528d357c8952d08cd1a9c15581", size = 908803, upload-time = "2025-09-08T23:07:47.551Z" },- { url = "https://files.pythonhosted.org/packages/7e/22/37d15eb05f3bdfa4abea6f6d96eb3bb58585fbd3e4e0ded4e743bc650c97/pyzmq-27.1.0-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c895a6f35476b0c3a54e3eb6ccf41bf3018de937016e6e18748317f25d4e925f", size = 668836, upload-time = "2025-09-08T23:07:49.436Z" },- { url = "https://files.pythonhosted.org/packages/b1/c4/2a6fe5111a01005fc7af3878259ce17684fabb8852815eda6225620f3c59/pyzmq-27.1.0-cp311-cp311-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5bbf8d3630bf96550b3be8e1fc0fea5cbdc8d5466c1192887bd94869da17a63e", size = 857038, upload-time = "2025-09-08T23:07:51.234Z" },- { url = "https://files.pythonhosted.org/packages/cb/eb/bfdcb41d0db9cd233d6fb22dc131583774135505ada800ebf14dfb0a7c40/pyzmq-27.1.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:15c8bd0fe0dabf808e2d7a681398c4e5ded70a551ab47482067a572c054c8e2e", size = 1657531, upload-time = "2025-09-08T23:07:52.795Z" },- { url = "https://files.pythonhosted.org/packages/ab/21/e3180ca269ed4a0de5c34417dfe71a8ae80421198be83ee619a8a485b0c7/pyzmq-27.1.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:bafcb3dd171b4ae9f19ee6380dfc71ce0390fefaf26b504c0e5f628d7c8c54f2", size = 2034786, upload-time = "2025-09-08T23:07:55.047Z" },- { url = "https://files.pythonhosted.org/packages/3b/b1/5e21d0b517434b7f33588ff76c177c5a167858cc38ef740608898cd329f2/pyzmq-27.1.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e829529fcaa09937189178115c49c504e69289abd39967cd8a4c215761373394", size = 1894220, upload-time = "2025-09-08T23:07:57.172Z" },- { url = "https://files.pythonhosted.org/packages/03/f2/44913a6ff6941905efc24a1acf3d3cb6146b636c546c7406c38c49c403d4/pyzmq-27.1.0-cp311-cp311-win32.whl", hash = "sha256:6df079c47d5902af6db298ec92151db82ecb557af663098b92f2508c398bb54f", size = 567155, upload-time = "2025-09-08T23:07:59.05Z" },- { url = "https://files.pythonhosted.org/packages/23/6d/d8d92a0eb270a925c9b4dd039c0b4dc10abc2fcbc48331788824ef113935/pyzmq-27.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:190cbf120fbc0fc4957b56866830def56628934a9d112aec0e2507aa6a032b97", size = 633428, upload-time = "2025-09-08T23:08:00.663Z" },- { url = "https://files.pythonhosted.org/packages/ae/14/01afebc96c5abbbd713ecfc7469cfb1bc801c819a74ed5c9fad9a48801cb/pyzmq-27.1.0-cp311-cp311-win_arm64.whl", hash = "sha256:eca6b47df11a132d1745eb3b5b5e557a7dae2c303277aa0e69c6ba91b8736e07", size = 559497, upload-time = "2025-09-08T23:08:02.15Z" },- { url = "https://files.pythonhosted.org/packages/92/e7/038aab64a946d535901103da16b953c8c9cc9c961dadcbf3609ed6428d23/pyzmq-27.1.0-cp312-abi3-macosx_10_15_universal2.whl", hash = "sha256:452631b640340c928fa343801b0d07eb0c3789a5ffa843f6e1a9cee0ba4eb4fc", size = 1306279, upload-time = "2025-09-08T23:08:03.807Z" },- { url = "https://files.pythonhosted.org/packages/e8/5e/c3c49fdd0f535ef45eefcc16934648e9e59dace4a37ee88fc53f6cd8e641/pyzmq-27.1.0-cp312-abi3-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:1c179799b118e554b66da67d88ed66cd37a169f1f23b5d9f0a231b4e8d44a113", size = 895645, upload-time = "2025-09-08T23:08:05.301Z" },- { url = "https://files.pythonhosted.org/packages/f8/e5/b0b2504cb4e903a74dcf1ebae157f9e20ebb6ea76095f6cfffea28c42ecd/pyzmq-27.1.0-cp312-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3837439b7f99e60312f0c926a6ad437b067356dc2bc2ec96eb395fd0fe804233", size = 652574, upload-time = "2025-09-08T23:08:06.828Z" },- { url = "https://files.pythonhosted.org/packages/f8/9b/c108cdb55560eaf253f0cbdb61b29971e9fb34d9c3499b0e96e4e60ed8a5/pyzmq-27.1.0-cp312-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43ad9a73e3da1fab5b0e7e13402f0b2fb934ae1c876c51d0afff0e7c052eca31", size = 840995, upload-time = "2025-09-08T23:08:08.396Z" },- { url = "https://files.pythonhosted.org/packages/c2/bb/b79798ca177b9eb0825b4c9998c6af8cd2a7f15a6a1a4272c1d1a21d382f/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:0de3028d69d4cdc475bfe47a6128eb38d8bc0e8f4d69646adfbcd840facbac28", size = 1642070, upload-time = "2025-09-08T23:08:09.989Z" },- { url = "https://files.pythonhosted.org/packages/9c/80/2df2e7977c4ede24c79ae39dcef3899bfc5f34d1ca7a5b24f182c9b7a9ca/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_i686.whl", hash = "sha256:cf44a7763aea9298c0aa7dbf859f87ed7012de8bda0f3977b6fb1d96745df856", size = 2021121, upload-time = "2025-09-08T23:08:11.907Z" },- { url = "https://files.pythonhosted.org/packages/46/bd/2d45ad24f5f5ae7e8d01525eb76786fa7557136555cac7d929880519e33a/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:f30f395a9e6fbca195400ce833c731e7b64c3919aa481af4d88c3759e0cb7496", size = 1878550, upload-time = "2025-09-08T23:08:13.513Z" },- { url = "https://files.pythonhosted.org/packages/e6/2f/104c0a3c778d7c2ab8190e9db4f62f0b6957b53c9d87db77c284b69f33ea/pyzmq-27.1.0-cp312-abi3-win32.whl", hash = "sha256:250e5436a4ba13885494412b3da5d518cd0d3a278a1ae640e113c073a5f88edd", size = 559184, upload-time = "2025-09-08T23:08:15.163Z" },- { url = "https://files.pythonhosted.org/packages/fc/7f/a21b20d577e4100c6a41795842028235998a643b1ad406a6d4163ea8f53e/pyzmq-27.1.0-cp312-abi3-win_amd64.whl", hash = "sha256:9ce490cf1d2ca2ad84733aa1d69ce6855372cb5ce9223802450c9b2a7cba0ccf", size = 619480, upload-time = "2025-09-08T23:08:17.192Z" },- { url = "https://files.pythonhosted.org/packages/78/c2/c012beae5f76b72f007a9e91ee9401cb88c51d0f83c6257a03e785c81cc2/pyzmq-27.1.0-cp312-abi3-win_arm64.whl", hash = "sha256:75a2f36223f0d535a0c919e23615fc85a1e23b71f40c7eb43d7b1dedb4d8f15f", size = 552993, upload-time = "2025-09-08T23:08:18.926Z" },- { url = "https://files.pythonhosted.org/packages/60/cb/84a13459c51da6cec1b7b1dc1a47e6db6da50b77ad7fd9c145842750a011/pyzmq-27.1.0-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:93ad4b0855a664229559e45c8d23797ceac03183c7b6f5b4428152a6b06684a5", size = 1122436, upload-time = "2025-09-08T23:08:20.801Z" },- { url = "https://files.pythonhosted.org/packages/dc/b6/94414759a69a26c3dd674570a81813c46a078767d931a6c70ad29fc585cb/pyzmq-27.1.0-cp313-cp313-android_24_x86_64.whl", hash = "sha256:fbb4f2400bfda24f12f009cba62ad5734148569ff4949b1b6ec3b519444342e6", size = 1156301, upload-time = "2025-09-08T23:08:22.47Z" },- { url = "https://files.pythonhosted.org/packages/a5/ad/15906493fd40c316377fd8a8f6b1f93104f97a752667763c9b9c1b71d42d/pyzmq-27.1.0-cp313-cp313t-macosx_10_15_universal2.whl", hash = "sha256:e343d067f7b151cfe4eb3bb796a7752c9d369eed007b91231e817071d2c2fec7", size = 1341197, upload-time = "2025-09-08T23:08:24.286Z" },- { url = "https://files.pythonhosted.org/packages/14/1d/d343f3ce13db53a54cb8946594e567410b2125394dafcc0268d8dda027e0/pyzmq-27.1.0-cp313-cp313t-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:08363b2011dec81c354d694bdecaef4770e0ae96b9afea70b3f47b973655cc05", size = 897275, upload-time = "2025-09-08T23:08:26.063Z" },- { url = "https://files.pythonhosted.org/packages/69/2d/d83dd6d7ca929a2fc67d2c3005415cdf322af7751d773524809f9e585129/pyzmq-27.1.0-cp313-cp313t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d54530c8c8b5b8ddb3318f481297441af102517602b569146185fa10b63f4fa9", size = 660469, upload-time = "2025-09-08T23:08:27.623Z" },- { url = "https://files.pythonhosted.org/packages/3e/cd/9822a7af117f4bc0f1952dbe9ef8358eb50a24928efd5edf54210b850259/pyzmq-27.1.0-cp313-cp313t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f3afa12c392f0a44a2414056d730eebc33ec0926aae92b5ad5cf26ebb6cc128", size = 847961, upload-time = "2025-09-08T23:08:29.672Z" },- { url = "https://files.pythonhosted.org/packages/9a/12/f003e824a19ed73be15542f172fd0ec4ad0b60cf37436652c93b9df7c585/pyzmq-27.1.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c65047adafe573ff023b3187bb93faa583151627bc9c51fc4fb2c561ed689d39", size = 1650282, upload-time = "2025-09-08T23:08:31.349Z" },- { url = "https://files.pythonhosted.org/packages/d5/4a/e82d788ed58e9a23995cee70dbc20c9aded3d13a92d30d57ec2291f1e8a3/pyzmq-27.1.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:90e6e9441c946a8b0a667356f7078d96411391a3b8f80980315455574177ec97", size = 2024468, upload-time = "2025-09-08T23:08:33.543Z" },- { url = "https://files.pythonhosted.org/packages/d9/94/2da0a60841f757481e402b34bf4c8bf57fa54a5466b965de791b1e6f747d/pyzmq-27.1.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:add071b2d25f84e8189aaf0882d39a285b42fa3853016ebab234a5e78c7a43db", size = 1885394, upload-time = "2025-09-08T23:08:35.51Z" },- { url = "https://files.pythonhosted.org/packages/4f/6f/55c10e2e49ad52d080dc24e37adb215e5b0d64990b57598abc2e3f01725b/pyzmq-27.1.0-cp313-cp313t-win32.whl", hash = "sha256:7ccc0700cfdf7bd487bea8d850ec38f204478681ea02a582a8da8171b7f90a1c", size = 574964, upload-time = "2025-09-08T23:08:37.178Z" },- { url = "https://files.pythonhosted.org/packages/87/4d/2534970ba63dd7c522d8ca80fb92777f362c0f321900667c615e2067cb29/pyzmq-27.1.0-cp313-cp313t-win_amd64.whl", hash = "sha256:8085a9fba668216b9b4323be338ee5437a235fe275b9d1610e422ccc279733e2", size = 641029, upload-time = "2025-09-08T23:08:40.595Z" },- { url = "https://files.pythonhosted.org/packages/f6/fa/f8aea7a28b0641f31d40dea42d7ef003fded31e184ef47db696bc74cd610/pyzmq-27.1.0-cp313-cp313t-win_arm64.whl", hash = "sha256:6bb54ca21bcfe361e445256c15eedf083f153811c37be87e0514934d6913061e", size = 561541, upload-time = "2025-09-08T23:08:42.668Z" },- { url = "https://files.pythonhosted.org/packages/87/45/19efbb3000956e82d0331bafca5d9ac19ea2857722fa2caacefb6042f39d/pyzmq-27.1.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:ce980af330231615756acd5154f29813d553ea555485ae712c491cd483df6b7a", size = 1341197, upload-time = "2025-09-08T23:08:44.973Z" },- { url = "https://files.pythonhosted.org/packages/48/43/d72ccdbf0d73d1343936296665826350cb1e825f92f2db9db3e61c2162a2/pyzmq-27.1.0-cp314-cp314t-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:1779be8c549e54a1c38f805e56d2a2e5c009d26de10921d7d51cfd1c8d4632ea", size = 897175, upload-time = "2025-09-08T23:08:46.601Z" },- { url = "https://files.pythonhosted.org/packages/2f/2e/a483f73a10b65a9ef0161e817321d39a770b2acf8bcf3004a28d90d14a94/pyzmq-27.1.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7200bb0f03345515df50d99d3db206a0a6bee1955fbb8c453c76f5bf0e08fb96", size = 660427, upload-time = "2025-09-08T23:08:48.187Z" },- { url = "https://files.pythonhosted.org/packages/f5/d2/5f36552c2d3e5685abe60dfa56f91169f7a2d99bbaf67c5271022ab40863/pyzmq-27.1.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:01c0e07d558b06a60773744ea6251f769cd79a41a97d11b8bf4ab8f034b0424d", size = 847929, upload-time = "2025-09-08T23:08:49.76Z" },- { url = "https://files.pythonhosted.org/packages/c4/2a/404b331f2b7bf3198e9945f75c4c521f0c6a3a23b51f7a4a401b94a13833/pyzmq-27.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:80d834abee71f65253c91540445d37c4c561e293ba6e741b992f20a105d69146", size = 1650193, upload-time = "2025-09-08T23:08:51.7Z" },- { url = "https://files.pythonhosted.org/packages/1c/0b/f4107e33f62a5acf60e3ded67ed33d79b4ce18de432625ce2fc5093d6388/pyzmq-27.1.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:544b4e3b7198dde4a62b8ff6685e9802a9a1ebf47e77478a5eb88eca2a82f2fd", size = 2024388, upload-time = "2025-09-08T23:08:53.393Z" },- { url = "https://files.pythonhosted.org/packages/0d/01/add31fe76512642fd6e40e3a3bd21f4b47e242c8ba33efb6809e37076d9b/pyzmq-27.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:cedc4c68178e59a4046f97eca31b148ddcf51e88677de1ef4e78cf06c5376c9a", size = 1885316, upload-time = "2025-09-08T23:08:55.702Z" },- { url = "https://files.pythonhosted.org/packages/c4/59/a5f38970f9bf07cee96128de79590bb354917914a9be11272cfc7ff26af0/pyzmq-27.1.0-cp314-cp314t-win32.whl", hash = "sha256:1f0b2a577fd770aa6f053211a55d1c47901f4d537389a034c690291485e5fe92", size = 587472, upload-time = "2025-09-08T23:08:58.18Z" },- { url = "https://files.pythonhosted.org/packages/70/d8/78b1bad170f93fcf5e3536e70e8fadac55030002275c9a29e8f5719185de/pyzmq-27.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:19c9468ae0437f8074af379e986c5d3d7d7bfe033506af442e8c879732bedbe0", size = 661401, upload-time = "2025-09-08T23:08:59.802Z" },- { url = "https://files.pythonhosted.org/packages/81/d6/4bfbb40c9a0b42fc53c7cf442f6385db70b40f74a783130c5d0a5aa62228/pyzmq-27.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:dc5dbf68a7857b59473f7df42650c621d7e8923fb03fa74a526890f4d33cc4d7", size = 575170, upload-time = "2025-09-08T23:09:01.418Z" },- { url = "https://files.pythonhosted.org/packages/4c/c6/c4dcdecdbaa70969ee1fdced6d7b8f60cfabe64d25361f27ac4665a70620/pyzmq-27.1.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:18770c8d3563715387139060d37859c02ce40718d1faf299abddcdcc6a649066", size = 836265, upload-time = "2025-09-08T23:09:49.376Z" },- { url = "https://files.pythonhosted.org/packages/3e/79/f38c92eeaeb03a2ccc2ba9866f0439593bb08c5e3b714ac1d553e5c96e25/pyzmq-27.1.0-pp311-pypy311_pp73-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:ac25465d42f92e990f8d8b0546b01c391ad431c3bf447683fdc40565941d0604", size = 800208, upload-time = "2025-09-08T23:09:51.073Z" },- { url = "https://files.pythonhosted.org/packages/49/0e/3f0d0d335c6b3abb9b7b723776d0b21fa7f3a6c819a0db6097059aada160/pyzmq-27.1.0-pp311-pypy311_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:53b40f8ae006f2734ee7608d59ed661419f087521edbfc2149c3932e9c14808c", size = 567747, upload-time = "2025-09-08T23:09:52.698Z" },- { url = "https://files.pythonhosted.org/packages/a1/cf/f2b3784d536250ffd4be70e049f3b60981235d70c6e8ce7e3ef21e1adb25/pyzmq-27.1.0-pp311-pypy311_pp73-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f605d884e7c8be8fe1aa94e0a783bf3f591b84c24e4bc4f3e7564c82ac25e271", size = 747371, upload-time = "2025-09-08T23:09:54.563Z" },- { url = "https://files.pythonhosted.org/packages/01/1b/5dbe84eefc86f48473947e2f41711aded97eecef1231f4558f1f02713c12/pyzmq-27.1.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:c9f7f6e13dff2e44a6afeaf2cf54cee5929ad64afaf4d40b50f93c58fc687355", size = 544862, upload-time = "2025-09-08T23:09:56.509Z" },-]-[[package]]name = "referencing"version = "0.37.0"@@ -1050,15 +696,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/10/85/48f0abdcef5cce4e034c7a5b0ceeceba0b01bf0d942824f4bb720afe2dec/rpds_py-2026.6.3-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:8e65860d238379ed982fd9ba690579b5e95af2f4840f99c772816dbe573cb826", size = 586486, upload-time = "2026-06-30T07:17:51.141Z" },]-[[package]]-name = "six"-version = "1.17.0"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },-]-[[package]]name = "sse-starlette"version = "3.4.8"@@ -1072,20 +709,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/dd/3a/764912c58293d95b6dcdf4cc255f9d10de310580ced547b082eb9d72018c/sse_starlette-3.4.8-py3-none-any.whl", hash = "sha256:6e82314c786709a3cd9520f2285cf9fff90e181e598e8a357b0cf80f66afba0d", size = 16516, upload-time = "2026-08-05T11:19:48.748Z" },]-[[package]]-name = "stack-data"-version = "0.6.3"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "asttokens" },- { name = "executing" },- { name = "pure-eval" },-]-sdist = { url = "https://files.pythonhosted.org/packages/28/e3/55dcc2cfbc3ca9c29519eb6884dd1415ecb53b0e934862d3559ddcb7e20b/stack_data-0.6.3.tar.gz", hash = "sha256:836a778de4fec4dcd1dcd89ed8abff8a221f58308462e1c4aa2a3cf30148f0b9", size = 44707, upload-time = "2023-09-30T13:58:05.479Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl", hash = "sha256:d5558e0c25a4cb0853cddad3d77da9891a08cb85dd9f9f91b9f8cd66e511e695", size = 24521, upload-time = "2023-09-30T13:58:03.53Z" },-]-[[package]]name = "starlette"version = "1.6.0"@@ -1099,32 +722,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/c8/cb/6a6a47d5b464bd08695d254f3da6e7986cc70c9fa5d778eda57538edfe56/starlette-1.6.0-py3-none-any.whl", hash = "sha256:a86dd39d14bb45f85a3d18525215a9ef0cfd1f192ac793220e72598c90335f0c", size = 75969, upload-time = "2026-08-08T18:27:56.196Z" },]-[[package]]-name = "tornado"-version = "6.5.8"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/10/d3/343e5bb989d6515b1646cf3d40135d73f3d5e45339bded401b56cdac24dd/tornado-6.5.8.tar.gz", hash = "sha256:9452e1b208a8bd771e2cb1f2ff564985b9b214bdebbe622793e1799e0a6bd23f", size = 520493, upload-time = "2026-08-07T02:12:42.971Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/f2/d5/007086fd8df5489338e204f65adce33fd4f21a4999dbb2b9cff2f897b5f4/tornado-6.5.8-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:cc6aa787d7cfab7c3d35189dc7a56fbd2399a569624c730c6b55b3d6531d0403", size = 449487, upload-time = "2026-08-07T02:12:28.682Z" },- { url = "https://files.pythonhosted.org/packages/70/c8/5a24a99495903f594f6a199dd7beead1cbc0a13e2cb9102727bcaaf2a997/tornado-6.5.8-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:9715b5eb79735b2bcd454ce216a9275b7c0470e64ea1bf5742f78b2f72b26eeb", size = 447649, upload-time = "2026-08-07T02:12:30.306Z" },- { url = "https://files.pythonhosted.org/packages/6e/de/f2e733f386b85962d1b1dc82cd63d169b5b4580062b35397eac9244a41fe/tornado-6.5.8-cp39-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:547d63f450d570c14fe0e8db2cfb14c9bbd1c2503b4a6612586267955aa47b58", size = 450707, upload-time = "2026-08-07T02:12:31.95Z" },- { url = "https://files.pythonhosted.org/packages/0b/94/20efeee9a01c141e9ac47c397f81679dfda24b32768fc4fff24e76d36c2c/tornado-6.5.8-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7e2360a0ffbe145eca8af0b19cb7203d79b1a98dd4cccdd6b368f6f49c2e3808", size = 451677, upload-time = "2026-08-07T02:12:33.512Z" },- { url = "https://files.pythonhosted.org/packages/42/ec/a96ccb8ccf0de2b7bc2c5fa1608a4803735018242e90c4882365a9fd418f/tornado-6.5.8-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:5d242290bdf7ab3151bc1065fdd75c0dcc21cbc7b49f22a4c56329c2d6566d22", size = 451510, upload-time = "2026-08-07T02:12:35.346Z" },- { url = "https://files.pythonhosted.org/packages/29/b5/93185859245ad3f00e62175f29607346788b696369347f0146e0421286bb/tornado-6.5.8-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7b94ff0e128fe0542f3bd331fb44d06260fc4ac16881545159f34ef08aad4195", size = 450917, upload-time = "2026-08-07T02:12:36.963Z" },- { url = "https://files.pythonhosted.org/packages/97/cf/fe33cf062834487d34d1559746a4a12521033c22645b6d74d4bca702e018/tornado-6.5.8-cp39-abi3-win32.whl", hash = "sha256:67832909c4779c64942380cb5f044a5c6163d00831472d80e25e115de9917836", size = 451952, upload-time = "2026-08-07T02:12:38.512Z" },- { url = "https://files.pythonhosted.org/packages/cb/e1/468ad54333e92ccb62627e62cb88e5fc14a2171daa67ed47b1b8542d5b86/tornado-6.5.8-cp39-abi3-win_amd64.whl", hash = "sha256:11881db6b7c168494be2c2d12e65931451bdf7ee718535418ae1d8855dd5a0ee", size = 452391, upload-time = "2026-08-07T02:12:39.971Z" },- { url = "https://files.pythonhosted.org/packages/ad/3e/cd5e4f06e34cde33b8ef66cf36aa2b5ad46354cc1af7d2136bbe365fee1d/tornado-6.5.8-cp39-abi3-win_arm64.whl", hash = "sha256:68a7468c7e289f8514d7d664101753903217eff1bb6822c6b5994a0b5f5bcb26", size = 451411, upload-time = "2026-08-07T02:12:41.469Z" },-]--[[package]]-name = "traitlets"-version = "5.16.1"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/2c/2e/a7fbfe268c8a3b32546930c0297c101d65a4a14c304ad5790a9f478f0e4e/traitlets-5.16.1.tar.gz", hash = "sha256:ed900c2b631aa3a112811139fa97b8d2c3bad5e989656bba4b7e52c7852c18c1", size = 166137, upload-time = "2026-08-03T08:32:36.848Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/ad/66/0d785f0bc5e4315a96c989bb476d0fc07ea4f85132550c7b156ca2035d52/traitlets-5.16.1-py3-none-any.whl", hash = "sha256:f775618166caa0396c8e337099240f2bd3e5e917d203b2e6fbe21a58d3cb1f6b", size = 86211, upload-time = "2026-08-03T08:32:34.48Z" },-]-[[package]]name = "truststore"version = "0.10.4"@@ -1193,12 +790,3 @@ sdist = { url = "https://files.pythonhosted.org/packages/f2/0f/3f86e61397dd33bf2wheels = [{ url = "https://files.pythonhosted.org/packages/f1/79/4a20b54ab0491485ccd8c077db2d39187c7f12b3e15485d38a7be37c81b4/uvicorn-0.52.4-py3-none-any.whl", hash = "sha256:f86e41a149d7d05a9969337e3946a9c171c06a5d42680896daaba624aeac8da1", size = 79871, upload-time = "2026-08-19T06:27:40.36Z" },]--[[package]]-name = "wcwidth"-version = "0.8.2"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/34/74/c6428f875774288bec1396f5bfcbc2d925700a4dad61727fd5f2b12f249d/wcwidth-0.8.2.tar.gz", hash = "sha256:91fbef97204b96a3d4d421609b80340b760cf33e26da123ff243d76b1fda8dda", size = 1466253, upload-time = "2026-06-29T18:11:11.601Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/96/42/3e5985a0a7e57de470b320c6d6a1a67c844f6737a587f3d44dd13d1819e7/wcwidth-0.8.2-py3-none-any.whl", hash = "sha256:d63947694a0539a1d51e01eda7caf800c291020e6cdd7e28ad7b14dd33ad4f85", size = 323166, upload-time = "2026-06-29T18:11:09.888Z" },-]diff --git a/scripts/boot-bench.mjs b/scripts/boot-bench.mjsdeleted file mode 100644index de456de786..0000000000--- a/scripts/boot-bench.mjs+++ /dev/null@@ -1,97 +0,0 @@-#!/usr/bin/env node-/**- * Kernel boot fan-out benchmark. Boots N IPython kernels concurrently- * and reports boot success rate, per-kernel latency, peak RSS, and wall time.- *- * node scripts/boot-bench.mjs --mode forkserver --n 100- *- * Modes:- * ungated direct `python -m ipykernel_launcher`, no boot gate- * gated direct spawn through the boot-gate semaphore (today's default)- * forkserver fork each kernel from the pre-imported template (PRIME_AGENT_KERNEL_FORKSERVER=1)- *- * Also asserts a forked kernel is a real, reachable kernel (runs code over ZMQ)- * and that namespaces are isolated (a var set in kernel A is absent in kernel B).- *- * Requires the coding-agent package to be built (dist/). Run from the repo root.- */-import { readFileSync } from "node:fs";-import { join } from "node:path";-import { fileURLToPath } from "node:url";--const repoRoot = join(fileURLToPath(import.meta.url), "..", "..");-const kernelMod = join(repoRoot, "packages", "coding-agent", "dist", "core", "kernel", "index.js");-const bootstrapMod = join(repoRoot, "packages", "coding-agent", "dist", "core", "kernel", "bootstrap.js");-const bootGateMod = join(repoRoot, "packages", "coding-agent", "dist", "core", "kernel", "boot-gate.js");--function arg(name, def) {- const i = process.argv.indexOf(`--${name}`);- return i !== -1 ? process.argv[i + 1] : def;-}--const mode = arg("mode", "gated");-const n = Number(arg("n", 50)) || 50;--// Pin per-mode so the default-on forkserver doesn't leak into the direct-spawn modes.-process.env.PRIME_AGENT_KERNEL_FORKSERVER = mode === "forkserver" ? "1" : "0";--const { KernelManager } = await import(kernelMod);-const { ensureKernelPython } = await import(bootstrapMod);-const { withKernelBootPermit } = await import(bootGateMod);--function peakRssMb() {- // Sum Pss across the process tree if available (COW-aware); fall back to RSS.- return Math.round(process.memoryUsage().rss / 1024 / 1024);-}--function pct(sorted, p) {- if (!sorted.length) return 0;- const idx = Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length));- return Math.round(sorted[idx]);-}--async function bootOne(python) {- const m = new KernelManager({ python });- const started = performance.now();- const boot = () => m.start();- if (mode === "ungated") await boot();- else await withKernelBootPermit(boot);- const latency = performance.now() - started;- return { m, latency };-}--async function main() {- console.log(`mode=${mode} n=${n} platform=${process.platform}`);- const python = await ensureKernelPython({});-- const wallStart = performance.now();- const results = await Promise.allSettled(Array.from({ length: n }, () => bootOne(python)));- const wallMs = performance.now() - wallStart;-- const ok = results.filter((r) => r.status === "fulfilled");- const latencies = ok.map((r) => r.value.latency).sort((a, b) => a - b);- const managers = ok.map((r) => r.value.m);-- console.log(`booted: ${ok.length}/${n} (${Math.round((100 * ok.length) / n)}%)`);- console.log(`latency: p50=${pct(latencies, 50)}ms p90=${pct(latencies, 90)}ms max=${pct(latencies, 100)}ms`);- console.log(`wall: ${Math.round(wallMs)}ms`);- console.log(`rss: ${peakRssMb()}MB (node process only)`);-- const firstErr = results.find((r) => r.status === "rejected");- if (firstErr) console.log(`first error: ${firstErr.reason?.message ?? firstErr.reason}`);-- // Reachability + isolation check on the first two booted kernels.- if (managers.length >= 2) {- const [a, b] = managers;- const setA = await a.execute("bench_marker = 4387\nprint(bench_marker)");- const seeB = await b.execute("print('bench_marker' in dir())");- const reachable = setA.status === "ok" && setA.stdout.includes("4387");- const isolated = seeB.status === "ok" && /False/.test(seeB.stdout);- console.log(`reachable: ${reachable ? "yes" : "NO"} isolated: ${isolated ? "yes" : "NO"}`);- }-- await Promise.allSettled(managers.map((m) => m.dispose()));-}--await main();-process.exit(0);