diff --git a/docs/dev/policies.md b/docs/dev/policies.md index 97abddac7..a4519eeca 100644 --- a/docs/dev/policies.md +++ b/docs/dev/policies.md @@ -455,8 +455,21 @@ four defaults, and `resolveHidden` (session, then global, then the defaults; the at each call and sends them as the host's `hideList` in ascending precedence (`hostHideList`, which sorts by `resolveHidden`'s own order, so the host's last match is the entry `resolveHidden` names). A host without `hello.hideList` gets no call while a `hide` applies. -- **A path the host reports `hiddenBy` asks** before any `allow` (`namesHidden` in `judgeCall`), and the card names the - rule from `ShFactsPlace.hideRules`. A library proposal refuses such a path, as it refuses a secret one. +- **A path the host reports `hiddenBy` asks** before any `allow` (`hiddenPathOf` in `judgeCall`, carried as the + judgement's `hidden`), and the card names the rule from `ShFactsPlace.hideRules`; `askWhyOf` gives it the cause + `hidden-path`. A default is named in `DEFAULT_RULE_WORDS` (`files-hide.ts`), which `hideRuleWords` merges, so the card + line and the ask's line say the same words. A library proposal refuses such a path, as it refuses a secret one. +- **The view shows the four defaults in every session**, with or without a stored `files` rule: unlike other consumers' + one default row, they hold files whatever was written. +- **`propose_files_rule` is the propose_manifest pattern.** The precheck (`checkFilesRuleProposal`) refuses what the + worker would not add, with no card; the card is checked again and frozen at the gate (`filesRuleCardFor`, `renderIn` + type `files-rule`); the resolve stores only that card's rule (`approveFilesRule`), at the session, or globally when + the answer carries `persist` and the card offered "Always"; the tool's run reads the outcome once. Every resolve path + drops a decision's `arguments`, so a forged one never chooses the rule. A `show` preview of a `/files/...` pattern + walks the browser copy's listing and keeps a path only when `resolveHidden` with the proposal says it decides, so the + card's list is the reader's own decision; any other pattern asks the host's `glob`, at most 1000. +- **The policy page writes global rows itself** (`POLICIES` ops `addFiles`, `removeFiles`), through `addFilesRule` and + `removeFilesRule` with no session, so removing a global `hide` confirms with what would then decide, as a view does. - **A `hide` row's label ends with its limits** (`hideLimits`): the hard-link line always, the late-file line only when `shellStatus().host.platform` is `linux`. In the label, since e3's view test allows a row no other key. diff --git a/docs/spec/POLICIES.md b/docs/spec/POLICIES.md index f7f53cd38..c5fd6535b 100644 --- a/docs/spec/POLICIES.md +++ b/docs/spec/POLICIES.md @@ -835,18 +835,26 @@ in the policy store, the four defaults as built-in rows, the layer rule and its `policy.files` command, the view's rows (`src/sw/files-hide-view.ts`), and the `/files` reader in the offscreen document bound by the resolved list (`src/session/files-hide-rule.ts`), which Python's mount and `ml.fs` both read through. The second PR (window-ml-host #58 and this repository's half) binds a program the shell starts: every `spawn` goes through -`spawnBound` (`src/sw/sw-spawn.ts`) and carries the list, below. NOT built: the model's proposal card, the offer when a -root is added, and the four defaults in the view of a session with no `files` rule: as for every consumer, a default row -appears once the consumer has a rule (a stated gap, closed before PR C merges, with the three tests that pin it). In the -browser copy, which has no symlinks, `default:link-target` and `default:linked-template` hold nothing, and the -linked-template refusal of a `show` is the host's to make. Three choices made in building it, on the red team's findings -at #2088: the policy page's generic edit and remove refuse a `files` row (an `allow` saved over a `hide` held nothing, -and one click removed a `hide` with no confirmation), so a hiding rule is removed only from a session's view, which -confirms, and DevTools Settings' own form for these rows is PR C; a `hide` that matches a directory holds everything -under it, as the offer's one row for a credential directory needs, while a `show` releases only what it matches; and -`ml.current.policies` carries no `files` row. The reason given at #2088, that a hidden file reads as absent, does not -hold: its NAME is listed ("What a hidden file shows", below). Whether the model may read its own hiding rules is decided -with the masked-file design; until then the row stays out. +`spawnBound` (`src/sw/sw-spawn.ts`) and carries the list, below. The third (PR C1) adds the model's proposal, +`propose_files_rule` (`src/tools/propose-files-rule-tool.ts`, its check and card in `src/sw/files-rule-proposal.ts` and +`src/sw/sw-files-proposal.ts`), the ask's cause line for a call naming a hidden path (`hidden-path`), the four defaults +in every session's view whether or not a `files` rule is stored (they hold files with no rule written, unlike every +other consumer's default row), and DevTools Settings' own form for these rows. NOT built: the offer when a root is +added. In the browser copy, which has no symlinks, `default:link-target` and `default:linked-template` hold nothing. +A linked group released whole or not at all is NOT built either: window-ml-host's main releases a template on a `show` +(its PROTOCOL.md, `hideList`) even when a held name links to it; the ruled design is window-ml-host #63 (open), below, +with files-host's worker-line PR. Until then `propose_files_rule` refuses, before any card, every `show` whose pattern's +last segment can match a dotenv template (`.env.example`, `.env.sample`, `.env.template`, a glob such as `.env.*` or +`.env.exampl?` included), whether or not a link points at it; a person's own `show` written on the policy page is not +checked this way. Files-host's worker-line PR lifts that refusal once a host that reports `unappliedShows` is the +minimum the extension accepts. Three choices made in building it, on the red +team's findings at #2088: the policy page's generic edit and remove refuse a `files` row (an `allow` saved over a `hide` +held nothing, and one click removed a `hide` with no confirmation), so the page draws its own row and form for them, +and removing a `hide` there, as from a session's view, first names what would decide instead; a `hide` that matches a +directory holds everything under it, as the offer's one row for a credential directory needs, while a `show` releases +only what it matches; and `ml.current.policies` carries no `files` row. The reason given at #2088, that a hidden file +reads as absent, does not hold: its NAME is listed ("What a hidden file shows", below). Whether the model may read its +own hiding rules is decided with the masked-file design; until then the row stays out. **One list, two verbs, the policy store's.** A hiding rule is a `StoredPolicy` with consumer `files`, effect `hide` or `show`, and `source` a path or a glob. Scope `global`, or `run`, which is the session's and keyed by its hash, as for @@ -864,11 +872,14 @@ lifetime rules (it survives a resume and is removed at archive) are the ones abo - **A pattern** is an absolute path inside a root, or a glob within the roots using `*`, `?` and `[…]` inside one path segment; `**` is refused, since on Linux every match is a mask the host builds by walking the tree. At most 512 characters, and at most 256 entries a scope. -- **A `show` that cannot be applied whole is refused with its reason, never half-applied.** In the - `ln -s .env.example .env` shape, `show .env.example` would leave `.env` listed as held while on Linux a read through - `.env` lands on the now-unmasked template (on macOS `.env` stays refused by its name, but the same bytes read under - the template's). So the entry is refused, naming `.env` as the link that resolves to it; `show .env` with it is the - entry that applies whole. +- **A `show` that cannot be applied whole is not applied, never half-applied** (window-ml-host #63, open; NOT built + until it and files-host's worker-line PR merge). In the `ln -s .env.example .env` shape, `show .env.example` alone + would leave `.env` listed as held while on Linux a read through `.env` lands on the now-unmasked template (on macOS + `.env` stays refused by its name, but the same bytes read under the template's). So the host refuses nothing: the + root-top names that reach one file are a group, released whole or not at all. A `show` that decided a member of a + group not released is not applied, the call still runs, and the host reports it as `unappliedShows: [{ id, link, + heldBy? }]`; the worker's line to the person names the rule and the link. `show .env` with it is the entry that + releases the group. Until then the model's proposal refuses every `show` that can reach a template (above). - **`mask `, a third effect, is ruled and not built** (ruling 113, 2026-11-24; SECRET_HANDLES.md, "A masked file"). It lists the file, shows its keys with each value replaced, takes writes through the extension's own code and puts the real values back, and is read-only to a program not allowed for it. `default:dotenv` becomes a `mask`. @@ -889,9 +900,17 @@ and `default:linked-template` (a template a held name resolves to). They are bui removed, only overridden. **Who writes and who proposes.** The main path is the MODEL'S PROPOSAL: a card that shows the exact entry and, for a -`show`, the paths it would release at that moment (the host's `glob`, bounded). It offers "this session" (the default) +`show`, the paths it would release at that moment (the host's `glob`, bounded). The card lists at most 50 paths and +counts up to 1000 ("and N more"); a host walk that stopped early says so, and a host that did not answer says the files +are not listed. For a `/files/...` pattern the list is the browser copy's files, read through the same matcher and name +mask as the `/files` reader, until the sync slice gives the host the session's files. It offers "this session" (the default) and "always" (global). A session `show` that overrides a global `hide` names that entry, verbatim, before the paths, and -offers no "always": a global `show` under a global `hide` is the person's own edit on the policy page. A glob releases +offers no "always": a global `show` under a global `hide` is the person's own edit on the policy page. With 256 rules for +every session already stored, the card offers no "always" and says why; a session already holding 256 is refused before +any card. "Always" is the approval's `persist`; an answer that carries it on a card that offered none adds nothing. +Only a person's answer adds a rule: an answer a policy gave adds nothing, and the tool then answers as for no approval. +A scope that fills while the card is open refuses at the answer, and the model reads `Refused: your rules for every +session already number 256.` (global) or `Refused: this session already holds 256 hiding rules.` (session). A glob releases what matches LATER too, and the card says so beside the paths it lists. Nothing changes until the person approves. A person may also write an entry directly, in DevTools Settings, from the file browser's right-click (ruling 24), or with "always" on a card that offers it; that is expected to be rare. A page, `change_setting` and `ml.settings` can neither diff --git a/docs/spec/PROMPT_BUDGET.md b/docs/spec/PROMPT_BUDGET.md index aca792b94..178caf7e4 100644 --- a/docs/spec/PROMPT_BUDGET.md +++ b/docs/spec/PROMPT_BUDGET.md @@ -347,6 +347,16 @@ a token); the default kit's tools, 29,907 → 30,744. No other tool's text diffe registered worker tools compared, ml.sh and `answer` on). The `usage.prompt_tokens` delta is measured at the next prompt review, with bench's rerun on the merge. +## `propose_files_rule` reaches every run with ml.sh (2026-11-30) + +`propose_files_rule` (POLICIES.md, "Hiding files") is offered beside `propose_manifest`, to a run the worker builds +while ml.sh is offered, so its definition is paid on every call of such a run. It is 972 characters as sent (name, +description, parameters, as JSON); `propose_manifest`'s is 1,665. Two hint sentences reach the model where it is +offered: one appended to `hiddenSecrets`' JSDoc in the contract, which `agent_api_docs` serves (about 105 characters, +read only when the model asks for those docs), and `ml.table`'s hidden-file error, which names the tool only in a run +that offers it. No hint follows a denial. The `usage.prompt_tokens` delta is measured at the next prompt review, with +the bench, as for `change_setting` below. + ## `change_setting` reaches every run the worker builds (2026-11-17) `change_setting` (MODEL_SETTINGS.md) is offered by `startUserRun` to every run the worker builds, beside diff --git a/docs/spec/export.schema.json b/docs/spec/export.schema.json index d75d5fdf4..b05666185 100644 --- a/docs/spec/export.schema.json +++ b/docs/spec/export.schema.json @@ -1838,6 +1838,9 @@ ], "additionalProperties": true }, + { + "$ref": "#/$defs/FilesRuleCard" + }, { "type": "object", "properties": { @@ -2599,6 +2602,9 @@ ], "additionalProperties": true }, + { + "$ref": "#/$defs/FilesRuleCard" + }, { "type": "object", "properties": { @@ -3384,6 +3390,78 @@ ], "additionalProperties": true }, + "FilesRuleCard": { + "type": "object", + "description": "propose_files_rule's card (sw/files-rule-proposal.ts), as the worker builds it and every surface draws it: the rule, the model's reason (scrubbed and cut, so a renderer escapes it), for a show the files it matches now, and whether the card offers \"Always\". The worker stores only the rule this card showed.", + "properties": { + "type": { + "type": "string", + "const": "files-rule" + }, + "effect": { + "anyOf": [ + { + "type": "string", + "enum": [ + "hide", + "show" + ] + }, + { + "type": "string", + "description": "This shape is UNSTABLE: it grows as the extension does and is NOT covered by the schema version. The members here are the ones known when this file was generated — read the ones you recognise and tolerate others." + } + ] + }, + "title": { + "type": "string" + }, + "reason": { + "description": "`The model says: \"\"`, the reason cut and scrubbed.", + "type": "string" + }, + "rule": { + "description": "The rule verbatim, ` `, drawn in a code block.", + "type": "string" + }, + "before": { + "description": "Sentences drawn before the paths (the override case).", + "type": "array", + "items": { + "type": "string" + } + }, + "paths": { + "description": "The paths a show matches now, relative to their root; absent for a hide.", + "type": "array", + "items": { + "type": "string" + } + }, + "after": { + "description": "Sentences drawn after the paths.", + "type": "array", + "items": { + "type": "string" + } + }, + "always": { + "description": "Whether the card offers \"Always\" (a global rule); false over a global hide, or with the global layer full.", + "type": "boolean" + } + }, + "required": [ + "type", + "effect", + "title", + "reason", + "rule", + "before", + "after", + "always" + ], + "additionalProperties": true + }, "FetchAttempt": { "type": "object", "description": "One rung of the Markdown ladder, as it actually ran. Recorded for every attempt — including the ones that were skipped — because the failure modes here are INVISIBLE in the body alone: a stub twin is a valid 200 Markdown document that is simply the wrong page, and a site-authored twin is content written specifically to be read by agents (GitBook appends an \"Agent Instructions\" section), so \"which URL did these bytes come from\" is provenance for an injection surface, not decoration.", diff --git a/scripts/test.mjs b/scripts/test.mjs index c2739fd19..33e04ece3 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -192,8 +192,8 @@ const GENRES = { }, // The model's proposal tools: a policy or a manifest or library it drafts, the card the person sees, what is stored. propose: { - about: "propose_policy and propose_manifest (a program manifest or a tier 3 library): the drafts, their cards, what is stored on approval", - files: ["propose-library.test.mjs", "propose-library-redteam.test.mjs", "propose-manifest.test.mjs", "python-install.test.mjs", "propose-policy-redteam.test.mjs", "propose-policy.test.mjs"], + about: "propose_policy, propose_manifest (a program manifest or a tier 3 library) and propose_files_rule (a hiding rule): the drafts, their cards, what is stored on approval", + files: ["files-rule-proposal.test.mjs", "propose-library.test.mjs", "propose-library-redteam.test.mjs", "propose-manifest.test.mjs", "python-install.test.mjs", "propose-policy-redteam.test.mjs", "propose-policy.test.mjs"], }, // The policy store's own tests by name prefix: the worker's ask over a policy, a policy lifted from a call, the model's proposals of one, and the effective view of a session. policy: { diff --git a/src/background.ts b/src/background.ts index dd2b94363..be513866a 100644 --- a/src/background.ts +++ b/src/background.ts @@ -75,7 +75,7 @@ import { runControlPayloadError } from "./sw/run-payload-check"; import { asIsTokens, forBackendFromPage, forPage, forTurn, scanTurn, withAsIs } from "./sw/sw-scrub"; // error text bound for a page, without the config's secrets; a page's model request, without a registered secret import { TurnUnreadable } from "./secret-registry"; import { secretRegistryOp } from "./sw/sw-secret-registry"; -import { filesHideList, signalFilesHideChanges } from "./sw/sw-files-hide"; +import { addFilesRule, filesHideList, removeFilesRule, signalFilesHideChanges } from "./sw/sw-files-hide"; import { pythonPrewarm, pythonExec, pythonInterrupt, relayPyStdout, deletePythonRun, dropPythonLibraries, pythonReaped, filesAttached, filesSecretForms, filesSpliced, filesQuota, filesLost, pythonStarted, pythonDone } from "./sw/sw-python"; import { focusLineFor } from "./sw/sw-focus"; import { chatHashFor, openChatPage } from "./sw/sw-open-chat"; @@ -814,6 +814,19 @@ function route(message: any, sender: chrome.runtime.MessageSender, sendResponse: // Removing a hide widens: only a session's view removes one, and it shows what that exposes first. if (id && isFilesRule(id)) { sendResponse({ error: "a hiding rule is removed from its session's view, which shows what it exposes first" }); return; } if (!id || !removePolicy(id)) { sendResponse({ error: "no such policy" }); return; } + } else if (p.op === "addFiles") { + // The policy page's own form for a hiding rule for every session: the one write path `policy.files` uses. + const source = str(p.source, POLICY_SOURCE_MAX); + if (!source || (p.effect !== "hide" && p.effect !== "show")) { sendResponse({ error: "a hiding rule needs hide or show and a path or a glob" }); return; } + const r = addFilesRule("", { effect: p.effect, source, scope: "global" }); + if ("refused" in r) { sendResponse({ error: `Refused: ${r.refused}.` }); return; } + } else if (p.op === "removeFiles") { + // A global hiding rule's remove: a widening one needs `confirm: true`, and refuses with the ids of what would + // then decide, as a session's view does (the global rows are every session's). + const id = str(p.id, 100); + if (!id || !isFilesRule(id)) { sendResponse({ error: "no such hiding rule" }); return; } + const r = removeFilesRule("", id, p.confirm === true); + if (!r.removed) { sendResponse(r.why === "confirm" ? { error: "confirm", data: { exposes: r.exposes ?? [] } } : { error: "no such hiding rule" }); return; } } else if (p.op === "session") { // One session's effective view (docs/spec/POLICIES.md, "The effective view"): a read, so no change to answer with. const hash = str(p.hash, 100); diff --git a/src/contract.ts b/src/contract.ts index 6e52a96bf..db074a6f5 100644 --- a/src/contract.ts +++ b/src/contract.ts @@ -118,7 +118,8 @@ export interface MlSh { * when the host reported nothing (unknown, never "none"); `protectedChangedTruncated` means the list was cut. * `hiddenSecrets` lists the files (`.env`, `.netrc`, …) the sandbox held unreadable for this call, at most 16, with * `hiddenSecretsMore` the count past them: a program that loads one without naming it fails (EPERM on macOS, EACCES on - * Linux), and naming one as a path argument asks to read it, and always asks. + * Linux), and naming one as a path argument asks to read it, and always asks. Where the propose_files_rule tool is + * offered, its effect "show" asks the person to release one for later calls. * When `ml.current.runtime.capabilities` reports `shellTilde`, an argument or `cwd` that is `~` or starts with `~/` * begins at the home directory; nothing else is expanded. The expanded path is checked like any other: a `cwd` of * `~` is refused (`CwdOutsideRoots`) unless home is inside a workspace folder. diff --git a/src/contract/contract-render.ts b/src/contract/contract-render.ts index 546d3312c..ae331f1cd 100644 --- a/src/contract/contract-render.ts +++ b/src/contract/contract-render.ts @@ -222,9 +222,31 @@ export type RenderDescriptor = ( // values in full, the guarded reason, the model's `why`, and where the change applies. Built by the worker from the // checked change; only `why` is the model's text, and a renderer escapes it with the values (`shownText`). | { type: "setting"; key: string; name: string; tip?: string; reason?: string; class: "guarded" | "ordinary"; from: unknown; to: unknown; why?: string; synced: boolean; host?: string } + | FilesRuleCard | { type: "action"; verb: string; kind?: string; target?: string; selector?: string; input?: string; note?: string; crossOrigin?: string; offMachine?: string; asYou?: string; ask?: string; answeredBy?: string; tokens?: number; askBody?: string; askBodyLang?: string; askBodyTruncated?: boolean; pipe?: string; attempts?: FetchAttempt[]; resolvedBy?: FetchAttempt["strategy"] } ); +/** propose_files_rule's card (sw/files-rule-proposal.ts), as the worker builds it and every surface draws it: the rule, the + * model's reason (scrubbed and cut, so a renderer escapes it), for a show the files it matches now, and whether the card + * offers "Always". The worker stores only the rule this card showed. */ +export interface FilesRuleCard { + type: "files-rule"; + effect: "hide" | "show"; + title: string; + /** `The model says: ""`, the reason cut and scrubbed. */ + reason: string; + /** The rule verbatim, ` `, drawn in a code block. */ + rule: string; + /** Sentences drawn before the paths (the override case). */ + before: string[]; + /** The paths a show matches now, relative to their root; absent for a hide. */ + paths?: string[]; + /** Sentences drawn after the paths. */ + after: string[]; + /** Whether the card offers "Always" (a global rule); false over a global hide, or with the global layer full. */ + always: boolean; +} + /** Input to a tool's `render`: the run's stringified result + the raw envelope * extras (live nodes/image), plus the call args. Runs page-side. */ export interface ToolRenderInput { diff --git a/src/files-hide.ts b/src/files-hide.ts index 88f7ef1fc..8e127b583 100644 --- a/src/files-hide.ts +++ b/src/files-hide.ts @@ -190,6 +190,14 @@ export const DEFAULT_HOLDS: readonly { id: string; label: string }[] = [ { id: "default:linked-template", label: "a template a held name resolves to" }, ]; +/** What a card and an ask call each default rule when a path it holds is named: "hidden by ". */ +export const DEFAULT_RULE_WORDS: Readonly> = { + "default:dotenv": "the default rule for .env files", + "default:credential-files": "the default rule for .netrc, .git-credentials and .pgpass", + "default:link-target": "the default rule for a file a held name links to", + "default:linked-template": "the default rule for a template a held name links to", +}; + /** The dotenv names that are templates and so are not held by `default:dotenv`. */ export const DOTENV_TEMPLATES = [".env.example", ".env.sample", ".env.template"]; diff --git a/src/python/table-answer.ts b/src/python/table-answer.ts index 9693f9463..f47186128 100644 --- a/src/python/table-answer.ts +++ b/src/python/table-answer.ts @@ -12,7 +12,8 @@ type Cell = string | number | boolean | null; * data as rows, as a page's HTML table, as a stored value's key, or as a `/files/` path. `preview` and `rowCount` are * for the run's log (a stored table's first rows and its size), and never cross to the cell. */ export interface TableAnswer { - source: TableSource | { kind: "file"; label: string }; + /** `offersFilesRule`: the run offers `propose_files_rule`, so the reader's hidden-file sentence names it. */ + source: TableSource | { kind: "file"; label: string; offersFilesRule?: true }; data: | { kind: "rows"; columns: string[]; rows: Cell[][] } | { kind: "html"; html: string } @@ -67,13 +68,14 @@ export async function tableAnswerBytes(answer: unknown, deps: TableAnswerDeps): // The source as the caller wrote it (`@file:`, or the /files path): the path read may hold a stored name a // listing masks, so no sentence here prints it (FILE_ATTACHMENTS.md, "Names under `/files`", rule 5). const label = (a.value?.source as { label?: unknown } | undefined)?.label; + const offersFilesRule = (a.value?.source as { offersFilesRule?: unknown } | undefined)?.offersFilesRule === true; const src = JSON.stringify(typeof label === "string" ? label : path); let buffer: ArrayBuffer; try { buffer = await deps.file(path.replace(/^\/files\//, "")); } catch (e) { const err = e as { code?: unknown }; const code = typeof err?.code === "string" ? err.code : "Failed"; - return fail(code, `ml.table(${src}): ${fileReadSaid(code, e)}`); + return fail(code, `ml.table(${src}): ${fileReadSaid(code, e, offersFilesRule)}`); } const bytes = new Uint8Array(buffer); const { path: _path, kind: _kind, ...opts } = data; @@ -97,9 +99,10 @@ export async function tableAnswerBytes(answer: unknown, deps: TableAnswerDeps): * which may hold a stored name, so it is never passed on: a code with no sentence here gets the default one. * @param code the reader's errno, or `Failed` * @param e the reader's error: EFBIG's `size` and `max`, and EACCES's message shape (hidden, or a shown name shared) + * @param offersFilesRule whether the run offers `propose_files_rule`: only then does a hidden file's sentence name it * @returns the sentence, with no path in it */ -export function fileReadSaid(code: string, e: unknown): string { +export function fileReadSaid(code: string, e: unknown, offersFilesRule = false): string { const err = e as { size?: unknown; max?: unknown; message?: unknown } | null; switch (code) { case "EFBIG": return typeof err?.size === "number" && typeof err?.max === "number" ? `the file is ${err.size} bytes, past the ${err.max} a table read takes.` : "the file is past the size a table read takes."; @@ -110,7 +113,7 @@ export function fileReadSaid(code: string, e: unknown): string { case "EACCES": { const shared = /is ambiguous, (\d+) files/.exec(String(err?.message ?? "")); if (shared) return `that name is shared by ${shared[1]} files.`; - if (/is hidden/.test(String(err?.message ?? ""))) return "that file is hidden."; + if (/is hidden/.test(String(err?.message ?? ""))) return offersFilesRule ? "that file is hidden; where the propose_files_rule tool is offered, its effect \"show\" asks the person to release it." : "that file is hidden."; return `the file could not be read (${code}).`; } default: return `the file could not be read (${code}).`; diff --git a/src/shell/host-protocol.ts b/src/shell/host-protocol.ts index 4f044e684..56bfead24 100644 --- a/src/shell/host-protocol.ts +++ b/src/shell/host-protocol.ts @@ -473,6 +473,9 @@ export class HostClient { return this.call("start", envelope === undefined ? { id } : { id, envelope }); } discard(id: string): Promise> { return this.call("discard", { id }); } + /** Expand a pattern within the roots (PROTOCOL.md, "`glob`"): the matches relative to `cwd`, sorted, and whether the + * host stopped at `limit` or its walk's bounds before it had them all. */ + glob(a: { cwd: string; pattern: string; limit?: number }): Promise<{ matches: string[]; truncated: boolean }> { return this.call("glob", a); } /** The owner table (PROTOCOL.md, `status`). Reading it consumes the `ended` records it returns. */ status(): Promise { return this.call("status"); } /** diff --git a/src/sidebar/card/files-rule-card-view.tsx b/src/sidebar/card/files-rule-card-view.tsx new file mode 100644 index 000000000..6ef7685d6 --- /dev/null +++ b/src/sidebar/card/files-rule-card-view.tsx @@ -0,0 +1,40 @@ +// files-rule-card-view.tsx — propose_files_rule's card: the rule, the model's reason, for a show the files it matches now. + +// Every sentence on it was built by the worker (sw/files-rule-proposal.ts); only the reason and the paths are text the +// model or a folder chose. Each is drawn as a text node with a control, bidi or invisible character replaced by U+FFFD +// and listed beside it (`shownText`), so a file name with a newline or a right-to-left mark cannot pose as another. + +import type { RenderDescriptor } from "../../contract/contract-render"; +import { shownText } from "../../python/pkg-card"; + +type FilesRuleCard = Extract; + +/** One line of text with its hidden characters replaced, and those characters listed beside it. */ +function Shown({ cls, text }: { cls: string; text: string }) { + const s = shownText(text); + return {s.text}{s.hidden.length ? {s.hidden.join(" ")} : null}; +} + +/** + * propose_files_rule's card: what it asks, the model's reason, the rule verbatim, and for a show the files it matches now + * and what releasing them gives the model. Whether "Always" is offered is the answer row's (`ApprovalRow`'s `filesRule`). + * @group card + * @gallery {"d": {"type": "files-rule", "effect": "show", "title": "Show files to the model?", "reason": "The model says: \"The task configures the dev server, whose port is in .env.local.\"", "rule": "show /Users/me/proj/.env.local", "before": ["Files it matches now:"], "paths": [".env.local"], "after": ["The model's shell commands, scripts and Python can read and change released files. A value registered as a secret is still scrubbed from what they print.", "Everything else in these files, the model can read."], "always": true}} + */ +export function FilesRuleCardRender({ d }: { d: FilesRuleCard }) { + return ( +
+
{d.title}
+
+
+ {d.before.map((t) =>
{t}
)} + {d.paths?.length ?
    {d.paths.map((p, i) =>
  • )}
: null} + {d.after.map((t) =>
{t}
)} +
+ ); +} + +/** The answer a files-rule card offers beyond "This session": whether "Always" is drawn. Undefined for any other card. */ +export function filesRuleAnswers(d: unknown): { always: boolean } | undefined { + return typeof d === "object" && d !== null && (d as { type?: unknown }).type === "files-rule" ? { always: (d as { always?: unknown }).always === true } : undefined; +} diff --git a/src/sidebar/card/hud-card.tsx b/src/sidebar/card/hud-card.tsx index c4416f336..45cb8bd98 100644 --- a/src/sidebar/card/hud-card.tsx +++ b/src/sidebar/card/hud-card.tsx @@ -35,6 +35,7 @@ import { toHost } from "../parent-channel"; import { imagesRefusal, promptLine } from "../../contract/contract-run"; import { TaskMark } from "./task-mark"; import { isRefusedPkgCard } from "./pkg-card-view"; +import { filesRuleAnswers } from "./files-rule-card-view"; /* ------------------------------ off-mode card ---------------------------- * The "card" surface. When debug is OFF but a privileged ml.agent run must be @@ -628,6 +629,8 @@ export function CardApp() { : pending && pendingStep && !pendingAsk ? (() => { const showGrants = hasPersistGrants(pendingStep.grants); + // A hiding rule's card: Approve is "This session"; "Always" only where the card offers it, never on a key. + const filesRule = filesRuleAnswers(pendingStep.renderIn); return
{pendingStep.askWhy ? : null} {showGrants ? : null} @@ -643,7 +646,8 @@ export function CardApp() { - + + {filesRule?.always ? : null} {showGrants ? : null}
} ; diff --git a/src/sidebar/export/export.ts b/src/sidebar/export/export.ts index f2b9ec697..8e16060dc 100644 --- a/src/sidebar/export/export.ts +++ b/src/sidebar/export/export.ts @@ -470,6 +470,14 @@ function writeAgent(s: Session, d: Sink): void { const notes = [ri.reason ? `Always asks: ${ri.reason}.` : "", ri.why ? `The agent says: "${esc(ri.why)}"` : "", ri.synced ? "Applies to every browser signed in to this profile." : ""].filter(Boolean); if (notes.length) d.note(notes.join(" "), true); renderedIn = true; + } else if (st.renderIn && st.renderIn.type === "files-rule") { + // propose_files_rule's card as the person saw it: the rule, the reason, and a show's paths, escaped as on the card. + const ri = st.renderIn; + const esc = (t: string): string => { const s = shownText(t); return s.hidden.length ? `${s.text} [${s.hidden.join(" ")}]` : s.text; }; + d.inline(ri.title, esc(ri.rule), { code: true }); + const lines = [esc(ri.reason), ...ri.before, ...(ri.paths ?? []).map(esc), ...ri.after]; + d.note(lines.join("\n"), true); + renderedIn = true; } else if (st.renderIn && st.renderIn.type === "action" && st.renderIn.ask) { // fetch `ask` mode: a clean In — the URL, the FULL question, and who answered it + the tokens spent // (a static export can't hover the raw toggle, so it shows the distilled meta inline; render-in-both). diff --git a/src/sidebar/settings/settings.tsx b/src/sidebar/settings/settings.tsx index 434828306..423a5d0f9 100644 --- a/src/sidebar/settings/settings.tsx +++ b/src/sidebar/settings/settings.tsx @@ -1134,27 +1134,31 @@ function SelfApprovalList() { // --- the policy page: every policy, one line each, editable and deletable (docs/dev/policies.md) --- /** A stored policy as the worker's `POLICIES` answer carries it (`StoredPolicy`, src/sw/sw-policies.ts; worker code, so not imported here). */ -interface PolicyRecord { id: string; scope: "global" | "run"; consumer: "fetch" | "sh" | "act" | "setting"; effect: "allow" | "deny" | "ask"; source: string; label: string; origin: "person" | "card" | "proposed"; created: number } +interface PolicyRecord { id: string; scope: "global" | "run"; consumer: "fetch" | "sh" | "act" | "setting" | "files"; effect: "allow" | "deny" | "ask" | "hide" | "show"; source: string; label: string; origin: "person" | "card" | "proposed"; created: number } /** What the worker's `POLICIES` answers (`policyView`, src/sw/sw-policies.ts). */ interface PolicyView { global: PolicyRecord[]; runs: { hash: string; policies: PolicyRecord[] }[]; builtin: { label: string; source: string }; broken: Record } /** The effect a selector's value names; anything else is `allow`, the policy page's default. */ -const policyEffectOf = (v: string): PolicyRecord["effect"] => (v === "deny" || v === "ask" ? v : "allow"); +const policyEffectOf = (v: string): "allow" | "deny" | "ask" => (v === "deny" || v === "ask" ? v : "allow"); /** The fields an Edit may change. */ type PolicyPatch = { effect?: "allow" | "deny" | "ask"; label?: string; source?: string }; +/** A `files` rule's effect, as the page writes it. */ +type HideRuleEffect = "hide" | "show"; /** The storage keys the policy store lives under, re-read on change. Defined as GLOBAL_POLICIES_KEY, RUN_POLICIES_KEY and ARCHIVED_POLICIES_KEY in src/sw/sw-policies.ts (worker code, not imported into this bundle). */ const POLICY_STORAGE_KEYS = ["ml_policies_global", "ml_policies_run", "ml_policies_archived"]; /** * Ask the worker for the policies (`POLICIES`), applying an add, edit or remove first when one is given. * @param payload `{}` to read, or `{ op, ... }` to change and read - * @returns the view after, or `{ error }` when the worker refused, or null when it could not be asked + * @returns the view after, or `{ error }` when the worker refused (with `exposes`, the ids a widening hiding rule's removal + * would let decide, when it asks to be confirmed), or null when it could not be asked */ -function askPolicies(payload: Record): Promise<{ view?: PolicyView; error?: string } | null> { +function askPolicies(payload: Record): Promise<{ view?: PolicyView; error?: string; exposes?: string[] } | null> { return new Promise((resolve) => { try { - chrome.runtime.sendMessage({ type: "POLICIES", payload }, (res: { data?: PolicyView; error?: string } | undefined) => { + chrome.runtime.sendMessage({ type: "POLICIES", payload }, (res: { data?: PolicyView & { exposes?: string[] }; error?: string } | undefined) => { void chrome.runtime.lastError; - if (res?.data) resolve({ view: { global: res.data.global ?? [], runs: res.data.runs ?? [], builtin: res.data.builtin, broken: res.data.broken ?? {} } }); + if (res?.error) resolve({ error: res.error, ...(Array.isArray(res.data?.exposes) ? { exposes: res.data.exposes } : {}) }); + else if (res?.data) resolve({ view: { global: res.data.global ?? [], runs: res.data.runs ?? [], builtin: res.data.builtin, broken: res.data.broken ?? {} } }); else resolve(res?.error ? { error: res.error } : null); }); } catch { resolve(null); } @@ -1187,10 +1191,11 @@ function usePolicies(): [PolicyView | null, (v: PolicyView) => void] { */ export function PolicyRow({ policy, broken, onEdit, onRemove }: { policy: PolicyRecord; broken?: string; onEdit: (patch: PolicyPatch) => void; onRemove: () => void }) { const [editing, setEditing] = useState(false); - const [effect, setEffect] = useState(policy.effect); + // A `files` row is drawn by FilesRuleRow, so the effect here is always one of the three. + const [effect, setEffect] = useState(policyEffectOf(policy.effect)); const [label, setLabel] = useState(policy.label); const [source, setSource] = useState(policy.source); - const open = (): void => { setEffect(policy.effect); setLabel(policy.label); setSource(policy.source); setEditing(true); }; + const open = (): void => { setEffect(policyEffectOf(policy.effect)); setLabel(policy.label); setSource(policy.source); setEditing(true); }; // A broken-policy card's "Edit policy" lands here with the editor already open. useEffect(() => { if (policyToEdit.value === policy.id) { policyToEdit.value = undefined; open(); } }, [policyToEdit.value, policy.id]); const save = (): void => { @@ -1232,6 +1237,37 @@ export function PolicyRow({ policy, broken, onEdit, onRemove }: { policy: Policy ); } +/** + * One hiding rule for every session on the policy page: its effect and pattern, who added it, and a remove. It is not + * edited: a changed pattern is a removal and an add. Removing a `hide` widens, so the first press may come back asking to + * confirm, naming the rules that would then decide. + * @group settings + * @gallery hide {"policy": {"id": "f1a2b3c", "scope": "global", "consumer": "files", "effect": "hide", "source": "/Users/me/proj/secrets/key-*", "label": "hide /Users/me/proj/secrets/key-*", "origin": "person", "created": 1760000000000}} + * @gallery confirm {"policy": {"id": "f1a2b3c", "scope": "global", "consumer": "files", "effect": "hide", "source": "/Users/me/proj/.env.local", "label": "hide /Users/me/proj/.env.local", "origin": "proposed", "created": 1760000000000}, "exposes": ["show /Users/me/proj/.env.*"]} + */ +export function FilesRuleRow({ policy, exposes, onRemove, onCancel }: { policy: PolicyRecord; exposes?: string[]; onRemove: (confirm: boolean) => void; onCancel?: () => void }) { + return ( +
+
+ {policy.effect === "hide" ? "hides" : "shows"} + {policy.source} + files + {policy.origin === "proposed" ? proposed by the model : null} + +
+ {exposes + ?
+
{exposes.length ? `Removing it lets these decide instead: ${exposes.join("; ")}.` : "Removing it lets the files it hides be read."} Remove it?
+
+ + +
+
+ : null} +
+ ); +} + /** The source a new global policy starts from: the shape every policy has, naming one host. */ const POLICY_STARTER = '(c) => c.kind === "fetch" && c.host === "example.com"'; @@ -1247,17 +1283,34 @@ function Policies() { const [consumer, setConsumer] = useState<"fetch" | "sh" | "setting">("fetch"); const [label, setLabel] = useState(""); const [source, setSource] = useState(POLICY_STARTER); + const [hideEffect, setHideEffect] = useState("hide"); + const [pattern, setPattern] = useState(""); + // The hiding rule whose removal is waiting to be confirmed, and what it would let decide. + const [confirming, setConfirming] = useState<{ id: string; exposes: string[] } | null>(null); if (!view) return null; const send = (payload: Record): Promise => askPolicies(payload).then((r) => { if (r?.view) { setView(r.view); setErr(""); return true; } setErr(r?.error ?? "The extension could not be reached."); return false; }); - const rows = (list: PolicyRecord[]) => list.map((p) => ( + const removeFiles = (id: string, confirm: boolean): void => { + void askPolicies({ op: "removeFiles", id, confirm }).then((r) => { + if (r?.view) { setView(r.view); setErr(""); setConfirming(null); return; } + if (r?.error === "confirm") { setConfirming({ id, exposes: (r.exposes ?? []).map((x) => view.global.find((p) => p.id === x)?.label ?? x) }); setErr(""); return; } + setErr(r?.error ?? "The extension could not be reached."); + }); + }; + const rows = (list: PolicyRecord[]) => list.map((p) => p.consumer === "files" ? ( + removeFiles(p.id, confirm)} onCancel={() => setConfirming(null)} /> + ) : ( { void send({ op: "edit", id: p.id, ...patch }); }} onRemove={() => { void send({ op: "remove", id: p.id }); }} /> )); + const addFiles = (): void => { + void send({ op: "addFiles", effect: hideEffect, source: pattern.trim() }).then((ok) => { if (ok) setPattern(""); }); + }; const add = (): void => { void send({ op: "add", consumer, effect, label: label.trim(), source }).then((ok) => { if (ok) { setLabel(""); setSource(POLICY_STARTER); } }); }; @@ -1282,6 +1335,15 @@ function Policies() {