diff --git a/.github/fork-seams.json b/.github/fork-seams.json index 6ff54d922030d..8165f0f1932e2 100644 --- a/.github/fork-seams.json +++ b/.github/fork-seams.json @@ -601,15 +601,11 @@ }, "apps/server/src/provider/Drivers/ClaudeSkills.ts": { "why": "#978 (model policy): the hook that checks Claude's Skill tool reads a skill's frontmatter with the skill list's own parser, so the repair of an unquoted \": \" in a value (which Claude Code accepts) is one source. parseSkillFrontmatter is exported, and its parsed result also carries the whole frontmatter record (fork/claudeAgentModelPolicy.ts reads context, model and effort from it). Tested in apps/server/src/fork/claudeAgentModelPolicy.test.ts.", - "added": [], - "announced": { - "since": "2026-11-22", - "added": [ - "readonly record: Record; // Fork: for the model policy's skill check", - "record, // Fork: the model policy reads context, model and effort from it", - "export { parseSkillFrontmatter }; // Fork: one frontmatter read for skills and the model policy" - ] - } + "added": [ + "readonly record: Record; // Fork: for the model policy's skill check", + "record, // Fork: the model policy reads context, model and effort from it", + "export { parseSkillFrontmatter }; // Fork: one frontmatter read for skills and the model policy" + ] } }, "//pending": "Upstream files whose fork lines predate counting every upstream file, each with its ceiling: the most fork lines it may hold against upstream (counted from upstream, as fork-follow runs the check). To move into fork files or pin as seams; lower a ceiling when lines move out and take a file off when none are left. A pull request may change them but not grow them.", diff --git a/FORK_CHANGES.md b/FORK_CHANGES.md index a03e5ff548000..640d186148ffe 100644 --- a/FORK_CHANGES.md +++ b/FORK_CHANGES.md @@ -12,45 +12,45 @@ setting is missing here or a setting named here does not exist. ## In T3 Code itself -| Change | Why | Setting | Default | PR | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| The server, the CLI and the desktop app look for updates in this fork's releases, not upstream's. | A fork build must never "update" to an upstream build and lose the fork's changes. | none | always | [#1](https://github.com/scuttletoby/t3code/pull/1) | -| A server installed as a boot service can update itself once no thread is working, after an optional "is it quiet?" command agrees. | Updates without someone watching, and without cutting off running work. | `server.automaticUpdates`, `server.automaticUpdatesQuietCommand` | off | [#5](https://github.com/scuttletoby/t3code/pull/5) | -| Every fork setting has a pinned default, and lives in the fork's own file (`forkSettings.ts`). | An upstream sync can never switch a fork feature on, and a new setting touches no upstream file. | none | always | [#171](https://github.com/scuttletoby/t3code/pull/171), [#185](https://github.com/scuttletoby/t3code/pull/185) | -| The server keeps a history of each provider account's usage-limit readings. | Pacing needs to know how fast a limit is being used, not only where it stands. | none | always (read only) | [#24](https://github.com/scuttletoby/t3code/pull/24) | -| The server reads usage limits every 10 minutes while no app is open. | Pacing has current numbers on a machine nobody is looking at. | `server.headlessUsageRefreshInterval` | on (10 minutes); read only | [#42](https://github.com/scuttletoby/t3code/pull/42) | -| Usage pacing: a reserve of each limit window kept free for the person, and an even pace for agents. | Agents should not use up a subscription before its owner needs it. | `server.usagePacing` | off | [#52](https://github.com/scuttletoby/t3code/pull/52) | -| The pacing gate on `delegate_task`: advise only, or move, lower the effort of, or hold a task on an account that is ahead of pace. | Delegated work follows the pace without the agent having to check. | `server.usagePacingGate`, `server.usagePacingLowerEffort` | off | [#73](https://github.com/scuttletoby/t3code/pull/73) | -| Agent slots: `delegate_task` is refused above a number of running agents per machine or account, or below a memory floor. | Too many agents at once can overload a small machine. | `server.agentSlots` | on: capacity rule decides | [#84](https://github.com/scuttletoby/t3code/pull/84), [#89](https://github.com/scuttletoby/t3code/pull/89) | -| Machine facts: `t3_environment_read` also returns `hostResources` (CPU, cores, memory; the field of upstream PR #34293, closed there unmerged) and `placement` (labels, available and reason, running agents, slots free, memory floor, facts time), for this machine and a linked one. | An agent choosing where to run work can see which machine has room without asking the person. | none | always | [#820](https://github.com/scuttletoby/t3code/pull/820) | -| Waits: agents can wait for a pull request, a file, a system unit, a named check command or a free agent slot (`wait_for`, `wait_list`, `wait_cancel`), and are woken when it happens. | An agent no longer polls or sleeps while it waits. | `server.waitFor`, `server.waitChecks`, `projectOverride.waitChecks` | off | [#84](https://github.com/scuttletoby/t3code/pull/84), [#90](https://github.com/scuttletoby/t3code/pull/90), [#91](https://github.com/scuttletoby/t3code/pull/91), [#103](https://github.com/scuttletoby/t3code/pull/103), [#106](https://github.com/scuttletoby/t3code/pull/106), [#109](https://github.com/scuttletoby/t3code/pull/109), [#110](https://github.com/scuttletoby/t3code/pull/110), [#116](https://github.com/scuttletoby/t3code/pull/116), [#119](https://github.com/scuttletoby/t3code/pull/119) | -| Delegated results: `task_list` lists a thread's delegated tasks whose result it has not read, and its running children per place from live status; a parent whose finished child's result never arrived gets one reminder. | A finished child's result can no longer sit unseen. | `server.waitFor` (the reminder) | off; `task_list` always (read only) | [#622](https://github.com/scuttletoby/t3code/pull/622), [#641](https://github.com/scuttletoby/t3code/pull/641) | -| The Settings page **Fork** (`/settings/fork`): every fork setting in one place, with one line per feature at the top saying whether it is on: waits, wait checks, agent slots, usage pacing (per account by name), model policy, review rules, automatic updates, handoff, playtest and MCP profiles. | Change every fork setting without editing a file. | `server.waitFor`, `server.waitChecks`, `server.agentSlots`, `server.usagePacing`, `server.usagePacingGate`, `server.usagePacingLowerEffort`, `server.reviewRules`, `server.modelPolicy`, `server.automaticUpdates`, `server.automaticUpdatesQuietCommand`, `server.handoff`, `server.playtest`, `server.mcpProfiles`, `server.mcpProfile`, `server.mcpSubagentProfile`, `server.mcpThreadProfiles` | off | [#104](https://github.com/scuttletoby/t3code/pull/104), [#543](https://github.com/scuttletoby/t3code/pull/543), [#544](https://github.com/scuttletoby/t3code/pull/544) | -| The fork's checks on `delegate_task` (pacing, slots) sit behind one fork module. | Fewer fork lines in upstream's code, so syncs conflict less. No change in behaviour. | none | always | [#174](https://github.com/scuttletoby/t3code/pull/174) | -| The fork's service layers in the server are wired from one fork file (`apps/server/src/fork/forkLayers.ts`). | Fewer fork lines in upstream's code, so syncs conflict less. No change in behaviour. | none | always | [#384](https://github.com/scuttletoby/t3code/pull/384) | -| A pure capacity rule for "dynamic slots" (one budget per machine), with shared test cases. Not wired into anything yet. | A later step replaces fixed agent counts with what the machine can take. | none | not used | [#203](https://github.com/scuttletoby/t3code/pull/203) | -| File links in chat open in the files viewer, full size, or in an editor on a remote machine, and can be downloaded, from their menu. | File links were only copyable on remote machines and had no menu on touch screens. | none | always | [#17](https://github.com/scuttletoby/t3code/pull/17) | -| A hidden read-only command, `t3 __fork-report --base-dir `, prints what a T3 home holds and which fork features are on, and where. | The go-live kit checks a build and a home before switching, without writing anything. | none | only when run | [#172](https://github.com/scuttletoby/t3code/pull/172), [#184](https://github.com/scuttletoby/t3code/pull/184) | -| A local, read-only "is T3 busy?" answer: `GET /api/fork/activity` on loopback, and `t3 __fork-report --base-dir --activity`, which asks it and exits 0 only when nothing is working. | A host quiet check reads T3's own turns and approvals instead of guessing from processes. | `server.activityProbe` | off | [#547](https://github.com/scuttletoby/t3code/pull/547) | -| `t3 serve --hold-work` starts a server on a copy of a T3 home with all agent work and T3 Connect held. | Look at a new build's threads and migrations on a copy before it replaces a running T3. | none | only with the flag | [#175](https://github.com/scuttletoby/t3code/pull/175) | -| Docs: one machine for new work through upstream's load-balancing weights; settings saved with an early draft's client setting for it still load. | Upstream already has the feature, so the fork's own setting was removed. | none | - | [#25](https://github.com/scuttletoby/t3code/pull/25) | -| MCP profiles: named profiles (which outside MCP servers and T3 tool groups a thread gets), a default, a sub-agent rule, a pick per thread and the rules that pick one. Claude and Codex apply the outside servers (Codex per thread, as `mcp_servers..enabled = false`) and refuse a turn when they cannot; any other provider refuses a turn whose profile leaves one out. T3's MCP server applies the T3 tool groups on every provider, fixed as each turn starts: a tool outside them is hidden and refused. A delegated task carries its parent's profile; a narrower one goes only to a Claude instance on a machine that applies it. Settings → Fork edits profiles, the default, the sub-agent rule (also per project) and each thread's pick. | Fewer tools per thread saves tokens and keeps agents from tools they should not use. | `server.mcpProfiles`, `server.mcpProfile`, `server.mcpSubagentProfile`, `server.mcpThreadProfiles`, `server.mcpCarriedProfiles`, `projectOverride.mcpProfile`, `projectOverride.mcpSubagentProfile` | off | [#227](https://github.com/scuttletoby/t3code/pull/227), [#528](https://github.com/scuttletoby/t3code/pull/528), [#640](https://github.com/scuttletoby/t3code/issues/640), [#672](https://github.com/scuttletoby/t3code/issues/672) | -| Playtest mode, part 1: settings for a project's playtest adapter (claim, renew, push and release steps only the person sets) and the contract those steps follow. Nothing starts a session yet. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#260](https://github.com/scuttletoby/t3code/pull/260) | -| Playtest mode, part 2: the session store and service: start (claim), rounds of push steps, end (release), kept across restarts. A session keeps the steps it started with. No tool calls it yet. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#261](https://github.com/scuttletoby/t3code/pull/261) | -| Playtest mode, part 3: the worker renews claims, ends idle, too-long and gone-thread sessions, finishes what a restart cut, and tells the thread once when T3 ended a session. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#262](https://github.com/scuttletoby/t3code/pull/262) | -| Playtest mode, part 4: the agent's `playtest` tool (start, push, status, end) on its own thread's session, in its own `playtest` tool group. The thread comes from the credential; the tool takes no setting; start and push need a full-access thread. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#809](https://github.com/scuttletoby/t3code/pull/809) | -| Handoff instead of compaction, part 1: the setting and the pure "should this thread hand off now?" decision. Nothing acts on it yet. | Long threads keep their children, PRs and waits instead of compacting. | `server.handoff`, `projectOverride.handoff` | off | [#282](https://github.com/scuttletoby/t3code/pull/282) | -| Review rules, part 1: the setting for how this machine runs a review lens (runner, state question), off by default; `{"preset": "recommended"}` turns the fork's defaults on. A bad hand edit reads as off and is kept. Nothing reads it yet. | The repo says what a pull request needs and CI enforces it; the machine says how reviews run. | `server.reviewRules`, `projectOverride.reviewRules` | off | [#291](https://github.com/scuttletoby/t3code/pull/291) | -| An interval setting the settings file cannot hold (negative, not finite, too large) is refused when saved; one already in the file reads as its default instead of resetting every setting. A test finds every interval setting from the schema. | A `1e400` saved as `null` made the next start reject the whole settings file. | none | always | [#323](https://github.com/scuttletoby/t3code/pull/323) | -| Handoff instead of compaction, part 2: the handoff service hands a big or idle thread to a fresh session in the same thread, with T3's state and the recent conversation, only while the thread is quiet and still at the run that triggered it. | Long threads keep their children, PRs and waits instead of compacting. | `server.handoff`, `projectOverride.handoff` | off | [#320](https://github.com/scuttletoby/t3code/pull/320) | -| A task delegated to a linked environment is still followed if the delegating call is cut off, and still delivers its reply when that environment runs another T3 version. | Its parent was never told: the task stayed running here and its result never arrived. | none | always | [#412](https://github.com/scuttletoby/t3code/pull/412), [#540](https://github.com/scuttletoby/t3code/pull/540) | -| A task delegated to a linked environment reports what its thread there waits on (a question, an approval, a secret by label and reason only) in `task_status` and `delegate_task`, and wakes its parent once per prompt; a machine that cannot be asked reads as unknown. | Upstream always reported it as not waiting, so its parent never learned it was blocked. | none | always | [#815](https://github.com/scuttletoby/t3code/pull/815) | -| Run records: one line per agent run that ends (model, effort, role, kind, estimate, times, end status, provider-reported tokens) in `/run-records/runs.jsonl`, append-only, and a weekly summary command. | Later choices of model, effort and task size need what earlier runs cost and took. | none | always (writes only its own files) | [#588](https://github.com/scuttletoby/t3code/pull/588) | -| Model policy: the setting for which models (and efforts) agents may pick, per provider driver: off, advise or enforce, and the allowed rows. The server checks an agent's pick (`delegate_task`, `create_threads`, `t3_thread_launch`, `t3_thread_configure`, here, and both before and after it goes to linked machines): a model in no row, a call that names no model, or an effort off its row is refused in enforce, only noted in advise. A person's own pick is never refused; Settings marks one outside the rows. A bad hand edit, or a settings file that does not parse, refuses every agent pick (a warning if the value says advise). Settings offers the fork's start rows (Opus 5.5 and Fable 5.2) while none are saved. While it is on, a child whose call names its model keeps only the options it names. | Agents should use the models the person chose for each kind of work. | `server.modelPolicy` | off | [#268](https://github.com/scuttletoby/t3code/pull/268), [#731](https://github.com/scuttletoby/t3code/issues/731) | -| Placement, part 1: the settings only. `placement` (off, advise or enforce; this machine's labels, an optional facts command, label groups that must never meet on one machine, and a weight per linked machine) and `placementNeeds` (labels a project's work needs). Person-only; a bad `placement` reads as off and a bad `placementNeeds` fits no machine, each kept as written. Nothing reads them yet. | Delegated work should go to a machine that has what it needs, and never where it must not run. | `server.placement`, `server.placementNeeds`, `projectOverride.placementNeeds` | off | [#134](https://github.com/scuttletoby/t3code/issues/134) | -| Calm sidebar, part 1: the settings. `threadRoles` names the assistant thread and one orchestrator per project; the server refuses a role for a thread that is missing, deleted, a sub-agent, a side chat, delegated from a linked machine or in another project. `calmSidebarEnabled` is the per-device switch. Nothing shows them yet. | A short sidebar: the threads that matter on top, the rest folded. | `server.threadRoles`, `client.calmSidebarEnabled` | off | [#928](https://github.com/scuttletoby/t3code/pull/928) | -| Assistant setup: the switch `assistant.enabled` (off) offers **Make assistant** in Settings, which makes a thread in the Scratch project, names it `threadRoles.assistant` and picks for it the new built-in MCP profile `assistant` (no outside servers, no shell, file or web tools; T3 tool groups `orchestration`, `threads` and `projects`). Claude only. | One thread you talk to across projects, with only T3's tools. | `server.assistant`, `server.mcpProfiles` | off | [#953](https://github.com/scuttletoby/t3code/pull/953) | -| Owner questions, part 1: the rule (label `status:needs-owner-decision`, titles starting "Owner question" or " Q:", answered by a comment starting "Owner decision:" or "Owner decision (") is one fork file, `packages/contracts/src/forkOwnerQuestions.ts`. A fork page, **Waiting on you** (`/owner-questions`), lists the open owner questions of every project on every connected server, read-only, through upstream's issue listing, plus a listing by the label so a labelled question is never cut; it names any repository read only in part and says nothing is waiting only when every server answered in full. No menu leads to it yet: the Issues page swaps to it in part 2. | Owner questions spread over several repositories, in one place inside T3. | none | always | [#828](https://github.com/scuttletoby/t3code/issues/828) | +| Change | Why | Setting | Default | PR | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| The server, the CLI and the desktop app look for updates in this fork's releases, not upstream's. | A fork build must never "update" to an upstream build and lose the fork's changes. | none | always | [#1](https://github.com/scuttletoby/t3code/pull/1) | +| A server installed as a boot service can update itself once no thread is working, after an optional "is it quiet?" command agrees. | Updates without someone watching, and without cutting off running work. | `server.automaticUpdates`, `server.automaticUpdatesQuietCommand` | off | [#5](https://github.com/scuttletoby/t3code/pull/5) | +| Every fork setting has a pinned default, and lives in the fork's own file (`forkSettings.ts`). | An upstream sync can never switch a fork feature on, and a new setting touches no upstream file. | none | always | [#171](https://github.com/scuttletoby/t3code/pull/171), [#185](https://github.com/scuttletoby/t3code/pull/185) | +| The server keeps a history of each provider account's usage-limit readings. | Pacing needs to know how fast a limit is being used, not only where it stands. | none | always (read only) | [#24](https://github.com/scuttletoby/t3code/pull/24) | +| The server reads usage limits every 10 minutes while no app is open. | Pacing has current numbers on a machine nobody is looking at. | `server.headlessUsageRefreshInterval` | on (10 minutes); read only | [#42](https://github.com/scuttletoby/t3code/pull/42) | +| Usage pacing: a reserve of each limit window kept free for the person, and an even pace for agents. | Agents should not use up a subscription before its owner needs it. | `server.usagePacing` | off | [#52](https://github.com/scuttletoby/t3code/pull/52) | +| The pacing gate on `delegate_task`: advise only, or move, lower the effort of, or hold a task on an account that is ahead of pace. | Delegated work follows the pace without the agent having to check. | `server.usagePacingGate`, `server.usagePacingLowerEffort` | off | [#73](https://github.com/scuttletoby/t3code/pull/73) | +| Agent slots: `delegate_task` is refused above a number of running agents per machine or account, or below a memory floor. | Too many agents at once can overload a small machine. | `server.agentSlots` | on: capacity rule decides | [#84](https://github.com/scuttletoby/t3code/pull/84), [#89](https://github.com/scuttletoby/t3code/pull/89) | +| Machine facts: `t3_environment_read` also returns `hostResources` (CPU, cores, memory; the field of upstream PR #34293, closed there unmerged) and `placement` (labels, available and reason, running agents, slots free, memory floor, facts time), for this machine and a linked one. | An agent choosing where to run work can see which machine has room without asking the person. | none | always | [#820](https://github.com/scuttletoby/t3code/pull/820) | +| Waits: agents can wait for a pull request, a file, a system unit, a named check command or a free agent slot (`wait_for`, `wait_list`, `wait_cancel`), and are woken when it happens. | An agent no longer polls or sleeps while it waits. | `server.waitFor`, `server.waitChecks`, `projectOverride.waitChecks` | off | [#84](https://github.com/scuttletoby/t3code/pull/84), [#90](https://github.com/scuttletoby/t3code/pull/90), [#91](https://github.com/scuttletoby/t3code/pull/91), [#103](https://github.com/scuttletoby/t3code/pull/103), [#106](https://github.com/scuttletoby/t3code/pull/106), [#109](https://github.com/scuttletoby/t3code/pull/109), [#110](https://github.com/scuttletoby/t3code/pull/110), [#116](https://github.com/scuttletoby/t3code/pull/116), [#119](https://github.com/scuttletoby/t3code/pull/119) | +| Delegated results: `task_list` lists a thread's delegated tasks whose result it has not read, and its running children per place from live status; a parent whose finished child's result never arrived gets one reminder. | A finished child's result can no longer sit unseen. | `server.waitFor` (the reminder) | off; `task_list` always (read only) | [#622](https://github.com/scuttletoby/t3code/pull/622), [#641](https://github.com/scuttletoby/t3code/pull/641) | +| The Settings page **Fork** (`/settings/fork`): every fork setting in one place, with one line per feature at the top saying whether it is on: waits, wait checks, agent slots, usage pacing (per account by name), model policy, review rules, automatic updates, handoff, playtest and MCP profiles. | Change every fork setting without editing a file. | `server.waitFor`, `server.waitChecks`, `server.agentSlots`, `server.usagePacing`, `server.usagePacingGate`, `server.usagePacingLowerEffort`, `server.reviewRules`, `server.modelPolicy`, `server.automaticUpdates`, `server.automaticUpdatesQuietCommand`, `server.handoff`, `server.playtest`, `server.mcpProfiles`, `server.mcpProfile`, `server.mcpSubagentProfile`, `server.mcpThreadProfiles` | off | [#104](https://github.com/scuttletoby/t3code/pull/104), [#543](https://github.com/scuttletoby/t3code/pull/543), [#544](https://github.com/scuttletoby/t3code/pull/544) | +| The fork's checks on `delegate_task` (pacing, slots) sit behind one fork module. | Fewer fork lines in upstream's code, so syncs conflict less. No change in behaviour. | none | always | [#174](https://github.com/scuttletoby/t3code/pull/174) | +| The fork's service layers in the server are wired from one fork file (`apps/server/src/fork/forkLayers.ts`). | Fewer fork lines in upstream's code, so syncs conflict less. No change in behaviour. | none | always | [#384](https://github.com/scuttletoby/t3code/pull/384) | +| A pure capacity rule for "dynamic slots" (one budget per machine), with shared test cases. Not wired into anything yet. | A later step replaces fixed agent counts with what the machine can take. | none | not used | [#203](https://github.com/scuttletoby/t3code/pull/203) | +| File links in chat open in the files viewer, full size, or in an editor on a remote machine, and can be downloaded, from their menu. | File links were only copyable on remote machines and had no menu on touch screens. | none | always | [#17](https://github.com/scuttletoby/t3code/pull/17) | +| A hidden read-only command, `t3 __fork-report --base-dir `, prints what a T3 home holds and which fork features are on, and where. | The go-live kit checks a build and a home before switching, without writing anything. | none | only when run | [#172](https://github.com/scuttletoby/t3code/pull/172), [#184](https://github.com/scuttletoby/t3code/pull/184) | +| A local, read-only "is T3 busy?" answer: `GET /api/fork/activity` on loopback, and `t3 __fork-report --base-dir --activity`, which asks it and exits 0 only when nothing is working. | A host quiet check reads T3's own turns and approvals instead of guessing from processes. | `server.activityProbe` | off | [#547](https://github.com/scuttletoby/t3code/pull/547) | +| `t3 serve --hold-work` starts a server on a copy of a T3 home with all agent work and T3 Connect held. | Look at a new build's threads and migrations on a copy before it replaces a running T3. | none | only with the flag | [#175](https://github.com/scuttletoby/t3code/pull/175) | +| Docs: one machine for new work through upstream's load-balancing weights; settings saved with an early draft's client setting for it still load. | Upstream already has the feature, so the fork's own setting was removed. | none | - | [#25](https://github.com/scuttletoby/t3code/pull/25) | +| MCP profiles: named profiles (which outside MCP servers and T3 tool groups a thread gets), a default, a sub-agent rule, a pick per thread and the rules that pick one. Claude and Codex apply the outside servers (Codex per thread, as `mcp_servers..enabled = false`) and refuse a turn when they cannot; any other provider refuses a turn whose profile leaves one out. T3's MCP server applies the T3 tool groups on every provider, fixed as each turn starts: a tool outside them is hidden and refused. A delegated task carries its parent's profile; a narrower one goes only to a Claude instance on a machine that applies it. Settings → Fork edits profiles, the default, the sub-agent rule (also per project) and each thread's pick. | Fewer tools per thread saves tokens and keeps agents from tools they should not use. | `server.mcpProfiles`, `server.mcpProfile`, `server.mcpSubagentProfile`, `server.mcpThreadProfiles`, `server.mcpCarriedProfiles`, `projectOverride.mcpProfile`, `projectOverride.mcpSubagentProfile` | off | [#227](https://github.com/scuttletoby/t3code/pull/227), [#528](https://github.com/scuttletoby/t3code/pull/528), [#640](https://github.com/scuttletoby/t3code/issues/640), [#672](https://github.com/scuttletoby/t3code/issues/672) | +| Playtest mode, part 1: settings for a project's playtest adapter (claim, renew, push and release steps only the person sets) and the contract those steps follow. Nothing starts a session yet. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#260](https://github.com/scuttletoby/t3code/pull/260) | +| Playtest mode, part 2: the session store and service: start (claim), rounds of push steps, end (release), kept across restarts. A session keeps the steps it started with. No tool calls it yet. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#261](https://github.com/scuttletoby/t3code/pull/261) | +| Playtest mode, part 3: the worker renews claims, ends idle, too-long and gone-thread sessions, finishes what a restart cut, and tells the thread once when T3 ended a session. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#262](https://github.com/scuttletoby/t3code/pull/262) | +| Playtest mode, part 4: the agent's `playtest` tool (start, push, status, end) on its own thread's session, in its own `playtest` tool group. The thread comes from the credential; the tool takes no setting; start and push need a full-access thread. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#809](https://github.com/scuttletoby/t3code/pull/809) | +| Handoff instead of compaction, part 1: the setting and the pure "should this thread hand off now?" decision. Nothing acts on it yet. | Long threads keep their children, PRs and waits instead of compacting. | `server.handoff`, `projectOverride.handoff` | off | [#282](https://github.com/scuttletoby/t3code/pull/282) | +| Review rules, part 1: the setting for how this machine runs a review lens (runner, state question), off by default; `{"preset": "recommended"}` turns the fork's defaults on. A bad hand edit reads as off and is kept. Nothing reads it yet. | The repo says what a pull request needs and CI enforces it; the machine says how reviews run. | `server.reviewRules`, `projectOverride.reviewRules` | off | [#291](https://github.com/scuttletoby/t3code/pull/291) | +| An interval setting the settings file cannot hold (negative, not finite, too large) is refused when saved; one already in the file reads as its default instead of resetting every setting. A test finds every interval setting from the schema. | A `1e400` saved as `null` made the next start reject the whole settings file. | none | always | [#323](https://github.com/scuttletoby/t3code/pull/323) | +| Handoff instead of compaction, part 2: the handoff service hands a big or idle thread to a fresh session in the same thread, with T3's state and the recent conversation, only while the thread is quiet and still at the run that triggered it. | Long threads keep their children, PRs and waits instead of compacting. | `server.handoff`, `projectOverride.handoff` | off | [#320](https://github.com/scuttletoby/t3code/pull/320) | +| A task delegated to a linked environment is still followed if the delegating call is cut off, and still delivers its reply when that environment runs another T3 version. | Its parent was never told: the task stayed running here and its result never arrived. | none | always | [#412](https://github.com/scuttletoby/t3code/pull/412), [#540](https://github.com/scuttletoby/t3code/pull/540) | +| A task delegated to a linked environment reports what its thread there waits on (a question, an approval, a secret by label and reason only) in `task_status` and `delegate_task`, and wakes its parent once per prompt; a machine that cannot be asked reads as unknown. | Upstream always reported it as not waiting, so its parent never learned it was blocked. | none | always | [#815](https://github.com/scuttletoby/t3code/pull/815) | +| Run records: one line per agent run that ends (model, effort, role, kind, estimate, times, end status, provider-reported tokens) in `/run-records/runs.jsonl`, append-only, and a weekly summary command. | Later choices of model, effort and task size need what earlier runs cost and took. | none | always (writes only its own files) | [#588](https://github.com/scuttletoby/t3code/pull/588) | +| Model policy: the setting for which models (and efforts) agents may pick, per provider driver: off, advise or enforce, and the allowed rows. The server checks an agent's pick (`delegate_task`, `create_threads`, `t3_thread_launch`, `t3_thread_configure`, here, before and after it goes to linked machines, Claude's Agent tool, and a Claude skill that starts a sub-agent or names a model): a model in no row, a call that names no model, or an effort off its row is refused in enforce, only noted in advise. A person's own pick is never refused; Settings marks one outside the rows. A bad hand edit or a settings file that does not parse, refuses every agent pick (a warning in advise). Settings offers the fork's start rows (Opus 5.5 and Fable 5.2) while none are saved. While it is on, a child whose call names its model keeps only the options it names. | Agents should use the models the person chose for each kind of work. | `server.modelPolicy` | off | [#268](https://github.com/scuttletoby/t3code/pull/268), [#731](https://github.com/scuttletoby/t3code/issues/731), [#128](https://github.com/scuttletoby/t3code/issues/128) | +| Placement, part 1: the settings only. `placement` (off, advise or enforce; this machine's labels, an optional facts command, label groups that must never meet on one machine, and a weight per linked machine) and `placementNeeds` (labels a project's work needs). Person-only; a bad `placement` reads as off and a bad `placementNeeds` fits no machine, each kept as written. Nothing reads them yet. | Delegated work should go to a machine that has what it needs, and never where it must not run. | `server.placement`, `server.placementNeeds`, `projectOverride.placementNeeds` | off | [#134](https://github.com/scuttletoby/t3code/issues/134) | +| Calm sidebar, part 1: the settings. `threadRoles` names the assistant thread and one orchestrator per project; the server refuses a role for a thread that is missing, deleted, a sub-agent, a side chat, delegated from a linked machine or in another project. `calmSidebarEnabled` is the per-device switch. Nothing shows them yet. | A short sidebar: the threads that matter on top, the rest folded. | `server.threadRoles`, `client.calmSidebarEnabled` | off | [#928](https://github.com/scuttletoby/t3code/pull/928) | +| Assistant setup: the switch `assistant.enabled` (off) offers **Make assistant** in Settings, which makes a thread in the Scratch project, names it `threadRoles.assistant` and picks for it the new built-in MCP profile `assistant` (no outside servers, no shell, file or web tools; T3 tool groups `orchestration`, `threads` and `projects`). Claude only. | One thread you talk to across projects, with only T3's tools. | `server.assistant`, `server.mcpProfiles` | off | [#953](https://github.com/scuttletoby/t3code/pull/953) | +| Owner questions, part 1: the rule (label `status:needs-owner-decision`, titles starting "Owner question" or " Q:", answered by a comment starting "Owner decision:" or "Owner decision (") is one fork file, `packages/contracts/src/forkOwnerQuestions.ts`. A fork page, **Waiting on you** (`/owner-questions`), lists the open owner questions of every project on every connected server, read-only, through upstream's issue listing, plus a listing by the label so a labelled question is never cut; it names any repository read only in part and says nothing is waiting only when every server answered in full. No menu leads to it yet: the Issues page swaps to it in part 2. | Owner questions spread over several repositories, in one place inside T3. | none | always | [#828](https://github.com/scuttletoby/t3code/issues/828) | ## Repository, CI and releases diff --git a/apps/server/src/fork/claudeAgentModelPolicy.test.ts b/apps/server/src/fork/claudeAgentModelPolicy.test.ts new file mode 100644 index 0000000000000..cb7f332093c78 --- /dev/null +++ b/apps/server/src/fork/claudeAgentModelPolicy.test.ts @@ -0,0 +1,427 @@ +/** + * Fork: the model policy's check of Claude's own Agent and Skill tools (claudeAgentModelPolicy.ts): + * each policy state, the alias read as the full id and a row naming the alias, a fork, a skill that + * runs in a sub-agent, and failing closed. The adapter test (claudeMcpProfile.adapter.test.ts) shows + * every Claude query carries the hook once. + */ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import type { HookInput } from "@anthropic-ai/claude-agent-sdk"; +import { assert, describe, it } from "@effect/vitest"; +import { + DEFAULT_SERVER_SETTINGS, + MODEL_POLICY_START_ROWS, + type ServerSettings, +} from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import { BUNDLED_CLAUDE_MODEL_CATALOG } from "../provider/ClaudeModelCatalog.ts"; +import * as ServerSettingsService from "../serverSettings.ts"; +import { + CLAUDE_AGENT_TOOLS, + claudeAgentCallPick, + claudeConfigDirOfTranscript, + makeClaudeAgentModelPolicyHook, +} from "./claudeAgentModelPolicy.ts"; + +type Policy = ServerSettings["modelPolicy"]; +const policy = (mode: string, allow: unknown = MODEL_POLICY_START_ROWS) => + ({ mode, allow }) as unknown as Policy; +const ENFORCE = policy("enforce"); +const ADVISE = policy("advise"); +const OFF = policy("off"); +/** Rows saved before the Agent tool was checked that name the alias, as Settings lets a person save. */ +const ALIAS_ROWS = [{ driver: "claudeAgent", model: "opus", efforts: ["high"] }]; + +/** Where the call runs: Claude's transcript (under its config folder) and the session's folder. */ +interface Place { + readonly transcript: string; + readonly cwd: string; +} +const NOWHERE: Place = { transcript: "/tmp/t.jsonl", cwd: "/workspace" }; + +const callInput = (toolInput: unknown, tool = "Agent", place = NOWHERE) => + ({ + hook_event_name: "PreToolUse", + tool_name: tool, + tool_input: toolInput, + tool_use_id: "toolu_agent", + session_id: "s", + transcript_path: place.transcript, + cwd: place.cwd, + }) as unknown as HookInput; + +type Settings = Policy | "no-settings" | "unreadable" | { readonly held: unknown }; + +/** Under these settings (`no-settings`: a host without them), with a file system. */ +const withSettings = + (modelPolicy: Settings) => + (effect: Effect.Effect) => + (modelPolicy === "no-settings" + ? effect + : modelPolicy === "unreadable" + ? Effect.provideService(effect, ServerSettingsService.ServerSettingsService, { + getSettings: Effect.die("settings read failed"), + } as never) + : "held" in modelPolicy + ? // As the server holds a policy from the file that does not parse. + Effect.provideService(effect, ServerSettingsService.ServerSettingsService, { + getSettings: Effect.succeed({ + ...DEFAULT_SERVER_SETTINGS, + modelPolicy: modelPolicy.held, + }), + } as never) + : Effect.provide(effect, ServerSettingsService.layerTest({ modelPolicy } as never)) + ).pipe( + // No managed folder: the host's own skills are not read. + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(HostProcess.Environment, {}), + Effect.provide(NodeServices.layer), + ); + +/** The matcher a query opens with, under these settings. */ +const matcherFor = (modelPolicy: Settings) => + Effect.flatten(makeClaudeAgentModelPolicyHook).pipe(withSettings(modelPolicy)); + +/** The hook's answer for one call, under these settings. */ +const answer = (modelPolicy: Settings, toolInput: unknown, tool = "Agent", place = NOWHERE) => + Effect.gen(function* () { + const matcher = yield* Effect.flatten(makeClaudeAgentModelPolicyHook); + return yield* Effect.promise(() => + matcher.hooks[0]!(callInput(toolInput, tool, place), "toolu_agent", { + signal: new AbortController().signal, + }), + ); + }).pipe(withSettings(modelPolicy)); + +const decision = (output: unknown) => + (output as { hookSpecificOutput?: { permissionDecision?: string } }).hookSpecificOutput + ?.permissionDecision; +const reason = (output: unknown) => + (output as { hookSpecificOutput?: { permissionDecisionReason?: string } }).hookSpecificOutput + ?.permissionDecisionReason ?? ""; +const context = (output: unknown) => + (output as { hookSpecificOutput?: { additionalContext?: string } }).hookSpecificOutput + ?.additionalContext; + +const START_PASSES = + 'Agent calls that pass: model "opus" (claude-opus-5-5 here) with effort medium, high, xhigh; model "fable" (claude-fable-5-2 here) with effort medium, high, xhigh.'; + +describe("claudeAgentCallPick", () => { + it("reads the alias as the full id this machine's Claude list maps it to, keeping the alias", () => { + assert.deepStrictEqual( + claudeAgentCallPick(BUNDLED_CLAUDE_MODEL_CATALOG, { model: "opus", effort: "high" }), + { + driver: "claudeAgent", + model: "claude-opus-5-5", + namedAs: "opus", + options: [{ id: "effort", value: "high" }], + }, + ); + // A name the list does not map stays as given; inherit and none name no model. + assert.deepStrictEqual(claudeAgentCallPick(BUNDLED_CLAUDE_MODEL_CATALOG, { model: "x-1" }), { + driver: "claudeAgent", + model: "x-1", + }); + for (const input of [{}, { model: "inherit" }, { model: " " }, null, "text"]) { + assert.isUndefined(claudeAgentCallPick(BUNDLED_CLAUDE_MODEL_CATALOG, input)?.model); + } + // A fork is read like any call (Claude runs it on the session's model; the owner's decision + // and the model guard still have every call name an allowed one). + assert.strictEqual( + claudeAgentCallPick(BUNDLED_CLAUDE_MODEL_CATALOG, { subagent_type: "fork", model: "sonnet" }) + .model, + "claude-sonnet-5-5", + ); + }); +}); + +describe("the Agent tool under the model policy (#128)", () => { + it.effect("enforce: refuses a model outside the rows, an effort it does not allow, or none", () => + Effect.gen(function* () { + for (const [input, why] of [ + [{ model: "sonnet", effort: "high" }, "claude-sonnet-5-5 (claudeAgent) is in no row"], + [{ model: "opus", effort: "max" }, "claude-opus-5-5 does not allow effort max"], + [ + { model: "opus" }, + "claude-opus-5-5 needs an effort from its row, and the pick names none", + ], + [{ effort: "high" }, "the call names no model"], + [{ model: "inherit", effort: "high" }, "the call names no model"], + [ + { model: "opus", effort: 3 }, + "claude-opus-5-5's effort option effort holds no effort name", + ], + ] as const) { + // Runs again: the same answer. + for (const _ of [1, 2]) { + const output = yield* answer(ENFORCE, input); + assert.strictEqual(decision(output), "deny", JSON.stringify(input)); + assert.include(reason(output), `Model policy refused this pick: ${why}.`); + // The refusal says what passes on this tool, which names only aliases. + assert.include(reason(output), START_PASSES); + assert.include( + reason(output), + "Name one of these models in the Agent call's model, with one of its efforts in effort.", + ); + } + } + // Task (older Claude Code) is read alike. + assert.strictEqual( + decision(yield* answer(ENFORCE, { model: "sonnet", effort: "high" }, "Task")), + "deny", + ); + }), + ); + + it.effect("enforce: an inside pick runs with its row's useFor; other tools pass", () => + Effect.gen(function* () { + const inside = yield* answer(ENFORCE, { model: "opus", effort: "high" }); + assert.isUndefined(decision(inside)); + assert.strictEqual( + context(inside), + "Model policy: claude-opus-5-5 is for most work: building, routine work, review lenses.", + ); + // The full id reads the same as its alias. + assert.isUndefined( + decision(yield* answer(ENFORCE, { model: "claude-fable-5-2", effort: "xhigh" })), + ); + // A fork must name an allowed model too: none is refused, an inside one runs. + assert.strictEqual(decision(yield* answer(ENFORCE, { subagent_type: "fork" })), "deny"); + assert.isUndefined( + decision(yield* answer(ENFORCE, { subagent_type: "fork", model: "opus", effort: "high" })), + ); + assert.deepStrictEqual(yield* answer(ENFORCE, { command: "ls" }, "Bash"), {}); + assert.deepStrictEqual(CLAUDE_AGENT_TOOLS, ["Agent", "Task"]); + }), + ); + + it.effect("a row saved with the alias matches the alias the call names, in both modes", () => + Effect.gen(function* () { + for (const mode of ["enforce", "advise"]) { + const rows = policy(mode, ALIAS_ROWS); + // Old state: a row saved as `opus` lets the Agent call `opus` run, as delegate_task does. + const inside = yield* answer(rows, { model: "opus", effort: "high" }); + assert.isUndefined(decision(inside), mode); + assert.isUndefined(context(inside), mode); + const outside = yield* answer(rows, { model: "sonnet", effort: "high" }); + const text = mode === "enforce" ? reason(outside) : (context(outside) ?? ""); + assert.strictEqual(decision(outside), mode === "enforce" ? "deny" : undefined); + assert.include( + text, + 'Agent calls that pass: model "opus" (claude-opus-5-5 here) with effort high.', + ); + // The effort is still the row's. + const effort = yield* answer(rows, { model: "opus", effort: "max" }); + assert.strictEqual(decision(effort), mode === "enforce" ? "deny" : undefined); + } + // A full-id row matches the alias that names it (both modes: the start rows above). + const advised = yield* answer(ADVISE, { model: "fable", effort: "high" }); + assert.isUndefined(decision(advised)); + assert.notInclude(context(advised) ?? "", "outside the policy"); + }), + ); + + it.effect( + "rows no alias reaches: the refusal says no Agent call passes and what still runs", + () => + Effect.gen(function* () { + const rows = policy("enforce", [ + { driver: "claudeAgent", model: "claude-opus-4-7", efforts: ["high"] }, + { driver: "claudeAgent", model: "opus", efforts: ["ultracode"] }, + { driver: "codex", model: "gpt-5.5", efforts: ["high"] }, + ]); + const output = yield* answer(rows, { model: "opus", effort: "high" }); + assert.strictEqual(decision(output), "deny"); + assert.include( + reason(output), + "No Agent call passes: no claudeAgent row names a model that an Agent alias (sonnet, opus, haiku, fable) runs here, at an effort the Agent tool can name.", + ); + assert.include(reason(output), "through delegate_task, which takes the full id"); + }), + ); + + it.effect("advise runs it with a note; off and a host without settings check nothing", () => + Effect.gen(function* () { + const advised = yield* answer(ADVISE, { model: "sonnet", effort: "high" }); + assert.isUndefined(decision(advised)); + assert.include( + context(advised) ?? "", + "Model policy (advise): this pick is outside the policy", + ); + assert.deepStrictEqual(yield* answer(OFF, { model: "sonnet" }), {}); + assert.deepStrictEqual(yield* answer("no-settings", { model: "sonnet" }), {}); + }), + ); + + it.effect("fails closed: unreadable policy or settings, and a check that throws, refuse", () => + Effect.gen(function* () { + const bad = yield* answer( + { held: { mode: "enforce", allow: [], unreadable: { mode: "on", allow: "x" } } }, + { model: "opus", effort: "high" }, + ); + assert.strictEqual(decision(bad), "deny"); + assert.include(reason(bad), "does not parse), so every agent pick is refused"); + // A settings read that dies: the hook refuses rather than letting the call through. + const died = yield* answer("unreadable", { model: "opus", effort: "high" }); + assert.strictEqual(decision(died), "deny"); + const matcher = yield* matcherFor(ENFORCE); + const throwing = { + hook_event_name: "PreToolUse", + get tool_name(): string { + throw new Error("malformed hook input"); + }, + } as unknown as HookInput; + const output = yield* Effect.promise(() => + matcher.hooks[0]!(throwing, undefined, { signal: new AbortController().signal }), + ); + assert.strictEqual(decision(output), "deny"); + assert.include(reason(output), "could not check this call"); + }), + ); + + it.effect("a hook that fails or times out refuses while a policy is on (onFailure block)", () => + Effect.gen(function* () { + for (const settings of [ENFORCE, ADVISE, "unreadable"] as const) { + assert.strictEqual((yield* matcherFor(settings)).onFailure, "block", String(settings)); + } + // Off: left out, so a Claude Code too old to know the option still opens its queries. + for (const settings of [OFF, "no-settings"] as const) { + assert.isUndefined((yield* matcherFor(settings)).onFailure, String(settings)); + } + assert.strictEqual((yield* matcherFor(ENFORCE)).matcher, "^(Agent|Task|Skill)$"); + }), + ); +}); + +describe("claudeConfigDirOfTranscript", () => { + it.effect("reads the config folder above projects/, for a session and a sub-agent", () => + Effect.gen(function* () { + const path = yield* Path.Path; + assert.strictEqual( + claudeConfigDirOfTranscript(path, "/h/.claude/projects/-w/s.jsonl"), + "/h/.claude", + ); + assert.strictEqual( + claudeConfigDirOfTranscript(path, "/h/cfg/projects/-w/s/subagents/agent-a.jsonl"), + "/h/cfg", + ); + for (const odd of ["/tmp/t.jsonl", "relative/projects/-w/s.jsonl", undefined, 3]) { + assert.isUndefined(claudeConfigDirOfTranscript(path, odd), String(odd)); + } + }).pipe(Effect.provide(NodeServices.layer)), + ); +}); + +describe("a skill that starts a sub-agent under the model policy (#128)", () => { + /** A config folder and a project, each with skills; the call's place in that project. */ + const fixture = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-policy-skills-" }); + const config = path.join(root, "claude"); + const project = path.join(root, "project"); + const write = (dir: string, name: string, text: string) => + Effect.gen(function* () { + yield* fileSystem.makeDirectory(path.join(dir, name), { recursive: true }); + yield* fileSystem.writeFileString(path.join(dir, name, "SKILL.md"), text); + }); + const user = path.join(config, "skills"); + const own = path.join(project, ".claude", "skills"); + yield* write(user, "fork-opus", "---\ncontext: fork\nmodel: opus\neffort: high\n---\nDo it."); + yield* write(user, "fork-sonnet", "---\ncontext: fork\nmodel: sonnet\neffort: high\n---\n"); + yield* write(user, "fork-none", "---\ncontext: fork\nagent: Explore\n---\nLook."); + yield* write(user, "fork-inherit", "---\ncontext: fork\nmodel: inherit\neffort: high\n---\n"); + yield* write(user, "inline", "---\ndescription: plain\n---\nInline."); + yield* write(user, "no-frontmatter", "Just text."); + yield* write(user, "inline-model", "---\nmodel: claude-sonnet-5-5\neffort: high\n---\n"); + // Frontmatter that does not start the file: Claude Code may still read it. + yield* write(user, "late", "\n---\ncontext: fork\nmodel: sonnet\n---\n"); + yield* write(user, "bad-yaml", "---\ncontext: fork\ncontext: inline\n---\n"); + // An unquoted ": " in a value: Claude Code and T3's skill list read it (its repair step). + const colon = "description: Review the code: bugs and style"; + yield* write(user, "inline-colon", `---\n${colon}\n---\nInline.`); + yield* write(user, "fork-colon", `---\n${colon}\ncontext: fork\nmodel: sonnet\n---\n`); + // Still broken after that repair (it leaves a value starting with "[" alone). + yield* write(user, "colon-broken", `---\n${colon}\ncontext: fork\nmodel: [opus\n---\n`); + yield* write(own, "project-fork", "---\ncontext: fork\nmodel: haiku\neffort: high\n---\n"); + yield* write( + own, + "project-alias", + '---\ncontext: "fork"\nmodel: "fable"\neffort: xhigh\n---\n', + ); + return { + session: { transcript: path.join(config, "projects", "-p", "s.jsonl"), cwd: project }, + subagent: { + transcript: path.join(config, "projects", "-p", "s", "subagents", "agent-a.jsonl"), + cwd: project, + }, + }; + }); + const skill = (settings: Settings, name: unknown, place: Place) => + answer(settings, { skill: name }, "Skill", place); + + it.effect("enforce: checks the frontmatter of a skill that runs forked or names a model", () => + Effect.gen(function* () { + const { session, subagent } = yield* fixture; + // Inside the rows, by alias or full id, from the user's skills or the project's. + for (const name of ["fork-opus", "/fork-opus", "project-alias"]) { + for (const place of [session, subagent]) { + assert.isUndefined(decision(yield* skill(ENFORCE, name, place)), name); + } + } + // Runs inline and names no model: it runs on the session's own model, nothing to check. + for (const name of ["inline", "no-frontmatter", "inline-colon"]) { + assert.deepStrictEqual(yield* skill(ENFORCE, name, session), {}, name); + assert.deepStrictEqual(yield* skill(ADVISE, name, session), {}, name); + } + for (const [name, why] of [ + ["fork-sonnet", "claude-sonnet-5-5 (claudeAgent) is in no row"], + ["fork-none", "the call names no model"], + ["fork-inherit", "the call names no model"], + ["inline-model", "claude-sonnet-5-5 (claudeAgent) is in no row"], + ["fork-colon", "claude-sonnet-5-5 (claudeAgent) is in no row"], + ["project-fork", "claude-haiku-5-5 (claudeAgent) is in no row"], + ] as const) { + // Runs again: the same answer. + for (const _ of [1, 2]) { + const output = yield* skill(ENFORCE, name, session); + assert.strictEqual(decision(output), "deny", name); + assert.include(reason(output), `Model policy refused this pick: ${why}.`, name); + assert.include(reason(output), "the skill's frontmatter: model", name); + } + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("fails closed: a skill T3 cannot find or read is refused under enforce", () => + Effect.gen(function* () { + const { session } = yield* fixture; + for (const [name, place, why] of [ + ["simplify", session, "T3 does not find the skill simplify among Claude's skills"], + ["", session, "the Skill call names no skill"], + [3, session, "the Skill call names no skill"], + ["late", session, "T3 cannot read the frontmatter of the skill late"], + ["bad-yaml", session, "T3 does not find the skill bad-yaml"], + ["colon-broken", session, "T3 does not find the skill colon-broken"], + [ + "fork-opus", + { ...session, transcript: "/elsewhere/t.jsonl" }, + "T3 cannot tell which Claude config folder holds the skill fork-opus", + ], + ] as const) { + const output = yield* skill(ENFORCE, name, place); + assert.strictEqual(decision(output), "deny", String(name)); + assert.include(reason(output), `Model policy refused this call (fail closed): ${why}`); + } + // Advise runs it with a note; off reads nothing. + const advised = yield* skill(ADVISE, "simplify", session); + assert.isUndefined(decision(advised)); + assert.include(context(advised) ?? "", "Model policy (advise): T3 does not find the skill"); + assert.deepStrictEqual(yield* skill(OFF, "fork-sonnet", session), {}); + assert.deepStrictEqual(yield* skill("no-settings", "simplify", session), {}); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/server/src/fork/claudeAgentModelPolicy.ts b/apps/server/src/fork/claudeAgentModelPolicy.ts new file mode 100644 index 0000000000000..8809c960c158c --- /dev/null +++ b/apps/server/src/fork/claudeAgentModelPolicy.ts @@ -0,0 +1,284 @@ +/** + * Fork: `modelPolicy` for calls that start Claude's own sub-agents, as each is made: the Agent tool + * (Task in older Claude Code), and Skill for a skill that forks or names a model or effort. An alias + * matches a row naming it or its full id here; a `fork` call must name a model too. + */ +import type { + HookCallback, + HookCallbackMatcher, + PreToolUseHookInput, +} from "@anthropic-ai/claude-agent-sdk"; +import type { AgentInput } from "@anthropic-ai/claude-agent-sdk/sdk-tools"; +import { + type ModelPolicyRow, + modelPolicyRowsText, + modelPolicyStance, + ProviderDriverKind, +} from "@t3tools/contracts"; +import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; + +import { + BUNDLED_CLAUDE_MODEL_CATALOG, + type ClaudeModelCatalog, + resolveClaudeModelCatalog, + resolveClaudeModelSlug, +} from "../provider/ClaudeModelCatalog.ts"; +import { discoverClaudeSkills, parseSkillFrontmatter } from "../provider/Drivers/ClaudeSkills.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { makePickCheck, type PolicyRoute, type ServerPick } from "./modelPolicyCheck.ts"; + +const CLAUDE_DRIVER = "claudeAgent"; +/** Claude Code's tools that start a sub-agent: Agent, and Task in older versions. */ +export const CLAUDE_AGENT_TOOLS: ReadonlyArray = ["Agent", "Task"]; +/** Claude Code's tool that runs a skill, in a sub-agent when its frontmatter says `context: fork`. */ +const CLAUDE_SKILL_TOOL = "Skill"; + +/** The Agent tool's model names and efforts (the SDK's `AgentInput`): a change there fails the typecheck. */ +const AGENT_MODELS: Record, true> = { + sonnet: true, + opus: true, + haiku: true, + fable: true, +}; +const AGENT_EFFORTS: Record, true> = { + low: true, + medium: true, + high: true, + xhigh: true, + max: true, +}; + +/** + * The pick a Claude model name and effort make: `inherit` and a missing model name no model. An alias + * is read as the full id this machine's Claude list maps it to, keeping the name given (`namedAs`), + * so a row naming either matches. + */ +function claudeModelPick(catalog: ClaudeModelCatalog, model: unknown, effort: unknown): ServerPick { + const named = typeof model === "string" ? model.trim() : ""; + const resolved = + named === "" || named === "inherit" ? undefined : resolveClaudeModelSlug(catalog, named); + return { + driver: CLAUDE_DRIVER, + model: resolved, + ...(resolved !== undefined && resolved !== named ? { namedAs: named } : {}), + // A value that is not a string reads as an effort with no name, which is refused. + ...(effort === undefined || effort === null + ? {} + : { options: [{ id: "effort", value: effort }] }), + }; +} + +const record = (value: unknown): Record => + typeof value === "object" && value !== null ? (value as Record) : {}; + +/** The pick an Agent call makes (a fork's too). */ +export function claudeAgentCallPick(catalog: ClaudeModelCatalog, input: unknown): ServerPick { + const args = record(input); + return claudeModelPick(catalog, args.model, args.effort); +} + +/** + * What passes the rows on the Agent tool, which names only aliases: each alias whose name or full id + * here a Claude row names, with the efforts the tool can name. None: says so, and where a row's model + * can still run. + */ +function claudeAgentPassesText( + catalog: ClaudeModelCatalog, + allow: ReadonlyArray, +): string { + const aliases = Object.keys(AGENT_MODELS); + const passes = aliases.flatMap((alias) => { + const id = resolveClaudeModelSlug(catalog, alias); + const rows = allow.filter( + (row) => row.driver === CLAUDE_DRIVER && (row.model === alias || row.model === id), + ); + const efforts = [ + ...new Set( + rows.flatMap( + (row) => row.efforts?.filter((one) => Object.hasOwn(AGENT_EFFORTS, one)) ?? [], + ), + ), + ]; + const ways = [ + ...(efforts.length === 0 ? [] : [`effort ${efforts.join(", ")}`]), + ...(rows.some((row) => row.efforts === undefined) ? ["no effort"] : []), + ]; + return ways.length === 0 + ? [] + : [`model "${alias}"${id === alias ? "" : ` (${id} here)`} with ${ways.join(" or ")}`]; + }); + return passes.length > 0 + ? `Agent calls that pass: ${passes.join("; ")}.` + : `No Agent call passes: no ${CLAUDE_DRIVER} row names a model that an Agent alias (${aliases.join(", ")}) runs here, at an effort the Agent tool can name. Rows: ${modelPolicyRowsText(allow)}. A row's model can still run as a task through delegate_task, which takes the full id.`; +} + +/** + * Claude Code's config folder for this call: the folder above `projects/` in the hook's transcript + * path (`/projects//.jsonl`, or a sub-agent's + * `/projects///subagents/.jsonl`). `undefined` for another shape. + */ +export function claudeConfigDirOfTranscript( + path: Path.Path, + transcript: unknown, +): string | undefined { + if (typeof transcript !== "string" || !path.isAbsolute(transcript)) return undefined; + const up = (from: string, levels: number): string => + levels === 0 ? from : up(path.dirname(from), levels - 1); + const subagent = path.basename(path.dirname(transcript)) === "subagents"; + const projects = up(transcript, subagent ? 4 : 2); + return path.basename(projects) === "projects" ? path.dirname(projects) : undefined; +} + +/** + * A SKILL.md's frontmatter as T3's skill list reads it (`parseSkillFrontmatter`, which repairs the + * unquoted `: ` in a value that Claude Code accepts); `undefined` when it cannot be read. + */ +function skillFrontmatter(text: string): Record | undefined { + const read = parseSkillFrontmatter(text); + // Something that looks like frontmatter but is not read as such here may be read by Claude Code. + if (read.kind === "missing") return /^\uFEFF?\s*---/.test(text) ? undefined : {}; + return read.kind === "parsed" && !Array.isArray(read.record) ? read.record : undefined; +} + +const unreadableSkill = (why: string): ServerPick => ({ + driver: CLAUDE_DRIVER, + model: undefined, + unreadable: `${why}, so T3 cannot tell whether it starts a sub-agent (context: fork) on a model outside the policy. Do the work without it, or a person puts a copy in the project's .claude/skills that names a model from the rows in its frontmatter model and effort`, +}); + +/** + * The pick a Skill call makes: its skill's frontmatter `model` and `effort` when it runs in a + * sub-agent (`context: fork`) or names either; `undefined` for a skill that runs inline and names + * neither (it runs on the session's own model). Found as T3 finds Claude's skills + * (`discoverClaudeSkills`, first name wins); a skill that cannot be found or read is unreadable. + */ +const claudeSkillCallPick = Effect.fn("claudeSkillCallPick")(function* ( + catalog: ClaudeModelCatalog, + input: Pick, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const raw = record(input.tool_input).skill; + const name = typeof raw === "string" ? raw.trim().replace(/^\//, "") : ""; + if (name === "") return unreadableSkill("the Skill call names no skill"); + const configDir = claudeConfigDirOfTranscript(path, input.transcript_path); + if (configDir === undefined) { + return unreadableSkill(`T3 cannot tell which Claude config folder holds the skill ${name}`); + } + const skills = yield* discoverClaudeSkills( + { homePath: configDir }, + input.cwd, + yield* HostProcess.Environment, + ); + const skill = skills.find((candidate) => candidate.name === name); + if (skill === undefined) { + return unreadableSkill( + `T3 does not find the skill ${name} among Claude's skills it reads (managed, user, project and plugin skills): a skill bundled with Claude Code, an MCP server's, a command or one in another folder cannot be read`, + ); + } + const text = yield* fileSystem + .readFileString(skill.path) + .pipe(Effect.orElseSucceed(() => undefined)); + const frontmatter = text === undefined ? undefined : skillFrontmatter(text); + if (frontmatter === undefined) { + return unreadableSkill(`T3 cannot read the frontmatter of the skill ${name}`); + } + const { context, model, effort } = frontmatter; + const named = (value: unknown) => value !== undefined && value !== null; + if (context !== "fork" && !named(model) && !named(effort)) return undefined; + return claudeModelPick(catalog, model, effort); +}); + +const deny = (reason: string) => ({ + hookSpecificOutput: { + hookEventName: "PreToolUse" as const, + permissionDecision: "deny" as const, + permissionDecisionReason: reason, + }, +}); + +const note = (text: string) => ({ + hookSpecificOutput: { hookEventName: "PreToolUse" as const, additionalContext: text }, +}); + +/** + * The matcher each query opens with. Fails closed: an error while checking refuses (a throw would let + * the call through), and while a policy is on `onFailure: "block"` refuses a timeout too; off, it is + * left out, as a Claude Code older than 2.1.295 fails every query that sets it. + */ +export const makeClaudeAgentModelPolicyHook = Effect.gen(function* () { + const check = yield* makePickCheck; + const settings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService); + const catalogService = yield* Effect.serviceOption(ModelCatalog.ModelCatalog); + const fileSystem = yield* Effect.serviceOption(FileSystem.FileSystem); + const path = yield* Effect.serviceOption(Path.Path); + const loadCatalog = Option.match(catalogService, { + onNone: () => Effect.succeed(BUNDLED_CLAUDE_MODEL_CATALOG), + onSome: (service) => + service.current(ProviderDriverKind.make(CLAUDE_DRIVER)).pipe( + Effect.map(resolveClaudeModelCatalog), + Effect.orElseSucceed(() => BUNDLED_CLAUDE_MODEL_CATALOG), + ), + }); + const readSkill = (catalog: ClaudeModelCatalog, input: PreToolUseHookInput) => + Option.isSome(fileSystem) && Option.isSome(path) + ? claudeSkillCallPick(catalog, input).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem.value), + Effect.provideService(Path.Path, path.value), + ) + : Effect.succeed(unreadableSkill("T3 cannot read files here")); + const run = Effect.runPromiseWith(yield* Effect.context()); + + const hook: HookCallback = async (input) => { + try { + if (input.hook_event_name !== "PreToolUse") return {}; + const skill = input.tool_name === CLAUDE_SKILL_TOOL; + if (!skill && !CLAUDE_AGENT_TOOLS.includes(input.tool_name)) return {}; + const route: PolicyRoute = skill ? "Skill" : "Agent"; + const answer = await run( + Effect.gen(function* () { + // Read only while a policy is on: `check` skips it when off. + const readPick = Effect.flatMap(loadCatalog, (catalog) => + skill + ? readSkill(catalog, input) + : Effect.succeed({ + ...claudeAgentCallPick(catalog, input.tool_input), + allowedText: (allow: ReadonlyArray) => + claudeAgentPassesText(catalog, allow), + }), + ); + return { note: yield* check(route, readPick) }; + }).pipe( + Effect.catchTags({ + OrchestratorMcpFailure: (failure) => Effect.succeed({ refuse: failure.message }), + }), + ), + ); + if ("refuse" in answer) return deny(answer.refuse); + return answer.note === undefined ? {} : note(answer.note); + } catch { + return deny( + "Model policy: T3 could not check this call against the model policy, so it refused it. Try again; if it stays, name a model and effort from the policy's rows.", + ); + } + }; + const matcher: HookCallbackMatcher = { + matcher: `^(${[...CLAUDE_AGENT_TOOLS, CLAUDE_SKILL_TOOL].join("|")})$`, + hooks: [hook], + }; + const blocking: HookCallbackMatcher = { ...matcher, onFailure: "block" }; + const policyOn = Option.match(settings, { + onNone: () => Effect.succeed(false), + onSome: (service) => + Effect.map(Effect.exit(service.getSettings), (read) => + Exit.isSuccess(read) ? modelPolicyStance(read.value.modelPolicy).mode !== "off" : true, + ), + }); + return Effect.map(policyOn, (on) => (on ? blocking : matcher)); +}); diff --git a/apps/server/src/fork/claudeMcpProfile.adapter.test.ts b/apps/server/src/fork/claudeMcpProfile.adapter.test.ts index a7b17dbe9b756..9ba603d5d1de3 100644 --- a/apps/server/src/fork/claudeMcpProfile.adapter.test.ts +++ b/apps/server/src/fork/claudeMcpProfile.adapter.test.ts @@ -44,7 +44,7 @@ const POLICY = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ cwd: "/workspace", }); -type McpSettings = Partial>; +type McpSettings = Partial>; const NATIVE_THREAD = "native-thread-mcp-profile"; /** @@ -220,12 +220,13 @@ const preToolUse = ( tool: unknown, /** Replaces the hook input, for a malformed one. */ rawInput?: object, + toolInput: object = {}, ) => Effect.promise(async () => { const input = (rawInput ?? { hook_event_name: "PreToolUse", tool_name: tool, - tool_input: {}, + tool_input: toolInput, tool_use_id: "toolu_profile", session_id: NATIVE_THREAD, transcript_path: "/tmp/transcript.jsonl", @@ -233,6 +234,13 @@ const preToolUse = ( }) as unknown as HookInput; const answers = []; for (const matcher of options?.hooks?.PreToolUse ?? []) { + // As Claude Code does: a matcher runs its hooks only for the tools it names. + if ( + matcher.matcher !== undefined && + !(typeof tool === "string" && new RegExp(matcher.matcher).test(tool)) + ) { + continue; + } for (const hook of matcher.hooks) { answers.push(await hook(input, "toolu_profile", { signal: new AbortController().signal })); } @@ -252,6 +260,68 @@ describe("ClaudeAdapterV2 MCP profile", () => { }), ); + it.effect("every query carries the model policy's check of Claude's Agent tool once (#128)", () => + Effect.gen(function* () { + const modelPolicy = { + mode: "enforce", + allow: [{ driver: "claudeAgent", model: "claude-opus-5-5", efforts: ["high"] }], + } as never; + const bare = { servers: "all", t3Tools: "all", builtinTools: "none" } as const; + // With no profile, and with a profile that adds its own PreToolUse hooks. + for (const settings of [ + { modelPolicy }, + { modelPolicy, mcpProfile: "t3-only" }, + { modelPolicy, mcpProfile: "bare", mcpProfiles: { bare } }, + ] as ReadonlyArray) { + // Runs again: a second turn on the same thread. + const { opened, refusal } = yield* runTurns( + settings, + settings.mcpProfile === "t3-only" ? [] : "unexpected", + [settings], + ); + assert.isUndefined(refusal); + assert.isAtLeast(opened.length, 1); + const reasons = (answers: ReadonlyArray) => + answers.map( + (answer) => + (answer as { hookSpecificOutput?: { permissionDecisionReason?: string } }) + .hookSpecificOutput?.permissionDecisionReason, + ); + for (const options of opened) { + // Once per query, first, refusing when it cannot answer: never stacked. + const policyHooks = (options.hooks?.PreToolUse ?? []).filter( + (matcher) => matcher.matcher === "^(Agent|Task|Skill)$", + ); + assert.lengthOf(policyHooks, 1, JSON.stringify(settings)); + assert.strictEqual(options.hooks?.PreToolUse?.[0], policyHooks[0]); + assert.strictEqual(policyHooks[0]?.onFailure, "block"); + const refused = yield* preToolUse(options, "Agent", undefined, { + model: "sonnet", + effort: "high", + }); + assert.lengthOf( + reasons(refused).filter((text) => + text?.startsWith( + "Model policy refused this pick: claude-sonnet-5-5 (claudeAgent) is in no row.", + ), + ), + 1, + JSON.stringify(settings), + ); + // Inside the rows: the policy's hook lets it run (builtinTools "none" refuses Agent anyway). + const inside = yield* preToolUse(options, "Agent", undefined, { + model: "opus", + effort: "high", + }); + assert.isFalse( + reasons(inside).some((text) => text?.startsWith("Model policy")), + JSON.stringify(settings), + ); + } + } + }), + ); + it.effect("t3-only opens Claude in strict MCP mode", () => Effect.gen(function* () { const { opened, refusal } = yield* runTurns({ mcpProfile: "t3-only" }, []); diff --git a/apps/server/src/fork/claudeMcpProfile.test.ts b/apps/server/src/fork/claudeMcpProfile.test.ts index cb31c20f01671..076dce2aa3a89 100644 --- a/apps/server/src/fork/claudeMcpProfile.test.ts +++ b/apps/server/src/fork/claudeMcpProfile.test.ts @@ -238,17 +238,19 @@ describe("makeClaudeMcpProfiles", () => { }); const reads = [lean(["threads"]), lean(["threads"]), lean(["threads", "orchestration"])]; const service = yield* ServerSettingsService.ServerSettingsService; - let next = 0; + // Each query opens on the settings of its round (the model policy reads them too). + let current: object = {}; const plan = yield* makeClaudeMcpProfiles.pipe( Effect.provideService(ServerSettingsService.ServerSettingsService, { ...service, - getSettings: Effect.suspend(() => Effect.succeed(fromFile(reads[next++] ?? {}))), + getSettings: Effect.suspend(() => Effect.succeed(fromFile(current))), }), ); const self = thread("t"); const keys: Array = []; const sets: Array = []; - for (const _ of reads) { + for (const read of reads) { + current = read; const overrides = {}; // The adapter reads the options only as it opens the query's process. void (yield* plan(self, overrides)).options; @@ -293,7 +295,13 @@ describe("makeClaudeMcpProfiles", () => { assert.deepStrictEqual(planned.servers, "all"); assert.strictEqual(T3ToolSets.t3ToolSetFor("t"), before); // The new process opens: its options are read, and the new set applies from then. - assert.deepStrictEqual(planned.options, {}); + // The lean profile adds no options of its own: only the model policy's Agent and Skill hook. + const options = planned.options; + assert.deepStrictEqual(Object.keys(options), ["hooks"]); + assert.deepStrictEqual( + options.hooks?.PreToolUse?.map((matcher) => matcher.matcher), + ["^(Agent|Task|Skill)$"], + ); const set = T3ToolSets.t3ToolSetFor("t"); assert.deepStrictEqual(set?._tag === "Groups" ? [...(set.groups as Set)] : set, []); }).pipe( diff --git a/apps/server/src/fork/claudeMcpProfile.ts b/apps/server/src/fork/claudeMcpProfile.ts index 2b7e3c724bcd6..a5fd9aecbc38c 100644 --- a/apps/server/src/fork/claudeMcpProfile.ts +++ b/apps/server/src/fork/claudeMcpProfile.ts @@ -42,6 +42,7 @@ import { type McpProfileThread, resolveMcpProfile, } from "./mcpProfile.ts"; +import { makeClaudeAgentModelPolicyHook } from "./claudeAgentModelPolicy.ts"; import { MAX_T3_TOOL_SETS, type T3ToolSet, @@ -705,6 +706,21 @@ export const makeThreadMcpProfilesById = Effect.gen(function* () { }); }); +/** A plan with the model policy's Agent and Skill tool hook first among its PreToolUse hooks. */ +const withAgentModelPolicy = ( + plan: ClaudeMcpProfilePlan, + agentPolicy: HookCallbackMatcher, +): ClaudeMcpProfilePlan => ({ + ...plan, + options: { + ...plan.options, + hooks: { + ...plan.options.hooks, + PreToolUse: [agentPolicy, ...(plan.options.hooks?.PreToolUse ?? [])], + }, + }, +}); + /** * The plan key each thread's Claude process last opened with. Its T3 tool groups are part of the * key, so a later plan with the same key has the same set as that process. Memory only, bounded @@ -746,6 +762,8 @@ const fixedWhenOpened = ( /** The thread's Claude plan, or a refusal, from {@link makeThreadMcpProfiles}. */ export const makeClaudeMcpProfiles = Effect.gen(function* () { const profileFor = yield* makeThreadMcpProfiles; + // Every query also gets the model policy's check of Claude's own Agent and Skill tools. + const agentPolicy = yield* makeClaudeAgentModelPolicyHook; const planFor = Effect.fn("ClaudeMcpProfile.planFor")(function* ( thread: LineageThread, overrides: McpOverrides, @@ -770,7 +788,8 @@ export const makeClaudeMcpProfiles = Effect.gen(function* () { if (openedPlanKeys.has(thread.id) && openedPlanKeys.get(thread.id) === planKey(plan)) { fixT3ToolSet(thread.id, set); } - return fixedWhenOpened(plan, thread.id, set); + // The policy hook goes in before the options are made lazy, so adding it reads nothing early. + return fixedWhenOpened(withAgentModelPolicy(plan, yield* agentPolicy), thread.id, set); }); return Effect.fn("ClaudeMcpProfile.plan")(function* ( diff --git a/apps/server/src/fork/delegateOwnOptions.test.ts b/apps/server/src/fork/delegateOwnOptions.test.ts index c8020b223ad27..0480a9c9bf213 100644 --- a/apps/server/src/fork/delegateOwnOptions.test.ts +++ b/apps/server/src/fork/delegateOwnOptions.test.ts @@ -621,12 +621,22 @@ describe("a child's own options, remote delegate_task", () => { `claimed ${driverKind}`, ); } - // The rows themselves allow the model with no effort named: sent. + // The rows themselves allow the model with no effort named (and ultracode named off, which a + // pick sent there must name for a claudeAgent row): sent. assert.deepStrictEqual( - yield* sentTarget({ driverKind: "claudeAgent", model: OPENCODE.model }, "enforce", { - settings: claimRows, - }), - [{ environmentId: box, driverKind: "claudeAgent", model: OPENCODE.model, options: [] }], + yield* sentTarget( + { driverKind: "claudeAgent", model: OPENCODE.model, options: { ultracode: false } }, + "enforce", + { settings: claimRows }, + ), + [ + { + environmentId: box, + driverKind: "claudeAgent", + model: OPENCODE.model, + options: [{ id: "ultracode", value: false }], + }, + ], ); assert.deepStrictEqual(yield* sentTarget({ model: OPENCODE.model }, "enforce"), [ { environmentId: box, model: OPENCODE.model, options: [] }, diff --git a/apps/server/src/fork/launchMcpProfile.test.ts b/apps/server/src/fork/launchMcpProfile.test.ts index eba3e71c9f89f..1b12e3875abb7 100644 --- a/apps/server/src/fork/launchMcpProfile.test.ts +++ b/apps/server/src/fork/launchMcpProfile.test.ts @@ -693,6 +693,7 @@ describe("the model policy on a launch sent to a linked machine (#731)", () => { model: "claude-opus", options: [{ id: "effort", value: effort }], }); + const ULTRACODE_OFF = { id: "ultracode", value: false }; it.effect("enforce: an agent's launch there off the rows, or naming no model, is not sent", () => Effect.gen(function* () { @@ -724,10 +725,11 @@ describe("the model policy on a launch sent to a linked machine (#731)", () => { } expect(forwarded).toHaveLength(0); expect(launched).toHaveLength(0); - // Inside the rows: sent. - expect( - refusal(yield* launch({ environmentId: THERE, modelSelection: opus("high") })), - ).toContain("sent there"); + // Inside the rows, naming ultracode (a Claude pick sent there must): sent. + const inside = { ...opus("high"), options: [...opus("high").options, ULTRACODE_OFF] }; + expect(refusal(yield* launch({ environmentId: THERE, modelSelection: inside }))).toContain( + "sent there", + ); expect(forwarded).toHaveLength(1); }), ); diff --git a/apps/server/src/fork/modelPolicyCheck.test.ts b/apps/server/src/fork/modelPolicyCheck.test.ts index 573db8c6c0e8d..3856b35b78888 100644 --- a/apps/server/src/fork/modelPolicyCheck.test.ts +++ b/apps/server/src/fork/modelPolicyCheck.test.ts @@ -15,6 +15,7 @@ import { EnvironmentId, MODEL_POLICY_DRIVER_ALIASES, MODEL_POLICY_EFFORT_OPTION_IDS, + MODEL_POLICY_SESSION_MODE_OPTION_ID, MODEL_POLICY_START_ROWS, modelPolicyPickEfforts, type ModelPolicy, @@ -29,6 +30,7 @@ import { OrchestratorMcpFailure, ThreadId, } from "@t3tools/contracts"; +import { ACP_SESSION_MODE_OPTION_ID } from "@t3tools/provider-acp/server/sessionConfig"; import { DEFAULT_VARIANT_CHOICE_ID } from "@t3tools/shared/model"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -473,13 +475,15 @@ describe("a selection as the policy reads it", () => { ], } as never); assert.include(refusal(policy("enforce", rows), decoy), "does not allow effort high + max"); - // Each row's driver reads its own id, so the pick names the effort under both. + // Each row's driver reads its own id, so the pick names the effort under both (and ultracode, + // which the machine there may turn on by default for a Claude model). const inside = ModelPolicyCheck.pickOfRemoteTarget([], { driverKind: "codex", model: "shared", options: [ { id: "reasoningEffort", value: "high" }, { id: "effort", value: "high" }, + { id: "ultracode", value: false }, ], } as never); assert.isUndefined(refusal(policy("enforce", rows), inside)); @@ -570,9 +574,11 @@ describe("an effort named only under a driver's own option id (#780)", () => { it("sent to a linked machine: an id the row's driver does not read names no effort there", () => { // Lens A's probes: both were inside before. Claude (the Opus row's driver) reads only `effort`. + // Each names ultracode, which a Claude pick sent there must. + const NO_ULTRA = { id: "ultracode", value: false }; const probes = [ - remote([acpOpus], OPUS, [{ id: ACP_REASONING_ID, value: "high" }]), - remote([], OPUS, [{ id: "reasoning", value: "high" }]), + remote([acpOpus], OPUS, [{ id: ACP_REASONING_ID, value: "high" }, NO_ULTRA]), + remote([], OPUS, [{ id: "reasoning", value: "high" }, NO_ULTRA]), ]; for (const pick of probes) { assert.include( @@ -581,7 +587,10 @@ describe("an effort named only under a driver's own option id (#780)", () => { ); } assert.isUndefined( - refusal(policy("enforce"), remote([acpOpus], OPUS, [{ id: "effort", value: "high" }])), + refusal( + policy("enforce"), + remote([acpOpus], OPUS, [{ id: "effort", value: "high" }, NO_ULTRA]), + ), ); }); @@ -682,18 +691,64 @@ describe("an effort named only under a driver's own option id (#780)", () => { ), "does not allow effort ultracode + xhigh", ); - // The pick names the option: its own value stands. No catalog here: no default read. + // The pick names the option: its own value stands. const off = remote([ultracodeByDefault], OPUS, [ { id: "effort", value: "high" }, { id: "ultracode", value: false }, ]); assert.isUndefined(off.ultracodeMaybeDefault); assert.isUndefined(refusal(policy("enforce"), off)); + // No catalog here that turns it on: the machine there reads its own, which may, so a + // Claude row reads it both ways too; the refusal says to name the option. + const unknown = refusal(policy("enforce"), remote([], OPUS, [{ id: "effort", value: "high" }])); + assert.include( + unknown, + `the machine that runs it may turn ultracode on by default for ${OPUS} (its model list is not read here)`, + ); + assert.include( + unknown, + 'Name the option ultracode in target.options: { "id": "ultracode", "value": false }', + ); assert.isUndefined( - refusal(policy("enforce"), remote([], OPUS, [{ id: "effort", value: "high" }])), + refusal( + policy("enforce"), + remote([], OPUS, [ + { id: "effort", value: "high" }, + { id: "ultracode", value: false }, + ]), + ), ); }); + it("an option that picks an agent or a mode is refused with what to leave out (#802)", () => { + const opencode = { + driver: "opencode", + model: "oc", + options: [ + { id: "variant", value: "high" }, + { id: "agent", value: "build" }, + ], + describedOptionIds: ["variant", "agent"], + }; + const rows: ReadonlyArray = [ + { driver: ProviderDriverKind.make("opencode"), model: "oc", efforts: ["high"] }, + ]; + const text = refusal(policy("enforce", rows), opencode); + assert.include(text, "the option agent picks an agent or a mode"); + assert.include( + text, + "Leave that option out of target.options: an option that picks an agent or a mode is not allowed while the model policy is on.", + ); + const advised = answer(policy("advise", rows), opencode); + assert.include("note" in advised ? (advised.note ?? "") : "", "the option agent picks"); + }); + + it("the session mode the policy refuses is ACP's own", () => { + // The agent-picking ids are the model guard's: fork-kit/model-guard/tests/guard.test.py keeps + // the two lists in step (app code reads no fork-owned file). + assert.strictEqual(MODEL_POLICY_SESSION_MODE_OPTION_ID, ACP_SESSION_MODE_OPTION_ID); + }); + it("the aliases a driver resolves by itself are Claude Code's own", () => { const source = NodeFS.readFileSync( new URL("../claudeModelOptions.ts", import.meta.url), @@ -1066,9 +1121,13 @@ describe("t3_thread_configure through upstream's handler", () => { // Runs again: refused again; nothing sent, nothing changed here. assert.include(yield* configure({ model: "claude-haiku-5-5" }, THERE), "is in no row"); assert.lengthOf(forwarded, 0); - // Inside the rows, or a change with no model (it only renames): sent. + // Inside the rows (naming ultracode, which a Claude pick sent there must), or a change + // with no model (it only renames): sent. assert.include( - yield* configure({ model: OPUS, options: effort("high") }, THERE), + yield* configure( + { model: OPUS, options: [...effort("high"), { id: "ultracode", value: false }] }, + THERE, + ), "sent there", ); assert.include(yield* configure(undefined, THERE), "sent there"); diff --git a/apps/server/src/fork/modelPolicyCheck.ts b/apps/server/src/fork/modelPolicyCheck.ts index ead0220355741..9c8ae6a7e3779 100644 --- a/apps/server/src/fork/modelPolicyCheck.ts +++ b/apps/server/src/fork/modelPolicyCheck.ts @@ -8,9 +8,11 @@ import { checkModelPolicyPick, type ModelPolicy, modelPolicyAliasTargets, + type ModelPolicyFix, modelPolicyCatalogEffortIds, type ModelPolicyPick, modelPolicyPickEfforts, + type ModelPolicyRow, modelPolicyRowsText, modelPolicyStance, type ModelSelection, @@ -33,7 +35,11 @@ export type PolicyRoute = | "delegate_task" | "create_threads" | "t3_thread_launch" - | "t3_thread_configure"; + | "t3_thread_configure" + /** Claude's own Agent tool (claudeAgentModelPolicy.ts). */ + | "Agent" + /** Claude's Skill tool, for a skill that runs in a sub-agent or names a model (same file). */ + | "Skill"; /** Where the call names its model, for the refusal's hint. */ const FIELDS: Record = { @@ -41,6 +47,9 @@ const FIELDS: Record = { create_threads: "target.model, with one of its efforts in target.options", t3_thread_launch: "modelSelection.model, with one of its efforts in modelSelection.options", t3_thread_configure: "modelSelection.model, with one of its efforts in modelSelection.options", + Agent: "the Agent call's model, with one of its efforts in effort", + Skill: + "the skill's frontmatter: model, with one of its efforts in effort (or use a skill that runs inline and names neither)", }; /** Where the call names its model alone, and its options. */ @@ -49,19 +58,20 @@ const MODEL_FIELD: Record = { create_threads: "target.model", t3_thread_launch: "modelSelection.model", t3_thread_configure: "modelSelection.model", + Agent: "model", + Skill: "the skill's frontmatter model", }; const OPTIONS_FIELD: Record = { delegate_task: "target.options", create_threads: "target.options", t3_thread_launch: "modelSelection.options", t3_thread_configure: "modelSelection.options", + Agent: "the call", + Skill: "the skill's frontmatter", }; /** What the agent does to fix a refused pick, per the verdict's `fix`. */ -const fixText = ( - fix: "option" | "model-option" | "effort-id" | undefined, - route: PolicyRoute, -): string => { +const fixText = (fix: ModelPolicyFix | undefined, route: PolicyRoute): string => { switch (fix) { case "model-option": return `Pick the model in the model field (${MODEL_FIELD[route]}) and leave the model option out of ${OPTIONS_FIELD[route]}: this option is not allowed while the model policy is on.`; @@ -69,6 +79,10 @@ const fixText = ( return `Leave that option out of ${OPTIONS_FIELD[route]}: this option is not allowed while the model policy is on. Pick the model in ${MODEL_FIELD[route]} and its effort under the id its driver reads.`; case "effort-id": return "Start that agent on this machine once so its model list shows the effort control, or pick a model whose driver has a fixed effort id."; + case "agent-option": + return `Leave that option out of ${OPTIONS_FIELD[route]}: an option that picks an agent or a mode is not allowed while the model policy is on. Pick the model in ${MODEL_FIELD[route]} and its effort under the id its driver reads.`; + case "ultracode": + return `Name the option ultracode in ${OPTIONS_FIELD[route]}: { "id": "ultracode", "value": false } runs the effort named, true runs ultracode (when its row allows it).`; case undefined: return `Name one of these models in ${FIELDS[route]}.`; } @@ -83,6 +97,16 @@ const SETTINGS_PLACE = "Settings → Fork → Model policy"; */ export interface ServerPick extends ModelPolicyPick { readonly aliasOf?: string | undefined; + /** + * What passes on this route, in place of the rows (Claude's Agent tool names only aliases, so it + * says which alias and effort pass, `claudeAgentModelPolicy.ts`). + */ + readonly allowedText?: ((allow: ReadonlyArray) => string) | undefined; + /** + * Why the pick cannot be read at all (a skill whose file T3 cannot read): `enforce` refuses it, + * `advise` lets it run with a note. + */ + readonly unreadable?: string | undefined; } /** What the check answers: refuse with a text, or let the pick run (with a note for the agent). */ @@ -117,6 +141,16 @@ export function answerPick( warn: true, }; } + if (pick.unreadable !== undefined) { + return stance.mode === "enforce" + ? { + refuse: `Model policy refused this call (fail closed): ${pick.unreadable}. Allowed: ${modelPolicyRowsText(stance.allow)}.`, + } + : { + note: `Model policy (advise): ${pick.unreadable}, so this call was not checked; it runs, and enforce would refuse it.`, + warn: true, + }; + } const verdict = checkModelPolicyPick(stance.allow, pick); if (verdict.inside) { const useFor = verdict.row.useFor; @@ -124,7 +158,8 @@ export function answerPick( ? {} : { note: `Model policy: ${verdict.row.model} is for ${useFor}.` }; } - const allowed = `Allowed: ${modelPolicyRowsText(stance.allow)}.`; + const allowed = + pick.allowedText?.(stance.allow) ?? `Allowed: ${modelPolicyRowsText(stance.allow)}.`; const why = pick.aliasOf === undefined || pick.model === undefined ? verdict.why @@ -280,6 +315,8 @@ const pickOfRemote = ( // What any list here describes for the model: the driver there is not known. describedOptionIds: describedIds(lists, listed), ...(ultracodeByDefault(lists, listed, options) ? { ultracodeMaybeDefault: true } : {}), + // The machine there reads its own list for the ultracode default: a Claude row reads both ways. + ultracodeDefaultUnknown: true, ...(aliasOf === undefined ? {} : { aliasOf }), }; }; @@ -316,8 +353,11 @@ export const makePickCheck = Effect.gen(function* () { const settings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService); return Effect.fn("ModelPolicyCheck.checkPick")(function* ( route: PolicyRoute, - /** The pick, read only while a policy is on (it may read the providers). */ - readPick: Effect.Effect, + /** + * The pick, read only while a policy is on (it may read the providers); `undefined`: the call + * picks no model (a skill that runs inline and names none), so nothing is checked or logged. + */ + readPick: Effect.Effect, options: PickCheckOptions = {}, ) { if (Option.isNone(settings)) return undefined; @@ -329,6 +369,7 @@ export const makePickCheck = Effect.gen(function* () { ); if (policy !== undefined && modelPolicyStance(policy).mode === "off") return undefined; const pick = yield* readPick; + if (pick === undefined) return undefined; const answer = answerPick(policy, route, pick); const annotations = { route, diff --git a/apps/server/src/fork/modelPolicyOptions.testkit.ts b/apps/server/src/fork/modelPolicyOptions.testkit.ts index ef092a921c58d..28e72748cdf98 100644 --- a/apps/server/src/fork/modelPolicyOptions.testkit.ts +++ b/apps/server/src/fork/modelPolicyOptions.testkit.ts @@ -82,6 +82,11 @@ export interface OptionCase { const OPTION_FIX = "this option is not allowed while the model policy is on"; const MODEL_FIX = "Pick the model in the model field"; +/** An option that picks an agent or a mode: refused even where the model list describes it. */ +const AGENT_WHY = (id: string) => + `the option ${id} picks an agent or a mode, which brings its own prompt, tools and settings (an agent can carry its own model) that the policy cannot see`; +const AGENT_FIX = + "an option that picks an agent or a mode is not allowed while the model policy is on"; const unreadable = (id: string, model: string) => `the option ${id} is not described for ${model} in this machine's model list and is not an effort id the policy reads`; @@ -101,8 +106,8 @@ export const OPTION_CASES: ReadonlyArray = [ model: ACP_OPTION_MODEL, allowed: { id: "thought_level", value: "high" }, extra: { id: "_t3/session-mode", value: "max" }, - why: unreadable("_t3/session-mode", ACP_OPTION_MODEL), - fix: OPTION_FIX, + why: AGENT_WHY("_t3/session-mode"), + fix: AGENT_FIX, }, { name: "Grok: the agent's native thought_level beside reasoningEffort", diff --git a/apps/server/src/provider/Drivers/ClaudeSkills.ts b/apps/server/src/provider/Drivers/ClaudeSkills.ts index ae020bf40a8c1..6065c0a6610e6 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkills.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkills.ts @@ -33,6 +33,7 @@ type SkillFrontmatter = readonly description?: string; readonly userInvocationOnly?: boolean; readonly userInvocable?: boolean; + readonly record: Record; // Fork: for the model policy's skill check }; /** Claude accepts YAML 1.1 booleans that this YAML 1.2 parser leaves as strings or numbers. */ @@ -95,6 +96,7 @@ function parseSkillFrontmatter(contents: string): SkillFrontmatter { const description = typeof record.description === "string" ? record.description.trim() : ""; return { kind: "parsed", + record, // Fork: the model policy reads context, model and effort from it ...(name ? { name } : {}), ...(description ? { description } : {}), ...(parseFrontmatterBoolean(record["disable-model-invocation"]) === true @@ -106,6 +108,8 @@ function parseSkillFrontmatter(contents: string): SkillFrontmatter { }; } +export { parseSkillFrontmatter }; // Fork: one frontmatter read for skills and the model policy + // A caller-supplied environment is a plain object, without Windows' case-insensitive keys. function windowsEnvironmentValue(environment: NodeJS.ProcessEnv, name: string) { const key = name.toLowerCase(); diff --git a/apps/web/src/components/settings/fork/ModelPolicySettings.tsx b/apps/web/src/components/settings/fork/ModelPolicySettings.tsx index c4d5640480ed4..21c352f822180 100644 --- a/apps/web/src/components/settings/fork/ModelPolicySettings.tsx +++ b/apps/web/src/components/settings/fork/ModelPolicySettings.tsx @@ -194,7 +194,7 @@ export function ModelPolicySettings() { const searchableSetting = useSearchableSetting(); const updateSettings = useUpdateScopedSettings(); const shown = useScopedSettings((settings) => settings.modelPolicy); - const { targets } = useSettingsScope(); + const { targets, target } = useSettingsScope(); const mixed = targetsDiffer(targets, (settings) => settings.modelPolicy); const [editing, setEditing] = useState(false); const unreadableText = mixed ? null : unreadableModelPolicyText(shown); @@ -244,7 +244,7 @@ export function ModelPolicySettings() { const aliasRows = new Map( aliasModelPolicyRows(shown.allow, providers).map(({ row, aliasOf }) => [row, aliasOf]), ); - const marks = personModelPickMarks(shown, picks, providers); + const marks = personModelPickMarks(shown, picks, providers, target?.environmentId); const byDriver = new Map>(); for (const row of shown.allow) byDriver.set(row.driver, [...(byDriver.get(row.driver) ?? []), row]); diff --git a/apps/web/src/components/settings/fork/modelPolicySettings.logic.test.ts b/apps/web/src/components/settings/fork/modelPolicySettings.logic.test.ts index 31eee9bf901c0..edca3baaba710 100644 --- a/apps/web/src/components/settings/fork/modelPolicySettings.logic.test.ts +++ b/apps/web/src/components/settings/fork/modelPolicySettings.logic.test.ts @@ -283,6 +283,41 @@ describe("personModelPickMarks: the outside policy mark (#125)", () => { ).toContain("names no effort under effort"); }); + it("reads the instance of the machine whose settings hold the picks, not another machine's with the same id (#802)", () => { + const acpOn = (environmentId: string, control: string) => ({ + environmentId, + instanceId: "acp", + driver: "acpRegistry", + models: [ + { + slug: "acp-model", + capabilities: { + optionDescriptors: [{ id: control, type: "select", role: "reasoning" }], + }, + }, + ], + }); + // The primary is listed first; the picks are the second machine's. + const both = [acpOn("primary", "effort_level"), acpOn("second", "thought_level")]; + const rows = [{ driver: "acpRegistry", model: "acp-model", efforts: ["high"] }]; + const mark = (environmentId: string) => + personModelPickMarks( + policy("enforce", rows), + { + defaultModelSelection: { + instanceId: "acp", + model: "acp-model", + options: [{ id: "thought_level", value: "high" }], + }, + } as never, + both, + environmentId, + )[0]?.outside; + expect(mark("second")).toBeNull(); + // The primary's list reads only effort_level: thought_level there names no effort. + expect(mark("primary")).toBe("acp-model needs an effort from its row, and the pick names none"); + }); + it("marks nothing while the policy is off or cannot be read; empty rows mark every pick", () => { expect(personModelPickMarks(policy("off"), picks, providers)).toEqual([]); expect( diff --git a/apps/web/src/components/settings/fork/modelPolicySettings.logic.ts b/apps/web/src/components/settings/fork/modelPolicySettings.logic.ts index 0c16218320c99..6dd9a9ad9bcf6 100644 --- a/apps/web/src/components/settings/fork/modelPolicySettings.logic.ts +++ b/apps/web/src/components/settings/fork/modelPolicySettings.logic.ts @@ -214,22 +214,36 @@ export interface PersonModelPickMark { } /** - * The person's own picks, each marked inside or outside the rows. Agents only: these picks - * are never refused; the mark only shows which ones an agent could not make. Empty while the policy - * is off or cannot be read (its warning says so). A pick on an instance no selected environment - * has reads without a driver, so every row naming its model must allow it. + * The person's own picks, marked inside or outside the rows (a mark only; never refused). Empty + * while the policy is off or unreadable. Only `environmentId`'s instances are read (a provider + * without one counts); a pick on an instance it lacks reads without a driver, so every row naming + * its model must allow it. */ export function personModelPickMarks( policy: ModelPolicy, picks: Partial>, - providers: ReadonlyArray, + providers: ReadonlyArray< + ModelPolicyAliasProvider & { + readonly instanceId: string; + readonly environmentId?: string | undefined; + } + >, + environmentId?: string, ): ReadonlyArray { const stance = modelPolicyStance(policy); if (stance.mode === "off" || stance.unreadable) return []; return PERSON_MODEL_PICKS.flatMap(({ key, label }) => { const selection = picks[key]; if (selection === null || selection === undefined) return []; - const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId); + // The machine whose settings hold the picks runs them: its instance, not another machine's + // instance with the same id (the default `claudeAgent` is on every machine). + const provider = providers.find( + (candidate) => + candidate.instanceId === selection.instanceId && + (environmentId === undefined || + candidate.environmentId === undefined || + candidate.environmentId === environmentId), + ); // The effort control the instance's catalog marks, as the server reads an agent's pick. const effortOptionIds = provider === undefined diff --git a/docs/fork/README.md b/docs/fork/README.md index f4a9ee9d3cf18..aa75804df2b76 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -361,9 +361,39 @@ policy too (the link names the agent's thread; a call the owner's client sends t so each machine refuses an agent's pick outside its own rows, whatever the sending machine's policy says. An agent is a caller whose session is bound to a thread; the owner's client has none, and anything that reaches -the server without such a session counts as a person, so the model guard hook is the backstop. A pick is inside when it -names a model by its full id (#128; an alias such as `opus` is not read as its model, and the -refusal names the id to use) that a row of its provider's driver lists (#127) and, for a row with +the server without such a session counts as a person, so the model guard hook is the backstop. +Claude's own Agent tool (Task in older Claude Code) is checked too, as each call is made (#128): T3 +gives every Claude session it opens one PreToolUse hook that reads the policy on each call. The call +must name a model and, for a row with `efforts`, its `effort`. The Agent tool names only aliases +(`sonnet`, `opus`, `haiku`, `fable`): the alias is read as the full id this machine's Claude model +list maps it to, the same id T3 shows for the sub-agent, and a row matches when it names either the +alias (as `delegate_task` reads a row saved as `opus`) or that full id. The refusal says which alias +and effort pass, or that none does and the row's model can still run through `delegate_task`. The +mapping is T3's list for Claude, shared by every Claude instance on the machine; a Claude Code whose +own mapping differs (an older binary, or an alias override in its environment) runs a model the +check did not read. A name the list does not map is read as given (so it matches no row). A +built-in sub-agent type that names no model (one that would run on its own, often smaller, model) is +refused in `enforce`. A `fork` call is read the same way, as the owner decided for every call and +as the model guard reads it, although Claude runs a fork on the session's own model and effort and +ignores the model and effort it names. A skill that starts a sub-agent is checked too, on Claude's +Skill tool: a skill whose frontmatter says `context: fork`, or names `model` or `effort`, must name a +model from the rows in `model` (and its effort in `effort`), read like an Agent call (an alias or a +full id); a skill that runs inline and names neither runs on the session's model and is not checked. +T3 finds the skill as it lists Claude's skills (managed, the config folder's, the project's, and +plugin skills; first name wins). A skill it cannot find or read (one bundled with Claude Code, an MCP +server's, a command, one in another folder or with frontmatter it cannot parse) is refused in +`enforce` and runs with a note in `advise`. `enforce` refuses with the rows, `advise` runs it with a +note to the agent, an inside pick gets its row's `useFor`, and each call is logged as "model policy +pick" with route `Agent` or `Skill`. A check that fails refuses the call; while a policy is on when +the process opens, so does a hook that times out (`onFailure: "block"`). So while a policy is on, +in `advise` too, Claude Code 2.1.295 or newer is required: an older one refuses to open every new +query, with an error that asks to remove `onFailure: "block"` from the hooks (a person cannot; turn +the policy off or update Claude Code). With the policy off it is left out. The hook is fixed +when the Claude process opens: a process started before this version runs without it until T3 +opens a new one (a new profile, a restart). Workflow `agent()` calls are not read here (the script +is code); the model guard reads them. On the MCP routes, a pick is inside when it +names a model as a row names it (#128; an alias such as `opus` is not read as its model there, and +the refusal names the id to use) that a row of its provider's driver lists (#127) and, for a row with `efforts`, names one of them (`ultracode` counts as its own effort; a row without `efforts` allows none) under the option id that driver reads it from (#780): a built-in driver's own id (`effort` for Claude and FX, `reasoningEffort` for Codex, Grok, Kiro and Muse, `variant` for OpenCode, `thinking` @@ -380,7 +410,11 @@ or `ultracode` (#793): a driver can still apply an option the policy does not re checked ones (Kiro's `effortLevel`, Grok's native `thought_level`, an ACP agent's `_t3/session-mode` that the list hides because it repeats the thought levels, or a `model` option written after the model). Such a pick is refused in `enforce` (pick the model in the model field; the option is not -allowed while the policy is on) and reported in `advise`, as the model guard does. So a second +allowed while the policy is on) and reported in `advise`, as the model guard does. An option that +picks an agent or a mode is refused even when the list describes it (#802), as the model guard's +`DRIVER_MODEL_OPTION_IDS` does: OpenCode's `agent` (an OpenCode agent can carry its own model), +Kiro's `mode`, and an ACP `_t3/session-mode` on any driver (each brings its own prompt, tools and +settings the policy cannot see); without a known driver each of them is refused. So a second effort option cannot hide a higher effort, and an option cannot change the model. A pick that leaves the ultracode option out runs at the model's default for it, so a model whose catalog default is ultracode reads as ultracode. Without a known driver (a call for a linked machine; a `driverKind` the agent names is its own claim and is not read), every row naming the model must allow it (the refusal names the drivers @@ -388,7 +422,16 @@ whose rows refuse it), and each row's driver needs the effort under its own id a for an ACP model this machine's catalog does not describe is refused here), every built-in driver's effort option and every control this machine's catalog marks for the model is read too (a decoy cannot hide a higher effort), a model this machine's catalog turns ultracode on for by default is -read both with and without it, and an alias gets the same "name the full id" hint as here. The +read both with and without it, and an alias gets the same "name the full id" hint as here. This +machine knows only its own catalog (#802): the machine there may turn ultracode on by default for a +Claude model where this one does not, so on a Claude row a pick that leaves the ultracode option out +is read both ways too (name `ultracode: false` or `true`); a control only the agent there has is +refused here (this machine cannot tell whether it sets the effort; start that agent here once so its +list describes it). When several instances of one driver here name a model's effort control +differently (two ACP agents listing the same model), the pick must name the effort under each id, +as which instance runs it is not known; the refusal names every id and why. This fails closed: an +instance whose list does not describe one of them refuses it there in turn, so pick a model whose +driver has a fixed effort id, or start the task where one instance runs it. The machine there checks the pick again with its own catalog (#780). In `enforce` a pick outside is refused with the rows; in `advise` it runs, and `delegate_task`'s reply says what `enforce` would refuse (the other routes only log it). A pick inside gets its row's `useFor` in `delegate_task`'s reply. Each checked pick is @@ -403,7 +446,9 @@ a policy change a retry is refused even when the first call already started its task runs on, with no record here). Not checked by the server: a project's default model (`t3_project_create`, `t3_project_update`) and `schedule_task`'s model, which a later run uses; the model guard hook (`fork-kit/model-guard`) refuses an agent's such call in `enforce`. The owner's own picks (in the app, or `t3_thread_launch` from the owner's client) -are never refused; Settings marks the server's model picks outside the rows ("outside policy"). +are never refused; Settings marks the server's model picks outside the rows ("outside policy"), +each read on the instance of the machine whose settings hold it (#802; the default `claudeAgent` is +on every machine, with its own catalog). Left (#731): a `t3_thread_launch` retry with the same key that names no model is not checked again. After a policy change, the retry of an idle launch (one without a message) that adds a message starts diff --git a/fork-kit/model-guard/tests/guard.test.py b/fork-kit/model-guard/tests/guard.test.py index 10e526460085f..87b0a031dc9e1 100644 --- a/fork-kit/model-guard/tests/guard.test.py +++ b/fork-kit/model-guard/tests/guard.test.py @@ -1859,6 +1859,25 @@ def test_driver_effort_ids_are_read_by_the_servers_model_policy(self): self.assertEqual(drivers, model_guard.DRIVER_EFFORT_IDS, 'MODEL_POLICY_DRIVER_EFFORT_IDS and the guard\'s DRIVER_EFFORT_IDS differ: keep them in step') + def test_agent_picking_options_are_the_servers_model_policy_ones(self): + """#802: while a policy is on, the server refuses the options that pick an agent or a mode, as the hook does: its + MODEL_POLICY_AGENT_OPTION_IDS (packages/contracts/src/modelPolicy.ts) is DRIVER_MODEL_OPTION_IDS entry for entry, + and its MODEL_POLICY_SESSION_MODE_OPTION_ID is ACP's session mode (a server test keeps that one ACP's own + constant). Kept here (not in an app test) so app code names no fork-owned path (#254).""" + path = os.path.join(REPO, 'packages', 'contracts', 'src', 'modelPolicy.ts') + with open(path, encoding='utf-8') as f: + source = f.read() + block = re.search(r'\bconst MODEL_POLICY_AGENT_OPTION_IDS[^=]*= \{(.*?)\};', source, re.S) + mode = re.search(r'export const MODEL_POLICY_SESSION_MODE_OPTION_ID = "([^"]+)";', source) + self.assertIsNotNone(block, f'MODEL_POLICY_AGENT_OPTION_IDS not found in {path}: keep the lists in step') + self.assertIsNotNone(mode, f'MODEL_POLICY_SESSION_MODE_OPTION_ID not found in {path}: keep the ids in step') + server = {driver: tuple(re.findall(r'"([^"]+)"', ids)) + for driver, ids in re.findall(r'(\w+): \[([^\]]*)\]', block.group(1))} + self.assertTrue(server, 'MODEL_POLICY_AGENT_OPTION_IDS reads as empty: keep the lists in step') + self.assertEqual(server, model_guard.DRIVER_MODEL_OPTION_IDS, + 'MODEL_POLICY_AGENT_OPTION_IDS and the guard\'s DRIVER_MODEL_OPTION_IDS differ: keep them in step') + self.assertEqual(mode.group(1), model_guard.ACP_SESSION_MODE_ID) + def test_ultracode_maps_like_the_server(self): """The old effort value "ultracode" runs at xhigh with the option "ultracode" on, as T3's shared model code maps it (packages/shared/src/model.ts withLegacyUltracodeEffort).""" diff --git a/packages/contracts/src/modelPolicy.test.ts b/packages/contracts/src/modelPolicy.test.ts index f60cd775ec32e..582822ee65a33 100644 --- a/packages/contracts/src/modelPolicy.test.ts +++ b/packages/contracts/src/modelPolicy.test.ts @@ -382,6 +382,31 @@ describe("one pick against the rows", () => { ).toBe(false); }); + it("a pick read as a full id from the name it gave (namedAs) matches a row naming either", () => { + const high = [{ id: "effort", value: "high" }]; + const aliasRow = [{ ...rows[0]!, model: "opus" }]; + const asOpus = { ...pick("claude-opus-5-5", high), namedAs: "opus" }; + // A row saved with the alias matches the alias the call gave; a full-id row the id it is read as. + expect(checkModelPolicyPick(aliasRow, asOpus)).toMatchObject({ + inside: true, + row: { model: "opus" }, + }); + expect(checkModelPolicyPick(rows, asOpus)).toMatchObject({ + inside: true, + row: { model: "claude-opus-5-5" }, + }); + // Still at the row's efforts, and only the names given: no other alias or id matches. + expect( + checkModelPolicyPick(aliasRow, { ...asOpus, options: [{ id: "effort", value: "max" }] }) + .inside, + ).toBe(false); + expect(checkModelPolicyPick(aliasRow, pick("claude-opus-5-5", high)).inside).toBe(false); + expect( + checkModelPolicyPick(aliasRow, { ...pick("claude-sonnet-5-5", high), namedAs: "sonnet" }) + .inside, + ).toBe(false); + }); + it("reads an unreadable value as enforce, or advise when its own text says advise", () => { const bad = (raw: unknown) => decodeFile(raw); expect(modelPolicyStance(bad({ mode: "advise", allow: "x" }))).toEqual({ @@ -539,6 +564,10 @@ describe("an effort under the id the row's driver reads (#780)", () => { }); }); +/** The refusal's note on a control only a linked machine's agent has. */ +const LINKED_CONTROL = + " (the pick runs on a linked machine: a control only the agent there has is refused here too, as this machine cannot tell whether it sets the effort; start that agent on this machine once so its model list describes it)"; + describe("an option the policy cannot read, while a policy is on (#793 review)", () => { const kiroRows = [{ driver: "kiro", model: "k", efforts: ["high"] }] as never; const acpRows = [{ driver: "acpRegistry", model: "acp-model", efforts: ["high"] }] as never; @@ -586,11 +615,19 @@ describe("an option the policy cannot read, while a policy is on (#793 review)", for (const known of [driver, undefined]) { // Runs again: the same verdict. for (const _ of [1, 2]) { - expect(checkModelPolicyPick(rows, { ...pick, driver: known }), name).toEqual({ - inside: false, - why: `the option ${unreadable} is not described for ${pick.model} in this machine's model list and is not an effort id the policy reads, so the driver could apply it unchecked`, - fix: "option", - }); + expect(checkModelPolicyPick(rows, { ...pick, driver: known }), name).toEqual( + unreadable === "_t3/session-mode" + ? { + inside: false, + why: "the option _t3/session-mode picks an agent or a mode, which brings its own prompt, tools and settings (an agent can carry its own model) that the policy cannot see", + fix: "agent-option", + } + : { + inside: false, + why: `the option ${unreadable} is not described for ${pick.model} in this machine's model list and is not an effort id the policy reads, so the driver could apply it unchecked${known === undefined ? LINKED_CONTROL : ""}`, + fix: "option", + }, + ); } const without = pick.options.filter((option) => option.id !== unreadable); expect( @@ -684,3 +721,131 @@ describe("modelPolicyAliasTargets", () => { expect(modelPolicyAliasTargets(lists, OPUS)).toEqual([]); }); }); + +describe("#802: what the sending machine cannot know, and options that pick an agent", () => { + const OPUS = "claude-opus-5-5"; + const rows = MODEL_POLICY_START_ROWS; + const options = (...pairs: ReadonlyArray) => + pairs.map(([id, value]) => ({ id, value })); + + it("a pick for a linked machine that leaves ultracode out reads both ways on a Claude row", () => { + const remote = (...pairs: ReadonlyArray) => ({ + driver: undefined, + model: OPUS, + options: options(...pairs), + ultracodeDefaultUnknown: true, + }); + // The machine there may turn ultracode on by default; its row does not allow ultracode. + for (const _ of [1, 2]) { + expect(checkModelPolicyPick(rows, remote(["effort", "high"]))).toEqual({ + inside: false, + why: `the pick leaves the option ultracode out, and the machine that runs it may turn ultracode on by default for ${OPUS} (its model list is not read here), which its claudeAgent row does not allow`, + fix: "ultracode", + }); + } + // Naming the option settles it, either way the row allows. + expect( + checkModelPolicyPick(rows, remote(["effort", "high"], ["ultracode", false])), + ).toMatchObject({ inside: true }); + expect(checkModelPolicyPick(rows, remote(["effort", "high"], ["ultracode", true])).inside).toBe( + false, + ); + const ultracodeToo = [ + { driver: "claudeAgent", model: OPUS, efforts: ["high", "ultracode"] }, + ] as never; + expect(checkModelPolicyPick(ultracodeToo, remote(["effort", "high"]))).toMatchObject({ + inside: true, + }); + // A known driver reads its own catalog's default (pickOfSelection), and another driver's row + // has no ultracode: the field changes neither. + expect( + checkModelPolicyPick(rows, { ...remote(["effort", "high"]), driver: "claudeAgent" }), + ).toMatchObject({ inside: true }); + const codexRows = [{ driver: "codex", model: "gpt", efforts: ["high"] }] as never; + expect( + checkModelPolicyPick(codexRows, { + ...remote(["reasoningEffort", "high"]), + model: "gpt", + }), + ).toMatchObject({ inside: true }); + }); + + it("several effort ids for one driver: the refusal names each and why (fail closed)", () => { + const acpRows = [{ driver: "acpRegistry", model: "acp-model", efforts: ["high"] }] as never; + const pick = (...pairs: ReadonlyArray) => ({ + driver: undefined, + model: "acp-model", + options: options(...pairs), + driverEffortIds: { acpRegistry: ["thought_level", "effort_level"] }, + }); + expect(checkModelPolicyPick(acpRows, pick(["thought_level", "high"]))).toEqual({ + inside: false, + why: "acp-model names no effort under effort_level, the option acpRegistry reads it from (left out, the driver runs its default level); acpRegistry reads acp-model's effort from each of thought_level, effort_level here (its instances' model lists name the control differently), and which instance runs the pick is not known, so the pick must name every one (an instance whose list does not describe an id refuses it in turn: pick a model whose driver has a fixed effort id, or start the task where one instance runs it)", + }); + expect( + checkModelPolicyPick(acpRows, pick(["thought_level", "high"], ["effort_level", "high"])), + ).toMatchObject({ inside: true }); + }); + + it("refuses an option that picks an agent or a mode while the policy is on, even when described", () => { + const agentText = (id: string) => ({ + inside: false, + why: `the option ${id} picks an agent or a mode, which brings its own prompt, tools and settings (an agent can carry its own model) that the policy cannot see`, + fix: "agent-option", + }); + const opencodeRows = [{ driver: "opencode", model: "oc", efforts: ["high"] }] as never; + const opencode = (driver: string | undefined, ...extra: ReadonlyArray<[string, unknown]>) => + checkModelPolicyPick(opencodeRows, { + driver, + model: "oc", + options: options(["variant", "high"], ...extra), + describedOptionIds: ["variant", "agent"], + }); + for (const driver of ["opencode", undefined]) { + expect(opencode(driver, ["agent", "build"])).toEqual(agentText("agent")); + expect(opencode(driver)).toMatchObject({ inside: true }); + } + // A described ACP session mode (its modes are not a copy of the thought levels), any driver. + const acpRows = [{ driver: "acpRegistry", model: "acp-model", efforts: ["high"] }] as never; + for (const driver of ["acpRegistry", undefined]) { + expect( + checkModelPolicyPick(acpRows, { + driver, + model: "acp-model", + options: options(["thought_level", "high"], ["_t3/session-mode", "plan"]), + driverEffortIds: { acpRegistry: ["thought_level"] }, + describedOptionIds: ["thought_level", "_t3/session-mode"], + }), + ).toEqual(agentText("_t3/session-mode")); + } + // Kiro mode: on Kiro, and on a pick whose driver is not known; another driver's own `mode` + // stays an ordinary option. + const kiroRows = [{ driver: "kiro", model: "k", efforts: ["high"] }] as never; + for (const driver of ["kiro", undefined]) { + expect( + checkModelPolicyPick(kiroRows, { + driver, + model: "k", + options: options(["reasoningEffort", "high"], ["mode", "x"]), + describedOptionIds: ["reasoningEffort", "mode"], + }), + ).toEqual(agentText("mode")); + } + expect( + checkModelPolicyPick([{ driver: "codex", model: "gpt", efforts: ["high"] }] as never, { + driver: "codex", + model: "gpt", + options: options(["reasoningEffort", "high"], ["mode", "x"]), + describedOptionIds: ["reasoningEffort", "mode"], + }), + ).toMatchObject({ inside: true }); + // Settings' marks (no described ids): not checked, as before. + expect( + checkModelPolicyPick(opencodeRows, { + driver: "opencode", + model: "oc", + options: options(["variant", "high"], ["agent", "build"]), + }), + ).toMatchObject({ inside: true }); + }); +}); diff --git a/packages/contracts/src/modelPolicy.ts b/packages/contracts/src/modelPolicy.ts index 8e1ec8dcf4aa2..c920aa6f33851 100644 --- a/packages/contracts/src/modelPolicy.ts +++ b/packages/contracts/src/modelPolicy.ts @@ -170,6 +170,18 @@ const MODEL_POLICY_DRIVER_EFFORT_IDS: Readonly> = { const MODEL_POLICY_OPENCODE_NO_VARIANT = "t3:default"; /** The ultracode option, and the effort name the policy gives it: it runs at xhigh in ultracode. */ const MODEL_POLICY_ULTRACODE = "ultracode"; +/** The only driver with the ultracode option (the Claude driver reads the catalog's default for it). */ +const MODEL_POLICY_ULTRACODE_DRIVER = "claudeAgent"; +/** + * Options that pick an agent or a mode (own prompt, tools, settings, maybe model): refused while a + * policy is on, even when described. The model guard's `DRIVER_MODEL_OPTION_IDS` and ACP's + * `ACP_SESSION_MODE_OPTION_ID`; the model guard's test and a server test keep them in step. + */ +const MODEL_POLICY_AGENT_OPTION_IDS: Readonly>> = { + kiro: ["mode"], + opencode: ["agent"], +}; +export const MODEL_POLICY_SESSION_MODE_OPTION_ID = "_t3/session-mode"; /** One pick of a model, as a call or a setting names it. */ export interface ModelPolicyPick { @@ -192,12 +204,24 @@ export interface ModelPolicyPick { * way, so both readings count, the one with ultracode and the one without. */ readonly ultracodeMaybeDefault?: boolean | undefined; + /** + * The pick leaves the ultracode option out and runs on a machine whose model list is not read here + * (a pick for a linked machine): that list may turn ultracode on by default for the model, so a + * Claude row reads it both ways, with ultracode and without. Naming the option settles it. + */ + readonly ultracodeDefaultUnknown?: boolean | undefined; /** * The option ids the checking machine's model lists describe for the model. When set, any other * option the policy does not read as an effort is refused: the driver may still apply it (Kiro's * `effortLevel`, a hidden `_t3/session-mode`, a `model` option). Unset (Settings): not checked. */ readonly describedOptionIds?: ReadonlyArray | undefined; + /** + * The name the call gave, when the check reads it as another id in `model`: Claude's Agent tool + * names only aliases (`opus`), read as the full id this machine maps it to. A row naming either + * matches, so a row naming the alias matches it as on the MCP routes, which read a name as given. + */ + readonly namedAs?: string | undefined; } /** @@ -361,6 +385,9 @@ const rowAllows = (row: ModelPolicyRow, efforts: ReadonlyArray) => ? efforts.length === 0 : efforts.length > 0 && efforts.every((effort) => row.efforts!.includes(effort)); +/** What fixes a refused pick, when it is not "name a model in the rows" ({@link ModelPolicyVerdict}). */ +export type ModelPolicyFix = "option" | "model-option" | "effort-id" | "agent-option" | "ultracode"; + export type ModelPolicyVerdict = | { readonly inside: true; readonly row: ModelPolicyRow } | { @@ -369,9 +396,10 @@ export type ModelPolicyVerdict = /** * What fixes it, when it is not "name a model in the rows": `option`, leave out an option the * policy cannot read; `model-option`, pick the model in the model field, not in the options; - * `effort-id`, the driver's effort id is not known on this machine. + * `effort-id`, the driver's effort id is not known on this machine; `agent-option`, leave out + * an option that picks an agent or a mode; `ultracode`, name the ultracode option. */ - readonly fix?: "option" | "model-option" | "effort-id"; + readonly fix?: ModelPolicyFix; }; /** @@ -381,6 +409,8 @@ export type ModelPolicyVerdict = */ function unreadableOption(pick: ModelPolicyPick): string | undefined { if (pick.describedOptionIds === undefined) return undefined; + const agentOption = agentPickingOption(pick); + if (agentOption !== undefined) return agentOption; const readable = new Set([ ...pick.describedOptionIds, ...pickEffortIds(pick, true), @@ -389,6 +419,22 @@ function unreadableOption(pick: ModelPolicyPick): string | undefined { return pick.options?.find((option) => !readable.has(option.id))?.id; } +/** + * The first option of a pick that picks an agent or a mode ({@link MODEL_POLICY_AGENT_OPTION_IDS}): + * its driver's own, or every driver's when the driver is not known (a pick for a linked machine). + */ +function agentPickingOption(pick: ModelPolicyPick): string | undefined { + const ids = new Set([ + MODEL_POLICY_SESSION_MODE_OPTION_ID, + ...(pick.driver === undefined + ? Object.values(MODEL_POLICY_AGENT_OPTION_IDS).flat() + : Object.hasOwn(MODEL_POLICY_AGENT_OPTION_IDS, pick.driver) + ? MODEL_POLICY_AGENT_OPTION_IDS[pick.driver]! + : []), + ]); + return pick.options?.find((option) => ids.has(option.id))?.id; +} + /** * Whether one pick is inside the rows: a named model in a row; for a row with efforts, one of them * under the id its driver reads (an id not known here refuses), and none for a row without. With no @@ -411,7 +457,9 @@ export function checkModelPolicyPick( return { inside: false, why: `${model}'s effort option ${unnamed.id} holds no effort name` }; } const rows = allow.filter( - (row) => row.model === model && (pick.driver === undefined || row.driver === pick.driver), + (row) => + (row.model === model || (pick.namedAs !== undefined && row.model === pick.namedAs)) && + (pick.driver === undefined || row.driver === pick.driver), ); if (rows.length === 0) { return { @@ -421,10 +469,18 @@ export function checkModelPolicyPick( } const efforts = modelPolicyPickEfforts(pick); const options = pick.options ?? []; + // The machine that runs it may turn ultracode on by default: a Claude row reads it both ways. + const ultracodeUnknown = + pick.driver === undefined && + pick.ultracodeDefaultUnknown === true && + !options.some((option) => option.id === MODEL_POLICY_ULTRACODE); + const bothWays = ultracodeUnknown + ? modelPolicyPickEfforts({ ...pick, ultracodeMaybeDefault: true }) + : efforts; /** Why one row refuses the pick, or `undefined` when it allows it. */ const refuses = ( row: ModelPolicyRow, - ): { readonly why: string; readonly fix?: "effort-id" } | undefined => { + ): { readonly why: string; readonly fix?: "effort-id" | "ultracode" } | undefined => { if (!rowAllows(row, efforts)) { return { why: @@ -433,6 +489,12 @@ export function checkModelPolicyPick( : `${model} does not allow effort ${efforts.join(" + ")}`, }; } + if (row.driver === MODEL_POLICY_ULTRACODE_DRIVER && !rowAllows(row, bothWays)) { + return { + why: `the pick leaves the option ultracode out, and the machine that runs it may turn ultracode on by default for ${model} (its model list is not read here), which its ${row.driver} row does not allow`, + fix: "ultracode", + }; + } if (row.efforts === undefined) return undefined; // The effort must be under the id the row's driver reads: under another, it runs its default. const own = driverReadIds(pick, row.driver); @@ -445,11 +507,16 @@ export function checkModelPolicyPick( const missing = own.find( (id) => !options.some((option) => option.id === id && typeof option.value === "string"), ); - return missing === undefined - ? undefined - : { - why: `${model} names no effort under ${missing}, the option ${row.driver} reads it from (left out, the driver runs its default level)`, - }; + if (missing === undefined) return undefined; + // Several ids: the model lists of several instances of the driver here name the control + // differently, and which one runs the pick is not known, so each must be named. + const several = + own.length > 1 + ? `; ${row.driver} reads ${model}'s effort from each of ${own.join(", ")} here (its instances' model lists name the control differently), and which instance runs the pick is not known, so the pick must name every one (an instance whose list does not describe an id refuses it in turn: pick a model whose driver has a fixed effort id, or start the task where one instance runs it)` + : ""; + return { + why: `${model} names no effort under ${missing}, the option ${row.driver} reads it from (left out, the driver runs its default level)${several}`, + }; }; const verdicts = rows.map((row) => ({ row, refusal: refuses(row) })); const allowed = verdicts.filter((verdict) => verdict.refusal === undefined); @@ -459,6 +526,13 @@ export function checkModelPolicyPick( // after the checked ones (a second effort id, a hidden session mode, a `model` option). const unreadable = unreadableOption(pick); if (unreadable === undefined) return { inside: true, row }; + if (unreadable === agentPickingOption(pick)) { + return { + inside: false, + why: `the option ${unreadable} picks an agent or a mode, which brings its own prompt, tools and settings (an agent can carry its own model) that the policy cannot see`, + fix: "agent-option", + }; + } return unreadable === "model" ? { inside: false, @@ -467,7 +541,11 @@ export function checkModelPolicyPick( } : { inside: false, - why: `the option ${unreadable} is not described for ${model} in this machine's model list and is not an effort id the policy reads, so the driver could apply it unchecked`, + why: `the option ${unreadable} is not described for ${model} in this machine's model list and is not an effort id the policy reads, so the driver could apply it unchecked${ + pick.driver === undefined + ? " (the pick runs on a linked machine: a control only the agent there has is refused here too, as this machine cannot tell whether it sets the effort; start that agent on this machine once so its model list describes it)" + : "" + }`, fix: "option", }; }