Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
4be6433
test(security): red-team rows for the fakes code is served (ruling 133)
wanderdev0 Nov 30, 2026
f46ca9a
feat(security): what the worker serves to code is faked (ruling 133)
wanderdev0 Dec 1, 2026
8104fd4
Merge origin/main into feat/code-reads-fakes
wanderdev0 Dec 1, 2026
5acd418
feat(security): ruling 133's conditions: every Arrow type decided, na…
wanderdev0 Dec 1, 2026
25a664d
docs(security): ruling 133's spec review: the page's candidate-list o…
wanderdev0 Dec 1, 2026
70f8fc6
test(security): 1h pins the page-hosted limit on both sides, and the …
wanderdev0 Dec 1, 2026
6ef1765
fix(security): byteString decodes natively, so a faked megabyte costs…
wanderdev0 Dec 1, 2026
5b3fc10
test(security): one red-team row per Arrow type, enumerated from the …
wanderdev0 Dec 1, 2026
d42b2b9
test(e2e): the 300,000-row cells declare expect_ms, and a detached or…
wanderdev0 Dec 1, 2026
3e4643c
docs(security): the cost of faking a 300,000-row binary column in a c…
wanderdev0 Dec 1, 2026
7fc272e
docs(security): the 15 s detach stated as a threshold, not as CI's me…
wanderdev0 Dec 1, 2026
0cd83bc
Merge branch 'feat/code-reads-fakes' of https://github.com/parawander…
wanderdev0 Dec 1, 2026
0a29eda
docs(security): ruling 133's rows listed by title, e4's per-type Arro…
wanderdev0 Dec 1, 2026
35fedbd
Merge remote-tracking branch 'origin/main' into feat/code-reads-fakes
wanderdev0 Dec 1, 2026
f9e4419
docs(security): which forms the candidate-list oracle can star: never…
wanderdev0 Dec 1, 2026
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
3 changes: 3 additions & 0 deletions docs/dev/pointers.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,9 @@ to re-run the step, and never degrades to the preview. `onEvict` is where the ca
- **Budget.** `valueStoreBudgetMB` (DevTools Settings → Output pointers, default 1024), capped at half of
`navigator.storage.estimate().quota`. Each eviction is `{ subsystem: "value-store", kind: "evict", reason, key, bytes,
detail.source }`; a body the whole budget cannot hold is `kind: "refuse"`, and the fetch still answers with its preview.
- **Code reads a pointer's value faked** (ruling 133; docs/spec/SECRET_HANDLES.md, "What the worker serves to code is
faked"): `derefWhole` fakes every read before any pipe runs, so a `dereference` or a pipe from code runs over the
session's fakes. The model's own dereference tool passes no mask and reads as before.

