Skip to content
5 changes: 3 additions & 2 deletions docs/dev/shell.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,9 @@ disk (ruling 91, H16) is not built.
so on the session, and `EROFS` or a read-only mount means no folder. The record is the name the host answered with:
on the saved row (`StoredSessionRow.folder`), or in `chrome.storage.session` (`ml_session_folder:<hash>`) for an
unsaved session, so an eviction does not make a second folder. Never on `SessionSummary`. `startedBy` is required:
anything but `"person"` (sw-runs.ts `runStartedBy`: a run the worker minted, never handed over from a page) mounts
nothing and reads no record. Nothing calls it yet.
anything but `"person"` (sw-runs.ts `runStartedBy`: the run payload's `startedBy`, written once where the worker
minted the id and kept as stored through a resume, a hand-over and a restore) mounts nothing and reads no record. A
run stored before `startedBy` existed reads `"page"`. Nothing calls it yet.
- `stat` gives the facts and a `basis`. `judgeMount(op, facts, to?)` takes every row of the table that applies, and the
most restrictive wins, refused over asks over free. Inside the uploads folder but outside `attached/`, the uploads
row stands in for the git rows: the folder is ignored by design, so `gitUndoable` would always be false there. A
Expand Down
1 change: 1 addition & 0 deletions docs/dev/state.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ page-hosted one. Several stores exist once per host.
| The run's current tab and URL | `activeRuns`, `tabPageUrl` | `ml_pinned_tabs` (pinned tabs only) | `run` |
| Interrupted / auto-resumed | `hydratedRuns`, `resurrectedRuns` | derived from `ml_bgrun_*` | `run` |
| The note a resume with no tab last gave the model (`noTabTold`), so a later one that reads the same is not given after each eviction | `bgRuns[runId].p.noTabTold` (set by `resumeDetached`, `sw-sessions.ts`; removed by every way onto a tab, `offNoTab`, `no-tab.ts`) | with the payload: `ml_bgrun_<runId>` while live, the session store's `runmeta` if saved | `run.noTabTold` |
| Who started the run (`startedBy: "person"`), what `runStartedBy` reads and a session's own folder is gated on | `bgRuns[runId].p.startedBy`, written once where the worker mints the id (`startMinted`, `sw-run-start.ts`); never by a hand-over, a resume, an adoption or a restore, and stripped from a page's START_RUN (`PAGE_STRIPPED_KEYS`). Not `builtBy` (a hand-over rewrites it) and not the hand-over list (a resume adds to it, and an entry can be lost) | with the payload: `ml_bgrun_<runId>` while live, the session store's `runmeta` if saved, and an archive's copy of it. Lost with the payload: an unsaved run's snapshot when it settles. A payload stored before the field existed has none and reads `"page"`; nothing infers it. A row a backup or the archive folder restores is read as stored, the person's own file | `run.started-by` |
| Delegated sub-call spend | `subTally` / `bgRuns.sub`; page: `subUsage` (`bus.ts`); a worker-built run's worker tools: `runs[runId].spent` (`worker-tools.ts`), reported per call as the envelope's `subUsage` | in `history.sub` if saved | `run` (the model sees it via `chat_metadata`) |
| What a worker-built run's worker-side `fetch_url` and `python_exec` were approved for (URL consent, one-time as-you reads, the running call's sheets and code outside the Python dialect) | `runs[runId].consented`, `.credOnce`, `.pyCall` (`worker-tools.ts`, worker memory); never the tab's | no; lost on an eviction, and a call then asks again | maybe |
| What a worker-built run's `fetch_url` read (the read-only survey's free re-reads) | `runs[runId].cache` (`worker-tools.ts`, worker memory, frozen copies); page-hosted and approved exec: `mlFetchCache` (`injected.ts`, page) | no; the worker's goes with an eviction (a re-read then asks again) | maybe |
Expand Down
10 changes: 7 additions & 3 deletions docs/spec/FILE_ATTACHMENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1489,9 +1489,13 @@ coordinator the same day.
the folder's name beside it.
- The record is keyed by the session id, and a page can name an id, so `mountForSession` mounts only for a run the
worker started for the person, never for a page-started run or an id a page supplied (the coordinator,
2026-11-29; the run's `startedBy` is required, read from the worker's own facts, `runStartedBy`). A chat session
has no folder: a worker chat has one tool (`read_pages`), no `ml.sh` and no cell, so nothing in it reads a folder on
disk, and `runStartedBy` reads it as `"page"`.
2026-11-29; the run's `startedBy` is required, read from the worker's own facts, `runStartedBy`). The fact is the
run payload's `startedBy`, written once where the worker mints the id and never by a resume, a hand-over or a
restore; a run stored before it existed reads `"page"` and gets no folder (the coordinator, 2026-11-30). A stated
limit: a row a backup or the archive folder brings back is read by its stored payload, so a file whose row says
`"person"` gets a folder; the file is the person's own, and restoring it is the person's act. A chat
session has no folder: a worker chat has one tool (`read_pages`), no `ml.sh` and no cell, so nothing in it reads a
folder on disk, and `runStartedBy` reads it as `"page"`.
- A collision, a directory of that name that the session's record does not name (another session whose id shares six
characters, or one the person made): the new folder takes the next free suffix, `-2`, `-3`, up to `-20`, and
records the name the host made. Past `-20` the mount fails: `No free folder name for this session under
Expand Down
6 changes: 5 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 1717 lines (+4 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 @@ -53,7 +53,7 @@
import { checkDraft } from "./sw/sw-manifest-proposal";

import { bringableSessions, bringHere } from "./sw/bring-here";
import { isWorkerRun, withoutWorkerSession, makeWorkerRun, dropHandedMemoryForTest, runControllers, runInboxes, bgRuns, activeRuns, runRebuilds, runReplayBuffer, replayedTo, hydratedRuns, resurrectedRuns, readoptPageInfo, hydratePersistedRuns, navBarrier, pageValueSession, hydrationDone, purgeAllBgRuns, bufferReplay, derefByRun, contextByRun, turnByRun, workerRunsStarting, execReads, deleteRun, releaseSessionTokens, tabPageUrl, switchRunModel, forgetRunModel, retabRuns, detachTabRuns, runHasNoTab, senderOwnsRun, reconcileTabPins, startingControllers, abortStart, startingOwnedBy } from "./sw/sw-runs";
import { isWorkerRun, withoutWorkerSession, makeWorkerRun, runStartedBy, dropHandedMemoryForTest, runControllers, runInboxes, bgRuns, activeRuns, runRebuilds, runReplayBuffer, replayedTo, hydratedRuns, resurrectedRuns, readoptPageInfo, hydratePersistedRuns, navBarrier, pageValueSession, hydrationDone, purgeAllBgRuns, bufferReplay, derefByRun, contextByRun, turnByRun, workerRunsStarting, execReads, deleteRun, releaseSessionTokens, tabPageUrl, switchRunModel, forgetRunModel, retabRuns, detachTabRuns, runHasNoTab, senderOwnsRun, reconcileTabPins, startingControllers, abortStart, startingOwnedBy } from "./sw/sw-runs";
import { cancelPageTasks, detachTask, dropAllTaskMemory, resetTaskChain, taskAction, type TaskOutcome } from "./sw/sw-tasks";
import { refreshTaskRow, setNoTabReader, setReleaseAtReader, syncTaskRows } from "./sw/sw-task-rows";
import { onTabClosed, releaseAtOf, restoreReleases } from "./sw/sw-release";
Expand Down Expand Up @@ -170,6 +170,10 @@
replayTabs: [...runReplayBuffer.keys()], deref: [...derefByRun.keys()], context: [...contextByRun.keys()], turns: [...turnByRun.keys()],
starting: [...new Set([...workerRunsStarting, ...startingControllers.keys()])], sessions: sessionServer.index.list().map((s) => s.id.hash),
});
// TEST-ONLY (SW realm only, like the ones above): the worker's own answer to who started a run (`runStartedBy`), so a
// red-team row can ask it after a REAL flow — a start, a hand-over, an eviction, a resume — with no message type that
// would give a page the same answer (tests/redteam-run-origin.test.mjs).
(globalThis as unknown as { __mlRunStartedByForTest?: unknown }).__mlRunStartedByForTest = (runId: string) => runStartedBy(runId);
// TEST-ONLY (SW realm only): the payloads a run's next message is recorded on (the live turn's and the stored one), as
// the files' ids and the message count each carries (tests/task-starts-turn.test.mjs: a message taken back leaves neither).
(globalThis as unknown as { __mlRunPayloadsForTest?: unknown }).__mlRunPayloadsForTest = (hash: string): Array<{ files: string[]; sends: number | undefined }> =>
Expand Down
5 changes: 5 additions & 0 deletions src/contract/contract-messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,11 @@ export interface StartRunPayload {
* sw-run-start.ts), so no page-side caller exists to emit its lifecycle events, and its remote tools run in the
* worker. Absent: a page built it (a console `ml.agent()`), as before. */
builtBy?: "worker";
/** "person": the worker minted this run's id for the person (sw-run-start.ts `startMinted`), the one place it is
* written. A hand-over, resume or restore keeps it as stored and never writes it; a page's START_RUN cannot set it
* (`PAGE_STRIPPED_KEYS`). Absent: a page's run, a hand-over from one, or a run stored before this field existed.
* Read by `runStartedBy` (sw-runs.ts), never `builtBy`, which a hand-over rewrites. */
startedBy?: "person";
}

/** The serializable state a fresh document needs to rebuild a background-hosted run's BUILTIN toolset after
Expand Down
1 change: 1 addition & 0 deletions src/sw/run-payload-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ const rebuild = shape({
const START_FIELDS: Record<string, Check> = {
runId: (v, at) => runIdError(v, at), task: str, systemPrompt: str, tools: listOf(RUN_PAYLOAD_LIMITS.tools, tool),
model: optional(strOrNull), think: optional(boolOrNull), display: optional(obj), origin: optional(obj), builtBy: optional(oneOf(["worker"])),
startedBy: optional(oneOf(["person"])),
stream: optional(bool), autoApprovePython: optional(bool), autoApproveReadonly: optional(bool),
// Retired (a same-origin as-you fetch is free, docs/spec/POLICIES.md "One free tier"): still accepted, and dropped, so a
// run persisted before the upgrade resumes.
Expand Down
5 changes: 3 additions & 2 deletions src/sw/sw-run-host.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// sw-run-host.ts — hosting ONE background agent run: the loop runs at the extension origin and every tool is

Check warning on line 1 in src/sw/sw-run-host.ts

View workflow job for this annotation

GitHub Actions / tools

src/sw/sw-run-host.ts is 2430 lines (+1 in this change, was 2429, and 13.1% 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.
// delegated back to the page that built the toolset (RUN_TOOL_IN_PAGE), with approval gated through the sidebar.
// This is design A, and it is the whole of it: the router in background.ts only hands a START_RUN / RESUME_RUN
// over and keeps the channel open until the run finishes.
Expand Down Expand Up @@ -362,7 +362,7 @@
* The keys a page's START_RUN may not set, at the payload's top level and inside its `rebuild` alike: the person's
* fields and the sender's (`pageStartPayload`). One list for both levels, so a key added here is stripped at each.
*/
export const PAGE_STRIPPED_KEYS = ["builtBy", "display", "files", "sends", "origin", "pageOrigin", "pageUrl", "inputScrubbed", "shell", "noTabTold"] as const;
export const PAGE_STRIPPED_KEYS = ["builtBy", "display", "files", "sends", "origin", "pageOrigin", "pageUrl", "inputScrubbed", "shell", "noTabTold", "startedBy"] as const;

/**
* A shallow copy of `o` without any of `PAGE_STRIPPED_KEYS`.
Expand All @@ -379,7 +379,8 @@
* A page's START_RUN payload as the worker may trust it. A page's payload may ask for MORE gating, never less.
* - Removed, the worker's to set, at the top level and inside `rebuild` alike (`PAGE_STRIPPED_KEYS`): `builtBy`, `display`, `files` (pointers naming value-store rows), `sends`,
* `inputScrubbed` (a page's claim would spare a stored session's raw user turns the scrub on resume), `shell`,
* `noTabTold` (a page's claim would keep the no-tab note from its model) and `origin` (the PromptOrigin: a page could stamp its prompt as typed on an extension surface). Only the worker's own `hostRun` call
* `noTabTold` (a page's claim would keep the no-tab note from its model), `startedBy` (a page's claim would make its
* run read as the person's, `runStartedBy`) and `origin` (the PromptOrigin: a page could stamp its prompt as typed on an extension surface). Only the worker's own `hostRun` call
* (sw-run-start.ts) marks a run worker-built, and `makeWorkerRun` hands one over; a page's claim would give its run the
* worker's tool routing, grants, vision and answer, and lock the run as the person's.
* - Removed from `tools`: `propose_policy`, which only a run the worker built offers (a page's run asking the person for
Expand Down
2 changes: 2 additions & 0 deletions src/sw/sw-run-start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ async function startMinted(tabId: number, tab: chrome.tabs.Tab | undefined, url:
...(recipe.display ? { display: recipe.display } : {}),
...(shelf.size ? { files: shelf.all() } : {}),
...(shellOn ? { shell: true } : {}),
// The one write of who started the run: here, where the worker minted its id (`runStartedBy` reads it).
startedBy: "person",
};
if (opts.keep) keepSession(runId);
// The run's result reaches every surface through its own lifecycle events (`builtBy: "worker"`), so nobody
Expand Down
16 changes: 12 additions & 4 deletions src/sw/sw-runs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,15 +157,23 @@ export function makeWorkerRun(runId: string): void {

/**
* Whether a run is one the worker started for the person, with an id the worker minted (sw-run-start.ts `shortHash`):
* built by the worker and never handed to it from a page. A run a page started, or handed over from one, keeps the id
* the page chose. Read after the restore (`hydrationDone`), so an evicted worker does not read a hand-over as absent.
* its stored payload's `startedBy`, written once where the id was minted and carried as stored by every hand-over,
* resume, adoption and restore. Neither `builtBy` (a hand-over rewrites it) nor the hand-over list (a resume adds to it,
* and an entry can be lost) says who started a run. Read after the restore (`hydrationDone`), so an evicted worker's
* runs are back in `bgRuns` first.
* @param runId the run
* @returns `"person"` for such a run, `"page"` for every other id, a run this worker does not know included
* @returns `"person"` for such a run, `"page"` for every other id: a page's run, a run stored before `startedBy`
* existed, a run still starting, and a run this worker does not hold
*/
export async function runStartedBy(runId: string): Promise<"person" | "page"> {
await hydrationDone;
return isWorkerRun(runId) && !handedToWorker.has(runId) ? "person" : "page";
return isWorkerRun(runId) && bgRuns.get(runId)?.p.startedBy === "person" ? "person" : "page";
}
defineState({
id: "run.started-by", scope: "run", realm: "worker", audience: "human", lostOn: [],
describe: "Who started the run: \"person\" when the worker minted its id for the person, written once then; absent for a page's run, a hand-over from one, and a run stored before the field existed. Kept on the run's snapshot and the saved session's payload.",
read: ({ runId }) => (runId ? bgRuns.get(runId)?.p.startedBy : undefined),
});

/** TEST-ONLY (`__mlEvictForTest`): forget the hand-overs held in memory, as an eviction does; storage keeps them. */
export function dropHandedMemoryForTest(): void { handedToWorker.clear(); }
Expand Down
Loading
Loading