Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -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

Expand Down
25 changes: 14 additions & 11 deletions coverage-baseline.json
Original file line number Diff line number Diff line change
@@ -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
}
Expand Down
186 changes: 23 additions & 163 deletions extensions/repl-extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading