SLOPSHOPPER

ClaudeRipple

Picks the reasoning effort for every prompt and the worker for every delegated task, can keep the prompt cache warm, and shows where ClaudeRipple sent each…

panebandspinnerguardcommandtoast
★ 74v0.7.0GPL-3.0-onlyupdated 2026-10-26PBJ-2/clauderipple/packages/mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · ripple
│ ┃ ClaudeRipple ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ All sessions │ ripple │ │ ┃ No model requests yet. ● ripple: ClaudeRipple│ ClaudeRipple: Haiku returned no verdict; │ │ ┃ ● this session ○ other sessions ● ripple: ClaudeRipple│ keeping the current effort or asking │ │ ┃ a: This session only ⏺ Read(src/auth.ts) │ Haiku. │ │ ⎿ Read 6 lines ╰────────────────────────────────────────────╯ │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /ripple │ ⎿ ripple: ClaudeRipple: settings, setup, auto, warm, save, stats, │ ● ripple: ClaudeRipple optional file: ENOENT: no such file /Users/dev │ ● ripple: ClaudeRipple panel settings: router HTTP 0 │ │ Welcome to ClaudeRipple ● ○ ○ A small, fast judge picks each prompt’s effort. Judge ● Haiku ○ Jev ○ Router model n: Next k: Skip setup ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
Welcome to ClaudeRipple ● ○ ○ A small, fast judge picks each prompt’s effort. Judge ● Haiku ○ Jev ○ Router model n: Next k: Skip setup
Pane · ClaudeRipple
All sessions No model requests yet. ● this session ○ other sessions a: This session only
Pane · ripple-agents
No agents or background tasks yet Tasks Claude delegates appear here, along with commands and monitoring tasks running in the background. Delegated tasks also show the worker Ripple picked and why.
Pane · ripple-context
Context breakdown The context breakdown is not available yet. x: Close
Pane · ripple-limits
Plan limits Plan usage is not available yet.
README

<img src="brand/mark.svg" width="120" height="120" alt="The ClaudeRipple mascot: a hollow ripple ring with a curling wave crest">

<h1 align="center">ClaudeRipple</h1>

<b>Chat stays Claude. Only Code becomes GPT.</b><br> Claude Desktop's own setting for other models switches the <b>whole app</b> — chat, phone Remote Control and connectors go with it.<br>ClaudeRipple turns nothing off: you stay signed in to your Claude subscription while GPT, DeepSeek, Kimi, Grok<br>or 400+ other models answer in the <b>Code tab</b>. Claude inside the <b>Codex app</b> and <b>Codex CLI</b> too.

<a href="https://apps.apple.com/us/app/id6823063731"><img height="40" alt="App Store" src="https://img.shields.io/badge/App%20Store-Download-0D96F6?style=for-the-badge&logo=apple&logoColor=white"></a> <img height="40" alt="Google Play" src="https://img.shields.io/badge/Google%20Play-Coming%20soon-666666?style=for-the-badge&logo=googleplay&logoColor=white"> <a href="https://discord.gg/R8ZgGSNHjw"><img height="40" alt="Discord" src="https://img.shields.io/badge/Discord-Join-5865F2?style=for-the-badge&logo=discord&logoColor=white"></a>

<a href="https://www.npmjs.com/package/clauderipple"><img alt="npm" src="https://img.shields.io/npm/v/clauderipple?label=npm"></a> <img alt="Alpha" src="https://img.shields.io/badge/status-alpha-orange"> <a href="LICENSE"><img alt="GPL-3.0" src="https://img.shields.io/badge/license-GPL--3.0-blue"></a> <img alt="macOS" src="https://img.shields.io/badge/macOS-arm64%20%7C%20x64-black"> <img alt="Windows" src="https://img.shields.io/badge/Windows-arm64%20%7C%20x64-0078D4"> <img alt="Linux" src="https://img.shields.io/badge/Linux-x64%20(systemd)-FCC624"> <img alt="Node" src="https://img.shields.io/badge/node-24%2B-success"> <a href="README.ko.md"><img alt="한국어" src="https://img.shields.io/badge/docs-한국어-red"></a>

<a href="https://github.com/PBJ-2/clauderipple/releases/download/v0.9.0/clauderipple-demo.mp4"><img src="docs/media/demo.webp" width="880" alt="A one-minute tour: other models in Claude Desktop's own model menu, effort set for every prompt, and each subagent sent to the model that fits. Click for the full video."></a><br> <sub>A one-minute tour: other models in Claude Desktop's own model menu, effort set for every prompt, and each subagent sent to the model that fits. Click for the full video.</sub>

<table align="center"> <tr> <td align="center" width="34%"><img src="docs/media/picker.png" width="300" alt="GPT, DeepSeek, GLM and Gemini in Claude Desktop's own model menu"><br><sub>GPT, DeepSeek, GLM and Gemini in Claude Desktop's own model menu</sub></td> <td align="center" width="66%"><img src="docs/media/answer.png" alt="GPT-6 Astra working in the Code tab, every request logged on the right"><br><sub>GPT-6 Astra working in the Code tab, every request logged on the right</sub></td> </tr> <tr> <td colspan="2" align="center"><img src="docs/media/subagents.png" alt="Subagents on DeepSeek and GLM, named in the background-task panel"><br><sub>Subagents on DeepSeek and GLM, named in the background-task panel</sub></td> </tr> <tr> <td colspan="2" align="center"><img src="docs/media/mod-band.png" alt="The ripple mod: effort, context, cache timer, and which model answered with its cache hit"><br><sub>The ripple mod: effort, context, cache timer, and which model answered with its cache hit</sub></td> </tr> <tr> <td align="center" width="50%"><img src="docs/media/mod-alerts.png" alt="Warnings when the cache goes cold or a limit is near, and a compaction offer"><br><sub>Warnings when the cache goes cold or a limit is near, and a compaction offer</sub></td> <td align="center" width="50%"><img src="docs/media/mod-settings.png" alt="Quick settings: automatic effort, the judge, worker modes"><br><sub>Quick settings: automatic effort, the judge, worker modes</sub></td> </tr> </table>


1P, not 3P: the difference this whole project exists for

Claude Desktop already ships an official way to use other models — the inference gateway setting, what the app calls third-party or 3P mode. Turning it on is not a per-session choice. It switches the whole app into a different deployment mode at launch, and that mode is a different product:

  • The window stops loading claude.ai and loads a local bundle instead. claude.ai /api/ and /v1/ calls answer custom_3p_not_available 503.
  • "Chat" is no longer claude.ai chat. It is a Claude Code local-agent session.
  • Remote Control and side sessions are switched off outright (shouldEnableSessionsBridge() returns false).
  • Anthropic's own claude.ai connectors, Claude Design, mobile continuity and chat search go with it.

