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
12 changes: 11 additions & 1 deletion src/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,13 @@ async function jailPathArg(

interface ToolSpec {
name: string;
/**
* Optional override of pi's own tool description. `read` needs one: pi's
* text claims "Images are sent as attachments", but this bridge keeps only
* text blocks (see the `c.type === "text"` filter below), so the model
* must be told the sandbox sees text only.
*/
description?: string;
// pi's tool factories each return a differently-shaped AgentTool and the
// package exports no common supertype. Narrowing this would mean
// re-declaring pi's types here, free to drift from the ones that actually
Expand All @@ -385,6 +392,9 @@ interface ToolSpec {
const TOOL_SPECS: ToolSpec[] = [
{
name: "read",
description:
"Read the contents of a text file. Returns text only — image files are " +
"not supported through the sandbox. Use offset/limit for large files.",
factory: (cwd, opts, jail) =>
createReadTool(cwd, {
...opts.read,
Expand Down Expand Up @@ -611,7 +621,7 @@ export function createPiBridgeTools(cwd: string, options: BridgeOptions = {}): H

return {
name: spec.name,
description: agentTool.description ?? "",
description: spec.description ?? agentTool.description ?? "",
params: spec.params,
returns: "str" as const,
requiresApproval: spec.mutating ? gateMutating : gateReads,
Expand Down
38 changes: 29 additions & 9 deletions src/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ export class ToolRegistry {
.map((tool) => {
const params = renderParams(tool);
const returns = renderReturn(tool);
const doc = tool.description.trim().replace(/\s+/g, " ");
const doc = renderToolDocstring(tool);
const sig = `def ${tool.name}(${params}) -> ${returns}:`;
return doc.length > 0 ? `${sig}\n """${doc}"""\n ...` : `${sig}\n ...`;
return doc.length > 0 ? `${sig}\n ${doc}\n ...` : `${sig}\n ...`;
})
.join("\n\n");
}
Expand Down Expand Up @@ -186,6 +186,23 @@ function renderParams(tool: HostTool): string {
.join(", ");
}

/**
* The docstring `renderToolDocs` shows for one tool: the tool-level
* description plus each parameter's own description, so non-obvious
* parameters (e.g. `edit`'s JSON-array `edits`) are documented rather than
* rendered as a bare `edits: str`.
*/
function renderToolDocstring(tool: HostTool): string {
const lines: string[] = [];
const summary = tool.description.trim().replace(/\s+/g, " ");
if (summary) lines.push(summary);
const described = tool.params
.filter((p) => p.description && p.description.trim().length > 0)
.map((p) => `- ${p.name}: ${p.description.trim().replace(/\s+/g, " ")}`);
if (described.length > 0) lines.push("Parameters:", ...described);
return lines.length > 0 ? `"""${lines.join("\n")}"""` : "";
}

/**
* The Python spelling of a tool's return type. `"void"` is `HostTool`
* vocabulary for "returns nothing"; rendered verbatim it is an unresolved
Expand Down Expand Up @@ -351,13 +368,15 @@ export const CANDIDATE_MODULES = [
"string",
"textwrap",
"base64",
"binascii",
"hashlib",
"statistics",
"io",
"copy",
"enum",
"dataclasses",
"uuid",
"unicodedata",
"csv",
"urllib",
];
Expand Down Expand Up @@ -519,7 +538,7 @@ export async function probeTypeCheckerGaps(
// ── Python tool rules ───────────────────────────────────────────

/** Examples used in the import restriction rule, filtered against reality. */
const BLOCKED_EXAMPLES = ["time", "random", "collections", "requests", "numpy"];
const BLOCKED_EXAMPLES = ["time", "random", "requests", "numpy"];

/**
* Ground rules for the model writing sandboxed Python. Include alongside
Expand All @@ -532,22 +551,23 @@ export function renderPythonToolRules(importableModules: string[]): string {
return `\
- Call tools as plain functions, WITHOUT \`await\`.
- Use print() to surface anything you need to see; printed output is returned to you.
stdout is capped (32 KiB / 1000 lines) and there is no stderr — summarise, don't dump.
- The value of the last top-level expression is returned as the result (expressions
inside if/try blocks are not).
- Imports: ONLY these modules exist: ${importableModules.join(", ")}. Anything else
- 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.
- To read, list, or search PROJECT files, use the tools (read, grep, find, ls,
read_file, list_files) — never open(), os.listdir(), or pathlib. The sandbox
has no filesystem of its own, so those raise PermissionError and cannot see
project files.
read_file, list_files) — never open(), os.listdir(), or pathlib. By default the
sandbox has no filesystem (open()/os.listdir()/pathlib raise PermissionError)
and cannot see project files.
- Example calls: find(pattern="*.ts", path="src"), ls("src"), read("src/rlm.ts"),
grep(pattern="runRlm", path="src"). If a run fails with PermissionError, either
you used a filesystem API (open()/os.listdir()/pathlib) — switch to these tools —
or you called a tool that requires approval (bash/edit/write/http_get are always
denied in the RLM loop) — do not call them.
- Class inheritance, metaclasses and match statements are not supported (NotImplementedError);
a plain class with __init__ and methods works.
- Class inheritance, metaclasses, match statements, and yield/generators are not
supported (NotImplementedError); a plain class with __init__ and methods works.
- Tool failures raise normal Python exceptions you can catch (e.g. ValueError,
FileNotFoundError, OSError).`;
}
68 changes: 52 additions & 16 deletions src/rlm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,14 @@ const TRUNCATED_VIEW_END = `${TRUNCATED_VIEW_PREFIX} END]`;
*/
const TRUNCATED_VIEW_NEUTRALISED = "[TRUNCATED\u200BVIEW";

/**
* Neutralised form of the history-drop notice phrase: a zero-width space
* (U+200B) replaces the ordinary space, so untrusted data can never carry the
* exact "turns were dropped" phrase the system emits as its own drop notice.
*/
const HISTORY_DROP_PHRASE = "earlier turns dropped";
const HISTORY_DROP_NEUTRALISED = "earlier turns\u200Bdropped";

/** Bytes the sentinel wrap adds: open + close + two newlines. */
const SENTINEL_OVERHEAD_BYTES = contentBytes(`${TRUNCATED_VIEW_BEGIN}\n\n${TRUNCATED_VIEW_END}`);

Expand All @@ -510,7 +518,9 @@ function truncateWithSentinels(
value: string,
opts: { maxBytes: number; headRatio: number; recovery: string },
): string {
const neutralised = value.replaceAll(TRUNCATED_VIEW_PREFIX, TRUNCATED_VIEW_NEUTRALISED);
const neutralised = value
.replaceAll(TRUNCATED_VIEW_PREFIX, TRUNCATED_VIEW_NEUTRALISED)
.replaceAll(HISTORY_DROP_PHRASE, HISTORY_DROP_NEUTRALISED);
const { text, truncated } = truncateText(neutralised, {
maxBytes: opts.maxBytes - SENTINEL_OVERHEAD_BYTES,
headRatio: opts.headRatio,
Expand Down Expand Up @@ -615,11 +625,13 @@ Your job: investigate the user's question by writing Python code, running it,
interpreting the results, and submitting your final answer.

Rules:
- Write ONLY Python code between \`\`\`python fences.
- Write Python code between \`\`\`python fences to investigate.
- Use print() to inspect data. stdout is returned to you.
- The last expression value is also returned.
- Call llm_query(prompt) to ask for reasoning help.
- Call SUBMIT(answer) exactly once when you have the final answer.
- The value of the last top-level expression is also returned (expressions inside
if/try blocks are not).
- Call llm_query(prompt) to ask for a self-contained answer to a sub-question.
- When you are done, call SUBMIT(answer). A plain-text answer may also be
accepted as the final answer.
- NEVER call SUBMIT without first investigating.
- If code errors, read the error message, fix the code, and retry.
${SENTINEL_RULE}
Expand Down Expand Up @@ -1000,7 +1012,16 @@ export function buildFeedback(result: RunResult): string {
.split("\n")
.map((line) => `> ${line}`)
.join("\n");
let feedback = `Error: ${quotedError}\nstdout: ${stdout}`;
// Same line-quoting as the error value: a forged `\nstdout:` inside
// stdout renders at column 2, so only the real delimiter can sit at
// column 0.
const quotedStdout = stdout
? stdout
.split("\n")
.map((line) => `> ${line}`)
.join("\n")
: "";
let feedback = `Error: ${quotedError}\nstdout:\n${quotedStdout}`;
if (result.errorKind === "syntax") {
feedback += "\n\nFix the syntax error in your Python code.";
} else if (result.errorKind === "typing") {
Expand Down Expand Up @@ -1037,12 +1058,16 @@ export function buildFeedback(result: RunResult): string {
// gone rather than merely unhappy, so every variable, import and
// definition from earlier in the run went with it. Telling the model to
// "fix the error" would invite it to build on state that no longer
// exists.
feedback +=
"\n\nThe sandbox was terminated and all its state was lost. " +
"Retry with self-contained code that does not rely on anything " +
"defined earlier, and make it cheaper — the usual cause is running " +
"too long.";
// exists. `src/sandbox.ts` names the one distinction that changes what
// to do: a watchdog kill is the model's cost problem, a bare worker
// death is not its doing — so do not blame "running too long" on it.
feedback += result.error.includes("exceeded its time budget")
? "\n\nThe sandbox was terminated because execution exceeded its time budget " +
"and all its state was lost. Retry with self-contained code that does " +
"not rely on anything defined earlier, and do less work."
: "\n\nThe sandbox worker died unexpectedly and all its state was lost. " +
"Retry with self-contained code that does not rely on anything " +
"defined earlier.";
}
return feedback;
}
Expand Down Expand Up @@ -1073,7 +1098,15 @@ export function buildFeedback(result: RunResult): string {
headRatio: STDOUT_HEAD_RATIO,
recovery: STDOUT_RECOVERY,
});
const stdoutSection = stdout ? `\nstdout:\n${stdout}` : "";
// Quote stdout lines too (D19/D36): a forged `\nstdout:` inside stdout then
// renders at column 2, so only the real delimiter sits at column 0.
const quotedStdout = stdout
? stdout
.split("\n")
.map((line) => `> ${line}`)
.join("\n")
: "";
const stdoutSection = quotedStdout ? `\nstdout:\n${quotedStdout}` : "";
// D36 (#156): quote every line of the output with a `> ` prefix — the same
// close D19 gives the error branch (test 18). A forged `\nstdout:` inside
// the value then renders as `> stdout:` and can no longer line up at
Expand Down Expand Up @@ -1611,9 +1644,12 @@ export async function runRlm(question: string, options: RlmOptions): Promise<Rlm

// An abort that landed during this iteration — mid-sandbox-run (partial
// errorKind:"aborted" result) or racing a completed run — surfaces here
// with the iteration included (#75, D34). The SUBMIT check below only runs
// when the signal is not aborted.
if (options.signal?.aborted) {
// with the iteration included (#75, D34). A sandbox that reported
// `aborted` because a `runOptions`-carried signal fired (the loop's own
// `options.signal` may be unset) is the same terminal outcome: feeding
// "Execution was aborted." back and calling the LLM again would leave the
// model no next step. The SUBMIT check below only runs when not aborted.
if (options.signal?.aborted || (result.status === "error" && result.errorKind === "aborted")) {
return aborted();
}

Expand Down
4 changes: 2 additions & 2 deletions src/rlm_tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ function createLLMQueryTool(onLLMQuery: RLMToolOptions["onLLMQuery"]): HostTool
return {
name: "llm_query",
description:
"Ask the sub-LLM a question. Blocks until the LLM responds. " +
"Use for: semantic reasoning, summarization, open-ended analysis. " +
"Ask the sub-LLM a question and get a self-contained answer. " +
"Blocks until the LLM responds. " +
"Avoid for: counting, filtering, regex — do those in Python directly. " +
CAP_NOTE,
params: [
Expand Down
9 changes: 9 additions & 0 deletions test/bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,15 @@ describe("createPiBridgeTools — tool creation", () => {
assert.equal(tool.returns, "str", `${tool.name} should return 'str'`);
}
});

it("the read tool is documented as text-only, not as image attachments", () => {
// The bridge keeps only text blocks from pi's read result, so pi's own
// "Images are sent as attachments" claim must not reach the sandbox model.
const read = findTool(createPiBridgeTools(tmpDir), "read");
assert.doesNotMatch(read.description, /images are sent as attachments/i);
assert.doesNotMatch(read.description, /Supports text files and images/i);
assert.match(read.description, /text only/i);
});
});

// ── Image sniffing ──────────────────────────────────────────────
Expand Down
62 changes: 62 additions & 0 deletions test/registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,33 @@ describe("ToolRegistry", () => {
`docs are stub-body-free: ${reg.renderToolDocs()}`,
);
});

it("renders parameter descriptions for non-obvious parameters", () => {
const reg = new ToolRegistry([
{
name: "edit",
description: "Edit a file",
params: [
{ name: "path", type: "str", description: "File to edit." },
{
name: "edits",
type: "str",
description: "JSON array of {oldText, newText} objects.",
},
],
returns: "str",
execute: () => "",
},
]);
const docs = reg.renderToolDocs();
assert.ok(docs.includes("def edit(path: str, edits: str) -> str:"), docs);
assert.ok(docs.includes("Parameters:"), docs);
assert.ok(docs.includes("- path: File to edit."), docs);
assert.ok(
docs.includes("- edits: JSON array of {oldText, newText} objects."),
`edits description missing:\n${docs}`,
);
});
});
});

Expand Down Expand Up @@ -355,6 +382,23 @@ describe("renderPythonToolRules", () => {
assert.equal(inherit.status, "error", JSON.stringify(inherit));
assert.match(inherit.status === "error" ? inherit.error : "", /NotImplementedError/);
});

it("softens the import claim and does not list importable modules as blocked", () => {
const rules = renderPythonToolRules(["json", "collections"]);
assert.doesNotMatch(rules, /ONLY these modules exist/);
assert.match(rules, /these modules are available/);
assert.doesNotMatch(rules, /e\.g\. [^\n]*collections/);
assert.match(rules, /e\.g\. time, random, requests, numpy/);
});

it("mentions yield/generators and the stdout cap, and qualifies the filesystem claim", () => {
const rules = renderPythonToolRules(["json"]);
assert.match(rules, /yield\/generators/);
assert.match(rules, /stdout is capped/);
assert.match(rules, /no stderr/);
assert.match(rules, /By default the\s+sandbox has no filesystem/);
assert.match(rules, /open\(\)\/os\.listdir\(\)\/pathlib raise PermissionError/);
});
});

// ── probeImportableModules / probeTypeCheckerGaps ────────────────
Expand All @@ -372,6 +416,24 @@ describe("probeImportableModules / probeTypeCheckerGaps", () => {
assert.ok(!result.includes("this_does_not_exist_xyz"));
});

it("CANDIDATE_MODULES names the verified importable stdlib modules", () => {
for (const name of ["json", "collections", "binascii", "unicodedata"]) {
assert.ok(CANDIDATE_MODULES.includes(name), `CANDIDATE_MODULES must include ${name}`);
}
});

it("the default probe finds the verified importable stdlib modules", async () => {
resetProbeMemos();
const result = await probeImportableModules();
for (const name of ["json", "collections", "binascii", "unicodedata"]) {
assert.ok(result.includes(name), `expected ${name} importable, got: ${result}`);
}
// These are typeshed stubs, not runtime modules — probing them must say so.
for (const name of ["builtins", "types", "typing_extensions", "_collections_abc"]) {
assert.ok(!result.includes(name), `expected ${name} absent, got: ${result}`);
}
});

it("reports a name the type checker cannot resolve", async () => {
// Still a gap on 0.0.21 — measured, along with the other five candidates.
// If this ever goes green upstream the probe self-prunes and this test is
Expand Down
Loading
Loading