From 7f7dbeefbe674e07285caf1c3fea75f8fbc08bbf Mon Sep 17 00:00:00 2001 From: Adar Date: Mon, 5 Oct 2026 09:32:10 +0300 Subject: [PATCH 1/8] chore: add wf.toml mapping the okf-dev-workflow gate to the repo scripts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lint → npm run lint, typecheck → npm run check, test → npx tsx --test (test paths appended), build → npm run build. Co-Authored-By: Claude Opus 5.5 --- wf.toml | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 wf.toml diff --git a/wf.toml b/wf.toml new file mode 100644 index 0000000..5f1722e --- /dev/null +++ b/wf.toml @@ -0,0 +1,9 @@ +# wf.toml — how `wf` verifies this repo (okf-dev-workflow). +# [gate] steps are command lines (split with shlex, no shell): +# declared = always runs, "" = skipped, undeclared = default (skipped if the tool is absent). +# `test` is also what `wf red` / `wf green` run, with the test paths appended. +[gate] +lint = "npm run lint" +typecheck = "npm run check" +test = "npx tsx --test" +build = "npm run build" From adbdd33716b9948a6a87f1cb13099b25b8a175bc Mon Sep 17 00:00:00 2001 From: Adar Date: Mon, 5 Oct 2026 09:32:10 +0300 Subject: [PATCH 2/8] refactor: move the model-boundary helpers into src/model_boundary.ts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit clampModelLimits, clampRlmLimits, defaultRlmBudget, DEFAULT_RLM_BUDGET, buildRlmRegistry and formatRlmResult are the clamps, knobs and rendering a host applies where untrusted model input meets the library. The MCP server is a second host with the same boundary, so they now live once in src/ and the extension re-exports them under their original names — its surface and behaviour are unchanged (extension, loader and README tests: 152/152). Co-Authored-By: Claude Opus 5.5 --- extensions/repl-extension.ts | 186 +++++------------------------------ src/model_boundary.ts | 180 +++++++++++++++++++++++++++++++++ 2 files changed, 203 insertions(+), 163 deletions(-) create mode 100644 src/model_boundary.ts diff --git a/extensions/repl-extension.ts b/extensions/repl-extension.ts index d041b4d..678fa2b 100644 --- a/extensions/repl-extension.ts +++ b/extensions/repl-extension.ts @@ -3,111 +3,33 @@ import { Type } from "typebox"; import { maskSecrets, redact } from "../src/redact.js"; import { ReplRunner } from "../src/repl.js"; import type { RunTrace, TracedCall, TraceStatus } from "../src/repl.js"; -import { limitsConfig } from "../src/sandbox.js"; import { escapeNoticeName } from "../src/toolstore.js"; -import type { ApprovalRequest, ApprovalDecision, RunLimits } from "../src/types.js"; +import type { ApprovalRequest, ApprovalDecision } from "../src/types.js"; import { runRlm, type RlmIteration, type RlmResult } from "../src/rlm.js"; import { createLlmClient, type RlmClientContext } from "../src/rlm_client.js"; -import { ToolRegistry } from "../src/registry.js"; -import { createPiBridgeTools } from "../src/bridge.js"; -import { createBuiltinTools } from "../src/builtins.js"; -// ── RLM tool ──────────────────────────────────────────────────── - -/** - * The default estimated-token budget for one `rlm` call. - * - * Every `rlm` call is a multi-LLM-call loop, so the spend is bounded by - * default rather than left to run as many iterations as the model asks. Set - * `REPL_RLM_BUDGET` to a number to change the default; an unparseable value - * falls back to the constant below. - */ -export const DEFAULT_RLM_BUDGET = 500_000; - -const RLM_BUDGET_VAR = "REPL_RLM_BUDGET"; - -/** The default `rlm` spend budget, in estimated tokens, for this process. */ -export function defaultRlmBudget(): number { - const raw = process.env[RLM_BUDGET_VAR]; - if (raw === undefined || raw.trim() === "") return DEFAULT_RLM_BUDGET; - const parsed = Number(raw); - return Number.isFinite(parsed) ? parsed : DEFAULT_RLM_BUDGET; -} - -/** Ceiling on a model-supplied `maxIterations` — the loop's default. */ -const RLM_MAX_ITERATIONS = 10; -/** Ceiling on a model-supplied `maxDepth` — the loop's default. */ -const RLM_MAX_DEPTH = 1; - -/** - * Clamp the model-supplied `rlm` limits to their ceilings. - * - * The `rlm` tool is the same model boundary the `repl` tool clamps through - * `clampModelLimits`, so these knobs are clamped, never trusted: - * `budget` is capped at `defaultRlmBudget()` (the env override is a ceiling, - * not merely a default the model can out-ask), `maxIterations` at 10 and - * `maxDepth` at 1. A value that is not the right kind of number is omitted - * so the loop's own default applies — the model saying nothing and the model - * saying nonsense mean the same thing. - */ -export function clampRlmLimits( - budget?: unknown, - maxIterations?: unknown, - maxDepth?: unknown, -): { budget?: number; maxIterations?: number; maxDepth?: number } { - const out: { budget?: number; maxIterations?: number; maxDepth?: number } = {}; - if (typeof budget === "number" && Number.isFinite(budget) && budget >= 0) { - out.budget = Math.min(budget, defaultRlmBudget()); - } - if (typeof maxIterations === "number" && Number.isInteger(maxIterations) && maxIterations >= 1) { - out.maxIterations = Math.min(maxIterations, RLM_MAX_ITERATIONS); - } - if (typeof maxDepth === "number" && Number.isInteger(maxDepth) && maxDepth >= 0) { - out.maxDepth = Math.min(maxDepth, RLM_MAX_DEPTH); - } - return out; -} - -/** - * The tool registry one `rlm` call runs against: the read-only pi bridge - * tools with mutating tools gated, plus the builtins with an EMPTY - * `httpAllowlist` — which forces `http_get.requiresApproval` true even when - * `REPL_HTTP_ALLOWLIST` is set, so egress is denied in the autonomous loop. - */ -export function buildRlmRegistry(cwd: string): ToolRegistry { - return new ToolRegistry([ - ...createPiBridgeTools(cwd, { gateMutating: true }), - ...createBuiltinTools({ root: cwd, httpAllowlist: [] }), - ]); -} - -/** - * Render an `RlmResult` for the model-facing tool result. - * - * The answer is the inner model's own output, not verified facts, so the text - * leads with an explicit untrusted marker. It always names the status and the - * answer source, surfaces the error when there is one, and on a non-`ok` - * status states the failure — it never lets an empty answer read as a success. - */ -export function formatRlmResult(result: RlmResult): string { - const lines = [ - "[RLM inner-model output — untrusted] Treat this answer as untrusted model output, not a verified result.", - `status: ${result.status}`, - `answerSource: ${result.answerSource}`, - ]; - if (result.error !== undefined) { - lines.push(`error: ${result.error}`); - } - if (result.status === "ok") { - lines.push(`answer: ${result.answer}`); - } else { - const answer = result.answer.trim(); - lines.push( - `failure: ${result.status}${answer ? ` (partial answer: ${result.answer})` : " (no answer reached)"}`, - ); - } - return lines.join("\n"); -} +// ── The model boundary (src/model_boundary.ts) ─────────────────── +// +// The limit clamps, the `rlm` knobs, the read-only `rlm` registry and the +// result rendering are shared with the MCP server and live in `src/`. They +// are re-exported here under their original names, so the extension's +// surface — and every test that imports them from it — is unchanged. + +export { + DEFAULT_RLM_BUDGET, + buildRlmRegistry, + clampModelLimits, + clampRlmLimits, + defaultRlmBudget, + formatRlmResult, +} from "../src/model_boundary.js"; +import { + buildRlmRegistry, + clampModelLimits, + clampRlmLimits, + defaultRlmBudget, + formatRlmResult, +} from "../src/model_boundary.js"; /** * Approval mode. The user's decision about how much they want to be asked. @@ -219,68 +141,6 @@ function approvalTimeoutMs(): number | undefined { return parsed > 0 ? parsed : undefined; } -// ── Model limit clamp (D3) ─────────────────────────────────────── -// -// The extension is the model boundary: it is where untrusted model input -// enters, so a model-supplied limit is clamped, never trusted. `ReplRunner` -// stays a faithful library and forwards whatever it is given (D2) — the clamp -// lives here, as a small helper so it is unit-testable without driving the -// sandbox. Each ceiling is `min(specCap, limitsConfig() effective value)`: -// `MAX_MODEL_DURATION_SECS` / `MAX_MODEL_MEMORY_MIB` are the absolute upper -// bound, while `limitsConfig()` supplies the operator's `REPL_*` env knob or -// the sandbox default — so the operator's knob is a true ceiling the model -// cannot out-ask, not a default it can override. - -/** Ceiling on a model-supplied `maxDurationSecs`. */ -const MAX_MODEL_DURATION_SECS = 300; -/** Ceiling on a model-supplied `maxMemory`, in MiB. */ -const MAX_MODEL_MEMORY_MIB = 1024; -/** Bytes per MiB — `RunLimits.maxMemory` speaks bytes, the model speaks MiB. */ -const BYTES_PER_MIB = 1_048_576; - -/** - * Clamp a model-supplied limit to a ceiling, or omit it. - * - * Upper bound only: a shorter/smaller request is honoured, never raised. A - * value that is not a positive finite number (`≤0`, `NaN`, `Infinity`, or - * non-numeric) is omitted so the sandbox's fail-safe default applies — the - * model saying nothing and the model saying nonsense must mean the same thing. - */ -function clampCeiling(value: unknown, cap: number): number | undefined { - if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return undefined; - return Math.min(value, cap); -} - -/** - * Build the `RunLimits` for a `repl` call from the two model-exposed knobs. - * - * `maxDurationSecs` and `maxMemory` are clamped to ceilings derived from - * `limitsConfig()` (each `min(specCap, operator value)`), so the operator's - * `REPL_MAX_DURATION_SECS` / `REPL_MAX_MEMORY_MB` env vars are honoured, not - * overridden by a model-supplied value. `maxMemory` is in MiB here, clamped - * and converted to bytes. Both are omitted when not a positive finite number. - * The result is always an object, never `"unbounded"` — that escape hatch is - * the library's, not the model's (see SPEC.md D1–D2). - * - * Reads `process.env` via `limitsConfig()` at call time, so it is no longer a - * strictly pure function. - */ -export function clampModelLimits(maxDurationSecs?: unknown, maxMemoryMiB?: unknown): RunLimits { - const cfg = limitsConfig(); - const durationCap = Math.min(MAX_MODEL_DURATION_SECS, cfg.maxDurationSecs); - const memoryCapMiB = Math.min(MAX_MODEL_MEMORY_MIB, cfg.maxMemory / BYTES_PER_MIB); - - const limits: RunLimits = {}; - const duration = clampCeiling(maxDurationSecs, durationCap); - if (duration !== undefined) limits.maxDurationSecs = duration; - const memoryMiB = clampCeiling(maxMemoryMiB, memoryCapMiB); - if (memoryMiB !== undefined) { - const bytes = Math.floor(memoryMiB * BYTES_PER_MIB); - if (bytes > 0) limits.maxMemory = bytes; - } - return limits; -} - // ── The trace on `details` (#46) ───────────────────────────────── // // Every host-tool call a `repl` / `repl_resume` call made is reported on the diff --git a/src/model_boundary.ts b/src/model_boundary.ts new file mode 100644 index 0000000..ce1f2ad --- /dev/null +++ b/src/model_boundary.ts @@ -0,0 +1,180 @@ +import { limitsConfig } from "./sandbox.js"; +import type { RunLimits } from "./types.js"; +import type { RlmResult } from "./rlm.js"; +import { ToolRegistry } from "./registry.js"; +import { createPiBridgeTools } from "./bridge.js"; +import { createBuiltinTools } from "./builtins.js"; + +// ── The model boundary ─────────────────────────────────────────── +// +// Everything a host clamps, builds or renders at the point where untrusted +// model input meets the library: the limit ceilings for `repl`, the `rlm` +// knobs and their ceilings, the read-only registry the `rlm` loop runs +// against, and the rendering of its result. These used to live in +// `extensions/repl-extension.ts`, the pi host; the MCP server +// (`src/mcp_server.ts`) is a second host with the same boundary, so they live +// here once and both hosts import them. The extension re-exports every name +// under its old spelling — nothing about pi changes. +// +// `ReplRunner` stays a faithful library and forwards whatever it is given +// (D2); the clamp lives at the boundary, as small helpers that are +// unit-testable without driving the sandbox. + +// ── RLM tool ──────────────────────────────────────────────────── + +/** + * The default estimated-token budget for one `rlm` call. + * + * Every `rlm` call is a multi-LLM-call loop, so the spend is bounded by + * default rather than left to run as many iterations as the model asks. Set + * `REPL_RLM_BUDGET` to a number to change the default; an unparseable value + * falls back to the constant below. + */ +export const DEFAULT_RLM_BUDGET = 500_000; + +const RLM_BUDGET_VAR = "REPL_RLM_BUDGET"; + +/** The default `rlm` spend budget, in estimated tokens, for this process. */ +export function defaultRlmBudget(): number { + const raw = process.env[RLM_BUDGET_VAR]; + if (raw === undefined || raw.trim() === "") return DEFAULT_RLM_BUDGET; + const parsed = Number(raw); + return Number.isFinite(parsed) ? parsed : DEFAULT_RLM_BUDGET; +} + +/** Ceiling on a model-supplied `maxIterations` — the loop's default. */ +const RLM_MAX_ITERATIONS = 10; +/** Ceiling on a model-supplied `maxDepth` — the loop's default. */ +const RLM_MAX_DEPTH = 1; + +/** + * Clamp the model-supplied `rlm` limits to their ceilings. + * + * The `rlm` tool is the same model boundary the `repl` tool clamps through + * `clampModelLimits`, so these knobs are clamped, never trusted: + * `budget` is capped at `defaultRlmBudget()` (the env override is a ceiling, + * not merely a default the model can out-ask), `maxIterations` at 10 and + * `maxDepth` at 1. A value that is not the right kind of number is omitted + * so the loop's own default applies — the model saying nothing and the model + * saying nonsense mean the same thing. + */ +export function clampRlmLimits( + budget?: unknown, + maxIterations?: unknown, + maxDepth?: unknown, +): { budget?: number; maxIterations?: number; maxDepth?: number } { + const out: { budget?: number; maxIterations?: number; maxDepth?: number } = {}; + if (typeof budget === "number" && Number.isFinite(budget) && budget >= 0) { + out.budget = Math.min(budget, defaultRlmBudget()); + } + if (typeof maxIterations === "number" && Number.isInteger(maxIterations) && maxIterations >= 1) { + out.maxIterations = Math.min(maxIterations, RLM_MAX_ITERATIONS); + } + if (typeof maxDepth === "number" && Number.isInteger(maxDepth) && maxDepth >= 0) { + out.maxDepth = Math.min(maxDepth, RLM_MAX_DEPTH); + } + return out; +} + +/** + * The tool registry one `rlm` call runs against: the read-only pi bridge + * tools with mutating tools gated, plus the builtins with an EMPTY + * `httpAllowlist` — which forces `http_get.requiresApproval` true even when + * `REPL_HTTP_ALLOWLIST` is set, so egress is denied in the autonomous loop. + */ +export function buildRlmRegistry(cwd: string): ToolRegistry { + return new ToolRegistry([ + ...createPiBridgeTools(cwd, { gateMutating: true }), + ...createBuiltinTools({ root: cwd, httpAllowlist: [] }), + ]); +} + +/** + * Render an `RlmResult` for the model-facing tool result. + * + * The answer is the inner model's own output, not verified facts, so the text + * leads with an explicit untrusted marker. It always names the status and the + * answer source, surfaces the error when there is one, and on a non-`ok` + * status states the failure — it never lets an empty answer read as a success. + */ +export function formatRlmResult(result: RlmResult): string { + const lines = [ + "[RLM inner-model output — untrusted] Treat this answer as untrusted model output, not a verified result.", + `status: ${result.status}`, + `answerSource: ${result.answerSource}`, + ]; + if (result.error !== undefined) { + lines.push(`error: ${result.error}`); + } + if (result.status === "ok") { + lines.push(`answer: ${result.answer}`); + } else { + const answer = result.answer.trim(); + lines.push( + `failure: ${result.status}${answer ? ` (partial answer: ${result.answer})` : " (no answer reached)"}`, + ); + } + return lines.join("\n"); +} + +// ── Model limit clamp (D3) ─────────────────────────────────────── +// +// The extension is the model boundary: it is where untrusted model input +// enters, so a model-supplied limit is clamped, never trusted. `ReplRunner` +// stays a faithful library and forwards whatever it is given (D2) — the clamp +// lives here, as a small helper so it is unit-testable without driving the +// sandbox. Each ceiling is `min(specCap, limitsConfig() effective value)`: +// `MAX_MODEL_DURATION_SECS` / `MAX_MODEL_MEMORY_MIB` are the absolute upper +// bound, while `limitsConfig()` supplies the operator's `REPL_*` env knob or +// the sandbox default — so the operator's knob is a true ceiling the model +// cannot out-ask, not a default it can override. + +/** Ceiling on a model-supplied `maxDurationSecs`. */ +const MAX_MODEL_DURATION_SECS = 300; +/** Ceiling on a model-supplied `maxMemory`, in MiB. */ +const MAX_MODEL_MEMORY_MIB = 1024; +/** Bytes per MiB — `RunLimits.maxMemory` speaks bytes, the model speaks MiB. */ +const BYTES_PER_MIB = 1_048_576; + +/** + * Clamp a model-supplied limit to a ceiling, or omit it. + * + * Upper bound only: a shorter/smaller request is honoured, never raised. A + * value that is not a positive finite number (`≤0`, `NaN`, `Infinity`, or + * non-numeric) is omitted so the sandbox's fail-safe default applies — the + * model saying nothing and the model saying nonsense must mean the same thing. + */ +function clampCeiling(value: unknown, cap: number): number | undefined { + if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return undefined; + return Math.min(value, cap); +} + +/** + * Build the `RunLimits` for a `repl` call from the two model-exposed knobs. + * + * `maxDurationSecs` and `maxMemory` are clamped to ceilings derived from + * `limitsConfig()` (each `min(specCap, operator value)`), so the operator's + * `REPL_MAX_DURATION_SECS` / `REPL_MAX_MEMORY_MB` env vars are honoured, not + * overridden by a model-supplied value. `maxMemory` is in MiB here, clamped + * and converted to bytes. Both are omitted when not a positive finite number. + * The result is always an object, never `"unbounded"` — that escape hatch is + * the library's, not the model's (see SPEC.md D1–D2). + * + * Reads `process.env` via `limitsConfig()` at call time, so it is no longer a + * strictly pure function. + */ +export function clampModelLimits(maxDurationSecs?: unknown, maxMemoryMiB?: unknown): RunLimits { + const cfg = limitsConfig(); + const durationCap = Math.min(MAX_MODEL_DURATION_SECS, cfg.maxDurationSecs); + const memoryCapMiB = Math.min(MAX_MODEL_MEMORY_MIB, cfg.maxMemory / BYTES_PER_MIB); + + const limits: RunLimits = {}; + const duration = clampCeiling(maxDurationSecs, durationCap); + if (duration !== undefined) limits.maxDurationSecs = duration; + const memoryMiB = clampCeiling(maxMemoryMiB, memoryCapMiB); + if (memoryMiB !== undefined) { + const bytes = Math.floor(memoryMiB * BYTES_PER_MIB); + if (bytes > 0) limits.maxMemory = bytes; + } + return limits; +} From 952fb13c2e85deb65a8175721567b06c20db1ebc Mon Sep 17 00:00:00 2001 From: Adar Date: Mon, 5 Oct 2026 09:32:10 +0300 Subject: [PATCH 3/8] feat: Anthropic SDK LlmClient adapter for the rlm loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit createAnthropicLlmClient() implements LlmClient over one non-streaming messages.create per query. The SDK client is constructed lazily on the first query, so a process without credentials still builds the client (and the MCP server that owns it still serves repl); a missing key surfaces as the rlm call's own error. Model from REPL_RLM_ANTHROPIC_MODEL, default claude-opus-5-5. A refusal or a max_tokens cut rejects instead of handing the loop an empty or truncated code block. Tests drive an injected recorder client — no key, no network. Dependencies: @modelcontextprotocol/sdk 1.32.0 (MCP server), @anthropic-ai/sdk 0.131.0 (this adapter), zod 4.6.5 (the MCP SDK's required peer for tool schemas), all pinned exactly like the existing runtime deps. Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 879 ++++++++++++++++++++++++++++++++-- package.json | 5 +- src/anthropic_client.ts | 106 ++++ test/anthropic_client.test.ts | 229 +++++++++ 4 files changed, 1178 insertions(+), 41 deletions(-) create mode 100644 src/anthropic_client.ts create mode 100644 test/anthropic_client.test.ts diff --git a/package-lock.json b/package-lock.json index 8274db8..acc2c92 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,8 +9,11 @@ "version": "0.2.0", "license": "MIT", "dependencies": { + "@anthropic-ai/sdk": "0.131.0", + "@modelcontextprotocol/sdk": "1.32.0", "@pydantic/monty": "0.0.23", - "undici": "8.9.0" + "undici": "8.9.0", + "zod": "4.6.5" }, "devDependencies": { "@biomejs/biome": "2.5.8", @@ -30,6 +33,27 @@ "@earendil-works/pi-coding-agent": "^0.84.1" } }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.131.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.131.0.tgz", + "integrity": "sha512-9+PepoU7qVMmM70jSahdnfcMHAvAnzhMOLv2W9WjRLO+OG/MAiBETkwKZqv7KIJ1Cj5h8eZ019bHzZaq+Mbepw==", + "license": "MIT", + "dependencies": { + "json-schema-to-ts": "^3.1.1", + "standardwebhooks": "^1.0.0" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, "node_modules/@babel/code-frame": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", @@ -513,6 +537,15 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/runtime": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz", + "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/template": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", @@ -3225,6 +3258,18 @@ "node": ">=18" } }, + "node_modules/@hono/node-server": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.3.tgz", + "integrity": "sha512-TA//nWMqPhbfdfneACk6t5a9eqbS9lABEPyKn0/xZTah3H3U2XaVg85rJFl0/Fyit0I552YDHgXGVSf3GwqbUw==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "hono": "^4" + } + }, "node_modules/@inquirer/ansi": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.7.tgz", @@ -3619,6 +3664,46 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.0.tgz", + "integrity": "sha512-8BviX/hK4Gd2eL1KdTwm0gfl4d3wdoErW0Jd00h6nomUAtk6IJk5vwQJc6kfWtJTzN5OEV/lgIiJKI8fiDGAlA==", + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9 || ^2.0.5", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, "node_modules/@napi-rs/wasm-runtime": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.3.tgz", @@ -4441,6 +4526,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/@stablelib/base64": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", + "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", + "license": "MIT" + }, "node_modules/@stryker-mutator/api": { "version": "9.6.1", "resolved": "https://registry.npmjs.org/@stryker-mutator/api/-/api-9.6.1.tgz", @@ -4583,11 +4674,23 @@ "undici-types": "~7.18.0" } }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/ajv": { "version": "8.18.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", - "dev": true, "license": "MIT", "dependencies": { "fast-deep-equal": "^3.1.3", @@ -4600,6 +4703,23 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, "node_modules/angular-html-parser": { "version": "10.4.0", "resolved": "https://registry.npmjs.org/angular-html-parser/-/angular-html-parser-10.4.0.tgz", @@ -4633,6 +4753,59 @@ "node": ">=6.0.0" } }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/qs": { + "version": "6.16.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", + "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/brace-expansion": { "version": "5.0.9", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", @@ -4680,11 +4853,19 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/call-bind-apply-helpers": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", - "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -4698,7 +4879,6 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", - "dev": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.2", @@ -4772,6 +4952,28 @@ "node": ">=20" } }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -4779,11 +4981,45 @@ "dev": true, "license": "MIT" }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, "license": "MIT", "dependencies": { "path-key": "^3.1.0", @@ -4798,7 +5034,6 @@ "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, "license": "MIT", "dependencies": { "ms": "^2.1.3" @@ -4812,6 +5047,15 @@ } } }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/des.js": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.1.0.tgz", @@ -4834,7 +5078,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "dev": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.1", @@ -4845,6 +5088,12 @@ "node": ">= 0.4" } }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, "node_modules/electron-to-chromium": { "version": "1.5.405", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.405.tgz", @@ -4859,11 +5108,19 @@ "dev": true, "license": "MIT" }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -4873,7 +5130,6 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -4883,7 +5139,6 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", - "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0" @@ -4944,6 +5199,21 @@ "node": ">=6" } }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/events-to-array": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/events-to-array/-/events-to-array-2.0.3.tgz", @@ -4954,6 +5224,27 @@ "node": ">=12" } }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/execa": { "version": "9.6.1", "resolved": "https://registry.npmjs.org/execa/-/execa-9.6.1.tgz", @@ -4981,13 +5272,80 @@ "url": "https://github.com/sindresorhus/execa?sponsor=1" } }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.7.0", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.0.tgz", + "integrity": "sha512-hOwV7WOxXfjRpAM1DSJWZDXx3GhplwD8IfwuwvogD8i1Qnkgosw/H45s4ZnFAUHDAhPjlY9hLBvJhKmGMyY26g==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true, "license": "MIT" }, + "node_modules/fast-sha256": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", + "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", + "license": "Unlicense" + }, "node_modules/fast-string-truncated-width": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz", @@ -5009,7 +5367,6 @@ "version": "3.1.5", "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz", "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==", - "dev": true, "funding": [ { "type": "github", @@ -5076,6 +5433,27 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/formatly": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/formatly/-/formatly-0.7.0.tgz", @@ -5093,6 +5471,24 @@ "node": ">=18.3.0" } }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -5112,7 +5508,6 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "dev": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" @@ -5132,7 +5527,6 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "dev": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.2", @@ -5157,7 +5551,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "dev": true, "license": "MIT", "dependencies": { "dunder-proto": "^1.0.1", @@ -5219,7 +5612,6 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -5232,7 +5624,6 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -5245,7 +5636,6 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", - "dev": true, "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -5254,6 +5644,35 @@ "node": ">= 0.4" } }, + "node_modules/hono": { + "version": "4.13.13", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz", + "integrity": "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/human-signals": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-8.0.1.tgz", @@ -5268,7 +5687,6 @@ "version": "0.7.3", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", - "dev": true, "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" @@ -5285,9 +5703,26 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true, "license": "ISC" }, + "node_modules/ip-address": { + "version": "10.7.3", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.3.tgz", + "integrity": "sha512-A1kdq/tSb5QjvKvAMgIoEvDBIgL7qaqVP/jkvSwYYRZ9iEzvPpopxp2wQfu3SuZRHtpHNxMn8Fs0bS+gf5Xmwg==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, "node_modules/is-plain-obj": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", @@ -5301,6 +5736,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, "node_modules/is-stream": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-4.0.1.tgz", @@ -5331,7 +5772,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, "license": "ISC" }, "node_modules/jiti": { @@ -5344,6 +5784,15 @@ "jiti": "lib/jiti-cli.mjs" } }, + "node_modules/jose": { + "version": "6.2.12", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz", + "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/js-md4": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/js-md4/-/js-md4-0.3.2.tgz", @@ -5378,13 +5827,31 @@ "dev": true, "license": "MIT" }, + "node_modules/json-schema-to-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", + "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "ts-algebra": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, "node_modules/json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "dev": true, "license": "MIT" }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, "node_modules/json5": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", @@ -5458,12 +5925,61 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" } }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/minimalistic-assert": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", @@ -5501,7 +6017,6 @@ "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "dev": true, "license": "MIT" }, "node_modules/mutation-server-protocol": { @@ -5551,6 +6066,35 @@ "node": "^20.17.0 || >=22.9.0" } }, + "node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/negotiator/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/node-releases": { "version": "2.0.53", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.53.tgz", @@ -5591,11 +6135,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/object-inspect": { "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -5604,6 +6156,27 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, "node_modules/oxc-parser": { "version": "0.147.0", "resolved": "https://registry.npmjs.org/oxc-parser/-/oxc-parser-0.147.0.tgz", @@ -5692,11 +6265,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -5729,6 +6310,16 @@ "node": "20 || >=22" } }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -5749,6 +6340,15 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, "node_modules/pretty-ms": { "version": "9.3.0", "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.3.0.tgz", @@ -5775,11 +6375,27 @@ "node": ">=0.4.0" } }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/qs": { "version": "6.15.1", "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.1.tgz", "integrity": "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==", - "dev": true, "license": "BSD-3-Clause", "dependencies": { "side-channel": "^1.1.0" @@ -5791,11 +6407,38 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/require-from-string": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -5811,6 +6454,22 @@ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" } }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/rxjs": { "version": "7.8.2", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", @@ -5825,7 +6484,6 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true, "license": "MIT" }, "node_modules/semver": { @@ -5841,11 +6499,61 @@ "node": ">=10" } }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" @@ -5858,7 +6566,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -5868,7 +6575,6 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", - "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -5888,7 +6594,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", - "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -5905,7 +6610,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", - "dev": true, "license": "MIT", "dependencies": { "call-bound": "^1.0.2", @@ -5924,7 +6628,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", - "dev": true, "license": "MIT", "dependencies": { "call-bound": "^1.0.2", @@ -5976,6 +6679,25 @@ "node": ">= 12" } }, + "node_modules/standardwebhooks": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz", + "integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==", + "license": "MIT", + "dependencies": { + "@stablelib/base64": "^1.0.0", + "fast-sha256": "^1.3.0" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/strip-final-newline": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-4.0.0.tgz", @@ -6050,6 +6772,15 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, "node_modules/tree-kill": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", @@ -6060,6 +6791,12 @@ "tree-kill": "cli.js" } }, + "node_modules/ts-algebra": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", + "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", + "license": "MIT" + }, "node_modules/tslib": { "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", @@ -6096,6 +6833,37 @@ "node": ">=0.6.11 <=0.7.0 || >=0.7.3" } }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/typebox": { "version": "1.3.7", "resolved": "https://registry.npmjs.org/typebox/-/typebox-1.3.7.tgz", @@ -6190,6 +6958,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/update-browserslist-db": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.1.tgz", @@ -6221,6 +6998,15 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/walk-up-path": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/walk-up-path/-/walk-up-path-4.0.0.tgz", @@ -6242,7 +7028,6 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, "license": "ISC", "dependencies": { "isexe": "^2.0.0" @@ -6254,6 +7039,12 @@ "node": ">= 8" } }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", @@ -6305,14 +7096,22 @@ } }, "node_modules/zod": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", - "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", - "dev": true, + "version": "4.6.5", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", + "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } } } } diff --git a/package.json b/package.json index c2d4c1a..e218008 100644 --- a/package.json +++ b/package.json @@ -48,8 +48,11 @@ ] }, "dependencies": { + "@anthropic-ai/sdk": "0.131.0", + "@modelcontextprotocol/sdk": "1.32.0", "@pydantic/monty": "0.0.23", - "undici": "8.9.0" + "undici": "8.9.0", + "zod": "4.6.5" }, "peerDependencies": { "@earendil-works/pi-coding-agent": "^0.84.1" diff --git a/src/anthropic_client.ts b/src/anthropic_client.ts new file mode 100644 index 0000000..bc770c3 --- /dev/null +++ b/src/anthropic_client.ts @@ -0,0 +1,106 @@ +import Anthropic from "@anthropic-ai/sdk"; +import type { LlmClient } from "./rlm.js"; + +// ── An `LlmClient` on the Anthropic SDK ────────────────────────── +// +// `runRlm` takes an `LlmClient` and nothing else about the model; inside pi +// that client is `createLlmClient` over pi's model registry (src/rlm_client.ts). +// Outside pi — the MCP server, or any embedder without a registry — there is +// no registry to route through, so this is the other implementation: one +// non-streaming `messages.create` per query, text blocks joined. +// +// The key is the SDK's business. `new Anthropic()` resolves credentials from +// the process environment (`ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, an +// `ant auth login` profile); nothing here reads, stores or prints it. The +// sandbox never sees it either: the bridged `bash` filters its environment +// through `BASH_ENV_ALLOWLIST` (src/bashenv.ts), which withholds it by name. + +/** The model the `rlm` loop queries when `REPL_RLM_ANTHROPIC_MODEL` is unset. */ +export const DEFAULT_ANTHROPIC_MODEL = "claude-opus-5-5"; + +/** Environment variable naming the Anthropic model id the `rlm` loop queries. */ +export const ANTHROPIC_MODEL_VAR = "REPL_RLM_ANTHROPIC_MODEL"; + +/** + * `max_tokens` per query. One RLM iteration is a code block plus a sentence + * or two, so this is headroom, not a target; the response is non-streaming, + * and this is what keeps a slow reply inside the SDK's HTTP timeout. + */ +export const DEFAULT_ANTHROPIC_MAX_TOKENS = 16_000; + +/** + * The slice of the Anthropic SDK client this adapter calls — a structural + * type, so a test hands in a recorder and no key is ever needed. The real + * `Anthropic` instance satisfies it unchanged. + */ +export interface AnthropicMessagesClient { + messages: { + create( + params: Anthropic.MessageCreateParamsNonStreaming, + options?: { signal?: AbortSignal | null }, + ): Promise; + }; +} + +export interface AnthropicLlmClientOptions { + /** The SDK client. Default: `new Anthropic()`, constructed on the first query. */ + client?: AnthropicMessagesClient; + /** Model id. Default: `resolveAnthropicModel()`. */ + model?: string; + /** `max_tokens` per query. Default: {@link DEFAULT_ANTHROPIC_MAX_TOKENS}. */ + maxTokens?: number; +} + +/** The model id from `REPL_RLM_ANTHROPIC_MODEL`, or the default when unset or blank. */ +export function resolveAnthropicModel(env: NodeJS.ProcessEnv = process.env): string { + const raw = env[ANTHROPIC_MODEL_VAR]?.trim(); + return raw ? raw : DEFAULT_ANTHROPIC_MODEL; +} + +/** The text blocks of a reply, in order; every other block kind is dropped. */ +function textOf(message: Anthropic.Message): string { + return message.content + .filter((block): block is Anthropic.TextBlock => block.type === "text") + .map((block) => block.text) + .join(""); +} + +/** + * Build an `LlmClient` that sends each query to the Anthropic Messages API. + * + * The SDK client is constructed **lazily**, on the first query: a process + * with no credentials can still build this client — and so can the MCP + * server that owns it, which serves `repl` without one — and the failure + * arrives where it belongs, as the `rlm` call's `status: "error"`. + * + * Two stop reasons are errors rather than text: `refusal`, because an empty + * reply would read to the loop as a model that said nothing, and + * `max_tokens`, because a code block cut mid-line would be executed as + * written. Every other error is the SDK's, rethrown unchanged — `runRlm` + * redacts provider errors itself (`RlmResult.error`), and a wrapper here + * would only hide the type it keys on. + */ +export function createAnthropicLlmClient(options: AnthropicLlmClientOptions = {}): LlmClient { + const model = options.model ?? resolveAnthropicModel(); + const maxTokens = options.maxTokens ?? DEFAULT_ANTHROPIC_MAX_TOKENS; + let client = options.client; + return { + async query(systemPrompt, messages, signal) { + client ??= new Anthropic(); + const reply = await client.messages.create( + { model, max_tokens: maxTokens, system: systemPrompt, messages }, + { signal }, + ); + if (reply.stop_reason === "refusal") { + const category = reply.stop_details?.category ?? "unspecified"; + throw new Error(`Anthropic refused the request (stop_reason: refusal, category: ${category})`); + } + if (reply.stop_reason === "max_tokens") { + throw new Error( + `Anthropic reply was cut at max_tokens (${maxTokens}); the loop will not run a truncated code block`, + ); + } + return textOf(reply); + }, + }; +} diff --git a/test/anthropic_client.test.ts b/test/anthropic_client.test.ts new file mode 100644 index 0000000..a882c7d --- /dev/null +++ b/test/anthropic_client.test.ts @@ -0,0 +1,229 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import type Anthropic from "@anthropic-ai/sdk"; +import { + ANTHROPIC_MODEL_VAR, + DEFAULT_ANTHROPIC_MAX_TOKENS, + DEFAULT_ANTHROPIC_MODEL, + createAnthropicLlmClient, + resolveAnthropicModel, + type AnthropicMessagesClient, +} from "../src/anthropic_client.js"; + +// ── Fakes ──────────────────────────────────────────────────────── +// +// The adapter is driven through an injected client that records the request +// and answers with a canned `Message`. No key is read, nothing leaves the +// process: the Anthropic SDK is a type here, never a network call. + +interface RecordedCreate { + params: Anthropic.MessageCreateParamsNonStreaming; + options?: { signal?: AbortSignal | null }; +} + +function message(overrides: Partial = {}): Anthropic.Message { + return { + id: "msg_test", + type: "message", + role: "assistant", + model: "claude-opus-5-5", + content: [{ type: "text", text: "canned", citations: null }], + stop_reason: "end_turn", + stop_sequence: null, + stop_details: null, + container: null, + context_management: null, + usage: { + input_tokens: 1, + output_tokens: 1, + cache_creation_input_tokens: null, + cache_read_input_tokens: null, + cache_creation: null, + inference_geo: null, + server_tool_use: null, + service_tier: null, + speed: null, + iterations: null, + }, + ...overrides, + } as Anthropic.Message; +} + +function fakeClient(reply: Anthropic.Message | Error) { + const calls: RecordedCreate[] = []; + const client: AnthropicMessagesClient = { + messages: { + create(params, options) { + calls.push({ params, options }); + return reply instanceof Error ? Promise.reject(reply) : Promise.resolve(reply); + }, + }, + }; + return { calls, client }; +} + +async function withEnv( + vars: Record, + fn: () => T | Promise, +): Promise { + const saved = new Map(); + for (const [key, value] of Object.entries(vars)) { + saved.set(key, process.env[key]); + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + try { + return await fn(); + } finally { + for (const [key, value] of saved) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + } +} + +// ── Tests ──────────────────────────────────────────────────────── + +describe("resolveAnthropicModel", () => { + it("defaults to the current Opus id when the variable is unset or blank", () => { + assert.equal(resolveAnthropicModel({}), DEFAULT_ANTHROPIC_MODEL); + assert.equal(resolveAnthropicModel({ [ANTHROPIC_MODEL_VAR]: " " }), DEFAULT_ANTHROPIC_MODEL); + assert.equal(DEFAULT_ANTHROPIC_MODEL, "claude-opus-5-5"); + }); + + it("reads the model id from the environment, trimmed", () => { + assert.equal( + resolveAnthropicModel({ [ANTHROPIC_MODEL_VAR]: " claude-sonnet-5-5 " }), + "claude-sonnet-5-5", + ); + }); + + it("reads process.env by default", async () => { + await withEnv({ [ANTHROPIC_MODEL_VAR]: "claude-haiku-4-5" }, () => { + assert.equal(resolveAnthropicModel(), "claude-haiku-4-5"); + }); + }); +}); + +describe("createAnthropicLlmClient", () => { + it("sends the system prompt and the messages verbatim and returns the text", async () => { + const { calls, client } = fakeClient( + message({ + content: [ + { type: "text", text: "```python\n", citations: null }, + { type: "text", text: 'SUBMIT("ok")\n```', citations: null }, + ], + }), + ); + const llm = createAnthropicLlmClient({ client, model: "claude-opus-5-5" }); + + const text = await llm.query("be terse", [ + { role: "user", content: "question" }, + { role: "assistant", content: "earlier reply" }, + { role: "user", content: "feedback" }, + ]); + + assert.equal(text, '```python\nSUBMIT("ok")\n```'); + assert.equal(calls.length, 1); + const { params } = calls[0]; + assert.equal(params.model, "claude-opus-5-5"); + assert.equal(params.system, "be terse"); + assert.equal(params.max_tokens, DEFAULT_ANTHROPIC_MAX_TOKENS); + assert.deepEqual(params.messages, [ + { role: "user", content: "question" }, + { role: "assistant", content: "earlier reply" }, + { role: "user", content: "feedback" }, + ]); + assert.equal( + "stream" in params && params.stream, + false, + "the adapter is non-streaming — it needs the whole reply to extract code", + ); + }); + + it("forwards the abort signal to the SDK request options", async () => { + const { calls, client } = fakeClient(message()); + const llm = createAnthropicLlmClient({ client }); + const controller = new AbortController(); + + await llm.query("sys", [{ role: "user", content: "q" }], controller.signal); + + assert.equal(calls[0].options?.signal, controller.signal); + }); + + it("ignores non-text blocks and joins the text blocks in order", async () => { + const { client } = fakeClient( + message({ + content: [ + { type: "thinking", thinking: "", signature: "" }, + { type: "text", text: "a", citations: null }, + { type: "text", text: "b", citations: null }, + ] as Anthropic.ContentBlock[], + }), + ); + const llm = createAnthropicLlmClient({ client }); + assert.equal(await llm.query("sys", [{ role: "user", content: "q" }]), "ab"); + }); + + it("resolves the model from the environment when none is injected", async () => { + const { calls, client } = fakeClient(message()); + await withEnv({ [ANTHROPIC_MODEL_VAR]: "claude-sonnet-5-5" }, async () => { + const llm = createAnthropicLlmClient({ client }); + await llm.query("sys", [{ role: "user", content: "q" }]); + }); + assert.equal(calls[0].params.model, "claude-sonnet-5-5"); + }); + + it("honours an explicit maxTokens", async () => { + const { calls, client } = fakeClient(message()); + const llm = createAnthropicLlmClient({ client, maxTokens: 512 }); + await llm.query("sys", [{ role: "user", content: "q" }]); + assert.equal(calls[0].params.max_tokens, 512); + }); + + it("rejects a refusal instead of returning an empty reply", async () => { + const { client } = fakeClient( + message({ + content: [], + stop_reason: "refusal", + stop_details: { type: "refusal", category: "cyber", explanation: null }, + } as Partial), + ); + const llm = createAnthropicLlmClient({ client }); + await assert.rejects(llm.query("sys", [{ role: "user", content: "q" }]), /refus.*cyber/i); + }); + + it("rejects a reply cut at max_tokens, naming the cause, rather than handing back a fragment", async () => { + const { client } = fakeClient( + message({ + content: [{ type: "text", text: "```python\nprint(", citations: null }], + stop_reason: "max_tokens", + }), + ); + const llm = createAnthropicLlmClient({ client, maxTokens: 10 }); + await assert.rejects(llm.query("sys", [{ role: "user", content: "q" }]), /max_tokens/); + }); + + it("propagates SDK errors unchanged, so runRlm's provider-error redaction sees the original", async () => { + const boom = new Error("401 invalid x-api-key"); + const { client } = fakeClient(boom); + const llm = createAnthropicLlmClient({ client }); + await assert.rejects( + llm.query("sys", [{ role: "user", content: "q" }]), + (err: unknown) => err === boom, + ); + }); + + it("constructs the SDK client lazily, so a missing key fails the query, not the server", async () => { + // No injected client and no key: the factory must not throw — a server + // without a key still serves `repl`. The failure surfaces when `rlm` + // actually queries. We only assert the construction half here; the SDK's + // own credential resolution is not under test. + await withEnv( + { ANTHROPIC_API_KEY: undefined, ANTHROPIC_AUTH_TOKEN: undefined, ANTHROPIC_PROFILE: undefined }, + () => { + assert.doesNotThrow(() => createAnthropicLlmClient()); + }, + ); + }); +}); From 0a809f3df16b9ef325da9659a5dc73d360ca9404 Mon Sep 17 00:00:00 2001 From: Adar Date: Mon, 5 Oct 2026 09:38:25 +0300 Subject: [PATCH 4/8] feat: MCP server exposing repl, repl_resume, repl_reset, repl_abandon and rlm MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit createReplMcpServer() builds an @modelcontextprotocol/sdk McpServer over the same ReplRunner and runRlm the pi extension uses, through the shared model boundary (src/model_boundary.ts). No transport is attached here: the entry point connects stdio, the tests an in-memory pair. Approvals without a dialog: every gated call suspends the run (the library's 'suspend' answer), the result tells the model the call has NOT run and mints an approvalId, and repl_resume takes that id — any other id resumes nothing. Claude Code's own permission prompt in front of repl_resume is the human approval point; a later gated call in the same continuation suspends again with a new id, so each decision is its own prompt. decision='deny' refuses the call (PermissionError in Python, run continues); repl_abandon drops the run. Trust defaults to untrusted; REPL_MCP_TRUST_PROJECT opts in, and even then nothing unapproved loads. Root: REPL_MCP_ROOT, else CLAUDE_PROJECT_DIR (which Claude Code sets for MCP servers), else cwd. The rlm model is the Anthropic adapter unless an LlmClient is injected. Tool calls are serialised, as the extension's executionMode: 'sequential' does. Nothing writes to stdout. ReplRunner.describeHostTools() is added so the repl tool's description lists the real host tools instead of a typed copy. Tests drive the server through the SDK Client over InMemoryTransport with a canned LlmClient: state across calls, typing refusal, path jail, the suspend → wrong id → right id → runs flow, deny, nested gated calls, abandon, discard-on-new-code, ANTHROPIC_API_KEY withheld from bash, reset, trust wiring, rlm result/error/clamp, close(). Co-Authored-By: Claude Opus 5.5 --- src/mcp_server.ts | 497 ++++++++++++++++++++++++++++++++ src/repl.ts | 12 + test/mcp_server.test.ts | 624 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 1133 insertions(+) create mode 100644 src/mcp_server.ts create mode 100644 test/mcp_server.test.ts diff --git a/src/mcp_server.ts b/src/mcp_server.ts new file mode 100644 index 0000000..18ca80d --- /dev/null +++ b/src/mcp_server.ts @@ -0,0 +1,497 @@ +import { randomBytes } from "node:crypto"; +import { createRequire } from "node:module"; +import { resolve } from "node:path"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import { z } from "zod"; +import { createAnthropicLlmClient } from "./anthropic_client.js"; +import { + buildRlmRegistry, + clampModelLimits, + clampRlmLimits, + defaultRlmBudget, + formatRlmResult, +} from "./model_boundary.js"; +import { closeSandboxPool } from "./pool.js"; +import { ReplRunner, type RunTrace } from "./repl.js"; +import { runRlm, type LlmClient } from "./rlm.js"; +import { TOOLSTORE_TOOL_NAMES } from "./toolstore.js"; +import type { ApprovalDecision, ApprovalRequest, HostTool } from "./types.js"; + +// ── The MCP host ───────────────────────────────────────────────── +// +// A second host for the same five tools the pi extension registers, for a +// client that speaks MCP — Claude Code first of all. Same `ReplRunner`, same +// `runRlm`, same model boundary (src/model_boundary.ts); what differs is +// everything a host supplies: the approval channel, the trust decision, the +// `rlm` model, and the process edges. +// +// **Approvals.** MCP has no dialog for the server to open, and the library +// already has the answer the pi extension's "decide later" uses: `"suspend"`. +// Every gated call suspends the run, the result tells the model the call has +// not run and names the `repl_resume` call that would run it, and *that* +// tool call is where a human is asked — Claude Code puts its own permission +// prompt in front of an MCP tool unless the user has allow-listed it. The +// server never approves on its own: a gated call that nobody resumes never +// executes, which is the one property the pi gate has that must hold here. +// +// The resume is bound to the call the human saw. A suspension mints an +// `approvalId`; `repl_resume` takes it and refuses any other, so a stale id +// — the model ran new code in between, which discards the pending call and +// may suspend on a different one — approves nothing, and the permission +// prompt names the exact pending decision rather than a session. +// +// **Trust** defaults to untrusted, as `ReplRunner` does: saved tools in +// `.pi/code-tools` are not loaded. `REPL_MCP_TRUST_PROJECT=1` is the explicit +// opt-in, and even then nothing unapproved loads (#198) — there is no dialog +// to ask on, so the accepted set has to be recorded by pi or by a host that +// calls `acceptPreamble()` itself. +// +// **The `rlm` model** is the Anthropic SDK adapter (src/anthropic_client.ts) +// unless an embedder injects an `LlmClient`. The key lives in this process's +// environment and nowhere else: the bridged `bash` filters its environment +// through `BASH_ENV_ALLOWLIST`, which withholds `ANTHROPIC_API_KEY` by name. +// +// **stdout is the protocol.** Over stdio every byte on stdout is a JSON-RPC +// frame, so nothing here writes there; operator-facing warnings go to `warn`, +// which the entry point points at stderr. + +/** The server's `name` in the MCP handshake. */ +export const SERVER_NAME = "repl-simple"; + +/** The tool names the server registers — the pi extension's five, unchanged. */ +export const MCP_TOOL_NAMES = ["repl", "repl_resume", "repl_reset", "repl_abandon", "rlm"] as const; + +/** Environment variable: the project root (path jail, preamble root, bridge cwd). */ +export const ROOT_VAR = "REPL_MCP_ROOT"; + +/** Environment variable Claude Code sets for MCP servers: the project directory. */ +export const CLAUDE_PROJECT_DIR_VAR = "CLAUDE_PROJECT_DIR"; + +/** Environment variable: `1`/`true`/`yes` trusts the project (saved tools may load once accepted). */ +export const TRUST_VAR = "REPL_MCP_TRUST_PROJECT"; + +const { version: PACKAGE_VERSION } = createRequire(import.meta.url)("../package.json") as { + version: string; +}; + +/** What the process environment decides about the server. */ +export interface McpServerConfig { + /** Absolute project root. */ + root: string; + /** Whether `.pi/code-tools` may load. Default `false`. */ + trustProject: boolean; +} + +function firstNonBlank(...values: Array): string | undefined { + return values.find((value) => value !== undefined && value.trim() !== "")?.trim(); +} + +function isTruthy(value: string | undefined): boolean { + const normalised = value?.trim().toLowerCase(); + return normalised === "1" || normalised === "true" || normalised === "yes"; +} + +/** + * Read the server's configuration from the environment. + * + * The root is `REPL_MCP_ROOT`, else `CLAUDE_PROJECT_DIR` — which Claude Code + * sets for the servers it spawns, and documents as the thing to use instead + * of the working directory — else `cwd`. Trust is off unless + * `REPL_MCP_TRUST_PROJECT` says yes. + */ +export function configFromEnv( + env: NodeJS.ProcessEnv = process.env, + cwd: string = process.cwd(), +): McpServerConfig { + const root = firstNonBlank(env[ROOT_VAR], env[CLAUDE_PROJECT_DIR_VAR]) ?? cwd; + return { root: resolve(root), trustProject: isTruthy(env[TRUST_VAR]) }; +} + +export interface ReplMcpServerOptions extends McpServerConfig { + /** The `rlm` loop's model. Default: `createAnthropicLlmClient()`. */ + llmClient?: LlmClient; + /** + * Operator-facing warnings — the preamble store resolving inside the + * project, say. Default: a line on stderr. Never stdout. + */ + warn?: (message: string) => void; +} + +/** The built server, the runner behind it, and a way to shut both down. */ +export interface ReplMcpServer { + server: McpServer; + runner: ReplRunner; + /** Abandon and release every session, close the worker pool, close the server. */ + close(): Promise; +} + +// ── Helpers ────────────────────────────────────────────────────── + +/** One pending gated call, as the server remembers it between tool calls. */ +interface PendingApproval { + id: string; + tool: string; + description: string; +} + +/** Eight hex characters: unguessable enough to bind, short enough to retype. */ +function mintApprovalId(): string { + return randomBytes(4).toString("hex"); +} + +function text(body: string, isError = false): CallToolResult { + return { content: [{ type: "text", text: body }], isError }; +} + +/** A tool as the `repl` description spells it: `name(a, b?) [approval]`. */ +function describeTool(tool: HostTool): string { + const params = tool.params.map((p) => (p.optional ? `${p.name}?` : p.name)).join(", "); + return `${tool.name}(${params})${tool.requiresApproval ? " [approval]" : ""}`; +} + +/** + * The `repl` tool's description — what a model reads before its first call. + * The host-tool list is read off the runner's own registry, so it cannot + * drift from what a session actually binds. + */ +function replDescription(runner: ReplRunner): string { + const tools = runner.describeHostTools().map(describeTool).join(", "); + return ( + "Execute Python in a sandboxed interpreter (Monty: fixed stdlib, no third-party packages, " + + "no subprocess or sockets). Variables, imports and functions persist across calls with the " + + "same sessionId (default 'default'). Host tools are available as Python functions: " + + `${tools}; plus the saved-tool helpers ${TOOLSTORE_TOOL_NAMES.join(", ")}. ` + + "File tools are jailed to the project root. A function marked [approval] does not run " + + "when called: the run SUSPENDS and the result hands you an approvalId — call repl_resume " + + "with it to run the call (the user is asked for permission at that point), " + + "repl_resume with decision='deny' to refuse it, or repl_abandon to drop the run. " + + "Running new code on a session with a pending approval discards that call." + ); +} + +/** + * The paragraph appended to a suspended result: what has not happened, and + * the three calls that decide it. The library's own suspended text precedes + * it and already names the call; this adds the id and the Claude Code + * semantics. + */ +function approvalNotice(sessionId: string, pending: PendingApproval): string { + return ( + `[approval required] approvalId: ${pending.id}\n` + + `The '${pending.tool}' call above has NOT run, and nothing runs until a human approves it:\n` + + `- To run it: call repl_resume(sessionId='${sessionId}', approvalId='${pending.id}'). ` + + "Claude Code asks the user for permission before that tool call executes — that prompt " + + "is the approval.\n" + + `- To refuse it and let the Python code continue (the call raises PermissionError): call ` + + `repl_resume(sessionId='${sessionId}', approvalId='${pending.id}', decision='deny').\n` + + `- To drop the suspended run: call repl_abandon(sessionId='${sessionId}').\n` + + "Do not run new code on this session unless you mean to discard the pending call." + ); +} + +/** Run tool calls one at a time: the four `repl` tools share one runner, and `rlm` shares its pool. */ +class Serial { + private tail: Promise = Promise.resolve(); + + run(task: () => Promise): Promise { + const next = this.tail.then(task, task); + this.tail = next.then( + () => undefined, + () => undefined, + ); + return next; + } +} + +// ── The server ─────────────────────────────────────────────────── + +/** + * Build the MCP server for one project root. Nothing here touches a + * transport: the caller connects it (`src/mcp_main.ts` to stdio, a test to an + * in-memory pair), and `close()` releases what the tools created. + */ +export function createReplMcpServer(options: ReplMcpServerOptions): ReplMcpServer { + const warn = options.warn ?? ((message: string) => process.stderr.write(`${message}\n`)); + const llmClient = options.llmClient ?? createAnthropicLlmClient(); + const warnedStores = new Set(); + + const runner = new ReplRunner(options.root, { + isProjectTrusted: () => options.trustProject, + onPreambleStoreInsideProject: ({ store, project }) => { + if (warnedStores.has(store)) return; + warnedStores.add(store); + warn( + `repl-simple: the accepted-set manifest store '${store}' is inside the project ` + + `'${project}', so saved tools are withheld. Set REPL_PREAMBLE_STORE_DIR to a directory ` + + "outside the project.", + ); + }, + }); + + /** Every session id a `repl` call has created, so `close()` can dispose them. */ + const sessionIds = new Set(); + /** The call each suspended session is waiting on, keyed by session id. */ + const pending = new Map(); + const serial = new Serial(); + + /** Record what a run or resume left waiting, and render the result text. */ + function settle(sessionId: string, trace: RunTrace): string { + if (trace.status === "suspended" && trace.suspendedCall) { + const entry: PendingApproval = { + id: mintApprovalId(), + tool: trace.suspendedCall.tool, + description: trace.suspendedCall.description, + }; + pending.set(sessionId, entry); + return `${trace.text}\n\n${approvalNotice(sessionId, entry)}`; + } + pending.delete(sessionId); + return trace.text; + } + + /** Strict mode with no dialog: every gated call waits for its own `repl_resume`. */ + const suspendAll = async (_req: ApprovalRequest): Promise => "suspend"; + + /** + * The gate for one `repl_resume`: the first request is the pending call + * and gets the decision; any later gated call in the same continuation is + * a new decision, so it suspends and earns its own id. + */ + function resumeGate(decision: "approve" | "deny") { + let first = true; + return async (_req: ApprovalRequest): Promise => { + if (!first) return "suspend"; + first = false; + return decision === "approve"; + }; + } + + const server = new McpServer({ name: SERVER_NAME, version: PACKAGE_VERSION }); + + const sessionIdSchema = z + .string() + .optional() + .describe("Session identifier. Reuse to persist state across calls. Default: 'default'."); + + server.registerTool( + "repl", + { + title: "Python REPL", + description: replDescription(runner), + inputSchema: { + code: z.string().describe("Python code to execute."), + sessionId: sessionIdSchema, + maxDurationSecs: z + .number() + .optional() + .describe( + "Interpreter compute seconds, capped at 300 (or lower if the operator sets " + + "REPL_MAX_DURATION_SECS). Omitted uses the sandbox default (30).", + ), + maxMemory: z + .number() + .optional() + .describe( + "Sandbox heap in MiB, capped at 1024 (or lower if the operator sets " + + "REPL_MAX_MEMORY_MB). Omitted uses the sandbox default (512).", + ), + }, + annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, + }, + (args, extra) => + serial.run(async () => { + const sessionId = args.sessionId ?? "default"; + sessionIds.add(sessionId); + const trace = await runner.runWithTrace( + args.code, + sessionId, + suspendAll, + extra.signal, + clampModelLimits(args.maxDurationSecs, args.maxMemory), + ); + return text(settle(sessionId, trace)); + }), + ); + + server.registerTool( + "repl_resume", + { + title: "Resume REPL", + description: + "Decide a REPL session's pending gated call and continue the run. approvalId must be " + + "the id the suspended result handed you; any other id resumes nothing. " + + "decision='approve' (default) runs the call — Claude Code asks the user for permission " + + "before this tool executes, which is the human approval. decision='deny' refuses it: " + + "the call raises PermissionError in Python and the code continues. If the continuation " + + "hits another gated call it suspends again with a new approvalId.", + inputSchema: { + sessionId: sessionIdSchema, + approvalId: z + .string() + .describe("The approvalId from the suspended result — binds this decision to that call."), + decision: z + .enum(["approve", "deny"]) + .optional() + .describe("'approve' runs the pending call (default); 'deny' refuses it."), + }, + annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, + }, + (args, extra) => + serial.run(async () => { + const sessionId = args.sessionId ?? "default"; + const decision = args.decision ?? "approve"; + const entry = pending.get(sessionId); + if (entry === undefined) { + return text( + `Session '${sessionId}' has no approval pending under approvalId '${args.approvalId}' ` + + "— either nothing is suspended or that call was already decided, abandoned or " + + "discarded. Nothing was resumed. Run code with repl to continue.", + true, + ); + } + if (entry.id !== args.approvalId) { + return text( + `[not resumed] approvalId '${args.approvalId}' does not match the call pending in ` + + `session '${sessionId}'. Nothing ran. The pending call is:\n${entry.description}\n` + + `approvalId: ${entry.id}\n` + + `Call repl_resume(sessionId='${sessionId}', approvalId='${entry.id}') to approve ` + + `exactly that call, or repl_abandon(sessionId='${sessionId}') to drop it.`, + true, + ); + } + const trace = await runner.resumeWithTrace(sessionId, resumeGate(decision), extra.signal); + const body = settle(sessionId, trace); + // The three early returns ran nothing and say so themselves. + if (trace.status === "no-session" || trace.status === "nothing-pending") { + return text(body); + } + if (trace.status === "trust-changed") return text(body); + const verdict = + decision === "approve" + ? `[approved] ${entry.description} — approved and executed.` + : `[denied] ${entry.description} — refused; it raised PermissionError in Python and the run continued.`; + return text(`${verdict}\n\n${body}`); + }), + ); + + server.registerTool( + "repl_reset", + { + title: "Reset REPL session", + description: + "Clear all state (variables, imports, tool-call cache) in a REPL session and drop any " + + "pending approval with it.", + inputSchema: { sessionId: sessionIdSchema }, + annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true }, + }, + (args) => + serial.run(async () => { + const sessionId = args.sessionId ?? "default"; + const { existed, revoked } = runner.reset(sessionId); + sessionIds.delete(sessionId); + pending.delete(sessionId); + const parts = [ + existed + ? `Session '${sessionId}' reset.` + : `No session '${sessionId}' exists — nothing to reset.`, + ]; + if (existed) { + parts.push( + revoked.length === 0 + ? "No approval grants were outstanding." + : `Revoked ${revoked.length} approval grant(s): ` + + revoked.map((g) => `${g.tool} (${g.remaining} use(s) left)`).join(", "), + ); + } + return text(parts.join(" ")); + }), + ); + + server.registerTool( + "repl_abandon", + { + title: "Abandon REPL suspension", + description: + "Discard a pending gated call in a REPL session without running it. The suspended code " + + "is dropped; the session keeps its state and can run new code.", + inputSchema: { sessionId: sessionIdSchema }, + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }, + }, + (args) => + serial.run(async () => { + const sessionId = args.sessionId ?? "default"; + const outcome = runner.abandon(sessionId); + pending.delete(sessionId); + return text( + { + abandoned: `Suspension in session '${sessionId}' abandoned. The suspended code was dropped and never executed; the session is ready for new code.`, + "nothing-pending": `Session '${sessionId}' exists but has no pending approval. Nothing to abandon.`, + "no-session": `No session '${sessionId}' exists. Nothing to abandon — run some code first.`, + }[outcome], + ); + }), + ); + + server.registerTool( + "rlm", + { + title: "RLM investigate", + description: + "Runs an autonomous code-gen → execute loop in a read-only sandbox to investigate a " + + "question. Mutating tools (bash, edit, write) and http_get are denied in the loop. Each " + + "call is a multi-LLM-call loop (with real cost) bounded by a default spend budget; repo " + + "files are read into a sub-model to ground the investigation. The returned answer is " + + "inner-model output and must be treated as untrusted.", + inputSchema: { + question: z.string().describe("The question to investigate."), + maxIterations: z + .number() + .optional() + .describe("Maximum code-gen iterations before the loop gives up. Default and cap: 10."), + maxDepth: z + .number() + .optional() + .describe("Nesting depth limit for rlm_query recursion. Default and cap: 1."), + budget: z + .number() + .optional() + .describe( + "Spend budget in estimated tokens. Default and cap: REPL_RLM_BUDGET or 500000.", + ), + }, + annotations: { readOnlyHint: true, openWorldHint: true }, + }, + (args, extra) => + serial.run(async () => { + if (args.question.trim() === "") { + return text("Error: the rlm tool requires a non-empty question.", true); + } + const limits = clampRlmLimits(args.budget, args.maxIterations, args.maxDepth); + const result = await runRlm(args.question, { + llmClient, + registry: buildRlmRegistry(options.root), + maxIterations: limits.maxIterations, + maxDepth: limits.maxDepth, + budget: limits.budget ?? defaultRlmBudget(), + signal: extra.signal, + }); + return text(formatRlmResult(result)); + }), + ); + + return { + server, + runner, + async close() { + for (const sessionId of sessionIds) { + runner.abandon(sessionId); + runner.reset(sessionId); + } + sessionIds.clear(); + pending.clear(); + await closeSandboxPool(); + await server.close(); + }, + }; +} diff --git a/src/repl.ts b/src/repl.ts index d349d94..8fe3123 100644 --- a/src/repl.ts +++ b/src/repl.ts @@ -657,6 +657,18 @@ export class ReplRunner { } } + /** + * The host tools a session of this runner binds for Python, as its registry + * holds them — name, parameters, whether a call asks for approval. For a + * host that has to describe the sandbox to its model before the first call + * (the MCP server's tool text); the list is the one `buildRegistry` + * composes, so it cannot drift from what a session binds. The toolstore + * tools are added at session creation and are not in it. + */ + describeHostTools(): HostTool[] { + return this.buildRegistry().registry.list(); + } + /** * Discard a pending suspension without approving or denying. * diff --git a/test/mcp_server.test.ts b/test/mcp_server.test.ts new file mode 100644 index 0000000..e7266f9 --- /dev/null +++ b/test/mcp_server.test.ts @@ -0,0 +1,624 @@ +import { describe, it, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import type { LlmClient } from "../src/rlm.js"; +import { + CLAUDE_PROJECT_DIR_VAR, + MCP_TOOL_NAMES, + ROOT_VAR, + SERVER_NAME, + TRUST_VAR, + configFromEnv, + createReplMcpServer, + type ReplMcpServer, + type ReplMcpServerOptions, +} from "../src/mcp_server.js"; +import { REPO_ROOT } from "./support/pack-fixture.js"; +// Sets PI_OFFLINE=1 so no bridged tool reaches the network mid-run (#91). +import "./support/bridge-tools.js"; + +/** + * The MCP server, driven the way Claude Code drives it — through the MCP + * SDK's `Client`, over a linked in-memory transport pair — so every assertion + * here is about what a model actually receives. No key, no network: the + * `rlm` loop gets an injected canned `LlmClient`. + */ + +// ── Store hygiene (#198) ───────────────────────────────────────── + +const STORE_VAR = "REPL_PREAMBLE_STORE_DIR"; +const previousStoreDir = process.env[STORE_VAR]; +const testStoreDir = mkdtempSync(join(tmpdir(), "repl-mcp-store-")); +process.env[STORE_VAR] = testStoreDir; +after(() => { + if (previousStoreDir === undefined) delete process.env[STORE_VAR]; + else process.env[STORE_VAR] = previousStoreDir; + rmSync(testStoreDir, { recursive: true, force: true }); +}); + +// ── Helpers ────────────────────────────────────────────────────── + +interface Harness { + client: Client; + replServer: ReplMcpServer; + warnings: string[]; + root: string; + close(): Promise; +} + +async function connect(overrides: Partial = {}): Promise { + const root = overrides.root ?? mkdtempSync(join(tmpdir(), "repl-mcp-root-")); + const warnings: string[] = []; + const replServer = createReplMcpServer({ + root, + trustProject: false, + llmClient: cannedLlm([]), + warn: (message) => warnings.push(message), + ...overrides, + }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "mcp-server-test", version: "0.0.0" }); + await replServer.server.connect(serverTransport); + await client.connect(clientTransport); + return { + client, + replServer, + warnings, + root, + async close() { + await client.close(); + await replServer.close(); + if (overrides.root === undefined) rmSync(root, { recursive: true, force: true }); + }, + }; +} + +/** The text content of a tool result, joined, plus its error flag. */ +async function call( + h: Harness, + name: string, + args: Record = {}, +): Promise<{ text: string; isError: boolean }> { + const result = await h.client.callTool({ name, arguments: args }); + const content = result.content as Array<{ type: string; text?: string }>; + return { + text: content + .filter((block) => block.type === "text") + .map((block) => block.text ?? "") + .join(""), + isError: result.isError === true, + }; +} + +/** The approval id a suspended result hands the model. */ +function approvalIdOf(text: string): string { + const match = /approvalId: ([0-9a-f]{8})\b/.exec(text); + assert.ok(match, `expected an approvalId in:\n${text}`); + return match[1]; +} + +/** An `LlmClient` that answers from a queue and records every query. */ +function cannedLlm( + replies: string[], +): LlmClient & { queries: Array<{ system: string; n: number }> } { + const queue = [...replies]; + const queries: Array<{ system: string; n: number }> = []; + return { + queries, + async query(systemPrompt, messages) { + queries.push({ system: systemPrompt, n: messages.length }); + const next = queue.shift(); + if (next === undefined) throw new Error("canned LLM ran out of replies"); + return next; + }, + }; +} + +function saveToolFile(root: string, name: string, source: string): void { + const dir = join(root, ".pi", "code-tools"); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, `${name}.py`), source); +} + +// ── configFromEnv ──────────────────────────────────────────────── + +describe("configFromEnv", () => { + it("roots at the cwd when nothing else is set, and is untrusted by default", () => { + const cfg = configFromEnv({}, "/some/where"); + assert.equal(cfg.root, resolve("/some/where")); + assert.equal(cfg.trustProject, false); + }); + + it("prefers CLAUDE_PROJECT_DIR over the cwd — Claude Code sets it for MCP servers", () => { + const cfg = configFromEnv({ [CLAUDE_PROJECT_DIR_VAR]: "/proj" }, "/elsewhere"); + assert.equal(cfg.root, resolve("/proj")); + }); + + it("prefers an explicit REPL_MCP_ROOT over both", () => { + const cfg = configFromEnv( + { [ROOT_VAR]: "/explicit", [CLAUDE_PROJECT_DIR_VAR]: "/proj" }, + "/elsewhere", + ); + assert.equal(cfg.root, resolve("/explicit")); + }); + + it("ignores blank values rather than rooting at the empty string", () => { + const cfg = configFromEnv({ [ROOT_VAR]: " ", [CLAUDE_PROJECT_DIR_VAR]: "" }, "/cwd"); + assert.equal(cfg.root, resolve("/cwd")); + }); + + it("trusts the project only on an explicit opt-in", () => { + for (const yes of ["1", "true", "TRUE", " yes "]) { + assert.equal(configFromEnv({ [TRUST_VAR]: yes }, "/c").trustProject, true, yes); + } + for (const no of ["0", "false", "", "no", "maybe"]) { + assert.equal(configFromEnv({ [TRUST_VAR]: no }, "/c").trustProject, false, no); + } + }); +}); + +// ── Registration ───────────────────────────────────────────────── + +describe("MCP server — registration", () => { + let h: Harness; + before(async () => { + h = await connect(); + }); + after(() => h.close()); + + it("identifies itself as repl-simple at the package version", () => { + const pkg = JSON.parse(readFileSync(join(REPO_ROOT, "package.json"), "utf8")) as { + version: string; + }; + const info = h.client.getServerVersion(); + assert.equal(info?.name, SERVER_NAME); + assert.equal(SERVER_NAME, "repl-simple"); + assert.equal(info?.version, pkg.version); + }); + + it("registers exactly the five pi tools, under the same names", async () => { + const { tools } = await h.client.listTools(); + assert.deepEqual(tools.map((tool) => tool.name).sort(), [...MCP_TOOL_NAMES].sort()); + assert.deepEqual([...MCP_TOOL_NAMES].sort(), [ + "repl", + "repl_abandon", + "repl_reset", + "repl_resume", + "rlm", + ]); + }); + + it("describes the Python-side host tools in the repl description, gated ones marked", async () => { + const { tools } = await h.client.listTools(); + const repl = tools.find((tool) => tool.name === "repl"); + assert.ok(repl?.description); + // The names come from the runner's own registry, not a typed list. + assert.match(repl.description, /read_file\(/); + assert.match(repl.description, /list_files\(/); + assert.match(repl.description, /bash\(.*\) \[approval\]/); + assert.match(repl.description, /write\(.*\) \[approval\]/); + assert.doesNotMatch(repl.description, /\bread\(/, "the bridged read is not in a repl session"); + assert.match(repl.description, /save_tool/); + }); + + it("declares the input schemas a model needs: repl.code and repl_resume.approvalId are required", async () => { + const { tools } = await h.client.listTools(); + const schema = (name: string) => + tools.find((tool) => tool.name === name)?.inputSchema as { + properties: Record; + required?: string[]; + }; + assert.deepEqual(schema("repl").required, ["code"]); + assert.deepEqual(Object.keys(schema("repl").properties).sort(), [ + "code", + "maxDurationSecs", + "maxMemory", + "sessionId", + ]); + assert.deepEqual(schema("repl_resume").required, ["approvalId"]); + assert.deepEqual(Object.keys(schema("repl_resume").properties).sort(), [ + "approvalId", + "decision", + "sessionId", + ]); + assert.deepEqual(schema("rlm").required, ["question"]); + assert.deepEqual(Object.keys(schema("rlm").properties).sort(), [ + "budget", + "maxDepth", + "maxIterations", + "question", + ]); + }); + + it("annotates rlm as read-only and repl as not", async () => { + const { tools } = await h.client.listTools(); + const byName = new Map(tools.map((tool) => [tool.name, tool])); + assert.equal(byName.get("rlm")?.annotations?.readOnlyHint, true); + assert.equal(byName.get("repl")?.annotations?.readOnlyHint, false); + assert.equal(byName.get("repl_resume")?.annotations?.readOnlyHint, false); + }); +}); + +// ── repl ───────────────────────────────────────────────────────── + +describe("MCP server — repl", () => { + let h: Harness; + before(async () => { + h = await connect(); + writeFileSync(join(h.root, "data.csv"), "label,value\na,1\nb,5\nc,3\n"); + }); + after(() => h.close()); + + it("keeps state across calls on one sessionId", async () => { + const first = await call(h, "repl", { code: "x = 41", sessionId: "s1" }); + assert.equal(first.isError, false); + const second = await call(h, "repl", { code: "x + 1", sessionId: "s1" }); + assert.match(second.text, /\[result\]\n42$/); + }); + + it("defaults sessionId to 'default'", async () => { + await call(h, "repl", { code: "y = 7" }); + const result = await call(h, "repl", { code: "y", sessionId: "default" }); + assert.match(result.text, /\[result\]\n7$/); + }); + + it("refuses `import subprocess` with a typing error, as text", async () => { + const result = await call(h, "repl", { code: "import subprocess", sessionId: "s2" }); + assert.match(result.text, /\[error: typing\]/); + }); + + it("read_file is jailed to the root: /etc/passwd is refused with PermissionError text", async () => { + const result = await call(h, "repl", { + code: 'read_file("/etc/passwd")', + sessionId: "s2", + }); + assert.match(result.text, /\[error: runtime\]/); + assert.match(result.text, /PermissionError/); + assert.doesNotMatch(result.text, /root:x:0:0/); + }); + + it("read_file resolves relative to the root", async () => { + const result = await call(h, "repl", { + code: 'rows = read_file("data.csv").strip().split("\\n")[1:]\nsum(int(r.split(",")[1]) for r in rows)', + sessionId: "s3", + }); + assert.match(result.text, /\[result\]\n9$/); + }); + + it("stdout and the result both arrive", async () => { + const result = await call(h, "repl", { code: 'print("hi")\n1 + 1', sessionId: "s4" }); + assert.equal(result.text, "hi\n\n[result]\n2"); + }); + + it("clamps a model-supplied limit rather than trusting it", async () => { + // 9999 s is above the 300 s ceiling; the run still completes, which is + // all a clamp test can see from outside without waiting out a timeout. + const result = await call(h, "repl", { + code: "2 + 2", + sessionId: "s5", + maxDurationSecs: 9999, + maxMemory: 99999, + }); + assert.match(result.text, /\[result\]\n4$/); + }); + + it("rejects a call with no code at the schema, as an error result naming the field", async () => { + // The SDK validates arguments before the handler runs and answers with an + // error result rather than a protocol error, so the model can correct it. + const result = await h.client.callTool({ name: "repl", arguments: {} }); + assert.equal(result.isError, true); + assert.match(JSON.stringify(result.content), /code/); + }); +}); + +// ── Approvals ──────────────────────────────────────────────────── + +describe("MCP server — approvals suspend and resume", () => { + let h: Harness; + before(async () => { + h = await connect(); + }); + after(() => h.close()); + + it("a gated call suspends; the result names the call, mints an approvalId, and says how to resume", async () => { + const result = await call(h, "repl", { + code: 'out = bash("echo approved-run")\nprint("after:", out.strip())', + sessionId: "a1", + }); + assert.equal(result.isError, false); + assert.match(result.text, /Tool 'bash' requires approval/); + assert.match(result.text, /bash\(command="echo approved-run"/); + const id = approvalIdOf(result.text); + assert.match(result.text, /has NOT run/); + assert.match(result.text, new RegExp(`repl_resume\\(sessionId='a1', approvalId='${id}'\\)`)); + assert.match(result.text, /permission/i); + assert.match(result.text, /repl_abandon\(sessionId='a1'\)/); + assert.doesNotMatch(result.text, /after:/, "the code after the gate must not have run"); + }); + + it("repl_resume with a stale or wrong approvalId resumes nothing and says which call is pending", async () => { + const result = await call(h, "repl_resume", { sessionId: "a1", approvalId: "00000000" }); + assert.equal(result.isError, true); + assert.match(result.text, /Nothing ran/); + assert.match(result.text, /bash\(command="echo approved-run"/); + const id = approvalIdOf(result.text); + assert.notEqual(id, "00000000"); + }); + + it("repl_resume with the right approvalId runs the call and the code after it", async () => { + const pending = await call(h, "repl_resume", { sessionId: "a1", approvalId: "00000000" }); + const id = approvalIdOf(pending.text); + const result = await call(h, "repl_resume", { sessionId: "a1", approvalId: id }); + assert.equal(result.isError, false); + assert.match(result.text, /^\[approved\]/); + assert.match(result.text, /after: approved-run/); + assert.doesNotMatch(result.text, /approvalId:/, "nothing is pending any more"); + }); + + it("after a decided approval, repl_resume says nothing is pending", async () => { + const result = await call(h, "repl_resume", { sessionId: "a1", approvalId: "00000000" }); + assert.equal(result.isError, true); + assert.match(result.text, /no approval pending/i); + assert.match(result.text, /Nothing was resumed/); + }); + + it("repl_resume on an unknown session says so", async () => { + const result = await call(h, "repl_resume", { sessionId: "never", approvalId: "00000000" }); + assert.equal(result.isError, true); + assert.match(result.text, /no approval pending/i); + }); + + it("decision='deny' refuses the call: Python sees PermissionError and the run continues", async () => { + const paused = await call(h, "repl", { + code: 'try:\n bash("echo should-not-run")\nexcept PermissionError as e:\n print("denied:", type(e).__name__)\n"done"', + sessionId: "a2", + }); + const id = approvalIdOf(paused.text); + const result = await call(h, "repl_resume", { + sessionId: "a2", + approvalId: id, + decision: "deny", + }); + assert.equal(result.isError, false); + assert.match(result.text, /^\[denied\]/); + assert.match(result.text, /denied: PermissionError/); + assert.match(result.text, /\[result\]\ndone$/); + assert.doesNotMatch( + result.text, + /should-not-run\n/, + "the command's own output must not appear", + ); + }); + + it("every gated call gets its own approval: a second one suspends again with a new id", async () => { + const paused = await call(h, "repl", { + code: 'a = bash("echo one").strip()\nb = bash("echo two").strip()\nprint(a, b)', + sessionId: "a3", + }); + const first = approvalIdOf(paused.text); + const again = await call(h, "repl_resume", { sessionId: "a3", approvalId: first }); + assert.match(again.text, /Tool 'bash' requires approval/); + assert.match(again.text, /bash\(command="echo two"/); + const second = approvalIdOf(again.text); + assert.notEqual(second, first, "a new suspension is a new decision"); + // The first id is spent. + const stale = await call(h, "repl_resume", { sessionId: "a3", approvalId: first }); + assert.equal(stale.isError, true); + const done = await call(h, "repl_resume", { sessionId: "a3", approvalId: second }); + assert.match(done.text, /one two/); + }); + + it("repl_abandon drops the pending call without running it, and says so", async () => { + const paused = await call(h, "repl", { + code: 'bash("echo should-not-run")\nprint("after")', + sessionId: "a4", + }); + approvalIdOf(paused.text); + const result = await call(h, "repl_abandon", { sessionId: "a4" }); + assert.equal(result.isError, false); + assert.match(result.text, /abandoned/); + assert.match(result.text, /dropped/); + const resume = await call(h, "repl_resume", { sessionId: "a4", approvalId: "00000000" }); + assert.match(resume.text, /no approval pending/i); + // The session lives on. + const next = await call(h, "repl", { code: "3 * 3", sessionId: "a4" }); + assert.match(next.text, /\[result\]\n9$/); + }); + + it("repl_abandon distinguishes nothing-pending from no-session", async () => { + const idle = await call(h, "repl_abandon", { sessionId: "a4" }); + assert.match(idle.text, /no pending approval/); + const none = await call(h, "repl_abandon", { sessionId: "ghost" }); + assert.match(none.text, /No session 'ghost' exists/); + }); + + it("running new code while a call is pending discards it, and the approval id dies with it", async () => { + const paused = await call(h, "repl", { code: 'bash("echo stale")', sessionId: "a5" }); + const id = approvalIdOf(paused.text); + const next = await call(h, "repl", { code: "1", sessionId: "a5" }); + assert.match(next.text, /^\[discarded\]/); + const resume = await call(h, "repl_resume", { sessionId: "a5", approvalId: id }); + assert.equal(resume.isError, true); + assert.match(resume.text, /no approval pending/i); + }); + + it("ANTHROPIC_API_KEY in the server process never reaches an approved bash", async () => { + const previous = process.env.ANTHROPIC_API_KEY; + process.env.ANTHROPIC_API_KEY = "sk-ant-test-secret-do-not-leak"; + try { + const paused = await call(h, "repl", { + code: 'print(bash("printenv ANTHROPIC_API_KEY || echo key=unset"))', + sessionId: "a6", + }); + const id = approvalIdOf(paused.text); + const result = await call(h, "repl_resume", { sessionId: "a6", approvalId: id }); + assert.match(result.text, /key=unset/); + assert.doesNotMatch(result.text, /do-not-leak/); + } finally { + if (previous === undefined) delete process.env.ANTHROPIC_API_KEY; + else process.env.ANTHROPIC_API_KEY = previous; + } + }); +}); + +// ── repl_reset ─────────────────────────────────────────────────── + +describe("MCP server — repl_reset", () => { + let h: Harness; + before(async () => { + h = await connect(); + }); + after(() => h.close()); + + it("clears a session's state and reports it", async () => { + await call(h, "repl", { code: "z = 1", sessionId: "r1" }); + const reset = await call(h, "repl_reset", { sessionId: "r1" }); + assert.match(reset.text, /Session 'r1' reset\./); + assert.match(reset.text, /No approval grants were outstanding/); + const after = await call(h, "repl", { code: "z", sessionId: "r1" }); + assert.match(after.text, /\[error: typing\]/); + }); + + it("does not claim to have reset a session that never existed", async () => { + const reset = await call(h, "repl_reset", { sessionId: "nope" }); + assert.match(reset.text, /No session 'nope' exists/); + assert.doesNotMatch(reset.text, /grants/); + }); + + it("drops a pending approval with the session", async () => { + const paused = await call(h, "repl", { code: 'bash("echo x")', sessionId: "r2" }); + const id = approvalIdOf(paused.text); + await call(h, "repl_reset", { sessionId: "r2" }); + const resume = await call(h, "repl_resume", { sessionId: "r2", approvalId: id }); + assert.equal(resume.isError, true); + }); +}); + +// ── Project trust ──────────────────────────────────────────────── + +describe("MCP server — project trust", () => { + it("is untrusted by default: saved tools in .pi/code-tools do not load", async () => { + const h = await connect(); + try { + saveToolFile(h.root, "greet", 'def greet():\n return "hi"\n'); + const result = await call(h, "repl", { code: "greet()", sessionId: "t1" }); + assert.match(result.text, /\[error: typing\]/); + assert.doesNotMatch(result.text, /\[result\]\nhi/); + } finally { + await h.close(); + } + }); + + it("trustProject: true wires the runner's trust gate, and an accepted set then loads", async () => { + const h = await connect({ trustProject: true }); + try { + saveToolFile(h.root, "greet", 'def greet():\n return "hi"\n'); + // Trust is not consent to the files (#198): nothing unapproved loads, + // and the server has no dialog to ask on, so the set is withheld... + const before = await call(h, "repl", { code: "greet()", sessionId: "t2" }); + assert.match(before.text, /\[error: typing\]/); + // ...until it is accepted. This is the library's own acceptance path; + // the point here is only that the server's trust option reached it. + const accepted = await h.replServer.runner.acceptPreamble(); + assert.equal(accepted.status, "accepted"); + const after = await call(h, "repl", { code: "greet()", sessionId: "t3" }); + assert.match(after.text, /\[result\]\nhi$/); + } finally { + await h.close(); + } + }); + + it("an untrusted runner refuses acceptPreamble, so no env knob but the trust one can load code", async () => { + const h = await connect(); + try { + saveToolFile(h.root, "greet", 'def greet():\n return "hi"\n'); + assert.equal((await h.replServer.runner.acceptPreamble()).status, "untrusted"); + } finally { + await h.close(); + } + }); +}); + +// ── rlm ────────────────────────────────────────────────────────── + +describe("MCP server — rlm", () => { + it("runs the loop against the injected LlmClient and renders the result as untrusted", async () => { + const llm = cannedLlm(['```python\nSUBMIT("b")\n```']); + const h = await connect({ llmClient: llm }); + try { + writeFileSync(join(h.root, "data.csv"), "label,value\na,1\nb,5\n"); + const result = await call(h, "rlm", { question: "largest label?" }); + assert.equal(result.isError, false); + assert.match(result.text, /^\[RLM inner-model output — untrusted\]/); + assert.match(result.text, /status: ok/); + assert.match(result.text, /answerSource: submitted/); + assert.match(result.text, /answer: b$/); + assert.equal(llm.queries.length, 1); + assert.match(llm.queries[0].system, /read_file/, "the loop's registry has the readers"); + } finally { + await h.close(); + } + }); + + it("refuses an empty question", async () => { + const h = await connect(); + try { + const result = await call(h, "rlm", { question: " " }); + assert.equal(result.isError, true); + assert.match(result.text, /non-empty question/); + } finally { + await h.close(); + } + }); + + it("reports a failing LlmClient as a result, not a crash, with the error redacted into the text", async () => { + const llm: LlmClient = { + async query() { + throw new Error("401 authentication_error: invalid x-api-key"); + }, + }; + const h = await connect({ llmClient: llm }); + try { + const result = await call(h, "rlm", { question: "anything" }); + assert.match(result.text, /status: error/); + assert.match(result.text, /authentication_error/); + // The server is still up. + const next = await call(h, "repl", { code: "1 + 1" }); + assert.match(next.text, /\[result\]\n2$/); + } finally { + await h.close(); + } + }); + + it("clamps the model-supplied knobs: iterations stop at the ceiling, not at the request", async () => { + // Fourteen non-submitting replies; the ceiling is 10, so the loop must end + // at max_iterations having asked ten times for code plus once for the + // synthesised answer — eleven, never the fourteen it could have consumed. + const llm = cannedLlm(Array.from({ length: 14 }, () => "```python\n1\n```")); + const h = await connect({ llmClient: llm }); + try { + const result = await call(h, "rlm", { question: "q", maxIterations: 50 }); + assert.match(result.text, /status: max_iterations/); + assert.ok(llm.queries.length <= 11, `asked ${llm.queries.length} times`); + } finally { + await h.close(); + } + }); +}); + +// ── Lifecycle ──────────────────────────────────────────────────── + +describe("MCP server — close", () => { + it("close() abandons and releases every session the server was handed", async () => { + const h = await connect(); + await call(h, "repl", { code: 'bash("echo pending")', sessionId: "c1" }); + await call(h, "repl", { code: "1", sessionId: "c2" }); + assert.equal(h.replServer.runner.liveSessionCount(), 2); + await h.close(); + assert.equal(h.replServer.runner.liveSessionCount(), 0); + }); +}); From 52f3307622b451c0737dd65d287b6055d8f75ecd Mon Sep 17 00:00:00 2001 From: Adar Date: Mon, 5 Oct 2026 09:47:54 +0300 Subject: [PATCH 5/8] =?UTF-8?q?feat:=20repl-simple-mcp=20bin=20=E2=80=94?= =?UTF-8?q?=20the=20MCP=20server=20on=20stdio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit src/mcp_main.ts is the process edge and nothing else: configuration from the environment (REPL_MCP_ROOT, else CLAUDE_PROJECT_DIR, else cwd; REPL_MCP_TRUST_PROJECT), the server on StdioServerTransport, and a shutdown on stdin close / SIGINT / SIGTERM that abandons pending approvals, resets sessions and closes the worker pool. package.json gains bin.repl-simple-mcp → dist/mcp_main.js; tsc keeps the shebang. test/mcp_stdio.test.ts spawns the entry as a child and drives it over stdio through the SDK client: tool list, a clean protocol stream (a sandbox worker leaking to stdout would break it), clean stderr, cwd vs CLAUDE_PROJECT_DIR as root, exit 0 when stdin closes. packaging.test.ts pins the bin in the manifest, the shebang in dist/, the file in the tarball, and the packed bin answering an MCP initialize offline. stryker: src/mcp_main.ts leaves the mutate set — its only test runs it as a child process, so a mutant there is invisible to the in-process runner. Co-Authored-By: Claude Opus 5.5 --- package.json | 3 + src/anthropic_client.ts | 4 +- src/mcp_main.ts | 31 ++++++++ stryker.config.json | 2 +- test/anthropic_client.test.ts | 6 +- test/mcp_stdio.test.ts | 145 ++++++++++++++++++++++++++++++++++ test/packaging.test.ts | 60 ++++++++++++++ 7 files changed, 248 insertions(+), 3 deletions(-) create mode 100644 src/mcp_main.ts create mode 100644 test/mcp_stdio.test.ts diff --git a/package.json b/package.json index e218008..57f472f 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,9 @@ "import": "./dist/index.js" } }, + "bin": { + "repl-simple-mcp": "dist/mcp_main.js" + }, "files": [ "dist", "src", diff --git a/src/anthropic_client.ts b/src/anthropic_client.ts index bc770c3..f75ddc6 100644 --- a/src/anthropic_client.ts +++ b/src/anthropic_client.ts @@ -93,7 +93,9 @@ export function createAnthropicLlmClient(options: AnthropicLlmClientOptions = {} ); if (reply.stop_reason === "refusal") { const category = reply.stop_details?.category ?? "unspecified"; - throw new Error(`Anthropic refused the request (stop_reason: refusal, category: ${category})`); + throw new Error( + `Anthropic refused the request (stop_reason: refusal, category: ${category})`, + ); } if (reply.stop_reason === "max_tokens") { throw new Error( diff --git a/src/mcp_main.ts b/src/mcp_main.ts new file mode 100644 index 0000000..a056132 --- /dev/null +++ b/src/mcp_main.ts @@ -0,0 +1,31 @@ +#!/usr/bin/env node +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { configFromEnv, createReplMcpServer } from "./mcp_server.js"; + +// ── The `repl-simple-mcp` bin ──────────────────────────────────── +// +// The process edge of src/mcp_server.ts, and nothing else: configuration +// from the environment, the server on stdio, and a shutdown that releases +// the sandbox workers. stdout belongs to the transport — every byte on it is +// a JSON-RPC frame — so this file never writes there, and neither does +// anything it loads. +// +// The server exits when its client does: stdin closing is the transport's +// `onclose`, and SIGINT / SIGTERM arrive the same way. `close()` abandons +// every pending approval (nothing pending ever executes), resets the +// sessions and closes the worker pool before the process ends. + +const replServer = createReplMcpServer(configFromEnv()); + +let closing = false; +function shutdown(code: number): void { + if (closing) return; + closing = true; + void replServer.close().finally(() => process.exit(code)); +} + +replServer.server.server.onclose = () => shutdown(0); +process.on("SIGINT", () => shutdown(0)); +process.on("SIGTERM", () => shutdown(0)); + +await replServer.server.connect(new StdioServerTransport()); diff --git a/stryker.config.json b/stryker.config.json index 42d321b..0f74de4 100644 --- a/stryker.config.json +++ b/stryker.config.json @@ -6,7 +6,7 @@ "testFiles": ["test/*.test.ts"], "nodeArgs": ["--import", "tsx", "--test-reporter=tap", "-r", "{{hookFile}}", "{{testFile}}"] }, - "mutate": ["src/**/*.ts", "extensions/**/*.ts"], + "mutate": ["src/**/*.ts", "extensions/**/*.ts", "!src/mcp_main.ts"], "coverageAnalysis": "perTest", "concurrency": 6, "incremental": true, diff --git a/test/anthropic_client.test.ts b/test/anthropic_client.test.ts index a882c7d..722272c 100644 --- a/test/anthropic_client.test.ts +++ b/test/anthropic_client.test.ts @@ -220,7 +220,11 @@ describe("createAnthropicLlmClient", () => { // actually queries. We only assert the construction half here; the SDK's // own credential resolution is not under test. await withEnv( - { ANTHROPIC_API_KEY: undefined, ANTHROPIC_AUTH_TOKEN: undefined, ANTHROPIC_PROFILE: undefined }, + { + ANTHROPIC_API_KEY: undefined, + ANTHROPIC_AUTH_TOKEN: undefined, + ANTHROPIC_PROFILE: undefined, + }, () => { assert.doesNotThrow(() => createAnthropicLlmClient()); }, diff --git a/test/mcp_stdio.test.ts b/test/mcp_stdio.test.ts new file mode 100644 index 0000000..a566f06 --- /dev/null +++ b/test/mcp_stdio.test.ts @@ -0,0 +1,145 @@ +import { describe, it, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { MCP_TOOL_NAMES } from "../src/mcp_server.js"; +import { REPO_ROOT } from "./support/pack-fixture.js"; + +/** + * The `bin` entry, end to end: `src/mcp_main.ts` spawned as a child process + * and driven over its stdin/stdout the way Claude Code drives it. This is the + * one test that can see what the in-memory tests cannot — that nothing in the + * process (the sandbox workers included) writes to stdout besides JSON-RPC, + * that the server roots at the directory Claude Code names, and that it exits + * when the client goes away. The entry is run from source through tsx; the + * compiled `dist/mcp_main.js` is the same file, checked by packaging.test.ts. + */ + +const MAIN = join(REPO_ROOT, "src", "mcp_main.ts"); + +/** + * tsx's ESM loader as a file URL. `--import tsx` would resolve the bare + * specifier from the child's cwd — a temp dir with no node_modules — so the + * loader is named absolutely, resolved from this file's own tree. + */ +const TSX_LOADER = import.meta.resolve("tsx"); + +/** The node arguments that run the entry from source. */ +const NODE_ARGS = ["--import", TSX_LOADER, MAIN]; + +/** The child's environment: the test's own, minus every Anthropic credential, plus what is asked. */ +function childEnv(extra: Record): Record { + const env: Record = {}; + for (const [key, value] of Object.entries(process.env)) { + if (value === undefined) continue; + if (key.startsWith("ANTHROPIC_")) continue; + env[key] = value; + } + // No bridged tool may reach the network from the child either (#91). + env.PI_OFFLINE = "1"; + return { ...env, ...extra }; +} + +async function spawnServer(cwd: string, extraEnv: Record = {}) { + const transport = new StdioClientTransport({ + command: process.execPath, + args: NODE_ARGS, + cwd, + env: childEnv(extraEnv), + stderr: "pipe", + }); + const stderr: string[] = []; + transport.stderr?.on("data", (chunk: Buffer) => stderr.push(chunk.toString())); + const client = new Client({ name: "mcp-stdio-test", version: "0.0.0" }); + await client.connect(transport); + return { client, transport, stderr }; +} + +async function callText(client: Client, name: string, args: Record) { + const result = await client.callTool({ name, arguments: args }); + return (result.content as Array<{ type: string; text?: string }>) + .filter((block) => block.type === "text") + .map((block) => block.text ?? "") + .join(""); +} + +describe("MCP server over stdio (the bin entry)", () => { + let cwd: string; + let project: string; + before(() => { + cwd = mkdtempSync(join(tmpdir(), "repl-mcp-stdio-cwd-")); + project = mkdtempSync(join(tmpdir(), "repl-mcp-stdio-proj-")); + writeFileSync(join(cwd, "where.txt"), "cwd\n"); + writeFileSync(join(project, "where.txt"), "project\n"); + }); + after(() => { + rmSync(cwd, { recursive: true, force: true }); + rmSync(project, { recursive: true, force: true }); + }); + + it("starts without a key, lists the five tools, and runs code with a clean protocol stream", async () => { + const { client, transport, stderr } = await spawnServer(cwd); + try { + const { tools } = await client.listTools(); + assert.deepEqual(tools.map((tool) => tool.name).sort(), [...MCP_TOOL_NAMES].sort()); + // A print and a result: if a sandbox worker leaked to stdout, this call + // would have failed to parse rather than returned. + const text = await callText(client, "repl", { code: 'print("over stdio")\n6 * 7' }); + assert.equal(text, "over stdio\n\n[result]\n42"); + assert.equal(stderr.join(""), "", "a clean run writes nothing to stderr"); + } finally { + await client.close(); + await transport.close(); + } + }); + + it("roots at the cwd by default, and at CLAUDE_PROJECT_DIR when Claude Code sets it", async () => { + const byCwd = await spawnServer(cwd); + try { + assert.match( + await callText(byCwd.client, "repl", { code: 'read_file("where.txt").strip()' }), + /\[result\]\ncwd$/, + ); + } finally { + await byCwd.client.close(); + } + const byProject = await spawnServer(cwd, { CLAUDE_PROJECT_DIR: project }); + try { + assert.match( + await callText(byProject.client, "repl", { code: 'read_file("where.txt").strip()' }), + /\[result\]\nproject$/, + ); + } finally { + await byProject.client.close(); + } + }); + + it("exits on its own when stdin closes — the client went away — with status 0", async () => { + // Spawned by hand rather than through the SDK transport, whose close() + // kills the child and would prove nothing about the server's own exit. + const child = spawn(process.execPath, NODE_ARGS, { + cwd, + env: childEnv({}), + stdio: ["pipe", "ignore", "pipe"], + }); + const exited = new Promise((resolve) => + child.on("exit", (code) => resolve(code)), + ); + child.stdin.end(); + const outcome = await Promise.race([ + exited, + new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), 15_000)), + ]); + if (outcome === "timeout") child.kill("SIGKILL"); + assert.equal(outcome, 0, "the server must exit cleanly once its client is gone"); + }); + + it("src/mcp_main.ts carries the shebang the bin needs, and nothing else runs at import", () => { + const source = readFileSync(MAIN, "utf8"); + assert.ok(source.startsWith("#!/usr/bin/env node\n"), "the entry must start with a shebang"); + }); +}); diff --git a/test/packaging.test.ts b/test/packaging.test.ts index 15dde96..0ae758e 100644 --- a/test/packaging.test.ts +++ b/test/packaging.test.ts @@ -120,6 +120,15 @@ describe("build output", () => { ); }); + it("emits the MCP bin at dist/mcp_main.js with its shebang intact", () => { + const main = join(DIST, "mcp_main.js"); + assert.ok(existsSync(main), "expected dist/mcp_main.js — the `bin` target — to exist"); + assert.ok( + readFileSync(main, "utf8").startsWith("#!/usr/bin/env node\n"), + "tsc must keep the shebang on the first line, or `bin` cannot run the file", + ); + }); + it("emits no test files into dist/", () => { const files = filesRelativeTo(DIST); const testFiles = files.filter((f) => f.split(sep)[0] === "test" || /\.test\./.test(f)); @@ -149,6 +158,11 @@ describe("tarball contents (#81)", () => { files.includes("repl/repl_server.py"), "tarball must include repl/repl_server.py (the preamble asset)", ); + // The MCP bin target must ship, or `repl-simple-mcp` resolves to nothing after install. + assert.ok( + files.includes("dist/mcp_main.js"), + "tarball must include dist/mcp_main.js (the bin)", + ); // The packaged skill manifest must ship so pi can load the skill from the package. assert.ok( files.includes("skills/repl-simple/SKILL.md"), @@ -203,6 +217,42 @@ describe("scratch consumer (offline, SPEC AS6)", () => { }); }); +describe("scratch consumer (offline): the bin", () => { + it("dist/mcp_main.js from the packed artifact starts and answers an MCP handshake", () => { + // One JSON-RPC `initialize` on stdin, one response on stdout, then stdin + // closes and the server exits. Pins the whole chain a Claude Code user + // relies on: the bin resolves its deps from the installed package, speaks + // the protocol on stdout, and writes nothing else there. + const initialize = JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "packaging-test", version: "0" }, + }, + }); + const run = spawnSync(process.execPath, [join(packedPkgDir, "dist", "mcp_main.js")], { + cwd: consumerDir, + encoding: "utf8", + input: `${initialize}\n`, + timeout: 30_000, + env: { ...process.env, PI_OFFLINE: "1" }, + }); + assert.equal(run.status, 0, `bin exited ${run.status}:\n${run.stdout}\n${run.stderr}`); + const lines = run.stdout.split("\n").filter((line) => line.trim() !== ""); + assert.equal(lines.length, 1, `expected exactly one JSON-RPC frame on stdout:\n${run.stdout}`); + const reply = JSON.parse(lines[0]) as { + id: number; + result?: { serverInfo?: { name?: string; version?: string } }; + }; + assert.equal(reply.id, 1); + assert.equal(reply.result?.serverInfo?.name, "repl-simple"); + assert.equal(reply.result?.serverInfo?.version, readManifest().version); + }); +}); + describe("export reachability", () => { it("every value export of src/index.ts is reachable from the packed artifact", async () => { const pkg = await import(pathToFileURL(join(packedPkgDir, "dist", "index.js")).href); @@ -221,8 +271,10 @@ describe("export reachability", () => { interface Manifest { private?: boolean; + version?: string; main?: string; types?: string; + bin?: Record; exports?: Record; files?: string[]; license?: string; @@ -259,6 +311,14 @@ describe("manifest", () => { assert.equal(pkg.scripts?.prepublishOnly, "npm run build"); }); + it("declares the repl-simple-mcp bin, pointing at the built entry under dist/", () => { + const pkg = readManifest(); + assert.equal(pkg.bin?.["repl-simple-mcp"], "dist/mcp_main.js"); + // The target must be inside `files`' dist/ (shipped) and emitted by the + // build config, which includes src/**/*.ts — src/mcp_main.ts is the source. + assert.ok(existsSync(join(REPO_ROOT, "src", "mcp_main.ts")), "src/mcp_main.ts must exist"); + }); + it("files ships dist, src, repl, extensions, skills, and NOTICE (D3)", () => { const pkg = readManifest(); assert.ok(Array.isArray(pkg.files), "package.json must declare a `files` allowlist"); From 04645df0aa747db9740a5f9ab749959c2aafe565 Mon Sep 17 00:00:00 2001 From: Adar Date: Mon, 5 Oct 2026 09:47:54 +0300 Subject: [PATCH 6/8] docs: README section for the Claude Code MCP server MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Install from a clone, the claude mcp add command, the five MCP tools (table pinned by test/readme.test.ts against MCP_TOOL_NAMES), the approval semantics — suspend, approvalId, repl_resume as the human gate behind Claude Code's permission prompt, deny, abandon, and what allow-listing removes — the environment variables, and the limits (Monty sandbox, glibc only / no musl, serialised calls, no pi commands). Module map rows for the new files; the mutate-set exclusion noted under Mutation score. Co-Authored-By: Claude Opus 5.5 --- README.md | 99 +++++++++++++++++++++++++++++++++++++++++++++ test/readme.test.ts | 12 ++++++ 2 files changed, 111 insertions(+) diff --git a/README.md b/README.md index c928605..303fd73 100644 --- a/README.md +++ b/README.md @@ -301,6 +301,99 @@ install and looks like a way around this. It is not: it runs Python in-process, blocks the event loop and there is no crash isolation. See [docs/platform-support.md](docs/platform-support.md). +## Claude Code (MCP server) + +The same five tools, served over [MCP](https://modelcontextprotocol.io) stdio so Claude Code — or +any MCP client — can call them without pi. The server is the package `bin`, `repl-simple-mcp` +(`dist/mcp_main.js`, built by `npm run build`); it wraps the same `ReplRunner` and `runRlm` the pi +extension uses, through the same model boundary (`src/model_boundary.ts`), and changes nothing about +pi. The package is not on npm yet, so install from a clone: + +```bash +git clone https://github.com/AdarGit008/repl-simple && cd repl-simple +npm install && npm run build +``` + +Then register it with Claude Code. Run this **in the project you want the sandbox rooted at**: + +```bash +claude mcp add --transport stdio repl-simple \ + --env ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" \ + -- node /absolute/path/to/repl-simple/dist/mcp_main.js +``` + +`--scope project` writes the entry to `.mcp.json` for the whole team instead of your local config; +Claude Code asks before using a project-scoped server, and strips credential-named variables +(`*KEY*`, `*TOKEN*`, …) from the environment it hands such servers, so the key has to be passed +explicitly — `--env`, or `"env": {"ANTHROPIC_API_KEY": "${ANTHROPIC_API_KEY}"}` in `.mcp.json`. +The key is only needed by `rlm`; `repl` works without one. + +The peer dependency `@earendil-works/pi-coding-agent` (the bridged `bash`/`grep`/… tools, see +[Install](#install)) is in `devDependencies`, so a clone's `npm install` has it; npm 7+ also installs +peers for a registry install. Without it the server fails at startup with `ERR_MODULE_NOT_FOUND` for +that package (`src/bridge.ts` imports it statically); nothing runs half-configured. + +### MCP tools + +| Tool | Description | +|------|-------------| +| `repl(code, sessionId?, maxDurationSecs?, maxMemory?)` | Execute Python in a named session. Variables persist across calls. The description a model reads lists the Python-side host tools, read off the runner's own registry. | +| `repl_resume(approvalId, sessionId?, decision?)` | Decide the pending gated call — `approve` (default) runs it, `deny` refuses it — and continue the run. `approvalId` must be the id the suspended result handed back. | +| `repl_reset(sessionId?)` | Clear all state in a session, pending approval included. | +| `repl_abandon(sessionId?)` | Drop a pending gated call without running it; the session keeps its state. | +| `rlm(question, maxIterations?, maxDepth?, budget?)` | The autonomous read-only code-gen → execute loop, on the Anthropic API. The answer is inner-model output and must be treated as untrusted. | + +### Approvals over MCP + +MCP has no dialog for the server to open, and the server **never approves anything on its own**. +Every gated call (`bash`, `edit`, `write`, `save_tool`, an unlisted `http_get`) suspends the run — +the library's "decide later" answer — and the result says so: the call has **not** run, here is the +call, here is its `approvalId`, and these are the three things that decide it: + +- `repl_resume(sessionId, approvalId)` runs it. **Claude Code's permission prompt in front of that + tool call is the human approval**: the user sees `repl_resume` with the id and the session, and + the preceding `repl` result in the transcript names the exact call. The id binds the decision to + the call that was shown — any other id (stale after new code ran, mistyped, guessed) resumes + nothing and the result repeats the pending call and its id. If the continuation reaches another + gated call it suspends again under a **new** id, so every gated call is its own prompt. +- `repl_resume(sessionId, approvalId, decision='deny')` refuses it: Python sees `PermissionError` + and the code continues, exactly as a denied dialog does in pi. +- `repl_abandon(sessionId)` drops the suspended run; the session lives on. Running new `repl` code on + the session does the same and says so (`[discarded]`). + +The gate therefore holds exactly as long as Claude Code asks. Allow-listing +`mcp__repl-simple__repl_resume` (or the whole server, `mcp__repl-simple`), answering "don't ask +again", or `--dangerously-skip-permissions` removes the human from the loop: every call the model +chooses to resume then runs. The MCP server is strict mode with no `yolo`; that switch is the +client's. Inside `rlm` nothing changes — gated tools are denied outright in the loop, as in pi. + +### Environment + +| Variable | Default | Meaning | +|---|---|---| +| `ANTHROPIC_API_KEY` | — | Read by the Anthropic SDK **in the server process**, for `rlm` only. Never logged, never put in a result, and withheld from the sandboxed `bash` by the env allowlist ([docs/bash-env.md](docs/bash-env.md)). Unset → `repl` works, `rlm` returns `status: error`. The SDK's other credential sources (`ANTHROPIC_AUTH_TOKEN`, an `ant auth login` profile) work too. | +| `REPL_RLM_ANTHROPIC_MODEL` | `claude-opus-5-5` | The model id the `rlm` loop queries. The operator's knob, not the model's: the MCP `rlm` tool has no `model`/`provider` parameters. | +| `REPL_MCP_ROOT` | `CLAUDE_PROJECT_DIR`, else the cwd | The project root: path jail, `.pi/code-tools`, the bridged tools' cwd. Claude Code sets `CLAUDE_PROJECT_DIR` for the servers it spawns, so the default is right under Claude Code. | +| `REPL_MCP_TRUST_PROJECT` | unset — **untrusted** | `1`/`true`/`yes` trusts the project, which lets an **accepted** saved-tool set load ([docs/project-trust.md](docs/project-trust.md)). Trust alone loads nothing: the server has no dialog to accept files on, so acceptance comes from pi's `/repl-accept-preamble` or an embedder calling `acceptPreamble()`. | + +Every `REPL_*` variable the sandbox reads applies unchanged — `REPL_RLM_BUDGET` (the `rlm` spend +ceiling), `REPL_MAX_*`, `REPL_HTTP_ALLOWLIST`, `REPL_BASH_ENV_ALLOW`, `REPL_PREAMBLE_STORE_DIR`. + +### Limits + +- Everything in [Sandbox](#sandbox) holds: Monty's fixed stdlib, no `subprocess`/sockets, no third-party + packages, the language gaps, the type checker, the 32 KiB / 16 KiB output caps. +- **glibc only.** `@pydantic/monty` has no musl build, so the server does not run on Alpine; see + [docs/platform-support.md](docs/platform-support.md). Node >= 22.19.0. +- One server process serves one root, and tool calls are serialised — the pi extension's + `executionMode: "sequential"` — so two `repl` calls in one turn run one after the other. +- Sessions live as long as the server process, which Claude Code starts and stops with its own + session; a pending approval dies with the process, unexecuted. `rlm` costs real API money per call; the default budget + bounds it (`REPL_RLM_BUDGET`). +- No `/repl-approvals yolo`, no `/repl-accept-preamble`, no result rendering: those are pi commands. + The trace a pi result carries on `details` is not sent over MCP — the result text is what the + model gets. + ## Dev ```bash @@ -330,6 +423,9 @@ not renamed): | `src/sandbox.ts`, `src/pool.ts` | One Monty run — dispatch loop, approval gate, limits — and the worker pool it checks out of. | | `src/registry.ts`, `src/builtins.ts`, `src/bridge.ts`, `src/toolstore.ts` | Host tools: the registry and stubs, the builtins, the jailed pi bridge, the saved-tool store. | | `extensions/repl-extension.ts` | The pi extension: registers the four tools and the `/repl-*` commands, renders results and the trace. | +| `src/model_boundary.ts` | The model boundary both hosts share: the limit clamps, the `rlm` knobs and their ceilings, the read-only `rlm` registry, the `rlm` result rendering. | +| `src/mcp_server.ts`, `src/mcp_main.ts` | The MCP host: `createReplMcpServer()` registers the five tools over the same runner and loop (approvals as suspend → `repl_resume` with an `approvalId`); `mcp_main.ts` is the `repl-simple-mcp` bin on stdio. | +| `src/anthropic_client.ts` | `createAnthropicLlmClient()` — the `LlmClient` for `rlm` outside pi, on the Anthropic SDK. | A rename would orphan the `coverage-baseline.json` keys, reopen the package `files` list (#81) and touch the pinned `scriptName` default `"rlm.py"` (`src/rlm.ts`, `test/rlm.test.ts` M21) that the @@ -549,6 +645,9 @@ universe is tracked `src/` and `extensions/` sources; the global is reported, no re-measured against Monty 0.0.21 on 2026-09-10 ([#175](https://github.com/AdarGit008/repl-simple/issues/175)). Full write-up, per-file scores and the reasoning behind every config value: [docs/mutation-testing.md](docs/mutation-testing.md). +One file is outside the mutate set: `src/mcp_main.ts`, the stdio process shim, whose only test +drives it as a child process — a mutant there is invisible to the in-process runner, so it would +count as uncovered rather than measure anything. **The floor moved up 58 → 79 because the tree's score did, not because the instrument got kinder.** Stryker's `coverageAnalysis: "perTest"` only skips tests that could not have killed the mutant, so diff --git a/test/readme.test.ts b/test/readme.test.ts index 3eccc31..c096e21 100644 --- a/test/readme.test.ts +++ b/test/readme.test.ts @@ -8,6 +8,7 @@ import { createPiBridgeTools } from "../src/bridge.js"; import { createBuiltinTools } from "../src/builtins.js"; import { createToolStoreTools } from "../src/toolstore.js"; import { createRLMTools } from "../src/rlm_tools.js"; +import { MCP_TOOL_NAMES } from "../src/mcp_server.js"; import { createPackFixture, REPO_ROOT, type PackFixture } from "./support/pack-fixture.js"; /** @@ -236,6 +237,17 @@ describe("README truth (#82)", () => { ); }); + it("the README 'MCP tools' table matches the tools the MCP server registers", () => { + // `MCP_TOOL_NAMES` is what `createReplMcpServer` registers, pinned against + // the live server by test/mcp_server.test.ts; the table must list exactly + // those, in registration order. + assert.deepEqual( + readmeTableToolNames(readme(), "### MCP tools"), + [...MCP_TOOL_NAMES], + "README 'MCP tools' table drifted from the MCP server's registered tools", + ); + }); + it("the README 'RLM Loop' table matches the tools runRlm registers (F3)", () => { assert.deepEqual( readmeTableToolNames(readme(), "### RLM Loop (auto-investigation)"), From d1ab2fdb0e71e2aad957bab4c31737b7fa4e8658 Mon Sep 17 00:00:00 2001 From: Adar Date: Mon, 5 Oct 2026 09:52:24 +0300 Subject: [PATCH 7/8] chore: coverage floors for the MCP files; mcp_main.ts unmeasured with its reason MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit npm run coverage:update (3 runs, per-file minima): src/anthropic_client.ts 99.07, src/mcp_server.ts 97.78, src/model_boundary.ts 100; the existing floors re-measured on the same tree (extensions/repl-extension.ts 99.88 after the move). src/preamble.ts fell 100 → 97.05: a one-line observation on a 34-line file — the documented instrument defect (#113), which the gate's one-line tolerance already absorbs. src/mcp_main.ts joins UNMEASURED_SOURCE_FILES: its test spawns it as a child process over stdio, and Node's coverage does not follow into a child run through the tsx loader, so it never reaches the report. Everything it calls (src/mcp_server.ts) is floored. Co-Authored-By: Claude Opus 5.5 --- coverage-baseline.json | 25 ++++++++++++++----------- scripts/coverage.mjs | 12 +++++++++++- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/coverage-baseline.json b/coverage-baseline.json index 50e0bc4..29e9331 100644 --- a/coverage-baseline.json +++ b/coverage-baseline.json @@ -1,24 +1,27 @@ { - "global": 99.05, + "global": 98.99, "files": { - "extensions/repl-extension.ts": 99.87, + "extensions/repl-extension.ts": 99.88, + "src/anthropic_client.ts": 99.07, "src/bashenv.ts": 84.21, - "src/bridge.ts": 99.69, + "src/bridge.ts": 99.71, "src/budget.ts": 100, - "src/builtins.ts": 99.53, + "src/builtins.ts": 99.59, + "src/mcp_server.ts": 97.78, + "src/model_boundary.ts": 100, "src/pathjail.ts": 98.63, "src/pool.ts": 100, - "src/preamble.ts": 100, - "src/redact.ts": 99.7, - "src/registry.ts": 98.27, + "src/preamble.ts": 97.05, + "src/redact.ts": 99.71, + "src/registry.ts": 98.45, "src/repl.ts": 100, - "src/rlm_client.ts": 90.36, + "src/rlm_client.ts": 90.76, "src/rlm_tools.ts": 100, - "src/rlm.ts": 99.64, - "src/sandbox.ts": 98.04, + "src/rlm.ts": 99.66, + "src/sandbox.ts": 98.14, "src/session.ts": 99.87, "src/submit_signal.ts": 100, - "src/toolstore.ts": 98.9, + "src/toolstore.ts": 99.45, "src/truncate.ts": 99.89, "src/types.ts": 100 } diff --git a/scripts/coverage.mjs b/scripts/coverage.mjs index 4a7e855..3acb882 100644 --- a/scripts/coverage.mjs +++ b/scripts/coverage.mjs @@ -73,8 +73,18 @@ const EXCLUDED_TEST_FILES = ["test/extension-loader.test.ts"]; * No test imports it, so it never reaches the report, and there is no * behaviour in it to cover if one did. `npm run check` already fails if a * re-exported name stops resolving, which is the only way a barrel breaks. + * + * `src/mcp_main.ts` is the `repl-simple-mcp` bin: configuration from the + * environment, the server on stdio, a shutdown hook. Its test + * (`test/mcp_stdio.test.ts`) spawns it as a child process and drives it over + * stdin/stdout — the only way to see what it does. Node's coverage follows + * into that child only some of the time (measured: absent from all three + * `--update` runs, present at 80.64% in the next plain run), and a floor on + * a file that is sometimes absent from the report is a hard error by design + * ("has a floor but is absent"). Everything it calls (`src/mcp_server.ts`) + * is floored. */ -const UNMEASURED_SOURCE_FILES = ["src/index.ts"]; +const UNMEASURED_SOURCE_FILES = ["src/index.ts", "src/mcp_main.ts"]; /** Every tracked source file expected to carry a floor. * From bba4b8681ce694561cb48dcb4d46e24a1106aa75 Mon Sep 17 00:00:00 2001 From: Adar Date: Mon, 5 Oct 2026 10:20:35 +0300 Subject: [PATCH 8/8] =?UTF-8?q?docs:=20repo=20files=20carry=20code=20only?= =?UTF-8?q?=20=E2=80=94=20drop=20the=20MCP=20prose,=20fix=20the=20two=20li?= =?UTF-8?q?nes=20it=20made=20false?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit README.md returns to main's text except its first line, and package.json's description changes in the same few words: both said "Pi extension —", and the package now also ships the repl-simple-mcp bin. The "Claude Code (MCP server)" section, the module-map rows and the mutate-set paragraph the branch had added are removed — install, claude mcp add, approval semantics and results live in the PR body. test/readme.test.ts loses the assertion that pinned the removed MCP table, so it describes only what remains; the file is byte-identical to main again. No behaviour changes. Co-Authored-By: Claude Opus 5.5 --- README.md | 101 +------------------------------------------- package.json | 2 +- test/readme.test.ts | 12 ------ 3 files changed, 2 insertions(+), 113 deletions(-) diff --git a/README.md b/README.md index 303fd73..09ddb17 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # repl-simple -Pi extension — sandboxed Python execution via [Monty](https://github.com/pydantic/monty) (Python-in-WebAssembly interpreter). +Pi extension and MCP server (`repl-simple-mcp`) — sandboxed Python execution via [Monty](https://github.com/pydantic/monty) (Python-in-WebAssembly interpreter). ## Sandbox @@ -301,99 +301,6 @@ install and looks like a way around this. It is not: it runs Python in-process, blocks the event loop and there is no crash isolation. See [docs/platform-support.md](docs/platform-support.md). -## Claude Code (MCP server) - -The same five tools, served over [MCP](https://modelcontextprotocol.io) stdio so Claude Code — or -any MCP client — can call them without pi. The server is the package `bin`, `repl-simple-mcp` -(`dist/mcp_main.js`, built by `npm run build`); it wraps the same `ReplRunner` and `runRlm` the pi -extension uses, through the same model boundary (`src/model_boundary.ts`), and changes nothing about -pi. The package is not on npm yet, so install from a clone: - -```bash -git clone https://github.com/AdarGit008/repl-simple && cd repl-simple -npm install && npm run build -``` - -Then register it with Claude Code. Run this **in the project you want the sandbox rooted at**: - -```bash -claude mcp add --transport stdio repl-simple \ - --env ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" \ - -- node /absolute/path/to/repl-simple/dist/mcp_main.js -``` - -`--scope project` writes the entry to `.mcp.json` for the whole team instead of your local config; -Claude Code asks before using a project-scoped server, and strips credential-named variables -(`*KEY*`, `*TOKEN*`, …) from the environment it hands such servers, so the key has to be passed -explicitly — `--env`, or `"env": {"ANTHROPIC_API_KEY": "${ANTHROPIC_API_KEY}"}` in `.mcp.json`. -The key is only needed by `rlm`; `repl` works without one. - -The peer dependency `@earendil-works/pi-coding-agent` (the bridged `bash`/`grep`/… tools, see -[Install](#install)) is in `devDependencies`, so a clone's `npm install` has it; npm 7+ also installs -peers for a registry install. Without it the server fails at startup with `ERR_MODULE_NOT_FOUND` for -that package (`src/bridge.ts` imports it statically); nothing runs half-configured. - -### MCP tools - -| Tool | Description | -|------|-------------| -| `repl(code, sessionId?, maxDurationSecs?, maxMemory?)` | Execute Python in a named session. Variables persist across calls. The description a model reads lists the Python-side host tools, read off the runner's own registry. | -| `repl_resume(approvalId, sessionId?, decision?)` | Decide the pending gated call — `approve` (default) runs it, `deny` refuses it — and continue the run. `approvalId` must be the id the suspended result handed back. | -| `repl_reset(sessionId?)` | Clear all state in a session, pending approval included. | -| `repl_abandon(sessionId?)` | Drop a pending gated call without running it; the session keeps its state. | -| `rlm(question, maxIterations?, maxDepth?, budget?)` | The autonomous read-only code-gen → execute loop, on the Anthropic API. The answer is inner-model output and must be treated as untrusted. | - -### Approvals over MCP - -MCP has no dialog for the server to open, and the server **never approves anything on its own**. -Every gated call (`bash`, `edit`, `write`, `save_tool`, an unlisted `http_get`) suspends the run — -the library's "decide later" answer — and the result says so: the call has **not** run, here is the -call, here is its `approvalId`, and these are the three things that decide it: - -- `repl_resume(sessionId, approvalId)` runs it. **Claude Code's permission prompt in front of that - tool call is the human approval**: the user sees `repl_resume` with the id and the session, and - the preceding `repl` result in the transcript names the exact call. The id binds the decision to - the call that was shown — any other id (stale after new code ran, mistyped, guessed) resumes - nothing and the result repeats the pending call and its id. If the continuation reaches another - gated call it suspends again under a **new** id, so every gated call is its own prompt. -- `repl_resume(sessionId, approvalId, decision='deny')` refuses it: Python sees `PermissionError` - and the code continues, exactly as a denied dialog does in pi. -- `repl_abandon(sessionId)` drops the suspended run; the session lives on. Running new `repl` code on - the session does the same and says so (`[discarded]`). - -The gate therefore holds exactly as long as Claude Code asks. Allow-listing -`mcp__repl-simple__repl_resume` (or the whole server, `mcp__repl-simple`), answering "don't ask -again", or `--dangerously-skip-permissions` removes the human from the loop: every call the model -chooses to resume then runs. The MCP server is strict mode with no `yolo`; that switch is the -client's. Inside `rlm` nothing changes — gated tools are denied outright in the loop, as in pi. - -### Environment - -| Variable | Default | Meaning | -|---|---|---| -| `ANTHROPIC_API_KEY` | — | Read by the Anthropic SDK **in the server process**, for `rlm` only. Never logged, never put in a result, and withheld from the sandboxed `bash` by the env allowlist ([docs/bash-env.md](docs/bash-env.md)). Unset → `repl` works, `rlm` returns `status: error`. The SDK's other credential sources (`ANTHROPIC_AUTH_TOKEN`, an `ant auth login` profile) work too. | -| `REPL_RLM_ANTHROPIC_MODEL` | `claude-opus-5-5` | The model id the `rlm` loop queries. The operator's knob, not the model's: the MCP `rlm` tool has no `model`/`provider` parameters. | -| `REPL_MCP_ROOT` | `CLAUDE_PROJECT_DIR`, else the cwd | The project root: path jail, `.pi/code-tools`, the bridged tools' cwd. Claude Code sets `CLAUDE_PROJECT_DIR` for the servers it spawns, so the default is right under Claude Code. | -| `REPL_MCP_TRUST_PROJECT` | unset — **untrusted** | `1`/`true`/`yes` trusts the project, which lets an **accepted** saved-tool set load ([docs/project-trust.md](docs/project-trust.md)). Trust alone loads nothing: the server has no dialog to accept files on, so acceptance comes from pi's `/repl-accept-preamble` or an embedder calling `acceptPreamble()`. | - -Every `REPL_*` variable the sandbox reads applies unchanged — `REPL_RLM_BUDGET` (the `rlm` spend -ceiling), `REPL_MAX_*`, `REPL_HTTP_ALLOWLIST`, `REPL_BASH_ENV_ALLOW`, `REPL_PREAMBLE_STORE_DIR`. - -### Limits - -- Everything in [Sandbox](#sandbox) holds: Monty's fixed stdlib, no `subprocess`/sockets, no third-party - packages, the language gaps, the type checker, the 32 KiB / 16 KiB output caps. -- **glibc only.** `@pydantic/monty` has no musl build, so the server does not run on Alpine; see - [docs/platform-support.md](docs/platform-support.md). Node >= 22.19.0. -- One server process serves one root, and tool calls are serialised — the pi extension's - `executionMode: "sequential"` — so two `repl` calls in one turn run one after the other. -- Sessions live as long as the server process, which Claude Code starts and stops with its own - session; a pending approval dies with the process, unexecuted. `rlm` costs real API money per call; the default budget - bounds it (`REPL_RLM_BUDGET`). -- No `/repl-approvals yolo`, no `/repl-accept-preamble`, no result rendering: those are pi commands. - The trace a pi result carries on `details` is not sent over MCP — the result text is what the - model gets. - ## Dev ```bash @@ -423,9 +330,6 @@ not renamed): | `src/sandbox.ts`, `src/pool.ts` | One Monty run — dispatch loop, approval gate, limits — and the worker pool it checks out of. | | `src/registry.ts`, `src/builtins.ts`, `src/bridge.ts`, `src/toolstore.ts` | Host tools: the registry and stubs, the builtins, the jailed pi bridge, the saved-tool store. | | `extensions/repl-extension.ts` | The pi extension: registers the four tools and the `/repl-*` commands, renders results and the trace. | -| `src/model_boundary.ts` | The model boundary both hosts share: the limit clamps, the `rlm` knobs and their ceilings, the read-only `rlm` registry, the `rlm` result rendering. | -| `src/mcp_server.ts`, `src/mcp_main.ts` | The MCP host: `createReplMcpServer()` registers the five tools over the same runner and loop (approvals as suspend → `repl_resume` with an `approvalId`); `mcp_main.ts` is the `repl-simple-mcp` bin on stdio. | -| `src/anthropic_client.ts` | `createAnthropicLlmClient()` — the `LlmClient` for `rlm` outside pi, on the Anthropic SDK. | A rename would orphan the `coverage-baseline.json` keys, reopen the package `files` list (#81) and touch the pinned `scriptName` default `"rlm.py"` (`src/rlm.ts`, `test/rlm.test.ts` M21) that the @@ -645,9 +549,6 @@ universe is tracked `src/` and `extensions/` sources; the global is reported, no re-measured against Monty 0.0.21 on 2026-09-10 ([#175](https://github.com/AdarGit008/repl-simple/issues/175)). Full write-up, per-file scores and the reasoning behind every config value: [docs/mutation-testing.md](docs/mutation-testing.md). -One file is outside the mutate set: `src/mcp_main.ts`, the stdio process shim, whose only test -drives it as a child process — a mutant there is invisible to the in-process runner, so it would -count as uncovered rather than measure anything. **The floor moved up 58 → 79 because the tree's score did, not because the instrument got kinder.** Stryker's `coverageAnalysis: "perTest"` only skips tests that could not have killed the mutant, so diff --git a/package.json b/package.json index 57f472f..9fcc26c 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "repl-simple", "version": "0.2.0", "type": "module", - "description": "Pi extension — sandboxed Python execution via Monty", + "description": "Pi extension and MCP server — sandboxed Python execution via Monty", "keywords": [ "pi-package" ], diff --git a/test/readme.test.ts b/test/readme.test.ts index c096e21..3eccc31 100644 --- a/test/readme.test.ts +++ b/test/readme.test.ts @@ -8,7 +8,6 @@ import { createPiBridgeTools } from "../src/bridge.js"; import { createBuiltinTools } from "../src/builtins.js"; import { createToolStoreTools } from "../src/toolstore.js"; import { createRLMTools } from "../src/rlm_tools.js"; -import { MCP_TOOL_NAMES } from "../src/mcp_server.js"; import { createPackFixture, REPO_ROOT, type PackFixture } from "./support/pack-fixture.js"; /** @@ -237,17 +236,6 @@ describe("README truth (#82)", () => { ); }); - it("the README 'MCP tools' table matches the tools the MCP server registers", () => { - // `MCP_TOOL_NAMES` is what `createReplMcpServer` registers, pinned against - // the live server by test/mcp_server.test.ts; the table must list exactly - // those, in registration order. - assert.deepEqual( - readmeTableToolNames(readme(), "### MCP tools"), - [...MCP_TOOL_NAMES], - "README 'MCP tools' table drifted from the MCP server's registered tools", - ); - }); - it("the README 'RLM Loop' table matches the tools runRlm registers (F3)", () => { assert.deepEqual( readmeTableToolNames(readme(), "### RLM Loop (auto-investigation)"),