There is no middle setting. "Chat on Claude, Code on the gateway" is impossible for anyone, because 1P mode routes nothing through the gateway at all. (All of this is read out of the app's own bundle; see docs/ARCHITECTURE.md §2.)

ClaudeRipple never touches that setting. The app stays signed in to your Claude subscription in 1P mode, and another model answers in the Code tab and its subagents — under its real name in the model picker, at the reasoning effort you chose. You do not trade your Claude account for a GPT one. You keep both, in one app.

Three things follow from staying in 1P, and no gateway-based tool can offer any of them:

  • Code from your phone, on GPT. Remote Control is off in 3P. It is on here, so you can pick a model and send a task from a phone and watch the commits land.
  • Connectors alive while another model works. 3P stubs claude.ai calls, which takes Anthropic's own connectors with them. Read a Google Drive doc and have GPT write the code.
  • Cloud and side sessions. Gone in 3P. Untouched here.

If you pay for Claude, 3P is not an option — it throws away the half of the subscription you are paying for. This is the only way to keep it and still choose the model.

FAQ

Can I use GPT in the Claude Desktop app?

Yes — in the Code tab and its subagents. Install ClaudeRipple, sign in with a ChatGPT Plus or Pro subscription, and GPT (GPT-6 Sol, Luna, Astra, GPT-5.6 Terra and the rest) shows up under its real name in the model picker, with the reasoning effort you pick. The app itself is not modified and not switched into any other mode. The general chat tab stays Claude: no tool can route it without turning the whole app into gateway mode (see 1P, not 3P).

How do I use GPT in Claude Code?

The same install covers the terminal claude CLI. ClaudeRipple is a local proxy that Claude Code is pointed at through two lines in ~/.claude/settings.json, so your skills, hooks, MCP servers, CLAUDE.md and subagents keep working while another model answers.

Do I have to turn on Claude Desktop's "third-party inference" (gateway) setting?

No — and you should not. That setting switches the whole app into 3P mode, which stops loading claude.ai, replaces chat with a local-agent session and turns Remote Control off. ClaudeRipple never touches it.

Will I lose claude.ai chat, Remote Control or my connectors?

No. The app stays signed in to your Claude subscription, so chat, phone Remote Control, cloud sessions and Anthropic's own connectors keep working. That is the whole point of staying in 1P.

Can I still use Claude itself?

Yes. Model mapping is per model name: leave a name mapped to Claude and it answers as Claude. Most people map one or two names to GPT and leave the rest alone.

Do I need an OpenAI API key?

No. Any ChatGPT plan that includes Codex works — Plus, Pro and Business, and Enterprise or Edu where the workspace admin has turned Codex on. You sign in from the app and no API key is involved. The plan's usage limits apply; once they are used up, Codex credits you have bought carry on. API keys are for the other providers (DeepSeek, Kimi, GLM, OpenRouter and anything else with an Anthropic- or OpenAI-compatible endpoint).

Which models can I use?

GPT through a ChatGPT subscription, and DeepSeek, Kimi, GLM, Grok, Qwen and 400+ more through OpenRouter or a direct API key. Claude models keep working as they are.

Does it work on Windows?

Yes, on Windows and macOS, arm64 and x64. Install, dashboard, restart and uninstall are measured on Windows 11 arm64; the x64 runtime is measured under emulation. Linux works too where there is a systemd user session: install, a Code-tab request through the router, a restart in the middle of a streaming answer and uninstall are measured on Ubuntu 24.04 x64 with Claude Desktop 2.2553.13, and so is picker mode: models from cli.extraModels show in the Code-tab picker next to Claude's own.

Is my code sent anywhere else?

No. The proxy runs on your own machine. Requests go to the provider you configured and nowhere else, and credentials stay in your home directory. See Privacy.

Will my Claude account get banned? Is this against Anthropic's terms?

What ClaudeRipple does with Claude is small and checkable: a request that stays on Claude leaves your machine byte for byte as Claude Code sent it, and a request routed to GPT or another provider never reaches Anthropic at all. It works through the proxy and certificate settings Claude Code documents for corporate networks (HTTPS_PROXY, NODE_EXTRA_CA_CERTS — Enterprise network configuration), not by patching the app. The reports of banned accounts are about the opposite direction — a Claude subscription login used from another program. ClaudeRipple has one optional feature of that kind: Claude inside Codex using your subscription login. That use is subject to Anthropic's terms; an Anthropic API key avoids the question. Rotating several Claude subscriptions is likewise your call under those terms. Only Anthropic can say how an account is treated, so nothing here is a promise.

What about Gemini through a Google account?

An AI Studio API key is the way Google supports, and the safe one. The Google account sign-in (Antigravity) is different: Google's Antigravity terms (section 6) and the Gemini CLI FAQ name using those credentials from another program as a breach. In February 2026 Google suspended accounts used this way — the suspension also cut off Gemini CLI and Code Assist — and said a second violation is permanent. ClaudeRipple offers the sign-in because others do and people asked, shows this warning before it starts, and does nothing to hide the traffic. Use a secondary account if you use it at all.

Can I use several ChatGPT accounts?

Yes. Each clauderipple login (or + Add ChatGPT account in the dashboard) adds one. When an account hits its usage limit, the same request moves to the next account and the spent one rests until its window resets; a conversation stays on the account that answered, to keep its prompt cache. This applies to the Claude Desktop Code tab, Claude Code, and GPT in the Codex app and CLI.

Can I use Claude inside Codex?

Yes. clauderipple codex on adds ClaudeRipple as a provider, and Claude models appear in the Codex app's and CLI's model list under their own names. They answer through your Claude Code login or an Anthropic API key. See Codex app and Codex CLI.

Can it generate images?

Yes, with a ChatGPT subscription and no API key: clauderipple image "a red paper boat" -o boat.png --aspect square. --ref FILE adds a reference image and --transparent a transparent background. One image takes about 30 seconds, and the subscription chooses the resolution and quality. Subagents ClaudeRipple generates are told the same call, so they can make images too. See Claude Code.

Does GPT do worse inside Claude Code?

Claude Code's system prompt and tool descriptions are written for Claude, so another model reads instructions tuned for someone else, and it may behave a little differently than in its own client. ClaudeRipple tells each model its own name and effort, reshapes tool schemas a vendor would reject, and lets you append instructions per provider. A common setup is Claude as the main model with GPT or DeepSeek as subagents.

How is this different from CC Switch, opencodex or claude-code-router?

See the comparison table. In short: ClaudeRipple reaches the Claude Desktop Code tab while the app stays signed in to Claude, and shows other models in its picker under their real names. CC Switch also reaches the desktop app, but by turning on its gateway (3P) mode.

Is it free?

Yes. ClaudeRipple is open source under GPL-3.0. You pay only for the subscriptions or API keys you already use.

One tool instead of four

Similar tools let the Claude Code CLI or Codex CLI use other models, but they either cannot reach the Claude desktop app or reach it only through its gateway (3P) mode, and the moment you switch models you lose the Claude-subscription side (claude.ai chat, Remote Control, cloud sessions). ClaudeRipple covers the desktop app, the terminal and Codex from one menu-bar app, runs both subscriptions side by side, and keeps the Claude Code harness intact: your skills, hooks, MCP servers, CLAUDE.md, subagents and claude.ai connectors keep working while another model does the thinking.

ClaudeRippleCC Switch (checked 2026-09-24)opencodex / openclaude (checked 2026-09-16)claude-code-routerClaude Desktop gateway (3P) mode
Claude Desktop Code tab without gateway (3P) mode✅❌ ²❌ ¹❌❌ by definition
Keeps claude.ai chat, Remote Control, cloud sessions, connectors✅❌❌❌❌
Claude and GPT subscriptions side by side✅❌ one provider at a time❌ all-or-nothing❌❌
Real model names in the Desktop picker✅❌ claude-* role names ²❌❌partial
Several ChatGPT accounts, switching when one runs out (Desktop and Codex)✅❌ switched by hand ³✅❌❌
Terminal claude CLI✅✅✅✅✅
Codex app and Codex CLI → Claude✅✅✅❌❌
Prompt cache on translated providers94–99 % measurednot measurednot measuredvariesn/a
Subagents named by real model in the task panel✅❌❌❌❌
Settings GUI, no terminal needed✅✅❌❌❌
Signed, notarized app with its own runtime✅✅❌❌–

¹ opencodex's README showed Claude Desktop in a demo but published no setup steps for it, in the repository or on its documentation site (checked 2026-09-16). At the time the only public way into the desktop app was the official gateway setting — the last column.

² CC Switch reaches Claude Desktop by writing the app's third-party profile (Claude-3p/claude_desktop_config.json, "inferenceProvider": "gateway"), which is the last column. Through its local gateway the picker shows only claude-sonnet-*, claude-opus-* and claude-haiku-* role names (its manual). CC Switch manages more tools than this table covers (Gemini CLI, OpenCode and others) and syncs MCP servers and skills across them.

³ Each ChatGPT account is bound to its own provider card, and official ChatGPT cards are kept out of the failover queue (v3.20.0 release notes).

The desktop app's own "third-party inference" setting flips the whole app into another mode: you lose claude.ai chat, Remote Control and cloud sessions. Tools that replace ANTHROPIC_BASE_URL never reach the desktop app, and the ones that do reach it write that same setting. ClaudeRipple instead is a tiny HTTPS proxy that only the Claude Code process trusts: requests for the models you map go to your provider, everything else goes to Anthropic byte for byte.

What you get

  • Any model in Claude Desktop and Claude Code. GPT-6 Sol / Luna / Astra and GPT-5.6 Terra / Sol / Luna through your ChatGPT Plus/Pro subscription (new models appear the day OpenAI serves them), Google Gemini, or DeepSeek, Kimi, GLM, MiniMax, Qwen, Grok, Mistral, Groq, Together, Fireworks, OpenRouter (400+ models) and local Ollama / LM Studio. Under their real names in the picker, or mapped onto a Claude name.
  • Claude in the Codex app and Codex CLI. A local OpenAI-compatible endpoint that Codex treats as a provider; Claude models appear in Codex's own model list. Uses your current Claude Code login or an Anthropic API key.
  • Multiple Claude accounts without breaking the prompt cache. Opt a native Claude provider into account rotation, add subscriptions from the dashboard, and each conversation stays on the account that answered. Before the response starts, a quota or authentication refusal moves that turn to the next account. This native Claude Desktop/Code path is separate from the translated Codex ingress, which picks one available login and does not rotate accounts.
  • Several ChatGPT accounts. Each clauderipple login (or + Add ChatGPT account in the dashboard) adds one. When an account hits its limit, the next one takes over the same request and the spent one rests until its window resets; a conversation stays on the account that answered, to keep its cache. This covers the Claude Desktop Code tab and subagents and GPT in the Codex app and CLI — Codex keeps its own sign-in and moves to the next account without signing out.
  • The full Claude Code harness, untouched. Skills, hooks, MCP, CLAUDE.md, subagents, plan mode, Remote Control on your phone: nothing is turned off.
  • Correct by construction. Prompt caching preserved (Anthropic cache breakpoints and stable OpenAI prefixes), Claude Code's server-side threads handled, tool calls and images round-tripped, reasoning effort clamped to what each model accepts, Anthropic-only request fields stripped for compatible vendors.
  • A real request log. Who asked, which model answered, tokens in / cached / out, latency, status, per request, with a one-hour summary.
  • Subagent name tags. The background-task panel shows Terra·high · Review instead of a generic "Agent".
  • The ripple mod, above the prompt. A band shows the reasoning effort, context, cache timer, and which model answered your last request with its cache hit. A small judge model (Haiku 5.5 or Jev) reads each prompt with the recent turns and sets the effort, low through max. Delegated work goes to ripple:auto, and the judge sends each task to a worker by difficulty: light work to DeepSeek or GLM, hard work to GPT or Opus. Cards warn when the cache has gone cold, the context gets heavy or a plan window passes 80%, and offer a compaction in place. Log (or /ripple-log) opens the request log in a side pane. One switch on the Clients screen, or clauderipple mod on.
  • Images from your ChatGPT subscription. clauderipple image "<prompt>", with reference images and transparent backgrounds. Subagents are told how, so a GPT or DeepSeek worker can make an image and look at it without an image tool.
  • Close the laptop, Claude keeps working. On macOS and Windows the laptop stays awake with the lid shut while Claude works (and 10 minutes after), so a task you started from your phone finishes. If the Wi-Fi loses its internet, it moves to your phone's hotspot (iPhone or Android) and back to a known Wi-Fi later. Off until you turn it on in the dashboard's Laptop view; see Lid closed and the phone hotspot.
  • Lean workers, if you want them. One switch gives generated subagents only the tools a worker uses instead of every MCP server and plugin of the session: one worker's first request fell from 33k to 9k tokens.
  • Made for people who don't want a terminal. Provider presets with one-click connection tests and model discovery, drop-down model mapping, auto-save, a UI in English, Korean, Chinese, Japanese, Spanish and Portuguese. A menu-bar app that carries its own runtime and sets itself up on first launch. Signed and notarized.

<img src="docs/media/mapping.png" width="880" alt="Model mapping: which model answers for each Claude name, with per-model reasoning effort">

Ripple Remote: every model, from your phone, for hours

Start a job in the Claude desktop app, close the laptop, and keep going from the couch. Ripple Remote is the phone app for ClaudeRipple: the same sessions, whichever model runs them, on your phone, and it does not drop you after 30 minutes.

<img src="docs/media/remote/store/en-1.png" width="260" alt="A remote that doesn't time out: a GPT session followed for 1h 47m"> <img src="docs/media/remote/store/en-2.png" width="260" alt="GPT, DeepSeek and Gemini in one model picker on the phone"> <img src="docs/media/remote/store/en-3.png" width="260" alt="Approve a DeepSeek session's request from the phone">

  • Hours, not minutes. The connection holds as long as your computer is on. Watch a two-hour refactor through to the end and approve it when it asks.
  • Any model you route. GPT, DeepSeek, Gemini or Claude: every session looks and works the same. Switch the next turn's model and reasoning effort from your phone.
  • Your Claude app sessions, as they are. Sessions you started in the Code tab on your Mac continue on the phone — the live timeline, tool calls, diffs, subagents and their models, plan approvals and question cards, photos and files.
  • Your Mac's status bar in your pocket. The model that answered, the cache and your usage limits, as the ClaudeRipple band shows them on the Mac.
  • Pairs with the laptop features. With lid-closed awake and the phone hotspot, the laptop keeps working in a bag and stays online when the Wi-Fi does not.
  • Private by design. Messages, attachments and notifications are end-to-end encrypted; the relay and the push service cannot read them. No account, no ads, no tracking, free.

Install ClaudeRipple on your computer, open the dashboard's Phone view and scan the QR code once. iPhone: App Store. Android: in a closed test on Google Play — ask on Discord. Claude app sessions are supported on macOS; the app has a demo you can try without a computer.

Install

macOS

curl -fsSL https://raw.githubusercontent.com/PBJ-2/clauderipple/main/scripts/install.sh | sh

Windows (PowerShell)

irm https://raw.githubusercontent.com/PBJ-2/clauderipple/main/scripts/install.ps1 | iex

Linux (a desktop session with systemd)

curl -fsSL https://raw.githubusercontent.com/PBJ-2/clauderipple/main/scripts/install.sh | sh

The router runs as a per-user systemd service: systemctl --user status clauderipple, and journalctl --user -u clauderipple for what it printed. Picker mode trusts the local CA in the NSS database Chromium reads (~/.pki/nssdb, your user only, no sudo), which takes certutil: run `sudo apt in

Source 34 files
hooks/register.tsx 2380 lines
1// Engine wiring lives here: imported logic and drawings never receive the engine interface.
2// Timers own background work; hooks only admit/rewrite a request and record its result.
3import { atom, read, update } from 'claude-code'
4import type { AgentSpawnInput, EngineInterface, ModelCompleteResult, ModelForkResult, Register, RenderElement, RenderInput, RenderNode, SessionCompactResult, SessionContextBreakdown, SessionContextUsage, SessionRateLimit, ToolCallInput, ToolCallResult, TurnStepInput, TurnUsage } from 'claude-code'
5import type { AgentRec, Effort, JudgeInput, JudgeKind, JudgeRun, LimitItem, ModSettingsSnapshot, Pick, Settings, StatusRequest, TierTarget, Verdict, WorkerCandidate, WorkerPick, WorkerVerdict } from '../types'
6import { MOD_SETTINGS_SCHEMA_VERSION, RUNG_EFFORT, applySettingsChanges, normalizeSettings, settingsChanges } from './settings'
7import { rungOf } from './ladder'
8import { debugText, langFrom, t } from './i18n'
9import type { Lang } from './i18n'
10import { EFFORT_JUDGE_SYSTEM, finalEffort, isCacheSafeModel, jevEffortRequest, jevFailure, jevUsage, judgeContext, parseEffortVerdict, parseJevEffort, parseJevKey, shouldJudge } from './judge'
11import { AUTO_DESCRIPTION, NATIVE_AGENTS, TIER_MARKERS, agentProvider, candidateUsable, chatgptUsable, claudeCandidates, ladderOptionsFrom, ladderPick, liveProviders, markerDomain, modelReason, readMarker, routerModelOptions, ruleReason, spawnModel, spawnTitle, titleName, takesOver, tierOf, userSaid, withoutReason, withoutRouting, workerRule, zenJev } from './workers'
12import { MARKER, agentModel, delegationPin as parseDelegationPin, fixSpawn, humanText, pinInstruction, pinSaid } from './worker'
13import { activeModeOf, chatgptProviders, claudeWindow, eagerNote, gptLimitsFrom, modeKey, modeOver, quotaWindows, resetProvider, routingSettings } from './modes'
14import type { QuotaWindow } from './modes'
15import type { Spawn, WorkerFix } from './worker'
16import { afterPing, nextMemo, restoreFromResume, shouldPing } from './cache'
17import { HEAVY_PERCENT, bandPriority, claudeLimitsFrom, claudeScopedFrom, coldAlert, contextWindow, hotAlert, hottest, hotWindowMoved, keptAlert, routerLimitItems, saveUntil as limitSaveUntil, swampAlert, swamped } from './session'
18import type { ScopedLimit } from './session'
19import { COMPACT_SYSTEM, compactResult, serializeTranscript } from './compact'
20import { QUICK_PROMPT, wrapForNewChat } from './handoff'
21import { addTask, endTasks, endWithAgent, settleTasks, stopTask, taskEnds, taskStarted } from './tasks'
22import { addAgentStep, addJudge, addPrompt, addRequest, addWarm, addWorker, emptyStats, formatStats, sentEffort } from './stats'
23import { besideBand, renderBand, renderFooter } from './ui/band'
24import { renderAlert } from './ui/alerts'
25import { PHONE_QUEUE_ROWS, renderPhoneQueue } from './ui/queue'
26import { renderSettings } from './ui/settings'
27import { renderSetup } from './ui/setup'
28import { renderAgents, renderAgentsFallback, talkOf } from './ui/agents'
29import { renderContext, renderContextFallback } from './ui/context'
30import type { ContextActions } from './ui/context'
31import { renderLimits, renderLimitsFallback } from './ui/limits'
32import { toolDetail } from './ui/tools'
33import { renderLog } from './ui/log'
34import { displayText } from './ui/display'
35import { EFFORTS, isRich, modelName, nextMinuteChange, routeOf, targetLabel } from './ui/view'
36import type { AgentTalk, AgentsActions, AlertActions, AlertView, BandActions, DashboardView, Frame, SettingsActions, SettingsView, SetupActions } from './ui/view'
37
38const line = atom({ plugin: 'ripple', key: 'line' } as const, null)
39const phoneQueue = atom({ plugin: 'ripple', key: 'phoneQueue' } as const, null)
40const last = atom({ plugin: 'ripple', key: 'last' } as const, null)
41const requests = atom({ plugin: 'ripple', key: 'requests' } as const, [])
42const logOpen = atom({ plugin: 'ripple', key: 'logOpen' } as const, false)
43const onlySession = atom({ plugin: 'ripple', key: 'onlySession' } as const, false)
44const bandHidden = atom({ plugin: 'ripple', key: 'bandHidden' } as const, false)
45const settings = atom({ plugin: 'ripple', key: 'settings' } as const, null)
46const settingsSync = atom({ plugin: 'ripple', key: 'settingsSync' } as const, { schemaVersion: MOD_SETTINGS_SCHEMA_VERSION, revision: null, pending: [], migrationChecked: false, migration: null })
47const settingsBase = atom({ plugin: 'ripple', key: 'settingsBase' } as const, null)
48const lang = atom({ plugin: 'ripple', key: 'lang' } as const, 'en')
49const pick = atom({ plugin: 'ripple', key: 'pick' } as const, null)
50const deciding = atom({ plugin: 'ripple', key: 'deciding' } as const, false)
51const decidingSince = atom({ plugin: 'ripple', key: 'decidingSince' } as const, null)
52const paused = atom({ plugin: 'ripple', key: 'paused' } as const, false)
53const heldPick = atom({ plugin: 'ripple', key: 'heldPick' } as const, null)
54const appEffort = atom({ plugin: 'ripple', key: 'appEffort' } as const, null)
55const modelIs = atom({ plugin: 'ripple', key: 'modelIs' } as const, null)
56const lastRequest = atom({ plugin: 'ripple', key: 'lastRequest' } as const, null)
57const lastSpawn = atom({ plugin: 'ripple', key: 'lastSpawn' } as const, null)
58const agents = atom({ plugin: 'ripple', key: 'agents' } as const, [])
59/** Commands and watches left running in the background, listed in the Agents pane (tasks.ts). */
60const bgTasks = atom({ plugin: 'ripple', key: 'bgTasks' } as const, [])
61/** What the band shows of the agents (countAgents): it reads this, never the list above. */
62const agentCounts = atom({ plugin: 'ripple', key: 'agentCounts' } as const, { live: 0, total: 0 })
63const cache = atom({ plugin: 'ripple', key: 'cache' } as const, null)
64const warm = atom({ plugin: 'ripple', key: 'warm' } as const, { pings: 0, cost: 0 })
65const warmHere = atom({ plugin: 'ripple', key: 'warmHere' } as const, null)
66const lastRealReplyAt = atom({ plugin: 'ripple', key: 'lastRealReplyAt' } as const, null)
67const context = atom({ plugin: 'ripple', key: 'context' } as const, null)
68/** Claude Code's own compaction point (settings.json `autoCompactWindow`), tokens or null. */
69const compactAt = atom({ plugin: 'ripple', key: 'compactAt' } as const, null as number | null)
70const hot = atom({ plugin: 'ripple', key: 'hot' } as const, null)
71const limit = atom({ plugin: 'ripple', key: 'limit' } as const, null)
72const limits = atom({ plugin: 'ripple', key: 'limits' } as const, null)
73const hotHidden = atom({ plugin: 'ripple', key: 'hotHidden' } as const, null)
74const hotHiddenFor = atom({ plugin: 'ripple', key: 'hotHiddenFor' } as const, null)
75const saveUntil = atom({ plugin: 'ripple', key: 'saveUntil' } as const, null)
76const swampHidden = atom({ plugin: 'ripple', key: 'swampHidden' } as const, null)
77const coldHidden = atom({ plugin: 'ripple', key: 'coldHidden' } as const, false)
78const kept = atom({ plugin: 'ripple', key: 'kept' } as const, null)
79const judgeDown = atom({ plugin: 'ripple', key: 'judgeDown' } as const, null)
80const judgeDownHidden = atom({ plugin: 'ripple', key: 'judgeDownHidden' } as const, null)
81const judgeSeen = atom({ plugin: 'ripple', key: 'judgeSeen' } as const, [])
82const judgeRuns = atom({ plugin: 'ripple', key: 'judgeRuns' } as const, [])
83// The standing judge failure was a dropped connection or a timeout: the card blames the network, not the judge.
84const judgeDownNetwork = atom({ plugin: 'ripple', key: 'judgeDownNetwork' } as const, false)
85const handoff = atom({ plugin: 'ripple', key: 'handoff' } as const, null)
86const handoffQueued = atom({ plugin: 'ripple', key: 'handoffQueued' } as const, false)
87const resultCard = atom({ plugin: 'ripple', key: 'result' } as const, null)
88const panel = atom({ plugin: 'ripple', key: 'panel' } as const, null)
89const busy = atom({ plugin: 'ripple', key: 'busy' } as const, false)
90const stats = atom({ plugin: 'ripple', key: 'stats' } as const, emptyStats())
91const settingsDraft = atom({ plugin: 'ripple', key: 'settingsDraft' } as const, null)
92const setupStep = atom({ plugin: 'ripple', key: 'setupStep' } as const, 1)
93const compactNote = atom({ plugin: 'ripple', key: 'compactNote' } as const, '')
94/** The compact card's tidy-up switch: on unless the person turned it off, and their last choice is kept. */
95const compactTidy = atom({ plugin: 'ripple', key: 'compactTidy' } as const, true)
96const effortMenuOpen = atom({ plugin: 'ripple', key: 'effortMenuOpen' } as const, false)
97const agentsOpen = atom({ plugin: 'ripple', key: 'agentsOpen' } as const, false)
98/** Compactions of the main conversation that finished, for the Compact icon's count; /clear zeroes it. */
99const compactions = atom({ plugin: 'ripple', key: 'compactions' } as const, 0)
100const agentsShowDone = atom({ plugin: 'ripple', key: 'agentsShowDone' } as const, false)
101const agentOpen = atom({ plugin: 'ripple', key: 'agentOpen' } as const, null)
102const agentRunsOpen = atom({ plugin: 'ripple', key: 'agentRunsOpen' } as const, [])
103const agentsTick = atom({ plugin: 'ripple', key: 'agentsTick' } as const, 0)
104const contextFull = atom({ plugin: 'ripple', key: 'contextFull' } as const, null)
105const contextShowAll = atom({ plugin: 'ripple', key: 'contextShowAll' } as const, [])
106/**
107 * The person's last few prompts as submitted. One typed while a turn runs is absorbed into that turn
108 * and never becomes a user message in `$.session.messages()`, so "솔한테 돌려" said mid-turn was not
109 * heard and the worker went by tier (2026-10-23). A model reason's quote is looked for in these too.
110 */
111const heardPrompts = atom({ plugin: 'ripple', key: 'heardPrompts' } as const, [] as string[])
112const delegationPin = atom({ plugin: 'ripple', key: 'delegationPin' } as const, null)
113const jev = atom({ plugin: 'ripple', key: 'jev' } as const, { source: null, test: { state: 'idle' } })
114const routerModels = atom({ plugin: 'ripple', key: 'routerModels' } as const, [])
115const ladderOptions = atom({ plugin: 'ripple', key: 'ladderOptions' } as const, null)
116const modeNoted = atom({ plugin: 'ripple', key: 'modeNoted' } as const, null)
117const demo = atom({ plugin: 'ripple', key: 'demo' } as const, null)
118
119/**
120 * Whether a state write would change anything. A write redraws each reader, and a redraw that
121 * hands the host new pictures reads as a blink (2026-10-10: the band flashed on polls and steps),
122 * so the writes on every step and poll are skipped when they would store what is there. The
123 * engine's scan wants each atom named at its read and update, hence a test rather than a wrapper.
124 */
125function same(a: unknown, b: unknown): boolean {
126  return JSON.stringify(a) === JSON.stringify(b)
127}
128
129const LOG_PANE = 'ripple-log'
130const AGENTS_PANE = 'ripple-agents'
131const CONTEXT_PANE = 'ripple-context'
132const LIMITS_PANE = 'ripple-limits'
133const HAIKU = 'claude-haiku-5-5'
134const EXECUTOR = 'Do the assigned task yourself. Inspect the relevant files, implement what was asked, and verify the result. Report the outcome concisely, citing evidence and marking uncertainty. Never delegate to another agent. Do not create unrequested files or commit unless explicitly asked.'
135let timersStarted = false
136let polling = false
137let ticking = false
138let forking = false
139let forkUsage: TurnUsage | null = null
140let countdownTimer: { at: number; cancel: () => void } | null = null
141let judgeSequence = 0
142/** Jev's network blips and timeouts in a row. */
143let jevBlips = 0
144let generation = 0
145/** The press whose handoff fork is running: a result carries it so a /clear cannot be handed another chat's note. */
146let handoffRun = 0
147/**
148 * A finished agent's conversation, read once. The Agents pane is redrawn every second while any
149 * agent or task runs, and re-reading a conversation that cannot grow was a full transcript read
150 * per tick per open pane (B19). A resumed agent runs again first, which changes the key.
151 */
152let agentTalkCache: { id: string; key: string; talk: AgentTalk } | null = null
153/** Preserve delivery order when transcript reads overlap; reset guards below reject stale work. */
154let receiveWork: Promise<void> = Promise.resolve()
155let carriedPick = false
156/**
157 * An agent's end that came before its spawn was recorded, kept until the record lands. A worker
158 * whose first request fails ends in milliseconds, while the spawn hook still reads its files; a
159 * workflow's 29 such agents stayed "running" in the pane for good (2026-10-24).
160 */
161const endedEarly = new Map<string, { state: 'done' | 'failed'; endedAt: number; outcome: Record<string, unknown> }>()
162// Serialize settings reads and writes so a slow poll cannot overwrite a queued edit.
163let settingsWork: Promise<void> = Promise.resolve()
164function settingsTask<T>(work: () => Promise<T>): Promise<T> {
165  const result = settingsWork.then(work)
166  settingsWork = result.then(() => undefined, () => undefined)
167  return result
168}
169
170function object(value: unknown): Record<string, unknown> {
171  return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}
172}
173function strings(value: unknown): string[] {
174  return Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []
175}
176function effortOf(value: unknown): Effort | undefined {
177  return typeof value === 'string' && EFFORTS.includes(value as Effort) ? value as Effort : undefined
178}
179function reason(error: unknown): string {
180  return error instanceof Error ? error.message : String(error)
181}
182async function report($: EngineInterface, where: string, error: unknown, language: Lang = 'en'): Promise<void> {
183  // Diagnostics cannot depend on the state read that may have just failed.
184  await $.ui.log(displayText(t(language, 'commands.debugLog', { where, reason: reason(error) }), 1800), { to: 'debug' })
185}
186async function userHome($: EngineInterface): Promise<string> {
187  return (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? '~'
188}
189async function rippleHome($: EngineInterface): Promise<string> {
190  return (await $.env.get('CLAUDERIPPLE_HOME')) ?? `${await userHome($)}/.clauderipple`
191}
192// The fs API has no append: serialize read/write pairs so concurrent picks in this mod survive.
193let workerLogWork: Promise<void> = Promise.resolve()
194/**
195 * Lines the pick log keeps. Each delegation writes a pick and an outcome, so 300 lines held only a
196 * few days; weighing whether a tier was enough needs weeks (2026-10-15).
197 */
198const PICK_LOG_LINES = 3000
199async function persistWorkerPick($: EngineInterface, entry: Record<string, unknown>): Promise<void> {
200  const work = workerLogWork.then(async () => {
201    try {
202      const path = `${await rippleHome($)}/logs/worker-picks.jsonl`
203      const old = await $.fs.exists(path) ? await $.fs.read(path) : ''
204      const lines = old.split('\n').filter(line => line.trim()).slice(-(PICK_LOG_LINES - 1))
205      await $.fs.write(path, [...lines, JSON.stringify(entry)].join('\n') + '\n')
206    } catch (error) { await report($, 'worker pick log', error) }
207  })
208  // A reporting failure must not poison the queue or undo the selected spawn either.
209  workerLogWork = work.catch(() => undefined)
210  await workerLogWork
211}
212/**
213 * What the phone queued for this chat. The host keeps the queue (packages/remote/src/queue.ts) and
214 * sends it when the turn ends; the Claude app never sees it, so the band says it is there. Keyed by
215 * the phone's session id, which for a Claude app session is this one, or by `desktopId`.
216 */
217export function phoneQueueOf(text: string | undefined, session: string): { count: number; first: string } | null {
218  if (!text) return null
219  for (const [key, value] of Object.entries(object(JSON.parse(text)))) {
220    const entry = object(value)
221    if (key !== session && entry.desktopId !== session) continue
222    const items = Array.isArray(entry.items) ? entry.items.map(object) : []
223    return items.length ? { count: items.length, first: typeof items[0]!.text === 'string' ? items[0]!.text : '' } : null
224  }
225  return null
226}
227async function refreshPhoneQueue($: EngineInterface, session: string): Promise<void> {
228  const path = `${await rippleHome($)}/remote/queue.json`
229  const next = await $.fs.exists(path) ? phoneQueueOf(await optionalFile($, path), session) : null
230  if (JSON.stringify(next) !== JSON.stringify(await read($, phoneQueue))) await update($, phoneQueue, () => next)
231}
232async function claudeHome($: EngineInterface): Promise<string> {
233  return (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${await userHome($)}/.claude`
234}
235async function optionalFile($: EngineInterface, path: string): Promise<string | undefined> {
236  try { return await $.fs.read(path) }
237  catch (error) { await report($, 'optional file', error); return undefined }
238}
239async function adminUrl($: EngineInterface): Promise<string> {
240  const text = await optionalFile($, `${await rippleHome($)}/config.json`)
241  if (!text) return 'http://127.0.0.1:8792'
242  const config = object(JSON.parse(text))
243  const admin = object(config.admin).port
244  const listen = object(config.listen).port
245  const port = typeof admin === 'number' ? admin : (typeof listen === 'number' ? listen : 8791) + 1
246  return `http://127.0.0.1:${port}`
247}
248/** Opens a URL with the system's opener (a browser page, or a claude:// link the desktop app takes); throws when it cannot. */
249async function openUrl($: EngineInterface, url: string): Promise<void> {
250  let argv: string[]
251  // cmd reads & as a command separator: escaped, a link's query reaches start whole.
252  if (await $.env.get('OS') === 'Windows_NT') argv = ['cmd', '/c', 'start', '', url.replace(/&/g, '^&')]
253  else {
254    const platform = await $.process.run(['uname', '-s'], { timeoutMs: 2000 })
255    if (platform.exitCode !== 0) throw new Error(platform.stderr || 'uname failed')
256    argv = [platform.stdout.trim() === 'Darwin' ? 'open' : 'xdg-open', url]
257  }
258  const result = await $.process.run(argv, { timeoutMs: 2000 })
259  if (result.exitCode !== 0) throw new Error(result.stderr || `opener exited ${result.exitCode}`)
260}
261async function openAllSettings($: EngineInterface): Promise<void> {
262  const url = `${await adminUrl($)}/#mod`
263  try {
264    await openUrl($, url)
265  } catch (error) {
266    await report($, 'open mod settings', error)
267    await $.ui.toast(url)
268  }
269}
270async function currentSettings($: EngineInterface): Promise<Settings> {
271  return normalizeSettings(await read($, settings))
272}
273async function resolveLanguage($: EngineInterface, s: Settings): Promise<Lang> {
274  if (s.language !== 'auto') return s.language
275  try {
276    const value = (await $.settings.read()).language
277    const host = langFrom(typeof value === 'string' ? value : undefined)
278    if (host) return host
279  } catch (error) { await report($, 'language settings', error) }
280  // On a Mac the system language comes before LANG: a session the desktop app starts can carry
281  // LANG=en_US on a Korean Mac (seen 2026-10-10: Korean headless, English in the Code tab).
282  // The engine exposes no platform noun. Avoid running macOS defaults elsewhere.
283  if (await $.env.get('OS') !== 'Windows_NT') {
284    try {
285      const platform = await $.process.run(['uname', '-s'], { timeoutMs: 2000 })
286      if (platform.exitCode === 0 && platform.stdout.trim() === 'Darwin') {
287        const apple = await $.process.run(['defaults', 'read', '-g', 'AppleLocale'], { timeoutMs: 2000 })
288        const mac = apple.exitCode === 0 ? langFrom(apple.stdout) : undefined
289        if (mac) return mac
290        if (apple.exitCode !== 0) await report($, 'language locale', apple.stderr)
291      }
292    } catch (error) { await report($, 'language locale', error) }
293  }
294  return langFrom(await $.env.get('LANG')) ?? langFrom(await $.env.get('LC_ALL')) ?? 'en'
295}
296async function registerAuto($: EngineInterface, s: Settings): Promise<void> {
297  if (s.agentAuto === 'off') return
298  await $.agent.register({ name: 'auto', description: AUTO_DESCRIPTION, prompt: EXECUTOR, disallowedTools: ['Agent'] })
299}
300async function installSettings($: EngineInterface, s: Settings): Promise<void> {
301  const previous = await currentSettings($)
302  await update($, settings, () => s)
303  const resolved = await resolveLanguage($, s)
304  await update($, lang, () => resolved)
305  // A router poll can land before the session binds, when register rejects; session.start
306  // registers again, so a rejection here must not cut the rest of the install short.
307  try { await registerAuto($, s) } catch (error) { await report($, 'agent register', error) }
308  if (!s.effortAuto) await update($, heldPick, () => null)
309  if (s.keepWarm && !previous.keepWarm) await update($, warm, value => ({ ...value, stopped: undefined }))
310  // Settings caught up with this chat's own choice: it follows Settings again.
311  if (await read($, warmHere) === s.keepWarm) await update($, warmHere, () => null)
312  // Setup was finished (here, in another chat, or the settings came back from the router): a setup
313  // card still open is stale, and the judge's key is looked up for the source now chosen. Both
314  // survive a reload, so after a router outage they asked for setup and a Jev key again although
315  // the router held both (2026-10-20).
316  if (s.setupDone && await read($, panel) === 'setup') {
317    await update($, panel, () => null)
318    await update($, settingsDraft, () => null)
319    await update($, settingsBase, () => null)
320  }
321  if (s.judge !== previous.judge || s.jevSource !== previous.jevSource || (s.judge === 'jev' && (await read($, jev)).source === null)) await jevKey($)
322}
323function settingsSnapshot(text: string): ModSettingsSnapshot {
324  const value = object(JSON.parse(text))
325  if (!Number.isSafeInteger(value.revision) || Number(value.revision) < 0 || typeof value.stored !== 'boolean' || !value.settings || typeof value.settings !== 'object' || Array.isArray(value.settings)) throw new Error('invalid router settings snapshot')
326  const at = value.compactAt
327  return { settings: normalizeSettings(value.settings), revision: Number(value.revision), stored: value.stored, compactAt: typeof at === 'number' && Number.isFinite(at) && at > 0 ? at : null }
328}
329async function routerSettingsDown($: EngineInterface, error: unknown): Promise<void> {
330  const notice = t(await read($, lang), 'band.routerDown')
331  if (await read($, line) !== notice) await update($, line, () => notice)
332  await report($, 'router settings', error)
333}
334async function acceptSettings($: EngineInterface, snapshot: ModSettingsSnapshot, sent = 0): Promise<void> {
335  const sync = await update($, settingsSync, value => ({ ...value, revision: snapshot.revision, pending: value.pending.slice(sent), migration: snapshot.stored ? null : value.migration }))
336  const base = snapshot.stored ? snapshot.settings : sync.migration ?? snapshot.settings
337  await installSettings($, applySettingsChanges(base, sync.pending))
338  await rebaseDraft($)
339}
340async function putSettings($: EngineInterface, admin: string, base: Settings): Promise<void> {
341  for (let attempt = 0; attempt < 2; attempt++) {
342    const sync = await read($, settingsSync)
343    // A migration that lost a CAS race is not a user edit: never retry it as a full save.
344    if (!sync.pending.length && !sync.migration) return
345    const count = sync.pending.length
346    const response = await $.http.fetch(`${admin}/api/mod-settings`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ schemaVersion: MOD_SETTINGS_SCHEMA_VERSION, settings: applySettingsChanges(base, sync.pending), revision: sync.revision }) })
347    if (!response.ok && response.status !== 409) throw new Error(t(await read($, lang), 'commands.routerHttp', { status: response.status }))
348    const snapshot = settingsSnapshot(response.text)
349    await acceptSettings($, snapshot, response.ok ? count : 0)
350    if (response.ok) return
351    base = snapshot.settings
352    if (attempt === 1) throw new Error(t(await read($, lang), 'commands.routerHttp', { status: 409 }))
353  }
354}
355async function syncSettings($: EngineInterface, admin: string): Promise<void> {
356  const response = await $.http.fetch(`${admin}/api/mod-settings`)
357  if (!response.ok) throw new Error(t(await read($, lang), 'commands.routerHttp', { status: response.status }))
358  const snapshot = settingsSnapshot(response.text)
359  // Claude Code writes `/autocompact` to settings.json itself, so this can change without a
360  // settings revision: the band reads it on every poll.
361  const at = snapshot.compactAt ?? null
362  if (at !== await read($, compactAt)) {
363    await update($, compactAt, () => at)
364    // The share is counted against this window: a count of the old one is another context's.
365    contextRun += 1
366    fullMark = null
367    await update($, contextFull, () => null)
368  }
369  let sync = await read($, settingsSync)
370  // Session atoms survive reloads. Old pending paths/drafts cannot prove user intent
371  // under this format; discard them rather than granting an old overwrite a new version.
372  if (sync.schemaVersion !== MOD_SETTINGS_SCHEMA_VERSION) {
373    sync = await update($, settingsSync, () => ({ schemaVersion: MOD_SETTINGS_SCHEMA_VERSION, revision: null, pending: [], migrationChecked: false, migration: null }))
374    await update($, settingsBase, () => null)
375  }
376  if (snapshot.stored && sync.migration) sync = await update($, settingsSync, value => ({ ...value, migration: null }))
377  // A router with no settings stored (a fresh or emptied home, or a stray test router that took the
378  // live one's launchd label, 2026-10-20) is not a reset: settings this chat holds from a finished
379  // setup are kept and written back, instead of taking defaults and asking for setup again.
380  if (!snapshot.stored && !sync.migration) {
381    const held = await read($, settings)
382    if (held !== null && normalizeSettings(held).setupDone) sync = await update($, settingsSync, value => ({ ...value, migrationChecked: true, migration: normalizeSettings(held) }))
383  }
384  if (!sync.migrationChecked) {
385    let migration: Settings | null = null
386    if (!snapshot.stored) {
387      const legacy = await $.store.get('settings')
388      const setupDone = await $.store.get('setupDone')
389      if (legacy !== undefined && legacy !== null || setupDone === true) {
390        migration = normalizeSettings(legacy)
391        if (setupDone === true) migration.setupDone = true
392      }
393    }
394    sync = await update($, settingsSync, value => ({ ...value, migrationChecked: true, migration }))
395  }
396  if (sync.revision !== snapshot.revision || await read($, settings) === null) await acceptSettings($, snapshot)
397  sync = await read($, settingsSync)
398  if (sync.pending.length || sync.migration) await putSettings($, admin, snapshot.stored ? snapshot.settings : sync.migration ?? snapshot.settings)
399}
400async function loadSettings($: EngineInterface): Promise<void> {
401  try { await settingsTask(async () => { await syncSettings($, await adminUrl($)) }) }
402  catch (error) { await installSettings($, await currentSettings($)); await routerSettingsDown($, error) }
403  const hidden = (await $.store.get('bandHidden')) === true
404  await update($, bandHidden, () => hidden)
405  if (!(await read($, pick))) {
406    const carried = object(await $.store.get('pick'))
407    const level = effortOf(carried.effort)
408    if (level && ['haiku', 'jev', 'model', 'manual', 'followup'].includes(String(carried.by))) {
409      carriedPick = true
410      await update($, pick, () => ({ effort: level, why: typeof carried.why === 'string' ? carried.why : '', by: carried.by as Pick['by'], at: typeof carried.at === 'number' ? carried.at : 0 }))
411    }
412  }
413}
414async function saveSettings($: EngineInterface, s: Settings, baseline?: Settings): Promise<boolean> {
415  // Both sides use the same format: normalization alone is never an edit.
416  const changes = settingsChanges(normalizeSettings(baseline ?? await currentSettings($)), normalizeSettings(s))
417  try {
418    await settingsTask(async () => {
419      await update($, settingsSync, value => ({ ...value, pending: [...value.pending, ...changes] }))
420      await installSettings($, applySettingsChanges(await currentSettings($), changes))
421      const admin = await adminUrl($)
422      // Always rebase on the router, never PUT the normalized local atom wholesale.
423      await syncSettings($, admin)
424    })
425    return true
426  } catch (error) { await routerSettingsDown($, error); return false }
427}
428async function installPick($: EngineInterface, value: Pick): Promise<void> {
429  carriedPick = false
430  await update($, pick, () => value)
431  await $.store.set('pick', value)
432}
433
434// The engine's pane list is authoritative: a reload can close panes without sending ui.close.
435async function isLogUp($: EngineInterface): Promise<boolean> {
436  return (await $.ui.panes()).some(p => p.id === LOG_PANE)
437}
438async function syncPanes($: EngineInterface): Promise<void> {
439  const panes = await $.ui.panes()
440  const log = panes.some(p => p.id === LOG_PANE)
441  const agent = panes.some(p => p.id === AGENTS_PANE)
442  if (log !== await read($, logOpen)) await update($, logOpen, () => log)
443  if (agent !== await read($, agentsOpen)) await update($, agentsOpen, () => agent)
444}
445async function toggleLog($: EngineInterface): Promise<boolean> {
446  const language = await read($, lang)
447  const open = await isLogUp($)
448  if (open) await $.ui.close({ id: LOG_PANE })
449  else {
450    // The surface may decline to draw the pane; say why rather than doing nothing on a press.
451    const opened = await $.ui.open({ id: LOG_PANE, title: t(language, 'commands.logTitle') })
452    if (!opened.isPlaced) {
453      const why = 'reason' in opened && opened.reason ? String(opened.reason) : 'not placed'
454      $.ui.toast(t(language, 'toasts.logNotPlaced', { reason: why }))
455      await report($, 'log pane', why)
456    }
457  }
458  await syncPanes($)
459  if (!open) await refreshRouter($)
460  return !open
461}
462async function toggleAgents($: EngineInterface): Promise<void> {
463  const language = await read($, lang)
464  const open = (await $.ui.panes()).some(p => p.id === AGENTS_PANE)
465  if (open) await $.ui.close({ id: AGENTS_PANE })
466  else await $.ui.open({ id: AGENTS_PANE, title: t(language, 'commands.agentsTitle') })
467  await syncPanes($)
468}
469/**
470 * The Context pane, opened as a dialog: it takes the keyboard, Escape closes it and toasts wait
471 * while it shows. It is read and left, as the app's own breakdown was.
472 */
473async function toggleContext($: EngineInterface): Promise<void> {
474  const language = await read($, lang)
475  if ((await $.ui.panes()).some(p => p.id === CONTEXT_PANE)) await $.ui.close({ id: CONTEXT_PANE })
476  else await $.ui.open({ id: CONTEXT_PANE, title: t(language, 'commands.contextTitle'), focus: true, closeOnEscape: true, holdToasts: true, rows: 30 })
477}
478/** What the precise count was taken in: the same tokens in another chat, model or window are a different share. */
479type FullMark = { basis: number | null; window: number | null; model: string; at: number | null; generation: number; context: number; run: number }
480let fullMark: FullMark | null = null
481/** Bumped whenever this chat's context is replaced or its model/window changes; a count from before is dropped. */
482let contextRun = 0
483/** Bumped when this chat's context is replaced by a compaction; clear/resume/fork move `generation`. */
484let contextEpoch = 0
485function countsHere(mark: FullMark, basis: number | null, model: string, at: number | null): boolean {
486  return mark.basis === basis && mark.model === model && mark.at === at && mark.generation === generation && mark.context === contextEpoch && mark.run === contextRun
487}
488/**
489 * The limits pane, opened from the band's limits row: every plan window with the share it has used
490 * and when it resets, which the row has no room to say. Opened again it closes, as does the pane's
491 * own close. The windows are read afresh on the way in, once a minute at most (refreshLimits).
492 */
493async function toggleLimits($: EngineInterface): Promise<void> {
494  const language = await read($, lang)
495  if ((await $.ui.panes()).some(p => p.id === LIMITS_PANE)) await $.ui.close({ id: LIMITS_PANE })
496  else {
497    await refreshLimits($)
498    await $.ui.open({ id: LIMITS_PANE, title: t(language, 'commands.limitsTitle') })
499  }
500}
501/**
502 * The token-count API's count of the context (`full`, one request per tool and memory file), kept
503 * against the last response's tokens when it was asked for: the next step makes it stale, and the
504 * pane (and the band, contextShare) shows the local estimate again. Its tokens alone do not say
505 * which model, window or conversation counted them (2026-10-25: a model switch left 20% standing
506 * where the new window read 4%), so `fullMark` holds that state beside it. A slow answer is
507 * published only in the state it was asked for: a clear, compaction or model/window switch while
508 * it runs drops it instead of writing over the newer count (2026-10-25).
509 */
510async function countContext($: EngineInterface): Promise<void> {
511  if ((await read($, contextFull))?.busy) return
512  const basis = (await read($, context))?.basis ?? null
513  const at = await read($, compactAt)
514  const model = await $.session.model()
515  const gen = generation
516  const epoch = contextEpoch
517  const run = ++contextRun
518  await update($, contextFull, () => ({ basis, busy: true }))
519  try {
520    const usage = await $.session.usage({ breakdown: 'full' })
521    const breakdown = usage.context.breakdown
522    const window = usage.context.window ?? null
523    // The answer must still describe this chat, model and request: a clear, a compaction or a
524    // switch while it ran makes it another context's count, and it is dropped.
525    const now = await $.session.usage().catch(error => { void report($, 'context check', error); return null })
526    const nowModel = await $.session.model()
527    const nowAt = await read($, compactAt)
528    const nowBasis = (await read($, context))?.basis ?? null
529    // Read the scope again after every await: a clear may have moved it while this ran.
530    const live = run === contextRun && gen === generation && epoch === contextEpoch && model === nowModel && at === nowAt && basis === nowBasis && now !== null && now.context.window === window
531    if (!live) {
532      await update($, contextFull, current => run === contextRun && current?.busy ? null : current)
533      return
534    }
535    fullMark = { basis, window, model, at, generation: gen, context: epoch, run }
536    const none = t(await read($, lang), 'context.none')
537    const result = breakdown ? { basis, breakdown } : { basis, error: none }
538    await update($, contextFull, current => run === contextRun && gen === generation && epoch === contextEpoch ? result : current)
539  } catch (error) {
540    if (run !== contextRun || gen !== generation || epoch !== contextEpoch) {
541      await update($, contextFull, current => run === contextRun && current?.busy ? null : current)
542      return
543    }
544    fullMark = { basis, window: null, model, at, generation: gen, context: epoch, run }
545    const failure = { basis, error: reason(error) }
546    await update($, contextFull, current => run === contextRun && gen === generation && epoch === contextEpoch ? failure : current)
547    await report($, 'context count', error)
548  }
549}
550function contextActions($: EngineInterface): ContextActions {
551  return {
552    refresh: () => countContext($),
553    toggle: section => update($, contextShowAll, list => (list.includes(section) ? list.filter(s => s !== section) : [...list, section])),
554    close: () => $.ui.close({ id: CONTEXT_PANE }),
555  }
556}
557async function toggleBar($: EngineInterface): Promise<boolean> {
558  const hidden = !await read($, bandHidden)
559  await $.store.set('bandHidden', hidden)
560  await update($, bandHidden, () => hidden)
561  return !hidden
562}
563async function refreshRouter($: EngineInterface): Promise<void> {
564  const language = await read($, lang)
565  if (polling) return
566  polling = true
567  try {
568    await syncPanes($)
569    const admin = await adminUrl($)
570    await settingsTask(() => syncSettings($, admin))
571    await endModeIfOver($)
572    const session = await $.session.id()
573    // Read even with the band hidden: the strip shows over whatever is above the prompt.
574    await refreshPhoneQueue($, session)
575    const open = await isLogUp($)
576    if (!open && await read($, bandHidden)) { await update($, line, () => null); return }
577    const own = await $.http.fetch(`${admin}/api/requests?kind=messages&n=${open ? 60 : 20}&session=${encodeURIComponent(session)}`)
578    if (!own.ok) throw new Error(t(language, 'commands.routerHttp', { status: own.status }))
579    const mine = (object(JSON.parse(own.text)).requests ?? []) as StatusRequest[]
580    const newest = mine[0] ?? null
581    const notice = newest && newest.session === undefined ? t(language, 'band.routerRestart') : null
582    if (notice !== await read($, line)) await update($, line, () => notice)
583    // Do not show a route belonging to another chat from a router without session support. The
584    // route is this chat's own: subagents share its session id, and a route that moved with each
585    // worker request redrew the band every poll, starting 리플이's motion over each time.
586    const route = notice ? null : mine.find(r => !r.subagent) ?? await read($, last)
587    if (JSON.stringify(route) !== JSON.stringify(await read($, last))) await update($, last, () => route)
588    if (!open) return
589    let shown = mine
590    if (!await read($, onlySession)) {
591      const all = await $.http.fetch(`${admin}/api/requests?kind=messages&n=60`)
592      if (!all.ok) throw new Error(t(language, 'commands.routerHttp', { status: all.status }))
593      shown = (object(JSON.parse(all.text)).requests ?? []) as StatusRequest[]
594    }
595    const rows = shown.map(record => ({ ...record, mine: record.session === session }))
596    if (JSON.stringify(rows) !== JSON.stringify(await read($, requests))) await update($, requests, () => rows)
597  } catch (error) {
598    if (await read($, line) !== t(language, 'band.routerDown')) await update($, line, () => t(language, 'band.routerDown'))
599    await report($, 'router poll', error)
600  } finally { polling = false }
601}
602
603// Files and availability are sampled at spawn, not cached across quota/account changes.
604async function workerFiles($: EngineInterface): Promise<Map<string, string>> {
605  const text = await optionalFile($, `${await rippleHome($)}/generated-agents.json`)
606  const names = text ? strings(object(JSON.parse(text)).agents) : []
607  const files = new Map<string, string>()
608  for (const name of names) {
609    if (!/^[A-Za-z0-9_.-]+$/.test(name)) continue
610    const file = await optionalFile($, `${await claudeHome($)}/agents/${name}.md`)
611    if (file && agentModel(file)) files.set(name, file)
612  }
613  return files
614}
615/**
616 * The provider a started agent runs on, for its card's dot: its worker file's (`via <provider>.`),
617 * Anthropic for a Claude id, else the router's catalogue entry for the id.
618 */
619async function spawnProvider($: EngineInterface, subagentType: string, model: string): Promise<string | undefined> {
620  const file = (await workerFiles($)).get(subagentType)
621  const fromFile = file ? agentProvider(file) : undefined
622  if (fromFile) return fromFile
623  const id = model.replace(/@[^@]*$/, '')
624  if (/^(?:sonnet|opus|haiku|fable|mythos|claude-)/.test(id)) return 'anthropic'
625  return (await read($, routerModels)).find(m => m.value === id)?.provider
626}
627async function releaseDelegationPin($: EngineInterface): Promise<void> {
628  if (!await read($, delegationPin)) return
629  await update($, delegationPin, () => null)
630  await $.ui.toast(t(await read($, lang), 'toasts.delegationUnpinned'))
631}
632async function hearDelegationPin($: EngineInterface, text: string): Promise<void> {
633  const instruction = pinInstruction(text)
634  if (!instruction) return
635  if (instruction === 'release') { await releaseDelegationPin($); return }
636  const files = await workerFiles($)
637  // Generated files cover routed workers even before the first catalogue poll.
638  const workers = [...files.values()].flatMap(file => {
639    const model = agentModel(file), provider = agentProvider(file)
640    return model && provider ? [{ model, provider }] : []
641  })
642  const sources = workers.concat(claudeCandidates(), (await read($, routerModels)).map(m => ({ model: m.value, provider: m.provider })))
643  const pin = parseDelegationPin({ role: 'user', text }, sources, workers)
644  if (pin === undefined) return
645  if (pin === null) { await releaseDelegationPin($); return }
646  const current = await read($, delegationPin)
647  // The same model said again keeps the sentence that first pinned it.
648  if (current && current.model === pin.model && current.provider === pin.provider) return
649  const said = pinSaid(text, pin.model)
650  await update($, delegationPin, () => ({ ...pin, ...(said ? { said } : {}) }))
651  await $.ui.toast(t(await read($, lang), 'toasts.delegationPinned', { name: titleName(pin.model, await read($, routerModels)) }))
652}
653async function workerFix($: EngineInterface, spawn: Spawn): Promise<WorkerFix | null> {
654  const text = await optionalFile($, `${await rippleHome($)}/generated-agents.json`)
655  if (!text || !strings(object(JSON.parse(text)).agents).includes(spawn.subagentType)) return null
656  if (!/^[A-Za-z0-9_.-]+$/.test(spawn.subagentType)) return null
657  const file = await optionalFile($, `${await claudeHome($)}/agents/${spawn.subagentType}.md`)
658  const model = file ? agentModel(file) : undefined
659  return model ? fixSpawn(spawn, model) : null
660}
661async function availability($: EngineInterface): Promise<boolean> {
662  try {
663    const status = await $.http.fetch(`${await adminUrl($)}/api/status`)
664    return status.ok ? chatgptUsable(JSON.parse(status.text)) : true
665  } catch (error) { await report($, 'availability unknown', error); return true }
666}
667async function refreshModels($: EngineInterface): Promise<void> {
668  const response = await $.http.fetch(`${await adminUrl($)}/api/config`)
669  if (!response.ok) throw new Error(t(await read($, lang), 'commands.routerHttp', { status: response.status }))
670  await update($, routerModels, () => routerModelOptions(JSON.parse(response.text)))
671}
672/** How long the rung choices are kept: ten minutes. */
673const KEEP_MS = 600000
674
675/**
676 * The quick settings' rung choices, read again each time the panel opens: a model ticked on the
677 * dashboard shows in every Select without a restart. A failure keeps what was there.
678 */
679async function refreshLadder($: EngineInterface): Promise<void> {
680  try {
681    const response = await $.http.fetch(`${await adminUrl($)}/api/mod-options`)
682    if (!response.ok) throw new Error(t(await read($, lang), 'commands.routerHttp', { status: response.status }))
683    const fresh = ladderOptionsFrom(JSON.parse(response.text), await $.clock.now() + KEEP_MS, (await currentSettings($)).allow, (await currentSettings($)).allowKnown)
684    if (!same(await read($, ladderOptions), fresh)) await update($, ladderOptions, () => fresh)
685  } catch (error) { await report($, 'ladder options', error) }
686}
687/** Turns a mode on (stamping when, for a mode that runs until the quota resets), or off with ''. */
688async function setMode($: EngineInterface, id: string): Promise<void> {
689  const change: Partial<Settings> = id ? { activeMode: id, activeSince: await $.clock.now() } : { activeMode: undefined, activeSince: undefined }
690  await settingsActions($).patch(change)
691}
692/** Keep observed reset deadlines while a mode is on, even if the next snapshot rolls forward. */
693let modeQuotaAt = 0
694let modeQuotaKey: string | null = null
695let modeQuotaWindows: QuotaWindow[] = []
696let endingMode = false
697/** The chosen provider's windows: Claude uses the band's binding limit; ChatGPT its account quota API. */
698async function modeWindows($: EngineInterface, provider: string): Promise<QuotaWindow[]> {
699  if (provider === 'anthropic') return claudeWindow(await read($, limit))
700  const response = await $.http.fetch(`${await adminUrl($)}/api/chatgpt-accounts?provider=${encodeURIComponent(provider)}`)
701  if (!response.ok) return []
702  const body: unknown = JSON.parse(response.text)
703  // The router answers for its first ChatGPT provider when the name is not one: not this provider.
704  return object(body).provider === provider ? quotaWindows(body) : []
705}
706/** A mode whose time is up turns itself off and says so (on each poll and prompt). */
707async function endModeIfOver($: EngineInterface): Promise<void> {
708  if (endingMode) return
709  endingMode = true
710  try {
711    const s = await currentSettings($)
712    const mode = activeModeOf(s)
713    const key = modeKey(s) + JSON.stringify([mode?.rungs, mode?.until])
714    if (modeQuotaKey !== key) { modeQuotaKey = key; modeQuotaAt = 0; modeQuotaWindows = [] }
715    if (!mode || mode.until === 'none') return
716    const now = await $.clock.now()
717    let windows = modeQuotaWindows
718    const provider = resetProvider(mode)
719    if (provider) {
720      // Claude's limit arrives with the session; read it on every check, not once a minute.
721      if (provider === 'anthropic') windows = [...windows, ...claudeWindow(await read($, limit))]
722      if (!modeOver(mode, s.activeSince, now, windows) && now - modeQuotaAt >= 60_000) {
723        const fresh = await modeWindows($, provider)
724        modeQuotaAt = now
725        // Keep only the earliest observed deadline after activation, plus current snapshots.
726        const first = [...windows, ...fresh].filter(w => w.at > (s.activeSince ?? now)).sort((a, b) => a.at - b.at)[0]
727        modeQuotaWindows = [...(first ? [first] : []), ...fresh]
728        windows = modeQuotaWindows
729      }
730    }
731    if (!modeOver(mode, s.activeSince, now, windows)) return
732    await saveSettings($, { ...s, activeMode: undefined, activeSince: undefined }, s)
733    await $.ui.toast(t(await read($, lang), 'toasts.modeEnded', { name: mode.name }))
734  } catch (error) { await report($, 'mode end', error) }
735  finally { endingMode = false }
736}
737async function jevKey($: EngineInterface, jevSource?: Settings['jevSource']): Promise<string | undefined> {
738  const selected = jevSource ?? normalizeSettings(await read($, settingsDraft) ?? await read($, settings)).jevSource
739  if (selected === 'zen') {
740    const file = await optionalFile($, `${await rippleHome($)}/config.json`)
741    const key = file ? zenJev(JSON.parse(file)).authorization : undefined
742    await update($, jev, value => ({ ...value, source: key ? 'zen' as const : null }))
743    return key
744  }
745  const env = (await $.env.get('TYPESAFE_API_KEY'))?.trim()
746  if (env) {
747    if ((await read($, jev)).source !== 'env') await update($, jev, value => ({ ...value, source: 'env' as const }))
748    return env
749  }
750  const file = await optionalFile($, `${await userHome($)}/.config/jev/.env`)
751  const key = file ? parseJevKey(file) : undefined
752  const source: 'pasted' | 'file' | null = key ? ((await read($, jev)).source === 'pasted' ? 'pasted' : 'file') : null
753  if ((await read($, jev)).source !== source) await update($, jev, value => ({ ...value, source }))
754  return key
755}
756/** OpenCode Zen's key from the router's config, when Zen lists a Jev model there; else none. */
757async function zenJevKey($: EngineInterface): Promise<string | undefined> {
758  const file = await optionalFile($, `${await rippleHome($)}/config.json`)
759  if (!file) return undefined
760  const config: unknown = JSON.parse(file)
761  const models = object(object(object(config).providers)['opencode-zen']).models
762  const listed = Array.isArray(models) && models.some(m => { const id = object(m).id; return typeof id === 'string' && id.toLowerCase().includes('jev') })
763  return listed ? zenJev(config).authorization : undefined
764}
765async function saveJevKey($: EngineInterface, input: string): Promise<void> {
766  const language = await read($, lang)
767  const key = parseJevKey(input) ?? input.trim()
768  if (!key || /[\r\n]/.test(key)) throw new Error(t(language, 'toasts.keySingle'))
769  const path = `${await userHome($)}/.config/jev/.env`
770  const old = await optionalFile($, path) ?? ''
771  const entry = `TYPESAFE_API_KEY=${key}`
772  const text = /^[ \t]*TYPESAFE_API_KEY[ \t]*=/m.test(old)
773    ? old.replace(/^[ \t]*TYPESAFE_API_KEY[ \t]*=[^\r\n]*/gm, () => entry)
774    : old + (old && !old.endsWith('\n') ? '\n' : '') + entry + '\n'
775  await $.fs.write(path, text)
776  const mode = await $.process.run(['chmod', '600', path])
777  if (mode.exitCode !== 0) throw new Error(t(language, 'toasts.keyPrivateFailed'))
778  await update($, jev, () => ({ source: 'pasted' as const, test: { state: 'idle' as const } }))
779  await update($, judgeDown, () => null)
780  await $.ui.toast(t(language, 'toasts.keySaved'))
781}
782/**
783 * A judge failure is said once per reason in a session (a toast and the band); the same reason
784 * again stays quiet, so a judge that keeps failing does not speak on every message.
785 */
786async function down($: EngineInterface, message: string, network = false): Promise<void> {
787  if ((await read($, judgeSeen)).includes(message)) return
788  await update($, judgeSeen, value => [...value, message].slice(-20))
789  await update($, judgeDownNetwork, () => network)
790  await update($, judgeDown, () => message)
791  await $.ui.toast(t(await read($, lang), 'toasts.judgeDown', { reason: message }))
792}
793
794type Judged = { verdict: Verdict | undefined; by: JudgeKind; ms: number; error?: string }
795function judgeFailure(answer: ModelCompleteResult): string | undefined {
796  if (answer.isAnswered) return undefined
797  return answer.reason === 'api-error' ? `${answer.reason}: ${answer.error} (${answer.status ?? 'no response'})` : answer.reason
798}
799async function completeJudge($: EngineInterface, model: string, system: string, prompt: string): Promise<ModelCompleteResult> {
800  return $.model.complete({ model, system, prompt, maxTokens: 160, timeoutMs: 6000, effort: 'low' })
801}
802/** The main session's effort. Delegated workers are no longer judged: the session names their tier (2026-10-24). */
803async function judge($: EngineInterface, s: Settings, input: JudgeInput, testing = false): Promise<Judged> {
804  const language = await read($, lang)
805  const started = await $.clock.now()
806  const system = EFFORT_JUDGE_SYSTEM
807  const prompt = judgeContext(input)
808  let failure: string | undefined
809  let by: JudgeKind = s.judge
810  let verdict: Verdict | undefined
811  let blip = false
812  if (s.judge === 'jev') {
813    try {
814      let source = s.jevSource
815      let key = await jevKey($, source)
816      // No TypeSafe key, but the router's OpenCode Zen offers Jev: ask Jev there.
817      if (!key && source === 'typesafe') {
818        key = await zenJevKey($)
819        if (key) source = 'zen'
820      }
821      if (!key) throw new Error(t(language, source === 'zen' ? 'jev.zenMissing' : 'toasts.keyMissing'))
822      const body = jevEffortRequest(input)
823      let model = 'jev-latest'
824      if (source === 'zen') {
825        const file = await optionalFile($, `${await rippleHome($)}/config.json`)
826        model = file ? zenJev(JSON.parse(file)).model : model
827      }
828      const response = await Promise.race([
829        $.http.fetch(source === 'zen' ? 'https://opencode.ai/zen/v1/systemone' : 'https://api.typesafe.ai/v1/systemone', { method: 'POST', headers: { 'content-type': 'application/json', authorization: source === 'zen' ? key : `Bearer ${key}` }, body: JSON.stringify({ ...body, model }) })
830          .catch(() => 'network' as const),
831        // Jev answers in about 2.1–2.4 s even with a full context (measured 2026-10-22), so 3 s timed
832        // out whenever OpenCode slowed down — and the Haiku fallback then cost more than waiting.
833        $.clock.sleep(5000).then(() => null),
834      ])
835      // A dropped connection or a slow answer is often one bad moment, not a broken judge.
836      if (!response || response === 'network') {
837        blip = true
838        throw new Error(jevFailure(response ? 'network' : 'timeout', language))
839      }
840      if (!response.ok) throw new Error(jevFailure(response.status, language))
841      const json: unknown = JSON.parse(response.text)
842      // An unsure Jev still answered: its odds settle it here and the bias setting tips it later. Haiku is only for a Jev that failed.
843      verdict = parseJevEffort(json, input.current ?? null, language)
844      await update($, stats, value => addJudge(value, 'jev', 0, jevUsage(json)))
845      if (!verdict) throw new Error(t(language, 'toasts.jevNoVerdict'))
846    } catch (error) { failure = reason(error); verdict = undefined }
847  }
848  if (s.judge === 'model') {
849    try {
850      const answer = await completeJudge($, s.judgeModel, system, prompt)
851      await update($, stats, value => addJudge(value, 'model', 0, answer.usage.input_tokens + answer.usage.output_tokens))
852      verdict = answer.isAnswered ? parseEffortVerdict(answer.text) : undefined
853      if (!verdict) failure = judgeFailure(answer) ?? t(language, 'toasts.routerNoVerdict')
854    } catch (error) { failure = reason(error) }
855  }
856  if (!verdict) {
857    by = 'haiku'
858    try {
859      let answer = await completeJudge($, HAIKU, system, prompt)
860      await update($, stats, value => addJudge(value, 'haiku', 0, answer.usage.input_tokens + answer.usage.output_tokens))
861      if (!answer.isAnswered) {
862        failure ??= judgeFailure(answer)
863        answer = await completeJudge($, 'haiku', system, prompt)
864        await update($, stats, value => addJudge(value, 'haiku', 0, answer.usage.input_tokens + answer.usage.output_tokens))
865      }
866      verdict = answer.isAnswered ? parseEffortVerdict(answer.text) : undefined
867      if (!verdict) failure ??= t(language, 'toasts.haikuNoVerdict')
868    } catch (error) { failure ??= reason(error) }
869  }
870  const ms = Math.max(0, await $.clock.now() - started)
871  await update($, stats, value => ({ ...value, judge: { ...value.judge, ms: value.judge.ms + ms } }))
872  if (!testing) {
873    // The log pane lists it: a Jev call never reaches the router, so nothing else would show it.
874    const run: JudgeRun = { at: started, for: 'prompt', asked: s.judge, by, ms, ...(verdict?.effort ? { effort: verdict.effort } : {}), ...(verdict?.sure !== undefined ? { sure: verdict.sure } : {}), ...(failure ? { error: failure } : {}) }
875    await update($, judgeRuns, value => [...value, run].slice(-40))
876    // A network blip or timeout is said only when it happens twice running; Haiku covers the one prompt.
877    jevBlips = blip ? jevBlips + 1 : 0
878    if (failure && !(blip && jevBlips < 2)) await down($, failure, blip)
879    else if (await read($, judgeDown)) await update($, judgeDown, () => null)
880  }
881  return { verdict, by, ms, ...(failure ? { error: failure } : {}) }
882}
883async function testJudge($: EngineInterface): Promise<void> {
884  const language = await read($, lang)
885  await update($, jev, value => ({ ...value, test: { state: 'testing' as const } }))
886  try {
887    const s = normalizeSettings(await read($, settingsDraft) ?? await read($, settings))
888    const judged = await judge($, s, { messages: [], next: 'Rename a local variable in one function and verify the result.' }, true)
889    const ok = !!judged.verdict && !judged.error
890    await update($, jev, value => ({ ...value, test: { state: ok ? 'ok' as const : 'fail' as const, message: `${judged.ms} ms · ${judged.verdict?.effort ? t(language, 'band.' + judged.verdict.effort).toLowerCase() : t(language, 'toasts.noVerdict')} · ${judged.error ?? judged.by}` } }))
891  } catch (error) {
892    await update($, jev, value => ({ ...value, test: { state: 'fail' as const, message: reason(error) } }))
893  }
894}
895
896async function requestPick($: EngineInterface, e: AgentSpawnInput, s: Settings): Promise<{ input: AgentSpawnInput; pick: WorkerPick } | { deny: string }> {
897  const language = await read($, lang)
898  const files = await workerFiles($)
899  try { await refreshModels($) } catch (error) { await report($, 'worker catalogue', error) }
900  // Claude's own models are candidates as well: general-purpose on the model, effort by turn.step.
901  const pinnedCandidates: WorkerCandidate[] = [...[...files].flatMap(([agent, file]) => { const model = agentModel(file)?.replace(/@[^@]*$/, ''); const provider = agentProvider(file); return model && provider ? [{ target: { agent }, model, provider }] : [] }), ...claudeCandidates()]
902  const usable = await availability($)
903  // The session names the tier and domain; the owner's ladder names the model (2026-10-24, the
904  // worker judge removed: see AUTO_DESCRIPTION). A model is named only with where it comes from.
905  const marker = readMarker(e.prompt)
906  const tier = tierOf(marker)
907  const markerModel = marker && !tier && !['auto', 'ripple'].includes(marker.name) ? marker.name : undefined
908  // Calling a worker agent by type, or Claude's own agent on a model (agentAuto "all"), names that
909  // model just as a marker does; ignored, a design brief sent to Opus ran on the general ladder.
910  const auto = ['ripple:auto', 'auto'].includes(e.subagentType)
911  const direct = auto ? undefined : files.has(e.subagentType) ? e.subagentType : e.subagentType === 'general-purpose' && e.model ? e.model.replace(/@[^@]*$/, '').toLowerCase() : undefined
912  const asked = markerModel ?? direct
913  const reason = modelReason(e.prompt)
914  const prompt = withoutRouting(e.prompt)
915  const pin = await read($, delegationPin)
916  const id = (await $.clock.now()).toString(36) + Math.random().toString(36).slice(2, 8)
917  const named = tier ? TIER_MARKERS[tier]! : { level: 'standard' as const, kind: 'do' as const }
918  let verdict: WorkerVerdict = { domain: markerDomain(tier ? marker!.domain : undefined), ...named, effort: RUNG_EFFORT[rungOf(named)], why: tier ? t(language, 'toasts.sessionTier', { tier }) : t(language, 'toasts.noTier') }
919  let by: WorkerPick['by'] = tier ? 'session' : 'default'
920  let target: TierTarget | undefined
921  const mode = activeModeOf(s)
922  const routing = routingSettings(s)
923  if (asked) {
924    // The mod checks the session's claim and never re-reads it as language: a reason must be given,
925    // the user's words must be ones they said, and the name must be a model this machine can run.
926    if (!reason) return { deny: t(language, 'workers.noReason', { name: asked }) }
927    if (reason.source === 'user') {
928      const words = (await $.session.messages()).flatMap(m => { const text = humanText(m); return text ? [text] : [] }).slice(-10)
929      words.push(...await read($, heardPrompts))
930      if (!reason.quote || !userSaid(reason.quote, words)) return { deny: t(language, 'workers.notSaid', { name: asked }) }
931    } else if (!ruleReason(reason.text)) return { deny: t(language, 'workers.noReason', { name: asked }) }
932    const known = [...files].some(([agent, f]) => agent.toLowerCase() === asked.toLowerCase() || agentModel(f)?.replace(/@[^@]*$/, '').toLowerCase() === asked.toLowerCase()) || ['opus', 'sonnet', 'haiku'].includes(asked) || asked.startsWith('claude-')
933    if (!known) return { deny: t(language, 'workers.unknownModel', { name: asked }) }
934  }
935  // The user's words for this task, then their standing pin, then a written rule, then the ladder.
936  const source = asked && reason!.source === 'user' ? 'user' : pin ? 'pin' : asked ? 'rule' : null
937  const namedModel = source === 'pin' ? pin!.model : source ? asked! : undefined
938  if (namedModel) {
939    const fromPin = source === 'pin' && pin?.provider
940    const name = [...files].find(([agent, file]) => (agent.toLowerCase() === namedModel.toLowerCase() || agentModel(file)?.replace(/@[^@]*$/, '').toLowerCase() === namedModel.toLowerCase()) && (!fromPin || agentProvider(file) === pin!.provider))?.[0]
941    target = name ? { agent: name } : { agent: 'general-purpose', model: namedModel }
942    by = source === 'rule' ? 'rule' : 'user'
943    verdict = { ...verdict, effort: (source !== 'pin' ? effortOf(marker?.level ?? /@([a-z]+)$/.exec(e.model ?? '')?.[1]) : undefined) ?? 'high', why: t(language, source === 'rule' ? 'toasts.rulePick' : 'toasts.yourPick') }
944  }
945  // Availability is request-time state, not the ten-minute panel catalogue. Refresh before every
946  // pick, even when no mode is active.
947  await refreshLadder($)
948  const now = await $.clock.now()
949  const options = await read($, ladderOptions)
950  const providers = options && options.until > now ? liveProviders(options.providers ?? {}, now) : {}
951  const explicitCandidate = target ? pinnedCandidates.find(c => c.target.agent === target!.agent && c.target.model === target!.model) ?? (target.agent === 'general-purpose' ? { target, model: target.model ?? 'sonnet', provider: (source === 'pin' ? pin?.provider : undefined) ?? (await read($, routerModels)).find(m => m.value.toLowerCase() === target!.model?.toLowerCase())?.provider ?? 'anthropic' } : undefined) : undefined
952  if (explicitCandidate && s.providers[explicitCandidate.provider] === false) return { deny: t(language, 'workers.disabled', { provider: explicitCandidate.provider }) }
953  // An active mode replaces the ladder, not the user's named model (2026-10-24).
954  const { rule, ladder } = workerRule(verdict.domain, routing)
955  const explicitUsable = !!explicitCandidate && candidateUsable(explicitCandidate, s, usable, providers)
956  const ladderResult = explicitUsable ? null : ladderPick(verdict, ladder, routing, pinnedCandidates, usable, language, routing.allow, providers, routing.allowKnown)
957  const resolved = ladderResult ?? { target: target!, effort: verdict.effort }
958  // The pick says who chose what ran: a named model that could not run leaves the ladder's choice
959  // (its name and source stay in the log beside the reason).
960  if (namedModel && ladderResult) by = tier ? 'session' : 'default'
961  // A named model that cannot run now says so beside the ladder's own reasons.
962  const reasons = [explicitCandidate && !explicitUsable ? t(language, 'workers.namedUnavailable', { name: explicitCandidate.model }) : '', resolved.fallbackReason ?? ''].filter(Boolean)
963  const fallbackReason = reasons.length ? reasons.join('; ') : undefined
964  const selected = resolved.target
965  if (!selected) {
966    const said = t(language, 'workers.ladderEmpty', { reason: fallbackReason ?? t(language, 'workers.none') })
967    await $.ui.toast(said)
968    return { deny: said }
969  }
970  verdict = { ...verdict, effort: resolved.effort }
971  const model = spawnModel(selected, verdict.effort, files.has(selected.agent) ? agentModel(files.get(selected.agent)!) : undefined)
972  const value: WorkerPick = { ...verdict, ...resolved, rule, target: selected, by, ms: 0, id, ...(fallbackReason ? { fallbackReason } : {}) }
973  // The decision behind a pick is otherwise only in the agents panel; one debug line per pick keeps
974  // it checkable: the tier it was given, the rung it landed on and what ran.
975  const entry = { task: e.description.slice(0, 200), domain: value.domain, level: value.level, kind: value.kind ?? 'do', rule: value.rule, rung: value.rung, position: value.position, skipped: value.skipped, target: value.target, model: model ?? null, effort: value.effort, by, ...(mode ? { mode: mode.name } : {}), ...(fallbackReason ? { fallbackReason } : {}) }
976  await $.ui.log('ClaudeRipple worker pick: ' + JSON.stringify(entry), { to: 'debug' })
977  // The brief itself is never logged (it can hold anything); its length is. To read a pick again,
978  // its brief is in the session's own transcript under the same description. A model's reason is
979  // kept, short, so a wrong source can be found.
980  await persistWorkerPick($, { type: 'pick', id, ...entry, at: new Date(now).toISOString(), ...(tier ? { tier } : {}), ...(namedModel ? { namedModel, source, ...(source !== 'pin' && reason ? { reason: reason.text.slice(0, 200) } : {}) } : {}), promptChars: e.prompt.length })
981  if (fallbackReason) await $.ui.toast(t(language, 'toasts.workerFallback', { reason: fallbackReason, name: targetLabel(selected, language) }))
982  await update($, lastSpawn, () => value)
983  await update($, stats, current => addWorker(current, verdict.level))
984  // A choice stays canonical for allow-lists, logs and effort (general-purpose:<model>).
985  // Dispatch an auto call's Claude choice through our own definition, which withholds Agent.
986  // A hook may change the definition and model, but cannot add disallowedTools to a spawn.
987  // Direct general-purpose calls keep their own definition and existing behaviour.
988  const executor = auto && (selected.agent === 'general-purpose' || /^(?:opus|sonnet|haiku)(?:@|$)|^claude-/.test(model ?? '')) ? 'ripple:auto' : selected.agent
989  return { input: { ...e, subagentType: executor, model, prompt }, pick: value }
990}
991
992async function toggleAuto($: EngineInterface): Promise<void> {
993  const s = await currentSettings($)
994  await saveSettings($, { ...s, effortAuto: !s.effortAuto })
995}
996/** The band's flame turns keep-warm on or off for this chat only; Settings is what a new chat starts with. */
997async function keepWarmOn($: EngineInterface, s: Settings): Promise<boolean> {
998  return await read($, warmHere) ?? s.keepWarm
999}
1000async function toggleWarm($: EngineInterface): Promise<void> {
1001  const s = await currentSettings($)
1002  const on = !await keepWarmOn($, s)
1003  await update($, warmHere, () => on === s.keepWarm ? null : on)
1004  if (on) await update($, warm, value => ({ ...value, stopped: undefined }))
1005}
1006async function toggleSave($: EngineInterface): Promise<void> {
1007  const now = await $.clock.now()
1008  const active = (await read($, saveUntil) ?? 0) > now
1009  const until = active ? null : limitSaveUntil(await read($, hot), now)
1010  await update($, saveUntil, () => until)
1011}
1012async function manualPick($: EngineInterface, effort: Effort): Promise<void> {
1013  const language = await read($, lang)
1014  await saveSettings($, { ...await currentSettings($), effortAuto: false })
1015  await installPick($, { effort, by: 'manual', why: t(language, 'toasts.yourPick'), at: await $.clock.now() })
1016  const draft = await $.prompt.read()
1017  if (!draft.text.trim() || /^\/effort\s+\w+\s*$/.test(draft.text)) {
1018    await $.prompt.fill({ text: `/effort ${effort}`, mode: 'replace' })
1019    await $.ui.toast(t(language, 'toasts.effortEnter'))
1020  }
1021}
1022// Only first-run setup has a draft; quick settings read the saved state directly.
1023async function startPanel($: EngineInterface, which: 'settings' | 'setup'): Promise<void> {
1024  try { await settingsTask(async () => { await syncSettings($, await adminUrl($)) }) }
1025  catch (error) { await report($, 'panel settings', error) }
1026  const s = await currentSettings($)
1027  await update($, settingsDraft, () => which === 'setup' ? normalizeSettings(s) : null)
1028  await update($, settingsBase, () => which === 'setup' ? normalizeSettings(s) : null)
1029  if (which === 'setup') await update($, setupStep, () => 1)
1030  await update($, panel, () => which)
1031  await jevKey($)
1032  if (which === 'settings') await refreshLadder($)
1033}
1034/**
1035 * An open panel's draft follows changes saved elsewhere (another session, the web page): the
1036 * person's own edits (draft against base) are replayed on the settings now held, and the base
1037 * moves to them. Without a base (a draft from an older mod) the draft starts over from them.
1038 */
1039async function rebaseDraft($: EngineInterface): Promise<void> {
1040  if (await read($, panel) !== 'setup') return
1041  const draft = await read($, settingsDraft)
1042  if (!draft) return
1043  const fresh = await currentSettings($)
1044  const base = await read($, settingsBase)
1045  const next = base ? applySettingsChanges(fresh, settingsChanges(normalizeSettings(base), normalizeSettings(draft))) : normalizeSettings(fresh)
1046  if (base && JSON.stringify(normalizeSettings(base)) === JSON.stringify(fresh)) return
1047  await update($, settingsBase, () => normalizeSettings(fresh))
1048  if (JSON.stringify(next) !== JSON.stringify(normalizeSettings(draft))) await update($, settingsDraft, () => next)
1049}
1050async function patchDraft($: EngineInterface, change: Partial<Settings>): Promise<void> {
1051  const current = normalizeSettings(await read($, settingsDraft) ?? await read($, settings))
1052  await update($, settingsDraft, () => normalizeSettings({ ...current, ...change }))
1053  if (change.jevSource) { await update($, jev, value => ({ ...value, test: { state: 'idle' as const } })); await jevKey($, change.jevSource) }
1054}
1055async function finishSetup($: EngineInterface, skip = false): Promise<void> {
1056  // A field whose rule picks as the main choice does is stored as no exception.
1057  const draft = normalizeSettings(skip ? await read($, settings) : await read($, settingsDraft))
1058  const saved = await saveSettings($, { ...draft, setupDone: true }, skip ? undefined : normalizeSettings(await read($, settingsBase) ?? await currentSettings($)))
1059  await update($, panel, () => null)
1060  await update($, settingsDraft, () => null)
1061  await update($, settingsBase, () => null)
1062  await $.ui.toast(t(await read($, lang), saved ? 'toasts.settingsSaved' : 'band.routerDown'))
1063}
1064async function fork($: EngineInterface, prompt: string): Promise<ModelForkResult | null> {
1065  const epoch = generation
1066  forking = true
1067  forkUsage = null
1068  try {
1069    const answer = await $.model.fork({ prompt })
1070    // Real forks dispatch turn.step; test stubs and older engines can provide only the result.
1071    const usage = answer && 'usage' in answer ? answer.usage : forkUsage
1072    if (usage && epoch === generation) {
1073      await update($, stats, value => addWarm(value, usage))
1074      if ((usage.cache_read_input_tokens ?? 0) > 0) {
1075        const memo = nextMemo(await read($, cache), usage, await $.clock.now())
1076        await update($, cache, () => memo)
1077      }
1078    }
1079    return answer
1080  } finally { forking = false; forkUsage = null }
1081}
1082/**
1083 * The band's Handoff (2026-10-24): the note is written by a fork of this session (its own model,
1084 * its cache), started by the tick once the session is idle; nothing is sent to this chat. A press
1085 * while one is being written does nothing. This chat is never cleared (2026-10-13: a handoff that
1086 * cleared it lost the owner the chat).
1087 */
1088async function queueHandoff($: EngineInterface): Promise<void> {
1089  if ((await read($, handoff))?.stage === 'writing') return
1090  await update($, handoff, () => ({ stage: 'writing' as const, run: ++handoffRun }))
1091  await update($, panel, () => null)
1092  await update($, handoffQueued, () => true)
1093  // A tick now rather than at the next 15 s one: the card already says the note is being written.
1094  $.clock.after(1, async () => { await tick($) })
1095}
1096async function copyHandoff($: EngineInterface): Promise<void> {
1097  const language = await read($, lang)
1098  const value = await read($, handoff)
1099  if (!value?.text) return
1100  const text = wrapForNewChat(value.text)
1101  try {
1102    const copied = await $.ui.copy({ text })
1103    if (!copied.isCopied) throw new Error(copied.reason)
1104  } catch (error) {
1105    await $.prompt.fill({ text, mode: 'replace' })
1106    await $.ui.toast(t(language, 'toasts.clipboardFallback'))
1107    await report($, 'copy fallback', error)
1108  }
1109  await update($, handoff, () => ({ ...value, stage: 'copied' as const }))
1110}
1111/** A note longer than this goes to a file the new session reads; the app takes ~14k characters in a link. */
1112const LINK_TEXT = 12_000
1113/**
1114 * Opens a new Code session in this session's folder with the handoff in its prompt box
1115 * (claude://code/new?folder=…&q=…, the desktop app's own link: it fills the box and waits for
1116 * Enter, never sends by itself). A long note is saved under ~/.clauderipple/handoffs and the box
1117 * says to read it. Where no link can be opened, the text is copied instead.
1118 */
1119async function moveToNewSession($: EngineInterface): Promise<void> {
1120  const value = await read($, handoff)
1121  if (!value?.text) return
1122  const language = await read($, lang)
1123  let text = wrapForNewChat(value.text)
1124  try {
1125    if (text.length > LINK_TEXT) {
1126      const path = `${await rippleHome($)}/handoffs/handoff-${await $.clock.now()}.md`
1127      await $.fs.write(path, text + '\n')
1128      text = t(language, 'alerts.readHandoffFile', { path })
1129    }
1130    const folder = await $.session.cwd()
1131    const url = 'claude://code/new?' + new URLSearchParams({ ...(folder ? { folder } : {}), q: text, source: 'services' }).toString()
1132    await openUrl($, url)
1133    await update($, handoff, () => ({ ...value, stage: 'opened' as const }))
1134  } catch (error) {
1135    await report($, 'open new session', error)
1136    await copyHandoff($)
1137    await $.ui.toast(t(language, 'toasts.newSessionFallback'))
1138  }
1139}
1140/**
1141 * Writes a queued handoff when the session is idle. A fork that fails or answers nothing fails the
1142 * handoff: no prompt goes to this chat in its place (the old fallback turn is not kept, 2026-10-24).
1143 */
1144async function driveHandoff($: EngineInterface): Promise<void> {
1145  const language = await read($, lang)
1146  const value = await read($, handoff)
1147  if (value?.stage !== 'writing' || value.text || !await read($, handoffQueued) || await read($, busy)) return
1148  await update($, handoffQueued, () => false)
1149  // The chat this press belongs to. A /clear while the fork runs starts another one, and its note
1150  // must not open a session over it (B11). `run` names the press, because a second press after the
1151  // clear has a fork of its own and this one's answer is not it.
1152  const chat = generation
1153  const run = value.run
1154  const stale = async (): Promise<boolean> => generation !== chat || (await read($, handoff))?.run !== run
1155  /** Drop this press's card, unless a later press has already taken the state over. */
1156  const drop = async (): Promise<void> => {
1157    if ((await read($, handoff))?.run === run) await update($, handoff, () => null)
1158  }
1159  try {
1160    const answer = await fork($, QUICK_PROMPT)
1161    if (await stale()) { await drop(); return }
1162    if (!answer?.isAnswered || !answer.text.trim()) throw new Error(answer && !answer.isAnswered ? answer.reason : 'empty handoff')
1163    await update($, handoff, () => ({ stage: 'writing' as const, text: answer.text, run }))
1164    await moveToNewSession($)
1165  } catch (error) {
1166    // A failure after the chat changed says nothing about this chat: no toast, no failed card.
1167    if (await stale()) { await drop(); return }
1168    await update($, handoff, () => ({ stage: 'failed' as const, run }))
1169    await $.ui.toast(t(language, 'toasts.handoffFailed'))
1170    await report($, 'handoff', error)
1171  }
1172}
1173/** The tidy prompt the last Compact press sent and the main-loop turn it became; null once it settles. */
1174type Tidy = { text: string; note: string; turnId: string | null }
1175let tidy: Tidy | null = null
1176async function compactNow($: EngineInterface, note: string): Promise<void> {
1177  const language = await read($, lang)
1178  await update($, resultCard, () => ({ stage: 'compacting' }))
1179  try {
1180    await $.command.run({ command: 'compact', args: note })
1181    await update($, resultCard, () => ({ stage: 'compacted' }))
1182  } catch (error) {
1183    await update($, resultCard, () => ({ stage: 'failed' as const, detail: t(language, 'alerts.compactFailed') }))
1184    await $.ui.toast(t(language, 'toasts.compactFailed'))
1185    await report($, 'compact command', error)
1186  }
1187}
1188/** The tidy-up did not finish: nothing is compacted, and the card says the chat was left as it was. */
1189async function tidyStopped($: EngineInterface): Promise<void> {
1190  const language = await read($, lang)
1191  await update($, resultCard, () => ({ stage: 'failed' as const, detail: t(language, 'alerts.tidyFailed') }))
1192  await $.ui.toast(t(language, 'toasts.tidyStopped'))
1193}
1194/**
1195 * A Compact press, and the tidy-up it asks for first (2026-10-25): a prompt of this plugin's own, a
1196 * user turn of its own, so the chat says what it has done, what is left and what it decided, and
1197 * updates its handoff or memory files while those are still in the transcript. The prompt and the
1198 * answer stay in the transcript, and the summary is built from them. The turn it becomes is bound at
1199 * `turn.start` and settled at `turn.complete`: only its own end compacts, and one that is stopped
1200 * compacts nothing. A prompt still waiting for that turn when Compact is pressed again (the queue
hooks/settings.ts 364 lines
1import type { Calibration, Domain, DomainRules, Effort, Level, Mode, Rule, Rung, Settings, SettingsChange, Skin, Step, TierTarget } from '../types/index.d.ts'
2
3/** Bump whenever a writer's normalization can lose another format's fields. */
4export const MOD_SETTINGS_SCHEMA_VERSION = 1
5
6export const DOMAINS: readonly Domain[] = ['general', 'design', 'frontend', 'backend', 'infra', 'data', 'test', 'docs', 'research']
7export const LEVELS: readonly Level[] = ['light', 'standard', 'deep']
8export const EFFORTS: readonly Effort[] = ['low', 'medium', 'high', 'xhigh', 'max']
9/** The worker ladder, bottom to top (docs/specs/2026-10-11-worker-ladder.md). */
10export const RUNGS: readonly Rung[] = ['light', 'standard', 'hard', 'plan']
11/** The rung each judged level lands on before kind and confidence move it. */
12export const LEVEL_RUNG: Readonly<Record<Level, Rung>> = { light: 'light', standard: 'standard', deep: 'hard' }
13/** A rung's effort when nothing else says one: a stored rung without one, a migrated pin. */
14export const RUNG_EFFORT: Readonly<Record<Rung, Effort>> = { light: 'low', standard: 'medium', hard: 'high', plan: 'high' }
15
16const claude = (model: string, effort: Effort): Step => ({ target: { agent: 'general-purpose', model }, effort })
17
18export const DEFAULTS: Settings = {
19  effortAuto: true, judge: 'haiku', judgeModel: 'deepseek-v4.1-flash', jevSource: 'typesafe',
20  bias: 0, floor: 'low', ceiling: 'max', agentAuto: 'auto',
21  rules: {
22    // The spec's "Claude + GPT" example; a rung whose worker is missing moves up and says so.
23    // Only the general rule: the four workers replaced the per-field rules (2026-10-12).
24    general: { mode: 'ladder', rungs: {
25      light: [{ target: { agent: 'deepseek-v4-1-flash' }, effort: 'max' }], standard: [{ target: { agent: 'gpt-6-1-sol' }, effort: 'medium' }],
26      hard: [{ target: { agent: 'gpt-6-astra' }, effort: 'high' }], plan: [claude('opus', 'high')],
27    } },
28  },
29  allow: [], allowKnown: [], modes: [], delegation: 'normal',
30  providers: {},
31  fallback: { agent: 'general-purpose', model: 'sonnet' },
32  keepWarm: false, keepWarmHours: 2, keepWarmMinTokens: 30000,
33  compactModel: 'claude-haiku-5-5',
34  swampAlert: false, layout: 'dashboard', appearance: 'auto', skin: 'deep', language: 'auto', hide: ['reason'], extras: [], setupDone: false,
35}
36
37/** The desktop's skins, in the order the panel offers them. */
38export const SKINS: readonly Skin[] = ['deep', 'flat']
39
40/** Band chips that show only when switched on in Look. */
41export const EXTRAS: readonly string[] = ['context', 'limits']
42
43/**
44 * Claude's own models as workers: the built-in general-purpose agent run on the model, `model` its
45 * current id. The key is what the allow-list stores. Mythos is not here: the Agent tool's `model`
46 * takes only sonnet, opus, haiku and fable (Claude Code 2.1.295, read 2026-10-14), so a
47 * general-purpose worker on it would be refused.
48 */
49export const CLAUDE_WORKERS: readonly { name: string; model: string; provider: string; target: TierTarget }[] = [
50  { name: 'general-purpose:haiku', model: 'claude-haiku-5-5', provider: 'anthropic', target: { agent: 'general-purpose', model: 'haiku' } },
51  { name: 'general-purpose:sonnet', model: 'claude-sonnet-5-5', provider: 'anthropic', target: { agent: 'general-purpose', model: 'sonnet' } },
52  { name: 'general-purpose:opus', model: 'claude-opus-5-5', provider: 'anthropic', target: { agent: 'general-purpose', model: 'opus' } },
53  { name: 'general-purpose:fable', model: 'claude-fable-5-1', provider: 'anthropic', target: { agent: 'general-purpose', model: 'fable' } },
54]
55
56/** The allow-list key of a target: the agent's name, or `general-purpose:<model>` for Claude's own. */
57export function candidateKey(target: TierTarget): string {
58  return target.model ? target.agent + ':' + target.model : target.agent
59}
60
61function object(raw: unknown): Record<string, unknown> {
62  return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw as Record<string, unknown> : {}
63}
64function names(raw: unknown): string[] {
65  return Array.isArray(raw) ? [...new Set(raw.filter((v): v is string => typeof v === 'string' && !!v.trim()).map(v => v.trim()))] : []
66}
67function target(raw: unknown, fallback?: TierTarget): TierTarget | undefined {
68  const value = object(raw)
69  const agent = typeof value.agent === 'string' && value.agent.trim() ? value.agent.trim() : fallback?.agent
70  const model = typeof value.model === 'string' && value.model.trim() ? value.model.trim() : fallback?.model
71  return agent ? { agent, ...(model ? { model } : {}) } : undefined
72}
73function calibration(value: Record<string, unknown>): Calibration {
74  const out: Calibration = {}
75  if ([-2, -1, 0, 1, 2].includes(Number(value.effortOffset)) && typeof value.effortOffset === 'number') out.effortOffset = value.effortOffset as NonNullable<Calibration['effortOffset']>
76  for (const field of ['floor', 'ceiling'] as const) if (EFFORTS.includes(value[field] as Effort)) out[field] = value[field] as Effort
77  return out
78}
79function copy<T>(value: T): T {
80  return JSON.parse(JSON.stringify(value)) as T
81}
82function sameTarget(a: TierTarget | undefined, b: TierTarget | undefined): boolean {
83  return !!a && !!b && a.agent === b.agent && a.model === b.model
84}
85/** An effort moved by calibration steps, then held between floor and ceiling (the floor wins). */
86function calibrated(effort: Effort, cal: Calibration): Effort {
87  const min = EFFORTS.indexOf(cal.floor ?? 'low')
88  const max = Math.max(min, EFFORTS.indexOf(cal.ceiling ?? 'max'))
89  const shifted = Math.max(0, Math.min(4, EFFORTS.indexOf(effort) + (cal.effortOffset ?? 0)))
90  return EFFORTS[Math.max(min, Math.min(max, shifted))]!
91}
92/** One effort step up, max staying max. */
93export function effortUp(effort: Effort): Effort {
94  return EFFORTS[Math.min(4, EFFORTS.indexOf(effort) + 1)]!
95}
96function step(raw: unknown, rung: Rung): Step | undefined {
97  const v = object(raw)
98  const chosen = target(v.target)
99  if (!chosen) return undefined
100  // A rung's backup model is dropped on load: the four workers have none (the next one up stands in).
101  return { target: chosen, effort: EFFORTS.includes(v.effort as Effort) ? v.effort as Effort : RUNG_EFFORT[rung] }
102}
103/** The effort a migrated rung starts at: the default ladder's when it runs the same model there. */
104function migratedEffort(rung: Rung, chosen: TierTarget): Effort {
105  const own = DEFAULTS.rules.general.rungs[rung]?.[0]
106  return own && sameTarget(own.target, chosen) ? own.effort : RUNG_EFFORT[rung]
107}
108/**
109 * A pin stored before 2026-10-11 as a ladder: light/standard/deep become Light/Standard/Hard, a
110 * missing level takes the nearest one above (as the pin climbed) or else below, each rung's effort
111 * is its default calibrated as the pin was, and Plan is Hard's model one effort higher.
112 */
113export function ladderFromPin(targets: Partial<Record<Level, TierTarget>>, cal: Calibration): Rule {
114  const known = LEVELS.filter(level => targets[level])
115  if (!known.length) return copy(DEFAULTS.rules.general)
116  const rungs: Partial<Record<Rung, Step>> = {}
117  LEVELS.forEach((level, at) => {
118    const above = LEVELS.slice(at).find(l => targets[l])
119    const chosen = targets[above ?? [...LEVELS.slice(0, at)].reverse().find(l => targets[l])!]!
120    const rung = LEVEL_RUNG[level]
121    rungs[rung] = { target: { ...chosen }, effort: calibrated(migratedEffort(rung, chosen), cal) }
122  })
123  rungs.plan = { target: { ...rungs.hard!.target }, effort: effortUp(rungs.hard!.effort) }
124  return { mode: 'ladder', rungs: ladderRungs(rungs) }
125}
126/** Single steps from older saves become one-item lists; malformed items are dropped in place. */
127function ladderRungs(raw: unknown): Rule['rungs'] {
128  const source = object(raw)
129  const rungs: Rule['rungs'] = {}
130  for (const rung of RUNGS) {
131    const items = Array.isArray(source[rung]) ? source[rung] : [source[rung]]
132    const parsed = items.flatMap(item => { const value = step(item, rung); return value ? [value] : [] })
133    if (parsed.length) rungs[rung] = parsed
134  }
135  return rungs
136}
137/**
138 * A domain ladder folded into two levels: light work is the light and standard rungs, heavy work
139 * hard and plan, by difficulty as the owner sets the two rows (2026-10-24). From 2026-10-22 to
140 * 10-24 standard sat in the heavy row, because the worker judge read ordinary design as standard
141 * and the owner wanted design on Opus; the judge is gone, and design now names Opus itself with a
142 * written rule (memory design-work-opus-only), so a standard UI or backend task no longer runs on
143 * the heavy model. Light reads its own rung, else standard's; heavy reads plan, else hard, else
144 * standard, else light, so one filled row still runs everything and a ladder stored by the old
145 * split reads right. The general ladder keeps its four rungs.
146 */
147export function twoLevelRungs(rungs: Rule['rungs']): Rule['rungs'] {
148  const out: Rule['rungs'] = {}
149  const light = rungs.light?.length ? rungs.light : rungs.standard
150  const heavy = [rungs.plan, rungs.hard, rungs.standard, rungs.light].find(list => list?.length)
151  if (light?.length) { out.light = copy(light); out.standard = copy(light) }
152  if (heavy?.length) { out.hard = copy(heavy); out.plan = copy(heavy) }
153  return out
154}
155/**
156 * The one rule left, the general ladder (the four workers). A ladder keeps its rungs; a pin from
157 * before the ladder becomes one; Auto (experimental, removed 2026-10-12) becomes a ladder with no
158 * rungs set, which the router fills from the ticked models (`fillLadder`). Field rules are gone.
159 */
160function generalRule(raw: unknown): Rule {
161  const v = object(raw)
162  if (v.mode === 'ladder') return { mode: 'ladder', rungs: ladderRungs(v.rungs) }
163  if (v.mode === 'auto') return { mode: 'ladder', rungs: {} }
164  if (v.mode === 'pin') {
165    const source = object(v.targets)
166    const targets: Partial<Record<Level, TierTarget>> = {}
167    for (const level of LEVELS) { const parsed = target(source[level]); if (parsed) targets[level] = parsed }
168    return ladderFromPin(targets, calibration(v))
169  }
170  return copy(DEFAULTS.rules.general)
171}
172
173/** Only optional domain ladders, never the retired per-field pin/Auto rules. */
174function domainRules(raw: unknown): DomainRules | undefined {
175  const source = object(raw)
176  const out: DomainRules = {}
177  for (const key of ['ui', 'backend'] as const) {
178    // A domain ladder has two levels, so its four rungs are folded on the way in.
179    if (object(source[key]).mode === 'ladder') out[key] = { mode: 'ladder', rungs: twoLevelRungs(generalRule(source[key]).rungs) }
180  }
181  return Object.keys(out).length ? out : undefined
182}
183
184type Worker = { name: string; provider: string }
185
186/**
187 * Auto's allow-list names worker agents. Settings saved before 2026-10-10 named providers there;
188 * with the worker list known, a provider name becomes that provider's workers (names it does not
189 * know are kept: a worker may be missing only for now).
190 */
191export function migrateAllow(allow: readonly string[], workers: readonly Worker[]): string[] {
192  const agents = new Set(workers.map(w => w.name))
193  return [...new Set(allow.flatMap(entry => agents.has(entry) || !workers.some(w => w.provider === entry) ? [entry] : workers.filter(w => w.provider === entry).map(w => w.name)))]
194}
195
196/** The workers switched on by an allow-list; empty means every worker. A worker that did not exist when the list was last written (absent from `known`) counts as on. */
197export function allowedWorkers(allow: readonly string[], workers: readonly Worker[], known: readonly string[] = []): string[] {
198  if (!allow.length) return workers.map(w => w.name)
199  const on = new Set(migrateAllow(allow, workers))
200  return workers.filter(w => on.has(w.name) || known.length > 0 && !known.includes(w.name)).map(w => w.name)
201}
202
203/** Switches one worker; every worker on again is stored as [], and the last one cannot go off. `known` is the allow-list keys the writer knew. */
204export function toggleAllow(allow: readonly string[], name: string, workers: readonly Worker[], known: readonly string[] = []): string[] {
205  const on = allowedWorkers(allow, workers, known)
206  const next = on.includes(name) ? on.filter(n => n !== name) : workers.filter(w => w.name === name || on.includes(w.name)).map(w => w.name)
207  if (!next.length) return [...allow]
208  return next.length === workers.length ? [] : next
209}
210
211/**
212 * Whether a stored model is ticked: its key (an agent name, or `general-purpose:<model>`) or, for
213 * settings from before 2026-10-10, its provider is listed; an empty list ticks every model. A key
214 * absent from a non-empty `known` list (a worker added after the list was last written) ticks on.
215 */
216export function isAllowed(key: string, provider: string, allow: readonly string[], known: readonly string[] = []): boolean {
217  return !allow.length || allow.includes(key) || allow.includes(provider) || known.length > 0 && !known.includes(key)
218}
219
220/** The design ladder every save stored until 2026-10-12: Claude, Sonnet then Opus. */
221const RETIRED_DESIGN = JSON.stringify([claude('sonnet', 'medium'), claude('sonnet', 'high'), claude('opus', 'high'), claude('opus', 'high')].map(s => [s.target.agent, s.target.model, s.effort]))
222
223/**
224 * Whether stored settings still carry what the four workers replaced: Auto (experimental), or a
225 * field rule that is not the design ladder every save used to store. The dashboard says so once.
226 */
227export function hadRetiredRouting(raw: unknown): boolean {
228  const rules = object(object(raw).rules)
229  if (object(rules.general).mode === 'auto') return true
230  return DOMAINS.some(domain => {
231    if (domain === 'general') return false
232    const stored = object(rules[domain])
233    if (stored.mode === undefined || stored.mode === 'inherit') return false
234    if (domain !== 'design' || stored.mode !== 'ladder') return true
235    const rungs = ladderRungs(stored.rungs)
236    return JSON.stringify(RUNGS.map(rung => { const s = rungs[rung]?.[0]; return s ? [s.target.agent, s.target.model, s.effort] : null })) !== RETIRED_DESIGN
237  })
238}
239
240/** How long a mode's name may be: it shows in the band. */
241export const MODE_NAME_MAX = 40
242/** How many modes are kept. */
243export const MODES_MAX = 20
244
245/** How long a mode's reset provider name may be. */
246const PROVIDER_NAME_MAX = 64
247
248/**
249 * A mode's end: a time, one provider's next quota reset, or none. Until 2026-10-12 `'reset'` meant
250 * any used provider's; it becomes the first that could have offered it, ChatGPT then Claude. Settings
251 * do not carry a worker's provider, and ChatGPT is the only worker provider with a known reset, so
252 * any worker that is not Claude's own stands for ChatGPT.
253 */
254function modeUntil(raw: unknown, rungs: Rule['rungs']): Mode['until'] {
255  if (typeof raw === 'number') return Number.isFinite(raw) && raw > 0 ? raw : 'none'
256  if (raw === 'reset') return { reset: Object.values(rungs).some(steps => steps?.some(step => step.target.agent !== 'general-purpose')) ? 'chatgpt' : 'anthropic' }
257  const reset = object(raw).reset
258  return typeof reset === 'string' && reset.trim() ? { reset: reset.trim().slice(0, PROVIDER_NAME_MAX) } : 'none'
259}
260
261/**
262 * Saved worker sets. Old prefer/avoid modes copy the base ladder on load, dropping their policy.
263 * Every entry owns its lists: later base edits cannot mutate a saved mode.
264 */
265export function normalizeModes(raw: unknown, base: Rule['rungs'] = DEFAULTS.rules.general.rungs): Mode[] {
266  if (!Array.isArray(raw)) return []
267  const out: Mode[] = []
268  for (const entry of raw) {
269    const v = object(entry)
270    const id = typeof v.id === 'string' ? v.id.trim().slice(0, 64) : ''
271    const name = typeof v.name === 'string' ? v.name.trim().slice(0, MODE_NAME_MAX) : ''
272    if (!id || !name || out.some(m => m.id === id)) continue
273    const rungs = ladderRungs(v.rungs === undefined ? base : v.rungs)
274    const domains = domainRules(v.domainRules)
275    out.push({ id, name, rungs, ...(domains ? { domainRules: domains } : {}), delegation: v.delegation === 'eager' ? 'eager' : 'normal', until: modeUntil(v.until, rungs) })
276    if (out.length === MODES_MAX) break
277  }
278  return out
279}
280
281/** The general pin every install had before the ladder: what stored `tiers` filled in. */
282const LEGACY_GENERAL: Readonly<Record<Level, TierTarget>> = { light: { agent: 'deepseek-v4-1-flash' }, standard: { agent: 'gpt-6-1-sol' }, deep: { agent: 'gpt-6-astra' } }
283
284/**
285 * Persisted settings may be old; migrate tiers and pins once and never alias nested default data.
286 * Only the general ladder survives: Auto becomes a ladder with no rungs set (its candidates become
287 * the ticked models); field rules and Auto's own fields (preference, autoFloors, autoTieBand) are
288 * dropped. With `workers`, provider names in an allow-list become those providers' workers.
289 */
290export function normalizeSettings(raw: unknown, workers?: readonly Worker[]): Settings {
291  const value = object(raw)
292  const stored = object(value.rules)
293  const rules: Settings['rules'] = { general: generalRule(stored.general) }
294  const old = object(value.tiers)
295  if (!Object.hasOwn(stored, 'general') && Object.keys(old).length) {
296    const targets: Partial<Record<Level, TierTarget>> = copy(LEGACY_GENERAL)
297    for (const level of LEVELS) { const parsed = target(old[level]); if (parsed) targets[level] = parsed }
298    rules.general = ladderFromPin(targets, {})
299  }
300  const ticked = names(Array.isArray(value.allow) ? value.allow : object(stored.general).mode === 'auto' ? object(stored.general).allow : [])
301  const savedKnown = names(value.allowKnown)
302  const result: Settings = { ...DEFAULTS, rules, allow: workers?.length ? migrateAllow(ticked, workers) : ticked, allowKnown: savedKnown, providers: {}, hide: [...DEFAULTS.hide], extras: [...DEFAULTS.extras], fallback: { ...DEFAULTS.fallback } }
303  for (const [name, enabled] of Object.entries(object(value.providers))) if (typeof enabled === 'boolean') result.providers[name] = enabled
304  for (const key of ['effortAuto', 'keepWarm', 'setupDone', 'swampAlert'] as const) if (typeof value[key] === 'boolean') result[key] = value[key]
305  if (Array.isArray(value.extras)) result.extras = [...new Set(value.extras.filter((part): part is string => typeof part === 'string' && EXTRAS.includes(part)))]
306  const choices = {
307    judge: ['haiku', 'jev', 'model'], jevSource: ['typesafe', 'zen'], bias: [-2, -1, 0, 1, 2], floor: EFFORTS,
308    delegation: ['normal', 'eager'],
309    ceiling: EFFORTS, agentAuto: ['off', 'auto', 'all'], keepWarmHours: [1, 2, 4, 8],
310    layout: ['dashboard', 'minimal'],
311    appearance: ['auto', 'dark', 'light'], skin: SKINS, language: ['auto', 'ko', 'en', 'zh', 'ja', 'es', 'pt'],
312  } as const
313  for (const key of Object.keys(choices) as (keyof typeof choices)[]) if ((choices[key] as readonly unknown[]).includes(value[key])) Object.assign(result, { [key]: value[key] })
314  if (typeof value.judgeModel === 'string' && value.judgeModel.trim()) result.judgeModel = value.judgeModel.trim()
315  if (typeof value.keepWarmMinTokens === 'number' && Number.isFinite(value.keepWarmMinTokens) && value.keepWarmMinTokens >= 0) result.keepWarmMinTokens = value.keepWarmMinTokens
316  // `compactWith: 'haiku' | 'session'` was the whole choice. A stored model id wins; otherwise the
317  // old choice (or anything unknown) reads as Haiku, the default it always meant.
318  if (typeof value.compactModel === 'string' && value.compactModel.trim()) result.compactModel = value.compactModel.trim()
319  else if (value.compactWith === 'session') result.compactModel = 'session'
320  if (Array.isArray(value.hide)) result.hide = [...new Set(value.hide.filter((part): part is string => typeof part === 'string' && ['timer', 'reason', 'route', 'limits'].includes(part)))]
321  result.fallback = target(value.fallback, DEFAULTS.fallback)!
322  const domains = domainRules(value.domainRules)
323  if (domains) result.domainRules = domains
324  result.modes = normalizeModes(value.modes, rules.general.rungs)
325  // An active mode must be one of the modes; its start time stays only with it.
326  if (typeof value.activeMode === 'string' && result.modes.some(m => m.id === value.activeMode)) {
327    result.activeMode = value.activeMode
328    if (typeof value.activeSince === 'number' && Number.isFinite(value.activeSince) && value.activeSince > 0) result.activeSince = value.activeSince
329  }
330  return result
331}
332
333/** Preserve unrelated remote edits, including sibling domains and provider switches. */
334export function settingsChanges(before: Settings, after: Settings): SettingsChange[] {
335  function diff(a: unknown, b: unknown, path: string[]): SettingsChange[] {
336    if (JSON.stringify(a) === JSON.stringify(b)) return []
337    if (b === undefined) return [{ path, remove: true }]
338    if (a && b && typeof a === 'object' && typeof b === 'object' && !Array.isArray(a) && !Array.isArray(b)) {
339      const left = object(a), right = object(b)
340      // Changing a discriminated rule replaces it, rather than retaining the old mode's fields.
341      if (left.mode === right.mode) return [...new Set([...Object.keys(left), ...Object.keys(right)])].flatMap(key => diff(left[key], right[key], [...path, key]))
342    }
343    return [{ path, value: b }]
344  }
345  return diff(before, after, [])
346}
347
348export function applySettingsChanges(base: Settings, changes: readonly SettingsChange[]): Settings {
349  const result = object(normalizeSettings(base))
350  for (const change of changes) {
351    let parent = result
352    for (const key of change.path.slice(0, -1)) {
353      const child = object(parent[key])
354      parent[key] = child
355      parent = child
356    }
357    const key = change.path.at(-1)
358    if (key === undefined) continue
359    if (change.remove) delete parent[key]
360    else parent[key] = change.value
361  }
362  return normalizeSettings(result)
363}
364
hooks/ladder.ts 175 lines
1// The four workers (docs/specs/2026-10-12-worker-tiers.md): which rung a verdict lands on, and the
2// fill that gives every rung a model from the ticked, connected ones. Pure, with type-only imports,
3// so the router fills settings with the same rule the mod uses.
4
5import type { Billing, Effort, LadderChoice, Preset, PresetId, Rung, Rungs, Step, WorkerVerdict } from '../types/index.d.ts'
6import { CLAUDE_WORKERS, EFFORTS, LEVEL_RUNG, RUNGS, candidateKey, isAllowed } from './settings.ts'
7
8/** Below this the judge is unsure enough that a task takes the next rung. */
9export const SURE_ENOUGH = 0.5
10
11/**
12 * Doing work lands on Low, Medium and High by level. Planning — a deliverable that is a decision,
13 * design, strategy or verdict — is the Max worker's job from standard up (a business strategy
14 * judged "standard plan" went to the Medium worker before, 2026-10-12 pick log); a light plan
15 * (rename a section of a spec) is still light work.
16 * An unsure verdict moves up one rung (Low → Medium → High); High and Plan stay, so only a
17 * planning verdict ever reaches Plan.
18 */
19export function rungOf(verdict: Pick<WorkerVerdict, 'level' | 'kind' | 'sure'>): Rung {
20  const rung = verdict.kind === 'plan' && verdict.level !== 'light' ? 'plan' : LEVEL_RUNG[verdict.level]
21  if (verdict.sure === undefined || !(verdict.sure < SURE_ENOUGH)) return rung
22  return rung === 'light' ? 'standard' : rung === 'standard' ? 'hard' : rung
23}
24
25/** The rung above, none above Plan. */
26export function rungAbove(rung: Rung): Rung | undefined {
27  return RUNGS[RUNGS.indexOf(rung) + 1]
28}
29
30/**
31 * The nearest effort a model takes, as the router clamps one (compat.ts clampEffort): ties go up,
32 * an unknown ladder keeps the effort.
33 */
34export function nearestEffort(effort: Effort, ladder: readonly string[]): Effort {
35  const known = ladder.filter((value): value is Effort => EFFORTS.includes(value as Effort))
36  if (!known.length || known.includes(effort)) return effort
37  const at = EFFORTS.indexOf(effort)
38  return known.reduce((best, next) => {
39    const d = Math.abs(EFFORTS.indexOf(next) - at)
40    const bd = Math.abs(EFFORTS.indexOf(best) - at)
41    return d < bd || (d === bd && EFFORTS.indexOf(next) > EFFORTS.indexOf(best)) ? next : best
42  })
43}
44
45/** How a provider is paid for, from its configuration (type, auth, preset, address). */
46export function billingOf(provider: { type?: string; auth?: string; preset?: string; url?: string }, model?: string): Billing {
47  if (model && /(?::|-)free$/i.test(model)) return 'free'
48  if (provider.type === 'chatgpt') return 'subscription'
49  if (provider.type === 'anthropic') return provider.auth === 'api-key' ? 'payg' : 'subscription'
50  if (provider.type === 'google') return provider.auth === 'antigravity' ? 'subscription' : 'payg'
51  if (provider.preset === 'opencode-go') return 'subscription'
52  if (provider.preset === 'ollama' || provider.preset === 'lmstudio') return 'free'
53  // A named hosted service is paid for wherever it is reached through; only a hand-entered local server is free.
54  if (provider.preset) return 'payg'
55  if (provider.url) {
56    try {
57      const host = new URL(provider.url).hostname
58      if (host === 'localhost' || host === '127.0.0.1' || host === '[::1]' || host.endsWith('.localhost')) return 'free'
59    } catch { /* not an address: paid like any other API */ }
60  }
61  return 'payg'
62}
63
64/** A family's newest model: gpt-6.1-sol over gpt-6-sol. */
65function newest(choices: readonly LadderChoice[], family: RegExp): LadderChoice | undefined {
66  const version = (model: string): number[] => (/(\d+(?:[.-]\d+)*)/.exec(model)?.[1] ?? '0').split(/[.-]/).map(Number)
67  const later = (a: number[], b: number[]): number => { for (let i = 0; i < Math.max(a.length, b.length); i++) { const d = (b[i] ?? 0) - (a[i] ?? 0); if (d) return d } return 0 }
68  return choices.filter(c => family.test(c.model) && !c.target.model).sort((a, b) => later(version(a.model), version(b.model)) || a.model.localeCompare(b.model))[0]
69}
70
71/** The cheapest model paid by the token or free: free first, then by measured cost; unmeasured last. */
72export function cheapest(choices: readonly LadderChoice[]): LadderChoice | undefined {
73  const cost = (c: LadderChoice): number => c.billing === 'free' ? 0 : c.cost ?? Number.POSITIVE_INFINITY
74  return choices.filter(c => (c.billing === 'payg' || c.billing === 'free') && !c.target.model)
75    .sort((a, b) => cost(a) - cost(b) || a.model.localeCompare(b.model))[0]
76}
77
78type Want = { pick: (choices: readonly LadderChoice[]) => LadderChoice | undefined; effort: Effort }
79
80const claudeModel = (alias: string) => (choices: readonly LadderChoice[]) => choices.find(c => c.target.agent === 'general-purpose' && c.target.model === alias)
81const family = (pattern: RegExp) => (choices: readonly LadderChoice[]) => newest(choices, pattern)
82const LUNA = family(/\bluna\b/i)
83const SOL = family(/\bsol\b/i)
84const ASTRA = family(/\bastra\b/i)
85const HAIKU = claudeModel('haiku')
86const SONNET = claudeModel('sonnet')
87const OPUS = claudeModel('opus')
88
89/**
90 * The fill rule's wishes (a preset's, by name; only `claudeGpt` is used): each rung's in order: the first is what the preset names, the rest what stands in
91 * when it is not connected (the nearest choice, a GPT model's Claude counterpart).
92 */
93const PRESETS: Readonly<Record<PresetId, Readonly<Record<Rung, readonly Want[]>>>> = {
94  claude: {
95    light: [{ pick: HAIKU, effort: 'low' }], standard: [{ pick: SONNET, effort: 'medium' }],
96    hard: [{ pick: OPUS, effort: 'high' }], plan: [{ pick: OPUS, effort: 'high' }],
97  },
98  claudeGpt: {
99    light: [{ pick: cheapest, effort: 'max' }, { pick: LUNA, effort: 'low' }, { pick: HAIKU, effort: 'low' }],
100    standard: [{ pick: SOL, effort: 'medium' }, { pick: SONNET, effort: 'medium' }],
101    hard: [{ pick: ASTRA, effort: 'high' }, { pick: OPUS, effort: 'high' }],
102    plan: [{ pick: OPUS, effort: 'high' }],
103  },
104  gpt: {
105    light: [{ pick: LUNA, effort: 'low' }, { pick: HAIKU, effort: 'low' }],
106    standard: [{ pick: SOL, effort: 'medium' }, { pick: SONNET, effort: 'medium' }],
107    hard: [{ pick: ASTRA, effort: 'high' }, { pick: OPUS, effort: 'high' }],
108    plan: [{ pick: ASTRA, effort: 'xhigh' }, { pick: OPUS, effort: 'high' }],
109  },
110  cheap: {
111    light: [{ pick: cheapest, effort: 'high' }, { pick: LUNA, effort: 'low' }, { pick: HAIKU, effort: 'low' }],
112    standard: [{ pick: cheapest, effort: 'max' }, { pick: LUNA, effort: 'medium' }, { pick: HAIKU, effort: 'medium' }],
113    hard: [{ pick: cheapest, effort: 'max' }, { pick: LUNA, effort: 'high' }, { pick: SONNET, effort: 'medium' }],
114    plan: [{ pick: SONNET, effort: 'high' }],
115  },
116}
117
118/** Claude's own models as rung choices: always there, since the session itself runs on Claude. */
119export function claudeChoices(efforts: readonly string[]): LadderChoice[] {
120  const ladder = efforts.filter((e): e is Effort => EFFORTS.includes(e as Effort))
121  return CLAUDE_WORKERS.map(w => ({ target: { ...w.target }, model: w.model, provider: w.provider, billing: 'subscription' as const, efforts: ladder }))
122}
123
124/**
125 * A preset's rule applied to the connected, ticked models: each rung takes its first wish that is
126 * there, at that wish's effort moved to the nearest the model takes. A rung that had to take a
127 * later wish is listed in `substituted`.
128 */
129export function preset(id: PresetId, choices: readonly LadderChoice[]): Preset {
130  const rungs = {} as Record<Rung, Step>
131  const substituted: Rung[] = []
132  for (const rung of RUNGS) {
133    const wants = PRESETS[id][rung]
134    let filled = false
135    for (const [at, want] of wants.entries()) {
136      const choice = want.pick(choices)
137      if (!choice) continue
138      rungs[rung] = { target: { ...choice.target }, effort: nearestEffort(want.effort, choice.efforts) }
139      if (at > 0) substituted.push(rung)
140      filled = true
141      break
142    }
143    // Claude is always there, so only a choice list without it lands here: the session model.
144    if (!filled) { rungs[rung] = { target: { agent: 'general-purpose' }, effort: wants[0]!.effort }; substituted.push(rung) }
145  }
146  return { rungs, substituted }
147}
148
149/** The choices a person ticked; an empty list ticks every one, and a key absent from `known` ticks on too. */
150export function tickedChoices(choices: readonly LadderChoice[], allow: readonly string[], known: readonly string[] = []): LadderChoice[] {
151  return choices.filter(choice => isAllowed(candidateKey(choice.target), choice.provider, allow, known))
152}
153
154/** Only empty lists need filling; unticked entries stay in order and are skipped at dispatch. */
155export function ladderNeedsFill(rungs: Rungs, _allow: readonly string[] = []): boolean {
156  return RUNGS.some(rung => !rungs[rung]?.length)
157}
158
159/**
160 * Fill empty lists from the ticked, connected choices. Existing ordered lists are never rewritten
161 * for temporary availability or shared allow-list changes; dispatch explains each skipped entry.
162 */
163export function fillLadder(rungs: Rungs, allow: readonly string[], choices: readonly LadderChoice[], known: readonly string[] = []): { rungs: Record<Rung, Step[]>; filled: Rung[] } {
164  const pick = preset('claudeGpt', tickedChoices(choices, allow, known))
165  const out = {} as Record<Rung, Step[]>
166  const filled: Rung[] = []
167  for (const rung of RUNGS) {
168    const own = rungs[rung]
169    if (own?.length) { out[rung] = own; continue }
170    out[rung] = [pick.rungs[rung]]
171    filled.push(rung)
172  }
173  return { rungs: out, filled }
174}
175
hooks/i18n.ts 3468 lines
1// Pure display strings. Model-facing prompts intentionally stay in English.
2import type { Lang } from '../types'
3export type { Lang } from '../types'
4
5const EN = {
6  // Band (including shared display labels and accessibility text).
7  'band.brand': 'ClaudeRipple',
8  'band.effort': 'Effort',
9  'band.model': 'Model',
10  'band.auto': 'Auto',
11  'band.manual': 'Manual',
12  'band.paused': 'Paused',
13  'band.off': 'Off',
14  'band.on': 'On',
15  'band.autoOff': 'Auto off',
16  'band.autoPaused': 'auto paused',
17  'band.deciding': 'Deciding…',
18  'band.decidingText': '◌ deciding…',
19  'band.low': 'Low',
20  'band.medium': 'Medium',
21  'band.high': 'High',
22  'band.xhigh': 'X-High',
23  'band.max': 'Max',
24  'band.pausedHint': 'Auto pauses on this model: effort changes there are not known to keep the cache.',
25  'band.offHint': 'Auto is off; the effort is yours.',
26  'band.decidingHint': 'The judge is picking the effort for this prompt.',
27  'band.effortTitle': 'Effort {value}{hint} · Click to pick an effort',
28  'band.effortAlt': 'Effort {value} ({mode}){why}',
29  'band.context': 'Context',
30  'band.contextAlt': 'Context {value} of {window} ({tokens} tokens)',
31  'band.cache': 'Cache',
32  'band.cacheWarm': 'Cache · Warm',
33  'band.cacheStopped': 'Cache · Warm stopped',
34  'band.cold': 'cold',
35  'band.cacheTip': 'Prompt cache {state}{warm}',
36  'band.warmFor': 'warm for {time}',
37  'band.expired': 'expired',
38  'band.warmStoppedTip': ' · keep-warm stopped: {reason}',
39  'band.warmOnTip': ' · keep-warm on, {count} pings',
40  'band.noReply': 'No reply yet',
41  'band.cacheAlt': 'Cache {state}{warm}',
42  'band.timeLeft': '{time} left',
43  'band.unknown': 'unknown',
44  'band.keepWarmAlt': ', keep warm on{count}',
45  'band.limitCaption': '{window} limit{save}',
46  'band.saveCaption': ' · SAVE',
47  'band.limitAlt': '{window} limit {value}{reset}',
48  'band.limitsTip': '{provider} {window} {value}{reset}',
49  'band.fiveHour': '5-hour',
50  'band.weekly': 'Weekly',
51  'band.resetting': 'resetting',
52  'band.resetsIn': 'resets in {time}',
53  'band.resetsAt': 'resets {time}',
54  'band.resetIn': 'in {time}',
55  'band.resetDay': '{day} {time}',
56  'band.router': 'Router',
57  'band.routerAlt': 'Router: {value}',
58  'band.resentCaption': 'RESENT · {status}',
59  'band.failedCaption': 'FAILED · {status}',
60  'band.lastRoute': 'LAST ROUTE',
61  'band.logHint': 'Click for the request log',
62  'band.limitsOpen': 'Click for each window\'s share and reset',
63  'band.routeAlt': 'Last route: {model} via {provider}{effort}{cache}, {time}{status}',
64  'band.routeCache': ', cache {percent}%',
65  'band.routeResent': ', resent {status}',
66  'band.routeFailed': ', failed {status}',
67  'band.warm': 'Warm',
68  'band.handoff': 'Handoff',
69  'band.compact': 'Compact',
70  'band.clear': 'Clear',
71  'band.compactAlt': 'Compact — summarise the conversation to free context',
72  'band.compactedTimes': 'compacted {count}×',
73  'band.clearAlt': 'New start (/clear) — clear the conversation and start fresh',
74  'band.log': 'Log',
75  'band.agents': 'Agents',
76  'band.settings': 'Settings',
77  'band.effortShort': 'Effort',
78  'band.hit': 'hit {percent}%',
79  'band.effortAutoAlt': 'Effort Auto {state}',
80  'band.warmAlt': 'Keep cache warm {state}',
81  'band.warmHere': 'this chat only; new chats follow Settings',
82  'band.closeLog': 'Close the request log',
83  'band.openLog': 'Open the request log',
84  'band.agentsAlt': 'Agents: {count} running',
85  'band.settingsAlt': 'Ripple settings',
86  'band.warmStopped': 'warm stopped',
87  'band.warmText': '≈warm',
88  'band.save': 'save',
89  'band.resent': '{status} resent',
90  'band.phoneQueue': 'Phone queue {count}',
91  'band.phoneQueueWhen': 'goes when this turn ends',
92  'band.cachePercent': 'cache {percent}%',
93  'band.closeLogText': 'Close log',
94  'band.footerPaused': ' (paused)',
95  'band.footerOff': ' (auto off)',
96  'band.footerManual': ' (manual)',
97  'band.footerContext': 'ctx {percent}%',
98  'band.routerRestart': 'ClaudeRipple: restart the router to show routes here',
99  'band.routerDown': 'ClaudeRipple: router not answering',
100  // Alerts.
101  'alerts.coldTitle': 'The cache went cold',
102  'alerts.coldBody': 'It sat {minutes} min, so the next prompt re-reads all {tokens} tokens at full price.',
103  'alerts.keptTitle': 'Cache kept warm while you were away',
104  'alerts.keptBody': '{pings} ping(s) held {tokens} tokens in cache, so your next prompt reads them at the cached rate. {minutes} min left.',
105  'alerts.gotIt': 'Got it',
106  'alerts.swampTitle': 'Context {percent}% full',
107  'alerts.swampBody': '{tokens} tokens ride along with every prompt: slower, dearer, blurrier.',
108  'alerts.hotTitle': '{window} limit at {percent}%',
109  'alerts.saveOnBody': 'Save mode is on: Auto stays at medium or below until the reset.',
110  'alerts.saveBody': 'Save mode holds Auto at medium or below until the reset.',
111  'alerts.saveOff': 'Turn save mode off',
112  'alerts.save': 'Save mode',
113  'alerts.notNow': 'Not now',
114  'alerts.judgeTitle': 'The effort judge is not answering',
115  'alerts.judgeNetworkTitle': 'The connection is unsteady; Haiku is judging for now',
116  'alerts.routerModel': 'The router model',
117  'alerts.judgeBody': '{judge}: {reason}. {fallback}',
118  'alerts.keepEffort': 'The current effort stays meanwhile.',
119  'alerts.askHaiku': 'Haiku judges meanwhile.',
120  'alerts.openSettings': 'Open settings',
121  'alerts.compactTitle': 'Compact this chat',
122  'alerts.compactBody': 'Say what the summary must keep, or leave it to the summary.',
123  'alerts.cancel': 'Cancel',
124  'alerts.dismiss': 'Dismiss',
125  'alerts.handoffTitle': 'Hand off to a fresh chat',
126  'alerts.handingOff': 'Handing off…',
127  'alerts.quickProgress': 'Writing a summary a fresh chat can resume from.',
128  'alerts.handoffDone': 'Handoff done',
129  'alerts.summaryReady': 'The summary is ready.',
130  'alerts.copyAgain': 'Copy again',
131  'alerts.compacting': 'Compacting…',
132  'alerts.compactingBody': 'Summarizing the chat; it continues from the summary.',
133  'alerts.compacted': 'Compacted',
134  'alerts.compactedBody': 'The chat continues from the summary.',
135  'alerts.failed': 'That did not finish',
136  'alerts.unchanged': 'Nothing was changed.',
137  'alerts.keep': 'Keep',
138  'alerts.keepPlaceholder': 'decisions, open questions, file names… (optional)',
139  'alerts.compactSubmit': 'compact',
140  'alerts.demoDown': 'Jev out of credits (demo)',
141  'alerts.openedBody': 'A new session opened with the handoff filled in: press Enter there to go on.',
142  'alerts.readHandoffFile': 'Read the handoff in {path} and continue from it.',
143  'alerts.copied': 'The resume note was copied; this chat was kept.',
144  'alerts.compactFailed': 'Compaction did not finish.',
145  'alerts.tidyFirst': 'Tidy up first: {state}',
146  'alerts.tidying': 'Tidying up…',
147  'alerts.tidyingBody': 'The chat is finishing what the summary would otherwise lose; it is compacted as soon as that turn ends.',
148  'alerts.tidyFailed': 'The tidy-up turn did not finish, so the chat was not compacted. Nothing changed.',
149  'alerts.tidyPrompt': 'The chat is about to be compacted. Do what is needed so the work can go on after the summary: say what you have done so far and what is left, note the decisions you made, and update any handoff document or memory file.',
150  'alerts.clearTitle': 'Start this conversation over?',
151  'alerts.clearBody': 'The conversation\'s context is emptied; a fresh chat starts with nothing.',
152  'alerts.clearGo': 'Start over',
153  // Settings.
154  'settings.effortBlurb': 'How Auto picks the effort for each prompt you send.',
155  'settings.workers': 'Workers',
156  'settings.mode': 'Mode',
157  'settings.modeNone': 'Base',
158  'band.delegationPin': 'Pinned: {name}',
159  'band.releasePin': 'Unpin',
160  'band.pinSaid': '“{said}” pinned it',
161  'band.pinKept': 'kept until this session ends',
162  'toasts.delegationPinned': 'Delegation pinned for this session: {name}.',
163  'toasts.delegationUnpinned': 'Delegation unpinned.',
164  'band.mode': 'Mode',
165  'band.modeTip': 'Mode “{name}” is on: the workers follow it. Change it in quick settings.',
166  'settings.workersBlurb': 'Which agent runs each kind of delegated task.',
167  'settings.judge': 'Judge',
168  'settings.judgeBlurb': 'Who decides: effort for prompts, tier for tasks.',
169  'settings.cacheBlurb': 'Keep the prompt cache warm while you step away.',
170  'settings.look': 'Look',
171  'settings.lookBlurb': 'What the band shows and how.',
172  'settings.light': 'Light',
173  'settings.lightBlurb': 'chores, repetition, lookups',
174  'settings.standard': 'Standard',
175  'settings.standardBlurb': 'designed builds, research, review',
176  'settings.deep': 'Deep',
177  'settings.deepBlurb': 'careful, high-stakes, hard reasoning',
178  'settings.design': 'Design',
179  'settings.designBlurb': 'UI, visual, brand',
180  'settings.tierAlt': '{name} tier',
181  'settings.biasAlt': 'Bias {value}{selected}',
182  'settings.selected': ' (selected)',
183  'settings.onSuffix': ' (on)',
184  'settings.offSuffix': ' (off)',
185  'settings.mixedSuffix': ' (some on)',
186  'settings.cheaper': 'Cheaper',
187  'settings.smarter': 'Smarter',
188  'settings.autoHint': 'picks per prompt; your own pick turns it off',
189  'settings.lean': 'Lean',
190  'settings.leanHint': 'tips close calls only',
191  'settings.floor': 'Never below',
192  'settings.ceiling': 'Never above',
193  'settings.floorWins': 'below the floor: the floor wins',
194  'settings.unavailable': ' (unavailable)',
195  'settings.takesOver': 'Takes over',
196  'settings.autoAgent': 'ripple:auto',
197  'settings.allSpawns': 'All spawns',
198  'settings.fallback': 'Fallback',
199  'settings.fallbackHint': 'when a tier’s provider is out of quota',
200  'settings.haiku': 'Haiku',
201  'settings.jev': 'Jev',
202  'settings.routerModel': 'Router model',
203  'settings.haikuHint': 'Haiku 5.5 on your Claude login · about a second a prompt',
204  'settings.keyEnv': 'from TYPESAFE_API_KEY',
205  'settings.keyFile': 'saved in ~/.config/jev/.env',
206  'settings.keySaved': 'saved',
207  'settings.keyPaste': 'paste a TypeSafe API key',
208  'settings.saveKey': 'save',
209  'settings.testing': 'Testing…',
210  'settings.keyWorks': 'Key works',
211  'settings.keyRejected': 'Key rejected',
212  'settings.key': 'Key',
213  'settings.test': 'Test',
214  'settings.noModels': 'no router models listed',
215  'settings.haikuFallback': 'falls back to Haiku',
216  'settings.keepWarm': 'Keep warm',
217  'settings.keepWarmHint': 'pings the cache just before it expires',
218  'settings.for': 'For',
219  'settings.afterReply': 'after the last reply',
220  'settings.chatsFrom': 'Chats from',
221  'settings.tokens': 'tokens',
222  'settings.warmCost': 'Each ping re-reads the whole chat from cache: about a tenth of its input price, and the same share of plan limits.',
223  'settings.compactModel': 'Compaction model',
224  'settings.sessionCompactor': 'The session’s own',
225  'settings.heavyAt': 'Heavy at',
226  'settings.context': 'context',
227  'settings.cacheTimer': 'Cache timer',
228  'settings.reason': 'Reason',
229  'settings.route': 'Route',
230  'settings.limits': 'Limits',
231  'settings.layout': 'Layout',
232  'settings.dashboard': 'Dashboard',
233  'settings.minimal': 'Minimal',
234  'settings.footerHint': 'one line in the footer',
235  'settings.appearance': 'Appearance',
236  'settings.dark': 'Dark',
237  'settings.lightAppearance': 'Light',
238  'settings.skin': 'Skin',
239  'settings.skinLine': 'How the band and the cards are drawn.',
240  'settings.skinDeep': 'Deep',
241  'settings.skinFlat': 'Flat',
242  'settings.show': 'Show',
243  'settings.language': 'Language',
244  'settings.title': 'settings',
245  'settings.quick': 'Quick settings',
246  'settings.effortAuto': 'Automatic effort',
247  'settings.openAll': 'Open all settings',
248  'setup.workersNote': 'Workers start on the ladder; set it up on the dashboard.',
249  'setup.changeDashboard': 'Use the band or /ripple for quick changes; open all settings for the dashboard.',
250  'settings.save': 'Save',
251  'settings.discard': 'Discard',
252  'settings.close': 'Close',
253  'settings.autoLine': 'Picks the effort for every prompt by itself.',
254  'settings.autoOffNote': 'The level you pick in the app’s effort menu stays.',
255  'settings.judgeLine': 'Sets each prompt’s effort and each delegated task’s tier.',
256  'settings.modeLine': 'The set of agents that delegated tasks go to.',
257  'settings.warmLine': 'Pings the cache just before it goes cold.',
258  'settings.warmCostShort': 'Each ping costs about a tenth of the input price.',
259  'settings.sayAuto': '{judge} picks the effort for every prompt.',
260  'settings.sayManual': 'Effort stays where you set it in the app.',
261  'settings.sayWarm': 'And I’ll keep the cache warm.',
262  'band.hideBand': 'Hide the band',
263  'settings.unsaved': '● unsaved',
264  // Setup.
265  'setup.judgeTitle': 'Who decides',
266  'setup.judgeBlurb': 'A small, fast judge picks each prompt’s effort.',
267  'setup.workersTitle': 'Who does the work',
268  'setup.cacheTitle': 'Keep the cache warm?',
269  'setup.cacheBlurb': 'An idle chat’s cache expires; Ripple can ping it while you are away.',
270  'setup.effortSummary': 'Auto {state}, judged by {judge}',
271  'setup.cacheSummary': 'kept warm for {hours}h after each reply',
272  'setup.cacheOff': 'not kept warm',
273  'setup.ready': 'ClaudeRipple is ready',
274  'setup.welcome': 'Welcome to ClaudeRipple',
275  'setup.start': 'Start',
276  'setup.finish': 'Finish',
277  'setup.next': 'Next',
278  'setup.back': 'Back',
279  'setup.skip': 'Skip setup',
280  // Agents.
281  'agents.routerModel': 'router model',
282  'agents.marker': 'marker',
283  'agents.default': 'default',
284  'agents.session': 'the session’s model',
285  'agents.rule': 'a written rule',
286  'agents.by': 'by {name}',
287  'agents.thinking': 'thinking',
288  'agents.fallback': '▲ ran the fallback: {reason}',
289  'agents.emptyTitle': 'No agents or background tasks yet',
290  'agents.emptyBody': 'Tasks Claude delegates appear here, along with commands and monitoring tasks running in the background. Delegated tasks also show the worker Ripple picked and why.',
291  'agents.liveCount': '{count} running',
292  'agents.noneRunning': 'None running',
293  'agents.doneCount': '{count} finished',
294  // Log.
295  'log.resent': '↻ {status} resent',
296  'log.statelessSwitch': '↻ resent as the whole conversation (expected)',
297  'log.input': 'in {tokens}',
298  'log.output': 'out {tokens}',
299  'log.thisSession': 'This session',
300  'log.allSessions': 'All sessions',
301  'log.showAll': 'Show all sessions',
302  'log.onlySession': 'This session only',
303  'log.legend': '● this session  ○ other sessions',
304  'log.empty': 'No model requests yet.',
305  'log.judge': 'Effort judge',
306  'log.judgeWorker': 'Worker judge',
307  'log.judgeFell': '{asked} failed → {by}',
308  'log.sure': 'sure {percent}%',
309  // Limits pane.
310  'limits.title': 'Plan limits',
311  'limits.hint': 'Share used in each window, and when it resets.',
312  'limits.empty': 'Plan usage is not available yet.',
313  // Toasts and locally generated failure/reason text.
314  'toasts.keySingle': 'Paste a single TypeSafe API key',
315  'toasts.keyPrivateFailed': 'Could not make the Jev key file private (chmod 600)',
316  'toasts.keySaved': 'ClaudeRipple: Jev key saved privately; environment keys still take priority.',
317  'toasts.judgeDown': 'ClaudeRipple: {reason}; keeping the current effort or asking Haiku.',
318  'toasts.keyMissing': 'Jev key missing',
319  'toasts.jevNoVerdict': 'Jev returned no verdict',
320  'judge.keptUnsure': 'Unsure, kept the running effort',
321  'toasts.routerNoVerdict': 'Router judge returned no verdict',
322  'toasts.haikuNoVerdict': 'Haiku returned no verdict',
323  'toasts.noVerdict': 'no verdict',
324  'toasts.judgeUnavailable': 'judge unavailable',
325  'toasts.explicitMarker': 'explicit worker marker',
326  'toasts.sessionTier': 'tier named by the main chat: {tier}',
327  'toasts.noTier': 'no tier named: general, standard',
328  'toasts.rulePick': 'a written rule',
329  'toasts.workerFallback': 'ClaudeRipple: {reason}; running {name}.',
330  'toasts.modeEnded': 'The {name} mode has ended.',
331  'toasts.yourPick': 'your pick',
332  'toasts.effortEnter': 'ClaudeRipple: press Enter so the app effort control follows your pick.',
333  'toasts.settingsSaved': 'ClaudeRipple: settings saved.',
334  'toasts.newSessionFallback': 'Could not open a new session; the handoff is copied instead.',
335  'toasts.clipboardFallback': 'ClaudeRipple: clipboard unavailable; the resume note is in the prompt.',
336  'toasts.handoffFailed': 'ClaudeRipple: handoff failed; nothing was cleared.',
337  'toasts.compactFailed': 'ClaudeRipple: compaction failed; the chat was kept.',
338  'toasts.tidyStopped': 'ClaudeRipple: the tidy-up did not finish; the chat was not compacted.',
339  'toasts.warmStopped': 'ClaudeRipple: {reason}',
340  'toasts.warmBoundReason': 'Keep warm stopped: time bound reached',
341  'toasts.warmBound': 'ClaudeRipple: keep warm stopped at its time bound.',
342  'toasts.appEffort': 'app effort',
343  'toasts.appEffortChanged': 'app effort changed',
344  'toasts.autoOff': 'ClaudeRipple: your app effort change turned Auto off.',
345  'toasts.ownModel': 'ClaudeRipple: {name} runs on its own model, not "{model}"',
346  'toasts.unnamedModel': 'ClaudeRipple: "{model}" was not named by you, so the task goes by tier, to {name}',
347  'toasts.transcriptEmpty': 'Transcript is empty or over the compaction budget',
348  'toasts.summaryEmpty': 'Haiku returned no usable summary',
349  'toasts.compactFallback': 'ClaudeRipple: the summary model failed; using the session compactor.',
350  'toasts.error': 'ClaudeRipple: {reason}',
351  'toasts.jevTimeout': 'Jev timed out',
352  'toasts.jevRejected': 'Jev key rejected',
353  'toasts.jevCredits': 'Jev out of credits',
354  'toasts.jevRateLimited': 'Jev rate limited',
355  'toasts.jevHttp': 'Jev request failed ({status})',
356  'toasts.warmNoReply': 'Keep warm stopped: no fork reply',
357  'toasts.warmNoCache': 'Keep warm stopped: cache was not read',
358  'toasts.providerQuota': 'ChatGPT accounts are unavailable or out of quota',
359  'toasts.logNotPlaced': 'The log could not open here: {reason}',
360  'toasts.saveMode': 'save mode',
361  'toasts.yourSettings': 'your settings',
362  'toasts.jevNetwork': 'Jev network unavailable',
363  'toasts.workerMissing': '{name} is not installed',
364  // Commands (stats and debug labels included).
365  'commands.description': 'ClaudeRipple effort, workers, cache and session tools',
366  'commands.argumentHint': 'settings|setup|auto|warm|save|stats|debug|agents|log|bar|cold|swamp|hot|down|kept',
367  'commands.logDescription': 'Open or close the ClaudeRipple request log',
368  'commands.barDescription': 'Show or hide the ClaudeRipple band',
369  'commands.logTitle': 'ClaudeRipple',
370  'commands.agentsTitle': 'ClaudeRipple Agents',
371  'commands.help': 'ClaudeRipple: settings, setup, auto, warm, save, stats, debug, agents, log, bar, cold, swamp, hot, down, kept.',
372  'commands.done': 'ClaudeRipple: {command}.',
373  'commands.logOpened': 'ClaudeRipple log opened.',
374  'commands.logClosed': 'ClaudeRipple log closed.',
375  'commands.barShown': 'ClaudeRipple line shown above the prompt.',
376  'commands.barShownMinimal': 'The layout is Minimal, so ClaudeRipple shows as a short line under the prompt. For the full band above the prompt, set Layout to Dashboard in /ripple settings.',
377  'commands.barHidden': 'ClaudeRipple line hidden. /ripple-bar shows it again.',
378  'commands.statsAuto': 'Auto: {prompts} prompts, {requests} requests; {total} weighted tokens',
379  'commands.statsTokens': 'Tokens: input {input}, write {write}, read {read}, output {output}',
380  'commands.statsEffort': '{effort} {prompts} prompts / {cost} weighted',
381  'commands.statsJudges': 'Judges: haiku {haiku}, jev {jev}, model {model}; {tokens} tokens, {ms} ms ({avg} ms avg)',
382  'commands.statsWorkers': 'Workers: {workers}',
383  'commands.statsWarm': 'Warm: {pings} pings, {cost} weighted tokens',
384  'commands.debugJudge': 'judge',
385  'commands.debugJudgeModel': 'judgeModel',
386  'commands.debugPick': 'pick',
387  'commands.debugPaused': 'paused',
388  'commands.debugCache': 'cache',
389  'commands.debugWarm': 'warm',
390  'commands.debugLastSpawn': 'lastSpawn',
391  'commands.debugLastRequest': 'lastRequest',
392  'commands.debugEffort': 'effort',
393  'commands.debugWhy': 'why',
394  'commands.debugBy': 'by',
395  'commands.debugAt': 'at',
396  'commands.debugSure': 'sure',
397  'commands.debugTtlMs': 'ttlMs',
398  'commands.debugLastReplyAt': 'lastReplyAt',
399  'commands.debugExpiresAt': 'expiresAt',
400  'commands.debugPings': 'pings',
401  'commands.debugCost': 'cost',
402  'commands.debugStopped': 'stopped',
403  'commands.debugLastPingAt': 'lastPingAt',
404  'commands.debugTier': 'tier',
405  'commands.debugTarget': 'target',
406  'commands.debugAgent': 'agent',
407  'commands.debugModel': 'model',
408  'commands.debugMs': 'ms',
409  'commands.debugFallbackReason': 'fallbackReason',
410  'commands.debugAppEffort': 'appEffort',
411  'commands.debugSentEffort': 'sentEffort',
412  'commands.debugLog': 'ClaudeRipple {where}: {reason}',
413  'commands.routerHttp': 'router HTTP {status}',
414  'commands.compactSkip': 'ClaudeRipple summarizes with Haiku when compaction is needed.',
415  // Workers card, Jev source, and worker picks in the Agents pane.
416  'workers.previous': 'Previous',
417  'workers.next': 'Next',
418  'workers.page': 'Page {page} of {pages}',
419  'workers.general': 'General',
420  'workers.design': 'Design',
421  'workers.frontend': 'Frontend',
422  'workers.backend': 'Backend',
423  'workers.infra': 'Infrastructure',
424  'workers.data': 'Data',
425  'workers.test': 'Tests',
426  'workers.docs': 'Documentation',
427  'workers.research': 'Research',
428  'workers.mode': 'Mode',
429  'workers.rung.light': 'Low worker',
430  'workers.rung.standard': 'Medium worker',
431  'workers.rung.hard': 'High worker',
432  'workers.rung.plan': 'Max worker',
433  'workers.rungHint.light': 'Finding files, quick lookups, skimming logs, mechanical edits',
434  'workers.rungHint.standard': 'Specified implementation, refactors, summaries, drafts',
435  'workers.rungHint.hard': 'Hard debugging, multi-file changes, independent review and rebuttal',
436  'workers.rungHint.plan': 'Best result available: planning, design, architecture, opinions',
437  'workers.rungEmpty': '{rung} has no model set',
438  'workers.notCandidate': '{name} is not a candidate here',
439  'workers.sessionModel': 'the session\'s model',
440  'workers.offset': 'Effort offset',
441  'workers.anyEffort': 'Any effort',
442  'workers.noTarget': 'Use next level / fallback',
443  'workers.judgeBlurb': 'Who decides: effort for prompts, domain and level for tasks.',
444  'workers.disabled': '{provider} is switched off',
445  'workers.nested': 'A subagent may not start another subagent: do this part yourself, then report back.',
446  'workers.none': 'No enabled worker is available',
447  'workers.noReason': 'No reason was given for the model {name}. On the second line write "Model reason: user \\"<the user\'s exact words>\\"" or "Model reason: rule <file> — <the rule>", or drop the model and give only the tier.',
448  'workers.notSaid': 'The words given as the reason for the model {name} are not in the user\'s recent messages. Quote what the user actually said, or drop the model and give only the tier.',
449  'workers.unknownModel': 'The model {name} cannot run on this computer. Name a worker agent, or opus, sonnet or haiku.',
450  'workers.namedUnavailable': 'The model {name} cannot run now',
451  'workers.ladderEmpty': 'No worker on this tier can run now ({reason}). Check the worker ladder in the dashboard.',
452  'workers.loading': 'Loading the router\'s workers…',
453  'workers.providerSub': '{on} of {count} on',
454  'workers.fallbackHint': 'when pinned targets cannot run',
455  'workers.pinDetails': 'More options',
456  'workers.back': 'Back',
457  'settings.ladderWaiting': 'Waiting for the router\'s model list.',
458  'jev.zenMissing': 'No OpenCode Zen authorization key in ClaudeRipple config',
459  'agents.domainLevel': '{domain} / {level}',
460  'agents.title': 'Agents',
461  'agents.total': 'All agents',
462  'agents.tokens': 'tokens',
463  'agents.cache': 'cache',
464  'agents.toolsLabel': 'tools',
465  'agents.failed': 'failed',
466  'agents.stopped': 'stopped',
467  'agents.shell': 'Command',
468  'agents.monitor': 'Monitor',
469  'agents.exitCode': 'exit code {code}',
470  'agents.more': 'Show {count} more',
471  'agents.less': 'Show fewer',
472  'agents.open': 'Open',
473  'agents.back': 'All agents',
474  'agents.task': 'Task',
475  'agents.answer': 'Final answer',
476  'agents.dropped': '{count} earlier entries left out: too long to draw',
477  'agents.act.command': 'ran {count} commands',
478  'agents.act.commandOne': 'ran a command',
479  'agents.act.read': 'read {count} files',
480  'agents.act.readOne': 'read a file',
481  'agents.act.write': 'created {count} files',
482  'agents.act.writeOne': 'created a file',
483  'agents.act.edit': 'edited {count} files',
484  'agents.act.editOne': 'edited a file',
485  'agents.act.notebook': 'edited {count} notebooks',
486  'agents.act.notebookOne': 'edited a notebook',
487  'agents.act.grep': 'searched code',
488  'agents.act.glob': 'found files',
489  'agents.act.browse': 'browsed the web',
490  'agents.act.fetch': 'fetched {count} pages',
491  'agents.act.fetchOne': 'fetched a page',
492  'agents.act.agent': 'ran {count} agents',
493  'agents.act.agentOne': 'ran an agent',
494  'agents.act.todo': 'updated todos',
495  'agents.act.other': 'used {count} tools',
496  'agents.act.otherOne': 'used a tool',
497  'agents.act.failed': '{count} failed',
498  'agents.showMore': 'Show more',
499  'agents.showLess': 'Show less',
500  'agents.working': 'Working',
501  'agents.diff': '{added} lines added, {removed} removed',
502  'agents.running': 'Running',
503  'agents.finished': 'Done {count}',
504  'agents.deny': 'This agent’s conversation can’t be read: {reason}',
505  'agents.gone': 'This agent is no longer in the list.',
506  'agents.nothingYet': 'Nothing in its conversation yet.',
507  // Context pane (the band's context chip opens it).
508  'commands.contextTitle': 'ClaudeRipple Context',
509  'commands.limitsTitle': 'ClaudeRipple Limits',
510  'band.contextOpen': '{tokens} of {window} tokens · Click for details',
511  'context.title': 'Context breakdown',
512  'context.of': '/ {max} tokens',
513  'context.estimate': 'Local estimate',
514  'context.precise': 'Counted by the token-count API',
515  'context.refresh': 'Count precisely',
516  'context.refreshing': 'Counting…',
517  'context.refreshAgain': 'Count again',
518  'context.failed': 'Precise count failed: {reason}',
519  'context.byCategory': 'By category',
520  'context.notCounted': 'not counted',
521  'context.none': 'The context breakdown is not available yet.',
522  'context.cat.systemPrompt': 'System prompt',
523  'context.cat.systemTools': 'System tools',
524  'context.cat.systemDeferred': 'System tools (on demand)',
525  'context.cat.mcpTools': 'MCP tools',
526  'context.cat.mcpDeferred': 'MCP tools (on demand)',
527  'context.cat.mcpInstructions': 'MCP server instructions',
528  'context.cat.agents': 'Custom agents',
529  'context.cat.memory': 'Memory files',
530  'context.cat.skills': 'Skills',
531  'context.cat.messages': 'Messages',
532  'context.cat.free': 'Free space',
533  'context.cat.buffer': 'Auto-compact buffer',
534  'context.cat.compactBuffer': 'Compact buffer',
535  'context.src.project': 'Project',
536  'context.src.user': 'User',
537  'context.src.local': 'Local',
538  'context.src.managed': 'Managed',
539  'context.src.automem': 'Auto memory',
540  'context.src.plugin': 'Plugin',
541  'context.src.builtin': 'Built-in',
542  'context.src.mcp': 'MCP',
543  'context.src.synced': 'Synced',
544  'context.memory': 'Memory files',
545  'context.mcp': 'MCP tools',
546  'context.skills': 'Skills',
547  'context.agents': 'Custom agents',
548  'context.count': '{count}',
549  'context.tools': '{count} tools',
550  'context.toolsDeferred': '{count} tools, {deferred} on demand',
551  'context.servers': '{count} servers · {tools} tools',
552  'context.skillsOf': '{included} of {total} listed',
553  'context.autoAt': 'Auto-compact runs at {tokens} tokens.',
554  'context.autoOn': 'Auto-compact is on.',
555  'context.autoOff': 'Auto-compact is off.',
556  'context.commands': 'Slash commands: {included} of {total} listed, {tokens} tokens.',
557  // Time units: countdowns, reset times, durations.
558  'units.seconds': '{n}s',
559  'units.minutes': '{n}m',
560  'units.hours': '{n}h',
561  'units.days': '{n}d',
562  'units.minSec': '{m}m {s}s',
563  'units.hourMin': '{h}h {m}m',
564  // Weekdays for a reset days away, Sunday first.
565  'units.weekdaySun': 'Sun',
566  'units.weekdayMon': 'Mon',
567  'units.weekdayTue': 'Tue',
568  'units.weekdayWed': 'Wed',
569  'units.weekdayThu': 'Thu',
570  'units.weekdayFri': 'Fri',
571  'units.weekdaySat': 'Sat',
572} as const
573
574export type Key = keyof typeof EN
575
576const KO: Record<Key, string> = {
577  // Band (including shared display labels and accessibility text).
578  'band.brand': 'ClaudeRipple',
579  'band.effort': '추론 강도',
580  'band.model': '모델',
581  'band.auto': '자동',
582  'band.manual': '수동',
583  'band.paused': '일시 중지',
584  'band.off': '꺼짐',
585  'band.on': '켜짐',
586  'band.autoOff': '자동 꺼짐',
587  'band.autoPaused': '자동 일시 중지',
588  'band.deciding': '판정 중…',
589  'band.decidingText': '◌ 판정 중…',
590  'band.low': '낮음',
591  'band.medium': '중간',
592  'band.high': '높음',
593  'band.xhigh': '매우 높음',
594  'band.max': '최대',
595  'band.pausedHint': '이 모델은 추론 강도를 바꿔도 캐시가 유지되는지 확인하지 못했습니다. 자동 선택을 잠시 멈춥니다.',
596  'band.offHint': '자동 선택이 꺼져 있습니다. 추론 강도를 직접 정합니다.',
597  'band.decidingHint': '판정 모델이 이번 프롬프트에 맞는 추론 강도를 고르고 있습니다.',
598  'band.effortTitle': '추론 강도 {value}{hint} · 눌러서 강도 선택',
599  'band.effortAlt': '추론 강도 {value} ({mode}){why}',
600  'band.context': '컨텍스트',
601  'band.contextAlt': '컨텍스트 {value} / {window} ({tokens} 토큰)',
602  'band.cache': '캐시',
603  'band.cacheWarm': '캐시 · 유지 중',
604  'band.cacheStopped': '캐시 · 유지 중단',
605  'band.cold': '만료',
606  'band.cacheTip': '프롬프트 캐시 {state}{warm}',
607  'band.warmFor': '{time} 후 만료',
608  'band.expired': '만료됨',
609  'band.warmStoppedTip': ' · 캐시 유지 중단: {reason}',
610  'band.warmOnTip': ' · 캐시 유지 켜짐, 유지 요청 {count}회',
611  'band.noReply': '아직 응답 없음',
612  'band.cacheAlt': '캐시 {state}{warm}',
613  'band.timeLeft': '{time} 남음',
614  'band.unknown': '알 수 없음',
615  'band.keepWarmAlt': ', 캐시 유지 켜짐{count}',
616  'band.limitCaption': '{window} 한도{save}',
617  'band.saveCaption': ' · 절약',
618  'band.limitAlt': '{window} 한도 {value}{reset}',
619  'band.limitsTip': '{provider} {window} {value}{reset}',
620  'band.fiveHour': '5시간',
621  'band.weekly': '주간',
622  'band.resetting': '초기화 중',
623  'band.resetsIn': '{time} 뒤 초기화',
624  'band.resetsAt': '{time} 초기화',
625  'band.resetIn': '{time} 뒤',
626  'band.resetDay': '{day} {time}',
627  'band.router': '리플',
628  'band.routerAlt': '리플: {value}',
629  'band.resentCaption': '재전송 · {status}',
630  'band.failedCaption': '실패 · {status}',
631  'band.lastRoute': '최근 경로',
632  'band.logHint': '눌러서 요청 로그 보기',
633  'band.limitsOpen': '눌러서 기간별 사용률과 초기화 시각 보기',
634  'band.routeAlt': '최근 경로: {provider}의 {model}{effort}{cache}, {time}{status}',
635  'band.routeCache': ', 캐시 {percent}%',
636  'band.routeResent': ', {status} 재전송',
637  'band.routeFailed': ', {status} 실패',
638  'band.warm': '캐시 유지',
639  'band.handoff': '인수인계',
640  'band.compact': '압축',
641  'band.clear': '새로 시작',
642  'band.compactAlt': '대화 압축 — 대화를 요약해 컨텍스트를 줄입니다',
643  'band.compactedTimes': '{count}번 압축됨',
644  'band.clearAlt': '새로 시작 (/clear) — 대화 내용을 비우고 새로 시작합니다',
645  'band.log': '로그',
646  'band.agents': '에이전트',
647  'band.settings': '설정',
648  'band.effortShort': '강도',
649  'band.hit': '적중 {percent}%',
650  'band.effortAutoAlt': '추론 강도 자동 {state}',
651  'band.warmAlt': '캐시 유지 {state}',
652  'band.warmHere': '이 대화에만 적용합니다. 새 대화는 설정을 따릅니다',
653  'band.closeLog': '요청 로그 닫기',
654  'band.openLog': '요청 로그 열기',
655  'band.agentsAlt': '에이전트: {count}개 실행 중',
656  'band.settingsAlt': '리플 설정',
657  'band.warmStopped': '유지 중단',
658  'band.warmText': '≈유지',
659  'band.save': '절약',
660  'band.resent': '{status} 재전송',
661  'band.phoneQueue': '휴대폰 대기열 {count}',
662  'band.phoneQueueWhen': '이 턴이 끝나면 보냄',
663  'band.cachePercent': '캐시 {percent}%',
664  'band.closeLogText': '로그 닫기',
665  'band.footerPaused': ' (일시 중지)',
666  'band.footerOff': ' (자동 꺼짐)',
667  'band.footerManual': ' (수동)',
668  'band.footerContext': '컨텍스트 {percent}%',
669  'band.routerRestart': '리플: 다시 시작하면 최근 경로를 표시합니다',
670  'band.routerDown': '리플: 응답이 없습니다',
671  // Alerts.
672  'alerts.coldTitle': '캐시가 만료되었습니다',
673  'alerts.coldBody': '{minutes}분 동안 대화가 없어 캐시가 만료되었습니다. 다음 프롬프트는 {tokens} 토큰 전체를 다시 읽고, 캐시 할인 없이 비용을 계산합니다.',
674  'alerts.keptTitle': '자리를 비운 동안 캐시를 유지했습니다',
675  'alerts.keptBody': '유지 요청 {pings}회로 {tokens} 토큰을 캐시에 남겨 두었습니다. 다음 프롬프트도 캐시 할인 요금으로 읽습니다. 만료까지 {minutes}분 남았습니다.',
676  'alerts.gotIt': '확인',
677  'alerts.swampTitle': '컨텍스트 {percent}% 사용',
678  'alerts.swampBody': '프롬프트마다 {tokens} 토큰을 함께 보냅니다. 응답이 느려지고 비용이 늘며, 답변도 덜 정확해집니다.',
679  'alerts.hotTitle': '{window} 한도 {percent}% 도달',
680  'alerts.saveOnBody': '절약 모드가 켜져 있습니다. 한도가 초기화될 때까지 자동 추론 강도를 중간 이하로 유지합니다.',
681  'alerts.saveBody': '절약 모드를 켜면 한도가 초기화될 때까지 자동 추론 강도를 중간 이하로 유지합니다.',
682  'alerts.saveOff': '절약 모드 끄기',
683  'alerts.save': '절약 모드',
684  'alerts.notNow': '나중에',
685  'alerts.judgeTitle': '추론 강도 판정 모델이 응답하지 않습니다',
686  'alerts.judgeNetworkTitle': '연결이 불안정해 당분간 Haiku가 판정합니다',
687  'alerts.routerModel': '리플 모델',
688  'alerts.judgeBody': '{judge}: {reason}. {fallback}',
689  'alerts.keepEffort': '당분간 현재 추론 강도를 유지합니다.',
690  'alerts.askHaiku': '당분간 Haiku가 판정합니다.',
691  'alerts.openSettings': '설정 열기',
692  'alerts.compactTitle': '대화 압축',
693  'alerts.compactBody': '꼭 남길 내용을 적으면 요약에 반영합니다. 비워 두면 알아서 요약합니다.',
694  'alerts.cancel': '취소',
695  'alerts.dismiss': '닫기',
696  'alerts.handoffTitle': '새 대화로 인수인계',
697  'alerts.handingOff': '인수인계 중…',
698  'alerts.quickProgress': '새 대화에서 이어갈 수 있도록 요약하고 있습니다.',
699  'alerts.handoffDone': '인수인계 완료',
700  'alerts.summaryReady': '요약을 준비했습니다.',
701  'alerts.copyAgain': '다시 복사',
702  'alerts.compacting': '압축 중…',
703  'alerts.compactingBody': '대화를 요약하고 있습니다. 요약이 끝나면 그 내용으로 대화를 이어갑니다.',
704  'alerts.compacted': '압축 완료',
705  'alerts.compactedBody': '요약한 내용으로 대화를 이어갑니다.',
706  'alerts.failed': '작업을 마치지 못했습니다',
707  'alerts.unchanged': '아무것도 바꾸지 않았습니다.',
708  'alerts.keep': '남길 내용',
709  'alerts.keepPlaceholder': '결정한 내용, 남은 질문, 파일 이름… (선택)',
710  'alerts.compactSubmit': '압축',
711  'alerts.demoDown': 'Jev 크레딧 소진 (데모)',
712  'alerts.openedBody': '새 대화를 열고 입력창에 인수인계 내용을 넣었습니다. 새 대화에서 Enter를 누르면 이어갑니다.',
713  'alerts.readHandoffFile': '{path}의 인수인계 내용을 읽고 이어서 진행해 주십시오.',
714  'alerts.copied': '이어서 대화할 요약을 복사했습니다. 현재 대화는 그대로 둡니다.',
715  'alerts.compactFailed': '대화 압축을 마치지 못했습니다.',
716  'alerts.tidyFirst': '압축 전 정리: {state}',
717  'alerts.tidying': '정리 중…',
718  'alerts.tidyingBody': '압축하면 사라질 수 있는 내용을 먼저 정리하고 있습니다. 정리가 끝나면 바로 압축합니다.',
719  'alerts.tidyFailed': '정리 단계를 마치지 못해 압축하지 않았습니다. 대화는 그대로입니다.',
720  'alerts.tidyPrompt': '곧 대화를 압축합니다. 압축 후에도 작업을 이어갈 수 있도록 필요한 정리를 진행해 주세요. 지금까지 한 일과 남은 일, 결정한 내용을 정리하고, 인수인계 문서나 기억 파일이 있으면 갱신해 주세요.',
721  'alerts.clearTitle': '대화 새로 시작',
722  'alerts.clearBody': '현재 대화의 컨텍스트를 모두 비웁니다. 이전 내용 없이 새로 시작합니다.',
723  'alerts.clearGo': '새로 시작',
724  // Settings.
725  'settings.effortBlurb': '프롬프트마다 추론 강도를 자동으로 고르는 방식을 정합니다.',
726  'settings.workers': '워커',
727  'settings.mode': '모드',
728  'settings.modeNone': '기본',
729  'band.delegationPin': '위임 고정: {name}',
730  'band.releasePin': '해제',
731  'band.pinSaid': '“{said}”라고 말씀하셔서 고정했습니다',
732  'band.pinKept': '이 세션이 끝날 때까지 유지됩니다',
733  'toasts.delegationPinned': '이 세션의 위임 모델을 고정했습니다: {name}.',
734  'toasts.delegationUnpinned': '위임 고정을 해제했습니다.',
735  'band.mode': '모드',
736  'band.modeTip': '“{name}” 모드에 따라 워커를 고릅니다. 빠른 설정에서 모드를 바꿀 수 있습니다.',
737  'settings.workersBlurb': '맡기는 작업의 종류에 따라 워커를 정합니다.',
738  'settings.judge': '판정 모델',
739  'settings.judgeBlurb': '프롬프트의 추론 강도와 맡긴 작업의 등급을 고르는 모델입니다.',
740  'settings.cacheBlurb': '자리를 비운 동안에도 프롬프트 캐시를 유지합니다.',
741  'settings.look': '화면 표시',
742  'settings.lookBlurb': '상태 바에 무엇을 어떻게 보여 줄지 정합니다.',
743  'settings.light': '간단',
744  'settings.lightBlurb': '단순 작업, 반복 작업, 자료 찾기',
745  'settings.standard': '표준',
746  'settings.standardBlurb': '설계에 따른 구현, 조사, 코드 검토',
747  'settings.deep': '고난도',
748  'settings.deepBlurb': '신중한 판단, 실수하면 위험한 작업, 어려운 추론',
749  'settings.design': '디자인',
750  'settings.designBlurb': '화면, 시각 디자인, 브랜드',
751  'settings.tierAlt': '{name} 등급',
752  'settings.biasAlt': '선택 성향 {value}{selected}',
753  'settings.selected': ' (선택됨)',
754  'settings.onSuffix': ' (켜짐)',
755  'settings.offSuffix': ' (꺼짐)',
756  'settings.mixedSuffix': ' (일부 켜짐)',
757  'settings.cheaper': '비용 우선',
758  'settings.smarter': '성능 우선',
759  'settings.autoHint': '프롬프트마다 자동으로 고릅니다. 직접 바꾸면 자동 선택이 꺼집니다.',
760  'settings.lean': '선택 성향',
761  'settings.leanHint': '어느 쪽을 고를지 애매할 때만 적용',
762  'settings.floor': '최저 강도',
763  'settings.ceiling': '최고 강도',
764  'settings.floorWins': '최저 강도보다 낮아 최저 강도로 맞춥니다.',
765  'settings.unavailable': ' (사용 불가)',
766  'settings.takesOver': '적용 대상',
767  'settings.autoAgent': 'ripple:auto',
768  'settings.allSpawns': '모든 서브에이전트',
769  'settings.fallback': '대체 워커',
770  'settings.fallbackHint': '이 등급의 프로바이더 한도를 모두 썼을 때',
771  'settings.haiku': 'Haiku',
772  'settings.jev': 'Jev',
773  'settings.routerModel': '리플 모델',
774  'settings.haikuHint': 'Claude 계정으로 Haiku 5.5 사용 · 프롬프트당 약 1초',
775  'settings.keyEnv': 'TYPESAFE_API_KEY의 키 사용',
776  'settings.keyFile': '~/.config/jev/.env에 저장',
777  'settings.keySaved': '저장 완료',
778  'settings.keyPaste': 'TypeSafe API 키 붙여넣기',
779  'settings.saveKey': '저장',
780  'settings.testing': '확인 중…',
781  'settings.keyWorks': 'API 키 확인 완료',
782  'settings.keyRejected': 'API 키 인증 실패',
783  'settings.key': 'API 키',
784  'settings.test': '확인',
785  'settings.noModels': '리플 모델 목록이 비어 있습니다.',
786  'settings.haikuFallback': '실패하면 Haiku로 대체',
787  'settings.keepWarm': '캐시 유지',
788  'settings.keepWarmHint': '캐시 만료 직전에 유지 요청 전송',
789  'settings.for': '유지 시간',
790  'settings.afterReply': '마지막 응답부터',
791  'settings.chatsFrom': '대상 대화',
792  'settings.tokens': '토큰 이상',
793  'settings.warmCost': '유지 요청마다 캐시에서 대화 전체를 다시 읽습니다. 비용은 일반 입력 비용의 약 1/10이며, 요금제 한도도 같은 비율로 사용합니다.',
794  'settings.compactModel': '압축 모델',
795  'settings.sessionCompactor': '현재 대화 기본',
796  'settings.heavyAt': '대화 압축 기준',
797  'settings.context': '컨텍스트',
798  'settings.cacheTimer': '캐시 남은 시간',
799  'settings.reason': '판정 이유',
800  'settings.route': '요청 경로',
801  'settings.limits': '한도',
802  'settings.layout': '배치',
803  'settings.dashboard': '대시보드',
804  'settings.minimal': '한 줄',
805  'settings.footerHint': '입력창 아래 한 줄로 표시',
806  'settings.appearance': '테마',
807  'settings.dark': '어두운 테마',
808  'settings.lightAppearance': '밝은 테마',
809  'settings.skin': '모양',
810  'settings.skinLine': '상태 바와 카드의 모양을 정합니다.',
811  'settings.skinDeep': '입체',
812  'settings.skinFlat': '평면',
813  'settings.show': '표시 항목',
814  'settings.language': '언어',
815  'settings.title': '설정',
816  'settings.quick': '빠른 설정',
817  'settings.effortAuto': '추론 강도 자동 선택',
818  'settings.openAll': '전체 설정 열기',
819  'setup.workersNote': '처음에는 기본 워커 단계에 따라 배정합니다. 대시보드에서 단계별 워커를 바꿀 수 있습니다.',
820  'setup.changeDashboard': '상태 바나 /ripple에서 빠르게 바꿉니다. 세부 설정은 전체 설정을 열어 대시보드에서 바꿉니다.',
821  'settings.save': '저장',
822  'settings.discard': '변경 취소',
823  'settings.close': '닫기',
824  'settings.autoLine': '프롬프트마다 알맞은 추론 강도를 자동으로 고릅니다.',
825  'settings.autoOffNote': '앱의 추론 강도 메뉴에서 고른 값을 그대로 씁니다.',
826  'settings.judgeLine': '프롬프트의 추론 강도와 맡긴 작업의 등급을 정합니다.',
827  'settings.modeLine': '맡긴 작업을 실행할 워커 묶음입니다.',
828  'settings.warmLine': '캐시 만료 직전에 유지 요청을 보냅니다.',
829  'settings.warmCostShort': '유지 요청마다 일반 입력 비용의 약 1/10이 듭니다.',
830  'settings.sayAuto': '{judge} 모델이 프롬프트마다 추론 강도를 고릅니다.',
831  'settings.sayManual': '추론 강도는 앱에서 고른 대로 유지합니다.',
832  'settings.sayWarm': '캐시도 만료되지 않도록 유지합니다.',
833  'band.hideBand': '상태 바 숨기기',
834  'settings.unsaved': '● 저장 전',
835  // Setup.
836  'setup.judgeTitle': '판정 모델 선택',
837  'setup.judgeBlurb': '작고 빠른 판정 모델이 프롬프트마다 추론 강도를 고릅니다.',
838  'setup.workersTitle': '작업을 맡길 워커',
839  'setup.cacheTitle': '캐시 유지 설정',
840  'setup.cacheBlurb': '대화를 쉬면 캐시가 만료됩니다. 자리를 비운 동안 리플이 유지 요청을 보내 캐시를 유지합니다.',
841  'setup.effortSummary': '추론 강도 자동 선택 {state}, 판정 모델: {judge}',
842  'setup.cacheSummary': '응답 후 {hours}시간 동안 캐시 유지',
843  'setup.cacheOff': '캐시 유지 꺼짐',
844  'setup.ready': '리플 준비 완료',
845  'setup.welcome': '리플을 시작합니다',
846  'setup.start': '시작',
847  'setup.finish': '완료',
848  'setup.next': '다음',
849  'setup.back': '이전',
850  'setup.skip': '설정 건너뛰기',
851  // Agents.
852  'agents.routerModel': '리플 모델',
853  'agents.marker': '직접 지정',
854  'agents.default': '기본값',
855  'agents.session': '현재 대화 모델',
856  'agents.rule': '적힌 규칙',
857  'agents.by': '{name} 기준',
858  'agents.thinking': '추론 중',
859  'agents.fallback': '▲ 대체 워커 실행: {reason}',
860  'agents.emptyTitle': '아직 에이전트나 백그라운드 작업이 없습니다',
861  'agents.emptyBody': 'Claude가 맡긴 작업, 백그라운드에서 실행 중인 명령과 감시 작업이 여기에 표시됩니다. 리플이 고른 워커와 선택 이유도 함께 확인할 수 있습니다.',
862  'agents.liveCount': '{count}개 실행 중',
863  'agents.noneRunning': '실행 중인 에이전트 없음',
864  'agents.doneCount': '{count}개 완료',
865  // Log.
866  'log.resent': '↻ {status} 재전송',
867  'log.statelessSwitch': '↻ 전체 대화로 다시 보냄 (정상)',
868  'log.input': '입력 {tokens}',
869  'log.output': '출력 {tokens}',
870  'log.thisSession': '현재 대화',
871  'log.allSessions': '모든 대화',
872  'log.showAll': '모든 대화 보기',
873  'log.onlySession': '현재 대화만 보기',
874  'log.legend': '● 현재 대화  ○ 다른 대화',
875  'log.empty': '아직 모델에 보낸 요청이 없습니다.',
876  'log.judge': '추론 강도 판정',
877  'log.judgeWorker': '워커 판정',
878  'log.judgeFell': '{asked} 실패 → {by}',
879  'log.sure': '확신도 {percent}%',
880  // Limits pane.
881  'limits.title': '기간별 한도',
882  'limits.hint': '기간별 사용률과 초기화 시각입니다.',
883  'limits.empty': '아직 한도 사용량을 확인할 수 없습니다.',
884  // Toasts and locally generated failure/reason text.
885  'toasts.keySingle': 'TypeSafe API 키는 하나만 붙여 넣어야 합니다',
886  'toasts.keyPrivateFailed': 'Jev 키 파일을 본인만 읽고 쓰도록 설정하지 못했습니다 (chmod 600)',
887  'toasts.keySaved': '리플: Jev 키를 본인만 읽고 쓰도록 저장했습니다. 환경 변수의 키를 먼저 씁니다.',
888  'toasts.judgeDown': '리플: {reason}. 현재 강도를 유지하거나 Haiku가 대신 판정합니다.',
889  'toasts.keyMissing': 'Jev 키 없음',
890  'toasts.jevNoVerdict': 'Jev 판정 결과 없음',
891  'judge.keptUnsure': '판정이 애매해 현재 추론 강도 유지',
892  'toasts.routerNoVerdict': '리플 판정 모델의 결과 없음',
893  'toasts.haikuNoVerdict': 'Haiku 판정 결과 없음',
894  'toasts.noVerdict': '판정 결과 없음',
895  'toasts.judgeUnavailable': '판정 모델 사용 불가',
896  'toasts.explicitMarker': '워커 직접 지정',
897  'toasts.sessionTier': '주 대화에서 정한 등급: {tier}',
898  'toasts.noTier': '등급 지정 없음: 일반·표준',
899  'toasts.rulePick': '적힌 규칙',
900  'toasts.workerFallback': '리플: {reason}. 대신 {name} 워커를 실행합니다.',
901  'toasts.modeEnded': '{name} 모드가 끝났습니다.',
902  'toasts.yourPick': '직접 선택',
903  'toasts.effortEnter': '리플: Enter를 누르면 앱에도 같은 추론 강도를 적용합니다.',
904  'toasts.settingsSaved': '리플: 설정을 저장했습니다.',
905  'toasts.newSessionFallback': '새 대화를 열지 못해 인수인계 내용을 대신 복사했습니다.',
906  'toasts.clipboardFallback': '리플: 클립보드를 쓸 수 없어 입력창에 인수인계 요약을 넣었습니다.',
907  'toasts.handoffFailed': '리플: 인수인계에 실패했습니다. 대화는 그대로 둡니다.',
908  'toasts.compactFailed': '리플: 대화 압축에 실패했습니다. 대화는 그대로 둡니다.',
909  'toasts.tidyStopped': '리플: 정리를 마치지 못해 대화를 압축하지 않았습니다.',
910  'toasts.warmStopped': '리플: {reason}',
911  'toasts.warmBoundReason': '캐시 유지 중단: 유지 시간 종료',
912  'toasts.warmBound': '리플: 설정한 시간이 지나 캐시 유지를 멈췄습니다.',
913  'toasts.appEffort': '앱 추론 강도',
914  'toasts.appEffortChanged': '앱에서 추론 강도 변경',
915  'toasts.autoOff': '리플: 앱에서 추론 강도를 바꿔 자동 선택을 껐습니다.',
916  'toasts.ownModel': '리플: {name} 에이전트는 "{model}" 대신 자체 모델을 씁니다.',
917  'toasts.unnamedModel': '리플: 직접 고르신 모델이 아니어서 "{model}" 대신 등급에 맞는 {name}에 맡깁니다.',
918  'toasts.transcriptEmpty': '대화 기록이 없거나 압축에 쓸 수 있는 토큰 한도를 넘었습니다.',
919  'toasts.summaryEmpty': 'Haiku가 쓸 만한 요약을 보내지 않았습니다.',
920  'toasts.compactFallback': '리플: 압축 모델이 응답하지 않아 현재 대화의 기본 방식으로 압축합니다.',
921  'toasts.error': '리플: {reason}',
922  'toasts.jevTimeout': 'Jev 응답 대기 시간 초과',
923  'toasts.jevRejected': 'Jev 키 인증 실패',
924  'toasts.jevCredits': 'Jev 크레딧 소진',
925  'toasts.jevRateLimited': 'Jev 요청 속도 한도 초과',
926  'toasts.jevHttp': 'Jev 요청 실패 ({status})',
927  'toasts.warmNoReply': '캐시 유지 중단: 유지 요청에 응답 없음',
928  'toasts.warmNoCache': '캐시 유지 중단: 캐시를 읽지 않음',
929  'toasts.providerQuota': 'ChatGPT 계정을 사용할 수 없거나 한도를 모두 썼습니다.',
930  'toasts.logNotPlaced': '여기서는 로그를 열 수 없습니다: {reason}',
931  'toasts.saveMode': '절약 모드',
932  'toasts.yourSettings': '직접 정한 설정',
933  'toasts.jevNetwork': 'Jev 연결 불가',
934  'toasts.workerMissing': '{name} 에이전트 설치 안 됨',
935  // Commands (stats and debug labels included).
936  'commands.description': '리플 추론 강도, 워커, 캐시, 대화 관리',
937  'commands.argumentHint': 'settings|setup|auto|warm|save|stats|debug|agents|log|bar|cold|swamp|hot|down|kept',
938  'commands.logDescription': '리플 요청 로그 열기/닫기',
939  'commands.barDescription': '리플 상태 바 표시/숨기기',
940  'commands.logTitle': 'ClaudeRipple',
941  'commands.agentsTitle': '리플 에이전트',
942  'commands.help': '리플 명령: settings, setup, auto, warm, save, stats, debug, agents, log, bar, cold, swamp, hot, down, kept.',
943  'commands.done': '리플: {command} 완료.',
944  'commands.logOpened': '리플 로그를 열었습니다.',
945  'commands.logClosed': '리플 로그를 닫았습니다.',
946  'commands.barShown': '입력창 위에 리플 상태 바를 표시합니다.',
947  'commands.barShownMinimal': '배치가 한 줄로 설정되어 있어 입력창 아래에 리플을 표시합니다. 입력창 위에 상태 바를 보려면 /ripple settings에서 배치를 대시보드로 바꾸면 됩니다.',
948  'commands.barHidden': '리플 상태 바를 숨겼습니다. /ripple-bar로 다시 표시합니다.',
949  'commands.statsAuto': '자동: 프롬프트 {prompts}개, 요청 {requests}개, 환산 토큰 {total}',
950  'commands.statsTokens': '토큰: 입력 {input}, 쓰기 {write}, 읽기 {read}, 출력 {output}',
951  'commands.statsEffort': '{effort} 프롬프트 {prompts}개 / 환산 토큰 {cost}',
952  'commands.statsJudges': '판정 모델: Haiku {haiku}, Jev {jev}, 모델 {model}; 토큰 {tokens}, {ms} ms (평균 {avg} ms)',
953  'commands.statsWorkers': '워커: {workers}',
954  'commands.statsWarm': '캐시 유지: 유지 요청 {pings}회, 환산 토큰 {cost}',
955  'commands.debugJudge': '판정 모델',
956  'commands.debugJudgeModel': '판정용 리플 모델',
957  'commands.debugPick': '선택',
958  'commands.debugPaused': '일시 중지',
959  'commands.debugCache': '캐시',
960  'commands.debugWarm': '캐시 유지',
961  'commands.debugLastSpawn': '최근 워커 실행',
962  'commands.debugLastRequest': '최근 요청',
963  'commands.debugEffort': '추론 강도',
964  'commands.debugWhy': '이유',
965  'commands.debugBy': '선택 기준',
966  'commands.debugAt': '시각',
967  'commands.debugSure': '확신도',
968  'commands.debugTtlMs': '유효 시간(ms)',
969  'commands.debugLastReplyAt': '최근 응답 시각',
970  'commands.debugExpiresAt': '만료 시각',
971  'commands.debugPings': '유지 요청 횟수',
972  'commands.debugCost': '비용',
973  'commands.debugStopped': '중단 이유',
974  'commands.debugLastPingAt': '최근 유지 요청 시각',
975  'commands.debugTier': '등급',
976  'commands.debugTarget': '대상',
977  'commands.debugAgent': '에이전트',
978  'commands.debugModel': '모델',
979  'commands.debugMs': 'ms',
980  'commands.debugFallbackReason': '대체 이유',
981  'commands.debugAppEffort': '앱 추론 강도',
982  'commands.debugSentEffort': '요청에 쓴 추론 강도',
983  'commands.debugLog': '리플 {where}: {reason}',
984  'commands.routerHttp': '리플 HTTP {status}',
985  'commands.compactSkip': '대화 압축이 필요하면 리플이 Haiku로 요약합니다.',
986  // Workers card, Jev source, and worker picks in the Agents pane.
987  'workers.previous': '이전',
988  'workers.next': '다음',
989  'workers.page': '{page} / {pages}페이지',
990  'workers.general': '일반',
991  'workers.design': '디자인',
992  'workers.frontend': '프론트엔드',
993  'workers.backend': '백엔드',
994  'workers.infra': '인프라',
995  'workers.data': '데이터',
996  'workers.test': '테스트',
997  'workers.docs': '문서',
998  'workers.research': '조사',
999  'workers.mode': '모드',
1000  'workers.rung.light': '기본 워커',
1001  'workers.rung.standard': '표준 워커',
1002  'workers.rung.hard': '고급 워커',
1003  'workers.rung.plan': '최상위 워커',
1004  'workers.rungHint.light': '파일 찾기, 간단한 조회, 로그 훑기, 반복 수정',
1005  'workers.rungHint.standard': '요구사항에 따른 구현, 코드 정리, 요약, 초안 작성',
1006  'workers.rungHint.hard': '어려운 오류 해결, 여러 파일 수정, 별도 검토와 반박',
1007  'workers.rungHint.plan': '최상의 결과: 기획, 설계, 전체 구조 설계, 의견 제시',
1008  'workers.rungEmpty': '{rung}에 지정한 모델이 없습니다',
1009  'workers.notCandidate': '{name}: 이 분야의 후보 모델이 아닙니다',
1010  'workers.sessionModel': '현재 대화 모델',
1011  'workers.offset': '추론 강도 조정',
1012  'workers.anyEffort': '모든 추론 강도',
1013  'workers.noTarget': '다음 단계 / 대체 워커',
1014  'workers.judgeBlurb': '프롬프트의 추론 강도와 작업의 분야·등급을 고르는 모델입니다.',
1015  'workers.disabled': '{provider} 꺼짐',
1016  'workers.nested': '서브에이전트는 다른 서브에이전트를 띄울 수 없습니다. 이 작업은 직접 마친 뒤 결과를 보고해야 합니다.',
1017  'workers.none': '실행할 수 있는 워커 없음',
1018  'workers.noReason': '{name} 모델을 지정한 근거가 없습니다. 둘째 줄에 "Model reason: user \\"사용자가 한 말 그대로\\"" 또는 "Model reason: rule <파일> — <규칙>"을 적어 주세요. 근거가 없으면 모델 표식을 빼고 등급만 적어 주세요.',
1019  'workers.notSaid': '{name} 모델의 근거로 든 말이 사용자의 최근 메시지에 없습니다. 사용자가 실제로 한 말을 그대로 인용하거나, 모델 표식을 빼고 등급만 적어 주세요.',
1020  'workers.unknownModel': '{name} 모델은 이 컴퓨터에서 실행할 수 없습니다. 워커 에이전트 이름이나 opus·sonnet·haiku 중 하나로 지정해 주세요.',
1021  'workers.namedUnavailable': '{name} 모델을 지금 실행할 수 없습니다',
1022  'workers.ladderEmpty': '이 등급에서 지금 실행할 수 있는 워커가 없습니다({reason}). 대시보드에서 워커 사다리를 확인해 주세요.',
1023  'workers.loading': '리플의 워커 목록을 불러오는 중…',
1024  'workers.providerSub': '{count}개 중 {on}개 켜짐',
1025  'workers.fallbackHint': '지정한 워커를 실행할 수 없을 때',
1026  'workers.pinDetails': '추가 설정',
1027  'workers.back': '뒤로',
1028  'settings.ladderWaiting': '리플의 모델 목록을 기다리고 있습니다.',
1029  'jev.zenMissing': '리플 설정에 OpenCode Zen 인증 키가 없습니다',
1030  'agents.domainLevel': '{domain} / {level}',
1031  'agents.title': '에이전트',
1032  'agents.total': '전체 에이전트',
1033  'agents.tokens': '토큰',
1034  'agents.cache': '캐시',
1035  'agents.toolsLabel': '도구',
1036  'agents.failed': '실패',
1037  'agents.stopped': '중지됨',
1038  'agents.shell': '명령',
1039  'agents.monitor': '모니터',
1040  'agents.exitCode': '종료 코드 {code}',
1041  'agents.more': '{count}개 더 보기',
1042  'agents.less': '접기',
1043  'agents.open': '대화 보기',
1044  'agents.back': '목록으로',
1045  'agents.task': '작업 지시',
1046  'agents.answer': '최종 답변',
1047  'agents.dropped': '너무 길어 앞의 {count}개는 생략했습니다',
1048  'agents.act.command': '실행됨 명령 {count}개',
1049  'agents.act.commandOne': '실행됨 명령 1개',
1050  'agents.act.read': '읽음 파일 {count}개',
1051  'agents.act.readOne': '읽음 파일 1개',
1052  'agents.act.write': '생성됨 파일 {count}개',
1053  'agents.act.writeOne': '생성됨 파일 1개',
1054  'agents.act.edit': '편집함 파일 {count}개',
1055  'agents.act.editOne': '편집함 파일 1개',
1056  'agents.act.notebook': '편집함 노트북 {count}개',
1057  'agents.act.notebookOne': '편집함 노트북 1개',
1058  'agents.act.grep': '검색함 코드',
1059  'agents.act.glob': '찾음 파일',
1060  'agents.act.browse': '탐색함 웹',
1061  'agents.act.fetch': '가져옴 페이지 {count}개',
1062  'agents.act.fetchOne': '가져옴 페이지 1개',
1063  'agents.act.agent': '실행됨 에이전트 {count}개',
1064  'agents.act.agentOne': '실행됨 에이전트 1개',
1065  'agents.act.todo': '업데이트됨 할 일',
1066  'agents.act.other': '사용함 도구 {count}개',
1067  'agents.act.otherOne': '사용함 도구 1개',
1068  'agents.act.failed': '{count}개 실패',
1069  'agents.showMore': '더 보기',
1070  'agents.showLess': '접기',
1071  'agents.working': '작업 중',
1072  'agents.diff': '{added}줄 추가, {removed}줄 삭제',
1073  'agents.running': '실행 중',
1074  'agents.finished': '완료 {count}',
1075  'agents.deny': '이 에이전트의 대화를 읽을 수 없습니다: {reason}',
1076  'agents.gone': '이 에이전트는 더는 목록에 없습니다.',
1077  'agents.nothingYet': '아직 대화 내용이 없습니다.',
1078  // Context pane (the band's context chip opens it).
1079  'commands.contextTitle': '리플 컨텍스트',
1080  'commands.limitsTitle': '리플 한도',
1081  'band.contextOpen': '{tokens} / {window} 토큰 · 눌러서 자세히 보기',
1082  'context.title': '컨텍스트 구성',
1083  'context.of': '/ {max} 토큰',
1084  'context.estimate': '로컬 추정치',
1085  'context.precise': '토큰 계산 API 기준',
1086  'context.refresh': '정밀 계산',
1087  'context.refreshing': '계산 중…',
1088  'context.refreshAgain': '다시 계산',
1089  'context.failed': '정밀 계산에 실패했습니다: {reason}',
1090  'context.byCategory': '분류별 사용량',
1091  'context.notCounted': '합계 제외',
1092  'context.none': '아직 컨텍스트 구성을 확인할 수 없습니다.',
1093  'context.cat.systemPrompt': '시스템 프롬프트',
1094  'context.cat.systemTools': '시스템 도구',
1095  'context.cat.systemDeferred': '시스템 도구 (필요 시 로드)',
1096  'context.cat.mcpTools': 'MCP 도구',
1097  'context.cat.mcpDeferred': 'MCP 도구 (필요 시 로드)',
1098  'context.cat.mcpInstructions': 'MCP 서버 지침',
1099  'context.cat.agents': '사용자 지정 에이전트',
1100  'context.cat.memory': '메모리 파일',
1101  'context.cat.skills': '스킬',
1102  'context.cat.messages': '메시지',
1103  'context.cat.free': '남은 공간',
1104  'context.cat.buffer': '자동 압축 예비 공간',
1105  'context.cat.compactBuffer': '압축 예비 공간',
1106  'context.src.project': '프로젝트',
1107  'context.src.user': '사용자',
1108  'context.src.local': '로컬',
1109  'context.src.managed': '관리형',
1110  'context.src.automem': '자동 메모리',
1111  'context.src.plugin': '플러그인',
1112  'context.src.builtin': '기본 제공',
1113  'context.src.mcp': 'MCP',
1114  'context.src.synced': '동기화됨',
1115  'context.memory': '메모리 파일',
1116  'context.mcp': 'MCP 도구',
1117  'context.skills': '스킬',
1118  'context.agents': '사용자 지정 에이전트',
1119  'context.count': '{count}개',
1120  'context.tools': '도구 {count}개',
1121  'context.toolsDeferred': '도구 {count}개 · 필요 시 로드 {deferred}개',
1122  'context.servers': '서버 {count}개 · 도구 {tools}개',
1123  'context.skillsOf': '전체 {total}개 중 {included}개 포함',
1124  'context.autoAt': '자동 압축은 {tokens} 토큰에서 실행됩니다.',
1125  'context.autoOn': '자동 압축이 켜져 있습니다.',
1126  'context.autoOff': '자동 압축이 꺼져 있습니다.',
1127  'context.commands': '슬래시 명령어는 전체 {total}개 중 {included}개가 포함되어 {tokens} 토큰을 차지합니다.',
1128  // Time units: countdowns, reset times, durations.
1129  'units.seconds': '{n}초',
1130  'units.minutes': '{n}분',
1131  'units.hours': '{n}시간',
1132  'units.days': '{n}일',
1133  'units.minSec': '{m}분 {s}초',
1134  'units.hourMin': '{h}시간 {m}분',
1135  'units.weekdaySun': '일',
1136  'units.weekdayMon': '월',
1137  'units.weekdayTue': '화',
1138  'units.weekdayWed': '수',
1139  'units.weekdayThu': '목',
1140  'units.weekdayFri': '금',
1141  'units.weekdaySat': '토',
1142}
1143
1144const ZH: Record<Key, string> = {
1145  // Band (including shared display labels and accessibility text).
1146  'band.brand': 'ClaudeRipple',
1147  'band.effort': '推理强度',
1148  'band.model': '模型',
1149  'band.auto': '自动',
1150  'band.manual': '手动',
1151  'band.paused': '已暂停',
1152  'band.off': '关闭',
1153  'band.on': '开启',
1154  'band.autoOff': '自动模式关闭',
1155  'band.autoPaused': '自动模式已暂停',
1156  'band.deciding': '判定中…',
1157  'band.decidingText': '◌ 判定中…',
1158  'band.low': '低',
1159  'band.medium': '中',
1160  'band.high': '高',
1161  'band.xhigh': '超高',
1162  'band.max': '最高',
1163  'band.pausedHint': '此模型上自动模式已暂停:尚不确定在此模型上切换推理强度能否保住缓存。',
1164  'band.offHint': '自动模式已关闭,推理强度由你决定。',
1165  'band.decidingHint': '判定模型正在为这条提示词选择推理强度。',
1166  'band.effortTitle': '推理强度 {value}{hint} · 点击选择推理强度',
1167  'band.effortAlt': '推理强度 {value}({mode}){why}',
1168  'band.context': '上下文',
1169  'band.contextAlt': '上下文 {value},共 {window}({tokens} token)',
1170  'band.cache': '缓存',
1171  'band.cacheWarm': '缓存 · 保温中',
1172  'band.cacheStopped': '缓存 · 保温已停',
1173  'band.cold': '已过期',
1174  'band.cacheTip': '提示词缓存{state}{warm}',
1175  'band.warmFor': '{time}后过期',
1176  'band.expired': '已过期',
1177  'band.warmStoppedTip': ' · 保温已停止:{reason}',
1178  'band.warmOnTip': ' · 保温开启,已 ping {count} 次',
1179  'band.noReply': '尚无回复',
1180  'band.cacheAlt': '缓存{state}{warm}',
1181  'band.timeLeft': '剩余 {time}',
1182  'band.unknown': '未知',
1183  'band.keepWarmAlt': ',保温开启{count}',
1184  'band.limitCaption': '{window}限额{save}',
1185  'band.saveCaption': ' · 节省',
1186  'band.limitAlt': '{window}限额 {value}{reset}',
1187  'band.limitsTip': '{provider} {window} {value}{reset}',
1188  'band.fiveHour': '5 小时',
1189  'band.weekly': '每周',
1190  'band.resetting': '重置中',
1191  'band.resetsIn': '{time}后重置',
1192  'band.resetsAt': '{time} 重置',
1193  'band.resetIn': '{time}后',
1194  'band.resetDay': '{day} {time}',
1195  'band.router': '路由服务',
1196  'band.routerAlt': '路由服务:{value}',
1197  'band.resentCaption': '已重发 · {status}',
1198  'band.failedCaption': '失败 · {status}',
1199  'band.lastRoute': '最近路由',
1200  'band.logHint': '点击查看请求日志',
hooks/judge.ts 209 lines
1import type { Effort, JudgeInput, Pick, Settings, Verdict } from '../types'
2import { t } from './i18n.ts'
3import type { Lang } from './i18n.ts'
4
5const EFFORTS: readonly Effort[] = ['low', 'medium', 'high', 'xhigh', 'max']
6
7// "xhigh for unusually difficult investigation, max only for the hardest open-ended problems" left
8// a medium..max range at medium and high: 10-13..10-17 ran ~9,000 Opus requests with no max and 91
9// xhigh, and Jev gave an architecture redesign 2% max (2026-10-19). Above high is now named by
10// what hinges on judgment, so important plans and failed attempts can reach it.
11export const EFFORT_JUDGE_SYSTEM = `Choose the reasoning effort this work deserves. This is a coding agent able to inspect files, run commands, and edit code, not merely answer a chat question.
12Assess work volume, uncertainty, and the cost of mistakes, not message length. A short choice approving a build inherits the size of that build. Closing remarks need little effort. "Think hard" or thorough reasoning requires at least high; an explicit quick answer calls for low.
13Low and medium are only for turns that need no judgment: low for chit-chat, thanks, or a direct answer needing no inspection; medium for one fully specified, low-risk step the user spelled out (run this command, rename this). Ordinary coding that asks the agent to decide, explain why, review, verify, debug with a known direction, delegate, or change more than one thing is high.
14Go above high when the outcome hinges on judgment rather than labor. xhigh: debugging whose cause is unknown, changes across interacting modules, or planning a feature. max: decisions that shape the product or system (architecture, an important plan or strategy, a design meant to last), work where a wrong call risks security, money, or data loss, and problems that earlier attempts in this conversation failed to solve. Not every plan is max; a small or routine plan is high or xhigh.
15When the user says the previous attempt failed, is wrong, or still does not work, choose at least one level above the running effort. Other corrections and steering keep at least the running effort. Consider the current model's strength.
16Return only JSON {"effort":"low|medium|high|xhigh|max","sure":0.0,"why":"short reason"}. Confidence is between zero and one. The reason uses the user's language and at most six words.`
17
18/** A terse continuation usually carries no new scope; answers to questions are handled separately. */
19export function isShortFollowUp(text: string): boolean {
20  const trimmed = text.trim()
21  return trimmed.length > 0 && trimmed.length <= 12 && trimmed.split(/\s+/).length <= 2
22}
23
24/** "Still broken" is short but asks for more thought, so it is judged rather than inheriting the effort that failed. */
25export function looksLikeRetry(text: string): boolean {
26  return /안\s*[돼되]|다시|틀렸|아직|여전|그대로|실패|\bstill\b|\bagain\b|\bwrong\b|\bbroken\b|n['’]?t work|\bfail/i.test(text)
27}
28
29export function looksLikeQuestion(assistantTail: string): boolean {
30  return assistantTail.slice(-400).includes('?')
31}
32
33/** The caller resolves slash commands so skills can be judged while host commands stay untouched. */
34export function shouldJudge(input: {
35  text: string; origin: string; auto: boolean; hostCommand?: boolean; modelId?: string
36  attachments?: readonly { type: string }[]; current?: Pick | null; assistantTail?: string
37}): boolean {
38  if (!input.auto || !['composer', 'bridge', 'sdk'].includes(input.origin) || (!input.text.trim() && !input.attachments?.length) || input.hostCommand) return false
39  if (input.modelId !== undefined && !isCacheSafeModel(input.modelId)) return false
40  const followup = input.current && input.current.by !== 'manual' && !input.text.trim().startsWith('/') &&
41    !input.attachments?.length && isShortFollowUp(input.text) && !looksLikeRetry(input.text) && !looksLikeQuestion(input.assistantTail ?? '')
42  return !followup
43}
44
45function recent(input: JudgeInput): string {
46  const user = input.messages.findLast(message => message.role === 'user' && message.text.trim())
47  const assistant = input.messages.findLast(message => message.role === 'assistant' && message.text.trim())
48  return [user && `user: ${user.text.slice(0, 400)}`, assistant && `assistant: ${assistant.text.slice(-2000)}`].filter(Boolean).join('\n')
49}
50
51function nextText(input: JudgeInput, limit: number): string {
52  const counts: Record<string, number> = {}
53  for (const attachment of input.attachments ?? []) counts[attachment.type] = (counts[attachment.type] ?? 0) + 1
54  const attachments = Object.entries(counts).map(([type, count]) => `${type}: ${count}`).join(', ')
55  return [input.next.slice(0, limit), attachments && `Attachments (${attachments}).`,
56    input.midTurn && 'Steering a running turn: keep its effort for corrections and additions.'].filter(Boolean).join('\n')
57}
58
59/** Keep options in the assistant tail, since a one-letter answer may approve substantial work. */
60export function judgeContext(input: JudgeInput): string {
61  return [
62    `Current: ${input.current?.model ?? 'unknown'} / ${input.current?.effort ?? 'medium'}`,
63    recent(input) && `Recent conversation:\n${recent(input)}`,
64    input.contextPercent !== undefined && Number.isFinite(input.contextPercent) && `Context: ${Math.round(input.contextPercent)}%`,
65    `Next message:\n${nextText(input, 2000)}`,
66  ].filter(Boolean).join('\n\n')
67}
68
69function record(value: unknown): Record<string, unknown> | undefined {
70  return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : undefined
71}
72
73function confidence(value: unknown): number | undefined {
74  return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1 ? value : undefined
75}
76
77function effort(value: unknown): Effort | undefined {
78  return EFFORTS.includes(value as Effort) ? value as Effort : undefined
79}
80
81/** JSON is a boundary: prose and fences are harmless, malformed objects are not verdicts. */
82export function parseEffortVerdict(text: string): Verdict | undefined {
83  const value = verdictObject(text)
84  const level = effort(value?.effort)
85  if (!level) return undefined
86  const sure = confidence(value?.sure)
87  return { effort: level, ...(sure !== undefined ? { sure } : {}), why: typeof value?.why === 'string' ? value.why.slice(0, 60) : '' }
88}
89
90/** Shared boundary decoder keeps effort and worker fields on the same object. */
91export function verdictObject(text: string): Record<string, unknown> | undefined {
92  for (let start = text.indexOf('{'); start !== -1; start = text.indexOf('{', start + 1)) {
93    for (let end = text.lastIndexOf('}'); end > start; end = text.lastIndexOf('}', end - 1)) {
94      try {
95        const value: unknown = JSON.parse(text.slice(start, end + 1))
96        const parsed = record(value)
97        if (parsed) return parsed
98      } catch {
99        // Try a smaller span: a judge can put braces in its surrounding prose.
100      }
101    }
102  }
103  return looseVerdictObject(text)
104}
105
106/**
107 * A small judge sometimes breaks its JSON (Haiku answered `…"why":"…","}`, #53). Its complete
108 * `"key": value` pairs still carry the verdict, so they are read one by one; the parsers above
109 * check every field they use, so nothing here is trusted beyond a JSON scalar.
110 */
111function looseVerdictObject(text: string): Record<string, unknown> | undefined {
112  const start = text.indexOf('{')
113  if (start === -1) return undefined
114  const value: Record<string, unknown> = {}
115  const pair = /"(\w+)"\s*:\s*("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|true|false|null)/g
116  for (const match of text.slice(start).matchAll(pair)) {
117    try { value[match[1]!] ??= JSON.parse(match[2]!) } catch { /* a malformed scalar adds nothing */ }
118  }
119  return Object.keys(value).length ? value : undefined
120}
121
122const effortCriteria = {
123  low: 'Chit-chat, thanks, or a direct answer needing no inspection.',
124  medium: 'One fully specified, low-risk step the user spelled out.',
125  high: 'Ordinary coding: implement, fix, review, or debug with a known direction.',
126  xhigh: 'Debugging with an unknown cause, changes across interacting modules, or planning a feature.',
127  max: 'Product or architecture decisions, important plans or strategy, security or data-loss risk, or a problem earlier attempts failed to solve.',
128}
129function jevBody(input: JudgeInput, task: string) {
130  return {
131    model: 'jev-latest' as const,
132    state: { task, current_model: input.current?.model ?? null, current_effort: input.current?.effort ?? null,
133      recent_conversation: recent(input), next_message: nextText(input, 4000) },
134    questions: { effort: { type: 'choice' as const, instructions: 'Select the effort needed for this work.', criteria: { ...effortCriteria } } },
135  }
136}
137
138export function jevEffortRequest(input: JudgeInput) {
139  return jevBody(input, EFFORT_JUDGE_SYSTEM)
140}
141
142function answers(json: unknown): Record<string, unknown> | undefined {
143  const root = record(json)
144  return record(root?.answers) ?? record(record(root?.result)?.answers)
145}
146
147function answerSure(answer: Record<string, unknown>): number | undefined {
148  return confidence(answer.confidence ?? record(answer.probabilities)?.[String(answer.choice)])
149}
150
151/** Torn between levels, Jev leaves a session at the effort it runs when that effort is still a plausible answer. */
152export function parseJevEffort(json: unknown, current?: { effort: Effort } | null, lang: Lang = 'en'): Verdict | undefined {
153  const answer = record(answers(json)?.effort)
154  const level = effort(answer?.choice)
155  if (!answer || !level) return undefined
156  const sure = answerSure(answer)
157  const odds = record(answer.probabilities)
158  const plausible = current && (!odds || (confidence(odds[current.effort]) ?? 0) >= 0.25)
159  if (sure !== undefined && sure < 0.5 && current && current.effort !== level && plausible) return { effort: current.effort, sure, why: t(lang, 'judge.keptUnsure') }
160  return { effort: level, ...(sure !== undefined ? { sure } : {}), why: '' }
161}
162
163export function jevUsage(json: unknown): number {
164  const usage = record(record(json)?.usage)
165  return [usage?.input_tokens, usage?.output_tokens].reduce<number>((sum, count) => sum + (typeof count === 'number' && Number.isFinite(count) && count >= 0 ? count : 0), 0)
166}
167
168export function jevFailure(status: number | 'timeout' | 'network', lang: Lang = 'en'): string {
169  if (status === 401 || status === 403) return t(lang, 'toasts.jevRejected')
170  if (status === 402) return t(lang, 'toasts.jevCredits')
171  if (status === 429) return t(lang, 'toasts.jevRateLimited')
172  if (status === 'timeout') return t(lang, 'toasts.jevTimeout')
173  if (status === 'network') return t(lang, 'toasts.jevNetwork')
174  return t(lang, 'toasts.jevHttp', { status })
175}
176
177export function parseJevKey(fileText: string): string | undefined {
178  const value = /^[ \t]*TYPESAFE_API_KEY[ \t]*=[ \t]*([^\r\n]*)/m.exec(fileText)?.[1]?.trim()
179  if (!value) return undefined
180  const unquoted = ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) ? value.slice(1, -1).trim() : value
181  return unquoted || undefined
182}
183
184export function tipped(level: Effort, sure: number | undefined, bias: Settings['bias']): Effort {
185  if (!bias || sure === undefined || !Number.isFinite(sure) || sure < 0 || sure >= (Math.abs(bias) === 2 ? 0.85 : 0.65)) return level
186  return EFFORTS[Math.max(0, Math.min(4, EFFORTS.indexOf(level) + Math.sign(bias)))]!
187}
188
189export function bounded(level: Effort, floor: Effort, ceiling: Effort): Effort {
190  const min = EFFORTS.indexOf(floor)
191  const max = Math.max(min, EFFORTS.indexOf(ceiling))
192  return EFFORTS[Math.max(min, Math.min(max, EFFORTS.indexOf(level)))]!
193}
194
195export function capped(level: Effort, saving: boolean): Effort {
196  return saving && EFFORTS.indexOf(level) > 1 ? 'medium' : level
197}
198
199/** Save is last, so even a high floor cannot defeat the subscription-saving cap. */
200export function finalEffort(verdict: Verdict, settings: Settings, saving: boolean, lang: Lang = 'en'): { effort: Effort; why: string } {
201  const adjusted = bounded(tipped(verdict.effort, verdict.sure, settings.bias), settings.floor, settings.ceiling)
202  const result = capped(adjusted, saving)
203  return { effort: result, why: result !== adjusted ? t(lang, 'toasts.saveMode') : adjusted !== verdict.effort ? t(lang, 'toasts.yourSettings') : verdict.why }
204}
205
206export function isCacheSafeModel(modelId: string): boolean {
207  return /(?:opus|sonnet|haiku)-5-5(?:$|[^\d])/.test(modelId)
208}
209
hooks/workers.ts 331 lines
1import type { Billing, Domain, Effort, LadderChoice, LadderOptions, ModelScore, ProviderAvailability, RouterModel, Rule, Rung, Settings, TierTarget, WorkerCandidate, WorkerPick, WorkerVerdict } from '../types'
2import { CLAUDE_WORKERS, EFFORTS, candidateKey, isAllowed } from './settings'
3import { MARKER, providerModelId } from './worker'
4import { t } from './i18n'
5import type { Lang } from './i18n'
6import { claudeChoices, rungAbove, rungOf, tickedChoices } from './ladder'
7
8/** The one agent the main chat delegates to (docs/specs/2026-10-12-worker-tiers.md). */
9// The description line: a chat that had seen other workers' "Sol·high · " titles wrote one here
10// too, and the app's running-agent row showed "Sol·high" while Sonnet ran (2026-10-22). The row
11// shows the call as written; only the task list gets the mod's corrected title.
12//
13// Who names the worker's model changed three times in two days (4000c3f, 28ae836, e9876fc). The
14// session guessed models from earlier tasks; then the worker judge, reading a few messages, gave a
15// render step's "딥시크" to the translation before it and could not see the written rule that
16// translation runs on Opus (2026-10-24). Now the session, which sees the whole conversation, names
17// the domain and rung; the owner's ladder names the model; a model is named only with its source,
18// which the mod checks but never re-reads as language. A wrong call is fixed in the criteria or the
19// review, not by moving the decision again.
20export const AUTO_DESCRIPTION = 'Delegate tasks here. Put the tier, and a domain word when it applies, on the prompt\'s first line: ' +
21  '[[ripple: light]], [[ripple: standard]], [[ripple: hard]] or [[ripple: max]]; light = lookups, mechanical edits, one small fix; ' +
22  'standard = carry out a designed change (even across several files), research, summarize, read-only review; ' +
23  'hard = subtle debugging, security review, or work where a wrong call is costly; max = planning or architecture where the deliverable is the decision itself. ' +
24  'Size, file count or the brief\'s warnings do not by themselves make a task hard. Add ui only when the work needs visual judgment: visual design, a new screen\'s layout, or UX decisions, as in [[ripple: standard ui]]; ' +
25  'restoring, porting, wiring or translating existing UI code takes no domain word. Add backend for server, API or database work. ' +
26  'With no marker the task runs as general standard. The owner\'s ladder picks the model for the tier. ' +
27  'Name a model instead only when the user asked for it for this task, or a written rule (CLAUDE.md, a memory file) assigns it to this step: ' +
28  'put [[ripple: <worker agent name or opus/sonnet/haiku>@<effort>]] on the first line and on the second line "Model reason: user \\"<the user\'s exact words>\\"" or "Model reason: rule <file> — <the rule>". ' +
29  'A model without a reason, or a quote the user did not say, is refused; never carry a model over from an earlier task. A standing pin the user set ("앞으로 솔로") is applied for you. ' +
30  'Write the Agent description as the task alone, with no model or effort in front. If an attempt failed, say so when delegating again. ' +
31  'A brief states the scope, what must not be touched, the done criteria and how to verify them. Read the report for whether it did what was asked before using it. ' +
32  'Continue a worker with SendMessage only within 5 minutes of its last reply; later start a new one with a summary of what is done and what is left.'
33
34/** The tier markers the session writes on a ripple:auto prompt, as the verdict they stand for (`rungOf` gives the rung). */
35export const TIER_MARKERS: Readonly<Record<string, Pick<WorkerVerdict, 'level' | 'kind'>>> = {
36  light: { level: 'light', kind: 'do' },
37  standard: { level: 'standard', kind: 'do' },
38  hard: { level: 'deep', kind: 'do' },
39  max: { level: 'deep', kind: 'plan' },
40}
41/** The tier a marker names, if it is one. */
42export function tierOf(marker: { name: string } | null): string | null {
43  return marker && Object.hasOwn(TIER_MARKERS, marker.name) ? marker.name : null
44}
45
46export function readMarker(prompt: string): { name: string; level?: string; domain?: string } | null {
47  const marker = MARKER.exec(prompt)
48  return marker ? { name: marker[1]!.toLowerCase(), ...(marker[2] ? { level: marker[2].toLowerCase() } : {}), ...(marker[3] ? { domain: marker[3].toLowerCase() } : {}) } : null
49}
50
51/** The line that says where a named model comes from: the user's words for this task, or a written rule. */
52const REASON = /^[ \t]*model reason[ \t]*:[ \t]*(user|rule)\b[ \t]*(.*)$/im
53export type ModelReason = { source: 'user' | 'rule'; text: string; quote?: string }
54export function modelReason(prompt: string): ModelReason | null {
55  const line = REASON.exec(prompt)
56  if (!line) return null
57  const text = line[2]!.trim()
58  const pair = /"([^"]+)"|“([^”]+)”|「([^」]+)」|『([^』]+)』/.exec(text)
59  const quote = pair?.slice(1).find(Boolean)?.trim()
60  return { source: line[1]!.toLowerCase() as ModelReason['source'], text, ...(quote ? { quote } : {}) }
61}
62/**
63 * A rule reason's minimal form: a concrete file identifier first and a non-empty rule after it
64 * ("memory/translation.md — draft translations run on Opus"). It reads the line's shape only —
65 * never whether the file exists or what it says. An empty "Model reason: rule" used to pass and
66 * named a model with no source at all (2026-10-25).
67 */
68export function ruleReason(text: string): boolean {
69  const trimmed = text.trim()
70  const at = trimmed.search(/\s/)
71  if (at <= 0) return false
72  const file = trimmed.slice(0, at).replace(/[,;]+$/, '')
73  // A path segment or an extension: "memory/x.md", "docs/specs/a.md", "C:\rules\x.md".
74  if (!/[/\\]|\.[A-Za-z0-9]{1,8}$/.test(file)) return false
75  // " — ", " - ", ": " or a plain space; the rule itself must hold something.
76  return trimmed.slice(at).replace(/^\s*[—–:,-]\s*/, '').trim().length > 0
77}
78/** A prompt without its model-reason line, which is for the mod only. */
79export function withoutReason(prompt: string): string {
80  return prompt.replace(new RegExp(REASON.source + '\\n?', 'gim'), '').replace(/^\s*\n/, '')
81}
82/** The prompt a routed worker reads: no routing marker, no model-reason line. */
83export function withoutRouting(prompt: string): string {
84  return withoutReason(prompt.replace(new RegExp(MARKER.source, 'gi'), ''))
85}
86/**
87 * Whether the user said these words: whitespace and case aside, inside one of their own messages.
88 * A check of the session's claim, not a reading of what the user meant; a word or two ("솔") could
89 * be found anywhere, so a quote is at least three letters.
90 */
91export function userSaid(quote: string, words: readonly string[]): boolean {
92  const flat = (text: string) => text.replace(/\s+/g, ' ').trim().toLowerCase()
93  const wanted = flat(quote)
94  return wanted.replace(/ /g, '').length >= 3 && words.some(text => flat(text).includes(wanted))
95}
96
97/** The domain a tier marker names, as the verdict domain its ladder reads. No word: general. */
98export function markerDomain(word: string | undefined): Domain {
99  return word === 'ui' || word === 'frontend' ? 'frontend' : word === 'design' ? 'design' : word === 'backend' || word === 'server' ? 'backend' : 'general'
100}
101export function agentProvider(agentFileText: string): string | undefined {
102  const head = /^---\r?\n([\s\S]*?)\r?\n---/.exec(agentFileText)?.[1]
103  const description = head && /^description:\s*(.*)$/m.exec(head)?.[1]
104  return description ? /\bvia\s+([A-Za-z0-9_-]+)\./.exec(description)?.[1]?.toLowerCase() : undefined
105}
106function record(value: unknown): Record<string, unknown> {
107  return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}
108}
109function list(value: unknown): unknown[] { return Array.isArray(value) ? value : [] }
110const baseModel = (model: string): string => model.replace(/@[^@]*$/, '')
111
112/** Unknown availability is not exhaustion; known accounts must pass every quota window. */
113export function chatgptUsable(status: unknown): boolean {
114  const accounts = record(record(record(status).chatgpt).accounts).chatgpt
115  if (!Array.isArray(accounts)) return true
116  return accounts.some(value => {
117    const account = record(value)
118    if (account.state !== 'ready' || account.paused || account.needsReauth) return false
119    const limits = record(record(account.quota).rate_limits)
120    return ['primary', 'secondary'].every(name => {
121      const window = record(limits[name])
122      return typeof window.used_percent !== 'number' || window.used_percent < 100
123    })
124  })
125}
126/** Config is the router's catalogue, including native Anthropic declarations. Never retain headers. */
127export function routerModelOptions(config: unknown): RouterModel[] {
128  const out: RouterModel[] = []
129  for (const [provider, value] of Object.entries(record(record(config).providers))) {
130    for (const model of list(record(value).models)) {
131      const { id, name } = record(model)
132      if (typeof id === 'string' && id) out.push({ value: id, label: `${id} · ${provider}`, provider, ...(typeof name === 'string' && name.trim() ? { name } : {}) })
133    }
134  }
135  const counts = new Map<string, number>()
136  for (const model of out) counts.set(model.value, (counts.get(model.value) ?? 0) + 1)
137  return out.map(model => counts.get(model.value)! > 1 ? { ...model, value: `${model.provider}:${model.value}` } : model)
138}
139export function zenJev(config: unknown): { authorization?: string; model: string } {
140  const provider = record(record(record(config).providers)['opencode-zen'])
141  const key = record(provider.headers).authorization
142  const model = list(provider.models).map(m => record(m).id).find(id => typeof id === 'string' && id.toLowerCase().includes('jev'))
143  return { ...(typeof key === 'string' && key.trim() ? { authorization: key } : {}), model: typeof model === 'string' ? model : 'jev-latest' }
144}
145/** Validate HTTP score data at the boundary; malformed entries are not selectable measurements. */
146export function scoreModels(raw: unknown): ModelScore[] {
147  return list(record(raw).models).flatMap(value => {
148    const model = record(value)
149    if (typeof model.model !== 'string' || typeof model.provider !== 'string') return []
150    const variants = list(model.variants).flatMap(v => {
151      const variant = record(v)
152      if (variant.effort !== null && !EFFORTS.includes(variant.effort as Effort)) return []
153      const valid = (n: unknown): n is number | null => n === null || typeof n === 'number' && Number.isFinite(n) && n >= 0
154      if (!valid(variant.intelligence) || !valid(variant.costPerTask)) return []
155      return [{ effort: variant.effort as Effort | null, intelligence: variant.intelligence, costPerTask: variant.costPerTask }]
156    })
157    return [{ model: model.model, provider: model.provider, variants }]
158  })
159}
160/**
161 * Allow-lists name worker agents, and Claude's own models as `general-purpose:<model>`; provider
162 * names from settings saved before 2026-10-10 still match.
163 */
164export function allowed(candidate: WorkerCandidate, allow: readonly string[], known: readonly string[] = []): boolean {
165  return isAllowed(candidateKey(candidate.target), candidate.provider, allow, known)
166}
167/** Claude's own models as candidates: general-purpose on each. */
168export function claudeCandidates(): WorkerCandidate[] {
169  return CLAUDE_WORKERS.map(w => ({ target: { ...w.target }, model: w.model, provider: w.provider }))
170}
171const BILLINGS: readonly Billing[] = ['free', 'payg', 'subscription']
172/**
173 * The router's rung choices (GET /api/mod-options), validated at the boundary: its workers whose
174 * provider can run now, with ladders, billing and cheapest measured cost, then Claude's own
175 * models; only the ticked ones (`allow`, empty for every model).
176 */
177export function ladderOptionsFrom(raw: unknown, until: number, allow: readonly string[] = [], allowKnown: readonly string[] = []): LadderOptions {
178  const root = record(raw)
179  const efforts = (value: unknown): Effort[] => list(value).filter((e): e is Effort => EFFORTS.includes(e as Effort))
180  const usable = new Set(list(root.providers).flatMap(p => { const v = record(p); return typeof v.name === 'string' && v.usable !== false ? [v.name] : [] }))
181  const modelsOut = new Map(list(root.providers).flatMap(p => { const v = record(p); return typeof v.name === 'string' ? [[v.name, unavailableModels(v.models)] as const] : [] }))
182  const catalogue = list(root.providers).length > 0
183  const scores = scoreModels(root.scores)
184  const choices: LadderChoice[] = list(root.agents).flatMap(value => {
185    const a = record(value)
186    if (typeof a.name !== 'string' || !a.name || typeof a.model !== 'string' || typeof a.provider !== 'string') return []
187    if (catalogue && !usable.has(a.provider)) return []
188    if (modelsOut.get(a.provider)?.[baseModel(a.model)]) return []
189    const costs = (scores.find(s => s.model === a.model && s.provider === a.provider)?.variants ?? []).flatMap(v => v.costPerTask === null ? [] : [v.costPerTask])
190    const billing = BILLINGS.includes(a.billing as Billing) ? a.billing as Billing : 'payg'
191    return [{ target: { agent: a.name }, model: a.model, provider: a.provider, billing, efforts: efforts(a.efforts), ...(costs.length ? { cost: Math.min(...costs) } : {}) }]
192  })
193  const providers = Object.fromEntries(list(root.providers).flatMap(value => {
194    const p = record(value)
195    if (typeof p.name !== 'string' || typeof p.usable !== 'boolean') return []
196    const models = unavailableModels(p.models)
197    return [[p.name, { usable: p.usable, ...(typeof p.reason === 'string' ? { reason: p.reason } : {}), ...(typeof p.exhaustedUntil === 'number' ? { exhaustedUntil: p.exhaustedUntil } : {}), ...(Object.keys(models).length ? { models } : {}) }]]
198  }))
199  return { until, choices: tickedChoices([...choices, ...claudeChoices(efforts(root.claudeEfforts))], allow, allowKnown), providers }
200}
201/**
202 * A provider's models that are out while it answers others (GET /api/mod-options `models`): a spent
203 * Antigravity quota group takes its own models out, not the provider's other ones.
204 */
205function unavailableModels(value: unknown): NonNullable<ProviderAvailability['models']> {
206  return Object.fromEntries(Object.entries(record(value)).flatMap(([model, entry]) => {
207    const e = record(entry)
208    if (!model || entry === null || typeof entry !== 'object') return []
209    return [[model, { ...(typeof e.reason === 'string' ? { reason: e.reason } : {}), ...(typeof e.exhaustedUntil === 'number' ? { exhaustedUntil: e.exhaustedUntil } : {}) }]]
210  }))
211}
212/** Drop availability entries whose stated reset has passed: a cached catalogue must not outlive them. */
213export function liveProviders(providers: NonNullable<LadderOptions['providers']>, now: number): NonNullable<LadderOptions['providers']> {
214  return Object.fromEntries(Object.entries(providers).flatMap(([name, p]) => {
215    const models = Object.fromEntries(Object.entries(p.models ?? {}).filter(([, m]) => m.exhaustedUntil === undefined || m.exhaustedUntil > now))
216    const expired = p.exhaustedUntil !== undefined && p.exhaustedUntil <= now
217    // A provider-wide exhaustion that has reset drops the provider entry, but not a model still out.
218    if (expired && !Object.keys(models).length) return []
219    const { models: _, ...rest } = p
220    const base: ProviderAvailability = expired ? { usable: true } : rest
221    return [[name, Object.keys(models).length ? { ...base, models } : base]]
222  }))
223}
224/** A model out while its provider answers others (a spent quota group), by its id without `@effort`. */
225function modelOut(candidate: WorkerCandidate, providers: NonNullable<LadderOptions['providers']>): boolean {
226  return !!providers[candidate.provider]?.models?.[providerModelId(candidate.model, candidate.provider)]
227}
228export function candidateUsable(candidate: WorkerCandidate, settings: Settings, chatgpt: boolean, providers: NonNullable<LadderOptions['providers']> = {}): boolean {
229  const live = providers[candidate.provider]
230  if (modelOut(candidate, providers)) return false
231  return settings.providers[candidate.provider] !== false && (live ? live.usable : candidate.provider !== 'chatgpt' || chatgpt)
232}
233function unavailableReason(provider: string, providers: NonNullable<LadderOptions['providers']>, lang: Lang, model?: string): string {
234  const reason = model ? providers[provider]?.models?.[providerModelId(model, provider)]?.reason : providers[provider]?.reason
235  if (!reason && provider === 'chatgpt') return t(lang, 'toasts.providerQuota')
236  const labels: Record<string, string> = lang === 'ko'
237    ? { insufficient_balance: '잔액 부족', billing_exhausted: '결제 한도 소진', quota_exhausted: '사용량 한도 소진' }
238    : { insufficient_balance: 'insufficient balance', billing_exhausted: 'billing exhausted', quota_exhausted: 'quota exhausted' }
239  return `${provider}: ${reason && labels[reason] || (lang === 'ko' ? '현재 사용 불가' : 'currently unavailable')}`
240}
241function sameTarget(a: TierTarget, b: TierTarget): boolean { return a.agent === b.agent && a.model === b.model }
242function candidateOf(target: TierTarget, candidates: readonly WorkerCandidate[]): WorkerCandidate | undefined {
243  return candidates.find(c => sameTarget(c.target, target)) ?? (target.agent === 'general-purpose' ? { target, model: target.model ?? 'sonnet', provider: candidates.find(c => c.model === baseModel(target.model ?? 'sonnet'))?.provider ?? 'anthropic' } : undefined)
244}
245/** Domain overrides belong to the effective worker set; a missing override uses its general ladder. */
246export function workerRule(domain: Domain, settings: Settings): { rule: WorkerPick['rule']; ladder: Rule } {
247  const key = domain === 'design' || domain === 'frontend' ? 'ui' : domain === 'backend' ? 'backend' : 'general'
248  const ladder = key === 'general' ? undefined : settings.domainRules?.[key]
249  return ladder ? { rule: key, ladder } : { rule: 'general', ladder: settings.rules.general }
250}
251
252export type Resolution = { target?: TierTarget; effort: Effort; rung?: Rung; position?: number; skipped?: { rung: Rung; position: number; model: string; reason: string }[]; fallbackReason?: string }
253
254/**
255 * The ladder: the verdict's rung, else one rung up, never down. Whatever ran instead says why (the
256 * fallback toast). With nothing on either rung usable there is no target: the session's own model
257 * used to run it, an Opus the owner had put on no rung and was there to save (2026-10-24).
258 */
259export function ladderPick(verdict: WorkerVerdict, rule: Rule, settings: Settings, candidates: readonly WorkerCandidate[], chatgpt: boolean, lang: Lang, allow: readonly string[] = [], providers: NonNullable<LadderOptions['providers']> = {}, known: readonly string[] = []): Resolution {
260  const wanted = rungOf(verdict)
261  const skipped: NonNullable<Resolution['skipped']> = []
262  const reasons: string[] = []
263  for (const rung of [wanted, rungAbove(wanted)]) {
264    if (!rung) continue
265    const steps = rule.rungs[rung] ?? []
266    if (!steps.length) reasons.push(t(lang, 'workers.rungEmpty', { rung: t(lang, 'workers.rung.' + rung) }))
267    for (const [index, step] of steps.entries()) {
268      const target = step.target
269      const candidate = candidateOf(target, candidates)
270      const ticked = target.agent === 'general-purpose' && !target.model || candidate && allowed(candidate, allow, known)
271      if (candidate && candidateUsable(candidate, settings, chatgpt, providers) && ticked) {
272        return { target: { ...target }, effort: step.effort, rung, position: index + 1, skipped, ...(reasons.length ? { fallbackReason: reasons.join('; ') } : {}) }
273      }
274      const reason = !candidate ? t(lang, 'toasts.workerMissing', { name: target.agent }) : settings.providers[candidate.provider] === false ? t(lang, 'workers.disabled', { provider: candidate.provider }) : !ticked ? t(lang, 'workers.notCandidate', { name: candidate.model }) : providers[candidate.provider]?.usable === false ? unavailableReason(candidate.provider, providers, lang) : modelOut(candidate, providers) ? unavailableReason(candidate.provider, providers, lang, candidate.model) : t(lang, 'toasts.providerQuota')
275      const model = candidate?.model ?? target.model ?? target.agent
276      skipped.push({ rung, position: index + 1, model, reason })
277      reasons.push(`${model}: ${reason}`)
278    }
279  }
280  const effort = rule.rungs[wanted]?.[0]?.effort ?? verdict.effort
281  return { effort, rung: wanted, skipped, fallbackReason: reasons.join('; ') || t(lang, 'workers.none') }
282}
283
284export function spawnModel(target: TierTarget, effort: Effort, fileModel?: string): string | undefined {
285  return fileModel && target.agent !== 'general-purpose' ? `${baseModel(fileModel)}@${effort}` : target.model
286}
287/** A prefix this mod (or the retired agent-title hook) put on a title: "Sol·high · ". */
288const TITLE_PREFIX = /^[^\s·]+(?:·[a-z]+)? · /
289
290/**
291 * The model a title names: a Claude id or alias as its family and version ("Opus5.5"), a routed id
292 * as its configured name's last word ("GPT-6.1 Sol" → "Sol"), else a gpt-* id's last part, else
293 * the id.
294 */
295export function titleName(model: string, models: readonly RouterModel[] = []): string {
296  const id = baseModel(model).replace(/\[.*?\]/g, '')
297  const claude = /^(?:claude-)?(opus|sonnet|haiku|fable|mythos)(?:-(\d+)(?:-(\d{1,2}))?)?/i.exec(id)
298  if (claude) return claude[1]!.charAt(0).toUpperCase() + claude[1]!.slice(1).toLowerCase() + (claude[2] ? claude[2] + (claude[3] ? '.' + claude[3] : '') : '')
299  // A hosted id's vendor path ("deepseek-ai/") is dropped: the title has room for the model only.
300  const named = models.find(m => m.value.toLowerCase() === id.toLowerCase())?.name
301  if (named) return named.trim().split(/\s+/).pop()!.replace(/^.*\//, '')
302  const gpt = /^gpt-[\d.]+-([a-z]+)$/i.exec(id)
303  return gpt ? gpt[1]!.charAt(0).toUpperCase() + gpt[1]!.slice(1) : id.replace(/^.*\//, '')
304}
305
306/**
307 * The background-task title with the model that really runs it in front: "Sol·medium · Fix X".
308 * The app names only Claude models, and for a routed one shows the parent's; the mod is the one
309 * that knows, since it picks. A prefix already there (the parent's guess) is replaced.
310 */
311export function spawnTitle(description: string, model: string, effort: string | undefined, models: readonly RouterModel[] = []): string {
312  const tag = titleName(model, models) + (effort ? '·' + effort : '')
313  return `${tag} · ${bareTitle(description)}`
314}
315
316/** A title without the model tag spawnTitle put in front ("Sol·high · Port it" → "Port it"). */
317export function bareTitle(description: string): string {
318  const bare = description.replace(TITLE_PREFIX, '')
319  return bare.trim() ? bare : description
320}
321
322/** Claude Code owns these agents and their read-only/tool constraints (2026-10-24). */
323export const NATIVE_AGENTS: readonly string[] = ['statusline-setup', 'claude-code-guide', 'Explore', 'Plan']
324
325export function takesOver(spawn: { subagentType: string; model?: string; fork: boolean }, settings: Settings): boolean {
326  if (spawn.fork || settings.agentAuto === 'off') return false
327  if (['ripple:auto', 'auto'].includes(spawn.subagentType)) return true
328  // A project agent's pinned model must not bypass the ladder either (2026-10-24, opus-xhigh).
329  return settings.agentAuto === 'all' && !spawn.subagentType.includes(':') && !NATIVE_AGENTS.includes(spawn.subagentType)
330}
331
hooks/worker.ts 257 lines
1// How a spawn of one of ClaudeRipple's workers is set right before it starts. Plain functions, no
2// engine: the hook in register.tsx feeds them and applies the answer, and the tests import them.
3//
4// A worker is an agent file the router generated, whose `model:` is a routed id with an optional
5// `@effort` (packages/router/src/agents.ts). Two things went wrong at spawn time, both silently:
6// - A `model` argument on the Agent call replaced that id with a Claude alias, so the worker ran on
7//   Claude and its output was cut to 64 tokens (2026-09).
8// - The `[[ripple: name@level]]` marker that sets a worker's effort counts only as the prompt's
9//   first line (packages/router/src/routing.ts); anywhere else it is prose and the level is lost.
10// Measured on CLI 2.1.286 (2026-10-05): an `agent.spawn` hook that sets `model` to
11// `deepseek-v4.1-flash@low` runs the worker on that id, and the router records effort low.
12import type { DelegationPin } from '../types/index.d.ts'
13
14/**
15 * The router's marker, found anywhere in the prompt rather than only at its top. A tier marker may
16 * add a domain word, `[[ripple: standard ui]]`; the router's own pattern stops at the name, so a
17 * marker with a domain never reaches it as a model.
18 */
19export const MARKER = /\[\[\s*(?:ripple|gpt)\s*:\s*([A-Za-z0-9._:/\-]+)\s*(?:@\s*([A-Za-z]+))?(?:\s+([A-Za-z]+))?\s*\]\]/
20
21// The session's model markers no longer authorize a worker (2026-10-24). The judge reads one-shot
22// delegation intent; these name helpers remain for the user's explicit standing pin.
23/** The words in a model id that name it: `gemini-3.8-flash` → gemini; `gpt-6.1-sol` → gpt, sol. */
24const GENERIC = new Set(['flash', 'free', 'pro', 'mini', 'max', 'lite', 'preview', 'latest', 'contributor', 'spark', 'code', 'chat', 'instruct', 'claude', 'turbo', 'high', 'low', 'medium', 'xhigh'])
25/** How the user says them in Korean. */
26const SPOKEN: Record<string, readonly string[]> = {
27  gemini: ['제미나이', '제미니'], deepseek: ['딥시크'], minimax: ['미니맥스'], gpt: ['지피티'], sol: ['솔'], astra: ['아스트라'],
28  luna: ['루나'], terra: ['테라'], opus: ['오푸스', '오퍼스'], sonnet: ['소넷'], haiku: ['하이쿠'], fable: ['페이블'], mythos: ['미토스'],
29  muse: ['뮤즈'], kimi: ['키미'], qwen: ['큐웬'], mimo: ['미모'], longcat: ['롱캣'], argon: ['아르곤'],
30}
31const PROVIDER_SPOKEN: Record<string, readonly string[]> = {
32  opencode: ['오픈코드'], google: ['구글'], chatgpt: ['챗지피티'], antigravity: ['안티그래비티'], anthropic: ['앤트로픽'],
33}
34// A Korean name counts when a particle or nothing Korean follows it: "솔한테" names Sol, "솔직히" does not.
35const PARTICLE = '(?:이한테|이랑|이가|이는|이를|이도|이로|이나|한테|에게|으로|께|로|이|가|은|는|을|를|도|만|랑|와|과|의|님|에)'
36export function modelWords(id: string): string[] {
37  return [...new Set(id.toLowerCase().split(/[^a-z]+/).filter(word => word.length >= 3 && !GENERIC.has(word)))]
38}
39// A delegating verb written onto the name: "오푸스시켜 중요한거잖아" named Opus and was read as
40// unnamed (2026-10-24), so the marker went and the tier sent the task to Sol.
41const VERB = '(?:시켜|시키|써|쓰|돌려|돌리|맡겨|맡기|불러|부르|줘)'
42function says(text: string, word: string): boolean {
43  if (new RegExp(`(?<![a-z])${word}(?![a-z])`, 'i').test(text)) return true
44  return [...(SPOKEN[word] ?? []), ...(PROVIDER_SPOKEN[word] ?? [])].some(name => new RegExp(`${name}(?:쪽)?(?:${PARTICLE}|${VERB}|(?![가-힣]))`).test(text))
45}
46type Said ={ role: 'user' | 'assistant'; text: string; toolResults?: readonly unknown[] }
47type ModelSource = { model: string; provider: string }
48/** Once the provider is known, metadata and intent checks use its original model id. */
49export function providerModelId(model: string, provider?: string): string {
50  const base = model.replace(/@[^@]*$/, '')
51  return provider && base.startsWith(provider + ':') ? base.slice(provider.length + 1) : base
52}
53/** The person's words alone, shared by one-shot authorization and session pinning. */
54export function humanText(m: Said): string | null {
55  const text = m.text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '').trim()
56  return m.role === 'user' && !m.toolResults?.length && !!text && !/^<[a-z][a-z-]*>/i.test(text) && !text.startsWith('This session is being continued') ? text : null
57}
58
59/**
60 * Explicit standing intent, never inferred from a one-off model choice. Everyday words stay out:
61 * "솔이 계속 실패하네" complains about Sol, and "헤더 고정해 줘" pins a header, not a worker.
62 */
63export const PIN_PHRASES = ['앞으로', '이제부터', '이 세션은', '이번 세션 내내', '위임 고정', '로 고정', 'from now on', 'for this session'] as const
64// A release must name the choice or the pin itself. Bare "알아서 골라" may mean test data;
65// "헤더 고정 풀어" is not a delegation instruction either.
66const REQUEST_END = '(?:\\s*(?:해\\s*)?(?:줘|주세요|주라|라|요))?[.!?。]*$'
67const CHOICE = '(?:위임(?:\\s*모델)?|모델)(?:\\s*선택)?'
68export const UNPIN_PHRASES: readonly RegExp[] = [
69  new RegExp(`^(?:${CHOICE}\\s*)?고정(?:을|은)?\\s*(?:풀어|해제)(?:해)?${REQUEST_END}`),
70  new RegExp(`^${CHOICE}(?:은|는|을|를)?\\s*(?:알아서|자동으로)\\s*(?:골라|정해|선택해|해)${REQUEST_END}`),
71  /^(?:please\s+)?unpin(?:\s+(?:the\s+)?(?:delegation|model|worker))?[.!?]*$/i,
72  /^(?:please\s+)?(?:choose|select)\s+(?:the\s+)?(?:delegation\s+)?(?:model|worker)\s+automatically[.!?]*$/i,
73]
74const hasPhrase = (text: string, phrases: readonly string[]) => phrases.some(phrase => /[a-z]/i.test(phrase)
75  ? new RegExp(`\\b${phrase}\\b`, 'i').test(text) : text.includes(phrase))
76// Keep a future instruction in one sentence/clause from making a separate one-shot choice stick.
77const pinParts = (text: string) => text.split(/(?<=[.!?。])\s+|\n+|[,;,;]+/).map(part => part.replace(/\s+/g, ' ').trim()).filter(Boolean)
78/** Cheap intent check before the hook loads the worker catalogue; pinning still needs a target. */
79export function pinInstruction(text: string): 'pin' | 'release' | undefined {
80  // A standing "don't": "앞으로 솔은 쓰지 마", "솔 말고", "솔로 고정하지 마".
81  if (/(?:고정\s*(?:하지|하지는|말|안)|(?:하지|쓰지|고르지|시키지|맡기지|보내지)\s*(?:마|말)|말고|빼고|\b(?:do not|don't|never|stop)\b)/i.test(text)) return undefined
82  const parts = pinParts(text)
83  if (parts.some(part => UNPIN_PHRASES.some(phrase => phrase.test(part)))) return 'release'
84  return parts.some(part => hasPhrase(part, PIN_PHRASES) || /고정/.test(part)) ? 'pin' : undefined
85}
86const modelId = (model: string) => model.toLowerCase().replace(/@[^@]*$/, '').replace(/\./g, '-')
87const pinId = (model: string) => modelId(model).replace(/^claude-/, '').replace(/^(opus|sonnet|haiku|fable|mythos)-.*$/, '$1')
88const escapePattern = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
89/** Dots and hyphens normalize alike, but no substring of a longer model id is exact. */
90const fullIdPattern = (model: string) => `(?<![a-z0-9_.-])${modelId(model).split('-').map(escapePattern).join('[.-]')}(?![a-z0-9_-]|\\.[a-z0-9])`
91function modelPattern(model: string): string {
92  const words = modelWords(model)
93  return `(?:${fullIdPattern(model)}|${words.map(word => `(?<![a-z])${word}(?![a-z])`).concat(words.flatMap(word => SPOKEN[word] ?? [])).join('|')})`
94}
95// Directional particles must lead to a delegation command (or finish an elliptical "솔로").
96// A name followed by "오류 로그" or "작성한 로그" is a subject, not the selected worker.
97const COMMAND_END = '(?:\\s*(?:줘|주세요|주라|라|요))?(?=$|\\s|[.!?。])'
98const PIN_COMMAND = `고정(?:해|하자|하세요)?${COMMAND_END}`
99const DELEGATION_VERB = `(?:해|하자|하세요|하라|시켜|시키자|시키세요|맡겨|맡기자|맡기세요|써|쓰자|쓰세요|돌려|돌리자|돌리세요|고정(?:해|하자|하세요)?|위임(?:해|하자|하세요)?|사용(?:해|하자|하세요)?)${COMMAND_END}`
100const DELEGATION_TASK = '(?:(?:검토|리뷰|작업|구현|교정|분석|테스트)(?:을|를)?\\s*)?'
101function pinsModel(text: string, model: string): boolean {
102  const name = modelPattern(model)
103  if (/위임\s*고정/.test(text)) return true // userNamed separately checks the named model/source.
104  if (new RegExp(`${name}\\s*(?:으로|로)?\\s*${PIN_COMMAND}`, 'i').test(text)) return true
105  if (!hasPhrase(text, PIN_PHRASES)) return false
106  const directed = new RegExp(`${name}\\s*(?:(?:으로|로|에게|한테|이한테)\\s*(?:${DELEGATION_TASK}${DELEGATION_VERB}|[.!?。]*$)|(?:을|를|은|는)?\\s*${DELEGATION_TASK}${DELEGATION_VERB})`, 'i')
107  const paired = new RegExp(`${name}(?:과|와|랑|이랑|\\s+(?:and|or))\\s*\\S+?(?:으로|로|에게|한테)\\s*${DELEGATION_TASK}${DELEGATION_VERB}`, 'i')
108  const english = new RegExp(`\\b(?:(?:use|pin)\\s+|(?:delegate|assign)\\s+(?:(?:work|tasks?)\\s+)?to\\s+)${name}(?=$|[.!?。]|\\s+(?:for|from|to|on|as|at)\\b)`, 'i')
109  return directed.test(text) || paired.test(text) || english.test(text)
110}
111
112/** Compare version components as numbers: 6.10 is newer than 6.9, and 7 is newer than 6.99. */
113function compareModelVersions(a: string, b: string): number {
114  const version = (model: string) => (modelId(model).match(/\d+(?:-\d+)*/)?.[0] ?? '0').split('-').map(Number)
115  const left = version(a), right = version(b)
116  for (let i = 0; i < Math.max(left.length, right.length); i++) {
117    const difference = (left[i] ?? 0) - (right[i] ?? 0)
118    if (difference) return difference
119  }
120  return 0
121}
122/** A family name chooses its one generated worker, otherwise its latest version. Never cross families. */
123function familyPinSources(sources: readonly ModelSource[], workers: readonly ModelSource[]): readonly ModelSource[] {
124  if (new Set(sources.map(source => modelWords(providerModelId(source.model, source.provider)).join('|'))).size !== 1) return []
125  const generated = sources.filter(source => workers.some(worker => modelId(worker.model) === modelId(source.model) && worker.provider === source.provider))
126  if (new Set(generated.map(source => modelId(source.model))).size === 1) return generated
127  const latest = sources.reduce((best, source) => compareModelVersions(source.model, best.model) > 0 ? source : best)
128  // Equal-version variants remain together: the caller refuses them rather than breaking a tie by order.
129  return sources.filter(source => compareModelVersions(source.model, latest.model) === 0)
130}
131
132/** undefined means no change; null explicitly releases the pin. Ambiguous models never pin. */
133export function delegationPin(message: Said, sources: readonly ModelSource[], workers: readonly ModelSource[] = []): DelegationPin | null | undefined {
134  const text = humanText(message)
135  if (!text) return undefined
136  const instruction = pinInstruction(text)
137  if (instruction === 'release') return null
138  if (instruction !== 'pin') return undefined
139  const parts = pinParts(text).filter(part => pinInstruction(part) === 'pin')
140  const matches = sources.flatMap(source => {
141    const providers = rivalProviders(source.model, sources)
142    const model = providerModelId(source.model, source.provider)
143    const targeted = parts.filter(part => pinsModel(part, model) && userNamed(source.model, [{ role: 'user', text: part }], [], { ...source, providers }))
144    if (!targeted.length) return []
145    const exact = targeted.some(part => new RegExp(fullIdPattern(model), 'i').test(part))
146    const score = Math.max(...targeted.map(part => modelWords(model).filter(word => says(part, word)).length))
147    return [{ ...source, exact, score }]
148  })
149  const exact = matches.some(source => source.exact)
150  const eligible = matches.filter(source => source.exact === exact)
151  const best = Math.max(1, ...eligible.map(source => source.score))
152  const ranked = eligible.filter(source => source.score === best)
153  const named = exact ? ranked : familyPinSources(ranked, workers)
154  if (new Set(named.map(source => modelId(source.model))).size !== 1) return undefined
155  const first = named[0]!
156  const providers = [...new Set(named.map(source => source.provider))]
157  return { model: first.model.replace(/@[^@]*$/, ''), ...(providers.length === 1 ? { provider: providers[0]! } : {}) }
158}
159
160/** The most characters of the person's sentence the band keeps beside a pin. */
161export const PIN_SAID_MAX = 60
162/**
163 * The sentence that pinned, for the band to show: the first one carrying a standing phrase, its
164 * whitespace folded and cut to PIN_SAID_MAX characters. Session state only.
165 */
166export function pinSaid(text: string, model?: string): string | undefined {
167  const parts = pinParts(text)
168  const part = parts.find(p => pinInstruction(p) === 'pin' && (!model || pinsModel(p, model))) ?? parts[0]
169  if (!part) return undefined
170  const chars = [...part]
171  return chars.length > PIN_SAID_MAX ? chars.slice(0, PIN_SAID_MAX - 1).join('') + '…' : part
172}
173
174export function pinAllows(pin: DelegationPin | null, model: string, provider?: string): boolean {
175  return !!pin && pinId(pin.model) === pinId(model) && (!pin.provider || pin.provider === provider)
176}
177/**
178 * Whether the user named this model (an id, agent name or Claude alias) in what they last wrote:
179 * their last two messages, and the answer they replied to when the last one is a short "go".
180 * Tool results, notices and compaction summaries are not the user.
181 */
182export function userNamed(model: string, messages: readonly Said[], prompts: readonly string[] = [], source: { provider?: string; providers?: readonly string[] } = {}): boolean {
183  const words = modelWords(providerModelId(model, source.provider))
184  if (!words.length) return false
185  // A notice opens on a tag (`<task-notification>`, `<local-command-stdout>`); a reply the app quotes
186  // opens on `<!-- reply 1 -->` and is the user's own words.
187  const at = messages.flatMap((m, index) => humanText(m) ? [index] : []).slice(-2)
188  const last = at.at(-1)
189  const heard = at.map(index => humanText(messages[index]!)!)
190  if (last !== undefined && messages[last]!.text.trim().length <= 12) {
191    const answer = messages.slice(0, last).findLast(m => m.role === 'assistant' && m.text.trim())
192    if (answer) heard.push(answer.text.slice(-2000))
193  }
194  // The prompts as submitted (`heardPrompts`): one typed mid-turn is in no user message above.
195  const texts = [...heard, ...prompts]
196  // Naming a provider chooses the source of a named model; it never authorizes all its models.
197  const providers = [...new Set([...(source.providers ?? []), ...(source.provider ? [source.provider] : [])])]
198  const distinct = providers.filter(provider => modelWords(provider).some(word => !Object.hasOwn(SPOKEN, word) && !words.includes(word)))
199  // The "gemini" inside the provider id "google-gemini" is not a separate model choice.
200  const modelTexts = texts.map(text => distinct.reduce((own, provider) => own.replace(new RegExp(`(?<![a-z0-9_-])${escapePattern(provider)}(?![a-z0-9_-])`, 'gi'), ' '), text))
201  if (!modelTexts.some(text => words.some(word => says(text, word)))) return false
202  // A provider names the source, not just its model: "Argon on OpenCode" must not authorize the
203  // Google API worker with the same model. Without a provider, the model name covers either source.
204  // Only the user's own words choose a source: the answer a short "go" replies to mentions
205  // providers in passing ("Google API is out of quota"), and that is not a choice.
206  const own = [...at.map(index => humanText(messages[index]!)!), ...prompts]
207  // "Sol or DeepSeek" names two models, not a requirement to run Sol on the DeepSeek API.
208  const named = providers.filter(provider => modelWords(provider).some(word => !Object.hasOwn(SPOKEN, word) && !words.includes(word) && own.some(text => says(text, word))))
209  if (named.length) return !!source.provider && named.includes(source.provider)
210  return true
211}
212
213/**
214 * The providers a named source could tell this model apart from: those serving a model that shares
215 * one of its name words. Naming OpenCode then decides between two Argons, and says nothing about Sol.
216 */
217export function rivalProviders(model: string, sources: readonly { model: string; provider: string }[]): string[] {
218  const owner = sources.find(s => model.startsWith(s.provider + ':'))?.provider
219  const words = modelWords(providerModelId(model, owner))
220  return [...new Set(sources.filter(s => modelWords(providerModelId(s.model, s.provider)).some(word => words.includes(word))).map(s => s.provider))]
221}
222
223export type Spawn = { subagentType: string; prompt: string; model?: string }
224export type WorkerFix = { prompt: string; model: string; dropped?: string }
225
226/** The `model:` line of an agent file's frontmatter. */
227export function agentModel(file: string): string | undefined {
228  const head = /^---\n([\s\S]*?)\n---/.exec(file)?.[1]
229  return head ? /^model:\s*(\S+)\s*$/m.exec(head)?.[1] : undefined
230}
231
232/**
233 * What the spawn should run with, or null to leave it alone. `fileModel` is the worker's agent
234 * file `model:` (an id, maybe with `@effort`).
235 */
236export function fixSpawn(spawn: Spawn, fileModel: string): WorkerFix | null {
237  const base = fileModel.replace(/@[^@]*$/, '')
238  const marker = MARKER.exec(spawn.prompt)
239  const dropped = spawn.model !== undefined && spawn.model !== fileModel && spawn.model.replace(/@[^@]*$/, '') !== base ? spawn.model : undefined
240  if (marker) {
241    const name = marker[1]!.toLowerCase()
242    const level = marker[2]?.toLowerCase()
243    const rest = (spawn.prompt.slice(0, marker.index) + spawn.prompt.slice(marker.index + marker[0].length)).replace(/^\s*\n/, '')
244    // The marker names this worker: its level goes on the model id, where the router reads it as
245    // the agent file's own suffix, and the worker no longer reads a routing note.
246    if (name === spawn.subagentType.toLowerCase() || name === base.toLowerCase()) {
247      return { prompt: rest, model: level ? `${base}@${level}` : fileModel, ...(dropped ? { dropped } : {}) }
248    }
249    // It names another model or alias, which only the router can resolve: put it where the router
250    // looks. Already there, there is nothing to move.
251    const atTop = MARKER.exec(spawn.prompt.replace(/^\s+/, ''))?.index === 0
252    if (atTop && !dropped) return null
253    return { prompt: atTop ? spawn.prompt : `${marker[0]}\n${rest}`, model: fileModel, ...(dropped ? { dropped } : {}) }
254  }
255  return dropped ? { prompt: spawn.prompt, model: fileModel, dropped } : null
256}
257
hooks/modes.ts 155 lines
1// Operating modes in the session (docs/specs/2026-10-12-worker-tiers.md "Operating modes"): which
2// mode is on, when it ends by itself, and the eager-delegation note (Base's while no mode is on).
3// Pure; register.tsx wires them.
4
5import type { Hot, LimitItem, Mode, Settings } from '../types'
6
7/** The mode that is on, if the settings name one that exists. */
8export function activeModeOf(s: Pick<Settings, 'modes' | 'activeMode'>): Mode | undefined {
9  return s.activeMode ? s.modes.find(m => m.id === s.activeMode) : undefined
10}
11
12/** One turning-on of a mode: the same mode turned off and on again is a new one. */
13export function modeKey(s: Pick<Settings, 'activeMode' | 'activeSince'>): string | null {
14  return s.activeMode ? `${s.activeMode}@${s.activeSince ?? 0}` : null
15}
16
17/** What the main chat reads beside the prompt while an eager mode is on. */
18export function modeNote(name: string): string {
19  return `ClaudeRipple mode ${name}: delegate everything except judgment and final review to ripple:auto.`
20}
21
22/** What it reads while no mode is on and Base is eager. */
23const BASE_NOTE = 'ClaudeRipple: delegate everything except judgment and final review to ripple:auto.'
24
25/**
26 * The eager note for this prompt: Base's while no mode is on, the active mode's otherwise. Sent
27 * with every prompt while the effective delegation is eager: a note sent once is buried in a long
28 * context, and the operator saw main chats doing the work themselves (2026-10-24). When
29 * it is not eager, nothing is said and `noted` becomes null. `_noted` is what was noted last time;
30 * it stays in the signature for callers and no longer changes the answer.
31 */
32export function eagerNote(s: Pick<Settings, 'modes' | 'activeMode' | 'activeSince' | 'delegation'>, _noted: string | null): { note?: string; noted: string | null } {
33  const mode = activeModeOf(s)
34  if ((mode?.delegation ?? s.delegation) !== 'eager') return { noted: null }
35  return { note: mode ? modeNote(mode.name) : BASE_NOTE, noted: mode ? modeKey(s) : 'base' }
36}
37
38/** Modes replace the base worker set, without changing fallback, allow-list or provider policy. */
39export function routingSettings(s: Settings): Settings {
40  const mode = activeModeOf(s)
41  return mode ? { ...s, rules: { general: { mode: 'ladder', rungs: mode.rungs } }, domainRules: mode.domainRules } : s
42}
43
44/** The provider whose quota reset ends the mode: 'anthropic' is Claude, any other a ChatGPT provider. */
45export function resetProvider(mode: Pick<Mode, 'until'>): string | undefined {
46  return typeof mode.until === 'object' ? mode.until.reset : undefined
47}
48
49/** Same binding limit as the band: highest percent used, input order breaking ties. */
50export function claudeWindow(limit: Hot | null): QuotaWindow[] {
51  const at = limit?.resetsAt ? Date.parse(limit.resetsAt) : NaN
52  return Number.isFinite(at) ? [{ at }] : []
53}
54
55/** One account's quota window: when it resets next, and how long it is when known. */
56export type QuotaWindow = { at: number; windowMs?: number }
57
58function record(value: unknown): Record<string, unknown> {
59  return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}
60}
61
62/**
63 * Each signed-in, unpaused ChatGPT account's known windows, from GET
64 * /api/chatgpt-accounts: `quota.rate_limits.{primary,secondary}` with `reset_at` (epoch seconds,
65 * or ms) or `reset_after_seconds` from the snapshot's `at`, and `window_minutes`
66 * (packages/router/src/providers/chatgpt/index.ts rateLimitsFromHeaders/rateLimitsFromUsage).
67 * An account whose reset is unknown is left out.
68 */
69export function quotaWindows(body: unknown): QuotaWindow[] {
70  const accounts = record(body).accounts
71  if (!Array.isArray(accounts)) return []
72  return accounts.flatMap(value => {
73    const account = record(value)
74    if (account.state === 'paused' || account.state === 'needs-login') return []
75    const quota = record(account.quota)
76    const limits = record(quota.rate_limits)
77    return ['primary', 'secondary'].flatMap(key => {
78      const window = record(limits[key])
79      const resetAt = typeof window.reset_at === 'number' ? (window.reset_at > 1e12 ? window.reset_at : window.reset_at * 1000)
80        : typeof window.reset_after_seconds === 'number' && typeof quota.at === 'number' ? quota.at + window.reset_after_seconds * 1000 : undefined
81      if (resetAt === undefined || !Number.isFinite(resetAt)) return []
82      const minutes = window.window_minutes
83      return [{ at: resetAt, ...(typeof minutes === 'number' && minutes > 0 ? { windowMs: minutes * 60_000 } : {}) }]
84    })
85  })
86}
87
88/**
89 * End at the first known reset after activation of the mode's chosen provider (`windows` are only
90 * that provider's), not after every account resets. ChatGPT's fixed window length also identifies a
91 * reset when a fresh snapshot has rolled forward. Claude windows are not extrapolated: the
92 * five-hour window can start lazily after idle.
93 */
94export function modeOver(mode: Pick<Mode, 'until'>, since: number | undefined, now: number, windows: readonly QuotaWindow[] = []): boolean {
95  if (typeof mode.until === 'number') return now >= mode.until
96  if (!resetProvider(mode) || since === undefined || !windows.length) return false
97  const passed = (at: number) => at > since && at <= now
98  return windows.some(w => passed(w.at) || (w.windowMs !== undefined && passed(w.at - w.windowMs)))
99}
100
101/** The configured providers of ChatGPT type, from GET /api/status `providers` (name → {type}). */
102export function chatgptProviders(status: unknown): string[] {
103  const providers = record(status).providers
104  if (!providers || typeof providers !== 'object' || Array.isArray(providers)) return []
105  return Object.entries(providers as Record<string, unknown>)
106    .filter(([, value]) => record(value).type === 'chatgpt')
107    .map(([name]) => name)
108}
109
110/**
111 * Every signed-in ChatGPT account's known windows as the limits row reads them, from GET
112 * /api/chatgpt-accounts (`quota.rate_limits.{primary,secondary}` with `reset_at` in epoch
113 * seconds or ms, or `reset_after_seconds` from the snapshot's `at`, and `window_minutes`;
114 * the same shape `quotaWindows` reads). Paused and needs-login accounts are left out (and take
115 * no number), and so is an account with no snapshot. `account` numbers the accounts kept, in
116 * answer order. A snapshot is not aged out: the router takes it from the account's own replies,
117 * so an account idle for an hour holds an hour-old figure that is still right (measured
118 * 2026-10-15: 30 minutes old between uses). Only a window whose reset has passed is dropped,
119 * since its figure no longer stands.
120 */
121export function gptLimitsFrom(body: unknown, provider: string, now: number): LimitItem[] {
122  const accounts = record(body).accounts
123  if (!Array.isArray(accounts)) return []
124  const kept = accounts.map(record).filter(account => account.state !== 'paused' && account.state !== 'needs-login' && account.paused !== true)
125  const out: LimitItem[] = []
126  kept.forEach((account, index) => {
127    const quota = record(account.quota)
128    const at = quota.at
129    if (typeof at !== 'number') return
130    const limits = record(quota.rate_limits)
131    for (const key of ['primary', 'secondary']) {
132      const window = record(limits[key])
133      const used = window.used_percent
134      if (typeof used !== 'number' || !Number.isFinite(used)) continue
135      const minutes = window.window_minutes
136      const resetAt = typeof window.reset_at === 'number' ? (window.reset_at > 1e12 ? window.reset_at : window.reset_at * 1000)
137        : typeof window.reset_after_seconds === 'number' && typeof at === 'number' ? at + window.reset_after_seconds * 1000 : NaN
138      if (Number.isFinite(resetAt) && resetAt <= now) continue
139      const kind = minutes === 300 ? 'five_hour' : minutes === 10080 ? 'seven_day' : 'window'
140      out.push({
141        provider,
142        type: 'chatgpt',
143        title: 'GPT',
144        account: index,
145        kind,
146        label: '',
147        ...(typeof minutes === 'number' && minutes > 0 ? { windowMinutes: minutes } : {}),
148        percent: Math.round(used * 10) / 10,
149        ...(Number.isFinite(resetAt) ? { resetsAt: new Date(resetAt).toISOString() } : {}),
150      })
151    }
152  })
153  return out
154}
155
hooks/cache.ts 61 lines
1import type { ModelForkResult } from 'claude-code'
2import type { CacheMemo, Settings, Usage, WarmState } from '../types'
3import { weighted } from './stats'
4import { t } from './i18n.ts'
5import type { Lang } from './i18n.ts'
6
7const HOUR = 3600000
8const FIVE_MINUTES = 300000
9
10export function ttlFromUsage(usage: Usage): number {
11  if ((usage.cache_creation?.ephemeral_1h_input_tokens ?? 0) > 0) return HOUR
12  if ((usage.cache_creation?.ephemeral_5m_input_tokens ?? 0) > 0) return FIVE_MINUTES
13  return HOUR
14}
15
16/** A five-minute tail must not shorten a mostly-read hour-long prefix. */
17export function nextMemo(prev: CacheMemo | null, usage: Usage, now: number): CacheMemo {
18  const total = (usage.input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0)
19  const mostlyRead = (usage.cache_read_input_tokens ?? 0) > total / 2
20  const explicit = (usage.cache_creation?.ephemeral_1h_input_tokens ?? 0) > 0 || (usage.cache_creation?.ephemeral_5m_input_tokens ?? 0) > 0
21  let ttlMs = explicit ? ttlFromUsage(usage) : prev?.ttlMs ?? HOUR
22  if (prev?.ttlMs === HOUR && mostlyRead) ttlMs = HOUR
23  if (!explicit && prev && now - prev.lastReplyAt > FIVE_MINUTES && mostlyRead) ttlMs = HOUR
24  return { ttlMs, lastReplyAt: now, expiresAt: now + ttlMs }
25}
26
27export function secondsLeft(memo: CacheMemo | null, now: number): number | null {
28  return memo ? Math.max(0, Math.ceil((memo.expiresAt - now) / 1000)) : null
29}
30
31/** Never pay to revive an expired cache or extend the last-real-reply bound with our own pings. */
32export function shouldPing(input: {
33  settings: Settings; memo: CacheMemo | null; warm: WarmState; now: number; idle: boolean
34  contextTokens: number; lastRealReplyAt: number | null
35}): { ping: true } | { ping: false; reason?: string } {
36  const { settings, memo, warm, now } = input
37  if (!settings.keepWarm) return { ping: false, reason: 'keep warm is off' }
38  if (warm.stopped) return { ping: false, reason: warm.stopped }
39  if (!input.idle) return { ping: false, reason: 'chat is busy' }
40  if (!memo || memo.expiresAt <= now) return { ping: false, reason: 'cache is not warm' }
41  if (input.lastRealReplyAt === null || now >= input.lastRealReplyAt + settings.keepWarmHours * HOUR) return { ping: false, reason: 'keep warm time bound reached' }
42  if (input.contextTokens < settings.keepWarmMinTokens) return { ping: false, reason: 'chat is too small' }
43  const lead = memo.ttlMs === FIVE_MINUTES ? 60000 : 240000
44  return memo.expiresAt - now <= lead ? { ping: true } : { ping: false }
45}
46
47/** Failed forks stop once; answered cache misses still count the real tokens they spent. */
48export function afterPing(warm: WarmState, forkResult: ModelForkResult | null, now: number, lang: Lang = 'en'): WarmState {
49  if (!forkResult?.isAnswered) return { ...warm, stopped: t(lang, 'toasts.warmNoReply') }
50  const next: WarmState = { pings: warm.pings + 1, cost: warm.cost + weighted(forkResult.usage), lastPingAt: now }
51  if (forkResult.usage.cache_read_input_tokens <= 0) next.stopped = t(lang, 'toasts.warmNoCache')
52  return next
53}
54
55export function restoreFromResume(secondsSinceLastResponse: number | undefined, likelyExpired: boolean | undefined, ttlMs: number, now: number): CacheMemo | null {
56  if (secondsSinceLastResponse === undefined || !Number.isFinite(secondsSinceLastResponse) || secondsSinceLastResponse < 0) return null
57  const lastReplyAt = now - secondsSinceLastResponse * 1000
58  const expiresAt = lastReplyAt + ttlMs
59  return { ttlMs, lastReplyAt, expiresAt: likelyExpired || expiresAt <= now ? now - 1 : expiresAt }
60}
61
hooks/session.ts 212 lines
1import type { SessionContextUsage, SessionRateLimit } from 'claude-code'
2import type { CacheMemo, Hot, LimitItem } from '../types'
3
4export function hottest(rateLimits: readonly SessionRateLimit[]): Hot | null {
5  const eligible = rateLimits.filter(limit => ['five_hour', 'seven_day'].includes(limit.kind) && limit.percentUsed >= 80)
6  const limit = eligible.reduce<SessionRateLimit | undefined>((hot, next) => !hot || next.percentUsed > hot.percentUsed ? next : hot, undefined)
7  return limit ? { kind: limit.kind, percent: limit.percentUsed, ...(limit.resetsAt ? { resetsAt: limit.resetsAt } : {}) } : null
8}
9
10const WINDOW_KIND: Record<number, string> = { 300: 'five_hour', 10080: 'seven_day' }
11/** A router snapshot older than this is not shown as the plan's figure. */
12export const CLAUDE_USAGE_STALE_MS = 15 * 60_000
13
14/**
15 * The plan windows of the Claude login this session's requests pass through, from the router's
16 * GET /api/status (`claude.accounts[id=current].quota`, packages/router/src/admin.ts
17 * claudeAccountUsage): for when the host leaves `rateLimits` empty though the requests carry them
18 * (measured 2026-10-14: the router passes the `anthropic-ratelimit-unified-*` headers through).
19 * Percent as the router reports it; a stale or unknown snapshot gives nothing.
20 */
21export function claudeLimitsFrom(status: unknown, now: number): SessionRateLimit[] {
22  const object = (v: unknown): Record<string, unknown> => v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : {}
23  const accounts = object(object(status).claude).accounts
24  const current = Array.isArray(accounts) ? accounts.map(object).find(a => a.id === 'current') : undefined
25  const quota = object(current?.quota)
26  if (typeof quota.at !== 'number' || now - quota.at > CLAUDE_USAGE_STALE_MS) return []
27  const limits = object(quota.rate_limits)
28  return [limits.primary, limits.secondary].map(object).flatMap(w => {
29    const kind = typeof w.window_minutes === 'number' ? WINDOW_KIND[w.window_minutes] : undefined
30    if (!kind || typeof w.used_percent !== 'number' || !Number.isFinite(w.used_percent)) return []
31    const reset = typeof w.reset_at === 'number' ? w.reset_at * (w.reset_at < 1e12 ? 1000 : 1) : NaN
32    return [{ kind, percentUsed: Math.round(w.used_percent * 10) / 10, ...(Number.isFinite(reset) ? { resetsAt: new Date(reset).toISOString() } : {}) }]
33  })
34}
35
36/** One per-model weekly window the router reports beside `rate_limits` (see `scopedFromLimits`). */
37export type ScopedLimit = { name: string; percent: number; resetsAt?: string }
38
39/**
40 * The per-model weekly windows of the Claude login, from the router's GET /api/status
41 * (`claude.accounts[id=current].quota.scoped`: `{name, used_percent, window_minutes, reset_at}`,
42 * reset in epoch seconds or ms). A stale or unknown snapshot gives nothing, like claudeLimitsFrom.
43 */
44export function claudeScopedFrom(status: unknown, now: number): ScopedLimit[] {
45  const object = (v: unknown): Record<string, unknown> => v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : {}
46  const accounts = object(object(status).claude).accounts
47  const current = Array.isArray(accounts) ? accounts.map(object).find(a => a.id === 'current') : undefined
48  const quota = object(current?.quota)
49  if (typeof quota.at !== 'number' || now - quota.at > CLAUDE_USAGE_STALE_MS) return []
50  const scoped = quota.scoped
51  if (!Array.isArray(scoped)) return []
52  return scoped.map(object).flatMap(entry => {
53    if (typeof entry.name !== 'string' || !entry.name || typeof entry.used_percent !== 'number' || !Number.isFinite(entry.used_percent)) return []
54    const reset = typeof entry.reset_at === 'number' ? entry.reset_at * (entry.reset_at < 1e12 ? 1000 : 1) : NaN
55    return [{ name: entry.name, percent: Math.round(entry.used_percent * 10) / 10, ...(Number.isFinite(reset) ? { resetsAt: new Date(reset).toISOString() } : {}) }]
56  })
57}
58
59const KINDS = ['five_hour', 'seven_day', 'scoped', 'window'] as const
60type LimitKind = (typeof KINDS)[number]
61
62/** One window of `GET /api/limits` as a limits-row item, or null when it carries nothing to show. */
63function limitItemFromWindow(w: unknown, provider: string, type: string | undefined, title: string | undefined, account: number, now: number): LimitItem | null {
64  const o = w && typeof w === 'object' && !Array.isArray(w) ? w as Record<string, unknown> : {}
65  const kind = o.kind
66  if (typeof kind !== 'string' || !(KINDS as readonly string[]).includes(kind)) return null
67  const used = o.used_percent
68  if (typeof used !== 'number' || !Number.isFinite(used)) return null
69  const minutes = typeof o.window_minutes === 'number' && o.window_minutes > 0 ? o.window_minutes : undefined
70  const reset = typeof o.reset_at === 'number' && Number.isFinite(o.reset_at) ? o.reset_at * (o.reset_at < 1e12 ? 1000 : 1) : NaN
71  // A window whose reset has passed starts again from nothing: it reads 0% until the provider next
72  // reports, not gone. Dropped, Claude's five-hour window vanished from the row the minute it reset,
73  // and the row read as one of Claude's figures cut off (2026-10-20).
74  if (Number.isFinite(reset) && reset <= now) {
75    return { provider, ...(type ? { type } : {}), ...(title ? { title } : {}), account, kind: kind as LimitKind, label: typeof o.label === 'string' ? o.label : '', ...(minutes !== undefined ? { windowMinutes: minutes } : {}), percent: 0 }
76  }
77  return {
78    provider,
79    ...(type ? { type } : {}),
80    ...(title ? { title } : {}),
81    account,
82    kind: kind as LimitKind,
83    label: typeof o.label === 'string' ? o.label : '',
84    ...(minutes !== undefined ? { windowMinutes: minutes } : {}),
85    percent: Math.round(used * 10) / 10,
86    ...(Number.isFinite(reset) ? { resetsAt: new Date(reset).toISOString() } : {}),
87  }
88}
89
90/**
91 * Every provider's windows from the router's `GET /api/limits`: one shape for Claude, each ChatGPT
92 * account and each Antigravity account (see `buildLimits` in packages/router/src/admin.ts). The
93 * providers keep the router's order (Claude first), and each account's windows keep theirs.
94 */
95export function routerLimitItems(body: unknown, now: number): LimitItem[] {
96  const object = (v: unknown): Record<string, unknown> => v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : {}
97  const providers = object(body).providers
98  if (!Array.isArray(providers)) return []
99  const out: LimitItem[] = []
100  for (const p of providers) {
101    const entry = object(p)
102    const provider = typeof entry.provider === 'string' ? entry.provider : ''
103    if (!provider) continue
104    const type = typeof entry.type === 'string' ? entry.type : undefined
105    const title = typeof entry.title === 'string' ? entry.title : undefined
106    const accounts = entry.accounts
107    if (!Array.isArray(accounts)) continue
108    for (const a of accounts) {
109      const account = object(a)
110      const index = typeof account.account === 'number' ? account.account : 0
111      const windows = account.windows
112      if (!Array.isArray(windows)) continue
113      for (const w of windows) {
114        const item = limitItemFromWindow(w, provider, type, title, index, now)
115        if (item) out.push(item)
116      }
117    }
118  }
119  return out
120}
121
122/**
123 * The reset is read in the person's own clock: `offsetMinutes` is `Date#getTimezoneOffset` (minutes
124 * behind UTC), passed in so tests do not depend on the machine's zone.
125 */
126export function limitLabel(hot: Hot, now: number, offsetMinutes = new Date(now).getTimezoneOffset()): string {
127  const label = `${hot.kind === 'five_hour' ? '5h' : 'weekly'} ${Math.round(hot.percent)}%`
128  const reset = hot.resetsAt ? Date.parse(hot.resetsAt) : NaN
129  if (!Number.isFinite(reset)) return label
130  const date = new Date(reset - offsetMinutes * 60000)
131  const time = `${String(date.getUTCHours()).padStart(2, '0')}:${String(date.getUTCMinutes()).padStart(2, '0')}`
132  const day = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][date.getUTCDay()]
133  return `${label} · resets ${reset - now < 20 * 3600000 ? time : `${day} ${time}`}`
134}
135
136export function saveUntil(hot: Hot | null, now: number): number {
137  const reset = hot?.resetsAt ? Date.parse(hot.resetsAt) : NaN
138  return Number.isFinite(reset) && reset > now ? reset : now + 5 * 3600000
139}
140
141/** The context share at which the heavy band turns amber, and its alert opens (a fixed 80%). */
142export const HEAVY_PERCENT = 80
143
144/**
145 * The context percent when it is at or past `HEAVY_PERCENT`, else null. The context atom's percent
146 * is already measured against the compaction window (register.tsx `refreshUsage`).
147 */
148export function swamped(context: SessionContextUsage | null, at: number = HEAVY_PERCENT): number | null {
149  if (!context || context.tokens === undefined) return null
150  const percent = context.percent ?? (context.window > 0 ? context.tokens / context.window * 100 : undefined)
151  return percent !== undefined && percent >= at ? percent : null
152}
153
154/**
155 * The window the context share is measured against: Claude Code's own compaction point
156 * (`autoCompactWindow`) while it is below the model's window, else the model's window.
157 */
158export function contextWindow(window: number, compactAt: number | null | undefined): number {
159  return compactAt !== null && compactAt !== undefined && compactAt > 0 && compactAt < window ? compactAt : window
160}
161
162export function coldAlert(memo: CacheMemo | null, contextTokens: number, now: number, hidden: boolean): boolean {
163  return !hidden && memo !== null && memo.expiresAt <= now && contextTokens >= 150000
164}
165
166/**
167 * Keep-warm held the cache while the person was away: at least one ping read cache tokens and the
168 * memo says the cache is still warm. Once it has expired the cold card is the truth, never this.
169 */
170export function keptAlert(kept: { pings: number; tokens: number } | null, memo: CacheMemo | null, now: number): boolean {
171  return kept !== null && kept.pings > 0 && memo !== null && memo.expiresAt > now
172}
173
174/**
175 * Whether a put-off hot card should be forgotten: only when the window itself has moved on — another
176 * window became the hottest, or its reset moved forward by more than an hour. A reading that is
177 * missing for a while (a routed model's session carries no plan windows) or that comes from the
178 * other source with its reset spelled to the second rather than the minute is the same window, and
179 * forgetting on either brought the card back on every turn (2026-10-14, weekly at 87%).
180 */
181export function hotWindowMoved(previous: Hot | null, next: Hot | null): boolean {
182  if (!previous || !next) return false
183  if (previous.kind !== next.kind) return true
184  const before = previous.resetsAt ? Date.parse(previous.resetsAt) : NaN
185  const after = next.resetsAt ? Date.parse(next.resetsAt) : NaN
186  return Number.isFinite(before) && Number.isFinite(after) && after - before > 3_600_000
187}
188
189export function hotAlert(hot: Hot | null, hidden: number | null): boolean {
190  return hot !== null && hot.percent >= 80 && (hidden === null || hot.percent >= hidden + 10)
191}
192
193/**
194 * The heavy-context band shows once per crossing: seen (or put off) at `hidden` percent, it waits
195 * until the context grows SWAMP_STEP points more. A hidden value over 100 is a token count kept by
196 * an older mod and is ignored.
197 */
198export const SWAMP_STEP = 15
199export function swampAlert(percent: number | null, hidden: number | null): boolean {
200  return percent !== null && (hidden === null || hidden > 100 || percent >= hidden + SWAMP_STEP)
201}
202
203/** Rendering consumes eligibility, keeping dismissal and idle decisions outside drawing code. */
204export function bandPriority(state: {
205  panel?: 'settings' | 'compact' | 'clear' | 'setup' | null
206  judgeDown?: boolean; hot?: boolean; result?: boolean; cold?: boolean; swamp?: boolean; kept?: boolean
207}): 'settings' | 'compact' | 'clear' | 'setup' | 'judgeDown' | 'hot' | 'result' | 'cold' | 'swamp' | 'kept' | 'dashboard' {
208  if (state.panel) return state.panel
209  for (const band of ['judgeDown', 'hot', 'result', 'cold', 'swamp', 'kept'] as const) if (state[band]) return band
210  return 'dashboard'
211}
212
hooks/compact.ts 41 lines
1import type { SessionCompacted, SessionMessage } from 'claude-code'
2
3export const COMPACT_SYSTEM = `Create a faithful continuation record of this coding conversation. Keep the user's intent and changes of mind, decisions and constraints, relevant concepts, files and code touched, errors and their fixes, and user feedback. List user requests in order, distinguish solved from pending work, and state exactly what is happening now. Include a next step only when the conversation justifies it. Preserve useful exact paths and commands, but omit secrets, redundant logs, and obsolete detail. Do not invent verification or claim unfinished work is complete. Write in the user's language.`
4
5function clipped(text: string, limit: number): string {
6  return text.length > limit ? `${text.slice(0, limit)}\n[truncated]` : text
7}
8
9function render(messages: readonly SessionMessage[], tight: boolean): string {
10  return messages.map((message, index) => {
11    const tail = index >= messages.length - 6
12    const inputLimit = tail ? (tight ? 4000 : 20000) : 400
13    const resultLimit = tail ? (tight ? 4000 : 20000) : (tight ? 300 : 2000)
14    const parts = [`${message.role}:\n${message.text}`]
15    for (const use of message.toolUses) {
16      parts.push(`tool ${use.tool} (${use.tool_use_id}):\n${clipped(JSON.stringify(use.input), inputLimit)}`)
17      const result = use.text ?? (use.result !== undefined ? JSON.stringify(use.result) : undefined)
18      if (result !== undefined) parts.push(`result${use.isError ? ' ERROR' : ''}:\n${clipped(result, resultLimit)}`)
19    }
20    if (!message.toolUses.length) {
21      for (const result of message.toolResults ?? []) parts.push(`result ${result.tool_use_id}${result.isError ? ' ERROR' : ''}:\n${clipped(result.text, resultLimit)}`)
22    }
23    return parts.join('\n\n')
24  }).join('\n\n---\n\n')
25}
26
27/** Shrink only tool bulk; losing user intent to hit a budget is worse than engine fallback. */
28export function serializeTranscript(messages: readonly SessionMessage[], budget = 2400000): string | null {
29  if (!messages.length) return null
30  const full = render(messages, false)
31  if (full.length <= budget) return full
32  const tight = render(messages, true)
33  return tight.length <= budget ? tight : null
34}
35
36/** No handle: the engine builds this replacement from role, text and tool blocks. */
37export function compactResult(summary: string): SessionCompacted {
38  return { messages: [{ role: 'user', toolUses: [], text:
39    `Continuation record from the previous conversation:\n\n${summary.trim()}\n\nResume the pending work from this record. Do not repeat completed work or ask for information already recorded.` }] }
40}
41
hooks/handoff.ts 14 lines
1// The band's Handoff (2026-10-24): one press has the session's own model write a resume note in a
2// fork, and a new session in the same folder opens with it in its prompt box. App changes do not
3// reach a chat already open (a /clear keeps it), so moving on to a new session is the only way to
4// take them up; the button folds "write a handoff, wait, open a session, paste" into one press and
5// one Enter. No advice judge, no choice panel, no settings: those were removed with 8480bae and
6// stay removed.
7
8export const QUICK_PROMPT = `Prepare a concise resume note for a fresh coding chat, in the user's language, about forty lines of bullets. Use only this conversation; do not run tools. Record project, folder and branch if known, the goal, verified completed work, unfinished work and blockers, git state as last checked, decisions and failed approaches, permissions or resume details, and the highest-priority runnable next action. Mark actions requiring the user. Keep only current relevant state and point to files or specs instead of copying them. Exclude secrets, environment values and raw logs. Output only the note, without an introduction or farewell.`
9
10/** The note as the new session's first prompt: the context, then go on with the next action. */
11export function wrapForNewChat(text: string): string {
12  return `Resume context from the previous chat:\n\n${text.trim()}\n\nContinue with the justified next action. If it needs my permission or input, explain what is needed and wait.`
13}
14