Codex (ChatGPT subscription), OpenCode Zen and Go, and configured API or local providers as session and subagent models, no proxy

A Claude Code mod that runs models from other subscriptions, APIs and local servers as ordinary Claude Code session and subagent models. Claude Code keeps its orchestration, tools, permissions, transcript storage and native agents; the mod answers each routed request with a direct call to the provider you selected. It works inside the normal claude command through supported plugin hooks. Release 0.11.0 removed every mod-owned agent type; Claude Code built-ins and user-supplied agent files remain native. Release 0.12.0 added credential-free web-tier eligibility and configuration diagnostics. Release 0.13.0 preserves more document and image content across provider codecs and reports configured model capabilities, including tool coverage and web tiers, in setup, doctor and status. Release 0.14.0 lets the Agent tool's model argument name any discovered <provider>/<model> id exactly. Release 0.16.0 fixes a false stale-context refusal on successive compactions by comparing like-for-like public history snapshots. Genuine context changes still discard the result. It also avoids starting the persistent inference helper in native-only sessions with no routed providers. Release 0.16.1 excludes runtime Agent lookup enrichment from compaction history identity and adds bounded, read-only recovery of persisted main-session text and completed ordinary native tools when public history is capped. Unsupported or ambiguous context still refuses compaction; see the compaction limits. Release 0.17.0 hands Claude model data instead of plugin guards: no request-size abort, model-switch denial or pre-request tool and effort refusals, so Claude's own accounting, compaction and recovery run. Claude receives the smallest context window among the routed main model and live routed subagents, so subagents compact natively. Subagent rows show the resolved model and effort, a failed child reports its error, and project agent files run as Claude applies them whatever model they name. Release 0.17.1 fills Claude's own model fields instead: every model is a picker row, its real window is its per-model modelSettings.<id>.autoCompactWindow, its effort levels go to CLAUDE_CODE_MODEL_CAPABILITIES, and CLAUDE_CODE_MAX_CONTEXT_TOKENS holds the largest window, all written to ~/.claude/settings.json, which Claude loads when it launches, so Claude compacts each agent at its own model's size. A model reporting under 100000, which Claude does not accept as a per-model window, compacts against the largest window instead. A model first discovered during a session gets its data from the next launch; the running session is not changed. Every subagent row shows its model and effort, and a failed subagent's error stays in its own answer. Release 0.17.2 labels every subagent row with the model Claude runs it on, inherited ones included, in Claude's own order: the Agent call's model, the agent definition's, CLAUDE_CODE_SUBAGENT_MODEL, then the parent's. Release 0.17.3 adds the two variables Claude resolves before that order: an agent in a workflow run takes CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL in place of the call's and the definition's model, and CLAUDE_CODE_SUBAGENT_MODEL_FORCE outranks every other model, so its row shows CLAUDE_CODE_SUBAGENT_MODEL, or the parent's when that is unset. Release 0.17.4 skips description rewrites for first-party workflow agent() spawns, which Claude ignores, while nested agents remain labelled. It documents the native Explore label limit: credential-dependent gateway routing can run Explore on opus for fable or mythos parents while the label shows the parent's model. Release 0.17.4 leaves every permission decision to Claude Code, auto mode included; Claude Code's auto-mode classifier calls its own Claude model directly. Release 0.17.4 retries a Codex WebSocket that closes before completion with 1000, 1001, 1005, 1006, 1011, 1012, 1013 or 1014 on a fresh socket, up to 3 attempts in all, and only before output is committed; every other close code stays permanent. It retires Codex Responses WebSockets before the 60-minute provider limit; a refused connection-limit step is retried on a fresh connection, 2 attempts in all, without replaying tool calls. The manual-seed fixture records wire observations per request and merges them only after each child exits. Release 0.17.5 maps instead of deciding. Model data, search and compaction are mapped onto Claude's own fields, input and result shapes, and the mod no longer gates, bounds or replaces what Claude does with them: WebSearch passes query, both domain lists and mode to the provider and returns Claude's result shape with no query, domain, use-count or source limits and no constraint-based tier skipping (the permission gate, fetch pipeline and destination checks stay until Claude offers a hook for them); web tools run Claude's own where the model, helper or provider approval gives nothing to map, except that a loop whose model was not observed inside a routed conversation is refused visibly. A session whose provider names no title is named by Claude, and an unavailable model.classify model is Claude's to handle. Compaction asks the routed provider only for the summary, with Claude's own prompt over Claude's own conversation, and returns Claude's summary message: no tail selection, clipping, receipts, staleness digests or PreCompact policy skip remain. A provider without a safeguard reviewer answers one unavailable verdict for every call, which Claude settles with its own classifier. Setup and refresh now say that newly written model data takes effect at the next Claude launch. New proofs cover a routed subagent's automatic compaction (foreground, background, cache-heavy, plus a late-data control) and record whether a child's compaction attempt fired, was skipped or failed. Earlier owner/model, capacity, streaming, failure and fork repairs remain. The mod registers no MCP tools and needs no launcher, proxy or gateway.
Routed conversation inference follows its observed owner. Exact provider/model ids are primary; family aliases are optional compatibility. Native agent dispatch, tool execution and permission ceilings remain authoritative. Compaction stays on the same exact active model with no alternate-provider fallback. Web tools alone have an explicit final native Claude fallback.
This is native in-process mod integration, not an external harness and not a claim that every stock inference pipeline is unchanged. Routed compaction and some auxiliary operations are native-like adapters on supported hooks. Hidden engine inference can remain native. See What runs where and Host limits.
Providers:
~/.codex/auth.json): model ids codex/<slug>.~/.claude/rice-multi-models.json: Chat Completions, the OpenAI Responses API, Anthropic Messages, Google Gemini or Bedrock, chosen per model: Ollama, llama.cpp, vLLM, LM Studio, OpenRouter, OpenAI, Anthropic API keys, other clouds. Model ids <provider>/<model> or an alias. See example.rice-multi-models.json./rice-models opencode write declares every model each one serves, in its own protocol, with the key from OpenCode's login.For switching between saved Anthropic OAuth accounts in one session, use the companion rice-session-accounts.
You need Claude Code 2.1.301 or newer and Node.js 22 or newer on the PATH Claude Code starts with. CI covers 2.1.301, 2.1.302 and 2.1.306 on Linux, plus 2.1.302 on native Windows. Install from a terminal:
claude plugin install rice-multi-models --marketplace moabualruz/rice-mods
The helper and its dependencies are bundled; nothing is built or installed inside the plugin cache. Then:
claude as usual and run /rice-models setup. It checks Node and the helper, discovers the models your logins and providers offer, and adds them to the /model picker without touching your other picker rows or settings.codex login; /rice-models setup codex installs a private copy of the Codex CLI if you have none and prints its login command./rice-models approve <provider> (or accept the prompt on first use)./model <id>, for example /model codex/gpt-6.1-sol. /rice-models models lists every discovered id with its reported limits./rice-models setup, /rice-models status and /rice-models doctor report the capability contract for every configured provider model. It covers the configured tool allowlist and provider cap, schema mapping, vision and document handling, known or unknown token bounds, parallel calls, effort, cache and web settings. The report describes this mod's configuration and request mapping, not a vendor certification or a guarantee that a model accepts every schema keyword. Unknown metadata stays unknown. A routed model offered fewer tools than the session has adds a coverage warning. Discovery lists candidates; a real request is what establishes access and quota.
A family is a provider: codex, each declared provider id, or claude for Anthropic's native models.
| You do | What runs |
|---|---|
/model codex/... and ask for a subagent | The subagent runs on the same Codex model |
Agent tool model: haiku, sonnet, opus or fable in a routed session | That tier inside the session's family (see tiers below), not Claude |
Agent tool model argument with an exact discovered id, such as codex/gpt-6.1-sol (see below) | Exactly that model, with no tier mapping |
Agent tool model argument with an id nothing discovered | Refused with the list of valid ids; no subagent starts |
| Built-in agents with their own default (Explore uses haiku) | The session's family |
A custom agent file with model: openrouter/some-model | Exactly that model |
A skill with model: haiku (or another alias) or context: fork | The family of the conversation that runs it |
A skill with model: provider/model | Exactly that model |
| A session on native Claude | Claude Code's own behavior, unchanged |
Claude Code's built-in agents and user-supplied agent files stay native. The mod registers no agent types of its own. Global, project, and plugin agent files keep their frontmatter, aliases, tools, and prompt; a file without model or with a native Claude model keeps Claude Code's normal resolution.
To route a custom agent to an exact model, put its full id in the agent frontmatter, for example model: codex/gpt-6.1-sol. That id reaches the engine unchanged and agent.spawn routes the resulting step. Frontmatter works in every session, routed or native. The main prompt gets a short section listing discovered families and models; no tools are added.
Agent({ model: '<provider>/<model>' }) runs the subagent on exactly that id. The id is any model the mod discovers (a Codex model, a declared provider's model, OpenCode, a local model) or a declared alias, spelled as /rice-models models lists it. There is no tier mapping, wrapper agent or proxy: the engine's own Agent tool starts the subagent on the id.
model schema is the engine's own enum plus every accepted id (with more than 200 ids the enum is dropped for a plain string), and the tool description gets one separated line, derived from discovery at runtime, naming the accepted ids. The engine's own description text is kept as it is. A Claude-native parent sees the same description line, but the API schema it receives is the engine's, so exact ids through Agent.model are meant for routed sessions. Use frontmatter anywhere else.model against four values, but only after the mod's tool.call hook has seen the raw call. The hook records the exact id under the call's tool_use_id (in host session state, so a hot reload keeps it), passes the engine a valid value (haiku) and adds a visible description note naming the exact model and explaining that haiku is validation only. agent.spawn takes the id back, removes the note and runs the subagent on the id. Each parallel call has its own record; a record is removed when its spawn takes it, and when its call ends for any reason.rice-multi-models: Agent model "<id>" is not a model this session can run, so no subagent was started. Valid values: haiku, sonnet, opus, fable, <ids>. A marked spawn whose record is missing is refused, not run as haiku: this Agent call's exact model could not be recovered (no record for it), so it was not run as haiku. An exact id on a fork is refused, because a fork runs on its parent's model. A resumed agent and a workflow agent keep their own model.tool.call hooks before it checks the arguments, which no documentation promises (verified on Claude Code 2.1.302 and 2.1.307). If a later engine checks first, an exact id fails in the engine's own validation with its message, and nothing runs on the wrong model. The Agent permission input still has the carrier value (haiku), but its description visibly names the exact model and permission asks add the exact id to their reason without changing the decision. Transcripts can retain that visible note; the child task description does not. Upstream requests: let tool.describe override input-schema fields that are not pinned, or let Agent.model accept any string that agent.spawn resolves or denies.$.env.get cannot read, so agent.spawn cannot know the resolved child model in that case and the row may show the parent's model. Dispatch remains native.Map tiers to specific models per family in rice-multi-models.json:
{
"tiers": {
"codex": { "haiku": "codex/gpt-6-luna", "opus": "codex/gpt-6.1-sol" },
"openrouter": { "default": "openrouter/qwen3-coder" }
}
}
Use ids from /rice-models models. Without a tier entry, a subagent uses the parent's own model. Entries naming a model from another family are ignored.
| Claude Code feature | In a routed conversation |
|---|---|
| Main and subagent turns | Selected provider, with Claude Code's tools and permissions; each built-in tool with the description and input schema the installed claude sends, and a subagent with the system prompt and tools the engine gives its agent type (see Known limits) |
/compact and automatic compaction | Claude Code's own summary prompt (with your /compact instructions in its slot) over the conversation as Claude holds it, answered by the selected provider with its reported output bound; the engine's own summary message wording, citing the transcript file, as the new transcript; Claude decides when to compact; a failed or unreadable-prompt compaction answers Claude's skip and keeps the original transcript |
| Session titles | Selected provider; where it gives none, Claude's own naming; manual names kept |
| Permission decisions in every mode, including auto | Claude Code's native permission processing and classifier |
| SubagentHandback admission classifier | Claude Code's native classifier; the public plugin API does not route this engine-owned decision |
| WebFetch | Provider-native retrieval where supported, configured fetch services, then native Claude WebFetch LAST; no hidden retrieval after it |
| WebSearch | The native input (query, domain lists, mode) mapped to the selected provider's own search, then your saved search services, then Claude's native search with the session's account; results keep Claude's result shape |
| Visible Stop / SubagentStop prompt hooks | Observed owner's exact model, with the installed host's captured evaluator contract and the owner's transcript; hidden sources and agent evaluators remain native |
model.complete and explicit model.classify | The caller's explicit model, never overwritten by the main model; native choices stay native; omitted classify model keeps its documented native default |
model.fork | Tool-free completion over the last successfully sent main request snapshot; nothing-to-fork when no verified snapshot is available |
| Context meter and automatic compaction threshold | The selected model's reported context window |
These come from what Claude Code exposes to plugins today:
stopReason: null. The public step result has no typed provider-error arm. On 2.1.308 the CLI can still report is_error: false for this unsuccessful plugin response. Native API-error/StopFailure bookkeeping is therefore not equivalent; automation must inspect the stop reason and diagnostic, not infer success from exit status alone. See Host limits.model.* hooks. A skill or command using the normal loop is routed only when its actual turn.step is observed.turn.step, model.complete and model.fork never fired. Only session.compact fires, with the trigger, the loop's agentId, the instructions and the transcript rows, so the routed adapter answers there: once per Claude Code version it runs the installed claude for a few seconds in a throwaway folder against a loopback stub (no network, none of your settings or sessions) to read the engine's own summary prompt and summary-message wording, and keeps them. Nothing of that text is copied into this repository. If it cannot be read, a routed conversation is not compacted and says why. The mapped call sends Claude's prompt over the conversation as Claude holds it and returns Claude's summary message as the new transcript; provider usage comes back as the call's usage. A conversation over the public 4096-row read is recovered from the transcript file under the event's own ids. The mod keeps no receipts, picks no tail and applies no PreCompact policy of its own; stock PreCompact and PostCompact and the collapsed "Compacted" row are not produced by the replacement. A failed or empty summary counts as a failed compaction for Claude's own circuit breaker (the hook lets Claude's summarizer reject on a single message, which it refuses locally without any request), so Claude backs off after three consecutive failures as it does natively; a cancelled summary answers skip. A loop whose model was not observed inside a routed conversation is refused visibly, for compaction and for web tools, so no part of a routed conversation silently reaches the Anthropic account.claude for about a second in a throwaway folder against a loopback stub (no network, none of your settings, plugins or sessions): the engine's first request gives the tools as it sends them, and the stub has it start every agent type it lists, plus a marker agent, in the foreground and in the background, to read each agent's system prompt, the text the engine puts around every subagent prompt (agent files included), and the tools it offers each type. The result is kept in the plugin's store; nothing of that text is copied into this repository. The identity line the engine opens a subagent prompt with is left out, as the main prompt's identity sections are; the subagent's environment and model notice reach it in its transcript, as natively. Without the capture a main step sends the schema table generated for this build and the descriptions the session lists, a routed subagent step is refused rather than run on a made-up prompt, and /rice-models status, doctor and the debug log say so; a failed read is tried again after a minute or at /rice-models refresh. What the capture cannot reach:bypassPermissions.hooks/register.ts 1670 lines1// rice-multi-models: non-Anthropic models as session and subagent models. A model id `codex/<slug>` set with
2// /model, --model or an agent's `model:` is answered here: the request is built from the engine's own
3// transcript, system prompt and tools, the shipped Node helper (dist/helper.mjs) calls
4// the provider, and its stream comes back as the engine's own chunks. Claude models pass through untouched.
5import { atom, read, update } from 'claude-code'
6import type { AgentDisplay, AgentModelOwner } from '../types'
7import type { EngineInterface, ModelCompleteResult, ModelUsage, Origin, Register, TurnStepChunk, TurnStepInput, TurnStepResult } from 'claude-code'
8
9import { AGENT_TOOL, CARRIER_VALUE, agentLabel, classifyCall, emptyCarrier, entryOf, exactModelIds, forgetEntry, markDescription, pickRequested, recordEntry, unmarkDescription, withDescriptionSuffix } from './agent-model'
10import { BUILTIN_AGENTS, HANDBACK_TOOL, identityLine, isFork, toolFilter } from './agents'
11import type { AgentDef } from './agents'
12import { CLAUDE_FAMILY, familyOf, isNativeAlias, spawnDecision, stepModel } from './family'
13import type { FamilyPorts, SpawnDecision, TierMap } from './family'
14import { collectText, helperStep, preferSession, readyLine, sessionHelper, setSessionHelper } from './backend'
15import type { HelperPort } from './backend'
16import { carryFor, remember, withCarry } from './carry'
17import type { Reasoning } from './carry'
18import { CONTINUATION_OFF, continuationSessionPrefix, continuationStatus } from './continuation'
19import type { ContinuationRecord } from './continuation'
20import { clearContinuations, continuationRecords, saveContinuation, withContinuationStore } from './continuation-store'
21import { persistedCompactSource, withUserText } from './compact'
22import { compactionPrompt, isTemplate, summaryBody, summaryMessage } from './native-compaction'
23import type { CompactionTemplate } from './native-compaction'
24import { classifierRequest, isClassifyTemplate } from './native-classify'
25import type { ClassifyTemplate } from './native-classify'
26import { builtinPrompt, isCapture, offeredTools, toolSetKey, toolTable } from './native-tools'
27import type { NativeCapture } from './native-tools'
28import { createMemory } from './memory'
29import { CATALOG_URL, kindCounts, liveIds, opencodeProvider, TIERS } from './opencode'
30import type { Tier } from './opencode'
31import { catalogueRows, nativeModelEnv, nativeModelSettings } from './picker'
32import { NATIVE_MODEL_LIMITATIONS, RELAUNCH_NOTICE, unknownMetadata } from './catalogue'
33import type { ModelCatalogue } from './catalogue'
34import { runtimeConfig } from './catalogue-runtime'
35import type { PickerRow } from './picker'
36import { candidates, discoveryGuidance, limitsReport, modelsReport, withDiscoverySection } from './discovery'
37import type { FamilyLine } from './discovery'
38import type { CandidateRoute } from './discovery'
39import { approvalQuestion, CONFIG_FILE, emptyLoaded, loadText, providerLines, remoteOf, TRUST_PREFIX } from './providers'
40import type { Loaded, Remote } from './providers'
41import { contested, definedModel, definitionOf, rewriteMain, systemFor, withIdentity } from './prompts'
42import type { PromptsPort } from './prompts'
43import { splitTarget } from './protocol'
44import type { ApiMessage, Effort, Limits, RemoteTool, StepRequest, StepWire, Transport } from './protocol'
45import { fingerprint } from './config'
46import { capabilityContracts, formatCapabilityContracts, selectTools, toolCoverageWarning } from './capability-contract'
47import { STAMP } from './schemas.gen'
48import { createAssembler } from './step'
49import { redact } from './redact'
50import { setCapped } from './util'
51import { remoteTools } from './tools'
52import type { Described } from './tools'
53import { handbackState, withTask } from './transcript'
54import { commandText, detectRuntime as probeRuntime, helperFile, setupSummary, startupNotice as publishNotice, syncPicker as synchronizePicker } from './setup'
55import type { PickerPort, PickerResult, Runtime } from './setup'
56import { searchConfigurationCommand } from './search-config'
57import type { SearchConfigurationResult, SearchEdit } from './search-config'
58import { fetchProviderProtocol, fetchTierConfigState } from './fetch-config'
59import type { FetchConfigMetadata } from './fetch-config'
60import { webSearchStatus } from './web-search-status'
61import { runNativeSearch } from './native-search'
62import { NativeFetchUnavailable, runNativeFetch } from './native-fetch'
63import { runFinalNativeFetch } from './web-fetch-fallback'
64import type { ToolSearchOutcome } from '../helper/search/tool-search'
65import type { WebFetchOutcome } from '../helper/web-fetch'
66import { createToolGate } from './tool-gate'
67import type { PublicWebSearchInput } from './web-search'
68import type { PublicWebFetchInput } from './web-fetch'
69import { titleAnswer, titleRequest } from './titles'
70import { registerEvaluators } from './evaluator-runtime'
71import type { EvaluatorCapacityPort } from './evaluator-runtime'
72import { createEvaluatorSources, registerEvaluatorSources } from './evaluator-sources'
73
74const PLUGIN = 'rice-multi-models'
75/** Who the requests to declared providers say they come from (OpenCode Go asks each client to name itself). */
76const USER_AGENT = 'rice-multi-models/0.17.5 (claude-code)'
77const PROVIDERS: Readonly<Record<string, string>> = { codex: 'OpenAI Codex (ChatGPT subscription)' }
78const EFFORTS: readonly Effort[] = ['low', 'medium', 'high', 'xhigh', 'max']
79const prefsAtom = atom({ plugin: 'rice-multi-models', key: 'prefs' } as const, { effort: null, transport: 'auto', helper: 'session' })
80/** Exact Agent model ids carried from a call's tool.call to its agent.spawn (see agent-model.ts), by tool_use_id; host state, so a hot reload keeps it. */
81const carrierAtom = atom({ plugin: 'rice-multi-models', key: 'agent-model-carrier' } as const, emptyCarrier)
82const ownersAtom = atom({ plugin: 'rice-multi-models', key: 'agent-model-owners' } as const, { entries: [] as readonly AgentModelOwner[] })
83const agentDisplayAtom = atom({ plugin: 'rice-multi-models', key: 'agent-display' } as const, { entries: [] as readonly AgentDisplay[] })
84/** The main transcript's file, as the engine's classic hooks name it; a compaction cites it in its summary message. */
85const transcriptAtom = atom({ plugin: 'rice-multi-models', key: 'transcript' } as const, { path: null })
86
87const memory = createMemory()
88const described = new Map<string, Described>()
89/** The model each subagent loop last ran on, for its compaction. */
90const agentModels = new Map<string, string>()
91const webToolGate = createToolGate()
92/** Agent definitions observed from Claude Code or user plugins, by their full type name. */
93const registered = new Map<string, AgentDef>()
94let runtime: Runtime = {}
95let helperSupervision: Promise<void> | undefined
96let helperReadiness: Promise<void> | undefined
97let codexDefaults: { model?: string; effort?: Effort } = {}
98let limits: Limits | undefined
99let lastStep: { model: string; who: string; ms: number; transport: string } | undefined
100/** The main model last recorded for this session, so a resume on another model can say so once. */
101let recordedMainModel: string | undefined
102/** The main conversation's last request effort, so a subagent that inherits it can show it. */
103let mainEffort: string | number | undefined
104const LAST_MODELS = 'last-main-models'
105/** How each spawned agent's model was decided, by its agent id. */
106const spawnDecisions = new Map<string, SpawnDecision>()
107let limitsObservedAt: number | undefined
108let declared: Loaded = emptyLoaded(CONFIG_FILE)
109let loaded: Loaded = declared
110let catalogue: ModelCatalogue = { models: [], providers: [] }
111let catalogueCheckedAt: number | undefined
112let capacityExpiresAt: number | undefined
113let catalogueRefresh: Promise<void> | undefined
114const CAPACITY_MAX_AGE_MS = 5 * 60_000
115let compactionTemplate: Promise<CompactionTemplate> | undefined
116/** The installed claude's tool definitions and agent prompts, per combination of the session's built-in tools (toolSetKey). */
117const toolCaptures = new Map<string, Promise<NativeCapture>>()
118const readyCaptures = new Map<string, NativeCapture>()
119/** The last failed capture, which is not retried for a minute (or until /rice-models refresh). */
120let toolCaptureFailure: { at: number; error: string } | undefined
121const TOOL_CAPTURE_RETRY_MS = 60_000
122/** The capture failures already written to the debug log. */
123const reportedToolFallbacks = new Set<string>()
124/** Whether this session is interactive, as its start said: an interactive session's subagents get the background tool set. */
125let interactiveSession: boolean | undefined
126/** Whether each spawned agent runs in the background, by its agent id. */
127const spawnBackground = new Map<string, boolean>()
128let seenTranscriptPath: string | undefined
129
130/** Immutable last dispatched routed main request prefix, never reconstructed from current context. */
131let mainSnapshot: StepRequest | undefined
132let lastContinuationStatus = 'not used'
133let continuationExpiredRecords = 0
134
135function activeContext(model: string) {
136 const route = splitTarget(model)
137 const target = remoteOf(loaded, model)?.target ?? (route ? `${route.provider}/${route.model}` : model)
138 const provider = target.slice(0, target.indexOf('/'))
139 if (!isRouted(model) || !catalogue.providers.some(entry => entry.provider === provider && entry.status === 'fresh')) return undefined
140 return catalogue.models.find(entry => entry.model === target && entry.execution === 'native provider')?.metadata
141}
142
143function outputLimit(model: string): number {
144 const configured = remoteOf(loaded, model)?.model.maxOutputTokens
145 const reported = activeContext(model)?.outputTokenLimit
146 const bounds = [configured, reported].filter((value): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value > 0)
147 return bounds.length ? Math.min(...bounds) : 2048
148}
149
150function defaultModel(provider: string): string | undefined {
151 const models = catalogue.models.filter(model => model.model.startsWith(`${provider}/`))
152 const preferred = provider === 'codex' && codexDefaults.model ? `codex/${codexDefaults.model}` : undefined
153 return models.find(model => model.model === preferred)?.model ?? models[0]?.model
154}
155
156function tiers(): TierMap {
157 return loaded.config?.tiers ?? {}
158}
159
160/** The model a family runs on when no conversation of it anchors the choice. */
161function familyDefault(family: string): string | undefined {
162 const configured = tiers()[family]?.default
163 if (configured && isRouted(configured)) return configured
164 return defaultModel(family)
165}
166
167const familyPorts: FamilyPorts = {
168 isRouted: model => isRouted(model),
169 providerOf: model => targetOf(model)?.provider,
170 defaultModel: family => familyDefault(family),
171}
172
173/** Native provider families with a fresh catalogue. */
174function routedFamilies(): string[] {
175 const fresh = new Set(catalogue.providers.filter(provider => provider.status === 'fresh').map(provider => provider.provider))
176 const families = new Set<string>()
177 for (const entry of catalogue.models) {
178 if (entry.execution !== 'native provider') continue
179 const family = entry.model.slice(0, entry.model.indexOf('/'))
180 if (family && fresh.has(family)) families.add(family)
181 }
182 return [...families].sort()
183}
184
185function familyLines(): FamilyLine[] {
186 const lines: FamilyLine[] = routedFamilies().map(family => ({
187 family, label: PROVIDERS[family] ?? family, model: familyDefault(family),
188 tiers: Object.fromEntries(Object.entries(tiers()[family] ?? {}).filter(([tier]) => tier !== 'default')),
189 }))
190 return lines.length ? [...lines, { family: CLAUDE_FAMILY, label: 'Claude (Anthropic)' }] : []
191}
192
193async function discoverCapacity(port: EvaluatorCapacityPort): Promise<void> {
194 const source = 'session capacity discovery'
195 const configured = declared
196 if (!runtime.executable || runtime.error) {
197 catalogue = { models: [], providers: [{ provider: 'runtime', status: 'unavailable', source, error: 'helper-unavailable' }] }
198 } else {
199 try {
200 const result = await port.run([runtime.executable, port.helper, 'discover'], { stdin: JSON.stringify({ configText: configured.text, approved: port.approved }), timeoutMs: 15_000 })
201 if (result.exitCode !== 0 || declared !== configured) throw new Error('helper-failed-or-configuration-changed')
202 const snapshot = JSON.parse(result.stdout) as ModelCatalogue
203 if (!Array.isArray(snapshot.models) || !Array.isArray(snapshot.providers)) throw new Error('protocol-invalid')
204 const now = port.now
205 // Discovery is optional, but old or invalid observations cannot inflate capacity.
206 catalogue = { ...snapshot, models: snapshot.models.map(entry => Number.isSafeInteger(entry.observedAt) && entry.observedAt <= now + 60_000 && now - entry.observedAt <= CAPACITY_MAX_AGE_MS ? entry : { ...entry, metadata: unknownMetadata() }) }
207 } catch {
208 catalogue = { models: [], providers: [{ provider: 'runtime', status: 'unavailable', source, error: 'discovery-helper-failed' }] }
209 }
210 }
211 catalogueCheckedAt = port.now
212 const expiries = catalogue.models.filter(entry => Number.isSafeInteger(entry.observedAt) && entry.observedAt + CAPACITY_MAX_AGE_MS > port.now).map(entry => entry.observedAt + CAPACITY_MAX_AGE_MS)
213 capacityExpiresAt = Math.min(port.now + CAPACITY_MAX_AGE_MS, ...expiries)
214 loaded = runtimeConfig(declared, catalogue)
215}
216
217/** A new catalogue; its native data reaches Claude through the picker sync that follows (see syncPicker). */
218async function refreshCatalogue($: EngineInterface): Promise<void> {
219 await discoverCapacity({ now: await $.clock.now(), helper: helperFile($.plugin.root), approved: [...await approvedSet($)], run: (argv, options) => $.process.run(argv, options) })
220}
221
222/** The catalogue whose model data was last handed to the settings sync, whichever path discovered it. */
223let publishedCatalogue: ModelCatalogue | undefined
224
225/** Shared by routed requests and prompt evaluators: a discovery here writes its model data for Claude's next launch. */
226async function refreshCapacity(port: EvaluatorCapacityPort): Promise<void> {
227 if (catalogueCheckedAt !== undefined && capacityExpiresAt !== undefined && port.now >= catalogueCheckedAt && port.now < capacityExpiresAt) return
228 catalogueRefresh ??= discoverCapacity(port).finally(() => { catalogueRefresh = undefined })
229 await catalogueRefresh
230 if (catalogue !== publishedCatalogue) {
231 await publishModelData({ helper: port.helper, run: async (argv, options) => ({ stderr: '', ...await port.run(argv, { stdin: options?.stdin ?? '', timeoutMs: options?.timeoutMs ?? 10_000 }) }) }, runtime, routedRows())
232 }
233}
234
235async function ensureFreshCapacity($: EngineInterface): Promise<void> {
236 await refreshCapacity({ now: await $.clock.now(), helper: helperFile($.plugin.root), approved: [...await approvedSet($)], run: (argv, options) => $.process.run(argv, options) })
237}
238
239/** Each configured alias and the `provider/model` it names, so the alias id carries its target's native data. */
240function aliasTargets(): Record<string, string> {
241 return Object.fromEntries(Object.entries(loaded.config?.aliases ?? {}).map(([name, alias]) => [name, alias.target]))
242}
243
244/** Engine calls stay in this module; imported setup logic receives plain values and callable ports. */
245async function detectRuntime($: EngineInterface): Promise<Runtime> {
246 return probeRuntime({
247 helper: helperFile($.plugin.root),
248 override: await $.env.get('RICE_MULTI_MODELS_NODE'),
249 run: (argv, options) => $.process.run(argv, options),
250 exists: path => $.fs.exists(path),
251 })
252}
253
254/** Picker rows, per-model settings and the env block, all in ~/.claude/settings.json, which Claude loads at launch. */
255/** The picker rows, per-model settings and env block of the current catalogue, for Claude's next launch. */
256function publishModelData(port: PickerPort, current: Runtime, rows: PickerRow[]): Promise<PickerResult> {
257 publishedCatalogue = catalogue
258 return synchronizePicker(port, current, rows, nativeModelSettings(catalogue, aliasTargets()), nativeModelEnv(catalogue, aliasTargets()))
259}
260
261async function syncPicker($: EngineInterface, current: Runtime, rows: PickerRow[]): Promise<PickerResult> {
262 return publishModelData({ helper: helperFile($.plugin.root), run: (argv, options) => $.process.run(argv, options) }, current, rows)
263}
264
265async function startupNotice($: EngineInterface, interactive: boolean, current: Runtime, picker: PickerResult | undefined, rows: PickerRow[], defaultModel: string | undefined, catalogueSummary?: string, capabilities?: string): Promise<void> {
266 return publishNotice({
267 get: key => $.store.get(key),
268 set: (key, value) => $.store.set(key, value),
269 log: text => $.ui.log(text, { to: 'transcript' }),
270 }, interactive, current, picker, rows, defaultModel, catalogueSummary ?? catalogue.providers.map(provider => `${provider.provider}: ${provider.status}${provider.error ? ` (${provider.error})` : ''}`).join('; '), capabilities)
271}
272
273/** Whether a model name is answered here: a Codex id, or a declared provider's model or alias. */
274export function isRouted(model: string | undefined): model is string {
275 if (!model) return false
276 const target = splitTarget(model)
277
278 return (target !== null && Object.hasOwn(PROVIDERS, target.provider)) || remoteOf(loaded, model) !== undefined
279}
280
281/** Whether the conversation is a routed one: its main model is answered here. */
282async function routedConversation($: EngineInterface): Promise<boolean> {
283 try { return isRouted(await $.session.model()) } catch { return false }
284}
285
286/** Why a model this mod's configuration names cannot run, so it is never sent to Claude instead. */
287function claimedRefusal(model: string): string | undefined {
288 const id: string | undefined = model
289 if (isRouted(id)) return undefined
290 const claimed = loaded.claimed ?? declared.claimed ?? []
291 const slash = model.indexOf('/')
292 if (!claimed.includes(model) && !(slash > 0 && claimed.includes(model.slice(0, slash)))) return undefined
293 return `${PLUGIN}: ${model} is declared in ${CONFIG_FILE}, which does not validate (${(declared.errors[0] ?? loaded.errors[0] ?? 'unknown error')}); fix it and run /rice-models reload. Nothing was sent.`
294}
295
296/** The provider and model a routed name stands for, an alias resolved. */
297function targetOf(model: string): { provider: string; model: string; label: string; remote?: Remote } | null {
298 const remote = remoteOf(loaded, model)
299 if (remote) return { provider: remote.provider.id, model: remote.modelId, label: remote.provider.id, remote }
300 const target = splitTarget(model)
301
302 return target ? { ...target, label: PROVIDERS[target.provider] ?? target.provider } : null
303}
304
305async function loadProviders($: EngineInterface): Promise<void> {
306 const dir = (await $.env.get('CLAUDE_CONFIG_DIR')) || `${(await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || ''}/.claude`
307 const path = `${dir}/${CONFIG_FILE}`
308 declared = (await $.fs.exists(path)) ? loadText(path, await $.fs.read(path)) : emptyLoaded(path)
309 loaded = runtimeConfig(declared, catalogue)
310}
311
312async function approvedSet($: EngineInterface): Promise<Set<string>> {
313 const keys = (await $.store.keys()).filter(key => key.startsWith(TRUST_PREFIX))
314 const grants = await Promise.all(keys.map(async key => await $.store.get(key) === true ? key.slice(TRUST_PREFIX.length) : undefined))
315 return new Set(grants.filter((grant): grant is string => grant !== undefined))
316}
317
318/** Undefined once the provider is approved (asked here the first time), else why the step is not sent. */
319async function approval($: EngineInterface, remote: Remote): Promise<string | undefined> {
320 if ((await approvedSet($)).has(remote.fingerprint)) return undefined
321 try {
322 const answer = await $.ui.ask(approvalQuestion(remote.provider), { options: ['Allow', 'Keep it off'], header: 'rice-models' })
323 if (answer === 'Allow') {
324 await $.store.set(`${TRUST_PREFIX}${remote.fingerprint}`, true)
325
326 return undefined
327 }
328
329 return `${remote.provider.id} was not approved; nothing was sent`
330 } catch {
331 return `${remote.provider.id} is not approved yet; run /rice-models approve ${remote.provider.id}. Nothing was sent`
332 }
333}
334
335/** What the helper gets with a step: the config's text and the approved fingerprints. */
336async function wireFor($: EngineInterface, req: StepRequest): Promise<StepWire> {
337 const maxTokens = req.native?.maxTokens ?? outputLimit(req.target)
338 if (maxTokens > outputLimit(req.target)) throw new Error('The requested output cap exceeds the active model output limit.')
339 // Readiness also marks an exhausted supervisor; do not restart it per dispatch.
340 if (helperReadiness === undefined) await ensureHelper($)
341 return { configText: loaded.text, approved: [...(await approvedSet($))], req: { ...req, native: { ...req.native, maxTokens } }, userAgent: USER_AGENT }
342}
343
344function limitsText(): string | undefined {
345 if (!limits || limits.windows.length === 0) return undefined
346
347 return `codex ${limits.windows.map(window => `${window.label} ${Math.round(window.usedPercent)}%`).join(' ')}`
348}
349
350function promptsPort($: EngineInterface): PromptsPort {
351 return {
352 compose: async (model, tools) => (await $.prompt.compose({ model, tools })).sections,
353 cwd: () => $.session.cwd(),
354 configDir: async () => (await $.env.get('CLAUDE_CONFIG_DIR')) || `${(await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || ''}/.claude`,
355 exists: path => $.fs.exists(path),
356 read: path => $.fs.read(path),
357 listDir: async dir => ((await $.fs.exists(dir)) ? (await $.fs.list(dir)).map(entry => ({ name: entry.name, kind: entry.kind })) : []),
358 run: async (argv, options) => {
359 try {
360 return await $.process.run(argv, { timeoutMs: options?.timeoutMs ?? 10_000 })
361 } catch {
362 return { exitCode: 127, stdout: '', stderr: '' }
363 }
364 },
365 now: () => $.clock.now(),
366 debug: text => $.ui.log(`${PLUGIN}: ${text}`, { to: 'debug' }),
367 }
368}
369
370function helperPort($: EngineInterface, timeoutMs?: number): HelperPort {
371 async function* bounded(argv: string[], input: string) {
372 const result = await $.process.run(argv, { stdin: input, timeoutMs: Math.min(timeoutMs!, 600_000) })
373 if (result.isStdoutTruncated) throw new Error('routed auxiliary response exceeded the bounded capture size')
374 if (result.stdout) yield { stream: 'stdout' as const, text: result.stdout }
375 return { code: result.exitCode, signal: null }
376 }
377 return {
378 once: input => {
379 if (!runtime.executable || runtime.error) throw new Error(runtime.error || 'Node.js 22+ helper unavailable; /rice-models setup repair')
380 return timeoutMs === undefined ? $.process.spawn({ argv: [runtime.executable, helperFile($.plugin.root), 'once'], input }) : bounded([runtime.executable, helperFile($.plugin.root), 'once'], input)
381 },
382 client: (input, socketPath) => {
383 if (!runtime.executable || runtime.error) throw new Error(runtime.error || 'Node.js 22+ helper unavailable; /rice-models setup repair')
384 return timeoutMs === undefined ? $.process.spawn({ argv: [runtime.executable, helperFile($.plugin.root), 'client', socketPath], input }) : bounded([runtime.executable, helperFile($.plugin.root), 'client', socketPath], input)
385 },
386 }
387}
388
389/**
390 * Keeps the session helper running for the session's life: started here, announced on its standard output,
391 * started again when it exits, and given up (one process per step from then on) after three exits within a
392 * minute. The loop ends with the module, which ends the helper.
393 */
394async function superviseHelper($: EngineInterface, announce: () => void): Promise<void> {
395 let exits: number[] = []
396 while (runtime.executable && !runtime.error) {
397 let buffer = ''
398 try {
399 for await (const piece of $.process.spawn({ argv: [runtime.executable, helperFile($.plugin.root), 'serve'] })) {
400 if (piece.stream !== 'stdout' || sessionHelper()) continue
401 buffer = (buffer + piece.text).slice(-16_000)
402 const ready = readyLine(buffer)
403 if (ready) { setSessionHelper(ready); announce() }
404 }
405 } catch {
406 $.ui.log(`${PLUGIN}: the session helper did not start; using the shipped one-shot helper`, { to: 'debug' })
407 }
408 setSessionHelper(undefined)
409 announce()
410 const now = await $.clock.now()
411 exits = [...exits.filter(at => now - at < 60_000), now]
412 if (exits.length >= 3) {
413 $.ui.log(`${PLUGIN}: the session helper keeps exiting; each step starts its own helper now`, { to: 'debug' })
414 return
415 }
416 await $.clock.sleep(1_000)
417 }
418}
419
420/** One supervisor per loaded module; startup waits a bounded time, never for the helper's lifetime. */
421async function ensureHelper($: EngineInterface): Promise<void> {
422 if (!runtime.executable || runtime.error || (await read($, prefsAtom)).helper === 'once') return
423 if (!helperSupervision) {
424 let announce: () => void = () => {}
425 helperReadiness = new Promise(resolve => { announce = resolve })
426 helperSupervision = superviseHelper($, announce).catch(() => { announce() }).finally(() => { helperSupervision = undefined })
427 }
428 await Promise.race([helperReadiness, $.clock.sleep(1500)])
429}
430
431/** The Codex CLI's own defaults: its model and reasoning effort, from config.toml. */
432async function readCodexDefaults($: EngineInterface): Promise<{ model?: string; effort?: Effort }> {
433 const home = (await $.env.get('CODEX_HOME')) || `${(await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || ''}/.codex`
434 try {
435 const text = await $.fs.read(`${home}/config.toml`)
436 const top = text.split(/^\[/m)[0] ?? ''
437 const model = /^model\s*=\s*"([^"]+)"/m.exec(top)?.[1]
438 const effort = /^model_reasoning_effort\s*=\s*"([^"]+)"/m.exec(top)?.[1]
439
440 return { model, effort: EFFORTS.includes(effort as Effort) ? (effort as Effort) : effort === 'ultra' ? 'max' : undefined }
441 } catch {
442 return {}
443 }
444}
445
446/**
447 * Whose prompt a subagent's step follows: its own agent type's and definition, or for a fork the conversation it
448 * forks, the nearest ancestor that is not a fork (no type when that is main).
449 */
450async function promptOwner($: EngineInterface, agentId: string) {
451 const agents = await $.agent.list()
452 const agent = agents.find(each => each.id === agentId)
453 const fork = agent !== undefined && isFork(agent.type)
454 let source = agent
455 for (let depth = 0; source !== undefined && isFork(source.type) && depth <= agents.length; depth++) {
456 const parent: string | undefined = source.parentId
457 source = parent === undefined ? undefined : agents.find(each => each.id === parent)
458 }
459 const type = fork ? source?.type : agent?.type
460 // A project's agent file is Claude's to apply: its prompt goes to whichever model runs the agent.
461 const def = (type && registered.get(type)) || (await definitionOf(promptsPort($), memory, type))
462 return { agent, fork, type, def, route: fork && type === undefined ? undefined : { type, label: '' } }
463}
464
465/** The request for one routed step: the system prompt, the tools, the transcript with reasoning put back. */
466async function buildRequest($: EngineInterface, e: TurnStepInput, transcript: readonly ApiMessage[]): Promise<{ req: StepRequest; handback?: string }> {
467 const who = e.agentId ?? 'main'
468 const target = targetOf(e.model)
469 if (!target) throw new Error(`${e.model} names no provider`)
470 const provider = target.label
471 const infos = await $.tool.list()
472 const builtins = builtinNames(infos)
473 const io = promptsPort($)
474 // The installed claude's own tool definitions and agent prompts. A main step without them still runs, with the
475 // generated schema table; a subagent's prompt cannot be had without them, so its step is refused (systemFor).
476 const native = e.agentId !== undefined || builtins.length ? await stepTools($, builtins) : undefined
477 // The hook API can list platform tools that the native model request does not receive. When a native capture is
478 // available, it is authoritative for the native surface sent to the provider; retain MCP tools separately.
479 const nativeCapture = native === undefined || native instanceof Error ? undefined : native
480 const modelInfos = nativeCapture === undefined ? infos : [
481 ...nativeCapture.tools.map(tool => infos.find(info => !info.mcp && info.name === tool.name) ?? { name: tool.name, description: tool.description, mcp: false }),
482 ...infos.filter(info => info.mcp && !nativeCapture.tools.some(tool => tool.name === info.name)),
483 ]
484 const names = modelInfos.map(info => info.name)
485 let system: string
486 let allow: (tool: string) => boolean = () => true
487 let messages = transcript
488 let handback: string | undefined
489 if (e.agentId === undefined) {
490 system = rewriteMain((await $.prompt.compose({ model: e.model, tools: names })).sections, identityLine(target.model, provider))
491 } else {
492 const owner = await promptOwner($, e.agentId)
493 // A fork keeps its parent's tool rules. Any other agent is offered what the engine offers its type: in an
494 // interactive session, and for an agent in the background, the background set.
495 const background = interactiveSession !== false || spawnBackground.get(e.agentId) !== false
496 const engineType = owner.def !== undefined ? undefined : BUILTIN_AGENTS.includes(owner.type ?? '') ? owner.type! : 'general-purpose'
497 const engine = native === undefined || native instanceof Error || owner.fork ? undefined : offeredTools(native, engineType, background)
498 allow = owner.fork ? toolFilter(owner.agent?.type, undefined) : toolFilter(owner.type, owner.def, engine)
499 const offered = names.filter(allow)
500 if (handbackState(transcript, HANDBACK_TOOL.name) === 'offered') handback = HANDBACK_TOOL.name
501 const prompt = await systemFor(io, memory, {
502 def: owner.def,
503 route: owner.route && { ...owner.route, label: e.model },
504 fork: owner.fork,
505 engineModel: e.model,
506 target: e.model,
507 model: target.model,
508 provider,
509 tools: handback ? [...offered, handback] : offered,
510 native,
511 })
512 system = prompt.text
513 messages = withTask(messages, owner.agent?.description)
514 }
515 const only = target.remote?.model.tools
516 if (Array.isArray(only)) {
517 const allowed = allow
518 allow = tool => allowed(tool) && only.includes(tool)
519 }
520 messages = withIdentity(messages, target.model, provider)
521 if (loaded.config?.continuation?.mode !== 'durable') messages = withCarry(messages, carryFor(who))
522 const candidates: RemoteTool[] = remoteTools(modelInfos, described, allow, {}, native === undefined || native instanceof Error ? undefined : toolTable(native), exactModelIds(catalogue, loaded))
523 if (handback) candidates.push({ name: HANDBACK_TOOL.name, description: HANDBACK_TOOL.description, schema: { ...HANDBACK_TOOL.schema } })
524 const tools = target.remote ? selectTools(candidates, target.remote.provider, target.remote.model) : candidates
525 if (target.remote) {
526 const warning = toolCoverageWarning(target.remote.target, names.length, tools.length)
527 if (warning && !memory.notes.includes(warning)) {
528 memory.notes.push(warning)
529 $.ui.toast(warning)
530 }
531 }
532 const prefs = await read($, prefsAtom)
533 const effort = routedEffort(e.model, e.effort, prefs.effort) as Effort | number | undefined
534
535 return {
536 req: { target: e.model, system, tools, transcript: messages, ...(effort === undefined ? {} : { effort }), who, session: await $.session.id(), transport: prefs.transport },
537 ...(handback ? { handback } : {}),
538 }
539}
540
541/** Routed failures terminate with the public unsuccessful stop shape, never native-provider replay. */
542function cacheOwner(owner: AgentModelOwner): void {
543 setCapped(agentModels, owner.id, owner.model)
544 setCapped(spawnDecisions, owner.id, { model: owner.model, family: owner.explicitNative ? CLAUDE_FAMILY : splitTarget(owner.model)?.provider ?? 'external', explicit: owner.explicitNative, reason: 'observed native loop ownership' })
545 if (owner.background !== undefined) setCapped(spawnBackground, owner.id, owner.background)
546}
547
548async function rememberOwner($: EngineInterface, id: string, model: string, background?: boolean, effort?: string | number, workflowRunId?: string): Promise<void> {
549 const owner: AgentModelOwner = { id, model, explicitNative: !isRouted(model) && claimedRefusal(model) === undefined, ...(background === undefined ? {} : { background }), ...(effort === undefined ? {} : { effort }), ...(workflowRunId === undefined ? {} : { workflowRunId }) }
550 cacheOwner(owner)
551 await update($, ownersAtom, state => ({ entries: [...state.entries.filter(entry => entry.id !== id), { ...state.entries.find(entry => entry.id === id), ...owner }].slice(-256) }))
552 await update($, agentDisplayAtom, state => ({ entries: state.entries.map(entry => entry.agentId === id ? { ...entry, model, ...(effort === undefined ? {} : { effort }) } : entry) }))
553}
554
555function routedEffort(model: string, explicit?: string | number, preference?: Effort | null): string | number | undefined {
556 return explicit ?? preference ?? (targetOf(model)?.provider === 'codex' && !targetOf(model)?.remote ? codexDefaults.effort : undefined)
557}
558
559/** Display joins are exact ids, never descriptions, names or inferred Claude tiers. */
560async function rememberDisplay($: EngineInterface, entry: AgentDisplay): Promise<void> {
561 if (!entry.toolUseId) return
562 await update($, agentDisplayAtom, state => ({ entries: [...state.entries.filter(row => row.toolUseId !== entry.toolUseId), { ...state.entries.find(row => row.toolUseId === entry.toolUseId), ...entry }].slice(-256) }))
563}
564
565
566async function restoreOwner($: EngineInterface, id: string): Promise<void> {
567 if (agentModels.has(id) && spawnDecisions.has(id)) return
568 const owner = (await read($, ownersAtom)).entries.find(entry => entry.id === id)
569 if (owner) cacheOwner(owner)
570}
571
572/** The model a step runs on: native aliases stay in the observed owning conversation's family. */
573async function stepOwnerModel($: EngineInterface, e: TurnStepInput): Promise<string> {
574 if (e.agentId === undefined) return stepModel(e.model, await $.session.model(), false, tiers(), familyPorts)
575 if (isRouted(e.model)) return e.model
576 await restoreOwner($, e.agentId)
577 // A loop with a native alias (an Explore default, a forked skill's
578 // model: haiku) stays in its owner's family unless it was explicitly
579 // placed on Claude. The owner is the spawn decision, else the parent loop.
580 const decision = spawnDecisions.get(e.agentId)
581 const explicitClaude = decision?.explicit === true && decision.family === CLAUDE_FAMILY
582 const owner = decision?.model ?? agentModels.get(e.agentId)
583 if (owner !== undefined && decision?.family !== CLAUDE_FAMILY && !isRouted(owner)) throw new Error('the observed external child model is unavailable; its request was not moved to a native provider')
584 if (owner === undefined && (isNativeAlias(e.model) || e.model === 'inherit') && isRouted(await $.session.model())) throw new Error('the child has no observed model or verified parent model')
585 // A list row identifies a loop, not its model choice. Never infer ownership from main.
586 // An exact native model on an unowned request remains native, rather than being remapped.
587 return stepModel(e.model, owner, explicitClaude, tiers(), familyPorts)
588}
589
590type AgentCallInput = { tool_use_id: string; model?: unknown; description?: unknown }
591
592/**
593 * An Agent call's `model`, seen before the engine checks it: an exact id this session can run is recorded under the
594 * call's tool_use_id and the engine gets its own carrier value; agent.spawn takes the id back (see agent-model.ts).
595 * An id nothing here can run is refused with the valid ones. The record goes when the call ends, however it ends.
596 */
597async function agentCall<E extends AgentCallInput, R>($: EngineInterface, e: E, next: (input: E) => Promise<R>): Promise<R | { deny: string }> {
598 const verdict = classifyCall(e.model, exactModelIds(catalogue, loaded))
599 if (verdict.kind === 'deny') return { deny: verdict.reason }
600 if (verdict.kind === 'pass') return next(e)
601 if (!e.tool_use_id) return { deny: `${PLUGIN}: this Agent call carries no tool_use_id, so its model cannot be carried to the spawn; no subagent was started` }
602 const entry = { toolUseId: e.tool_use_id, kind: 'exact' as const, at: Date.now(), id: verdict.id }
603 await update($, carrierAtom, state => recordEntry(state, entry))
604 try {
605 return await next({ ...e, model: CARRIER_VALUE, description: markDescription(e.description, verdict.id) })
606 } finally {
607 await update($, carrierAtom, state => forgetEntry(state, e.tool_use_id))
608 }
609}
610
611/** The record an Agent call left for its spawn; taking it removes it. */
612async function takeCarried($: EngineInterface, toolUseId: string) {
613 const entry = entryOf(await read($, carrierAtom), toolUseId)
614 if (entry) await update($, carrierAtom, state => forgetEntry(state, toolUseId))
615 return entry
616}
617
618/**
619 * Remember the main model per session (bounded). The first step after a resume
620 * that runs on a different model than the routed one this conversation last used
621 * says how to return; the host restores only its default model on resume.
622 */
623async function noteMainModel($: EngineInterface, model: string): Promise<void> {
624 try {
625 const session = await $.session.id()
626 const stored = await $.store.get(LAST_MODELS)
627 const models: Record<string, string> = stored && typeof stored === 'object' && !Array.isArray(stored) ? { ...(stored as Record<string, string>) } : {}
628 const previous = models[session]
629 if (recordedMainModel === undefined && previous !== undefined && previous !== model && isRouted(previous)) {
630 $.ui.toast(`${PLUGIN}: this conversation last ran on ${previous}; it now runs on ${model}. Use /model ${previous} to continue on ${previous}.`)
631 }
632 recordedMainModel = model
633 delete models[session]
634 models[session] = model
635 const keys = Object.keys(models)
636 for (const old of keys.slice(0, Math.max(0, keys.length - 200))) delete models[old]
637 await $.store.set(LAST_MODELS, models)
638 } catch {
639 $.ui.log(`${PLUGIN}: the session model note could not be saved`, { to: 'debug' })
640 }
641}
642
643/** Whether a subagent's transcript holds its task: any user content beyond host reminders. */
644function carriesTask(transcript: readonly ApiMessage[]): boolean {
645 const reminder = (text: string) => { const trimmed = text.trim(); return trimmed === '' || trimmed.startsWith('<system-reminder>') && trimmed.endsWith('</system-reminder>') }
646 return transcript.some(message => message.role !== 'user' || (typeof message.content === 'string'
647 ? !reminder(message.content)
648 : message.content.some(block => block.type !== 'text' || typeof block.text !== 'string' || !reminder(block.text))))
649}
650
651
652/** A step answered with a visible refusal, without any provider request. */
653async function* refusedStep($: EngineInterface, e: TurnStepInput, text: string): AsyncGenerator<TurnStepChunk, TurnStepResult> {
654 $.ui.log(text, { to: 'transcript' })
655 const assembler = createAssembler(e.model)
656 assembler.feed({ type: 'error', kind: 'request', text })
657 const end = assembler.end({ child: e.agentId !== undefined })
658 yield* end.chunks
659 return { turnId: e.turnId, index: e.index, answer: end.answer, toolUses: end.toolUses, stopReason: end.stopReason, usage: end.usage }
660}
661
662async function* routedStep($: EngineInterface, e: TurnStepInput, signal?: AbortSignal): AsyncGenerator<TurnStepChunk, TurnStepResult> {
663 const who = e.agentId ?? 'main'
664 $.ui.log(`${PLUGIN}: step ${who} ${e.model} index=${e.index} effort=${e.effort ?? 'unset'}`, { to: 'debug' })
665 const assembler = createAssembler(e.model)
666 let handback: string | undefined
667 const pending: TurnStepChunk[] = []
668 let holdingTools = false
669 let visibleAnswer = ''
670 try {
671 signal?.throwIfAborted()
672 await ensureFreshCapacity($)
673 const transcript = await $.session.messages(e.agentId === undefined ? { as: 'api' } : { as: 'api', agentId: e.agentId })
674 if (!Array.isArray(transcript)) throw new Error(`the transcript of ${who} is unreadable (${transcript.deny})`)
675 if (e.agentId !== undefined && !carriesTask(transcript as ApiMessage[])) throw new Error(`the task of ${who} is not readable by plugins (subagent transcripts need session persistence); nothing was sent`)
676 const built = await buildRequest($, e, transcript as ApiMessage[])
677 handback = built.handback
678 const remote = targetOf(e.model)?.remote
679 if (remote) {
680 const refused = await approval($, remote)
681 if (refused) throw new Error(refused)
682 }
683 const continuation = loaded.config?.continuation
684 if (continuation?.mode === 'durable') {
685 if (!runtime.executable) throw new Error('Durable continuation requires the native Node helper')
686 const records = remote?.model.kind === 'openai' ? [] : await withContinuationStore($, runtime.executable, store => continuationRecords(store, built.req.session, who, Date.now(), () => { continuationExpiredRecords++ }))
687 built.req.continuation = { boundary: { turnId: e.turnId, index: e.index }, maxAgeSeconds: continuation.maxAgeSeconds, records }
688 }
689 const wire = await wireFor($, built.req)
690 signal?.throwIfAborted()
691 if (e.agentId === undefined) mainSnapshot = JSON.parse(JSON.stringify(wire.req)) as StepRequest
692 const reasoning: Reasoning[] = []
693 let durable: ContinuationRecord | undefined
694 let firstTool: string | undefined
695 for await (const event of helperStep(helperPort($), wire)) {
696 signal?.throwIfAborted()
697 if (event.type === 'continuation') durable = event.record
698 else if (event.type === 'continuation_status') {
699 lastContinuationStatus = event.status
700 if (event.status === 'opaque-state-not-retained') throw new Error('Durable continuation blocked: signed plaintext, oversized state or an unrepresentable opaque position cannot be retained; tool calls withheld')
701 }
702 else if (event.type === 'signature') reasoning.push({ thinking: event.thinking, signature: event.signature })
703 else if (event.type === 'limits') {
704 limits = event.limits
705 limitsObservedAt = await $.clock.now()
706 $.ui.status(limitsText())
707 } else if (event.type === 'stats') {
708 const via = event.transport ?? 'http'
709 lastStep = { model: e.model, who, ms: event.totalMs, transport: via }
710 $.ui.log(`${PLUGIN}: step ${who} answered in ${event.totalMs} ms over ${via}`, { to: 'debug' })
711 }
712 else {
713 if (event.type === 'tool_use') { firstTool ??= event.id; holdingTools = true }
714 const chunks = assembler.feed(event)
715 // Text before the first tool remains live. Tool chunks stay pending until success; on failure,
716 // the caller keeps real text but withholds every tool chunk.
717 if (holdingTools) pending.push(...chunks)
718 else {
719 yield* chunks
720 }
721 for (const chunk of chunks) if (chunk.kind === 'text') visibleAnswer += chunk.text
722 }
723 }
724 if (durable && runtime.executable && assembler.end().failure === undefined) {
725 // Staged until the next native transcript proves every real call committed successfully.
726 const status = await withContinuationStore($, runtime.executable, store => saveContinuation(store, built.req.session, who, durable!, Date.now()))
727 lastContinuationStatus = status === 'saved' ? 'staged: awaiting successful native tool results' : status
728 if (status !== 'saved') throw new Error(`Durable continuation blocked: ${status}; tool calls withheld`)
729 }
730 if (!built.req.continuation) remember(carryFor(who), firstTool, reasoning)
731 } catch (error) {
732 if (loaded.config?.continuation?.mode === 'durable') lastContinuationStatus = ['budget-full', 'expired', 'cleared', 'opaque-state-not-retained'].includes(lastContinuationStatus) ? `blocked: ${lastContinuationStatus}` : 'blocked: durable dispatch or store operation failed'
733 assembler.feed({ type: 'error', kind: 'request', text: `rice-multi-models: ${error instanceof Error ? error.message : String(error)}` })
734 }
735 const end = assembler.end({ child: e.agentId !== undefined, ...(handback ? { handback } : {}), ...(signal?.aborted ? { failure: `${PLUGIN}: request aborted` } : {}) })
736 if (end.failure !== undefined) {
737 $.ui.log(end.diagnostic ?? redact(end.failure).slice(0, 1200), { to: 'transcript' })
738 for (const chunk of pending) if (chunk.kind === 'text') yield chunk
739 } else {
740 yield* pending
741 }
742 yield* end.chunks
743
744 return { turnId: e.turnId, index: e.index, answer: end.failure === undefined || end.diagnostic !== undefined ? end.answer : visibleAnswer, toolUses: end.toolUses, stopReason: end.stopReason, usage: end.usage }
745}
746
747/** Host-attested caller plugin, not an inferred loop identity for hidden requests. */
748const auxiliaryOwner = (purpose: string, origin?: Origin) => origin ? JSON.stringify(['auxiliary', purpose, origin.tier, origin.plugin]) : purpose
749
750const NO_USAGE: ModelUsage = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }
751
752/** A one-shot completion on a routed model, for `model.complete` and `model.fork`. */
753async function complete($: EngineInterface, req: StepRequest, timeoutMs?: number, requireFinished = false, signal?: AbortSignal): Promise<ModelCompleteResult> {
754 if (signal?.aborted) return { isAnswered: false, reason: 'aborted', usage: NO_USAGE }
755 await ensureFreshCapacity($)
756 if (signal?.aborted) return { isAnswered: false, reason: 'aborted', usage: NO_USAGE }
757 if (req.native?.maxTokens !== undefined && req.native.maxTokens > outputLimit(req.target)) return { isAnswered: false, reason: 'api-error', status: null, error: 'invalid_request', usage: NO_USAGE }
758 if (timeoutMs !== undefined && (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647)) return { isAnswered: false, reason: 'api-error', status: null, error: 'invalid_request', usage: NO_USAGE }
759 const remote = targetOf(req.target)?.remote
760 if (remote && (await approval($, remote))) return { isAnswered: false, reason: 'api-error', status: null, error: 'invalid_request', usage: NO_USAGE }
761 let answer: Awaited<ReturnType<typeof collectText>>
762 const started = await $.clock.now()
763 try { answer = await collectText(helperPort($, timeoutMs), await wireFor($, req), signal) } catch (error) {
764 if (signal?.aborted || error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError') || timeoutMs !== undefined && await $.clock.now() - started >= timeoutMs) return { isAnswered: false, reason: 'aborted', usage: NO_USAGE }
765 return { isAnswered: false, reason: 'api-error', status: null, error: 'unknown', usage: NO_USAGE }
766 }
767 const usage = answer.usage ?? NO_USAGE
768 if (signal?.aborted || answer.aborted || answer.error !== undefined && timeoutMs !== undefined && await $.clock.now() - started >= timeoutMs) return { isAnswered: false, reason: 'aborted', usage }
769 if (answer.error !== undefined) {
770 if (answer.cause) $.ui.log(`${PLUGIN}: ${req.target} auxiliary request failed [${answer.cause}]; no plugin recovery attempted`, { to: 'transcript' })
771 const status = answer.status ?? null
772 const error = status === 429 ? 'rate_limit' : status === 529 ? 'overloaded' : status === 401 || status === 403 ? 'authentication_failed' : status === 402 ? 'billing_error' : status === 404 ? 'model_not_found' : status !== null && status >= 500 ? 'server_error' : status !== null && status >= 400 ? 'invalid_request' : 'unknown'
773 return { isAnswered: false, reason: 'api-error', status, error, usage }
774 }
775 if (requireFinished && answer.stopReason !== 'end_turn' && answer.stopReason !== 'stop_sequence') return { isAnswered: false, reason: 'api-error', status: null, error: answer.stopReason === 'max_tokens' ? 'max_output_tokens' : 'unknown', usage }
776 if (answer.text.trim() === '') return { isAnswered: false, reason: 'empty-reply', usage }
777 return { isAnswered: true, text: answer.text, usage }
778}
779
780/**
781 * Claude Code's own compaction prompt and summary message, read from the installed claude by the helper once
782 * per running version and kept in the plugin's store. Rejects, naming why, when they cannot be read: a routed
783 * conversation is then not compacted rather than compacted with text this mod made up.
784 */
785function nativeCompaction($: EngineInterface): Promise<CompactionTemplate> {
786 compactionTemplate ??= (async () => {
787 const version = (await $.session.version()).version
788 const key = `native-compaction:${version}`
789 const cached = await $.store.get(key)
790 if (isTemplate(cached) && cached.version === version) return cached
791 if (!runtime.executable || runtime.error) throw new Error(runtime.error || 'the Node.js helper is unavailable; /rice-models setup repair')
792 const ran = await $.process.run([runtime.executable, helperFile($.plugin.root), 'capture-compaction'], { timeoutMs: 100_000 })
793 let result: { ok?: boolean; template?: unknown; error?: unknown } = {}
794 try { result = JSON.parse(ran.stdout) as typeof result } catch { /* reported below */ }
795 if (ran.exitCode !== 0 || result.ok !== true || !isTemplate(result.template)) throw new Error(typeof result.error === 'string' ? result.error : 'the helper could not capture it')
796 if (result.template.version !== version) throw new Error('The installed compaction contract does not match this host version.')
797 await $.store.set(key, result.template)
798 return result.template
799 })()
800 compactionTemplate.catch(() => { compactionTemplate = undefined })
801 return compactionTemplate
802}
803
804async function nativeClassifier($: EngineInterface): Promise<ClassifyTemplate> {
805 const version = (await $.session.version()).version
806 const key = `native-classifier:${version}`
807 const cached = await $.store.get(key)
808 if (isClassifyTemplate(cached) && cached.version === version) return cached
809 if (!runtime.executable || runtime.error) throw new Error('The native classifier capture needs the Node helper.')
810 const ran = await $.process.run([runtime.executable, helperFile($.plugin.root), 'capture-classifier'], { timeoutMs: 100_000 })
811 const result = JSON.parse(ran.stdout) as { ok?: boolean; template?: unknown }
812 if (ran.exitCode !== 0 || !result.ok || !isClassifyTemplate(result.template) || result.template.version !== version) throw new Error('The native classifier contract could not be captured for this host version.')
813 await $.store.set(key, result.template)
814 return result.template
815}
816
817/** The session's built-in tools by name: the combination the engine's tool texts and agent prompts are read for. */
818const builtinNames = (infos: readonly { name: string; mcp: boolean }[]): string[] => infos.filter(info => !info.mcp).map(info => info.name)
819
820/**
821 * Claude Code's own tool definitions and built-in agent prompts for this combination of built-in tools, read from
822 * the installed claude by the helper once per running version and combination and kept in the plugin's store.
823 * Rejects, naming why, when they cannot be read: a main step then sends the generated schema table and the
824 * descriptions the session lists, and a subagent step is refused rather than sent with a prompt this mod made up.
825 */
826function nativeTools($: EngineInterface, names: readonly string[]): Promise<NativeCapture> {
827 const set = toolSetKey(names)
828 let pending = toolCaptures.get(set)
829 if (pending) return pending
830 pending = (async () => {
831 const version = (await $.session.version()).version
832 const key = `native-tools:${version}:${set}`
833 const cached = await $.store.get(key)
834 if (isCapture(cached)) return cached
835 if (toolCaptureFailure && await $.clock.now() - toolCaptureFailure.at < TOOL_CAPTURE_RETRY_MS) throw new Error(toolCaptureFailure.error)
836 if (!runtime.executable || runtime.error) throw new Error(runtime.error || 'the Node.js helper is unavailable; /rice-models setup repair')
837 const ran = await $.process.run([runtime.executable, helperFile($.plugin.root), 'capture-tools'], { stdin: JSON.stringify({ tools: [...names] }), timeoutMs: 100_000 })
838 let result: { ok?: boolean; capture?: unknown; error?: unknown } = {}
839 try { result = JSON.parse(ran.stdout) as typeof result } catch { /* reported below */ }
840 if (ran.exitCode !== 0 || result.ok !== true || !isCapture(result.capture)) {
841 const error = typeof result.error === 'string' ? result.error : 'the helper could not capture them'
842 toolCaptureFailure = { at: await $.clock.now(), error }
843 throw new Error(error)
844 }
845 toolCaptureFailure = undefined
846 try { await $.store.set(key, result.capture) } catch { $.ui.log(`${PLUGIN}: the installed claude's tool definitions could not be saved; they are read again next session`, { to: 'debug' }) }
847 if (result.capture.version !== version) $.ui.log(`${PLUGIN}: tool definitions and agent prompts come from the installed claude ${result.capture.version}; this session runs ${version}`, { to: 'debug' })
848 return result.capture
849 })()
850 setCapped(toolCaptures, set, pending, 16)
851 pending.then(capture => { setCapped(readyCaptures, set, capture, 16) }, () => { if (toolCaptures.get(set) === pending) toolCaptures.delete(set) })
852 return pending
853}
854
855/** The capture for these tools when it is already read (in this process or in the store), without running one. */
856async function readyTools($: EngineInterface, names: readonly string[]): Promise<NativeCapture | undefined> {
857 const set = toolSetKey(names)
858 const ready = readyCaptures.get(set)
859 if (ready) return ready
860 const cached = await $.store.get(`native-tools:${(await $.session.version()).version}:${set}`)
861 return isCapture(cached) ? cached : undefined
862}
863
864/** The capture for a step's tools, or why there is none; a failure is written to the debug log once. */
865async function stepTools($: EngineInterface, names: readonly string[]): Promise<NativeCapture | Error> {
866 try {
867 return await nativeTools($, names)
868 } catch (error) {
869 const failure = error instanceof Error ? error : new Error(String(error))
870 if (!reportedToolFallbacks.has(failure.message)) {
871 reportedToolFallbacks.add(failure.message)
872 $.ui.log(`${PLUGIN}: Claude Code's own tool definitions could not be read from the installed claude (${failure.message}); built-in tools use the generated schema table (${STAMP.engineVersion}) and the descriptions the session lists, and routed subagent steps are refused`, { to: 'debug' })
873 }
874 return failure
875 }
876}
877
878/** Where the tool definitions and agent prompts of routed steps come from now, for status and doctor. */
879async function toolDefinitionsState($: EngineInterface): Promise<{ source: string; version: string | null; agentTypes: string[]; error: string | null }> {
880 const capture = await $.tool.list().then(infos => readyTools($, builtinNames(infos))).catch(() => undefined)
881 if (capture) return { source: 'installed claude', version: capture.version, agentTypes: Object.keys(capture.prompts).sort(), error: null }
882 return { source: `generated schema table (${STAMP.engineVersion})`, version: null, agentTypes: [], error: toolCaptureFailure?.error ?? 'not read yet' }
883}
884
885/** The main transcript's file path, from the latest classic hook that named it; kept across a plugin reload. */
886async function transcriptPath($: EngineInterface): Promise<string | undefined> {
887 return seenTranscriptPath ?? (await read($, transcriptAtom)).path ?? undefined
888}
889
890/** Remembers the transcript path a main-conversation classic hook names. */
891async function noteTranscript($: EngineInterface, e: { transcript_path: string; agent_id?: string }): Promise<void> {
892 if (e.agent_id !== undefined || !e.transcript_path || e.transcript_path === seenTranscriptPath) return
893 seenTranscriptPath = e.transcript_path
894 await update($, transcriptAtom, () => ({ path: e.transcript_path }))
895}
896
897async function nativeContextStatus($: EngineInterface) {
898 const model = await $.session.model()
899 const metadata = activeContext(model)
900 const usage = await $.session.usage({ breakdown: 'summary' })
901 const current = await $.env.get('CLAUDE_CODE_MAX_CONTEXT_TOKENS') ?? null
902 return {
903 model,
904 activeContextWindow: metadata?.contextWindow ?? null,
905 maxContextWindow: metadata?.maxContextWindow ?? null,
906 inputTokenLimit: metadata?.inputTokenLimit ?? null,
907 outputTokenLimit: metadata?.outputTokenLimit ?? null,
908 autoCompactTokenLimit: metadata?.autoCompactTokenLimit ?? null,
909 reasoningEfforts: metadata?.reasoningEfforts ?? null,
910 capabilities: { inputModalities: metadata?.inputModalities ?? null, tools: metadata?.tools ?? null, parallelToolCalls: metadata?.parallelToolCalls ?? null },
911 nativeWindow: usage.context.window,
912 override: current ?? 'unset',
913 scope: 'the mod writes Claude\'s native model fields to ~/.claude/settings.json, loaded at launch; window resolution, accounting and automatic compaction are Claude\'s own',
914 limitations: NATIVE_MODEL_LIMITATIONS,
915 }
916}
917
918async function configuredCapabilities($: EngineInterface, checked: Runtime = runtime) {
919 if (!loaded.config) return []
920 const reports = capabilityContracts(loaded.config)
921 const search = await readSearchConfiguration($, checked)
922 const fetch = await readFetchConfiguration($, checked)
923 const legacyUrl = await $.env.get('RICE_MULTI_MODELS_SEARCH_URL')
924 const searchConfig = search.config ?? { version: 1 as const, endpoints: [] }
925 const fetchConfig = fetch.config ?? { endpoints: [] }
926 const web: Record<string, { search: string; fetch: string }> = {}
927 for (const report of reports) {
928 const remote = remoteOf(loaded, report.target)
929 const providerNative = remote !== undefined && fetchProviderProtocol(remote.model.kind, remote.provider.baseUrl, remote.modelId) !== undefined
930 const status = webSearchStatus(report.target, remote, searchConfig, legacyUrl, search.ok,
931 fetchTierConfigState(fetchConfig, providerNative), { available: fetch.ok, error: fetch.error ?? null })
932 web[report.target] = {
933 search: JSON.stringify({ policy: remote?.model.webSearch ?? 'auto', providerNative: status.providerNative, configuredServices: status.configuredServices, configuredServicesAvailable: status.configuredServicesAvailable, claudeFallback: status.claudeFallback }),
934 fetch: JSON.stringify({ configuration: status.fetchConfiguration, tiers: status.fetchTierState.tiers }),
935 }
936 }
937 return capabilityContracts(loaded.config, web)
938}
939
940async function capabilitySummary($: EngineInterface): Promise<string> {
941 return formatCapabilityContracts(await configuredCapabilities($))
942}
943
944async function statusText($: EngineInterface): Promise<string> {
945 const prefs = await read($, prefsAtom)
946 const version = await $.session.version()
947 const context = await nativeContextStatus($)
948 const tools = await toolDefinitionsState($)
949 const table = `the schema table generated for ${STAMP.engineVersion}${version.version !== STAMP.engineVersion ? ` (this is ${version.version})` : ''} and the descriptions the session lists`
950 const lines = [
951 `helper: ${runtime.error || !runtime.executable ? runtime.error || 'Node.js 22+ unavailable; /rice-models setup repair' : prefs.helper === 'once' ? 'one process per step (/rice-models helper session for the session helper)' : sessionHelper() ? 'session helper running (one connection per conversation, private socket)' : 'session helper not running; one process per step'}`,
952 `transport: ${prefs.transport} (auto = WebSocket, falling back to server-sent events)`,
953 `effort: ${prefs.effort ?? (codexDefaults.effort ? `${codexDefaults.effort} (configured Codex policy)` : 'unset; provider chooses')}${prefs.effort ? ' (set here)' : ''}, unless the session sets one`,
954 `Codex session candidate: ${defaultModel('codex') ?? 'none discovered'}`,
955 `Discovery: ${catalogue.providers.map(provider => `${provider.provider}: ${provider.status}${provider.error ? ` (${provider.error})` : ''}`).join('; ')}`,
956 await capabilitySummary($),
957 `Primary context (${context.model}): active context ${context.activeContextWindow ?? 'unknown'}, maximum context ${context.maxContextWindow ?? 'unknown'}, reported input ${context.inputTokenLimit ?? 'unknown'}, reported output ${context.outputTokenLimit ?? 'unknown'}, native window ${context.nativeWindow}; override ${context.override}.`,
958 `Native context scope: ${context.scope}. ${NATIVE_MODEL_LIMITATIONS.registration}`,
959 `Native child recovery limitation: ${NATIVE_MODEL_LIMITATIONS.childBudget} ${NATIVE_MODEL_LIMITATIONS.recovery}`,
960 'Compaction: Claude decides when to compact and what the transcript becomes; for a routed model the summary request (Claude\'s own captured prompt over the conversation as Claude holds it) goes to the model\'s provider and its answer comes back as Claude\'s own summary message. A failed summary leaves the conversation as it is.',
961 tools.source === 'installed claude'
962 ? `Tool definitions and agent prompts: Claude Code's own, read from the installed claude ${tools.version} (built-in agent types ${tools.agentTypes.join(', ') || 'none'}); a tool it did not show (MCP, or interactive only) uses ${table}.`
963 : `Tool definitions and agent prompts: ${tools.error === 'not read yet' ? 'not read from the installed claude yet' : `the installed claude's could not be read (${tools.error})`}; built-in tools use ${table}, and a routed subagent step is refused until they are read.`,
964 limitsText() ? `ChatGPT limits: ${limitsText()}` : 'ChatGPT limits: shown after the first WebSocket request',
965 `Web search: ${JSON.stringify(await currentWebSearchStatus($))}`,
966 lastStep ? `last step: ${lastStep.model} for ${lastStep.who}, ${lastStep.ms} ms over ${lastStep.transport}` : 'no routed step yet',
967 ...memory.notes.slice(-5),
968 ]
969
970 return lines.join('\n')
971}
972
973function routedRows(): PickerRow[] {
974 return catalogueRows(catalogue)
975}
976
977async function modelsText($: EngineInterface): Promise<string> {
978 return `${await discoveryText($, 'models')}\n\nUse a discovered candidate with /model <id>, --model <id>, or model: <id> in an agent file. /rice-models refresh fetches a new catalogue; discovery tools read this snapshot.`
979}
980
981function candidateRoute(model: string): CandidateRoute | undefined {
982 const remote = remoteOf(loaded, model)
983 if (remote) {
984 return {
985 source: 'configured provider',
986 execution: 'native provider',
987 identity: JSON.stringify({
988 kind: 'configured-provider',
989 requestedModel: model,
990 resolvedTarget: remote.target,
991 approvalFingerprint: remote.fingerprint,
992 provider: remote.provider,
993 model: remote.model,
994 }),
995 codexSubscriptionQuota: false,
996 }
997 }
998 const target = splitTarget(model)
999 if (!target) return undefined
1000 if (target.provider === 'codex') {
1001 return {
1002 source: 'Codex authenticated models endpoint',
1003 execution: 'native provider',
1004 identity: JSON.stringify({ kind: 'codex-subscription', model: target.model }),
1005 codexSubscriptionQuota: true,
1006 }
1007 }
1008 return undefined
1009}
1010
1011function candidateModels() {
1012 return candidates(routedRows(), candidateRoute).map(candidate => {
1013 const entry = catalogue.models.find(model => model.model === candidate.model)!
1014 return { ...candidate, source: entry.source, metadata: entry.metadata, metadataSources: entry.metadataSources, observedAt: entry.observedAt }
1015 })
1016}
1017
1018async function discoveryText($: EngineInterface, action: 'models' | 'status'): Promise<string> {
1019 const models = candidateModels()
1020 const approvals = await approvedSet($)
1021 const providers = Object.values(loaded.config?.providers ?? {}).map(provider => ({ provider: provider.id, approved: approvals.has(fingerprint(provider)) }))
1022 const report = modelsReport(models, providers, limitsReport(limits, limitsObservedAt), catalogue)
1023 if (action === 'models') return report
1024 return `${report}\n\nSession status:\n${JSON.stringify(await discoveryStatus($), null, 2)}`
1025}
1026
1027async function discoveryStatus($: EngineInterface): Promise<Record<string, unknown>> {
1028 const prefs = await read($, prefsAtom)
1029 const version = await $.session.version()
1030 return {
1031 helper: !runtime.executable || runtime.error ? 'unavailable' : prefs.helper === 'once' ? 'one process per step' : sessionHelper() ? 'session helper running' : 'one process per step',
1032 transport: prefs.transport,
1033 effort: prefs.effort ?? codexDefaults.effort ?? null,
1034 defaultCodexModel: defaultModel('codex'),
1035 nativeContext: await nativeContextStatus($),
1036 toolSchemaVersion: STAMP.engineVersion,
1037 toolDefinitions: await toolDefinitionsState($),
1038 webSearch: await currentWebSearchStatus($),
1039 continuation: continuationStatus(loaded.config?.continuation ?? CONTINUATION_OFF, ['codex-responses', ...Object.values(loaded.config?.providers ?? {}).flatMap(provider => Object.values(provider.models).map(model => model.kind))], lastContinuationStatus, continuationExpiredRecords),
1040 modelCapabilities: await configuredCapabilities($),
1041 currentEngineVersion: version.version,
1042 limits: limitsReport(limits, limitsObservedAt),
1043 lastStep: lastStep ? { model: lastStep.model, who: lastStep.who, durationMs: lastStep.ms, transport: lastStep.transport } : null,
1044 diagnostics: { count: memory.notes.length, class: memory.notes.length === 0 ? 'none' : 'agent/configuration diagnostics' },
1045 }
1046}
1047
1048/** The Node helper serializes writes and tracks exact owned rows, never provider prefixes. */
1049async function writePicker($: EngineInterface): Promise<string> {
1050 const result = await syncPicker($, runtime, routedRows())
1051 return result.ok ? `Synchronized ${result.count} owned rows into ${result.path}; custom and edited rows were kept. /model lists them in new sessions.` : `Picker not changed: ${result.error}`
1052}
1053
1054async function setupCommand($: EngineInterface, action: string | undefined): Promise<string> {
1055 if (action === 'native') return 'Start the normal claude command. This mod uses supported plugin hooks; separate launchers are no longer installed. Use /rice-models setup repair to check the local runtime.'
1056 if (action && !['repair', 'codex'].includes(action)) return 'Usage: /rice-models setup [repair|codex]. No global install is performed.'
1057 runtime = await detectRuntime($)
1058 if (runtime.error) {
1059 return setupSummary(runtime, undefined, 0, undefined, undefined, await capabilitySummary($))
1060 }
1061 if (action === 'codex') {
1062 try {
1063 const result = await $.process.run([runtime.executable!, helperFile($.plugin.root), 'setup-codex'], { timeoutMs: 180_000 })
1064 const installed = JSON.parse(result.stdout.trim()) as { ok: boolean; installed: boolean; login?: string[]; error?: string }
1065 if (!installed.ok) return `Codex setup failed: ${installed.error || 'inspect /rice-models doctor'}`
1066 runtime = await detectRuntime($)
1067 return `${installed.installed ? 'Installed the pinned official Codex CLI into plugin-owned state (not globally).' : 'Using the existing Codex CLI; no install was needed.'}\nRun ${commandText(installed.login || ['codex', 'login'], runtime.info?.platform)} in your terminal to sign in. No login, provider approval or permission change was performed.`
1068 } catch { return 'Codex setup did not complete; inspect /rice-models doctor and retry /rice-models setup codex. No login or provider approval was performed.' }
1069 }
1070 codexDefaults = await readCodexDefaults($)
1071 await loadProviders($)
1072 await refreshCatalogue($)
1073 await ensureHelper($)
1074 const rows = routedRows()
1075 return setupSummary(runtime, await syncPicker($, runtime, rows), rows.length, defaultModel('codex'), undefined, await capabilitySummary($))
1076}
1077
1078async function readSearchConfiguration($: EngineInterface, checked: Runtime, edit?: SearchEdit): Promise<SearchConfigurationResult> {
1079 if (checked.error || !checked.executable) return { ok: false, error: 'Search configuration is unavailable until the local helper is ready.' }
1080 const configDir = (await $.env.get('CLAUDE_CONFIG_DIR')) || `${checked.info?.home || (await $.env.get('USERPROFILE')) || (await $.env.get('HOME')) || ''}/.claude`
1081 try {
1082 const result = await $.process.run([checked.executable, helperFile($.plugin.root), 'search-config'], { stdin: JSON.stringify({ configDir, ...(edit ? { edit } : {}) }), timeoutMs: 10_000 })
1083 const parsed: SearchConfigurationResult = JSON.parse(result.stdout)
1084 return typeof parsed.ok === 'boolean' ? parsed : { ok: false, error: 'Search configuration helper returned an invalid result.' }
1085 } catch { return { ok: false, error: 'Search configuration helper did not complete.' } }
1086}
1087
1088type FetchConfigurationResult = { ok: boolean; config?: FetchConfigMetadata; error?: string }
1089
1090async function readFetchConfiguration($: EngineInterface, checked: Runtime): Promise<FetchConfigurationResult> {
1091 if (checked.error || !checked.executable) return { ok: false, config: { endpoints: [] }, error: 'Fetch configuration could not be read.' }
1092 const configDir = (await $.env.get('CLAUDE_CONFIG_DIR')) || `${checked.info?.home || (await $.env.get('USERPROFILE')) || (await $.env.get('HOME')) || ''}/.claude`
1093 try {
1094 const result = await $.process.run([checked.executable, helperFile($.plugin.root), 'fetch-config-status'], { stdin: JSON.stringify({ configDir }), timeoutMs: 10_000 })
1095 const value: unknown = JSON.parse(result.stdout)
1096 if (!value || typeof value !== 'object' || Array.isArray(value)) return { ok: false, config: { endpoints: [] }, error: 'Fetch configuration could not be read.' }
1097 const parsed = value as FetchConfigurationResult
1098 const endpoints = parsed.config?.endpoints
1099 if (typeof parsed.ok !== 'boolean' || !Array.isArray(endpoints) || !endpoints.every(endpoint =>
1100 endpoint && typeof endpoint.name === 'string' && Number.isSafeInteger(endpoint.priority))) return { ok: false, config: { endpoints: [] }, error: 'Fetch configuration could not be read.' }
1101 return {
1102 ok: parsed.ok,
1103 config: { endpoints: endpoints.map(({ name, priority }) => ({ name, priority })) },
1104 ...(parsed.ok ? {} : { error: 'Fetch configuration could not be read.' }),
1105 }
1106 } catch { return { ok: false, config: { endpoints: [] }, error: 'Fetch configuration could not be read.' } }
1107}
1108
1109async function currentWebSearchStatus($: EngineInterface, checked: Runtime = runtime) {
1110 const model = await $.session.model()
1111 const remote = remoteOf(loaded, model)
1112 const search = await readSearchConfiguration($, checked)
1113 const fetch = await readFetchConfiguration($, checked)
1114 const config = search.config ?? { version: 1 as const, endpoints: [] }
1115 const providerNative = remote !== undefined && fetchProviderProtocol(remote.model.kind, remote.provider.baseUrl, remote.modelId) !== undefined
1116 const fetchTiers = fetchTierConfigState(fetch.config ?? { endpoints: [] }, providerNative)
1117 return webSearchStatus(model, remote, config, await $.env.get('RICE_MULTI_MODELS_SEARCH_URL'), search.ok, fetchTiers,
1118 { available: fetch.ok, error: fetch.error ?? null })
1119}
1120
1121/** Pure diagnostics: no startup, settings write, install, network request, login or approval. */
1122async function doctorCommand($: EngineInterface): Promise<string> {
1123 const checked = await detectRuntime($)
1124 return JSON.stringify({ runtime: checked.info || { node: { executable: checked.executable, version: checked.version } }, error: checked.error || null,
1125 integration: { kind: 'public plugin hooks', start: 'claude', compaction: 'session.compact', toolDefinitions: await toolDefinitionsState($), webSearch: await currentWebSearchStatus($, checked) },
1126 continuation: continuationStatus(loaded.config?.continuation ?? CONTINUATION_OFF, ['codex-responses', ...Object.values(loaded.config?.providers ?? {}).flatMap(provider => Object.values(provider.models).map(model => model.kind))], lastContinuationStatus, continuationExpiredRecords),
1127 modelCapabilities: await configuredCapabilities($),
1128 actions: checked.error ? ['/rice-models setup repair'] : ['/rice-models setup repair', ...(!checked.info?.auth.codex ? ['codex login', ...(!checked.info?.clis.codex ? ['/rice-models setup codex'] : [])] : [])] }, null, 2)
1129}
1130
1131/**
1132 * OpenCode Zen and Go as providers, from each gateway's model list and the models.dev catalog: a summary, or
1133 * with `write` the providers saved into rice-multi-models.json (other providers kept) and reloaded.
1134 */
1135async function opencodeCommand($: EngineInterface, words: readonly string[]): Promise<string> {
1136 const tiers: Tier[] = words.includes('zen') ? ['zen'] : words.includes('go') ? ['go'] : ['zen', 'go']
1137 const write = words.includes('write')
1138 if (!runtime.executable || runtime.error || !runtime.info) return setupSummary(runtime)
1139 const home = runtime.info.home
1140 const authFile = runtime.info.opencodeAuthFile
1141 // The helper emits entry names only here, never credential values.
1142 const listed = await $.process.run([runtime.executable, helperFile($.plugin.root), 'opencode-entries', authFile], { timeoutMs: 10_000 }).catch(() => undefined)
1143 if (!listed || listed.exitCode !== 0) return 'OpenCode auth metadata is malformed or unreadable. Check /rice-models doctor or run opencode auth login; no provider configuration was written.'
1144 const entries = new Set(JSON.parse(listed.stdout) as string[])
1145 const catalog = await $.http.fetch(CATALOG_URL)
1146 if (!catalog.ok) return `rice-models opencode: ${CATALOG_URL} answered HTTP ${catalog.status}; retry later.`
1147 const parsed: unknown = JSON.parse(catalog.text)
1148 const built: { tier: Tier; provider: Record<string, unknown>; skipped: string[] }[] = []
1149 for (const tier of tiers) {
1150 const live = await $.http.fetch(`${TIERS[tier].base}/models`)
1151 if (!live.ok) return `rice-models opencode: ${TIERS[tier].base}/models answered HTTP ${live.status}; retry later.`
1152 built.push({ tier, ...opencodeProvider(tier, parsed, liveIds(live.text), runtime.executable, authFile, helperFile($.plugin.root)) })
1153 }
1154 const lines = built.map(({ tier, provider, skipped }) => {
1155 const t = TIERS[tier]
1156 const key = entries.has(t.keys[0]) ? `key: the ${t.keys[0]} entry` : entries.has(t.keys[1]) ? `key: the ${t.keys[1]} entry (one console key serves Zen and Go)` : `key: none yet; run opencode auth login and pick ${t.label}`
1157 const models = Object.keys(provider.models as object)
1158
1159 return `${t.id} (${t.label}, ${t.base}): ${models.length} models (${kindCounts(provider)}); ${key}${skipped.length > 0 ? `\n left out: ${skipped.join(', ')}` : ''}`
1160 })
1161 if (!write) return `${lines.join('\n')}\n\n/rice-models opencode ${tiers.length === 1 ? `${tiers[0]} ` : ''}write saves ${tiers.length === 1 ? 'it' : 'them'} into rice-multi-models.json.`
1162 const dir = (await $.env.get('CLAUDE_CONFIG_DIR')) || `${home}/.claude`
1163 const path = `${dir}/${CONFIG_FILE}`
1164 const current = (await $.fs.exists(path)) ? (JSON.parse(await $.fs.read(path)) as Record<string, unknown>) : {}
1165 const providers = { ...((current.providers as Record<string, unknown> | undefined) ?? {}) }
1166 for (const { tier, provider } of built) providers[TIERS[tier].id] = provider
1167 const next = `${JSON.stringify({ ...current, providers }, null, 2)}\n`
1168 const checked = loadText(path, next)
1169 if (checked.errors.length > 0) return `rice-models opencode: the result does not validate, so nothing was written:\n${checked.errors.join('\n')}`
1170 await $.fs.write(path, next)
1171 await loadProviders($)
1172
1173 return `${lines.join('\n')}\n\nWrote ${built.map(b => TIERS[b.tier].id).join(' and ')} into ${path}; other providers were kept. The first request asks to approve each one (or /rice-models approve <id>). /rice-models picker write lists the models in /model.`
1174}
1175
1176async function searchCommand($: EngineInterface, args: string): Promise<string> {
1177 const checked = await detectRuntime($)
1178 if (checked.error || !checked.executable) return setupSummary(checked)
1179 return searchConfigurationCommand(args, { read: () => readSearchConfiguration($, checked), edit: edit => readSearchConfiguration($, checked, edit), ask: (question, options) => $.ui.ask(question, options) })
1180}
1181
1182async function runCommand($: EngineInterface, args: string): Promise<string> {
1183 const [first, value] = args.trim().split(/\s+/)
1184 if (first === 'search') return searchCommand($, args.trim().replace(/^search(?:\s+|$)/, ''))
1185 if (first === 'setup') return setupCommand($, value)
1186 if (first === 'doctor') return doctorCommand($)
1187 if (first === 'opencode') return opencodeCommand($, args.trim().split(/\s+/).slice(1))
1188 if (!first || first === 'status') return statusText($)
1189 if (first === 'models') return modelsText($)
1190 if (first === 'picker') return value === 'write' ? writePicker($) : `${JSON.stringify({ modelPicker: { options: routedRows() } }, null, 2)}\n\n/rice-models picker write puts these rows in your user settings.`
1191 if (first === 'providers') return providerLines(loaded, await approvedSet($)).join('\n')
1192 if (first === 'reload' || first === 'refresh') {
1193 // A failed read of the tool definitions is tried again now.
1194 toolCaptureFailure = undefined
1195 await loadProviders($)
1196 await refreshCatalogue($)
1197 await syncPicker($, runtime, routedRows())
1198 return `${loaded.errors.length > 0 ? `${loaded.path} does not validate; no declared provider routes:\n${loaded.errors.join('\n')}` : providerLines(loaded, await approvedSet($)).join('\n')}\n\n${await discoveryText($, 'models')}\n\n${RELAUNCH_NOTICE}`
1199 }
1200 if (first === 'approve') {hooks/agent-model.ts 126 lines1// Exact-model selection through the Agent tool's `model` argument.
2//
3// The engine accepts only `fable`, `haiku`, `opus` and `sonnet` there, and checks the argument after the plugin's
4// `tool.call` hook ran. The hook sees the raw argument first, so a call naming an exact id this session can run
5// is carried: `tool.call` records the id under the call's tool_use_id and hands the engine a valid value
6// (CARRIER_VALUE) and adds a visible exact-model note to the description; `agent.spawn` takes the id back, removes the
7// mark and the subagent runs on exactly that id. A marked spawn with no record is refused, never run as the carrier's
8// tier (an unmarked `haiku` is the engine's own request and passes). Pure: state in and out.
9import type { ModelCatalogue } from './catalogue'
10import { NATIVE_ALIASES } from './family'
11import type { Loaded } from './providers'
12
13export const AGENT_TOOL = 'Agent'
14/** A value of the engine's own enum that stands in for the exact id while the engine checks the call. */
15export const CARRIER_VALUE = 'haiku'
16const PLUGIN = 'rice-multi-models'
17/** A visible note distinguishes a lost carried call from a real haiku and makes approval/transcript text truthful. */
18export const CARRIER_MARK = ` [${PLUGIN}: exact Agent model `
19const CARRIER_END = `; ${CARRIER_VALUE} is validation only]`
20export const markDescription = (description: unknown, id: string): string => `${typeof description === 'string' ? description : ''}${CARRIER_MARK}${JSON.stringify(id)}${CARRIER_END}`
21export function unmarkDescription(description: string): { text: string; marked: boolean } {
22 const start = description.lastIndexOf(CARRIER_MARK)
23 return start >= 0 && description.endsWith(CARRIER_END) ? { text: description.slice(0, start), marked: true } : { text: description, marked: false }
24}
25/** Records kept per session; calls remove their own, so only abandoned ones (a hot reload) ever reach this. */
26const MAX_ENTRIES = 128
27const DENIAL_LIST_LIMIT = 60
28const DESCRIPTION_LIST_LIMIT = 30
29/** Above this many ids the schema keeps a plain string instead of an enum, so the list does not ride on every request. */
30export const SCHEMA_ENUM_LIMIT = 200
31export const DESCRIPTION_MARK = `[${PLUGIN}] The model parameter also takes`
32
33/** What a call recorded: the exact id its spawn runs. */
34export type CarrierEntry = { toolUseId: string; kind: 'exact'; at: number; id: string }
35export type CarrierState = { readonly entries: readonly CarrierEntry[] }
36export const emptyCarrier: CarrierState = { entries: [] }
37
38/** Every exact id a call may name: discovered models of fresh providers, declared models and declared aliases. */
39export function exactModelIds(catalogue: ModelCatalogue, loaded: Loaded): string[] {
40 const fresh = new Set(catalogue.providers.filter(provider => provider.status === 'fresh').map(provider => provider.provider))
41 const ids = new Set<string>()
42 for (const entry of catalogue.models) {
43 const slash = entry.model.indexOf('/')
44 if (entry.execution === 'native provider' && slash > 0 && entry.model.length > slash + 1 && fresh.has(entry.model.slice(0, slash))) ids.add(entry.model)
45 }
46 for (const provider of Object.values(loaded.config?.providers ?? {})) {
47 for (const model of Object.keys(provider.models)) ids.add(`${provider.id}/${model}`)
48 }
49 for (const alias of Object.keys(loaded.config?.aliases ?? {})) ids.add(alias)
50 return [...ids].sort()
51}
52
53export type CallVerdict =
54 | { kind: 'pass' }
55 | { kind: 'carry'; id: string }
56 | { kind: 'deny'; reason: string }
57
58const listed = (ids: readonly string[], limit: number): string => ids.length <= limit ? ids.join(', ') : `${ids.slice(0, limit).join(', ')} and ${ids.length - limit} more (/rice-models models lists them)`
59
60/** What a raw Agent `model` argument asks for. */
61export function classifyCall(model: unknown, ids: readonly string[]): CallVerdict {
62 if (typeof model !== 'string' || model === '') return { kind: 'pass' }
63 if ((NATIVE_ALIASES as readonly string[]).includes(model)) return { kind: 'pass' }
64 if (ids.includes(model)) return { kind: 'carry', id: model }
65 const valid = [...NATIVE_ALIASES, ...ids]
66 return { kind: 'deny', reason: `${PLUGIN}: Agent model "${model}" is not a model this session can run, so no subagent was started. Valid values: ${listed(valid, DENIAL_LIST_LIMIT)}.` }
67}
68
69const prune = (entries: readonly CarrierEntry[], toolUseId: string): CarrierEntry[] => entries.filter(entry => entry.toolUseId !== toolUseId)
70
71export function recordEntry(state: CarrierState, entry: CarrierEntry): CarrierState {
72 const kept = [...prune(state.entries, entry.toolUseId), entry]
73 return { entries: kept.slice(Math.max(0, kept.length - MAX_ENTRIES)) }
74}
75
76export function forgetEntry(state: CarrierState, toolUseId: string): CarrierState {
77 return state.entries.some(entry => entry.toolUseId === toolUseId) ? { entries: prune(state.entries, toolUseId) } : state
78}
79
80export const entryOf = (state: CarrierState, toolUseId: string): CarrierEntry | undefined => toolUseId === '' ? undefined : state.entries.find(entry => entry.toolUseId === toolUseId)
81
82export type SpawnPick = { requested: string | undefined; exact?: string } | { deny: string }
83
84/**
85 * The `model` a spawn decides from. An exact record wins; a carrier-valued spawn with no record is refused (it
86 * would otherwise run as the carrier's tier); a fork inherits its parent, so an exact id on one is refused.
87 */
88export function pickRequested(entry: CarrierEntry | undefined, model: string | undefined, fork: boolean, marked: boolean): SpawnPick {
89 if (entry !== undefined) {
90 if (fork) return { deny: `${PLUGIN}: a fork runs on its parent's model, so the Agent model "${entry.id}" cannot be applied; name a subagent_type to run on it. No subagent was started.` }
91 return { requested: entry.id, exact: entry.id }
92 }
93 if (marked) {
94 return { deny: `${PLUGIN}: this Agent call's exact model could not be recovered (no record for it), so it was not run as ${CARRIER_VALUE}. Retry with an exact model id. No subagent was started.` }
95 }
96 return { requested: model }
97}
98
99/** The Agent schema a routed model sees: the engine's `model` enum plus the exact ids. */
100export function widenAgentSchema(schema: Record<string, unknown>, ids: readonly string[]): Record<string, unknown> {
101 const properties = schema['properties']
102 if (ids.length === 0 || typeof properties !== 'object' || properties === null || Array.isArray(properties)) return schema
103 const model = (properties as Record<string, unknown>)['model']
104 if (typeof model !== 'object' || model === null || Array.isArray(model)) return schema
105 const current = (model as Record<string, unknown>)['enum']
106 if (!Array.isArray(current)) return schema
107 const { enum: _enum, ...rest } = model as Record<string, unknown>
108 const widened = ids.length > SCHEMA_ENUM_LIMIT ? rest : { ...rest, enum: [...new Set([...current, ...ids])] }
109 return { ...schema, properties: { ...properties, model: widened } }
110}
111
112/** The short statement appended to the Agent tool's description; empty when nothing is discovered. */
113export function descriptionSuffix(ids: readonly string[]): string {
114 if (ids.length === 0) return ''
115 return `\n\n${DESCRIPTION_MARK} an exact provider/model id from this session, which runs the subagent on exactly that model with no tier mapping: ${listed(ids, DESCRIPTION_LIST_LIMIT)}. Any other id is refused with the valid ones.`
116}
117
118export const withDescriptionSuffix = (description: string, ids: readonly string[]): string => description.includes(DESCRIPTION_MARK) ? description : `${description}${descriptionSuffix(ids)}`
119
120/** Presentation only. Never rewrite an agent's address/type or turn an exact model into a tier. */
121export function agentLabel(description: string, model: string, effort?: string | number): string {
122 const line = (value: string) => value.replace(/[\p{Cc}\p{Cf}]+/gu, ' ').replace(/\s+/g, ' ').trim()
123 const label = `(${line(model).slice(0, 200)}${effort === undefined ? '' : ` ${line(String(effort)).slice(0, 40)}`})`
124 return description.endsWith(label) ? description : `${description} ${label}`.trim()
125}
126hooks/agents.ts 287 lines1// Copied from Trosfy/claude-styx hooks/agents.ts at 5072384
2// (MIT, Copyright (c) 2026 styx contributors; see LICENSES/claude-styx.MIT.txt).
3// Modified by Mo Abualruz: imports its JSON helpers from ./util; the built-in types' prompts styx wrote are gone (a
4// routed subagent is given the prompt the installed claude sends, see native-tools.ts), and the tool filter
5// follows the tools the engine offers each agent type where the capture saw them.
6// Custom agent types as Claude Code defines them in agent files (`<name>.md`: a YAML frontmatter, then the
7// markdown body that is the agent's whole system prompt), the plugin directory installed_plugins.json
8// records, which tools a routed subagent is given, and styx's own definition of the SubagentHandback tool a
9// subagent reports through (the engine's name and input shape, styx's text). Pure: the files are read by register.ts.
10
11import { isObject, own } from './util'
12import type { JsonSchema } from './util'
13
14// The agent types the engine defines itself (2.1.293); every other type is a custom agent with a
15// definition file.
16export const BUILTIN_AGENTS: readonly string[] = ['general-purpose', 'Explore', 'Plan', 'statusline-setup', 'claude-code-guide', 'web-fetch', 'claude', 'fork', 'comment-thread-analyst']
17
18// What Explore and Plan may not call on 2.1.292, as the Agent tool's listing of agent types states it
19// ("All tools except …"); every other tool the parent has stays. These static rules decide only the tools the
20// capture did not see (see toolFilter).
21const READ_ONLY_DENIED = ['Agent', 'Artifact', 'ArtifactComments', 'ArtifactData', 'ArtifactCheck', 'ExitPlanMode', 'Edit', 'Write', 'NotebookEdit']
22
23// The tools a built-in agent type is denied; a type not named here keeps its parent's tools.
24const AGENT_DENIED: Readonly<Record<string, readonly string[]>> = { Explore: READ_ONLY_DENIED, Plan: READ_ONLY_DENIED }
25
26// The only tools a built-in agent type may call, where its 2.1.292 definition lists them (claude-code-guide's
27// list is the union of its two forms); a type not named here keeps its parent's tools.
28const AGENT_ALLOWED: Readonly<Record<string, readonly string[]>> = {
29 'statusline-setup': ['Read', 'Edit'],
30 'claude-code-guide': ['Bash', 'Glob', 'Grep', 'Read', 'WebFetch', 'WebSearch'],
31 'web-fetch': ['WebFetch'],
32}
33
34// The model a built-in agent type's own definition sets on 2.1.310 (general-purpose and claude set none): a
35// subagent of one runs on it, whatever the parent runs on, and "inherit" runs it on its parent's model before
36// CLAUDE_CODE_SUBAGENT_MODEL is read. web-fetch's is chosen at run time, haiku or else inherit.
37export const BUILTIN_MODELS: Readonly<Record<string, string>> = {
38 'statusline-setup': 'sonnet',
39 'claude-code-guide': 'haiku',
40 Explore: 'inherit',
41 Plan: 'inherit',
42 'web-fetch': 'inherit',
43 'comment-thread-analyst': 'inherit',
44}
45
46// The main conversation's own tools, which no native subagent is given: asking the person, plan mode, the
47// session's task list and schedule, and messages to the person.
48export const SUBAGENT_DENIED: readonly string[] = [
49 'AskUserQuestion',
50 'EnterPlanMode',
51 'ExitPlanMode',
52 'TaskCreate',
53 'TaskGet',
54 'TaskList',
55 'TaskUpdate',
56 'TodoWrite',
57 'CronCreate',
58 'CronDelete',
59 'CronList',
60 'ScheduleWakeup',
61 'PushNotification',
62 'SendUserMessage',
63 'SendUserFile',
64 'EndConversation',
65]
66
67// The SubagentHandback tool as styx offers it to a routed subagent, when the engine's transcript says it delivers
68// the report through it (2.1.294: only in auto permission mode). The engine runs or refuses the call itself
69// (pool.ts): the name and the input shape are its contract, the texts are styx's own.
70export const HANDBACK_TOOL = {
71 name: 'SubagentHandback',
72 description:
73 'Ends your run and hands message to the agent that launched you, as your report. Call it once, after all other work, with the complete report in message: the launcher reads that text and nothing else you wrote, and a run that ends on plain text instead delivers no report. It takes no recipient and is not for progress updates or questions; put those in the report.',
74 schema: {
75 type: 'object',
76 properties: { message: { type: 'string', description: 'The whole report, as the agent that launched you will read it; nothing else reaches it.' } },
77 required: ['message'],
78 additionalProperties: false,
79 } as JsonSchema,
80} as const
81
82// What an agent file defines: its frontmatter's fields, and its body as `prompt`.
83export type AgentDef = {
84 name?: string
85 description?: string
86 tools?: readonly string[]
87 disallowedTools?: readonly string[]
88 model?: string
89 effort?: string | number
90 isolation?: string
91 permissionMode?: string
92 omitClaudeMd?: true
93 hooks?: Record<string, unknown>
94 prompt: string
95}
96export const AGENT_PERMISSION_MODES = new Set(['acceptEdits', 'auto', 'bypassPermissions', 'default', 'dontAsk', 'plan'])
97export type Parsed<T> = T | { error: string }
98// installed_plugins.json's `plugins`: each `<name>@<marketplace>` with its installs.
99type InstalledPlugins = Readonly<Record<string, readonly unknown[]>>
100
101const UNREAD = (s: string) => ({ error: `"${s}" is a YAML form this mod does not read (only text and lists are)` })
102const UNCLOSED = { error: 'a quoted value that does not close on its line, or has an escape JSON does not know' }
103
104// One frontmatter value as text: plain (a ` #` comment cut off), "double-quoted" with JSON's escapes, or
105// 'single-quoted' with '' for a quote. Block scalars, maps, nested lists, anchors and tags are errors.
106function scalar(raw: string): Parsed<string> {
107 const s = raw.trim()
108 if (s.startsWith('"')) {
109 const m = /^("(?:[^"\\]|\\.)*")\s*(?:#.*)?$/.exec(s)
110 try {
111 const v: unknown = m === null ? undefined : JSON.parse(m[1] as string)
112 if (typeof v === 'string') return v
113 } catch {}
114 return UNCLOSED
115 }
116 if (s.startsWith("'")) {
117 const m = /^'((?:[^']|'')*)'\s*(?:#.*)?$/.exec(s)
118 return m === null ? UNCLOSED : (m[1] as string).replaceAll("''", "'")
119 }
120 if (/^[|>{[\]&*!%@`]/.test(s)) return UNREAD(s)
121 return s.replace(/\s+#.*$/, '')
122}
123
124// A `[a, b]` list on one line, its items text. A comma inside a rule's `(…)` part, as in
125// `Bash(git:*, npm:*)`, separates no items.
126function flowList(raw: string): Parsed<string[]> {
127 const m = /^\[(.*)\]\s*(?:#.*)?$/.exec(raw.trim())
128 if (m === null) return { error: 'a [list] that does not close on its line' }
129 const inner = (m[1] as string).trim()
130 const items: string[] = []
131 for (const part of inner === '' ? [] : inner.split(/,(?![^(]*\))/)) {
132 const v = scalar(part)
133 if (typeof v !== 'string') return v
134 items.push(v)
135 }
136 return items
137}
138
139// Tool names from a `tools` value: a list, or one comma-separated text. A rule's `(…)` part is dropped,
140// so `Bash(git:*)` names Bash and `Agent(worker, researcher)` names Agent.
141const toolNames = (v: string | readonly string[]) =>
142 (typeof v === 'string' ? v.split(/,(?![^(]*\))/) : v).map(s => s.replace(/\(.*\)$/s, '').trim()).filter(s => s !== '')
143
144// Why a file that does not open on a frontmatter does not read. Claude Code ignores such a file in an agents
145// directory without a word, so styx tells this error apart from the others and says nothing of it either.
146export const NO_FRONTMATTER = 'no frontmatter (the file must open with a --- line)'
147
148// An agent file's definition. The frontmatter is the YAML agent files use: `key: value` text, and lists as
149// `[a, b]` or as `- a` lines under a bare `key:` (a bare key with no items is left out). Keys other than
150// the definition's own are read and ignored.
151export function parseAgentFile(text: string): Parsed<AgentDef> {
152 const lines = text.replace(/^/, '').split(/\r?\n/)
153 if (lines[0]?.trimEnd() !== '---') return { error: NO_FRONTMATTER }
154 const close = lines.findIndex((l, i) => i > 0 && l.trimEnd() === '---')
155 if (close < 0) return { error: 'the frontmatter has no closing --- line' }
156 const fields = new Map<string, string | string[]>()
157 const bare = new Set<string>()
158 let list: string[] | undefined
159 for (let i = 1; i < close; i++) {
160 const line = lines[i] as string
161 const at = `line ${i + 1}`
162 if (/^\s*(#.*)?$/.test(line)) continue
163 const item = /^\s*-(?:\s+(.*))?$/.exec(line)
164 if (item !== null) {
165 if (list === undefined) return { error: `${at}: a list item with no key above it` }
166 const v = scalar(item[1] ?? '')
167 if (typeof v !== 'string') return { error: `${at}: ${v.error}` }
168 list.push(v)
169 continue
170 }
171 const kv = /^([A-Za-z_][\w-]*):(?:\s+(.*))?$/.exec(line)
172 if (kv === null) return { error: `${at}: not a "key: value" line, a "- item" of a list, or a comment` }
173 const key = kv[1] as string
174 const raw = (kv[2] ?? '').trim()
175 if (fields.has(key)) return { error: `${at}: ${key} is given twice` }
176 list = undefined
177 if (raw === '') {
178 fields.set(key, (list = []))
179 bare.add(key)
180 continue
181 }
182 const v = raw.startsWith('[') ? flowList(raw) : scalar(raw)
183 if (!Array.isArray(v) && typeof v !== 'string') return { error: `${at}: ${v.error}` }
184 fields.set(key, v)
185 }
186 for (const key of bare) if ((fields.get(key) as string[]).length === 0) fields.delete(key)
187 const def: AgentDef = { prompt: lines.slice(close + 1).join('\n').trim() }
188 for (const key of ['name', 'description', 'model', 'effort', 'isolation', 'permissionMode'] as const) {
189 const v = fields.get(key)
190 if (Array.isArray(v)) return { error: `${key} must be text, not a list` }
191 if (v !== undefined) def[key] = v
192 }
193 for (const key of ['tools', 'disallowedTools'] as const) {
194 const v = fields.get(key)
195 if (v !== undefined) def[key] = toolNames(v)
196 }
197 if (def.prompt === '') return { error: 'the body (the system prompt) is empty' }
198 return def
199}
200
201// installed_plugins.json's plugins (version 2: `plugins` maps `<name>@<marketplace>` to its installs).
202export function parseInstalled(text: string): Parsed<{ plugins: InstalledPlugins }> {
203 let raw: unknown
204 try {
205 raw = JSON.parse(text)
206 } catch (err) {
207 return { error: `not JSON (${String(err)})` }
208 }
209 const plugins = isObject(raw) ? raw['plugins'] : undefined
210 if (!isObject(plugins)) return { error: 'no plugins object' }
211 for (const [key, installs] of Object.entries(plugins)) if (!Array.isArray(installs)) return { error: `plugins.${key} is not a list of installs` }
212 return { plugins: plugins as InstalledPlugins }
213}
214
215// The directory `plugin` loads from: the absolute `installPath` of its install for the project `cwd` is in
216// (`cwd` itself or a directory beneath it; of several, the one with the longest `projectPath`), else of its
217// install for every project (one with no `projectPath`). A name installed from two marketplaces is not
218// guessed between.
219export function pluginRoot(plugins: InstalledPlugins, plugin: string, cwd: string): Parsed<{ root: string }> {
220 const keys = Object.keys(plugins).filter(k => k.startsWith(`${plugin}@`))
221 if (keys.length === 0) return { error: `plugin ${plugin} is not installed` }
222 if (keys.length > 1) return { error: `plugin ${plugin} is installed from more than one marketplace (${keys.join(', ')})` }
223 const key = keys[0] as string
224 const installs = (plugins[key] ?? []).filter(isObject)
225 const comparable = (path: string) => {
226 const normalized = path.replace(/\\/g, '/').replace(/\/+$/, '')
227 return /^[A-Za-z]:\//.test(normalized) || normalized.startsWith('//') ? normalized.toLowerCase() : normalized
228 }
229 const current = comparable(cwd)
230 const covering = installs.flatMap(i => {
231 const path = i['projectPath']
232 const parent = typeof path === 'string' ? comparable(path) : undefined
233 return parent !== undefined && (current === parent || current.startsWith(`${parent}/`)) ? [{ install: i, path: parent }] : []
234 })
235 const deepest = covering.sort((a, b) => b.path.length - a.path.length)[0]
236 const install = deepest?.install ?? installs.find(i => i['projectPath'] === undefined)
237 const root = install?.['installPath']
238 return typeof root === 'string' && !/[\0\r\n]/.test(root) && (root.startsWith('/') || /^[A-Za-z]:[\\/]/.test(root) || /^\\\\[^\\]+\\[^\\]+/.test(root))
239 ? { root: root.replace(/[\\/]+$/, '') }
240 : { error: `plugin ${key} has no install for ${cwd}` }
241}
242
243// Whether a definition lets its agent call `tool`: listed in `tools` (or `tools` left out, or `*`), and not
244// in `disallowedTools`.
245export const allowsTool = (def: AgentDef, tool: string) =>
246 (def.tools === undefined || def.tools.includes('*') || def.tools.includes(tool)) && !(def.disallowedTools ?? []).includes(tool)
247
248// What the installed claude offers an agent, where its capture saw the tool: `known` are the tools the capture
249// saw, `offered` the ones the engine gives that agent (see native-tools.ts offeredTools).
250export type EngineOffer = { known: ReadonlySet<string>; offered: ReadonlySet<string> }
251
252// Which of its parent's tools a routed subagent may call. A tool the capture saw is offered when the engine offers
253// it to that agent (`engine`), and a custom type's must also be one its definition allows. Any other tool (an MCP
254// server's, or one the headless capture cannot see) follows the static rules: never a main-only one
255// (SUBAGENT_DENIED); a custom type's, as its definition allows; any other type's (or a custom one whose definition
256// did not read), what AGENT_ALLOWED lets its type call, less what AGENT_DENIED denies it.
257export function toolFilter(type: string | undefined, def: AgentDef | undefined, engine?: EngineOffer): (tool: string) => boolean {
258 const seen = (tool: string) => engine !== undefined && engine.known.has(tool)
259 if (def !== undefined) return tool => allowsTool(def, tool) && (seen(tool) ? engine!.offered.has(tool) : !SUBAGENT_DENIED.includes(tool))
260 const allowed = own(AGENT_ALLOWED, type ?? '')
261 const denied = own(AGENT_DENIED, type ?? '') ?? []
262 return tool => seen(tool) ? engine!.offered.has(tool) : !SUBAGENT_DENIED.includes(tool) && !denied.includes(tool) && (allowed === undefined || allowed.includes(tool))
263}
264
265// --- the built-in types -------------------------------------------------------------------------------------
266
267// Built-in types styx cannot run itself: comment-thread-analyst builds its prompt from the thread it is given. A
268// plain Agent call of one stays native, and a styx agent call naming one is denied. A fork is not among them: it
269// runs on its parent's prompt (prompts.ts) and is claimed on its parent's route (inherit.ts).
270export const NOT_REPRODUCED: readonly string[] = ['comment-thread-analyst']
271// The agent type of a fork, which the engine runs with its parent's context and model.
272export const FORK = 'fork'
273
274// Whether an agent type names a fork as Claude Code reads it: NFKC-normalised, lowercased, and with whitespace, `-`
275// and `_` removed, it is `fork`. The engine starts such a call as a fork whatever its spelling, so styx must hold
276// every spelling to the fork rule, not only the exact one.
277export const isFork = (type: unknown): boolean => typeof type === 'string' && type.normalize('NFKC').toLowerCase().replace(/[\s_-]/g, '') === FORK
278
279// --- a routed subagent's identity ------------------------------------------------------------------------------
280
281// The line naming what answers a routed step: its model and provider.
282export const identityLine = (model: string, provider: string) => `You are powered by ${model} served by the ${provider} provider.`
283
284// How a fork delivers its result. Claude Code offers a fork no SubagentHandback: the fork's final message is what
285// reaches the conversation that started it.
286export const FORK_REPORT = `You are a fork: a copy of the conversation above, started to do the task in this message while that conversation goes on. Do only that task, then end with your full report as your final message. That message is what reaches the conversation that started you; no tool delivers it.`
287hooks/family.ts 133 lines1// Same-family defaults. A conversation on a routed model keeps its subagents,
2// skill aliases and auxiliary work on that model's provider unless the caller
3// explicitly chooses another family. Native Claude aliases are tier requests.
4
5export const NATIVE_ALIASES = ['haiku', 'sonnet', 'opus', 'fable'] as const
6export type NativeAlias = typeof NATIVE_ALIASES[number]
7export type Tier = NativeAlias | 'default'
8/** Optional per-family tier models from rice-multi-models.json `tiers`. */
9export type TierMap = Readonly<Record<string, Partial<Record<Tier, string>>>>
10export const CLAUDE_FAMILY = 'claude'
11
12export type FamilyPorts = {
13 isRouted: (model: string) => boolean
14 /** The provider id a routed model belongs to (`codex`, a declared provider id). */
15 providerOf: (model: string) => string | undefined
16 /** A family's default model when no conversation of it is the parent. */
17 defaultModel: (family: string) => string | undefined
18}
19
20export function isNativeAlias(model: string | undefined): model is NativeAlias {
21 return model !== undefined && (NATIVE_ALIASES as readonly string[]).includes(model)
22}
23
24/** The tier a native alias or recognized Claude model id names. */
25const CLAUDE_MODEL_TIERS: Readonly<Record<string, NativeAlias>> = {
26 'claude-haiku-4-5': 'haiku',
27 'claude-haiku-5-5': 'haiku',
28 'claude-sonnet-4-5': 'sonnet',
29 'claude-sonnet-4-6': 'sonnet',
30 'claude-sonnet-5': 'sonnet',
31 'claude-sonnet-5-5': 'sonnet',
32 'claude-opus-4-5': 'opus',
33 'claude-opus-4-6': 'opus',
34 'claude-opus-4-7': 'opus',
35 'claude-opus-4-8': 'opus',
36 'claude-opus-5': 'opus',
37 'claude-opus-5-5': 'opus',
38 'claude-fable-5': 'fable',
39 'claude-fable-5-1': 'fable',
40}
41const CLAUDE_1M_MODEL_IDS = new Set([
42 'claude-haiku-5-5',
43 'claude-sonnet-4-6',
44 'claude-sonnet-5',
45 'claude-sonnet-5-5',
46 'claude-opus-4-6',
47 'claude-opus-4-7',
48 'claude-opus-4-8',
49 'claude-opus-5',
50 'claude-opus-5-5',
51 'claude-fable-5',
52 'claude-fable-5-1',
53])
54
55export function tierOf(model: string | undefined): NativeAlias | undefined {
56 if (model === undefined) return undefined
57 if (isNativeAlias(model)) return model
58 const oneMillion = model.endsWith('[1m]')
59 const id = oneMillion ? model.slice(0, -'[1m]'.length) : model
60 const tier = CLAUDE_MODEL_TIERS[id]
61 return tier !== undefined && (!oneMillion || CLAUDE_1M_MODEL_IDS.has(id)) ? tier : undefined
62}
63
64export function familyOf(model: string | undefined, ports: Pick<FamilyPorts, 'isRouted' | 'providerOf'>): string {
65 return model !== undefined && ports.isRouted(model) ? ports.providerOf(model) ?? CLAUDE_FAMILY : CLAUDE_FAMILY
66}
67
68/** The routed model a tier request resolves to inside one family. */
69export function tierModel(family: string, tier: string | undefined, anchor: string | undefined, tiers: TierMap, ports: FamilyPorts): string | undefined {
70 const configured = tiers[family]
71 const named = tierOf(tier)
72 const chosen = (named ? configured?.[named] : undefined) ?? configured?.default
73 if (chosen !== undefined && ports.isRouted(chosen) && familyOf(chosen, ports) === family) return chosen
74 if (anchor !== undefined && ports.isRouted(anchor) && familyOf(anchor, ports) === family) return anchor
75 const fallback = ports.defaultModel(family)
76 return fallback !== undefined && ports.isRouted(fallback) && familyOf(fallback, ports) === family ? fallback : undefined
77}
78
79export type SpawnInput = {
80 /** The parent's effective model (agent.spawn `parentModel`). */
81 parentModel: string
82 /** The Agent tool's `model` argument, or a hook's rewrite. */
83 requested?: string
84 /** The definition's own `model`, when a readable definition names one. */
85 definitionModel?: string
86 fork: boolean
87}
88export type SpawnDecision = { model?: string; family: string; explicit: boolean; reason: string }
89
90/** What a spawn runs on. Undefined `model` leaves the native resolution alone. */
91export function spawnDecision(input: SpawnInput, tiers: TierMap, ports: FamilyPorts): SpawnDecision {
92 const parentFamily = familyOf(input.parentModel, ports)
93 if (input.fork) return { family: parentFamily, explicit: false, reason: 'forks inherit their parent model' }
94 const tier = input.requested ?? input.definitionModel
95 if (tier !== undefined && ports.isRouted(tier)) return { model: tier, family: familyOf(tier, ports), explicit: true, reason: input.requested === undefined ? 'the agent definition names a routed model' : 'an explicit routed model was requested' }
96 if (tier !== undefined && tier !== 'inherit' && !isNativeAlias(tier)) return { family: CLAUDE_FAMILY, explicit: true, reason: 'an explicit native model was requested' }
97 if (parentFamily === CLAUDE_FAMILY) return { family: CLAUDE_FAMILY, explicit: false, reason: 'the parent runs on Claude' }
98 const model = tierModel(parentFamily, tier === 'inherit' ? undefined : tier, input.parentModel, tiers, ports)
99 return model === undefined
100 ? { family: parentFamily, explicit: false, reason: `no ${parentFamily} model is available` }
101 : { model, family: parentFamily, explicit: false, reason: `subagents default to the parent's ${parentFamily} family` }
102}
103
104/**
105 * A loop's step model. A native alias inside a routed family (a skill's
106 * `model: haiku`, an unspawned fork) resolves within the owner's family unless
107 * the loop was explicitly placed on Claude.
108 */
109export function stepModel(requested: string, owner: string | undefined, explicitClaude: boolean, tiers: TierMap, ports: FamilyPorts): string {
110 if (explicitClaude || ports.isRouted(requested) || owner === undefined || !ports.isRouted(owner)) return requested
111 const family = familyOf(owner, ports)
112 return tierModel(family, requested, owner, tiers, ports) ?? owner
113}
114
115/** Parses the optional top-level `tiers` block of rice-multi-models.json. */
116export function parseTiers(value: unknown): { tiers: TierMap; errors: string[] } {
117 if (value === undefined) return { tiers: {}, errors: [] }
118 const errors: string[] = []
119 const tiers: Record<string, Partial<Record<Tier, string>>> = {}
120 if (value === null || typeof value !== 'object' || Array.isArray(value)) return { tiers, errors: ['tiers must be an object of family id to { default, haiku, sonnet, opus, fable } model ids'] }
121 for (const [family, map] of Object.entries(value)) {
122 if (map === null || typeof map !== 'object' || Array.isArray(map)) { errors.push(`tiers.${family} must be an object`); continue }
123 const entry: Partial<Record<Tier, string>> = {}
124 for (const [tier, model] of Object.entries(map as Record<string, unknown>)) {
125 if (tier !== 'default' && !isNativeAlias(tier)) { errors.push(`tiers.${family}.${tier} is not one of default, ${NATIVE_ALIASES.join(', ')}`); continue }
126 if (typeof model !== 'string' || !model.includes('/')) { errors.push(`tiers.${family}.${tier} must be a routed model id such as ${family}/<model>`); continue }
127 entry[tier as Tier] = model
128 }
129 tiers[family] = entry
130 }
131 return { tiers, errors }
132}
133hooks/backend.ts 141 lines1// The helper that calls providers, seen from the mod. The shipped Node helper (`serve`, started
2// at session start) keeps one provider connection per conversation; each step reaches it through its client on
3// its private Unix socket, the token in the request body. When it is not running a step starts a one-shot
4// helper (`once`) instead. Either way the step goes in on standard input and its events come back one JSON
5// line at a time; leaving the loop, or the dispatch being abandoned, kills the process and so cancels the
6// provider request.
7import type { ModelUsage, ProcessSpawnChunk, ProcessSpawnResult } from 'claude-code'
8
9import type { StepEvent, StepFailureCause, StepWire, StopReason } from './protocol'
10
11type Child = AsyncGenerator<ProcessSpawnChunk, ProcessSpawnResult, void>
12
13/** How the mod starts processes; register.ts builds it over `$.process.spawn`. */
14export type HelperPort = {
15 once: (input: string) => Child
16 client: (input: string, socketPath: string) => Child
17}
18
19/** The running session helper: where it listens and the token every call carries. */
20export type SessionHelper = { socketPath: string; token: string }
21
22let session: SessionHelper | undefined
23let useSession = true
24
25export function setSessionHelper(helper: SessionHelper | undefined): void {
26 session = helper
27}
28
29export function sessionHelper(): SessionHelper | undefined {
30 return session
31}
32
33/** Whether steps go to the session helper when it runs (else always one process per step). */
34export function preferSession(prefer: boolean): void {
35 useSession = prefer
36}
37
38/** The session helper's structured announcement, only after its entire line arrives. */
39export function readyLine(text: string): SessionHelper | undefined {
40 for (const line of text.split('\n').slice(0, -1)) {
41 if (!line.startsWith('ready ')) continue
42 try {
43 const value: unknown = JSON.parse(line.slice(6))
44 if (!value || typeof value !== 'object' || Array.isArray(value)) continue
45 const ready = value as Record<string, unknown>
46 if (typeof ready.socketPath === 'string' && ready.socketPath !== '' && !/[\r\n\0]/.test(ready.socketPath) && typeof ready.token === 'string' && /^[0-9a-f]{64}$/.test(ready.token)) return { socketPath: ready.socketPath, token: ready.token }
47 } catch { /* A partial or malformed announcement is not readiness. */ }
48 }
49 return undefined
50}
51
52const lastLine = (text: string) => text.trim().split('\n').at(-1)?.slice(0, 300) ?? ''
53
54/** A child's events, and how it ended. */
55async function* eventsOf(child: Child, ended: { code: number | null; stderr: string; events: number }): AsyncGenerator<StepEvent> {
56 let buffer = ''
57 let next = await child.next()
58 while (!next.done) {
59 const piece = next.value
60 if (piece.stream === 'stderr') ended.stderr = (ended.stderr + piece.text).slice(-4000)
61 else {
62 buffer += piece.text
63 let newline = buffer.indexOf('\n')
64 while (newline >= 0) {
65 const line = buffer.slice(0, newline).trim()
66 buffer = buffer.slice(newline + 1)
67 newline = buffer.indexOf('\n')
68 if (line === '') continue
69 let event: StepEvent
70 try {
71 event = JSON.parse(line) as StepEvent
72 } catch {
73 continue
74 }
75 ended.events += 1
76 yield event
77 }
78 }
79 next = await child.next()
80 }
81 ended.code = next.value.code
82}
83
84/** Client exit 3 means unavailable before sending a request. Other failures must never be replayed. */
85const UNREACHED = new Set([3])
86
87/**
88 * A step's events. Through the session helper when it runs; a call it never answered goes to a one-shot
89 * helper instead, and the session helper is forgotten until it announces itself again. A helper that ends
90 * without a stop or an error yields one error.
91 */
92export async function* helperStep(port: HelperPort, wire: StepWire): AsyncGenerator<StepEvent> {
93 let finished = false
94 const helper = useSession ? session : undefined
95 if (helper) {
96 const ended = { code: null as number | null, stderr: '', events: 0 }
97 for await (const event of eventsOf(port.client(JSON.stringify({ ...wire, token: helper.token }), helper.socketPath), ended)) {
98 if (event.type === 'stop' || event.type === 'error') finished = true
99 yield event
100 }
101 if (finished) return
102 if (ended.events > 0 || !UNREACHED.has(ended.code ?? -1)) {
103 yield { type: 'error', kind: 'request', text: `rice-multi-models: the session helper ended the step without an answer (client exit ${ended.code})` }
104
105 return
106 }
107 if (session === helper) session = undefined
108 }
109 const ended = { code: null as number | null, stderr: '', events: 0 }
110 for await (const event of eventsOf(port.once(JSON.stringify(wire)), ended)) {
111 if (event.type === 'stop' || event.type === 'error') finished = true
112 yield event
113 }
114 if (!finished) yield { type: 'error', kind: 'request', text: `rice-multi-models: the helper ended without an answer${ended.stderr ? ` (${lastLine(ended.stderr)})` : ''}` }
115}
116
117/** A whole answer as text, for compaction and one-shot completions. */
118export async function collectText(port: HelperPort, wire: StepWire, signal?: AbortSignal): Promise<{ text: string; usage?: ModelUsage; error?: string; cause?: StepFailureCause; status?: number; aborted?: boolean; stopReason?: StopReason }> {
119 let text = ''
120 let usage: ModelUsage | undefined
121 let error: string | undefined
122 let cause: StepFailureCause | undefined
123 let status: number | undefined
124 let aborted = false
125 let stopReason: StopReason | undefined
126 try {
127 for await (const event of helperStep(port, wire)) {
128 if (event.type === 'text') text += event.text
129 else if (event.type === 'usage') usage = { input_tokens: event.in, output_tokens: event.out, cache_read_input_tokens: event.cacheRead, cache_creation_input_tokens: event.cacheWrite }
130 else if (event.type === 'error') { error = event.text; cause = event.cause; status = event.status; aborted = event.aborted === true }
131 else if (event.type === 'stop') stopReason = event.reason
132 }
133 } catch (failure) {
134 error ??= 'The routed helper stream did not complete.'
135 aborted ||= signal?.aborted === true || failure instanceof Error && (failure.name === 'AbortError' || failure.name === 'TimeoutError')
136 }
137 aborted ||= signal?.aborted === true
138
139 return { text, ...(usage ? { usage } : {}), ...(error !== undefined ? { error } : {}), ...(cause ? { cause } : {}), ...(status === undefined ? {} : { status }), ...(aborted ? { aborted: true } : {}), ...(stopReason ? { stopReason } : {}) }
140}
141hooks/carry.ts 54 lines1// Reasoning a provider returns encrypted, carried back on later steps. The engine shows thinking a hook
2// streams but does not record it, so the mod keeps each step's reasoning by the first tool call it led to and
3// puts it back, as `thinking` blocks before that call, in the transcript it sends next. Pure.
4import type { ApiMessage } from './protocol'
5import { setCapped } from './util'
6
7export type Reasoning = { thinking: string; signature: string; at?: number }
8export type Carry = Map<string, readonly Reasoning[]>
9
10const CARRY_MAX = 400
11
12/** Keeps a step's reasoning under its first tool call; the oldest entries go first past the bound. */
13export function remember(carry: Carry, firstToolId: string | undefined, reasoning: readonly Reasoning[]): void {
14 if (!firstToolId || reasoning.length === 0) return
15 carry.set(firstToolId, reasoning)
16 while (carry.size > CARRY_MAX) {
17 const oldest = carry.keys().next().value
18 if (oldest === undefined) break
19 carry.delete(oldest)
20 }
21}
22
23/** The transcript with each kept reasoning put back at the head of the assistant message holding its tool call. */
24export function withCarry(messages: readonly ApiMessage[], carry: Carry): readonly ApiMessage[] {
25 if (carry.size === 0) return messages
26 let changed = false
27 const out = messages.map(message => {
28 if (message.role !== 'assistant' || typeof message.content === 'string') return message
29 const first = message.content.find(block => block.type === 'tool_use' && typeof block['id'] === 'string')
30 const kept = first ? carry.get(first['id'] as string) : undefined
31 if (!kept) return message
32 changed = true
33 const clean = message.content.filter(block => block.type !== 'thinking' && block.type !== 'redacted_thinking')
34 const at = (index: number) => kept.filter(item => (item.at ?? 0) === index).map(item => ({ type: 'thinking', thinking: item.thinking, signature: item.signature }))
35 const tail = kept.filter(item => (item.at ?? 0) >= clean.length).map(item => ({ type: 'thinking', thinking: item.thinking, signature: item.signature }))
36 return { ...message, content: [...clean.flatMap((block, index) => [...at(index), block]), ...tail] }
37 })
38
39 return changed ? out : messages
40}
41
42const carries = new Map<string, Carry>()
43
44/** The reasoning kept for one conversation (`main`, or a subagent's id). */
45export function carryFor(who: string): Carry {
46 let carry = carries.get(who)
47 if (!carry) {
48 carry = new Map()
49 setCapped(carries, who, carry)
50 }
51
52 return carry
53}
54hooks/continuation.ts 71 lines1// Operational protocol extras only. The native transcript remains the conversation owner.
2import type { Kind } from './config'
3import type { Placed } from '../helper/styx/history'
4
5export type ContinuationPolicy = { mode: 'off' } | { mode: 'durable'; maxAgeSeconds: number }
6export const CONTINUATION_OFF: ContinuationPolicy = { mode: 'off' }
7export const CONTINUATION_BUDGET = 2 * 1024 * 1024
8export const CONTINUATION_RECORD_MAX = 128 * 1024
9export const CONTINUATION_OWNER_MAX = 256
10export const CONTINUATION_PREFIX = 'continuation:v1:'
11export type ContinuationAdapter = Kind | 'codex-responses'
12export type ContinuationRecord = {
13 version: 1
14 owner: string
15 scope: string
16 adapter: ContinuationAdapter
17 createdAt: number
18 expiresAt: number
19 boundary: { turnId: string; index: number }
20 prefixLength: number
21 prefixDigest: string
22 contextDigest: string
23 dispatchedDigest: string
24 callsDigest: string
25 assistantDigest: string
26 calls: readonly { id: string; providerId?: string }[]
27 blocks: readonly Placed[]
28 integrity: string
29}
30
31// Exhaustive wire contracts, not configured provider names. A new adapter must declare and test its contract.
32const CONTRACTS: Readonly<Record<ContinuationAdapter, 'none' | 'opaque'>> = {
33 openai: 'none', responses: 'opaque', 'codex-responses': 'opaque', gemini: 'opaque', anthropic: 'opaque', bedrock: 'opaque',
34}
35export function continuationCapability(adapter: ContinuationAdapter) {
36 return { adapter, history: 'native replay', extra: CONTRACTS[adapter],
37 detail: CONTRACTS[adapter] === 'none' ? 'no extra protocol state required'
38 : adapter === 'anthropic' || adapter === 'bedrock' ? 'redacted/empty-text signed extras only; plaintext signed state blocked' : 'exact-scope opaque provider protocol extras',
39 } as const
40}
41
42export function parseContinuation(value: unknown, errors: string[]): ContinuationPolicy {
43 if (value === undefined) return CONTINUATION_OFF
44 if (!value || typeof value !== 'object' || Array.isArray(value)) {
45 errors.push('continuation: must be { mode: "off" } or { mode: "durable", maxAgeSeconds: 1..86400 }')
46 return CONTINUATION_OFF
47 }
48 const v = value as Record<string, unknown>
49 if (Object.keys(v).some(key => key !== 'mode' && key !== 'maxAgeSeconds') ||
50 v['mode'] !== 'off' && v['mode'] !== 'durable' ||
51 v['mode'] === 'off' && v['maxAgeSeconds'] !== undefined ||
52 v['mode'] === 'durable' && (!Number.isSafeInteger(v['maxAgeSeconds']) || Number(v['maxAgeSeconds']) < 1 || Number(v['maxAgeSeconds']) > 86400)) {
53 errors.push('continuation: off by default; durable requires an explicit maxAgeSeconds from 1 to 86400 after owner policy review')
54 return CONTINUATION_OFF
55 }
56 return v['mode'] === 'durable' ? { mode: 'durable', maxAgeSeconds: Number(v['maxAgeSeconds']) } : CONTINUATION_OFF
57}
58
59export function continuationStatus(policy: ContinuationPolicy, adapters: readonly ContinuationAdapter[], last = 'not used', expiredRecordsRemoved = 0) {
60 return { mode: policy.mode, history: 'native replay', capabilities: [...new Set(adapters)].map(continuationCapability),
61 maxAgeSeconds: policy.mode === 'durable' ? policy.maxAgeSeconds : null,
62 budgetBytes: CONTINUATION_BUDGET, recordMaxBytes: CONTINUATION_RECORD_MAX, recordsPerOwner: CONTINUATION_OWNER_MAX, status: last, expiredRecordsRemoved,
63 privacy: 'plugin-wide native store; logical owner separation, not host-enforced isolation',
64 cleanup: 'read-time expiry; serialized expiry cleanup; synchronous session clear; no active-owner eviction',
65 policy: 'owner review required before real-data activation; 24h is a configurable proposal ceiling, not approved retention',
66 }
67}
68
69export const continuationOwnerPrefix = (session: string, owner: string) => `${CONTINUATION_PREFIX}${encodeURIComponent(session)}:${encodeURIComponent(owner)}:`
70export const continuationSessionPrefix = (session: string) => `${CONTINUATION_PREFIX}${encodeURIComponent(session)}:`
71hooks/continuation-store.ts 86 lines1import type { EngineInterface } from 'claude-code'
2import { CONTINUATION_BUDGET, CONTINUATION_PREFIX, CONTINUATION_RECORD_MAX, CONTINUATION_OWNER_MAX, continuationOwnerPrefix, continuationSessionPrefix } from './continuation'
3import type { ContinuationRecord } from './continuation'
4import { helperFile } from './setup'
5
6export type ContinuationStorePort = {
7 keys(): Promise<string[]>
8 get(key: string): Promise<unknown>
9 set(key: string, value: unknown): Promise<void>
10 delete(key: string): Promise<void>
11}
12const RETIRED_PREFIX = 'continuation-retired:v1:'
13const BLOCKED_KEY = 'continuation-budget-blocked:v1'
14const retiredKey = (session: string) => RETIRED_PREFIX + encodeURIComponent(session)
15const bytes = (value: unknown) => new TextEncoder().encode(JSON.stringify(value) ?? 'null').length
16const record = (value: unknown): value is ContinuationRecord => !!value && typeof value === 'object' && !Array.isArray(value) && (value as ContinuationRecord).version === 1 && Number.isFinite((value as ContinuationRecord).expiresAt)
17const owns = (key: string) => key.startsWith(CONTINUATION_PREFIX) || key.startsWith(RETIRED_PREFIX) || key === BLOCKED_KEY
18async function usedBytes(store: ContinuationStorePort, except?: string): Promise<number> {
19 let used = 2
20 for (const key of await store.keys()) if (owns(key) && key !== except) used += bytes(key) + bytes(await store.get(key)) + 2
21 return used
22}
23
24// Caller holds the cross-process lock over enumeration, cleanup, admission and mutation. Never a racy CAS.
25export async function continuationRecords(store: ContinuationStorePort, session: string, owner: string, now: number, expired?: () => void): Promise<unknown[]> {
26 if (await store.get(BLOCKED_KEY)) throw new Error('Continuation metadata budget exhausted; durable mode is blocked pending policy review')
27 if (await store.get(retiredKey(session)) !== undefined) return []
28 const prefix = continuationOwnerPrefix(session, owner)
29 const out: unknown[] = []
30 for (const key of await store.keys()) {
31 if (!key.startsWith(CONTINUATION_PREFIX)) continue
32 const value = await store.get(key)
33 if (record(value) && value.expiresAt <= now) { await store.delete(key); expired?.() }
34 else if (key.startsWith(prefix) && bytes(value) <= CONTINUATION_RECORD_MAX && out.length < CONTINUATION_OWNER_MAX) out.push(value)
35 }
36 return out
37}
38
39export async function saveContinuation(store: ContinuationStorePort, session: string, owner: string, value: ContinuationRecord, now: number): Promise<'saved' | 'expired' | 'budget-full' | 'cleared'> {
40 if (await store.get(BLOCKED_KEY)) return 'budget-full'
41 if (await store.get(retiredKey(session)) !== undefined) return 'cleared'
42 if (value.expiresAt <= now) return 'expired'
43 if (bytes(value) > CONTINUATION_RECORD_MAX) return 'budget-full'
44 await continuationRecords(store, session, owner, now)
45 const prefix = continuationOwnerPrefix(session, owner)
46 const key = prefix + value.scope + ':' + value.integrity
47 const keys = await store.keys()
48 if (!keys.includes(key) && keys.filter(existing => existing.startsWith(prefix)).length >= CONTINUATION_OWNER_MAX) return 'budget-full'
49 const used = await usedBytes(store, key) + bytes(key) + bytes(value) + 2
50 // Reserve room for a fixed fail-closed latch if session-retirement metadata eventually fills its budget.
51 if (used > CONTINUATION_BUDGET - 1024) return 'budget-full'
52 // Immutable per-dispatch keys: another active owner's state is never evicted to make room.
53 await store.set(key, value)
54 return 'saved'
55}
56
57export async function clearContinuations(store: ContinuationStorePort, session: string): Promise<number> {
58 const prefix = continuationSessionPrefix(session)
59 let count = 0
60 // Fence first: even a failed/aborted deletion must not admit a late writer.
61 // A late dispatch cannot resurrect a cleared session. Reference-only retirement markers do not expire.
62 // If their bounded allowance fills, block all later durable writes rather than evict an active owner.
63 const retired = retiredKey(session)
64 if (await usedBytes(store, retired) + bytes(retired) + 6 > CONTINUATION_BUDGET - 1024) await store.set(BLOCKED_KEY, true)
65 else await store.set(retired, true)
66 for (const key of await store.keys()) if (key.startsWith(prefix)) { await store.delete(key); count++ }
67 // A successful return means deletion was awaited, not scheduled as best effort.
68 if ((await store.keys()).some(key => key.startsWith(prefix))) throw new Error('Continuation clear verification failed')
69 return count
70}
71
72export async function withContinuationStore<T>($: EngineInterface, executable: string, operation: (store: ContinuationStorePort) => Promise<T>): Promise<T> {
73 const config = await $.env.get('CLAUDE_CONFIG_DIR') || `${await $.env.get('HOME') || await $.env.get('USERPROFILE') || ''}/.claude`
74 const child = $.process.spawn({ argv: [executable, helperFile($.plugin.root), 'continuation-lock', config] })
75 let output = ''
76 try {
77 for (;;) {
78 const piece = await child.next()
79 if (piece.done) throw new Error('Continuation store lock unavailable; durable mode is blocked. Inspect the configured rice-multi-models/continuation.lock and stop confirmed holders before explicit stale-lock recovery; locks are never stolen. Off/history-only chat does not require this lock.')
80 if (piece.value.stream === 'stdout') output = (output + piece.value.text).slice(-1000)
81 if (output.includes('continuation-lock-acquired\n')) break
82 }
83 return await operation({ keys: () => $.store.keys(), get: key => $.store.get(key), set: (key, value) => $.store.set(key, value), delete: key => $.store.delete(key) })
84 } finally { await child.return({ code: null, signal: null }) }
85}
86hooks/compact.ts 125 lines1import type { ApiMessage } from './protocol'
2
3/** Public compaction rows. Handles stay local and are never sent to a provider. */
4export type CompactMessage = {
5 role: 'user' | 'assistant'
6 text: string
7 toolUses: { tool_use_id: string; tool: string; input: Record<string, unknown>; result?: unknown; text?: string; isError?: true; agentId?: string; durationMs?: number }[]
8 toolResults?: { tool_use_id: string; text: string; result?: unknown; isError: boolean }[]
9 handle?: string
10}
11
12/**
13 * Recover a capped source, not a transcript branch: the compact event supplies the
14 * complete order and each native UUID. Disk is context only; the caller still owns
15 * cancellation, current public/API snapshots and model checks. Only plain text and
16 * completed native tool exchanges are supported, with exact event/suffix agreement.
17 * Same-session meta/virtual context is unsupported, even when potentially archived.
18 */
19export function persistedCompactSource(jsonl: string, messages: readonly CompactMessage[], session: string, api: readonly ApiMessage[]): ApiMessage[] {
20 const fail = (reason: string): never => { throw new Error(`persisted compaction context ${reason}`) }
21 const object = (value: unknown): Record<string, unknown> | undefined => value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : undefined
22 const textBlocks = (content: unknown): { type: 'text'; text: string }[] => {
23 if (typeof content === 'string') return [{ type: 'text', text: content }]
24 if (!Array.isArray(content)) return fail('has unsupported message content')
25 return content.map(value => {
26 const block = object(value)
27 if (block?.type !== 'text' || typeof block.text !== 'string' || Object.keys(block).some(key => !['type', 'text', 'citations'].includes(key)) || block.citations != null && (!Array.isArray(block.citations) || block.citations.length > 0)) return fail('has unsupported non-text or annotated content')
28 return { type: 'text', text: block.text }
29 })
30 }
31 const same = (left: unknown, right: unknown) => {
32 const encode = (value: unknown) => JSON.stringify(value, (_, item) => object(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item)
33 return encode(left) === encode(right)
34 }
35 const blocks = (content: unknown, role: CompactMessage['role']): ({ type: string } & Record<string, unknown>)[] => {
36 if (typeof content === 'string') return textBlocks(content)
37 if (!Array.isArray(content)) return fail('has unsupported message content')
38 return content.map(value => {
39 const block = object(value)
40 if (block?.type === 'text') return textBlocks([block])[0]!
41 if (role === 'assistant' && block?.type === 'tool_use' && typeof block.id === 'string' && block.id && typeof block.name === 'string' && block.name && object(block.input) && Object.keys(block).every(key => ['type', 'id', 'name', 'input'].includes(key))) return { ...block, type: 'tool_use' }
42 if (role === 'user' && block?.type === 'tool_result' && typeof block.tool_use_id === 'string' && block.tool_use_id && (block.is_error === undefined || typeof block.is_error === 'boolean') && Object.keys(block).every(key => ['type', 'tool_use_id', 'content', 'is_error'].includes(key))) {
43 const text = textBlocks(block.content)
44 return { ...block, type: 'tool_result', content: typeof block.content === 'string' ? block.content : text }
45 }
46 return fail('has unsupported tool, media or annotated content')
47 })
48 }
49 const handles = new Set(messages.map(message => message.handle))
50 if (handles.has(undefined) || handles.has('') || handles.size !== messages.length) return fail('has missing or duplicate event UUIDs')
51 if (!jsonl.endsWith('\n')) return fail('has an incomplete or unflushed row')
52 const records = new Map<string, Record<string, unknown>>()
53 for (const line of jsonl.split('\n')) {
54 if (!line.trim()) continue
55 let row: Record<string, unknown> | undefined
56 try { row = object(JSON.parse(line)) } catch { return fail('contains an unreadable or partial row') }
57 if (!row) return fail('contains an unsupported record')
58 if (row.type === 'content-replacement' && row.sessionId === session) return fail('has unsupported content replacements')
59 // Native projection can omit contextual rows. Missing UUIDs cannot prove them inactive.
60 if (row.sessionId === session && (row.type === 'user' || row.type === 'assistant') && (row.isMeta === true || row.isVirtual === true)) return fail('has unsupported meta or virtual context')
61 if (typeof row.uuid !== 'string' || !handles.has(row.uuid)) continue
62 const previous = records.get(row.uuid)
63 if (previous && JSON.stringify(previous) !== JSON.stringify(row)) return fail('has conflicting records for an event UUID')
64 records.set(row.uuid, row)
65 }
66 const calls = new Map<string, CompactMessage['toolUses'][number]>()
67 const results = new Map<string, NonNullable<CompactMessage['toolResults']>[number]>()
68 const projected: CompactMessage[] = []
69 const recovered = messages.map(message => {
70 const row = records.get(message.handle!)
71 if (!row) return fail('is missing an event UUID (not persisted or no longer readable)')
72 if (row.sessionId !== session || row.agentId !== undefined || row.isSidechain === true || row.isMeta === true || row.isVirtual === true || object(row.mcpMeta)?._meta !== undefined) return fail('has an unsupported session or message scope')
73 const native = object(row.message)
74 if (row.type !== message.role || native?.role !== message.role) return fail('does not match the event role')
75 const content = blocks(native.content, message.role)
76 const projection: CompactMessage = { role: message.role, text: content.filter(block => block.type === 'text').map(block => block.text).join(''), toolUses: [] }
77 for (const block of content) {
78 if (block.type === 'tool_use') {
79 const id = block.id as string
80 if (calls.has(id)) return fail('has ambiguous duplicate tool calls')
81 const call = { tool_use_id: id, tool: block.name as string, input: block.input as Record<string, unknown> }
82 calls.set(id, call); projection.toolUses.push(call)
83 } else if (block.type === 'tool_result') {
84 const id = block.tool_use_id as string
85 if (!calls.has(id) || results.has(id)) return fail('has missing or ambiguous tool results')
86 const result = { tool_use_id: id, text: textBlocks(block.content).map(text => text.text).join('\n'), isError: block.is_error === true, ...(row.toolUseResult !== undefined && { result: row.toolUseResult }) }
87 results.set(id, result); (projection.toolResults ??= []).push(result)
88 }
89 }
90 projected.push(projection)
91 return { role: message.role, content }
92 })
93 for (const [id, call] of calls) {
94 const result = results.get(id)
95 if (!result) return fail('has pending or missing tool results')
96 Object.assign(call, { text: result.text, ...(result.result !== undefined && { result: result.result }), ...(result.isError && { isError: true }) })
97 // Native Agent/Task enrichment derives these fields from the stored result,
98 // not the live task lookup. The latter alone is excluded from identity.
99 if (['Agent', 'Task'].includes(call.tool)) {
100 const stored = object(result.result)
101 if (typeof stored?.totalDurationMs === 'number') call.durationMs = stored.totalDurationMs
102 }
103 }
104 const identity = ({ role, text, toolUses, toolResults }: CompactMessage) => ({ role, text, toolUses: toolUses.map(({ agentId, ...tool }) => tool), ...(toolResults?.length && { toolResults }) })
105 if (!same(projected.map(identity), messages.map(identity))) return fail('does not match the event text/tool projection')
106 if (!api.length || api.length >= recovered.length) return fail('does not have a capped native API suffix')
107 const normalized = api.map(message => ({ role: message.role, content: blocks(message.content, message.role) }))
108 if (!same(recovered.slice(-api.length), normalized)) return fail('does not match the native API suffix')
109 // Preserve native API normalization for the available suffix, with only its
110 // missing prefix supplied by the UUID-checked persisted API records.
111 return [...recovered.slice(0, -api.length), ...api]
112}
113
114/** The transcript with `text` as the last user turn's final block (a new user turn when it ends on the model). */
115export function withUserText(messages: readonly ApiMessage[], text: string): readonly ApiMessage[] {
116 const last = messages.at(-1)
117 if (last?.role === 'user') {
118 const blocks = typeof last.content === 'string' ? [{ type: 'text', text: last.content }] : last.content
119
120 return [...messages.slice(0, -1), { role: 'user', content: [...blocks, { type: 'text', text }] }]
121 }
122
123 return [...messages, { role: 'user', content: [{ type: 'text', text }] }]
124}
125hooks/native-compaction.ts 90 lines1// Claude Code's own compaction text, learned from the installed claude and rendered here.
2//
3// The engine's summarizer cannot be routed to another provider, so a routed conversation is compacted by this
4// mod. What it sends and what it keeps still comes from the engine: the helper runs the installed claude once
5// per version in an isolated folder against a loopback stub (see helper/native-compaction.ts), records the
6// summary prompt, the slot its `/compact` instructions take and the summary message it writes, and this module
7// turns those captures into a template. Nothing here is a copy of the engine's text.
8export const TRANSCRIPT_TOKEN = '{{transcript}}'
9/** Sent as the summary body and as the `/compact` instructions while capturing; never shown to a model in use. */
10export const SUMMARY_MARK = 'RICECAPTURESUMMARYBODY'
11export const INSTRUCTIONS_MARK = 'ZZRICECAPTUREINSTRUCTIONSZZ'
12
13/** The summary prompt and summary message of one Claude Code version, with the slots filled in at use. */
14export type CompactionTemplate = {
15 version: string
16 /** The prompt's text before and after the place the person's `/compact` instructions go. */
17 promptHead: string
18 promptTail: string
19 /** What the engine writes around those instructions when there are some. */
20 instructionsBefore: string
21 instructionsAfter: string
22 /** The summary message: its text before the summary body and after it (the transcript path is `TRANSCRIPT_TOKEN`). */
23 summaryHead: string
24 summaryTail: string
25}
26
27/** What the capture observed: the prompt with and without instructions, and the summary message with a known body. */
28export type CompactionCapture = {
29 version: string
30 plain: string
31 custom: string
32 summaryMessage: string
33 transcriptPath: string
34}
35
36const TEMPLATE_KEYS = ['version', 'promptHead', 'promptTail', 'instructionsBefore', 'instructionsAfter', 'summaryHead', 'summaryTail'] as const
37
38export function isTemplate(value: unknown): value is CompactionTemplate {
39 if (value === null || typeof value !== 'object') return false
40 const fields = value as Record<string, unknown>
41 return TEMPLATE_KEYS.every(key => typeof fields[key] === 'string') && (fields.promptHead as string).length > 0 && (fields.summaryHead as string).length > 0
42}
43
44/** The template a capture implies; throws when the capture does not have the shape the engine is expected to produce. */
45export function deriveTemplate(capture: CompactionCapture): CompactionTemplate {
46 const { plain, custom } = capture
47 const added = custom.length - plain.length
48 if (added <= 0) throw new Error('the prompt with instructions is not longer than the prompt without')
49 let at = 0
50 while (at < plain.length && plain[at] === custom[at]) at++
51 // One insertion: the rest of the longer prompt is the rest of the shorter one, and the instructions are inside it.
52 if (custom.slice(at + added) !== plain.slice(at)) throw new Error('the instructions are not one insertion into the summary prompt')
53 const inserted = custom.slice(at, at + added)
54 const mark = inserted.indexOf(INSTRUCTIONS_MARK)
55 if (mark < 0) throw new Error('the instructions do not appear in the summary prompt')
56 const body = capture.summaryMessage.indexOf(SUMMARY_MARK)
57 if (body <= 0) throw new Error('the summary body does not appear in the summary message')
58 const tail = capture.summaryMessage.slice(body + SUMMARY_MARK.length)
59 return {
60 version: capture.version,
61 promptHead: plain.slice(0, at),
62 promptTail: plain.slice(at),
63 instructionsBefore: inserted.slice(0, mark),
64 instructionsAfter: inserted.slice(mark + INSTRUCTIONS_MARK.length),
65 summaryHead: capture.summaryMessage.slice(0, body),
66 summaryTail: capture.transcriptPath ? tail.split(capture.transcriptPath).join(TRANSCRIPT_TOKEN) : tail,
67 }
68}
69
70/** The summary prompt for the person's `/compact` instructions, if any, as the engine words it. */
71export function compactionPrompt(template: CompactionTemplate, instructions?: string): string {
72 const text = instructions?.trim()
73 return template.promptHead + (text ? template.instructionsBefore + text + template.instructionsAfter : '') + template.promptTail
74}
75
76/** The summary the model wrote: the inside of its `<summary>` block, else its reply without the `<analysis>` block. */
77export function summaryBody(reply: string): string | undefined {
78 const closed = /<summary>([\s\S]*?)<\/summary>/i.exec(reply)
79 const text = (closed ? closed[1]! : reply.replace(/<analysis>[\s\S]*?<\/analysis>/gi, '').replace(/<\/?summary>/gi, '')).trim()
80 return text === '' ? undefined : text
81}
82
83/** The summary message of a compaction, as the engine writes it; without a transcript path the line that cites it is left out. */
84export function summaryMessage(template: CompactionTemplate, body: string, transcriptPath?: string): string {
85 const tail = transcriptPath
86 ? template.summaryTail.split(TRANSCRIPT_TOKEN).join(transcriptPath)
87 : template.summaryTail.split('\n').filter(line => !line.includes(TRANSCRIPT_TOKEN)).join('\n')
88 return template.summaryHead + body + tail
89}
90hooks/native-classify.ts 29 lines1// The installed host supplies the classifier wording. No prompt is guessed when capture fails.
2export const CLASSIFY_TEXT_MARK = 'RICE_CLASSIFY_OWNED_TEXT_42'
3export const CLASSIFY_LABELS = ['RICE_CLASSIFY_LABEL_A_42', 'RICE_CLASSIFY_LABEL_B_42'] as const
4export type ClassifyTemplate = { version: string; system: readonly [string, string]; prompt: readonly [string, string]; maxTokens: number }
5
6export function isClassifyTemplate(value: unknown): value is ClassifyTemplate {
7 if (!value || typeof value !== 'object') return false
8 const v = value as ClassifyTemplate
9 const pair = (a: unknown) => Array.isArray(a) && a.length === 2 && a.every(item => typeof item === 'string')
10 return typeof v.version === 'string' && pair(v.system) && pair(v.prompt) && Number.isSafeInteger(v.maxTokens) && v.maxTokens > 0 && v.maxTokens <= 64000
11}
12
13export function deriveClassifier(version: string, system: string, prompt: string, maxTokens: number): ClassifyTemplate {
14 const labelSlot = CLASSIFY_LABELS.map(label => JSON.stringify(label)).join(', ')
15 const systemParts = system.split(labelSlot)
16 const promptParts = prompt.split(CLASSIFY_TEXT_MARK)
17 const template = { version, system: systemParts, prompt: promptParts, maxTokens }
18 if (!isClassifyTemplate(template) || !promptParts[0]?.endsWith('> ')) throw new Error('The native classifier contract has an unsupported shape.')
19 return template
20}
21
22export function classifierRequest(template: ClassifyTemplate, text: string, labels: readonly string[]) {
23 return {
24 system: template.system[0] + labels.map(label => JSON.stringify(label)).join(', ') + template.system[1],
25 prompt: template.prompt[0] + text.replaceAll('\n', '\n> ') + template.prompt[1],
26 maxTokens: template.maxTokens,
27 }
28}
29hooks/native-tools.ts 162 lines1// Claude Code's own tool definitions and built-in agent prompts, learned from the installed claude and used here.
2//
3// A routed session builds no Anthropic request, so the engine never renders its tools or a subagent's prompt for
4// it. The helper runs the installed claude once per version and tool combination in an isolated folder against a
5// loopback stub (see helper/native-tools.ts): the main request carries the tools as the engine sends them, and the
6// stub answers it by starting every agent type the engine lists, in the foreground and in the background, plus an
7// agent file whose whole prompt is a known marker. This module turns those requests into what a routed step
8// sends. Nothing here is a copy of the engine's text.
9import { isObject, own } from './util'
10
11/** The capture's user line, an agent's task and the marker agent's prompt; never shown to a model in use. */
12export const MAIN_MARK = 'RICECAPTUREMAINTURN'
13export const SPAWN_MARK = 'RICECAPTURESPAWN'
14export const BODY_MARK = 'RICECAPTUREAGENTBODY'
15/** The agent file the capture adds: a custom agent whose whole prompt is BODY_MARK, so the text the engine puts around a prompt shows. */
16export const MARKER_AGENT = 'rice-capture-marker'
17
18/** One built-in tool as the engine sends it to the model. */
19export type NativeTool = { name: string; description: string; input_schema: Record<string, unknown> }
20/** The tools an agent is offered when it runs in the foreground and in the background. */
21export type ToolSets = { foreground: readonly string[]; background: readonly string[] }
22
23/** What one Claude Code version sends, for one combination of the session's built-in tools. */
24export type NativeCapture = {
25 version: string
26 /** The built-in tools, in the engine's order. */
27 tools: readonly NativeTool[]
28 /** The text the engine writes before and after every subagent's own prompt. */
29 agentHead: string
30 agentTail: string
31 /** Each built-in agent type's own prompt, by type. */
32 prompts: Readonly<Record<string, string>>
33 /** The tools the engine offers each built-in agent type. */
34 offered: Readonly<Record<string, ToolSets>>
35 /** The tools it offers an agent whose definition does not list them. */
36 custom: ToolSets
37}
38
39/** What the capture observed: the agent types the engine listed, its main request, and each started agent's first request. */
40export type ToolsCapture = {
41 version: string
42 listed: readonly string[]
43 main: unknown
44 spawned: readonly { type: string; background: boolean; body: unknown }[]
45}
46
47/** The agent file the capture writes into its isolated configuration. */
48export const markerAgentFile = (): string => `---\nname: ${MARKER_AGENT}\ndescription: Capture marker\n---\n${BODY_MARK}\n`
49
50/** The task the capture gives an agent: names its type and whether it runs in the background. */
51export const spawnTask = (type: string, background: boolean): string => `${SPAWN_MARK} ${background ? 'background' : 'foreground'} ${type}`
52
53/** The type and mode an agent's opening text names, when it is one the capture started. */
54export function spawnOf(text: string): { type: string; background: boolean } | undefined {
55 const found = new RegExp(`${SPAWN_MARK} (foreground|background) (\\S+)`).exec(text)
56 return found ? { type: found[2]!, background: found[1] === 'background' } : undefined
57}
58
59/** A short, stable name for a set of tool names, whatever their order. */
60export function toolSetKey(names: readonly string[]): string {
61 let hash = 0x811c9dc5
62 for (const char of [...new Set(names)].sort().join(',')) {
63 hash ^= char.charCodeAt(0)
64 hash = Math.imul(hash, 0x01000193) >>> 0
65 }
66 return hash.toString(16).padStart(8, '0')
67}
68
69const isStrings = (value: unknown): value is string[] => Array.isArray(value) && value.every(item => typeof item === 'string')
70const isSets = (value: unknown): value is ToolSets => isObject(value) && isStrings(value.foreground) && isStrings(value.background)
71const isTool = (value: unknown): value is NativeTool => isObject(value) && typeof value.name === 'string' && typeof value.description === 'string' && isObject(value.input_schema)
72
73export function isCapture(value: unknown): value is NativeCapture {
74 if (!isObject(value)) return false
75 return typeof value.version === 'string' && Array.isArray(value.tools) && value.tools.length > 0 && value.tools.every(isTool)
76 && typeof value.agentHead === 'string' && typeof value.agentTail === 'string'
77 && isObject(value.prompts) && Object.values(value.prompts).every(text => typeof text === 'string')
78 && isObject(value.offered) && Object.values(value.offered).every(isSets) && isSets(value.custom)
79}
80
81/** The texts of a request's system blocks, in order. */
82function systemOf(body: unknown): string[] {
83 const system = isObject(body) ? body.system : undefined
84 if (typeof system === 'string') return [system]
85 if (!Array.isArray(system) || !system.every(block => isObject(block) && typeof block.text === 'string')) throw new Error('a request has no system prompt the capture can read')
86 return system.map(block => (block as { text: string }).text)
87}
88
89/** A request's tools, as the engine sent them. */
90function toolsOf(body: unknown): NativeTool[] {
91 const tools = isObject(body) ? body.tools : undefined
92 if (!Array.isArray(tools)) return []
93 if (!tools.every(isTool)) throw new Error('a request carries a tool without a name, a description or an input schema')
94 return tools.map(tool => ({ name: tool.name, description: tool.description, input_schema: tool.input_schema }))
95}
96
97/**
98 * The definitions and prompts a capture implies; throws when it does not have the shape the engine is expected to
99 * produce. Every subagent's system prompt is the engine's preamble (its blocks before the agent's own) and then one
100 * block: the agent's own prompt between a head and a tail, which the marker agent shows. The preamble names the
101 * engine's model and product, as the main prompt's identity sections do, and is left out as they are.
102 */
103export function deriveCapture(capture: ToolsCapture): NativeCapture {
104 const tools = toolsOf(capture.main)
105 if (tools.length === 0) throw new Error('the installed claude sent no tools')
106 const find = (type: string, background: boolean) => capture.spawned.find(each => each.type === type && each.background === background)
107 const marker = find(MARKER_AGENT, false)
108 const markerBackground = find(MARKER_AGENT, true)
109 if (!marker || !markerBackground) throw new Error('the marker agent did not start in both the foreground and the background')
110 const blocks = systemOf(marker.body)
111 const at = blocks.length - 1
112 const mark = blocks[at]!.indexOf(BODY_MARK)
113 if (mark < 0) throw new Error('the marker agent\'s prompt is not the last block of its system prompt')
114 const head = blocks[at]!.slice(0, mark)
115 const tail = blocks[at]!.slice(mark + BODY_MARK.length)
116 const ownPrompt = (type: string, body: unknown) => {
117 const system = systemOf(body)
118 const text = system.at(-1)!
119 if (system.length !== blocks.length || !text.startsWith(head) || !text.endsWith(tail) || text.length < head.length + tail.length) throw new Error(`the ${type} agent's system prompt does not have the shape of the marker agent's`)
120 return text.slice(head.length, text.length - tail.length)
121 }
122 if (ownPrompt(MARKER_AGENT, markerBackground.body) !== BODY_MARK) throw new Error('the marker agent\'s prompt differs in the background')
123 const names = (body: unknown) => toolsOf(body).map(tool => tool.name)
124 // Keyed by names the engine lists, so without a prototype a name could reach.
125 const prompts: Record<string, string> = Object.create(null)
126 const offered: Record<string, ToolSets> = Object.create(null)
127 for (const type of capture.listed) {
128 if (type === MARKER_AGENT || Object.hasOwn(prompts, type)) continue
129 const foreground = find(type, false)
130 const background = find(type, true)
131 // A listed type the engine did not start has no prompt here; a routed step of it is refused.
132 if (!foreground || !background) continue
133 const prompt = ownPrompt(type, foreground.body)
134 if (ownPrompt(type, background.body) !== prompt) throw new Error(`the ${type} agent's prompt differs between the foreground and the background`)
135 prompts[type] = prompt
136 offered[type] = { foreground: names(foreground.body), background: names(background.body) }
137 }
138 return { version: capture.version, tools, agentHead: head, agentTail: tail, prompts, offered, custom: { foreground: names(marker.body), background: names(markerBackground.body) } }
139}
140
141/** A subagent's system prompt as the engine words it, around the agent's own prompt `body`. */
142export const agentPrompt = (capture: NativeCapture, body: string): string => capture.agentHead + body + capture.agentTail
143
144/** A built-in agent type's own prompt, if the capture holds it. */
145export const builtinPrompt = (capture: NativeCapture, type: string): string | undefined => own(capture.prompts, type)
146
147/** The captured tools by name. */
148export const toolTable = (capture: NativeCapture): ReadonlyMap<string, NativeTool> => new Map(capture.tools.map(tool => [tool.name, tool]))
149
150/**
151 * What the capture says about the tools an agent is offered: `known` are the tools it saw, `offered` the ones the
152 * engine gives the agent type (or, with no type, an agent defined by a file). A type the capture did not start
153 * answers undefined.
154 */
155export function offeredTools(capture: NativeCapture, type: string | undefined, background: boolean): { known: ReadonlySet<string>; offered: ReadonlySet<string> } | undefined {
156 const sets = type === undefined ? capture.custom : own(capture.offered, type)
157 if (!sets) return undefined
158 const known = new Set(capture.tools.map(tool => tool.name))
159 for (const each of [capture.custom, ...Object.values(capture.offered)]) for (const name of [...each.foreground, ...each.background]) known.add(name)
160 return { known, offered: new Set(background ? sets.background : sets.foreground) }
161}
162