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
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@ through `open()` on arbitrary host paths.
- **`match` statements** — pattern matching is not implemented.
- **class inheritance and metaclasses** — a plain `class` with methods and `__init__` works, but
`class B(A)` raises `NotImplementedError`.
- **`del`** — the `del` statement is not implemented.

A refusal is all-or-nothing: the parser and the type checker both run before the first statement,
so a rejected construct discards the whole snippet — nothing in it runs and no side effect happens.

**Type checker.** A static type check runs before execution and fails as `[error: typing]`. Missing
names are typing errors, not catchable `NameError`s (`ImportError` and `ModuleNotFoundError` are
themselves rejected by the checker, and a refused import never runs). `map`, `filter`, `getattr`,
`hasattr` and `setattr` exist at runtime but the checker rejects them; a longer list of names is
absent from both — `skills/repl-simple/SKILL.md` carries the measured lists. I/O is `print()`-only
(`sys.stdout.write`/`sys.stderr.write` and `os.environ`/`os.getenv` raise at runtime), and only
class objects carry `__name__` — functions, builtins and instances expose no dunder methods.

**Returned values.** The value a snippet ends on crosses to the host as data, with two limits on
Monty 0.0.23. Nesting is capped: a list 48 levels deep and a class instance 24 deep are fine, and
Expand All @@ -52,7 +64,8 @@ Sessions are pooled per project directory, with a **cap of 32 live sessions** an
when a new one would exceed it: the session used least recently is dropped first. The knobs, in
precedence order: `ReplRunnerOptions.maxSessions` (embedders) > `REPL_MAX_SESSIONS` env (positive
integer) > 32. A dropped session is gone — its variables, imports and cache are released, and the
next `repl` call on that id starts fresh.
next `repl` call on that id starts fresh. That first call carries a one-shot `[evicted]` notice
naming the cap, so the model is not left guessing why its variables vanished.

**A session with a pending approval is never evicted, and neither is one whose call is still
running.** Evicting either would discard a call the user was asked to approve — or may be about to
Expand Down
5 changes: 4 additions & 1 deletion docs/path-jail.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,10 @@ Two tools deliberately have none:
exactly the path it is given, which the argument jail has already canonicalised.
- **`find`** only consults its operations when they supply `glob`, which replaces the `fd`
subprocess entirely — losing .gitignore handling and the result caps with it. `fd`, like `rg`,
does not follow symlinks out of the tree it is pointed at.
does not follow symlinks out of the tree it is pointed at. The bridge refuses an absolute
`pattern` (or one containing a `..` segment) before `fd` runs, so the model gets a refusal it
can act on instead of fd's "no files found": the pattern is not a `path` and never reaches the
jail described above.

