diff --git a/.github/actions/test-python/action.yml b/.github/actions/test-python/action.yml new file mode 100644 index 0000000..f56a10f --- /dev/null +++ b/.github/actions/test-python/action.yml @@ -0,0 +1,35 @@ +name: Test one Python version +description: Run the kernel suite against one Python version and the selected JS host + +inputs: + python-version: + description: Python version for actions/setup-python + required: true + runtime-kind: + description: node or bun + required: true + +runs: + using: composite + steps: + - uses: actions/setup-python@v7 + with: + python-version: ${{ inputs.python-version }} + + - name: Report Python + shell: bash + run: python --version + + - name: Test under Node + if: inputs.runtime-kind == 'node' + shell: bash + run: npm test + env: + PI_PYTHON_TEST_INTERPRETER: python + + - name: Test under Bun + if: inputs.runtime-kind == 'bun' + shell: bash + run: npm run test:bun + env: + PI_PYTHON_TEST_INTERPRETER: python diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 89b182d..beb929d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,37 +15,124 @@ concurrency: jobs: check: - name: node ${{ matrix.node }} / python ${{ matrix.python }} - runs-on: ubuntu-latest + name: ${{ matrix.runtime.name }} / ${{ matrix.os }} + runs-on: ${{ matrix.os }} + timeout-minutes: 20 strategy: fail-fast: false matrix: - # Lower bound is what pi core requires; upper bound is current LTS. - node: ["22.19", "24"] - # Lower bound is the oldest interpreter runner.py supports. - python: ["3.9", "3.13"] + # The three hosted OS families, all on x64 so Python 3.9 is available + # (macos-latest is arm64 and has no Python 3.9 build). + os: [ubuntu-latest, macos-26-intel, windows-latest] + runtime: + # Node 22.19 is pi's minimum, 22.x is the current maintenance patch, + # 24.x is Active LTS, and 26.x is Current. + - { name: node-22.19, kind: node, version: "22.19" } + - { name: node-22.x, kind: node, version: "22.x" } + - { name: node-24.x, kind: node, version: "24.x" } + - { name: node-26.x, kind: node, version: "26.x" } + # Semver ranges select the latest patch in each modern Bun line. + - { name: bun-1.3.x, kind: bun, version: "1.3.x" } + - { name: bun-1.4.x, kind: bun, version: "1.4.x" } steps: - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 + - name: Set up Node + if: matrix.runtime.kind == 'node' + uses: actions/setup-node@v7 + with: + node-version: ${{ matrix.runtime.version }} + cache: npm + + # npm and tsc still use Node when Bun is the host under test. + - name: Set up Node for dependencies + if: matrix.runtime.kind == 'bun' + uses: actions/setup-node@v7 with: - node-version: ${{ matrix.node }} + node-version: "24.x" cache: npm - - uses: actions/setup-python@v7 + - name: Set up Bun + if: matrix.runtime.kind == 'bun' + uses: oven-sh/setup-bun@v2 with: - python-version: ${{ matrix.python }} + bun-version: ${{ matrix.runtime.version }} - # The kernel resolves `python3` from PATH when no override is set, - # so confirm the matrix leg's interpreter is the one under test. - - name: Report interpreter - run: python3 --version + - name: Report JS runtime + shell: bash + run: | + if [ "${{ matrix.runtime.kind }}" = "node" ]; then + node --version + else + bun --version + fi - run: npm ci - name: Typecheck run: npm run check - - name: Test - run: npm test + # Keep Python versions as steps rather than a matrix axis: this yields + # one check per JS runtime/OS pair (18 total), not 108 separate checks. + # continue-on-error lets every version run; the aggregate step below + # still fails the job if any one of them failed. + - id: py39 + name: Python 3.9 + continue-on-error: true + uses: ./.github/actions/test-python + with: { python-version: "3.9", runtime-kind: "${{ matrix.runtime.kind }}" } + - id: py310 + name: Python 3.10 + continue-on-error: true + uses: ./.github/actions/test-python + with: { python-version: "3.10", runtime-kind: "${{ matrix.runtime.kind }}" } + - id: py311 + name: Python 3.11 + continue-on-error: true + uses: ./.github/actions/test-python + with: { python-version: "3.11", runtime-kind: "${{ matrix.runtime.kind }}" } + - id: py312 + name: Python 3.12 + continue-on-error: true + uses: ./.github/actions/test-python + with: { python-version: "3.12", runtime-kind: "${{ matrix.runtime.kind }}" } + - id: py313 + name: Python 3.13 + continue-on-error: true + uses: ./.github/actions/test-python + with: { python-version: "3.13", runtime-kind: "${{ matrix.runtime.kind }}" } + - id: py314 + name: Python 3.14 + continue-on-error: true + uses: ./.github/actions/test-python + with: { python-version: "3.14", runtime-kind: "${{ matrix.runtime.kind }}" } + + - name: Require every Python version + if: always() + shell: bash + env: + PY39: ${{ steps.py39.outcome }} + PY310: ${{ steps.py310.outcome }} + PY311: ${{ steps.py311.outcome }} + PY312: ${{ steps.py312.outcome }} + PY313: ${{ steps.py313.outcome }} + PY314: ${{ steps.py314.outcome }} + run: | + printf '3.9=%s 3.10=%s 3.11=%s 3.12=%s 3.13=%s 3.14=%s\n' \ + "$PY39" "$PY310" "$PY311" "$PY312" "$PY313" "$PY314" + test "$PY39 $PY310 $PY311 $PY312 $PY313 $PY314" = \ + "success success success success success success" + + # Branch protection requires this stable context. It turns red unless all + # 18 runtime/OS jobs (and therefore all 108 combinations) succeeded. + gate: + name: CI gate + if: always() + needs: check + runs-on: ubuntu-latest + steps: + - name: Require the full matrix + env: + MATRIX_RESULT: ${{ needs.check.result }} + run: test "$MATRIX_RESULT" = success diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 37c4f4a..8a623f4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,7 +3,7 @@ ## Local setup ```bash -npm install +npm ci npm run check # tsc --noEmit npm test # drives a real PythonKernel, no mocks ``` @@ -23,26 +23,35 @@ pi -e ./index.ts * Node ≥ 22.19 (pi core's floor; the test script needs `--experimental-transform-types`). +* Bun ≥ 1.3 when using Bun as the TypeScript host. * Python ≥ 3.9 for `runner.py`, stdlib only. -CI runs the matrix ends: Node 22.19 and 24, each against Python 3.9 and -3.13. If you rely on a newer Python feature in `runner.py`, raise the floor -in the CI matrix, `README.md`, and this file in the same commit. +CI cross-products every claimed Python version (3.9–3.14), every modern +supported Node line (22, 24, 26, plus the exact 22.19 floor), Bun 1.3 and +1.4, and all three GitHub-hosted OS families (Linux, macOS, Windows): 108 +combinations. Python versions run sequentially inside each runtime/OS job, +so GitHub shows 18 matrix checks rather than 108. Python 3.9 remains +despite upstream EOL because it is still the documented floor. + +When changing a runtime floor or support range, update `package.json`, the +CI matrix, `README.md`, and this file together. ## Commit messages -[Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) are -required, because releases are generated from them. The type drives the -version bump and the changelog: +Commits landing on `main` must use [Conventional +Commits](https://www.conventionalcommits.org/en/v1.0.0/), because +release-please generates versions and changelogs from them. For squash +merges, the PR title becomes that commit message and must follow the +convention. The type drives the version bump and changelog section: | Prefix | Changelog section | Bump (pre-1.0) | | --- | --- | --- | -| `feat:` | Features | minor | +| `feat:` | Features | patch | | `fix:` | Bug Fixes | patch | | `perf:` | Performance | patch | | `refactor:` | Refactoring | patch | | `docs:` | Documentation | patch | -| `test:`, `build:`, `ci:`, `chore:` | hidden | patch | +| `test:`, `build:`, `ci:`, `chore:` | hidden | no release on their own | | any type with `!` or `BREAKING CHANGE:` | Breaking | minor while 0.x | Write the body for someone who has to touch the same code in a year. @@ -53,8 +62,9 @@ justified the change. The existing history is the style reference. `main` requires a PR (0 approvals — review is encouraged, not enforced for a project this size), a linear history, resolved conversations, and the -four CI legs passing. Force pushes and deletion are blocked. Admins are -not bound by the rules, deliberately: see the release caveat below. +`CI gate` check. That stable gate succeeds only when the entire dynamic +runtime/OS matrix passes. Force pushes and deletion are blocked. Admins +are not bound by the rules, deliberately: see the release caveat below. Because linear history is required, merge commits are disabled repo-wide. Squash and rebase merges both work. @@ -87,7 +97,7 @@ PR therefore shows a CI run stuck at `action_required` with no jobs, and the required checks never report. Two ways through: * Open the run in the Actions tab and click *Approve and run*, then merge - normally once the four legs pass. + normally once the full matrix and `CI gate` pass. * Or merge it as an admin, which the protection rules allow. Neither skips testing: the publish job re-runs the typecheck and the full @@ -95,7 +105,8 @@ kernel suite against the tagged commit before it publishes, so an unapproved release PR cannot ship untested code. Wiring a PAT into release-please would make checks run on its PR, at the -cost of a long-lived credential in the repository. Not worth it here. +cost of maintaining a long-lived repository secret. One explicit approval +per release is the simpler tradeoff here. ## What counts as breaking diff --git a/README.md b/README.md index 2f0dcc4..81a78aa 100644 --- a/README.md +++ b/README.md @@ -1,354 +1,287 @@ # pi-python -A pi extension that gives the agent a persistent Python execution -environment. +[![npm version](https://img.shields.io/npm/v/pi-python?color=cb3837&logo=npm)](https://www.npmjs.com/package/pi-python) +[![npm downloads](https://img.shields.io/npm/dm/pi-python?color=cb3837&logo=npm)](https://www.npmjs.com/package/pi-python) +[![CI](https://github.com/Luminger/pi-python/actions/workflows/ci.yml/badge.svg)](https://github.com/Luminger/pi-python/actions/workflows/ci.yml) +[![license](https://img.shields.io/npm/l/pi-python)](LICENSE) + +**An IPython-style Python session, made available as a tool to the +[pi](https://github.com/earendil-works/pi) coding agent.** + +pi-python gives the agent a notebook-style Python session instead of a sequence +of isolated `python -c` invocations. The agent submits cells to one long-lived +interpreter, sees streaming stdout and stderr plus the value of the final +expression, and keeps the resulting namespace for the next call. Imports, +variables, functions, classes, and live Python objects remain in memory while the +pi session continues. + +The interaction model is deliberately familiar: execute cells, inspect results, +refine the code, and continue from the current state. The difference is that the +agent operates the session through a tool rather than a human typing into an +IPython prompt or notebook UI. IPython itself is not a dependency; the runner +implements the relevant cell semantics on top of stock Python. -Spawns one long-lived `python3 -u` subprocess per pi session, lazily on -first use. Variables, imports, and definitions live in that process and -persist across tool calls for as long as it does. +```bash +pi install npm:pi-python +``` -The namespace is deliberately **not** persisted to disk. An earlier -version pickled the whole namespace after every call so kernel restarts -and `/tree` navigation could resurrect it; in practice the restores were -rarely useful, while the snapshots cost a full serialization per call and -grew to 80 GB across 421 sessions. Re-running the cells is cheaper and -more predictable. See *Known limitations*. +That is the only required step. The runner uses the Python standard library and +works with Python 3.9 or newer. The TypeScript side supports Node 22.19 or newer, +matching pi itself, and Bun 1.3 or newer. -## Tools the agent sees +> [!WARNING] +> **This gives the active LLM arbitrary Python execution as your user.** The +> model writes and invokes cells without per-cell approval and can do anything +> that user can do. See [Security](#security). -| Tool | What it does | -| ---- | ------------ | -| `python` | Run one or more Python cells in the persistent kernel. Variables, imports, and definitions persist across calls for the life of the kernel process. Default timeout 120s, max 3600s (configurable via `maxTimeoutSeconds`). On timeout the runner is SIGINT'd; the kernel catches KeyboardInterrupt and the namespace from any cells that completed before the interrupt survives. | -| `python_set_interpreter` | Switch the kernel to a different python interpreter binary (e.g. `/path/to/.venv/bin/python` or `python3.12`). Kills the current kernel and spawns a new one, so the namespace is wiped. | +## Persistence model -Both tools are registered with `executionMode: "sequential"` so the agent -never tries to run two cells (or a cell and an interpreter switch) -concurrently against the same kernel. +One pi session owns one Python process and one namespace. -There is intentionally **no** `python_reset` tool. If the agent needs a -clean namespace it can call `python_set_interpreter` with the same path -(which discards state by design), run `globals().clear()` in a cell, or -ask the user to `/python-restart`. +| Event | Namespace survives? | +| --- | --- | +| Another cell in the same `python` call | **Yes** | +| A later `python` call | **Yes** | +| An ordinary Python exception | **Yes** — mutations made before the exception remain | +| A timeout that reaches Python as `KeyboardInterrupt` | **Yes** | +| `/tree` navigation | **Yes** | +| `reset: true` on a `python` call | No | +| `/python-restart` | No | +| `python_set_interpreter` | No | +| Native crash or hard kill after ignored SIGINT | No | +| Quitting pi | No | -## Slash commands the user sees +A failed cell is not a transaction: Python keeps assignments and mutations made +before it raised. Later cells in the same call are skipped, but the next tool +call can inspect or continue from the state that remains. -| Command | What it does | -| ------- | ------------ | -| `/python-status` | Kernel info (executable, pid, cwd, alive) + active settings with their source. | -| `/python-restart` | Kill and respawn the kernel — interrupts a hung cell. The namespace is discarded; re-run the cells you still need. | +## What it provides -## CLI flags +- **Notebook-style cells** — cells run in order and the `repr()` of a trailing + expression is displayed. A failing cell stops the cells after it. +- **Live output** — stdout and stderr stream back while code runs. +- **Project-aware Python selection** — discovers `.venv` and `venv`, including + venvs at a uv-workspace or repository root. +- **Runtime interpreter switching** — the agent can move to another Python + binary when a task needs packages from a different environment. +- **Cooperative interruption** — timeouts send SIGINT first, preserving the + process and namespace when Python can raise `KeyboardInterrupt`. +- **Useful failure output** — if a genuinely wedged process must be killed, all + output captured before the kill is still returned. -``` ---python Override the interpreter pi-python should use. - Either an absolute path (/path/to/.venv/bin/python) or a - bare command name (python3.12) resolvable on PATH. - Smoke-tested at session_start; bad values are reported - and ignored (default resolution kicks in instead). -``` +## Using it -## How it works +### Agent tools -``` -┌──────────────┐ NDJSON over stdio ┌──────────────────┐ -│ pi (host) │ ──────────────────▶ │ python3 runner │ -│ index.ts │ ◀────────────────── │ runner.py │ -│ kernel.ts │ stream events │ (persistent ns) │ -│ settings.ts │ └──────────────────┘ -└──────────────┘ -``` +| Tool | Purpose | +| --- | --- | +| `python` | Run one or more cells in the persistent interpreter. Supports per-call timeout, namespace reset, and working-directory selection. | +| `python_set_interpreter` | Replace the kernel with one using a specific Python executable. This intentionally starts with an empty namespace. | -* **`runner.py`** — Python subprocess that reads NDJSON requests on stdin - (`execute`) and emits framed events on stdout. - User code that prints is captured by replacing `sys.stdout` / - `sys.stderr` with stream writers; control messages always go through - `sys.__stdout__`. -* **`kernel.ts`** — Owns the subprocess. Parses the NDJSON stream, supports - cancellation via `SIGINT`, respawns after a hard kill, exposes typed - `execute()`, and validates interpreter paths. -* **`settings.ts`** — Loader for `pi-python/settings.json` (global + - project) and the `PI_PYTHON_*` env vars. -* **`index.ts`** — Glue: registers the tools and slash commands, owns the - single kernel reference, and tears down on `session_shutdown`. - `session_tree` is deliberately *not* hooked — see *Known limitations*. - -Cells inside one `python` call run sequentially; if a cell raises, later -cells are skipped (Jupyter notebook semantics). The trailing expression -of a cell, if any, has its `repr()` shown — same as a notebook cell. - -## Interrupt model - -The kernel is designed to **survive timeouts**. SIGINT handling is -routed carefully so a runaway cell can be interrupted without taking -down the whole runner: - -* At startup the runner installs `SIG_IGN` for `SIGINT`. The main - loop, `sys.stdin` readline, and between-cell bookkeeping all ignore - the signal. -* During `_run_cell` only, the runner installs Python's default - `SIGINT` handler (which raises `KeyboardInterrupt`). On entry to - the next cell the previous handler is restored unconditionally so - a buggy cell can't un-protect the runner. -* `kernel.execute()` sends `SIGINT` when `timeoutMs` expires. The cell - catches it, the runner emits the usual `cell_end` + `done` events, - and the namespace stays intact. State established by cells that - completed before the interrupt is preserved in the live kernel, so a - follow-up call resumes from there. -* If the cell doesn't return within `interruptGraceMs` (default 30s, - configurable) the kernel is hard-killed as a last resort — this - catches genuinely wedged cases like a C extension that ignores - signals. A second SIGINT is sent halfway through the grace period - first — Python-level loops that swallowed the first one often act on - the repeat. -* **A hard kill is not an error.** The call resolves with `killed: true` - and every byte the cells printed before the hang, not an exception. - Losing a long sweep's findings because its last HTTP call wedged is - worse than losing the kernel. The namespace *is* gone — the result - says so explicitly so the next call knows to re-run its setup. - Set `interruptGraceMs: 0` to disable the auto-kill entirely (rely on - `/python-restart` for truly wedged kernels). - -**Implication for long-running work**: split big jobs into multiple -cells. State accrued in cells 0..N–1 survives a timeout in cell N, -so a follow-up `python` call can resume from where you left off. - -## Settings - -`pi-python` reads its own JSON settings file from two locations, -mirroring pi's own settings.json layout: +Two Python calls cannot run concurrently against one interpreter, so both tools +are serialized automatically. -``` -~/.pi/pi-python/settings.json (global) -/.pi/pi-python/settings.json (project, overrides global) -``` +### User commands -Both files are optional; missing fields fall back to the lower-precedence -source. Schema: +| Command | Purpose | +| --- | --- | +| `/python-status` | Show the executable, Python version, process ID, cwd, liveness, and active settings with their sources. | +| `/python-restart` | Kill and respawn the kernel with an empty namespace. Useful for a wedged process or an intentionally clean start. | -```jsonc -{ - // When auto-resolving the interpreter, walk from `cwd` upward looking - // for a venv. Stops at the first match, or at a `.git` repo root - // (never crosses repo boundaries). Default: true. - "venvParentWalk": true, +Start pi with an explicit interpreter when needed: - // Directory names checked at each level when auto-resolving the - // interpreter. A user-provided list FULLY OVERWRITES the default — - // setting `[".my-env"]` means *only* `.my-env` is searched, the - // defaults below are not appended. Set to `[]` to disable venv - // autodiscovery entirely. Default: [".venv", "venv"]. - "venvDirNames": [".venv", "venv"], - - // Upper bound (seconds) the `python` tool's `timeout` parameter is - // clamped to. Raise this if you have very long-running cells (data - // pulls, training, large aggregations). Default: 3600 (1 hour). - "maxTimeoutSeconds": 3600, - - // Grace period (milliseconds) after the timeout SIGINT before the - // kernel is hard-killed. The runner catches SIGINT and wraps up - // cleanly; SIGKILL only fires if the cell is genuinely wedged - // (e.g. a C extension that ignores signals). Set to 0 to disable - // the auto-kill entirely. Default: 30000. - "interruptGraceMs": 30000 -} +```bash +pi --python /path/to/.venv/bin/python +pi --python python3.12 ``` -Precedence (highest wins): env var → project file → global file → -built-in default. - -### Environment variable overrides +The flag is validated at startup. A bad path is reported and normal interpreter +resolution is used instead. -| Env var | Setting it overrides | -| ------- | -------------------- | -| `PI_PYTHON_VENV_PARENT_WALK` | `venvParentWalk` (boolean: `true`/`false`/`1`/`0`/`yes`/`no`/`on`/`off`) | -| `PI_PYTHON_VENV_DIR_NAMES` | `venvDirNames` (comma-separated; an explicitly-empty value disables autodiscovery; leave the env var unset to use the default) | -| `PI_PYTHON_MAX_TIMEOUT_SECONDS` | `maxTimeoutSeconds` (positive integer) | -| `PI_PYTHON_INTERRUPT_GRACE_MS` | `interruptGraceMs` (non-negative integer; 0 disables auto-kill) | -| `PI_PYTHON` | Default interpreter (same role as `--python`, lower precedence than the flag and `python_set_interpreter`) | +## Interpreter selection -## Interpreter resolution +Unless explicitly overridden, pi-python selects an interpreter in this order: -In order of priority: - -1. `python_set_interpreter` (if the agent has switched mid-session) -2. `--python ` CLI flag -3. `$PI_PYTHON` env var +1. The most recent `python_set_interpreter` selection +2. `--python ` +3. `$PI_PYTHON` 4. `$VIRTUAL_ENV/bin/python` -5. A venv directory named in `venvDirNames` (default: `.venv`, `venv`) - found in `cwd`. If `venvParentWalk` is true (default), the search - ascends from `cwd` until a venv is found or a `.git` repo root is - hit — useful for uv-workspace layouts where the venv lives at the - workspace root, not next to every member. +5. `.venv` or `venv` in the working directory or one of its parents, stopping + after checking the repository root 6. `python3` on `PATH` -`python_set_interpreter` and the `--python` flag both accept either an -absolute path to a binary or a bare command name on `PATH`. Directories -are rejected with a hint pointing at the binary path inside. - -## Security +This makes the common case automatic: start pi anywhere inside a repository and +its project venv is used. Both explicit selection mechanisms accept an absolute +or relative path to an executable, or a bare command name resolvable on `PATH`. +Directories are rejected with a hint pointing at the interpreter inside. -**This extension is not a security boundary.** It exists to run -LLM-generated code, and that code executes with your full user -privileges: your filesystem, your network, your SSH keys, your browser -profiles, your cloud credentials. There is no sandbox, no syscall -filter, and no allowlist. Run it only on code and in projects you would -be willing to run by hand. +## Timeouts and hard kills -As a shallow convenience measure, API-key-shaped env vars (`OPENAI_*`, -`ANTHROPIC_*`, `*_API_KEY`, `*_TOKEN`, `*_SECRET`, etc.) are stripped -from the subprocess environment. This is best-effort pattern matching -against accidental leakage into a tool result — it is trivially defeated -by a cell that reads `~/.config`, `~/.netrc`, or any credential file, and -it must not be relied on as a control against hostile code. +The default tool-call timeout is 120 seconds. The default ceiling is one hour, +and `maxTimeoutSeconds` can raise it for training, large data pulls, or expensive +analysis. -## Requirements +When a timeout expires: -* **Node** ≥ 22.19 (matches pi core; the test script additionally needs - Node's `--experimental-transform-types`). -* **Python** ≥ 3.9 for the runner. No third-party packages are required — - a stock interpreter is enough. +1. The host sends SIGINT. During cell execution, the runner maps it to + `KeyboardInterrupt`; outside a cell, SIGINT is ignored so bookkeeping cannot + accidentally kill the process. +2. If the cell has not returned halfway through `interruptGraceMs`, a second + SIGINT is sent. This catches Python loops or libraries that swallowed the + first one. +3. At the end of the grace period, the process is hard-killed as a last resort. + This is necessary for native extensions and blocking system calls that never + return control to Python. -## Install +A cooperative timeout keeps the namespace. A hard kill cannot, but the result is +marked `killed` and includes every byte printed before termination. Set +`interruptGraceMs` to `0` to disable automatic hard kills and rely on +`/python-restart` for wedged kernels. -```bash -pi install npm:pi-python -``` +On Windows, Node cannot deliver a catchable SIGINT to a child process. A timeout +therefore hard-kills the kernel immediately, preserving partial output but not +the namespace. -Or pin a version, which opts out of `pi update --extensions`: +For long work, use multiple cells: completed setup cells remain available if a +later cell times out. -```bash -pi install npm:pi-python@0.2.0 -``` +## Configuration -To try it for a single run without installing: +Optional settings are read from: -```bash -pi -e npm:pi-python +```text +~/.pi/pi-python/settings.json # global +/.pi/pi-python/settings.json # project, overrides global ``` -Then `/reload` inside pi (or restart). `/python-status` confirms it is -loaded; so does the `--python ` flag showing up in `pi --help`, -since this extension registers it. +Environment variables override project settings, which override global settings, +which override built-in defaults. + +```jsonc +{ + // Search parent directories for a venv, stopping at the repo root. + "venvParentWalk": true, -### From a clone + // Full replacement for the default [".venv", "venv"]. + // Use [] to disable venv directory discovery. + "venvDirNames": [".venv", "venv"], -The repo doubles as the extension package, so `npm install` here pulls in -the typings and dev tooling, and `npm run check` typechecks the TS -files. `npm test` runs the end-to-end interrupt/timeout suite (no mocks; -uses a real `PythonKernel`). + // Maximum timeout the agent may request, in seconds. + "maxTimeoutSeconds": 3600, -```bash -npm install -npm run check -npm test + // Delay between timeout SIGINT and the final hard kill, in milliseconds. + // Use 0 to disable automatic hard kills. + "interruptGraceMs": 30000 +} ``` -For pi to pick a clone up, place the directory under one of pi's -auto-discovery roots: +| Environment variable | Setting | +| --- | --- | +| `PI_PYTHON` | Default interpreter; below the CLI flag and runtime tool selection in precedence | +| `PI_PYTHON_VENV_PARENT_WALK` | `venvParentWalk`; accepts `true`/`false`, `1`/`0`, `yes`/`no`, or `on`/`off` | +| `PI_PYTHON_VENV_DIR_NAMES` | `venvDirNames` as a comma-separated list; an explicitly empty value disables discovery | +| `PI_PYTHON_MAX_TIMEOUT_SECONDS` | `maxTimeoutSeconds` as a positive integer | +| `PI_PYTHON_INTERRUPT_GRACE_MS` | `interruptGraceMs` as a non-negative integer | -```bash -# global (all projects) -ln -s "$(pwd)" ~/.pi/agent/extensions/pi-python +`/python-status` reports the effective value and source of every setting, plus +warnings for malformed configuration. -# or project-local -mkdir -p .pi/extensions -ln -s "$(pwd)" .pi/extensions/pi-python -``` +## Security -For one-off testing of a clone: +Installing pi-python delegates arbitrary Python execution to the active LLM. +The model supplies and invokes the code without per-cell approval. There is no +sandbox, and the Python process runs as your user with pi's environment. In +short: the model can do anything that user can do. -```bash -pi -e ./index.ts +If that authority is too broad, isolate pi at the OS level. See +[SECURITY.md](SECURITY.md) for the threat model and reporting policy. + +## How it works + +```text +┌──────────────┐ NDJSON over stdio ┌──────────────────┐ +│ pi (host) │ ──────────────────▶ │ python3 runner │ +│ index.ts │ ◀────────────────── │ runner.py │ +│ kernel.ts │ stream events │ persistent ns │ +│ settings.ts │ └──────────────────┘ +└──────────────┘ ``` -## Tool reference +- **`runner.py`** executes cells in the persistent namespace and emits framed + stdout, stderr, cell results, and completion events. Control messages always + use the original `sys.__stdout__`, so normal Python output cannot be confused + with protocol traffic. +- **`kernel.ts`** owns the subprocess, parses the event stream, handles timeout + escalation, preserves partial output on hard kills, and respawns dead kernels. +- **`settings.ts`** resolves global, project, and environment configuration. +- **`index.ts`** registers the tools, slash commands, CLI flag, rendering, and + session lifecycle hooks. + +The protocol deliberately needs only a stock Python interpreter — no IPython, +Jupyter server, or kernel gateway. The architecture is inspired by +[oh-my-pi's IPython runtime](https://github.com/can1357/oh-my-pi/blob/main/docs/python-repl.md), +with the gateway replaced by a small stdio protocol. -### `python` +## Known limitations -```ts -{ - cells: Array<{ code: string; title?: string }>; // ≥1 - timeout?: number; // seconds, default 120, clamped to 1..maxTimeoutSeconds (3600) - reset?: boolean; // drop the namespace before the first cell - cwd?: string; // working dir for this call -} +- **Text output only** — stdout, stderr, and `repr()` of a trailing expression. + There are no rich `image/png` or `text/markdown` display envelopes. +- **No interactive stdin** — `input()` is unsupported. Pass data through code, + variables, files, or tool parameters instead. +- **Raw file-descriptor output bypasses capture** — child processes writing + directly to fd 1 are not intercepted by the `sys.stdout` wrapper. + `subprocess.run(..., capture_output=True)` works normally. +- **One kernel per pi process** — kernels are not shared between separate pi + instances. +- **The namespace is process-local** — quitting, restarting, switching + interpreters, native crashes, and hard kills discard it. Persist important + results explicitly when they must outlive the session. +- **`/tree` does not rewind Python** — conversation history can move to another + branch while the interpreter retains everything executed before the move. Use + `/python-restart` when you want the process to match the visible transcript. + +
+Why the namespace is not checkpointed to disk + +An earlier version pickled the whole namespace after every call so restarts and +`/tree` navigation could restore it. The snapshots required a full serialization +on every call and grew to 80 GB across 421 sessions. Block-level analysis found +only 8% deduplication potential, so the growth was structural rather than a +compression problem. Restores were rarely useful, and many Python objects cannot +be safely serialized in the first place. Re-running setup cells is cheaper and +more predictable. + +
+ +## Development + +```bash +git clone git@github.com:Luminger/pi-python.git +cd pi-python +npm install +npm run check +npm test # Node host +npm run test:bun # Bun host ``` -Result includes per-cell stdout, stderr, last-expression value (when the -cell ends in a bare expression), and a formatted traceback for failures. -Output is truncated with `truncateTail` (50 KB / 2000 lines) so the LLM -sees the most recent output when runs are noisy. +The test suite drives real Python subprocesses and real signals; it does not mock +the behavior it is meant to verify. -### `python_set_interpreter` +Run the checkout directly for one session: -```ts -{ - path: string; // absolute path or bare PATH command name -} +```bash +pi -e ./index.ts ``` -Validates the path, kills the current kernel, spawns a new one with the -requested interpreter, and reports the resolved executable, version, and -new pid. Throws (with the validation error) if the path doesn't point at -a runnable interpreter. +Or install the checkout as a local pi package: -## Known limitations +```bash +pi install . +``` -* **No rich display** — only text stdout/stderr and `repr()` of trailing - expressions. No `image/png` / `text/markdown` envelopes (yet). -* **`input()` is not supported** — there is no interactive stdin. Pass - data through variables instead. -* **`subprocess` output via raw fd 1** — `subprocess.run(..., - capture_output=True)` works, but child processes that write directly - to fd 1 bypass our `sys.stdout` shadowing. -* **One kernel per pi process** — no shared gateway across multiple pi - instances. If you need that, the next step is binding the kernel to a - Unix socket per session file. -* **The namespace dies with the kernel.** `/python-restart`, - `python_set_interpreter`, a hard kill after an ignored SIGINT, and - quitting pi all discard it. This is a deliberate trade against the old - on-disk checkpointing; if you need state to outlive the process, write - it to a file from inside a cell. -* **`/tree` navigation does not touch the kernel.** Time travel rewinds - the conversation, not the interpreter — variables stay exactly as the - cells left them, so the namespace can legitimately contain things the - visible history hasn't produced yet. Use `/python-restart` when you - want the interpreter to match the rewound transcript. - -## Versioning and releases - -`0.x`, and staying there. Nothing here is a stability promise — tool -names, parameters, result formatting, and defaults change whenever a -better shape turns up. - -The agent-facing surface is the *cheapest* part to change, not the most -expensive. The model re-reads the tool schema every session; rename -`cells` to `blocks` tomorrow and it simply adapts. Nobody has code -calling this by hand, so treating tool signatures as an API contract -would be cargo-culting semver at a consumer that doesn't need it. - -What actually warrants a `!` / `BREAKING CHANGE:` trailer is anything -that silently breaks a working install: - -* `settings.json` keys and `PI_PYTHON_*` env vars being renamed or dropped -* a change in interpreter resolution order, so a different python gets picked -* raising the Node or Python floor -* a change to whether the namespace survives some event - -Version numbers exist so `pi update --extensions` has something to -compare, and so a bad release can be pinned around. Releases are -generated from [Conventional -Commits](https://www.conventionalcommits.org/en/v1.0.0/) by -release-please and published to npm from CI with trusted publishing, so -each one carries provenance. See [CONTRIBUTING.md](CONTRIBUTING.md) and -[CHANGELOG.md](CHANGELOG.md). +See [CONTRIBUTING.md](CONTRIBUTING.md) for commit conventions, branch protection, +and the release process. See [CHANGELOG.md](CHANGELOG.md) for release history. ## License MIT — see [LICENSE](LICENSE). - -The architecture is borrowed in spirit from -[oh-my-pi's IPython kernel runtime](https://github.com/can1357/oh-my-pi/blob/main/docs/python-repl.md), -with the heavy Jupyter Kernel Gateway replaced by a stdio NDJSON protocol -so this works with a stock Python install. (oh-my-pi's runtime offers an -interactive REPL too; pi-python intentionally does not.) diff --git a/SECURITY.md b/SECURITY.md index c2179ba..5772c64 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,54 +1,41 @@ # Security Policy -## Threat model, stated plainly - -pi-python exists to execute code written by a language model on your -machine. Arbitrary code execution is the **feature**, not a -vulnerability. The extension spawns a normal `python3` subprocess with -your user's privileges and pipes code into it. There is no sandbox, no -container, no seccomp filter, no import allowlist, and no filesystem -restriction. - -A cell can therefore read your SSH keys, exfiltrate data over the -network, delete files, and spawn further processes. This is inherent to -what the tool does. Use it only where you would be comfortable running -the same code by hand. - -The environment-variable filter in `kernel.ts` (`filterEnv`) strips -API-key-shaped variables from the subprocess environment. It exists to -reduce *accidental* credential leakage into a tool result that then goes -back to a model provider. It is pattern matching, it is best-effort, and -it is not a control against deliberately hostile code — anything that -reads a credential file bypasses it entirely. - -## What counts as a reportable vulnerability - -Because the above is by design, a report is in scope when the extension -does something a user could not reasonably expect, such as: - -* Code executing when no `python` tool call was made, or after the kernel - was supposed to be shut down. -* The kernel being spawned with a different interpreter than the one - resolution rules and `/python-status` report. -* Credentials or namespace contents being written somewhere not - documented (the extension deliberately persists nothing to disk). -* A crash or protocol confusion in the NDJSON framing that lets cell - output forge control messages to the host. -* Privilege escalation beyond the invoking user. - -Out of scope: "a cell can read `/etc/passwd`", "a cell can make network -requests", "the env filter can be bypassed by reading a file", and -similar restatements of the documented design. +## Threat model + +Installing pi-python gives the active LLM arbitrary code execution as the user +running pi. The model supplies and invokes the code without per-cell approval. +There is no sandbox, and the Python process inherits pi's environment unchanged. +The model can do anything that user can do. + +Model mistakes, prompt injection, and malicious instructions all operate within +that same authority. pi-python cannot make arbitrary model-driven execution safe +from inside the process being controlled. + +If this authority is too broad, restrict it outside pi-python: run pi under a +dedicated account, container, VM, sandbox, or other OS-level boundary. + +## What counts as a vulnerability + +Arbitrary execution through an accepted `python` tool call is the intended +capability. Reports are in scope when pi-python exceeds or misrepresents that +boundary—for example by executing without a corresponding tool call, crossing +session boundaries, using a different interpreter than reported, persisting or +transmitting cell data on its own, accepting forged protocol messages, or +escalating beyond the OS identity running pi. + +The fact that the model can exercise the authority of the user running pi, +including after prompt injection, is not a bypass in pi-python; it is the +documented security model. ## Reporting -Please report suspected vulnerabilities privately via GitHub's +Please report suspected vulnerabilities privately through GitHub's [security advisory form](https://github.com/Luminger/pi-python/security/advisories/new) rather than a public issue. -Include the pi version, the extension commit, your OS and Python version, -and a minimal reproduction. Expect an initial response within a couple of -weeks — this is a spare-time project, not a funded one. +Include the pi version, pi-python version or commit, OS and Python version, and a +minimal reproduction. Expect an initial response within a couple of weeks; this +is a spare-time project, not a funded service. ## Supported versions diff --git a/index.ts b/index.ts index 3c119c6..247c576 100644 --- a/index.ts +++ b/index.ts @@ -1,5 +1,5 @@ /** - * pi-python — exposes a persistent Python execution environment to the agent. + * pi-python — exposes a persistent, IPython-style Python session to the agent. * * Tools registered: * - python : execute one or more Python cells in a long-lived kernel @@ -113,23 +113,24 @@ export default function pythonExtension(pi: ExtensionAPI) { // call would just throw. Force the agent loop to serialize them. executionMode: "sequential", description: - "Execute Python code in a persistent interpreter session. " + - "Variables, imports, and definitions persist across calls in the same session, " + - "The namespace lives in the kernel process: it survives across tool calls and " + - "across cell timeouts, but not across /python-restart or a pi restart. " + + "Preferred tool for executing Python code. Run one or more cells in a persistent, " + + "IPython-style interpreter session instead of invoking python through bash. " + + "Variables, imports, functions, and live objects persist across calls in the same session. " + + "The namespace survives ordinary exceptions and cooperative cell timeouts, but not " + + "/python-restart, interpreter switching, a hard kill, or a pi restart. " + "Cells run sequentially; if a cell raises, later cells are skipped. " + `Default timeout is ${DEFAULT_TIMEOUT_S}s (cap ${DEFAULT_MAX_TIMEOUT_S}s by default, ` + "raise via project settings.json `maxTimeoutSeconds`); pass a higher `timeout` for " + - "long-running work. On timeout the cell is SIGINT'd \u2014 the runner catches " + - "KeyboardInterrupt cleanly and the namespace from cells that completed first " + - "survives for the next call. Use cells: [{code: '...'}].", + "long-running work. Use cells: [{code: '...'}].", promptSnippet: - "Run Python code in a persistent kernel for data wrangling, math, and parsing", + "Execute Python directly in a persistent IPython-style session; prefer this over running python through bash", promptGuidelines: [ - "Use python for non-trivial data transforms, JSON/CSV parsing, math, and stateful scratch work.", - "Use python with multiple cells when you want to inspect intermediate results without rerunning earlier setup.", - `Pass python's \`timeout\` parameter (in seconds, up to ${DEFAULT_MAX_TIMEOUT_S}) for long-running work like training, large IO, or expensive aggregations \u2014 the default of ${DEFAULT_TIMEOUT_S}s is tuned for interactive scratch work.`, - "Long cells that hit a timeout still preserve namespace state from any cells that completed first \u2014 you can resume work in a follow-up `python` call without restarting from scratch.", + "Prefer the python tool for all inline Python execution, including short one-offs. Do not use bash with `python -c`, a Python heredoc, or a temporary Python script when this tool can run the code directly.", + "Use bash instead only when invoking an existing Python script or CLI, testing fresh-process/startup behavior, or when shell pipelines and shell semantics are material to the task.", + "Reuse variables, imports, functions, and objects already present in the persistent kernel instead of rebuilding them in bash or another Python process.", + "Use multiple cells when you want to inspect intermediate results without rerunning earlier setup.", + `Pass python's \`timeout\` parameter (in seconds, up to ${DEFAULT_MAX_TIMEOUT_S} by default) for long-running work like training, large IO, or expensive aggregations \u2014 the default of ${DEFAULT_TIMEOUT_S}s is tuned for interactive work.`, + "After an ordinary exception or cooperative timeout, continue in the same kernel: state created before the failure remains available.", ], parameters: Type.Object({ cells: Type.Array( @@ -148,9 +149,9 @@ export default function pythonExtension(pi: ExtensionAPI) { description: `Wall-clock timeout in seconds for the whole call. Defaults to ${DEFAULT_TIMEOUT_S}s. ` + `Maximum is ${DEFAULT_MAX_TIMEOUT_S}s out of the box (1h), configurable per project via ` + - "settings.json `maxTimeoutSeconds`. On timeout the runner is SIGINT'd; the kernel " + - "catches KeyboardInterrupt and keeps the namespace, so any state populated by cells " + - "that completed before the interrupt survives.", + "settings.json `maxTimeoutSeconds`. On POSIX, timeout sends SIGINT and the kernel " + + "keeps state created before KeyboardInterrupt, including earlier statements in the " + + "interrupted cell. On Windows, timeout hard-kills the process and loses the namespace.", }), ), reset: Type.Optional( diff --git a/kernel.ts b/kernel.ts index 8cf5c7b..cc98885 100644 --- a/kernel.ts +++ b/kernel.ts @@ -10,38 +10,6 @@ import { fileURLToPath } from "node:url"; const RUNNER_PATH = join(dirname(fileURLToPath(import.meta.url)), "runner.py"); -/** Provider/secret env vars stripped before launching python. */ -const ENV_DENYLIST_PREFIXES = [ - "OPENAI_", - "ANTHROPIC_", - "GEMINI_", - "GOOGLE_API", - "GOOGLE_GENERATIVE", - "GROQ_", - "MISTRAL_", - "XAI_", - "DEEPSEEK_", - "COHERE_", - "PERPLEXITY_", - "TOGETHER_", - "FIREWORKS_", - "OPENROUTER_", - "AZURE_OPENAI", - "HUGGINGFACE_", - "HF_TOKEN", - "REPLICATE_", - "AWS_SECRET", - "AWS_SESSION", -]; - -const ENV_DENYLIST_EXACT = new Set([ - "GITHUB_TOKEN", - "GH_TOKEN", - "NPM_TOKEN", - "NPM_PASSWORD", - "PI_API_KEY", -]); - export interface CellRequest { code: string; title?: string; @@ -106,6 +74,7 @@ interface PendingRequest { } export class PythonKernel { + private readonly options: KernelOptions; private proc: ChildProcessWithoutNullStreams | null = null; private buffer = ""; private pending: PendingRequest | null = null; @@ -116,7 +85,9 @@ export class PythonKernel { private exitReason: string | null = null; private nextRequestId = 1; - constructor(private readonly options: KernelOptions) {} + constructor(options: KernelOptions) { + this.options = options; + } getInfo(): KernelInfo | null { return this.readyInfo; @@ -137,9 +108,10 @@ export class PythonKernel { if (this.readyInfo) return this.readyInfo; if (this.readyPromise) return this.readyPromise; - const env = filterEnv(this.options.env ?? process.env); - // Make sure cwd ends up in sys.path (runner does this too, belt + braces). - env.PYTHONUNBUFFERED = "1"; + // Python is a first-class execution environment, not a sandbox. Inherit + // the host environment unchanged so project tooling and credentials work + // exactly as they do from the user's shell. + const env = { ...(this.options.env ?? process.env), PYTHONUNBUFFERED: "1" }; const proc = spawn(this.options.pythonPath, ["-u", RUNNER_PATH], { cwd: this.options.cwd, @@ -497,8 +469,16 @@ export class PythonKernel { } } - /** Send SIGINT to interrupt the currently running cell. */ + /** Interrupt the current cell, preserving the kernel where the OS permits it. */ interrupt(): void { + // Node cannot deliver a catchable SIGINT to a Windows child: kill("SIGINT") + // terminates it outright and the exit event rejects the request before we can + // return a useful result. Make that unavoidable hard kill explicit instead, + // preserving partial output and reporting `killed: true` consistently. + if (process.platform === "win32") { + this.kill(); + return; + } if (this.proc && this.proc.exitCode === null) { try { this.proc.kill("SIGINT"); @@ -561,21 +541,6 @@ export class PythonKernel { } } -/** Build the env handed to the python subprocess, stripping likely secrets. */ -export function filterEnv(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv { - const out: NodeJS.ProcessEnv = {}; - for (const [key, value] of Object.entries(source)) { - if (value === undefined) continue; - if (ENV_DENYLIST_EXACT.has(key)) continue; - if (ENV_DENYLIST_PREFIXES.some((prefix) => key.startsWith(prefix))) continue; - if (/_API_KEY$/i.test(key)) continue; - if (/_SECRET$/i.test(key)) continue; - if (/_TOKEN$/i.test(key)) continue; - out[key] = value; - } - return out; -} - /** * Resolve which python interpreter to use. * diff --git a/package-lock.json b/package-lock.json index acef60c..d7f4b7b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,6 +7,7 @@ "": { "name": "pi-python", "version": "0.3.1", + "license": "MIT", "devDependencies": { "@earendil-works/pi-coding-agent": "^0.84.2", "@earendil-works/pi-tui": "^0.84.2", @@ -14,9 +15,14 @@ "typebox": "^1.1.0", "typescript": "^5.6.0" }, + "engines": { + "bun": ">=1.3.0", + "node": ">=22.19.0" + }, "peerDependencies": { "@earendil-works/pi-coding-agent": "*", - "@earendil-works/pi-tui": "*" + "@earendil-works/pi-tui": "*", + "typebox": "*" } }, "node_modules/@earendil-works/pi-coding-agent": { diff --git a/package.json b/package.json index 19c4ee2..47dc763 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "pi-python", "version": "0.3.1", "type": "module", - "description": "pi extension that exposes a persistent Python execution environment to the agent", + "description": "Persistent IPython-style Python session for the pi coding agent", "license": "MIT", "author": "Simon Brakhane ", "repository": { @@ -18,6 +18,8 @@ "pi-package", "pi-extension", "python", + "ipython", + "notebook", "repl", "kernel" ], @@ -31,7 +33,8 @@ "CHANGELOG.md" ], "engines": { - "node": ">=22.19.0" + "node": ">=22.19.0", + "bun": ">=1.3.0" }, "pi": { "extensions": [ @@ -40,7 +43,8 @@ }, "scripts": { "check": "tsc --noEmit", - "test": "node --experimental-transform-types --no-warnings test-interrupt.ts" + "test": "node --no-warnings test-interrupt.ts", + "test:bun": "bun test-interrupt.ts" }, "peerDependencies": { "@earendil-works/pi-coding-agent": "*", diff --git a/test-interrupt.ts b/test-interrupt.ts index 3ef3ab1..ffafb4b 100644 --- a/test-interrupt.ts +++ b/test-interrupt.ts @@ -1,7 +1,9 @@ /** * End-to-end test for SIGINT-safe kernel behaviour. * - * Drives a real PythonKernel through the relevant failure scenarios: + * Drives a real PythonKernel through the relevant failure scenarios and + * verifies that the selected interpreter receives the host environment + * unchanged: * 0. An ordinary Python exception is reported as a cell failure without * killing the kernel. State created before the exception — including * mutations earlier in the failed cell itself — remains available. @@ -35,13 +37,30 @@ function check(condition: boolean, label: string): void { } async function main(): Promise { - const k = new PythonKernel({ pythonPath: "python3", cwd: process.cwd() }); + const envMarker = "inherited-from-pi-host"; + const pythonPath = process.env.PI_PYTHON_TEST_INTERPRETER ?? + (process.platform === "win32" ? "python.exe" : "python3"); + const k = new PythonKernel({ + pythonPath, + cwd: process.cwd(), + env: { ...process.env, PI_PYTHON_ENV_INHERITANCE_TEST: envMarker }, + }); await k.start(); const initialPid = k.getInfo()?.pid; if (!initialPid) throw new Error("no initial pid"); console.log(`kernel up (pid ${initialPid})`); try { + console.log("\n[env] host environment is inherited unchanged"); + const inheritedEnv = await k.execute( + [{ code: "import os\nos.environ['PI_PYTHON_ENV_INHERITANCE_TEST']" }], + { timeoutMs: 5_000 }, + ); + check( + inheritedEnv.cells[0]?.value === `'${envMarker}'`, + `custom host variable is visible (got ${JSON.stringify(inheritedEnv.cells[0]?.value)})`, + ); + // ── 0. Ordinary exception: same process and namespace survive ── console.log("\n[0] ordinary exception preserves the kernel and namespace"); const ordinaryFailure = await k.execute( @@ -73,89 +92,113 @@ async function main(): Promise { `failed-cell mutations preserved (got ${JSON.stringify(afterOrdinaryFailure.cells[0]?.value)})`, ); - // ── 1. Multi-cell timeout: marker set, then long sleep gets SIGINT'd ── - console.log("\n[1] multi-cell call where cell 2 times out"); - const r1 = await k.execute( - [ - { code: "marker='alpha'\nprint('marker set')" }, - { code: "import time\nfor _ in range(100): time.sleep(0.1)\n" }, - { code: "marker='omega' # never runs" }, - ], - { timeoutMs: 500, interruptGraceMs: 5_000 }, - ); + if (process.platform === "win32") { + // Node cannot deliver a catchable SIGINT to a Windows child process. + // Timeouts therefore hard-kill the kernel immediately and preserve only + // output, not namespace state. Verify that behavior is explicit rather + // than surfacing as a rejected "kernel exited" tool call. + console.log("\n[windows] timeout hard-kills and cleanly respawns"); + const timedOutPid = k.getInfo()?.pid; + const timedOut = await k.execute( + [{ code: "print('before hard kill', flush=True)\nimport time\ntime.sleep(30)" }], + { timeoutMs: 500, interruptGraceMs: 5_000 }, + ); + check(timedOut.timedOut, "result.timedOut === true"); + check(timedOut.killed === true, "result.killed === true"); + check( + (timedOut.cells[0]?.stdout ?? "").includes("before hard kill"), + "partial output survives the hard kill", + ); + check(!k.isAlive(), "kernel is dead after timeout"); - check(r1.timedOut, "result.timedOut === true"); - check(r1.cancelled, "result.cancelled === true"); - check(r1.cellsRun === 2, `cellsRun is 2 (set marker + interrupted sleep), got ${r1.cellsRun}`); - check(r1.cells[0]?.ok === true, "cell 0 (set marker) succeeded"); - const cell0Stdout = r1.cells[0]?.stdout ?? ""; - check(cell0Stdout.includes("marker set"), `cell 0 printed 'marker set' (got ${JSON.stringify(cell0Stdout)})`); - check(r1.cells[1]?.ok === false, "cell 1 (sleep) ok=false"); - check( - (r1.cells[1]?.exception ?? "").includes("KeyboardInterrupt"), - "cell 1 exception mentions KeyboardInterrupt", - ); + const fresh = await k.execute([{ code: "'respawned'" }], { timeoutMs: 5_000 }); + check(fresh.cells[0]?.value === "'respawned'", "next call respawns cleanly"); + check(k.getInfo()?.pid !== timedOutPid, "respawn uses a new pid"); + } else { + // ── 1. Multi-cell timeout: marker set, then long sleep gets SIGINT'd ── + console.log("\n[1] multi-cell call where cell 2 times out"); + const r1 = await k.execute( + [ + { code: "marker='alpha'\nprint('marker set')" }, + { code: "import time\nfor _ in range(100): time.sleep(0.1)\n" }, + { code: "marker='omega' # never runs" }, + ], + { timeoutMs: 500, interruptGraceMs: 5_000 }, + ); - // ── 2. Kernel still alive after the interrupted call ── - console.log("\n[2] kernel survives the interrupt"); - check(k.isAlive(), "k.isAlive() === true after timeout"); - const pidAfter = k.getInfo()?.pid; - check(pidAfter === initialPid, `same pid (${pidAfter} === ${initialPid})`); + check(r1.timedOut, "result.timedOut === true"); + check(r1.cancelled, "result.cancelled === true"); + check(r1.cellsRun === 2, `cellsRun is 2 (set marker + interrupted sleep), got ${r1.cellsRun}`); + check(r1.cells[0]?.ok === true, "cell 0 (set marker) succeeded"); + const cell0Stdout = r1.cells[0]?.stdout ?? ""; + check(cell0Stdout.includes("marker set"), `cell 0 printed 'marker set' (got ${JSON.stringify(cell0Stdout)})`); + check(r1.cells[1]?.ok === false, "cell 1 (sleep) ok=false"); + check( + (r1.cells[1]?.exception ?? "").includes("KeyboardInterrupt"), + "cell 1 exception mentions KeyboardInterrupt", + ); - // ── 3. Marker preserved ── - console.log("\n[3] namespace state from before-the-interrupt cell preserved"); - const r2 = await k.execute([{ code: "marker" }], { timeoutMs: 10_000 }); - check(r2.cells[0]?.ok === true, "follow-up cell succeeded"); - check( - r2.cells[0]?.value === "'alpha'", - `marker preserved (got ${JSON.stringify(r2.cells[0]?.value)})`, - ); + // ── 2. Kernel still alive after the interrupted call ── + console.log("\n[2] kernel survives the interrupt"); + check(k.isAlive(), "k.isAlive() === true after timeout"); + const pidAfter = k.getInfo()?.pid; + check(pidAfter === initialPid, `same pid (${pidAfter} === ${initialPid})`); - // ── 4. SIGINT-trapping cell still doesn't kill the kernel even with - // interruptGraceMs: 0. The runner's SIG_IGN-by-default keeps it - // alive between cells; the cell itself catches KeyboardInterrupt - // and reports normally. - console.log("\n[4] cell that traps KeyboardInterrupt + zero grace"); - const r3 = await k.execute( - [ - { - code: [ - "import time", - "try:", - " for _ in range(100):", - " time.sleep(0.05)", - "except KeyboardInterrupt:", - " pass", - "print('finished gracefully')", - "survival_marker = 'beta'", - ].join("\n"), - }, - ], - { timeoutMs: 500, interruptGraceMs: 0 }, - ); - // Cell-level SIGINT is caught inside the `try:` so the cell completes - // successfully; the timedOut flag still reflects that the wall clock - // expired. - check(r3.timedOut, "result.timedOut still true (timer fired)"); - check(k.isAlive(), "kernel still alive with interruptGraceMs: 0"); - check( - r3.cells[0]?.ok === true, - `cell ok=true (caught its own KeyboardInterrupt): ok=${r3.cells[0]?.ok}, exc=${JSON.stringify(r3.cells[0]?.exception)}`, - ); - check( - (r3.cells[0]?.stdout ?? "").includes("finished gracefully"), - "cell printed 'finished gracefully'", - ); + // ── 3. Marker preserved ── + console.log("\n[3] namespace state from before-the-interrupt cell preserved"); + const r2 = await k.execute([{ code: "marker" }], { timeoutMs: 10_000 }); + check(r2.cells[0]?.ok === true, "follow-up cell succeeded"); + check( + r2.cells[0]?.value === "'alpha'", + `marker preserved (got ${JSON.stringify(r2.cells[0]?.value)})`, + ); - const r4 = await k.execute([{ code: "survival_marker" }], { timeoutMs: 5_000 }); - check( - r4.cells[0]?.value === "'beta'", - `survival_marker preserved (got ${JSON.stringify(r4.cells[0]?.value)})`, - ); + // ── 4. SIGINT-trapping cell still doesn't kill the kernel even with + // interruptGraceMs: 0. The runner's SIG_IGN-by-default keeps it + // alive between cells; the cell itself catches KeyboardInterrupt + // and reports normally. + console.log("\n[4] cell that traps KeyboardInterrupt + zero grace"); + const r3 = await k.execute( + [ + { + code: [ + "import time", + "try:", + " for _ in range(100):", + " time.sleep(0.05)", + "except KeyboardInterrupt:", + " pass", + "print('finished gracefully')", + "survival_marker = 'beta'", + ].join("\n"), + }, + ], + { timeoutMs: 500, interruptGraceMs: 0 }, + ); + // Cell-level SIGINT is caught inside the `try:` so the cell completes + // successfully; the timedOut flag still reflects that the wall clock + // expired. + check(r3.timedOut, "result.timedOut still true (timer fired)"); + check(k.isAlive(), "kernel still alive with interruptGraceMs: 0"); + check( + r3.cells[0]?.ok === true, + `cell ok=true (caught its own KeyboardInterrupt): ok=${r3.cells[0]?.ok}, exc=${JSON.stringify(r3.cells[0]?.exception)}`, + ); + check( + (r3.cells[0]?.stdout ?? "").includes("finished gracefully"), + "cell printed 'finished gracefully'", + ); - // ── 5. Same pid still — never hard-killed ── - console.log("\n[5] still the same kernel pid throughout"); - check(k.getInfo()?.pid === initialPid, `pid unchanged (${k.getInfo()?.pid})`); + const r4 = await k.execute([{ code: "survival_marker" }], { timeoutMs: 5_000 }); + check( + r4.cells[0]?.value === "'beta'", + `survival_marker preserved (got ${JSON.stringify(r4.cells[0]?.value)})`, + ); + + // ── 5. Same pid still — never hard-killed ── + console.log("\n[5] still the same kernel pid throughout"); + check(k.getInfo()?.pid === initialPid, `pid unchanged (${k.getInfo()?.pid})`); + } } finally { await k.shutdown(); } @@ -169,7 +212,7 @@ async function main(): Promise { // string "python kernel killed", discarding everything the cell had // printed. It must now resolve with that output plus killed=true. console.log("\n[6] uninterruptible cell: hard kill keeps partial output"); - const k2 = new PythonKernel({ pythonPath: "python3", cwd: process.cwd() }); + const k2 = new PythonKernel({ pythonPath, cwd: process.cwd() }); await k2.start(); const pid2 = k2.getInfo()?.pid; try {