Nothing READS a stored value yet: `python_exec` opening one is slice 5. Until then the one reader is the worker's TEST-ONLY
`globalThis.__mlValues` (`rows()`, `read(key)`, reachable only through `serviceWorker.evaluate`), which
Expand Down
3 changes: 3 additions & 0 deletions docs/dev/python-sandbox.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ charge) are [`docs/spec/ML_TABLE.md`](../spec/ML_TABLE.md); this is where they l
`pd.read_csv` with the decided `sep`, header and names. It then pops the buffer, and the worker deletes any name left
in `finally`. The background still refuses a stored key unless the sender is entitled to it: a run active on its tab
holds it, or the worker disclosed it to that tab (`page:<tabId>`).
- **A cell reads registered values as fakes** (ruling 133; docs/spec/SECRET_HANDLES.md, "What the worker serves to code
is faked"): `ml.table` and every wire answer are faked, and a stored table's carrier may be Arrow where the store
holds Parquet (`table-fake.ts` rebuilds one that holds a value).

**A returned DataFrame larger than its 200-row preview becomes a stored table** (slice 6):

Expand Down
4 changes: 4 additions & 0 deletions docs/spec/ML_TABLE.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,10 @@ wait for the kept-bytes store (§10, step 3), and ask until then. As built:
delimiter. A reader errno (`EACCES`, `EFBIG`, `ENOENT`) is the call's error code. The worker binds the bytes once as a
bytearray (`bindTableBytes`, under `_ml_wbuf_<seq>`), the frame builder takes them, and they are dropped after the
cell if it never did.
- **Faked** (ruling 133, SECRET_HANDLES.md, "What the worker serves to code is faked"). Every answer's strings, and a
stored table's bytes, reach the cell with each registered value replaced by the session's fake: delimited text and
Arrow in place, a Parquet table that holds a value as an Arrow IPC stream (`table-fake.ts`), or refused naming a
column that cannot carry a fake.
- **The frame** is built in the cell by `_ml_table_frame` (`python-runtime.ts`): Arrow and Parquet through pyarrow, a
delimited body re-read by `pd.read_csv` with the delimiter and header already decided (so pandas cannot disagree with
the JS reader), rows and HTML as the old loader built them. The source facts go on `df.attrs`.
Expand Down
301 changes: 300 additions & 1 deletion docs/spec/SECRET_HANDLES.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion scripts/test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ const GENRES = {
// of what a page or the model reads, as each crossing applies it and over a ranged read, and the input that takes one.
secrets: {
about: "secrets: the registry, the scrub at each crossing and over a ranged read, and the secret input",
files: ["secret-registry.test.mjs", "secret-scrub-crossings.test.mjs", "secret-scrub-range.test.mjs", "secret-input.test.mjs", "secret-mask.test.mjs"],
files: ["secret-registry.test.mjs", "secret-scrub-crossings.test.mjs", "secret-scrub-range.test.mjs", "secret-input.test.mjs", "secret-mask.test.mjs", "code-reads-fakes.test.mjs"],
},
// `/files` (FILE_ATTACHMENTS.md, "`/files/` read by range, and `ml.fs`"): the ranged reader over the shelf, the
// offscreen document's source for it, the synchronous channel Python's mount is served over, and the mount itself.
Expand Down
2 changes: 1 addition & 1 deletion src/agent/agent-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export interface RunAgentHostDeps {
tryReadonly?(name: string, args: Record<string, unknown>, live?: LiveOutput, call?: { seq: number; step: number }): Promise<ToolRunResult | null>;
/** Receives this run's pointer resolver at start, so the host can answer a page-side `ml.dereference`
* (the loop, and the store, live here; the tool runs in the page). See background's derefByRun. */
tokenSink?(resolve: (ref: string, pipe?: string | string[], limits?: PipeLimits) => DerefRead): void;
tokenSink?(resolve: (ref: string, pipe?: string | string[], limits?: PipeLimits, mask?: (v: import("../pointers/token-pipe").TokenValue) => import("../pointers/token-pipe").TokenValue) => DerefRead): void;
/** Receives the run's context snapshot function (agent-loop.ts `contextSink`), for `ml.current` in a read-only
* survey evaluated in the worker (sw-readonly.ts). */
contextSink?(snapshot: (extra?: { model?: string | null; log?: readonly import("../log/run-log").RunLogEvent[] }) => import("./current-context").CurrentSnapshot): void;
Expand Down
11 changes: 7 additions & 4 deletions src/agent/agent-loop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ export interface AgentLoopOptions { tools: ToolMeta[]; maxSteps?: number | (() =
/** Called once at run start with a resolver for this run's `@tool:` pointers. The host binds it into the
* ToolContext so `ml.dereference` inside an approved exec reads THIS run's outputs — and only while a
* tool of this run is executing. The loop owns the store, so it is the only place that can hand this out. */
tokenSink?: (resolve: (ref: string, pipe?: string | string[], limits?: PipeLimits) => DerefRead) => void;
tokenSink?: (resolve: (ref: string, pipe?: string | string[], limits?: PipeLimits, mask?: (v: TokenValue) => TokenValue) => DerefRead) => void;
/** Called once at run start with a way to SNAPSHOT this run's context, for `ml.current` in a read-only `exec`
* (docs/spec/CURRENT_CONTEXT.md). The same arrangement as `tokenSink`, for the same reason: the loop is the only
* thing holding the messages and what it recorded about each, so it hands out the reader. The host adds what
Expand Down Expand Up @@ -787,7 +787,9 @@ export async function runAgentLoop(task: string, opts: AgentLoopOptions, deps: A
};
// Hand the resolver to the host (see tokenSink). Throws exactly what the tool would return, so a failed
// read inside exec surfaces the same MemoryFault / pipe error the model sees from the tool itself.
opts.tokenSink?.((ref: string, pipe?: string | string[], limits?: PipeLimits): DerefRead => {
// `mask` is code's (worker-readonly-ml.ts `derefWhole`, ruling 133): the value faked before any pipe reads it, so
// the pipe, the meta and the answer all read the fake.
opts.tokenSink?.((ref: string, pipe?: string | string[], limits?: PipeLimits, mask?: (v: TokenValue) => TokenValue): DerefRead => {
// An attached file: what it is, and the key of what code reads, never the text: a text file's bytes as
// attached (`data`, which derefWhole masks), a PDF's read document. The read is the worker's (derefWhole),
// which can wait on the store; a caller that cannot is refused there (preReadsFor).
Expand All @@ -798,8 +800,9 @@ export async function runAgentLoop(task: string, opts: AgentLoopOptions, deps: A
const file = { name: f.name, type: f.type, bytes: f.bytes, turn: f.turn, ...(isTextFile(f) ? { lines: f.lines } : { pages: f.pages }) };
return { value: `${fileRef(f)} ${quoteName(f.name)}: attached by the person. ${fileKindSaid(f)}.`, meta: { id: f.id, tool: "attached", kind: "text", step: 0, value: isTextFile(f) ? f.data : f.doc, file } };
}
const { value: v, matched, score } = tokenStore.resolveRef(ref, opts.labelMatch);
if (!v) throw new Error(memoryFault(ref, tokenStore.nearest(ref), seq));
const { value: found, matched, score } = tokenStore.resolveRef(ref, opts.labelMatch);
if (!found) throw new Error(memoryFault(ref, tokenStore.nearest(ref), seq));
const v = mask ? mask(found) : found;
// A soft label match travels BESIDE the value, never inside it: the caller here is a script that will
// parse/split/pipe what it gets back, so a note appended to the value would corrupt the data.
const warning = matched
Expand Down
5 changes: 4 additions & 1 deletion src/background.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Background service worker: owns config, builds per-format request bodies,

Check warning on line 1 in src/background.ts

View workflow job for this annotation

GitHub Actions / tools

src/background.ts is 1716 lines (+3 in this change, was 1713, and 9.6% of the repo's edit cost) — over 800. consider refactoring this into separate logical modules (`node scripts/move-symbols.mjs` does the move), and moving the tests that cover them into per-module files where that follows.
// extracts replies, and makes the privileged (host-permissioned) fetches. All
// server JSON is genuinely opaque, so it's typed `any`; our own data uses the
// shared contract types.
Expand Down Expand Up @@ -43,6 +43,7 @@
import { handleRunStateDump } from "./sw/sw-run-state";
import { releaseSessionValues, startValueSweeps, valueHolders, readStoredColumns } from "./sw/sw-values"; // where a table larger than its preview lives (docs/spec/POINTER_VALUES.md) // what the system decided on its own (docs/dev/housekeeping.md)
import { costCalls } from "./sw/sw-prices";
import { sessionFakeForms } from "./sw/sw-fake-key"; // code reads a stored table faked (ruling 133)
import { PendingApprovalDescriptor, pendingApprovals, externallyResolvable, externalApprovals, resolveApproval, fetchConsent, credFetchGrants, senderTrust, serverToolKey, tabGrants } from "./sw/sw-consent";
import { syncPresence, isVisible, presence, injectRunTools, injectPageScripts, SITE_REQUESTS_KEY } from "./sw/sw-presence";
import { isExtensionSender, senderFacts, editSiteAccess, pageRefusal, agentRefusal, readSiteLists, selfApprovalFacts, senderSelfApproves, siteLevels, siteSchemaReady, upgradeNotice, dismissUpgradeNotice } from "./sw/sw-site-access";
Expand Down Expand Up @@ -1049,7 +1050,9 @@
sendResponse({ error: "That stored table was not named by the running script." }); return;
}
try {
const r = await readStoredColumns(key, names, { ...(typeof message.delimiter === "string" ? { delimiter: message.delimiter } : {}), ...(message.headerless ? { headerless: true } : {}) }, plan);
// Faked as code reads it (ruling 133), with the run's session's fakes, or the tab's for a page-hosted run.
const forms = await sessionFakeForms(viaPage ? `page:${tabId}` : runId).catch(() => null);
const r = await readStoredColumns(key, names, { ...(typeof message.delimiter === "string" ? { delimiter: message.delimiter } : {}), ...(message.headerless ? { headerless: true } : {}) }, forms, plan);
sendResponse(r);
} catch (e) { sendResponse({ error: (e as Error)?.message || String(e) }); }
})();
Expand Down
12 changes: 10 additions & 2 deletions src/ml/ml-python.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,20 @@ export const pythonExec = async function(this: MlApi, code: string, { image = nu
// A returned DataFrame → the UI renders a real table. Past its preview it carries the whole frame's row count, and
// the value-store key its pointer will name.
if (r.table) extra.resultTable = { ...r.table, ...(r.valueKey ? { value: r.valueKey } : {}) };
const read = hoisted.flatMap((h) => h.answer ? [{ src: h.src, answer: h.answer }] : []);
// What the cell READ, which the worker hands back faked (ruling 133, `tablesRead`, one per table sent), never what this
// page hoisted: a table it did not hand back is left out.
const asRead = (r as { tablesRead?: (LoadedTable["data"] | null)[] }).tablesRead;
const read = hoisted.flatMap((h, i) => {
if (!h.answer) return [];
const data = asRead ? asRead[i] : h.answer.data;
return data ? [{ src: h.src, answer: { ...h.answer, data, ...(data === h.answer.data ? {} : { preview: undefined }) } }] : [];
});
if (read.length) extra.inputTables = read.map(({ src, answer: l }) => ({
name: src, source: l.source,
...(l.data.kind === "rows" ? { columns: l.data.columns, rows: l.data.rows } : l.data.kind === "value" ? { columns: l.data.columns, rows: l.preview ?? [], ...(l.rowCount != null ? { rowCount: l.rowCount } : {}) } : { html: true }),
}));
return Object.keys(extra).length ? { ...r, ...extra } : r;
const { tablesRead: _read, ...answer } = r as typeof r & { tablesRead?: unknown };
return Object.keys(extra).length ? { ...answer, ...extra } : answer;
};

/**
Expand Down
11 changes: 9 additions & 2 deletions src/offscreen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ import { b64ToBytes, bytesToB64, type PdfMessage, type PdfReadReply, type PdfRen
import { importTestCode } from "./python/pkg-install-test";
import { attachFiles, detachFiles, filesMessage, readWholeFile, setFilesReader } from "./python/files-host";
import { ML_TABLE_FILE_MAX, tableAnswerBytes } from "./python/table-answer";
import { fakeKeyOf } from "./sw/ml-wire-serve";
import type { FakedForm } from "./secret-fake";
import { createFilesSource } from "./python/files-source";
import { RangedReader } from "./session/ranged-reader";
import { AgentFiles } from "./session/agent-files";
Expand Down Expand Up @@ -216,7 +218,7 @@ type PendingEntry = typeof pending extends Map<number, infer E> ? E : never;
// document's to stamp — the worker never sees it (LANE_1_PR2_DESIGN.md "Who stamps the handle"). An
// `ask` first answer is NOT relayed down: the cell's `send` stays pending until the later `ML_ANSWER`
// push, matched by `client`, arrives here.
const wireByClient = new Map<string, { post: (m: unknown, transfer?: Transferable[]) => void; runMsgId: number; principal: string; calls: Map<number, string> }>(); // state: plumbing — one in-flight cell each
const wireByClient = new Map<string, { post: (m: unknown, transfer?: Transferable[]) => void; runMsgId: number; principal: string; fakeKey: string; calls: Map<number, string> }>(); // state: plumbing — one in-flight cell each

/**
* Post a wire call's final answer to the cell that made it. An `ml.table` answer over a stored table or a `/files/` file
Expand All @@ -234,6 +236,11 @@ async function postWireAnswer(client: string, seq: number, answer: unknown): Pro
? await tableAnswerBytes(answer, {
stored: async (key) => { const { row, blob } = await store().get(key); return { format: row.format, buffer: await blob.arrayBuffer() }; },
file: (path) => readWholeFile(entry.principal, path, ML_TABLE_FILE_MAX),
forms: async () => {
const got = await chrome.runtime.sendMessage({ type: "FILES_SECRET_FORMS", session: entry.fakeKey }) as { forms?: FakedForm[] | null } | undefined;
if (!Array.isArray(got?.forms)) throw new Error("the secrets could not be read");
return got.forms;
},
})
: { answer };
const mlAnswer = { seq, answer: ready.answer, ...(ready.buffer ? { buffer: ready.buffer } : {}) };
Expand Down Expand Up @@ -725,7 +732,7 @@ function runInWorker(code: string, image: string | null, hardened: boolean, stre
// THE `ml` WIRE: the handle stays HERE. The worker is told only that this run has a wire and which
// run's namespace it is — never `client` (LANE_1_PR2_DESIGN.md, "Who stamps the handle").
if ((inside && Array.isArray(libraries?.libraries) && libraries.libraries.length) || libraries?.library) libraryPrincipals.add(principal);
if (wire) wireByClient.set(wire.client, { post: (m, transfer) => { try { w.postMessage(m, transfer ?? []); } catch { /* worker gone */ } }, runMsgId: id, principal, calls: new Map() });
if (wire) wireByClient.set(wire.client, { post: (m, transfer) => { try { w.postMessage(m, transfer ?? []); } catch { /* worker gone */ } }, runMsgId: id, principal, fakeKey: fakeKeyOf(wire, wire.client), calls: new Map() });
// A leased cell always streams to this document, which keeps its tail; the chunks go on only for a `streamId`.
w.postMessage({ id, code, image, hardened, stream: stream || cell !== undefined, ...(wire ? { wire: true, run: wire.run } : {}), ...(env ? { env: true } : {}), ...(complete ? { complete } : {}), ...(bench?.persist ? { persist: true } : {}), ...(bench?.reset ? { benchReset: true } : {}), ...(inside ? { inside: true } : {}),
// The person's approved tier 3 libraries ride an inside run; a library op (its card's shape, its load after
Expand Down
17 changes: 15 additions & 2 deletions src/python/table-answer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { binaryKind } from "../sw/body-read";
import { hasHeaderRow, looksArrowFile, looksParquet, parseDelimited, sniffDelimiter } from "../table/table-data";
import type { TableSource } from "../contract";
import { WireError } from "../sw/ml-wire-serve";
import { fakeStoredTable, TableNotFaked } from "./table-fake";
import { fakeSecretText, type FakedForm } from "../secret-fake";

type Cell = string | number | boolean | null;

Expand All @@ -31,10 +33,12 @@ export const ML_TABLE_FILE_MAX = 64 * 1024 * 1024;
/** How much of a file's head decides its delimiter and header: enough lines for `sniffDelimiter` and `hasHeaderRow`. */
const HEAD_BYTES = 64 * 1024;

/** What the relay needs of the offscreen document: a stored value's bytes and format, and a whole `/files/` file. */
/** What the relay needs of the offscreen document: a stored value's bytes and format, a whole `/files/` file, and the
* cell's forms with their fakes (FILES_SECRET_FORMS), which throws when they cannot be read. */
export interface TableAnswerDeps {
stored(key: string): Promise<{ format: string; buffer: ArrayBuffer }>;
file(path: string): Promise<ArrayBuffer>;
forms(): Promise<readonly FakedForm[]>;
}

type Answer = { seq?: number; value?: { source?: unknown; data?: Record<string, unknown> } & Record<string, unknown>; error?: unknown } & Record<string, unknown>;
Expand All @@ -55,11 +59,20 @@ export async function tableAnswerBytes(answer: unknown, deps: TableAnswerDeps):
if (!a || !data || (data.kind !== "value" && data.kind !== "file")) return { answer };
const fail = (code: string, message: string) => ({ answer: { seq: a.seq, error: { code, message } } });
if (data.kind === "value") {
// A stored table reaches the cell faked (ruling 133): read here, from the store, which keeps what the server sent.
let forms: readonly FakedForm[];
try { forms = await deps.forms(); } catch { return fail("Failed", "ml.table: the registered secrets could not be read, so this read is withheld."); }
try {
const { format, buffer } = await deps.stored(String(data.key));
const stored = await deps.stored(String(data.key));
const { format, buffer } = await fakeStoredTable(stored.format, stored.buffer, forms);
const { key: _key, ...rest } = data;
return { answer: { ...a, value: { ...a.value, data: { ...rest, format } } }, buffer };
} catch (e) {
if (e instanceof TableNotFaked) {
const label = (a.value?.source as { label?: unknown } | undefined)?.label;
// The source is the code's own text, faked too, so the refusal holds no registered value.
return fail("Failed", `ml.table(${JSON.stringify(fakeSecretText(typeof label === "string" ? label : String(data.label ?? ""), forms))}): ${e.message}`);
}
return fail("Failed", `ml.table could not read the stored table: ${(e as Error)?.message ?? e}`);
}
}
Expand Down
Loading
Loading