A caller's own `operations` still compose: the jail wraps them, and they see canonical, in-root
paths or nothing at all.
Expand Down
3 changes: 2 additions & 1 deletion docs/review-59.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ All four review findings were fixed in `59.5` and `59.6` (tests added first, RED
- **Verified** `src/repl.ts:269-284`: the `for (;;)` loop's `existing !== undefined` correctly
distinguishes trust-discard rebuilds (notice) from eviction-recreation (no notice); the
revalidation `continue` cannot busy-spin (every iteration awaits a trust check, and each
`continue` requires another caller to have changed the map).
`continue` requires another caller to have changed the map). (Superseded in part:
eviction-recreation now carries a one-shot `[evicted]` notice.)
- **Verified** `src/repl.ts:296-311`: `inflight.delete` and `insert` run in the same synchronous
`.then`, so no caller can miss both maps; concurrent joiners of a failing creation all reject
together, which is correct (the creation genuinely failed; only *later* callers retry).
Expand Down
5 changes: 4 additions & 1 deletion docs/ship-59.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@
mutant changes no observable behavior (every access re-checks trust). None in the single-flight,
LRU, or eviction-skip logic.
3. **Silent eviction for idle sessions** (no model-facing notice when an evicted id comes back
fresh) — not requested by #59; observe in practice before adding a tombstone.
fresh) — not requested by #59; observe in practice before adding a tombstone. **Observed and
resolved**: the live e2e run showed sessions vanishing with no explanation, and the pool now
keeps a bounded tombstone that delivers a one-shot `[evicted]` notice on the next
`repl`/`repl_resume` call for a dropped id.
4. **Concurrent same-id runs through the direct API** replay from the same starting snapshot —
unreachable via the shipped extension (`executionMode: "sequential"`); inherent to replay-based
sessions, belongs to #61 if it ever matters.
Expand Down
9 changes: 7 additions & 2 deletions extensions/repl-extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1536,6 +1536,9 @@ export default function (pi: ReplExtensionApi) {
"with no pause points runs until the duration limit (maxDurationSecs). " +
`One repl or repl_resume call opens at most ${MAX_DIALOGS_PER_CALL} approval ` +
"dialogs; gated calls past that are denied and the result says why. " +
"At most 32 live sessions are pooled per project by default (REPL_MAX_SESSIONS); " +
"past that cap the oldest session that is not awaiting approval is dropped, and the " +
"next call on that id starts fresh with an [evicted] notice. " +
"The sessionId is scoped to this Pi session: when the conversation ends " +
"(/new, /resume, /fork, quit) every REPL session is disposed, a pending approval " +
"is dropped, and the same sessionId in the next conversation is a new, empty REPL.",
Expand All @@ -1552,15 +1555,17 @@ export default function (pi: ReplExtensionApi) {
description:
"Maximum interpreter compute time in seconds, capped at 300, or lower if the " +
"operator sets REPL_MAX_DURATION_SECS (default 30). " +
"Omitted uses the sandbox default (30).",
"Omitted uses the sandbox default (30); 0, a negative or a non-finite value " +
"is treated as omitted.",
}),
),
maxMemory: Type.Optional(
Type.Number({
description:
"Maximum sandbox heap in MiB, capped at 1024, or lower if the operator sets " +
"REPL_MAX_MEMORY_MB (default 512 MiB). " +
"Omitted uses the sandbox default (512 MiB).",
"Omitted uses the sandbox default (512 MiB); 0, a negative or a non-finite " +
"value is treated as omitted.",
}),
),
}),
Expand Down
14 changes: 11 additions & 3 deletions skills/repl-simple/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ Sandboxed Python execution in pi via [Monty](https://github.com/pydantic/monty)

- `maxDurationSecs`: interpreter compute seconds, default 30, cap 300.
- `maxMemory`: sandbox heap MiB, default 512, cap 1024.
- A non-positive or non-finite limit is treated as omitted (the fail-safe default applies) — `maxDurationSecs=0` is not a limit of zero.
- Sessions are pooled per project: at most 32 live (`REPL_MAX_SESSIONS`); the least-recently-used is evicted — never one with a pending approval — and the next call on that id starts fresh with a one-shot `[evicted]` notice.
- A `repl` or `repl_resume` call opens at most **8 approval dialogs**; gated calls past that are denied and the result says so.
- Running new `repl` code while a call is suspended discards that call — `repl_resume` first if you still want it.
- Sessions are scoped to one pi conversation: `/new`, `/resume`, `/fork`, or quit disposes every session and drops pending approvals. The same `sessionId` next conversation is a fresh, empty REPL.
Expand Down Expand Up @@ -55,10 +57,16 @@ The sandbox has no filesystem of its own: `open()`, `os.listdir()`, and `pathlib
- `match` statements (no pattern matching)
- class inheritance / metaclasses (`class B(A)` fails; a plain `class` with methods works)

A construct the parser or checker refuses discards the whole snippet — no statement in it runs, and no side effect happens.

**Type-checker limits** (a static type check runs before execution and fails as `[error: typing]`, distinct from `[error: syntax]`/`[error: runtime]`):
- Some builtins are blocked by the checker: `dir`, `callable`, `eval`, `exec`, `vars`, `globals`, `locals`, `bytearray` do not exist at runtime, while `getattr`, `hasattr`, `setattr`, `map`, `filter` exist at runtime but the checker rejects them — either way a missing name is a typing error, **not** a catchable `NameError`, so `try/except NameError` will not save you.
- Stdlib stubs are partial: `sys.maxsize`, `asyncio.sleep`, and `pathlib.PurePath` are missing, and modules have no `__dict__`.
- Lambda parameters infer as `object`: `lambda a, b: a + b` is rejected (unsupported `+`) — use a `def` with annotated parameters instead.
- Rejected by the checker **and** absent at runtime — a missing name is a typing error, **not** a catchable `NameError`, so `try/except NameError` will not save you: `dir`, `vars`, `callable`, `format`, `issubclass`, `super`, `classmethod`, `staticmethod`, `memoryview`, `complex`, `compile`, `eval`, `exec`, `globals`, `locals`, `input`, `breakpoint`, `__import__`, `bytearray`.
- Rejected by the checker but **present** at runtime (measured with the checker off), so a normal type-checked run still cannot use them: `map`, `filter`, `getattr`, `hasattr`, `setattr`.
- `ImportError` and `ModuleNotFoundError` exist at runtime but are rejected by the checker — and a refused import never runs, so there is nothing to catch.
- Stdlib stubs are partial: `os.getcwd`, `os.path`, `sys.argv`, `sys.exit`, `sys.path`, `sys.maxsize`, `collections.OrderedDict`, `asyncio.sleep`, `itertools.product`/`permutations`/`combinations`, `functools.wraps`/`lru_cache` and `pathlib.PurePath` are missing, and modules have no `__dict__`.
- Lambda parameters passed as callbacks infer as `object`: a body that uses them (`a + b`, `p[0]`, `len(w)`) is rejected in some positions — `functools.reduce(lambda …)` passes as a bare expression and fails inside `print(...)`, and `max`/`min(..., key=lambda …)` behave the same way. `sorted(..., key=…)` and `list.sort(key=…)` are accepted, and a lambda called directly is always fine. Use a `def` with annotated parameters when the callback uses its arguments.
- I/O is `print()`-only: `sys.stdout.write`/`sys.stderr.write` and `os.environ`/`os.getenv` pass the checker but raise at runtime.
- Only class objects carry `__name__` (and `type(x).__name__`); functions, builtins and instances expose no dunder methods.

**Return values** cross to the host as data, with nesting caps: a list ~48 levels deep or a class instance ~24 deep is fine, one more fails the whole run with `RuntimeError: Max output depth exceeded` (after side effects). Instances cross **without their methods** — `__repr__` is not called, so end a snippet on `repr(obj)` to see a useful value.

Expand Down
45 changes: 45 additions & 0 deletions src/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,23 @@ async function jailPathArg(
return { ...args, path: await jail.resolve(raw) };
}

/**
* Whether a glob is absolute or climbs out of the project root.
*
* An honesty guard, not an escape guard: both `fd` and `rg` walk only the
* jailed search path, so a pattern like `/etc/*` comes back as "no files
* found" / "no matches found" — an empty result the model reads as fact.
* Absolute patterns are refused even when they happen to name an in-root
* path, because accepting some would mean resolving them against the jail
* first; the rule is simply "project-relative globs". Both separators are
* checked so the guard does not stop at the platform boundary.
*/
function notProjectRelative(pattern: string): boolean {
if (pattern.startsWith("/") || pattern.startsWith("\\")) return true;
if (/^[A-Za-z]:[\\/]/.test(pattern)) return true;
return pattern.split(/[\\/]/).includes("..");
}

interface ToolSpec {
name: string;
/**
Expand Down Expand Up @@ -472,6 +489,19 @@ const TOOL_SPECS: ToolSpec[] = [
},
],
mutating: false,
// The same honesty guard as `find`: a `glob` is not a `path`, so an
// absolute one never reaches the jail and rg answers "No matches found"
// — an empty result the model reads as fact.
prepareArgs: (args) => {
const glob = args.glob;
if (typeof glob === "string" && notProjectRelative(glob)) {
throw new HostToolError(
"PermissionError",
`the grep glob '${glob}' is not project-relative; use a glob inside the project root`,
);
}
return args;
},
},
{
name: "find",
Expand All @@ -487,6 +517,21 @@ const TOOL_SPECS: ToolSpec[] = [
{ name: "limit", type: "int", description: "Maximum number of results.", optional: true },
],
mutating: false,
// `path` is jailed above; `pattern` is not a path and never reaches the
// jail, so a glob pointing outside the root would be answered with "No
// files found matching pattern" — a refusal-shaped fact the model would
// act on. Refuse it by name instead.
prepareArgs: (args) => {
const pattern = args.pattern;
if (typeof pattern === "string" && notProjectRelative(pattern)) {
throw new HostToolError(
"PermissionError",
`the find pattern '${pattern}' is not project-relative; use a glob inside the ` +
"project root (e.g. '*.ts' with an optional jailed 'path')",
);
}
return args;
},
},
{
name: "ls",
Expand Down
16 changes: 13 additions & 3 deletions src/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,8 @@ export const TY_GAP_REASONS: Readonly<Record<string, string>> = {
* rejects as unresolved. These need `name: Any = None` declarations
* in the type-check stubs.
*
* The gaps did **not** close on 0.0.21 — measured, all six still report
* The gaps did **not** close on 0.0.21 — measured, all six names in the list
* then (five today; see `TY_GAP_REASONS` for why `bytearray` left) reported
* `unresolved-reference`. What changed is where the declaration goes: into
* out-of-band `typeCheckStubs` rather than a prefix prepended to the user's
* source, so it no longer shifts the line numbers in reported diagnostics
Expand Down Expand Up @@ -555,8 +556,11 @@ export function renderPythonToolRules(importableModules: string[]): string {
- The value of the last top-level expression is returned as the result (expressions
inside if/try blocks are not).
- Imports: these modules are available: ${importableModules.join(", ")}. Anything else
(e.g. ${blocked.join(", ")}) is refused before your code runs (a type-check error,
error[unresolved-import]) — you cannot except it; delete the import and retry.
(e.g. ${blocked.join(", ")}) is refused before your code runs — a typing error named
\`unresolved-import\`, never a catchable ImportError — and there are no third-party
packages. Delete the import and retry.
- I/O is print()-only: sys.stdout.write, sys.stderr.write, os.environ and os.getenv
raise at runtime even though the checker accepts them.
- To read, list, or search PROJECT files, use the tools (read, grep, find, ls,
read_file, list_files) — never open(), os.listdir(), or pathlib. By default the
sandbox has no filesystem (open()/os.listdir()/pathlib raise PermissionError)
Expand All @@ -568,6 +572,12 @@ export function renderPythonToolRules(importableModules: string[]): string {
denied in the RLM loop) — do not call them.
- Class inheritance, metaclasses, match statements, and yield/generators are not
supported (NotImplementedError); a plain class with __init__ and methods works.
A construct the parser or checker refuses discards the whole snippet — nothing in it runs.
- Lambda callbacks get object parameters: when the body uses them (a + b, p[0], len(w)),
pass an annotated def — reduce/max/min reject such callbacks in some positions, while
sorted(..., key=lambda ...) and list.sort(key=...) are accepted.
- Only class objects carry \`__name__\` (and \`type(x).__name__\`); functions, builtins and
instances expose no dunder methods.
- Tool failures raise normal Python exceptions you can catch (e.g. ValueError,
FileNotFoundError, OSError).`;
}
Loading
Loading