SLOPSHOPPER

deckhand

Deckhand — the multi-AI toolbar for Claude Code. A band above the prompt with usage gauges, one-click model buttons, Sub5 parallel sub agents in git worktrees…

panebandguardcommandprompttool
v2.3.0MITupdated 2026-10-18stephen-taipei/deckhand/plugins/deckhand
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · deckhand
│ ┃ Codex inbox ✕ › fix the failing auth test and add an audit log call │ ┃ This project · last 7 days [ Refresh ] [ All │ ┃ ⏺ Read(src/auth.ts) │ ┃ Failed to read: JSON Parse error: Unexpected ⎿ Read 6 lines │ ┃ identifier "dev" ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ [ Close ] ⏺ 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 │ │ › /watch-deploy │ ⎿ deckhand: No watches. Usage: /watch-deploy #128, /watch-deploy h │ │ 5h 31% · 7d – · ctx 49% [ O ] [ F ] [ S ] [ H ] [ Sub5 ] [ cL ] [ cS ] [ cA ] [ cR ] [ gF ] [ Recap ] [ iG ] [ ⚙ ] ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
5h 31% · 7d – · ctx 49% [ O ] [ F ] [ S ] [ H ] [ Sub5 ] [ cL ] [ cS ] [ cA ] [ cR ] [ gF ] [ Recap
Pane · Codex inbox
This project · last 7 days [ Refresh ] [ All projects ] Failed to read: JSON Parse error: Unexpected identifier "dev" [ Close ]
Pane · Sub5 leftovers
Removed: worktrees with no uncommitted change, and branches merged into the base. Anything uncommitted, unmerged, locked, checked out or used in the last hour stays. Could not list the leftovers: dev [ Refresh ] [ Close ]
Pane · Delegate records
Delegate runs · last 3 days [ Refresh ] Failed to read: JSON Parse error: Unexpected identifier "dev" [ Close ]
Pane · Deckhand settings
[ General ] [ Delegates ] [ Translate & search ] [ Sub5 ] [ Language Display language Auto (Claude Code's language) ▾ Band buttons Which parts of the band above the prompt show. [ ☑ Usage ] [ ☑ Model buttons ] [ ☐ Also in the desktop app Usage warning (%) 80 ⏎ Save [ Close ]
Pane · deckhand-recap
[ Again ] [ Close ]
Pane · deckhand-galaxy
iG expands a goal into a galaxy of options in your browser, then locks your choices as constraints for Claude. It needs Intent Galaxy, which is not installed yet. Install runs npm install @stephen.taipei/intent-galaxy into ~/.deckhand/intent-galaxy, with install scripts off. Your Claude Code settings do not change; delete that folder to remove it. Checking Node.js… [ Cancel ]
README

<img src="docs/images/wordmark-light.svg" alt="Deckhand" width="360">

Deckhand — the multi-AI toolbar for Claude Code

Many hands, one deck.

Usage gauges, one-click model switching, parallel sub agents and read-only second opinions from other AI CLIs, in one band above the Claude Code prompt.

Version Python Claude Code License CI

English · 繁體中文 · 简体中文 · 日本語 · 한국어

Install · The band · Delegate buttons · Settings · More tools · Privacy and safety · Sponsor · Changelog

The Deckhand band above the Claude Code prompt: in the desktop app (usage, Sub5, delegate buttons, Recap and settings) and in the terminal, where the model buttons O F S H also show

<sub>Screenshots show the Traditional Chinese display language.</sub>

Sponsor Deckhand with USDT (TRC20) — one-time support only.

What Deckhand does

Deckhand is a Claude Code plugin. It adds a band above the prompt, in the terminal and in the desktop app. Claude stays the main agent. From the band you can:

  • see how much of each usage window is left;
  • switch the model with one click;
  • split a task across parallel sub agents in separate git worktrees;
  • ask another AI CLI for a read-only second opinion, which Claude then reviews;
  • get a plain-language recap of where the session stands.

Install

Run these two commands in Claude Code:

/plugin marketplace add stephen-taipei/deckhand
/plugin install deckhand@deckhand

The band appears above the prompt. If it does not, start a new session.

Updates

To get new versions on their own, turn on auto-update for the deckhand marketplace in /plugin, under Marketplaces. Without it, Deckhand tells you once when a new release is out: it asks GitHub once a day, and you can turn that off in ⚙ → Advanced → Updates. To update by hand, run this in a terminal, then restart Claude Code:

claude plugin marketplace update deckhand
claude plugin update deckhand@deckhand

The band

PartWhat it does
Usage gauges5-hour window, per-model weekly windows, weekly all-models window and context window
O F S HSwitch the model to Opus, Fable, Sonnet or Haiku
Sub5Split the current task into up to 5 items and run them in parallel sub agents
cL cS cA cR gFHand one task to another AI CLI, read-only, and let Claude review the answer
RecapExplain the current context plainly, with analogies, in a side pane
iGExpand the goal in the prompt box into a galaxy with Intent Galaxy, then lock it as constraints
⚙Open the settings pane (right end of the band)

Hover a button to see what it does.

Usage gauges

  • 5h: the 5-hour window.
  • Per-model weekly windows that your account has, for example fb for Fable.
  • 7d: the weekly window across all models.
  • ctx: how full the context window is.

The numbers match the usage card in the Claude app (rounded down). When a window crosses the warning threshold, Deckhand shows a toast once.

Model buttons

O Opus · F Fable · S Sonnet · H Haiku

  • Terminal: the button switches the session model directly and keeps your effort level.
  • Desktop app: the app owns the session model there, and a plugin cannot switch it in one click: Claude Code refuses a plugin prompt that starts with /, and the app refuses a session that sets its own model. So the button puts /model <full model id> in the prompt box, for example /model claude-opus-5-5, because the app's model menu knows models only by full id (if the box has text, send or clear it first). Press Enter in the prompt box: the model switches, the app's model menu follows, and Deckhand puts your effort level back. If the box cannot take the text (a dialog is open), the command goes to the clipboard instead: paste it into the prompt box and press Enter. These buttons are off by default in the desktop app, because its own model menu already switches in a click. To show them, turn on Also in the desktop app in the General tab of settings.

Sub5

Sub5 splits the current task into up to 5 independent items. Each item runs in its own sub agent, in its own git worktree, at the same time. When the workers finish, the main agent reviews their work, integrates it, and cleans up the worktrees and branches.

A script (bin/sub5.py) runs the exact git steps. It never pushes, and never forces a dirty worktree. It deletes a worker branch only once every file of it is verified in your worktree (content, file type, executable bit), and prints the branch's tip so you can bring it back. You can set the workers' model, effort and the maximum number of items in settings.

A run that is interrupted (the turn is stopped, a worker fails, the session closes) can leave worktrees and branches behind. /sub5-clean, or Review in the Sub5 tab of settings, lists them and, after you confirm, removes only the safe ones: worktrees with no uncommitted change and branches already merged; anything used in the last hour stays.

Delegate buttons

A delegate button hands one task to another AI CLI. That AI works read-only and writes an answer. Claude reviews the answer and integrates what holds up.

ButtonCLIModelEffort
cLCodexGPT-6 Lunamax
cSCodexGPT-6.1 Solmedium
cACodexGPT-6 Astramedium
cRCursor agentGrok 4.7high
gFagyGemini 3.8 Flashhigh

These are the defaults. In settings you can edit every target: label, CLI, model ID, effort, name, and on/off.

  • Read-only, per CLI: Codex runs with -s read-only, Cursor agent with --mode ask, and agy runs headless, which denies tools automatically.
  • Web search (search only): Codex gets -c web_search="live", and Cursor agent gets --auto-review (still in ask mode) so that a search runs without asking. agy can already search in headless mode.
  • Secret check: Deckhand refuses a brief that contains a token, key or password. The check matches common formats; it cannot prove a brief holds nothing sensitive, and it does not see the files the CLI itself reads.
  • Local records: the brief and the answer stay in a private temporary folder. Records older than 3 days are deleted the next time a delegate runs.
  • Progress in the band: while a delegate runs, a row above the usage line shows its label, CLI, model and elapsed time. When it ends, the row shows the outcome for 10 minutes, or until you press Clear finished. There is no Stop button: Deckhand only watches the Bash call that runs the delegate.
  • Records: the /delegates command, or Records on a finished row, lists the runs from the last 3 days. You can open each answer in full, copy it, or put it into the prompt box when the box is empty. Each run also shows the tokens its CLI counted, with a 3-day total per CLI at the top; Deckhand does not estimate prices, so a cost appears only if the CLI itself reports one (Codex, the Cursor agent and agy report none today).
  • Requirements: the CLI must be installed and logged in. Buttons for CLIs that are not installed are hidden.

[!NOTE] Delegating sends the brief to the provider behind that CLI.

Recap

Recap explains the whole current context as plainly and briefly as possible, with analogies, in a side pane. It does not add anything to the conversation. The button reads Recap in every language.

iG (Intent Galaxy)

iG, right of Recap, hands the main agent the goal in the prompt box (with none, the current work) to run through Intent Galaxy: Claude calls intent_spawner_prompt, writes the galaxy itself, and calls intent_open_galaxy, which opens the galaxy in your browser. While it waits for you to lock it, the band shows how to drive it (1 2 3, Space, x, Enter). The locked intent comes back to the conversation as constraints, and Claude waits for you before it starts the work.

  • With Intent Galaxy's MCP server connected, under any name, iG uses its tools.
  • Without it, the first press opens a pane that asks before anything happens. It checks for Node.js 22.18 or later, then Install and enable runs npm install @stephen.taipei/intent-galaxy into ~/.deckhand/intent-galaxy (install scripts off) and offers the same two tools through Deckhand, in the same conversation. Your Claude Code MCP settings do not change; delete that folder to remove it.
  • Hide the button in Settings → General.

Settings

The ⚙ button at the right end of the band, or /deckhand, opens the settings pane. It has five tabs:

TabWhat you set
GeneralDisplay language, which buttons show, the usage warning threshold
DelegatesEach delegate target: on/off, label, CLI, model ID, effort, name
Translate & searchWhether translation and web search go to a delegate, and which one (cL … gF). Both are off by default.
Sub5The workers' model, effort and maximum number of items; how many worktrees interrupted runs left behind
AdvancedCLI paths and the Codex home folder, the guards, the update check, the deploy watch, the settings file, reset to defaults

Deckhand settings: the General tab and the Translate & search tab

Settings are stored per user, on this machine. Settings file in the Advanced tab exports them as JSON (by default to ~/.deckhand-settings.json), imports such a file back after showing how many settings change, or copies them to the clipboard.

Languages

41 locales: English, 繁體中文(Taiwan, Hong Kong, generic), 简体中文, 日本語, 한국어, Tiếng Việt, Українська, Türkçe, ไทย, Svenska, Slovenčina, Русский, Română, Português (Portugal, Brasil), Polski, Nederlands, Norsk bokmål, မြန်မာ, Bahasa Melayu, ລາວ, ខ្មែរ, Italiano, Bahasa Indonesia, Magyar, Hrvatski, हिन्दी, עברית, Français, Filipino, Suomi, Español (España, México), Ελληνικά, Deutsch, Dansk, Čeština, Català, العربية. English, 繁體中文 (Taiwan), 简体中文, 日本語 and 한국어 are maintained with every change; the other 36 are machine-translated with local wording and may read less naturally. By default the display language follows Claude Code's language setting. You can also pick a language in settings.

More tools

ToolWhat it does
/watch-deploy and the watch_deploy toolWatch a PR, a CI run or a URL in the background. The watch stops itself after N identical results in a row. In the Claude desktop app, the tool leaves a PR to the app's own PR bar and watches only runs, commits and URLs; /watch-deploy still watches whatever you give it.
/handoff, /handoff-in, /codexHand work between Claude and Codex: write a handoff for Codex, bring Codex's latest handoff back into the prompt box, and open the Codex inbox.
Attribution guardStrips Co-Authored-By trailers and the Claude Code footer from commit and PR commands. Off by default, unless your Claude settings already turn attribution off. In the desktop app, which already tells Claude to leave attribution out, Deckhand adds no reminder of its own and only strips.
Polling guardStops sleep polling loops and blocking waits such as gh run watch, and stops a status check that returns the same result N times in a row. In the desktop app, a blocked PR wait points Claude to the app's PR bar instead of watch_deploy.
translateLocalized translation by the delegate you pick in settings, in the wording native speakers use rather than word for word. Off by default: turn it on in ⚙.
searchWeb research by the delegate you pick in settings: a short answer, key points and the source of each, which Claude then checks. Off by default: turn it on in ⚙.

Requirements

  • macOS or Linux. Windows has not been tested yet.
  • Claude Code 2.1.299 or later. The hooks module is split across files, and earlier versions refuse to load it. The desktop app runs its own copy of Claude Code: update the app until that copy is 2.1.299 or later.
  • Python 3.9 or newer.
  • Optional: gh for watches; the codex, Cursor agent and agy CLIs for the delegate buttons.

Privacy and safety

What leaves your machine:

  • Delegate briefs go to the provider of the CLI you chose, and only when you press a delegate button.
  • The usage readout calls Anthropic's usage endpoint with the session's own credential, through Claude Code.
  • The update check asks GitHub's API for Deckhand's newest release, once a day. The request carries nothing about you or your work. Turn it off in ⚙ → Advanced → Updates.
  • Installing Intent Galaxy downloads @stephen.taipei/intent-galaxy from the npm registry, and only after you press Install and enable. The galaxy itself runs on 127.0.0.1.
  • Tools that you or Claude call on purpose reach the service they name: translate and search, once you turn them on, send their text to the delegate you picked, and a watch queries GitHub through gh or fetches the URL you gave it.

Nothing else leaves your machine.

Safety rules:

  • Delegates are read-only, enforced by each CLI's own flag or mode.
  • The secret check refuses briefs that contain tokens, keys or passwords. It is pattern-based: it cannot prove a brief holds nothing sensitive.
  • Briefs and answers are kept in a private temporary folder; records older than 3 days are pruned the next time a delegate runs.
  • Sub5's git script never pushes and never forces a dirty worktree. It deletes a worker branch only after verifying its work is in your worktree, and prints the tip to restore it.

Development

(cd plugins/deckhand && python3 -m unittest discover -s tests -p 'test_*.py')
python3 -m unittest discover -s scripts -p 'test_*.py'
python3 scripts/scan-secrets.py

scripts/scan-secrets.py checks every tracked file for keys, tokens, credentials in URLs, email addresses and home-folder paths. See CONTRIBUTING.md.

Sponsor

One-time USDT support helps maintain Deckhand's code, documentation and five-language localization. It does not buy membership, roadmap priority or support priority.

USDT · TRON (TRC20) · TGuMUi1d8MoBQcuFrGJZnu4JrbaeP3wy9a

<img src="docs/images/sponsor-usdt-trc20.png" alt="USDT (TRC20) QR: TGuMUi1d8MoBQcuFrGJZnu4JrbaeP3wy9a" width="160">

Send USDT on the TRON (TRC20) network only. Tokens sent on another network cannot be recovered.

Contributing, security and license

Contributing · Security policy · Changelog · License

Made and maintained by stephen-taipei. Deckhand is an independent plugin and is not an Anthropic product. Released under the MIT License.

Source 61 files
hooks/register.tsx 277 lines
1import { read } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { DelegateTool, Watch } from '../types'
5import { sendHeldHandOver, startDelegate, startSub5 } from './actions'
6import { registerBand } from './band'
7import { cfg, currentLocale, isDesktopApp, loadSettings, msgs, resolveBin } from './core'
8import type { Engine } from './core'
9import { assistArgv, findTarget, SEARCH_MINUTES, targetLabel, TOOL_NAME, TRANSLATE_MINUTES } from './delegate'
10import { awaitedRuns, noteTaskEnded, registerDelegates, settleRun, startRun, syncRunTimers } from './delegates'
11import { blockingWait, executable, normalizeOutput, recordStrike, statusKey, stripAttribution } from './guard'
12import type { Strike } from './guard'
13import { detectGalaxy, offerInstalled, registerGalaxy } from './galaxy'
14import { registerHandoff, syncSharedTool } from './handoff'
15import { messages } from './i18n'
16import { registerLeftovers } from './leftovers'
17import { loadUsage, refreshAccountUsage, refreshModel, registerModels, rememberEffort } from './models'
18import { registerRecap } from './recap'
19import { parseDelegateCall } from './runs'
20import { buildSearchPrompt } from './search'
21import type { SearchInput } from './search'
22import { ASSISTS, assistTarget, checkBins, checkForUpdate, registerAssist, registerCommands, registerWorker } from './session'
23import type { Assist } from './session'
24import type { DelegateTarget, Settings } from './settings'
25import { markSettingsOpen, registerSettingsPane, SETTINGS_PANE } from './settings-pane'
26import { errorText, text } from './state'
27import { buildPrompt, cleanOutput, findSecret } from './translate'
28import type { TranslateInput } from './translate'
29import { effortLevel } from './usage'
30import { registerWatches, resumeWatches, WATCH_TOOL, watchSettingsOf } from './watches'
31
32const TRANSLATE_TOOL = 'mcp__deckhand__translate'
33const SEARCH_TOOL = 'mcp__deckhand__search'
34
35// ── Translate and search: work handed to a delegate, off until the person turns it on ──
36
37/**
38 * Runs one translation or web search through delegate.py (the chosen CLI, read-only, secrets checked
39 * again; `--raw`: the prompt is whole and stdout is the answer alone) and answers the tool call.
40 */
41async function runAssist($: Engine, kind: Assist, prompt: string, clean: (stdout: string) => string) {
42  const m = await msgs($)
43  const s = await cfg($)
44  const words = m[kind]
45  const target = assistTarget(s, kind)
46  const who = `${target.key} · ${targetLabel(target, m)}`
47  const explicit: Record<DelegateTool, string> = { codex: s.paths.codexBin, agent: s.paths.agentBin, agy: s.paths.agyBin }
48  const minutes = kind === 'search' ? SEARCH_MINUTES : TRANSLATE_MINUTES
49  try {
50    const ran = await $.process.run(
51      assistArgv({
52        python: await resolveBin($, 'python3'),
53        tool: `${$.plugin.root}/bin/delegate.py`,
54        target,
55        locale: await currentLocale($),
56        bin: explicit[target.tool] || undefined,
57        codexHome: s.paths.codexHome || undefined,
58        minutes,
59        web: kind === 'search',
60      }),
61      { stdin: prompt, timeoutMs: minutes * 60_000 + 30_000 },
62    )
63    const out = clean(ran.stdout)
64    if (ran.exitCode !== 0 || !out) {
65      const why = (ran.stderr || ran.stdout).trim().split('\n').slice(-3).join(' ') || `exit ${ran.exitCode}`
66      return { deny: words.failed(who, why) }
67    }
68    return { result: `${out}\n\n---\n${words.footer(who)}` }
69  } catch (error) {
70    return { deny: words.cannotRun(who, errorText(error)) }
71  }
72}
73
74// ── Routing: what the model is told about the plugin ────────────────────────
75
76const who = (t: DelegateTarget) => `${t.key}: ${TOOL_NAME[t.tool]} · ${t.name}`
77
78/** A command about a pull request: in the desktop app its CI is the app PR bar's to watch. */
79const PR_COMMAND = /\bgh\s+pr\b|\/pulls\/\d+/
80
81const NO_POLLING =
82  'Never poll with sleep loops, `gh run watch`, `gh pr checks --watch` or repeated gh/curl status checks; the plugin polls locally, stops itself after repeated identical results and notifies the user.'
83
84const routing = (s: Settings, isDesktop: boolean) =>
85  [
86    "Deckhand (the user's Claude Code plugin):",
87    isDesktop
88      ? `- In the desktop app a PR's CI is watched by the app: bind the PR with the ccd_pr tools and let its CI monitor notify you. To wait for an Actions run, a commit's CI (sha:), a merge's CI or a deploy, call ${WATCH_TOOL} once and end your turn. ${NO_POLLING}`
89      : `- To wait for a PR, CI run, merge or deploy, call ${WATCH_TOOL} once and end your turn. ${NO_POLLING}`,
90    ...(s.translate.enabled
91      ? [
92          `- To translate i18n strings, docs or copy, call ${TRANSLATE_TOOL} (${who(assistTarget(s, 'translate'))}, localized-wording standard), then review terms and format before using the result. Never put secrets in it.`,
93        ]
94      : []),
95    ...(s.search.enabled
96      ? [
97          `- For web research (docs, versions, prices, recent changes), call ${SEARCH_TOOL} (${who(assistTarget(s, 'search'))}) instead of running many searches yourself, then check the sources your answer depends on. Never put secrets in it.`,
98        ]
99      : []),
100    // The desktop app already tells the model this in every session; the guard still strips what slips through.
101    ...(s.guards.attribution && !isDesktop ? ['- Commit messages and PR descriptions carry no Co-Authored-By trailer and no "Generated with Claude Code" footer.'] : []),
102  ].join('\n')
103
104export const register: Register = on => {
105  registerBand(on)
106  registerSettingsPane(on)
107  registerModels(on)
108  registerDelegates(on)
109  registerWatches(on)
110  registerLeftovers(on)
111  registerHandoff(on)
112  registerRecap(on)
113  registerGalaxy(on)
114  const strikes = new Map<string, Strike>()
115
116  on('session.start', async ($, e, next) => {
117    const s = await loadSettings($)
118    // After a reload the engine still knows which panes are up; ⚙ reads its state from that.
119    const isUp = (await $.ui.panes().catch(() => [])).some(p => p.id === SETTINGS_PANE)
120    await markSettingsOpen($, isUp)
121    const m = await msgs($)
122    await registerCommands($, m, s)
123    await registerWorker($, m, s)
124    await $.tool.register({
125      name: 'watch_deploy',
126      description:
127        'Watch a GitHub PR, an Actions run, all CI runs of a commit, or a deployed URL in the background, without spending tokens. ' +
128        'Use this INSTEAD of sleep/poll loops, `gh run watch`, `gh pr checks --watch` or repeated gh/curl status checks. ' +
129        'target: "#128", "run:123", "sha:<commit>", a GitHub PR or Actions run URL, or an https URL. ' +
130        'expect (URL only, strongly recommended): text whose appearance means the new version is live (a commit sha, a version string). ' +
131        'Without it the watch compares the page itself and needs two checks to confirm a change. ' +
132        'Returns the current state at once. When the watch finishes, or stops after repeated identical results, the user gets a toast and a [deckhand] note is added to this conversation. ' +
133        "A merged PR automatically continues as a watch of its merge commit's CI runs. After calling it, end your turn instead of polling.",
134      inputSchema: {
135        type: 'object',
136        properties: {
137          target: { type: 'string', description: 'PR / run / commit / URL to watch.' },
138          expect: { type: 'string', description: 'For a URL: text that proves the new deploy is live.' },
139        },
140        required: ['target'],
141      },
142    })
143    for (const kind of ASSISTS) await registerAssist($, s, kind)
144    // The usage readout lives in the band above the prompt: no status line.
145    $.ui.status(undefined)
146    await syncSharedTool($)
147    await resumeWatches($)
148    await syncRunTimers($)
149    await loadUsage($).catch(() => undefined)
150    await refreshModel($)
151    void refreshAccountUsage($, true).catch(() => undefined)
152    void checkBins($).catch(() => undefined)
153    // MCP servers connect after the session starts: look now, and again once they have had time.
154    void offerInstalled($).then(() => detectGalaxy($)).catch(() => undefined)
155    $.clock.after(8_000, () => void detectGalaxy($).catch(() => undefined))
156    void checkForUpdate($).catch(() => undefined)
157    return next(e)
158  })
159
160  // ── Guards, translation, usage, routing ─────────────────────────────────
161
162  on('prompt.submit', async ($, e, next) => {
163    // A stopped check resumes only after the user speaks again.
164    strikes.clear()
165    // An MCP server connected or dropped since the last look: the iG button follows.
166    void detectGalaxy($).catch(() => undefined)
167    // A background delegate run ends with its task's notification.
168    if (e.text.includes('<task-notification>')) void noteTaskEnded($, e.text).catch(() => undefined)
169    return next(e)
170  }).catch(($, e, next) => next(e))
171
172  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
173    const s = await cfg($)
174    const m = await msgs($)
175    const notes: string[] = []
176    const stripped = s.guards.attribution ? stripAttribution(e.command) : null
177    const command = stripped ?? e.command
178    if (stripped !== null) notes.push(m.guard.stripped)
179    const limit = watchSettingsOf(s).limit
180    const key = s.guards.polling ? statusKey(command) : null
181    if (s.guards.polling) {
182      const wait = blockingWait(command, m)
183      const isStuck = key !== null && (strikes.get(key)?.count ?? 0) >= limit
184      const isAppPr = (wait !== null || isStuck) && PR_COMMAND.test(executable(command)) && (await isDesktopApp($))
185      if (wait) return { deny: isAppPr ? m.guard.blockingPr(wait) : m.guard.blocking(wait, WATCH_TOOL) }
186      if (isStuck) return { deny: isAppPr ? m.guard.repeatedPr(limit) : m.guard.repeated(limit, WATCH_TOOL) }
187    }
188    // A delegate.py run gets a row in the band while it runs; its brief is never read.
189    const call = s.show.delegates ? parseDelegateCall(command) : null
190    const runId = call ? await startRun($, call, e.tool_use_id || `run-${(await $.clock.now()).toString(36)}`).catch(() => null) : null
191    let ran
192    try {
193      ran = await next(stripped === null ? e : { ...e, command })
194    } finally {
195      if (runId) awaitedRuns.delete(runId)
196    }
197    if (runId) await settleRun($, runId, ran).catch(() => undefined)
198    if (ran.deny !== undefined) return ran
199    if (key) {
200      const count = recordStrike(strikes, key, normalizeOutput(ran.text ?? ''))
201      if (count >= limit) notes.push(m.guard.repeatNote(count))
202    }
203    return notes.length ? { ...ran, context: [...(ran.context ?? []), ...notes] } : ran
204  }).catch(($, e, next) => next(e))
205
206  on('tool.call', { tool: TRANSLATE_TOOL }, async ($, e) => {
207    const m = await msgs($)
208    const s = await cfg($)
209    const raw = e as unknown as Record<string, unknown>
210    const input: TranslateInput = {
211      text: text(raw.text),
212      target: text(raw.target).trim(),
213      source: text(raw.source).trim() || undefined,
214      context: text(raw.context).trim() || undefined,
215      glossary: Array.isArray(raw.glossary) ? raw.glossary.filter((g): g is string => typeof g === 'string') : undefined,
216    }
217    if (!s.translate.enabled) return { deny: m.translate.off }
218    if (!input.text.trim() || !input.target) return { deny: m.translate.needs }
219    if (findSecret(input.text) || findSecret(input.context ?? '')) return { deny: m.translate.sensitiveRefused }
220    return runAssist($, 'translate', buildPrompt(input), out => cleanOutput(out, input.text))
221  }).catch(async ($, _e, next) => ({ deny: (await msgs($)).translate.internal(errorText(next.error)) }))
222
223  on('tool.call', { tool: SEARCH_TOOL }, async ($, e) => {
224    const m = await msgs($)
225    const s = await cfg($)
226    const raw = e as unknown as Record<string, unknown>
227    const input: SearchInput = {
228      question: text(raw.question).trim(),
229      context: text(raw.context).trim() || undefined,
230      freshness: text(raw.freshness).trim() || undefined,
231    }
232    if (!s.search.enabled) return { deny: m.search.off }
233    if (!input.question) return { deny: m.search.needs }
234    if (findSecret(input.question) || findSecret(input.context ?? '')) return { deny: m.search.sensitiveRefused }
235    return runAssist($, 'search', buildSearchPrompt(input, m.languageName), out => out.trim())
236  }).catch(async ($, _e, next) => ({ deny: (await msgs($)).search.internal(errorText(next.error)) }))
237
238  // The engine measures the session after each main-thread turn and when a limit moves a whole point:
239  // the readout is pushed to, not polled.
240  // The effort the last turn really ran at (after any downgrade the model needed): what a switch keeps.
241  on('classic.Stop', async ($, e, next) => {
242    const level = effortLevel(e.effort?.level)
243    if (!e.agent_id && level) await rememberEffort($, level)
244    if (!e.agent_id) sendHeldHandOver($)
245    return next(e)
246  }).catch(($, e, next) => next(e))
247
248  on('command.run', { command: 'sub5' }, async ($, e) => {
249    const note = e.args.trim()
250    // The engine refuses prompt.submit from inside a command hook (it would wait on the turn this hook
251    // holds): a timer's callback is a later event, and submits from there.
252    $.clock.after(10, () => void startSub5($, note, false).catch(() => undefined))
253    return { text: (await msgs($)).sub5.scheduled }
254  })
255
256  on('command.run', { command: 'delegate' }, async ($, e) => {
257    const m = await msgs($)
258    const s = await cfg($)
259    const args = e.args.trim()
260    const first = args.split(/\s+/)[0] ?? ''
261    const target = first ? findTarget(s.delegates, first) : undefined
262    if (!target) {
263      return { text: m.delegate.usage(s.delegates.filter(t => t.enabled).map(t => `  ${t.key}  ${targetLabel(t, m)}`)) }
264    }
265    const task = args.slice(first.length).trim()
266    // Same as /sub5: the engine refuses prompt.submit from inside a command hook, a timer submits later.
267    $.clock.after(10, () => void startDelegate($, target, task, false, false).catch(() => undefined))
268    return { text: m.delegate.scheduled(target.key) }
269  })
270
271  on('prompt.compose', async ($, e, next) => {
272    const composed = await next(e)
273    const s = await cfg($)
274    return { sections: [...composed.sections, { id: 'deckhand:routing', text: routing(s, await isDesktopApp($)), scope: 'session' as const }] }
275  })
276}
277
hooks/actions.ts 122 lines
1/** Handing work to the main agent: the Sub5 and delegate buttons, and the hand-over that waits for a running turn to end. */
2import { cfg, currentLocale, msgs } from './core'
3import type { Engine } from './core'
4import { delegatePrompt, targetLabel } from './delegate'
5import type { DelegateTarget, DelegateTool } from './settings'
6import { errorText } from './state'
7import { sub5Prompt } from './sub5'
8import { TOAST } from './ui'
9
10/**
11 * What the Sub5 and delegate buttons hand the main agent: the full brief as a row only the model reads,
12 * then one short line in the person's name, so the transcript shows the request and not the procedure.
13 * If the engine will not take the row, the brief goes as the prompt itself, as before.
14 */
15export async function handOver($: Engine, visible: string, brief: string) {
16  const row = await $.session
17    .append({ message: { type: 'user', content: [{ type: 'text', text: brief }] } })
18    .catch(() => ({ deny: 'failed' }) as const)
19  await $.prompt.submit({ text: row.deny ? brief : visible, asUser: true })
20}
21
22/** The main turn ended: a hand-over held while it ran goes now. */
23export function sendHeldHandOver($: Engine) {
24  const held = heldHandOver
25  if (!held) return
26  heldHandOver = null
27  // After the turn has ended: a hook may not start the next turn itself.
28  $.clock.after(10, () => void handOver($, held.visible, held.brief).catch(error => $.ui.log(`deckhand: hand-over not sent (${errorText(error)})`)))
29}
30
31/** Now when idle; when a turn runs, held for its end (the brief row would otherwise reach that turn). */
32export async function handOverWhenIdle($: Engine, visible: string, brief: string, isWorking: boolean) {
33  if (isWorking) {
34    heldHandOver = { visible, brief }
35    return
36  }
37  await handOver($, visible, brief)
38}
39
40/** The Sub5 button and `/sub5`: hands the main agent the flow as the user's own instruction. */
41export async function startSub5($: Engine, note: string, isWorking: boolean) {
42  const m = await msgs($)
43  const s = await cfg($)
44  const now = await $.clock.now()
45  if (now - lastSub5At < 8_000) {
46    $.ui.toast(m.sub5.guard, { timeoutMs: TOAST.problem })
47    return false
48  }
49  lastSub5At = now
50  $.ui.toast(isWorking ? m.sub5.queued : m.sub5.sent, { timeoutMs: TOAST.info })
51  try {
52    const brief = sub5Prompt(
53      { ...s.sub5, tool: `${$.plugin.root}/bin/sub5.py`, note, locale: await currentLocale($), attribution: s.guards.attribution },
54      m,
55    )
56    await handOverWhenIdle($, m.sub5.visible(note.trim() || m.delegate.currentTask), brief, isWorking)
57  } catch (error) {
58    lastSub5At = 0
59    $.ui.toast(m.sub5.failed(errorText(error)), { timeoutMs: TOAST.problem })
60    return false
61  }
62  return true
63}
64
65/**
66 * A delegate button, or `/delegate`: hands the main agent one delegation to an outside model, as the
67 * user's own instruction. The task is `task` when one is given, else (`useDraft`) the draft in the
68 * prompt box, else the conversation's current work. This never touches the main agent's model or effort.
69 */
70export async function startDelegate($: Engine, target: DelegateTarget, task: string, isWorking: boolean, useDraft: boolean) {
71  const m = await msgs($)
72  const s = await cfg($)
73  const now = await $.clock.now()
74  if (now - lastDelegateAt < 8_000) {
75    $.ui.toast(m.delegate.guard, { timeoutMs: TOAST.problem })
76    return false
77  }
78  lastDelegateAt = now
79  let taskText = task.trim()
80  let draft = ''
81  if (!taskText && useDraft) {
82    // Only a surface that gives the plugin its prompt box has a draft to read; the others read ''.
83    draft = (await $.prompt.read().catch(() => ({ text: '', cursor: 0 }))).text.trim()
84    taskText = draft
85  }
86  // The draft leaves the box now, not after the turn: `submit` waits for the turn, and a draft left
87  // standing could be sent a second time.
88  if (draft) await $.prompt.fill({ text: '' }).catch(() => undefined)
89  const source = draft ? m.delegate.fromBox : taskText ? m.delegate.fromCommand : m.delegate.currentWork
90  const label = targetLabel(target, m)
91  $.ui.toast(isWorking ? m.delegate.queued(target.key, label, source) : m.delegate.sent(target.key, label, source), { timeoutMs: TOAST.info })
92  const explicit: Record<DelegateTool, string> = { codex: s.paths.codexBin, agent: s.paths.agentBin, agy: s.paths.agyBin }
93  try {
94    const brief = delegatePrompt(
95      {
96        tool: `${$.plugin.root}/bin/delegate.py`,
97        target,
98        locale: await currentLocale($),
99        bin: explicit[target.tool] || undefined,
100        codexHome: s.paths.codexHome || undefined,
101        task: taskText,
102        attribution: s.guards.attribution,
103      },
104      m,
105    )
106    await handOverWhenIdle($, m.delegate.visible(target.key, label, taskText || m.delegate.currentTask), brief, isWorking)
107  } catch (error) {
108    lastDelegateAt = 0
109    if (draft) await $.prompt.fill({ text: draft }).catch(() => undefined)
110    $.ui.toast(m.delegate.failed(target.key, errorText(error)), { timeoutMs: TOAST.problem })
111    return false
112  }
113  return true
114}
115
116/** A hand-over pressed while a turn ran: sent when that turn ends, so the running turn never reads it. */
117let heldHandOver: { visible: string; brief: string } | null = null
118
119let lastSub5At = 0
120
121let lastDelegateAt = 0
122
hooks/band.tsx 184 lines
1/** The band above the prompt: the running watches and delegate runs, then the control row (usage, model buttons, Sub5, the delegates, Recap, a tip slot and ⚙). */
2import type { On } from 'claude-code'
3
4import { startDelegate, startSub5 } from './actions'
5import { cfgForDrawing, msgsForDrawing } from './core'
6import { targetLabel } from './delegate'
7import { bandRuns, clearFinishedRows, isFinished, openRecords } from './delegates'
8import { currentModel, currentSegments, pressModel } from './models'
9import { galaxyState, startGalaxy } from './galaxy'
10import { startRecap } from './recap'
11import { runLine, whoOf } from './runs'
12import { foundBins } from './session'
13import { isSettingsShown, toggleSettings } from './settings-pane'
14import { MARK, runState, TONE, usageTone, watchState } from './ui'
15import { MODEL_BUTTONS, modelFamily } from './usage'
16import { bandWatches, hideWatches, isBandHidden, stopWatches } from './watches'
17
18
19/** The hooks of this part of the plugin; register.tsx calls this first. */
20export function registerBand(on: On) {
21  // The band above the prompt: the running watches, then the control row: the usage readout, the model
22  // buttons, Sub5, the delegates, the recap, a tip slot that takes the free width, and ⚙ at the right end.
23  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
24    if (e.props.hasSurvey) return next(e)
25    const { Box, Text, Button } = $.ui.resolve(e)
26    const m = await msgsForDrawing($)
27    const s = await cfgForDrawing($)
28    const watches = await bandWatches($)
29    const hasWatches = watches.length > 0 && !(await isBandHidden($))
30    const hasFinished = watches.some(w => w.status !== 'watching')
31    // Delegate runs: read the tick so the elapsed time is drawn again every second.
32    const runs = s.show.delegates ? await bandRuns($) : []
33    const now = runs.length ? await $.clock.now() : 0
34    const segments = s.show.usage ? await currentSegments($, s.usage.warnPercent, true) : []
35    const family = modelFamily(await currentModel($))
36    const found = await foundBins($)
37    const galaxy = await galaxyState($)
38    // Always offered: without Intent Galaxy, the first press asks to install it.
39    const showGalaxy = s.show.galaxy
40    const isWorking = e.props.isWorking
41    const isSettingsOpen = await isSettingsShown($)
42    const isDesktop = e.surface === 'desktop'
43    // In the desktop app its own model menu switches in a click; the buttons only fill `/model <id>` there.
44    const showModels = s.show.models && (!isDesktop || s.show.modelsOnDesktop)
45    // A target whose CLI is known to be missing has no button; an unchecked one keeps it.
46    const targets = s.show.delegates ? s.delegates.filter(t => t.enabled && found[t.tool] !== null) : []
47    const scope = (id: string) => `deckhand-tip-${id}`
48    const tips = [
49      ...(segments.length ? [{ id: 'usage', text: m.tips.usage }] : []),
50      ...(showModels ? MODEL_BUTTONS.map(b => ({ id: `m-${b.key}`, text: isDesktop ? m.tips.modelDesktop(b.name) : m.tips.model(b.name) })) : []),
51      ...(s.show.sub5 ? [{ id: 'sub5', text: m.tips.sub5(s.sub5.max) }] : []),
52      ...targets.map(t => ({ id: `d-${t.key}`, text: m.tips.delegate(targetLabel(t, m)) })),
53      ...(s.show.recap ? [{ id: 'recap', text: m.tips.recap }] : []),
54      ...(showGalaxy ? [{ id: 'galaxy', text: m.tips.galaxy }] : []),
55      { id: 'gear', text: m.tips.settings },
56      ...runs.filter(isFinished).map(r => ({ id: `dr-${r.id}`, text: m.delegate.recordsTip })),
57    ]
58    // Clear and Hide end the last watch or delegate row instead of taking a line of their own.
59    const shownWatches = hasWatches ? watches.slice(-4) : []
60    const lastRow = runs.length ? `r-${runs[runs.length - 1]!.id}` : shownWatches.length ? `w-${shownWatches[shownWatches.length - 1]!.id}` : ''
61    const rowActions = [
62      ...((hasWatches && hasFinished) || runs.some(isFinished)
63        ? [<Button key="clear" label={m.watch.clearDone} variant="secondary" onPress={() => void clearFinishedRows($)} />]
64        : []),
65      ...(hasWatches ? [<Button key="hide" label={m.watch.hide} variant="secondary" onPress={() => void hideWatches($)} />] : []),
66    ]
67    return (
68      <Box flexDirection="column">
69        {galaxy.isOpen && (
70          <Box key="galaxy-open" gap={1}>
71            <Text color={TONE.accent}>{`${MARK.running} ${m.galaxy.label}`}</Text>
72            <Text dimColor wrap="truncate">
73              {m.galaxy.waiting}
74            </Text>
75          </Box>
76        )}
77        {shownWatches.map(w => {
78          const state = watchState(w.status)
79          return (
80          <Box key={`w-${w.id}`} gap={1}>
81            <Text color={state.tone && TONE[state.tone]}>
82              {state.mark} {w.label}
83            </Text>
84            <Text dimColor wrap="truncate">
85              {w.reason ?? w.summary}
86              {w.status === 'watching' ? m.watch.checkCount(w.checks) : ''}
87            </Text>
88            {w.status === 'watching' && <Button key={`stop-${w.id}`} label={m.watch.stop} variant="secondary" onPress={() => void stopWatches($, w.id)} />}
89            {lastRow === `w-${w.id}` && rowActions}
90          </Box>
91          )
92        })}
93        {runs.map(r => {
94          const line = runLine(r, now, m)
95          const state = runState(r.status)
96          return (
97            <Box key={`r-${r.id}`} gap={1}>
98              <Text color={state.tone && TONE[state.tone]}>
99                {line.mark} {r.label}
100              </Text>
101              <Text dimColor wrap="truncate">
102                {line.text}
103              </Text>
104              {isFinished(r) && (
105                <Button
106                  key={`dr-${r.id}`}
107                  label={m.delegate.records}
108                  variant="secondary"
109                  hover={{ scope: scope(`dr-${r.id}`) }}
110                  onPress={() =>
111                    void openRecords($, r.answerPath && r.status === 'answered' ? { path: r.answerPath, label: r.label, who: whoOf(r.tool, r.name, m) } : undefined)
112                  }
113                />
114              )}
115              {lastRow === `r-${r.id}` && rowActions}
116            </Box>
117          )
118        })}
119        <Box gap={1} flexWrap="wrap">
120          {/* The gauges, a quiet dot between them; only a gauge near its limit takes a colour. */}
121          {segments.flatMap((seg, i) => [
122            ...(i > 0 ? [<Text key={`u-sep-${seg.id}`} dimColor hover={{ scope: scope('usage') }}>·</Text>] : []),
123            <Text
124              key={`u-${seg.id}`}
125              color={seg.level === 'high' || seg.level === 'warn' ? TONE[usageTone(seg.level)] : undefined}
126              dimColor={seg.level === 'ok' || seg.level === 'unknown'}
127              hover={{ scope: scope('usage') }}
128            >
129              {seg.text}
130            </Text>,
131          ])}
132          {showModels &&
133            MODEL_BUTTONS.map(b => (
134              <Button
135                key={`m-${b.key}`}
136                label={b.key}
137                variant={family === b.family ? 'primary' : 'secondary'}
138                dimColor={family !== b.family}
139                hover={{ scope: scope(`m-${b.key}`) }}
140                onPress={press => void pressModel($, b.family, isWorking, press.surface)}
141              />
142            ))}
143          {s.show.sub5 && (
144            <Button key="sub5" label="Sub5" variant="secondary" hover={{ scope: scope('sub5') }} onPress={() => void startSub5($, '', isWorking)} />
145          )}
146          {targets.map(t => (
147            <Button
148              key={`d-${t.key}`}
149              label={t.key}
150              variant="secondary"
151              hover={{ scope: scope(`d-${t.key}`) }}
152              onPress={() => void startDelegate($, t, '', isWorking, true)}
153            />
154          ))}
155          {s.show.recap && (
156            <Button key="recap" label={m.recap.label} variant="secondary" hover={{ scope: scope('recap') }} onPress={() => void startRecap($)} />
157          )}
158          {showGalaxy && (
159            <Button key="galaxy" label={m.galaxy.label} variant="secondary" hover={{ scope: scope('galaxy') }} onPress={() => void startGalaxy($, isWorking)} />
160          )}
161          <Box key="tips" flexGrow={1} minWidth={1}>
162            {tips.map(t => (
163              <Box
164                key={`tip-${t.id}`}
165                position="absolute"
166                top={0}
167                left={0}
168                width="100%"
169                display="none"
170                hover={{ display: 'flex', scope: scope(t.id) }}
171              >
172                <Text key={`tip-text-${t.id}`} dimColor wrap="truncate">
173                  {t.text}
174                </Text>
175              </Box>
176            ))}
177          </Box>
178          <Button key="gear" label="⚙" variant={isSettingsOpen ? 'primary' : 'secondary'} hover={{ scope: scope('gear') }} onPress={() => void toggleSettings($)} />
179        </Box>
180      </Box>
181    )
182  })
183}
184
hooks/core.ts 142 lines
1/**
2 * The core every part of the plugin shares: the settings and the language they resolve to, the ids of its
3 * panes and tools. An atom lives in the one file that reads and writes it (the engine reads each file on its
4 * own), so the rest of the plugin reaches these through the functions below.
5 */
6import { atom, read, update } from 'claude-code'
7import type { EngineInterface } from 'claude-code'
8
9import type { Locale } from '../types'
10import { LOCALES, messages, resolveLocale } from './i18n'
11import type { Messages } from './i18n'
12import { defaultSettings, normalizeSettings } from './settings'
13import type { Settings } from './settings'
14
15export type Engine = EngineInterface
16
17
18const settingsAtom = atom({ plugin: 'deckhand', key: 'settings' } as const, null as Settings | null)
19const localeAtom = atom({ plugin: 'deckhand', key: 'locale' } as const, 'en' as Locale)
20const knownScopedAtom = atom({ plugin: 'deckhand', key: 'knownScoped' } as const, [] as string[])
21
22export const asRecord = (v: unknown): Record<string, unknown> => (v !== null && typeof v === 'object' ? (v as Record<string, unknown>) : {})
23
24/**
25 * The person's settings from `$.store`, read against defaults that depend on their Claude settings
26 * (the attribution guard), and the language they resolve to. Called at session start and on demand.
27 */
28export async function loadSettings($: Engine): Promise<Settings> {
29  const claude = asRecord(await $.settings.read().catch(() => ({})))
30  const base = defaultSettings({ attributionOff: asRecord(claude.attribution).commit === '' })
31  const stored = await $.store.get('settings').catch(() => undefined)
32  const s = normalizeSettings(stored, base, LOCALES)
33  await update($, settingsAtom, () => s)
34  const sys = await systemLanguage($)
35  await update($, localeAtom, () => resolveLocale(s.language, claude.language, sys))
36  const known = await $.store.get('knownScoped').catch(() => undefined)
37  if (Array.isArray(known)) await update($, knownScopedAtom, () => known.filter((k): k is string => typeof k === 'string'))
38  return s
39}
40
41export async function cfg($: Engine): Promise<Settings> {
42  return (await read($, settingsAtom)) ?? loadSettings($)
43}
44
45/** For drawing: reads only (a render hook may not write state); defaults until the session has loaded them. */
46export async function cfgForDrawing($: Engine): Promise<Settings> {
47  return (await read($, settingsAtom)) ?? defaultSettings({ attributionOff: false })
48}
49
50/** The catalog for a handler: loads the settings first when the session has not, so the language is right. */
51export async function msgs($: Engine): Promise<Messages> {
52  if (!(await read($, settingsAtom))) await loadSettings($)
53  return messages(await read($, localeAtom))
54}
55
56/** The catalog for drawing: reads only. */
57export async function msgsForDrawing($: Engine): Promise<Messages> {
58  return messages(await read($, localeAtom))
59}
60
61/** The language the plugin speaks now. */
62export async function currentLocale($: Engine): Promise<Locale> {
63  return read($, localeAtom)
64}
65
66/** Stores new settings and the language they resolve to; what else depends on them is the caller's to redo. */
67export async function storeSettings($: Engine, next: Settings, claudeLanguage: unknown) {
68  await update($, settingsAtom, () => next)
69  await $.store.set('settings', next).catch(error => $.ui.log(`deckhand: settings not saved (${error instanceof Error ? error.message : String(error)})`))
70  const sys = await systemLanguage($)
71  await update($, localeAtom, () => resolveLocale(next.language, claudeLanguage, sys))
72}
73
74/** The per-model weekly windows this account has shown, so they read – rather than vanish while unreadable. */
75export async function knownScoped($: Engine): Promise<string[]> {
76  return read($, knownScopedAtom)
77}
78
79export async function rememberScoped($: Engine, families: string[]) {
80  await update($, knownScopedAtom, () => families)
81  await $.store.set('knownScoped', families).catch(() => undefined)
82}
83
84/** The system's language, read once: the locale environment, else macOS's first preferred language. */
85let system: string | undefined
86
87/**
88 * What `auto` falls back to when Claude Code has no `language` setting: LC_ALL, LC_MESSAGES or LANG
89 * (not C or POSIX), else, on macOS, where an app started from the Dock has no LANG, the first of
90 * AppleLanguages (`zh-Hant-TW`). Empty when neither says.
91 */
92export async function systemLanguage($: Engine): Promise<string> {
93  if (system !== undefined) return system
94  system = ''
95  try {
96    // $.env.get takes a literal name, so the engine can list what the plugin reads.
97    const values = [
98      await $.env.get('LC_ALL').catch(() => undefined),
99      await $.env.get('LC_MESSAGES').catch(() => undefined),
100      await $.env.get('LANG').catch(() => undefined),
101    ]
102    for (const raw of values) {
103      const value = (raw ?? '').trim()
104      if (value && !/^(C|POSIX)([.@]|$)/i.test(value)) return (system = value)
105    }
106    // A terminal has LANG; the desktop app, started from the Dock, may not.
107    if (!(await isDesktopApp($))) return system
108    const ran = await $.process.run(['/usr/bin/defaults', 'read', '-g', 'AppleLanguages'], { timeoutMs: 5_000 })
109    if (ran.exitCode === 0) system = ran.stdout.match(/"?([A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*)"?/)?.[1] ?? ''
110  } catch {
111    // No env or process here (tests, a sandbox): English.
112  }
113  return system
114}
115
116/** Absolute paths of CLIs: the desktop app's PATH may lack ~/.local/bin or Homebrew. */
117const bins = new Map<string, string>()
118
119export async function resolveBin($: Engine, name: string) {
120  const known = bins.get(name)
121  if (known) return known
122  let found = name
123  try {
124    const home = (await $.env.get('HOME')) ?? ''
125    for (const dir of [`${home}/.local/bin`, '/opt/homebrew/bin', '/usr/local/bin', '/usr/bin']) {
126      if (await $.fs.exists(`${dir}/${name}`)) {
127        found = `${dir}/${name}`
128        break
129      }
130    }
131  } catch {
132    // No fs or env here (tests): fall back to PATH lookup.
133  }
134  bins.set(name, found)
135  return found
136}
137
138/** The Claude desktop app starts the engine with this entrypoint; its own PR bar watches a bound PR's CI. */
139export async function isDesktopApp($: Engine) {
140  return (await $.env.get('CLAUDE_CODE_ENTRYPOINT').catch(() => undefined)) === 'claude-desktop'
141}
142
hooks/delegate.ts 86 lines
1/**
2 * The delegate buttons: which outside model each one stands for (the person's settings), the exact
3 * command line that runs it, and the brief the main agent gets (one per language, in the catalogs).
4 * The exact parts (CLI flags, read-only mode, the secrets check, the time limit, the record) are
5 * bin/delegate.py's; the judgment (what to hand over, whether the answer holds) is the main agent's.
6 * Kept free of `$` so tests can read it.
7 */
8import type { Locale, Messages } from './i18n'
9import type { DelegateTarget, DelegateTool } from './settings'
10import { shq } from './shell'
11
12export const TOOL_NAME: Readonly<Record<DelegateTool, string>> = { codex: 'Codex', agent: 'Cursor agent', agy: 'agy' }
13
14/** `Codex (GPT-6 Luna, effort max)`, in the catalog's punctuation. */
15export const targetLabel = (t: DelegateTarget, m: Messages) => m.delegate.label(TOOL_NAME[t.tool], t.name, t.effort)
16
17/** The enabled target on this label, whatever its case. */
18export const findTarget = (targets: readonly DelegateTarget[], key: string) =>
19  targets.find(t => t.enabled && t.key.toLowerCase() === key.trim().toLowerCase())
20
21export type CommandArgs = {
22  /** Absolute path of bin/delegate.py. */
23  tool: string
24  target: DelegateTarget
25  locale: Locale
26  /** The CLI's path when the person set one; empty finds it. */
27  bin?: string
28  /** CODEX_HOME for a codex target, when the person set one. */
29  codexHome?: string
30}
31
32/** `run` and the target's flags, unquoted. */
33const runArgs = (o: CommandArgs) => [
34  'run',
35  '--tool',
36  o.target.tool,
37  '--model',
38  o.target.model,
39  '--effort',
40  o.target.effort,
41  '--label',
42  o.target.key,
43  '--name',
44  o.target.name,
45  '--lang',
46  o.locale,
47  ...(o.bin ? ['--bin', o.bin] : []),
48  ...(o.codexHome && o.target.tool === 'codex' ? ['--codex-home', o.codexHome] : []),
49]
50
51/** The command line the brief hands the main agent, up to the heredoc opener. */
52export const delegateCommand = (o: CommandArgs) => ['python3', o.tool, ...runArgs(o)].map(shq).join(' ')
53
54/** Minutes a translation or a web search may take before delegate.py stops the CLI. */
55export const TRANSLATE_MINUTES = 5
56export const SEARCH_MINUTES = 8
57
58/**
59 * The process of the translate and search tools: the prompt is whole (`--raw`: no standard rules in
60 * front of it) and stdout is the answer alone; `web` lets the CLI search the web (Codex needs it
61 * switched on). `python` is the interpreter's resolved path.
62 */
63export const assistArgv = (o: CommandArgs & { python: string; minutes: number; web?: boolean }) => [
64  o.python,
65  o.tool,
66  ...runArgs(o),
67  '--raw',
68  ...(o.web ? ['--web'] : []),
69  '--timeout',
70  String(o.minutes),
71]
72
73export type BriefArgs = CommandArgs & { task: string; attribution: boolean }
74
75export const delegatePrompt = (o: BriefArgs, m: Messages): string =>
76  m.delegate.brief({
77    key: o.target.key,
78    label: targetLabel(o.target, m),
79    task: o.task.trim(),
80    command: delegateCommand(o),
81    toolName: TOOL_NAME[o.target.tool],
82    readsFiles: o.target.tool !== 'agy',
83    languageName: m.languageName,
84    attribution: o.attribution,
85  })
86
hooks/delegates.tsx 387 lines
1/** Delegate runs and records: the band's progress rows for each delegate.py run, and the records pane with every answer of the last 3 days. */
2import { atom, read, update } from 'claude-code'
3import type { On, Timer } from 'claude-code'
4
5import type { DelegateAnswer, DelegateRecord, DelegateRun } from '../types'
6import { ago } from './codex'
7import { asRecord, currentLocale, msgs, msgsForDrawing, resolveBin } from './core'
8import type { Engine } from './core'
9import {
10  exitCodeOf,
11  matchRecord,
12  parseDelegateOutput,
13  parseMetaUsage,
14  parseRecords,
15  parseTaskNotification,
16  pasteAnswer,
17  recordResult,
18  recordsTotal,
19  whoOf,
20} from './runs'
21import type { DelegateCall } from './runs'
22import { errorText, lastLine, text } from './state'
23import { listRoom, TOAST, TONE } from './ui'
24import { clearFinished } from './watches'
25
26/**
27 * The last four runs, for the band. While one runs, the tick is read too, so the band is drawn again every
28 * second and its elapsed time moves.
29 */
30export async function bandRuns($: Engine) {
31  const runs = (await read($, delegateRunsAtom)).slice(-4)
32  if (runs.some(r => r.status === 'running')) await read($, delegateTickAtom)
33  return runs
34}
35
36export async function startRun($: Engine, call: DelegateCall, id: string) {
37  const run: DelegateRun = {
38    id,
39    label: call.label,
40    tool: call.tool,
41    name: call.name,
42    startedAt: await $.clock.now(),
43    timeoutMin: call.timeoutMin,
44    status: 'running',
45  }
46  awaitedRuns.add(id)
47  await update($, delegateRunsAtom, list => [...list.filter(r => r.id !== id).slice(-7), run])
48  await syncRunTimers($)
49  return id
50}
51
52/** Ends a run that is still running; one that already ended keeps its first outcome. */
53export async function finishRun($: Engine, id: string, patch: Partial<DelegateRun>) {
54  const now = await $.clock.now()
55  await update($, delegateRunsAtom, list =>
56    list.map(r => (r.id === id && r.status === 'running' ? { ...r, status: 'answered' as const, ...patch, finishedAt: now } : r)),
57  )
58  await syncRunTimers($)
59}
60
61/** The Bash call's result: the outcome, or the background task it became. */
62export async function settleRun($: Engine, id: string, ran: { deny?: string; result?: unknown; text?: string; isError?: true }) {
63  if (ran.deny !== undefined) {
64    await update($, delegateRunsAtom, list => list.filter(r => r.id !== id))
65    await syncRunTimers($)
66    return
67  }
68  const out = asRecord(ran.result)
69  const said = ran.text ?? [text(out.stdout), text(out.stderr)].join('\n')
70  if (!ran.isError && typeof out.backgroundTaskId === 'string' && out.backgroundTaskId) {
71    const taskId = out.backgroundTaskId
72    await update($, delegateRunsAtom, list => list.map(r => (r.id === id ? { ...r, taskId } : r)))
73    return
74  }
75  if (out.interrupted === true) return finishRun($, id, { status: 'stopped' })
76  const code = ran.isError ? exitCodeOf(said) : 0
77  await finishRun($, id, { status: code === 0 ? 'answered' : 'failed', exitCode: code, ...parseDelegateOutput(said) })
78  await readRunUsage($, id)
79}
80
81/** An ended run's token counts, from the meta.json in its folder (written before delegate.py printed its outcome). */
82export async function readRunUsage($: Engine, id: string) {
83  const run = (await read($, delegateRunsAtom)).find(r => r.id === id)
84  const folder = run?.folder ?? run?.answerPath?.split('/').slice(0, -1).join('/')
85  if (!run || !folder || run.usage) return
86  const usage = parseMetaUsage(await $.fs.read(`${folder}/meta.json`).catch(() => ''))
87  if (usage) await update($, delegateRunsAtom, list => list.map(r => (r.id === id ? { ...r, usage } : r)))
88}
89
90/** A background task's notification: ends the run that task was, with its exit code and output. */
91export async function noteTaskEnded($: Engine, prompt: string) {
92  const ended = parseTaskNotification(prompt)
93  if (!ended) return
94  const run = (await read($, delegateRunsAtom)).find(
95    r =>
96      r.status === 'running' &&
97      ((ended.taskId !== undefined && r.taskId === ended.taskId) || (ended.toolUseId !== undefined && r.id === ended.toolUseId)),
98  )
99  if (!run) return
100  const said = ended.outputFile ? await $.fs.read(ended.outputFile).catch(() => '') : ''
101  const code = ended.exitCode ?? (ended.status === 'completed' ? 0 : undefined)
102  const status = ended.status === 'killed' ? 'stopped' : code === 0 ? 'answered' : 'failed'
103  await finishRun($, run.id, { status, exitCode: code, ...parseDelegateOutput(said) })
104  await readRunUsage($, run.id)
105}
106
107/** `delegate.py list`: the run folders of the last 3 days, newest first. */
108export async function listRecords($: Engine, dirs: readonly string[]): Promise<DelegateRecord[]> {
109  const ran = await $.process.run(
110    [
111      await resolveBin($, 'python3'),
112      `${$.plugin.root}/bin/delegate.py`,
113      'list',
114      '--format',
115      'json',
116      '--lang',
117      await currentLocale($),
118      ...dirs.flatMap(d => ['--dir', d]),
119    ],
120    { timeoutMs: 30_000 },
121  )
122  if (ran.exitCode !== 0) throw new Error(lastLine(ran.stderr || ran.stdout) || `exit ${ran.exitCode}`)
123  return parseRecords(ran.stdout)
124}
125
126/** Looks up the runs nobody awaits in the run folders: a meta.json with an outcome ends one. */
127export async function pollRuns($: Engine) {
128  const runs = await read($, delegateRunsAtom)
129  const open = runs.filter(r => r.status === 'running' && !awaitedRuns.has(r.id))
130  if (!open.length) return
131  const records = await listRecords($, runDirs(runs))
132  const claimed = new Set(runs.flatMap(r => (r.folder ? [r.folder] : [])))
133  for (const run of open) {
134    const rec = matchRecord(run, records, claimed)
135    if (!rec) continue
136    claimed.add(rec.path)
137    if (rec.exit === null) {
138      if (!run.folder) await update($, delegateRunsAtom, list => list.map(r => (r.id === run.id ? { ...r, folder: rec.path } : r)))
139      continue
140    }
141    await finishRun($, run.id, {
142      status: rec.exit === 0 ? 'answered' : 'failed',
143      exitCode: rec.exit,
144      folder: rec.path,
145      ...(rec.seconds !== null ? { seconds: rec.seconds } : {}),
146      ...(rec.answerPath ? { answerPath: rec.answerPath } : {}),
147      ...(Object.values(rec.usage).some(v => v !== null) ? { usage: rec.usage } : {}),
148    })
149  }
150}
151
152/** Every second while a run is in flight: the elapsed time moves; every few seconds the folders are looked up. */
153export async function tickRuns($: Engine) {
154  const now = await $.clock.now()
155  await update($, delegateTickAtom, () => now)
156  const open = (await read($, delegateRunsAtom)).filter(r => r.status === 'running' && !awaitedRuns.has(r.id))
157  for (const r of open) {
158    if (now - r.startedAt > r.timeoutMin * 60_000 + RUN_LOST_MARGIN_MS) await finishRun($, r.id, { status: 'lost' })
159  }
160  if (open.length && now - lastRunPoll >= RUN_POLL_MS) {
161    lastRunPoll = now
162    await pollRuns($).catch(() => undefined)
163  }
164}
165
166/** Starts or stops the ticker and sets the timer that drops finished rows; after a reload, re-arms both. */
167export async function syncRunTimers($: Engine) {
168  const runs = await read($, delegateRunsAtom)
169  const isRunning = runs.some(r => r.status === 'running')
170  if (isRunning && !runTicker) runTicker = $.clock.every(1000, () => void tickRuns($).catch(() => undefined))
171  if (!isRunning && runTicker) {
172    runTicker.cancel()
173    runTicker = null
174  }
175  runExpiry?.cancel()
176  runExpiry = null
177  const ends = runs.filter(isFinished).map(r => (r.finishedAt ?? 0) + RUN_SHOWN_MS)
178  if (ends.length) {
179    const wait = Math.max(1000, Math.min(...ends) - (await $.clock.now()))
180    runExpiry = $.clock.after(wait, () => void dropShownRuns($).catch(() => undefined))
181  }
182}
183
184export async function dropShownRuns($: Engine) {
185  const now = await $.clock.now()
186  await update($, delegateRunsAtom, list => list.filter(r => !isFinished(r) || (r.finishedAt ?? 0) + RUN_SHOWN_MS > now))
187  await syncRunTimers($)
188}
189
190/** The band's "clear finished": finished watches and finished delegate rows alike. */
191export async function clearFinishedRows($: Engine) {
192  await clearFinished($)
193  await update($, delegateRunsAtom, list => list.filter(r => r.status === 'running'))
194  await syncRunTimers($)
195}
196
197export async function loadRecords($: Engine) {
198  await update($, recordsLoadingAtom, () => true)
199  try {
200    const records = await listRecords($, runDirs(await read($, delegateRunsAtom)))
201    await update($, recordsAtom, () => records)
202    await update($, recordsErrorAtom, () => null)
203  } catch (error) {
204    await update($, recordsErrorAtom, () => errorText(error))
205  } finally {
206    await update($, recordsLoadingAtom, () => false)
207  }
208}
209
210/** Opens the records pane on the list, or on one answer when one is named. */
211export async function openRecords($: Engine, show?: { path: string; label: string; who: string }) {
212  const m = await msgs($)
213  await update($, answerAtom, () => null)
214  await $.ui.open({ id: DELEGATES_PANE, title: m.delegate.recordsTitle })
215  if (show) await openAnswer($, show.path, show.label, show.who)
216  void loadRecords($).catch(() => undefined)
217}
218
219export async function readAnswer($: Engine, path: string): Promise<string | null> {
220  try {
221    return await $.fs.read(path)
222  } catch (error) {
223    $.ui.toast((await msgs($)).delegate.readFailed(errorText(error)), { timeoutMs: TOAST.problem })
224    return null
225  }
226}
227
228export async function openAnswer($: Engine, path: string, label: string, who: string) {
229  const answer = await readAnswer($, path)
230  if (answer !== null) await update($, answerAtom, () => ({ path, label, who, text: answer }))
231}
232
233export async function copyAnswer($: Engine, path: string, surface: Parameters<Engine['ui']['copy']>[0]['surface']) {
234  const m = await msgs($)
235  const answer = await readAnswer($, path)
236  if (answer === null) return
237  const copied = await $.ui.copy({ text: answer, surface }).catch(() => ({ isCopied: false }))
238  if (copied.isCopied) $.ui.toast(m.delegate.copied, { timeoutMs: TOAST.done })
239}
240
241/** Puts the answer (or, when long, where it is kept) into the prompt box; never over a draft. */
242export async function answerToPrompt($: Engine, path: string, label: string, who: string) {
243  const m = await msgs($)
244  const box = await $.prompt.read().catch(() => ({ text: '', cursor: 0 }))
245  if (box.text.trim()) {
246    $.ui.toast(m.delegate.boxBusy, { timeoutMs: TOAST.problem })
247    return
248  }
249  const answer = await readAnswer($, path)
250  if (answer === null) return
251  const filled = await $.prompt
252    .fill({ text: pasteAnswer({ label, who, path, text: answer }, m), mode: 'replace' })
253    .catch(() => ({ isFilled: false }))
254  $.ui.toast(filled.isFilled ? m.delegate.filled(label) : m.delegate.fillFailed, { timeoutMs: TOAST.info })
255}
256
257export const DELEGATES_PANE = 'deckhand-delegates'
258
259const delegateRunsAtom = atom({ plugin: 'deckhand', key: 'delegateRuns' } as const, [] as DelegateRun[])
260
261const delegateTickAtom = atom({ plugin: 'deckhand', key: 'delegateTick' } as const, 0)
262
263const recordsAtom = atom({ plugin: 'deckhand', key: 'delegateRecords' } as const, [] as DelegateRecord[])
264
265const recordsErrorAtom = atom({ plugin: 'deckhand', key: 'delegateRecordsError' } as const, null as string | null)
266
267const recordsLoadingAtom = atom({ plugin: 'deckhand', key: 'isDelegateRecordsLoading' } as const, false)
268
269const answerAtom = atom({ plugin: 'deckhand', key: 'delegateAnswer' } as const, null as DelegateAnswer | null)
270
271/** How long a finished run's row stays in the band, unless cleared sooner. */
272const RUN_SHOWN_MS = 10 * 60_000
273
274/** How often a run nobody awaits (a background task, or one from before a reload) is looked up. */
275const RUN_POLL_MS = 10_000
276
277/** A run with no word this long past its time limit is given up as lost. */
278const RUN_LOST_MARGIN_MS = 10 * 60_000
279
280/** The one-second ticker while a run is in flight, and the timer that drops finished rows. */
281let runTicker: Timer | null = null
282
283let runExpiry: Timer | null = null
284
285let lastRunPoll = 0
286
287/** Runs whose Bash call a hook of this module still awaits: that call's result ends them. */
288export const awaitedRuns = new Set<string>()
289
290export const isFinished = (r: DelegateRun) => r.status !== 'running'
291
292/** The folders the runs so far were kept in, for `list --dir`. */
293const runDirs = (runs: readonly DelegateRun[]) => [
294  ...new Set(
295    runs.flatMap(r =>
296      r.answerPath ? [r.answerPath.split('/').slice(0, -2).join('/')] : r.folder ? [r.folder.split('/').slice(0, -1).join('/')] : [],
297    ),
298  ),
299]
300
301/** The hooks of this part of the plugin; register.tsx calls this first. */
302export function registerDelegates(on: On) {
303  // ── Delegate records pane ───────────────────────────────────────────────
304
305  on('command.run', { command: 'delegates' }, async $ => {
306    await openRecords($)
307    return { text: (await msgs($)).delegate.recordsOpened }
308  })
309
310  on('ui.render', { component: 'Pane', requestId: DELEGATES_PANE }, async ($, e) => {
311    const { Box, Text, Button, Markdown } = $.ui.resolve(e)
312    const m = await msgsForDrawing($)
313    const answer = await read($, answerAtom)
314    if (answer) {
315      return (
316        <Box flexDirection="column" gap={1}>
317          <Text bold wrap="truncate">
318            {answer.label} · {answer.who}
319          </Text>
320          <Box gap={1} flexWrap="wrap">
321            <Button key="back" label={m.delegate.back} variant="secondary" onPress={() => void update($, answerAtom, () => null)} />
322            <Button key="a-copy" label={m.delegate.copy} variant="primary" onPress={press => void copyAnswer($, answer.path, press.surface)} />
323            <Button key="a-fill" label={m.delegate.toPrompt} variant="secondary" onPress={() => void answerToPrompt($, answer.path, answer.label, answer.who)} />
324          </Box>
325          <Markdown key="answer" text={answer.text} />
326          {e.surface !== 'desktop' && (
327            <Box>
328              <Button key="close" label={m.common.close} role="dismiss" onPress={() => void $.ui.close({ id: DELEGATES_PANE })} />
329            </Box>
330          )}
331        </Box>
332      )
333    }
334    const records = await read($, recordsAtom)
335    const isLoading = await read($, recordsLoadingAtom)
336    const error = await read($, recordsErrorAtom)
337    const now = await $.clock.now()
338    const room = listRoom(e.viewport?.rows, 8, 5)
339    return (
340      <Box flexDirection="column" gap={1}>
341        <Box gap={1} alignItems="center">
342          <Text bold>{m.delegate.recordsHeading}</Text>
343          <Button key="refresh" label={m.delegate.refresh} variant="secondary" onPress={() => void loadRecords($)} />
344        </Box>
345        {isLoading && <Text dimColor>{m.delegate.loading}</Text>}
346        {error !== null && <Text color={TONE.bad}>{m.delegate.loadFailed(error)}</Text>}
347        {!isLoading && error === null && records.length === 0 && <Text dimColor>{m.delegate.noRecords}</Text>}
348        {records.length > 0 && (
349          <Text key="total" dimColor>
350            {recordsTotal(records, m)}
351          </Text>
352        )}
353        {records.slice(0, room).map((r, i) => {
354          const who = whoOf(r.tool, r.name ?? r.model, m)
355          const when = r.started !== null ? ago(r.started * 1000, now, m) : '?'
356          const result = recordResult(r, m)
357          const path = r.answerBytes ? r.answerPath : null
358          return (
359            <Box key={`rec-${i}`} flexDirection="column">
360              <Text bold wrap="truncate">
361                {r.label} · {who}
362              </Text>
363              <Text dimColor wrap="truncate">
364                {when} · {result}
365              </Text>
366              {r.firstLine ? <Text wrap="truncate">{r.firstLine}</Text> : null}
367              {path ? (
368                <Box gap={1} flexWrap="wrap">
369                  <Button key={`open-${i}`} label={m.delegate.open} variant="secondary" onPress={() => void openAnswer($, path, r.label, who)} />
370                  <Button key={`copy-${i}`} label={m.delegate.copy} variant="secondary" onPress={press => void copyAnswer($, path, press.surface)} />
371                  <Button key={`fill-${i}`} label={m.delegate.toPrompt} variant="secondary" onPress={() => void answerToPrompt($, path, r.label, who)} />
372                </Box>
373              ) : null}
374            </Box>
375          )
376        })}
377        {records.length > room ? <Text dimColor>{m.common.more(records.length - room)}</Text> : null}
378        {e.surface !== 'desktop' && (
379          <Box>
380            <Button key="close" label={m.common.close} role="dismiss" onPress={() => void $.ui.close({ id: DELEGATES_PANE })} />
381          </Box>
382        )}
383      </Box>
384    )
385  })
386}
387
hooks/guard.ts 167 lines
1/**
2 * Pure helpers for the Bash guards: attribution stripping, blocking waits and
3 * the 3-strike rule for repeated status checks. Kept free of `$` so tests can
4 * call them.
5 */
6import { outputSignature } from './fingerprint'
7import type { Messages } from './i18n'
8
9const ATTRIBUTION = [
10  /Co-Authored-By:[^\n"'`]*/gi,
11  /🤖\s*Generated with \[Claude Code\]\([^)\n]*\)/g,
12  /Generated with \[Claude Code\]\([^)\n]*\)/g,
13]
14
15const WRITES_MESSAGE = /\bgit\b[^\n|;&]*\bcommit\b|\bgh\s+pr\s+(create|edit)\b|\bgit\b[^\n|;&]*\btag\b\s+-[am]/
16
17/** Removes Co-Authored-By trailers and the Claude Code PR footer from a commit / PR command. */
18export const stripAttribution = (command: string): string | null => {
19  if (!WRITES_MESSAGE.test(command)) return null
20  const kept: string[] = []
21  let isChanged = false
22  for (const line of command.split('\n')) {
23    let next = line
24    for (const pattern of ATTRIBUTION) next = next.replace(pattern, '')
25    if (next === line) {
26      kept.push(line)
27      continue
28    }
29    isChanged = true
30    const isLeading = /^\s*(Co-Authored-By:|🤖|Generated with)/i.test(line)
31    if (next.trim() !== '' && !isLeading) {
32      kept.push(next)
33      continue
34    }
35    // The line opened with the trailer: drop it and the blank lines that set it
36    // apart, and hand what closed the message (a quote, a paren) to the line before.
37    while (kept.length > 0 && kept[kept.length - 1]!.trim() === '') kept.pop()
38    const rest = next.trim()
39    if (rest === '') continue
40    if (kept.length > 0) kept[kept.length - 1] += rest
41    else kept.push(rest)
42  }
43  return isChanged ? kept.join('\n') : null
44}
45
46// ── what a command line runs ───────────────────────────────────────────────
47
48/** A command whose quoted argument or heredoc is itself run: `bash -c '…'`, `ssh host '…'`, `eval "…"`. */
49const RUNS_TEXT = /(?:^|[\s|;&(!])(?:\S*\/)?(?:(?:ba|z|da|k)?sh|ssh|eval|watch)(?:\s|$)/
50
51/** The command being written when the scan reaches this point: the text since the last `|`, `;`, `&`, `(` or line break. */
52const segmentOf = (before: string) => before.slice(Math.max(...['|', ';', '&', '(', '\n'].map(c => before.lastIndexOf(c))) + 1)
53
54/** Data in quotes becomes one opaque word: `"gh run watch"` → `gh_run_watch`, so no guard pattern sees a command in it, while a quoted URL stays a URL. */
55const opaque = (text: string) => text.replace(/[^\w:/.@~%+=,-]/g, '_')
56
57/** In double quotes, `$(…)` and backticks still run: keep them, the rest is data. */
58const keepSubstitutions = (text: string) =>
59  [...text.matchAll(/\$\(([^()]*(?:\([^()]*\)[^()]*)*)\)|`([^`]*)`/g)].map(s => ` ${s[1] ?? s[2]} `).join('') || opaque(text)
60
61/** A heredoc start, `<<EOF`, `<<-'EOF'`, never a here-string (`<<<`). */
62const HEREDOC = /(?<!<)<<-?\s*(['"]?)([A-Za-z_][\w-]*)\1/g
63
64/**
65 * The part of a command line the shell runs, as the guards read it: heredoc bodies and quoted
66 * strings are data (a script fed to `python3 -`, a commit message, a `grep` pattern) unless the
67 * command they belong to runs them. So writing about `gh run watch` is never mistaken for running it.
68 */
69export const executable = (command: string): string => {
70  const lines = command.split('\n')
71  const kept: string[] = []
72  for (let i = 0; i < lines.length; i++) {
73    const line = lines[i]!
74    kept.push(line)
75    for (const tag of line.matchAll(HEREDOC)) {
76      const isRun = RUNS_TEXT.test(segmentOf(line.slice(0, tag.index)))
77      for (i++; i < lines.length && lines[i]!.trim() !== tag[2]; i++) if (isRun) kept.push(lines[i]!)
78    }
79  }
80  const text = kept.join('\n')
81  let out = ''
82  for (let i = 0; i < text.length; i++) {
83    const c = text[i]!
84    if (c === '\\') {
85      out += text.slice(i, i + 2)
86      i++
87    } else if (c === "'" || c === '"') {
88      let end = i + 1
89      while (end < text.length && text[end] !== c) end += c === '"' && text[end] === '\\' ? 2 : 1
90      const body = text.slice(i + 1, end)
91      out += RUNS_TEXT.test(segmentOf(out)) ? ` ${body} ` : c === '"' ? keepSubstitutions(body) : opaque(body)
92      i = end
93    } else out += c
94  }
95  return out
96}
97
98/** Long blocking waits the watch tool replaces. Quoted text and heredocs are data, not waits. */
99export const blockingWait = (raw: string, m: Messages): string | null => {
100  const command = executable(raw)
101  if (/\bgh\s+run\s+watch\b/.test(command)) return 'gh run watch'
102  if (/\bgh\s+pr\s+checks\b[^\n]*--watch\b/.test(command)) return 'gh pr checks --watch'
103  // A loop that sleeps and calls a status tool, in whichever order the words come.
104  if (/\b(?:until|while)\b/.test(command) && /\bsleep\b/.test(command) && /\b(?:gh|curl|wget|ssh)\b/.test(command)) {
105    return m.guard.loop
106  }
107  const sleep = command.match(/\bsleep\s+(\d+)/)
108  if (sleep && Number(sleep[1]) >= 20 && /\b(gh|curl|wget|ssh)\b/.test(command)) return m.guard.sleepPoll(sleep[1]!)
109  return null
110}
111
112// ── repeated status checks ─────────────────────────────────────────────────
113
114/** Parts of a command line that wait or print, not check: they change between tries, the check does not. */
115const FILLER = /^(?:sleep\s+[\d.]+[smhd]?|echo\b.*|printf\b.*|date\b.*|true|:)$/
116
117const STATUS_CHECK = new RegExp(
118  [
119    String.raw`\bgh\s+pr\s+(?:view|checks|status)\b`,
120    String.raw`\bgh\s+run\s+(?:list|view)\b`,
121    String.raw`\bgh\s+api\b[^\n|]*\/(?:actions\/runs|deployments|check-runs|status|pulls\/\d+)`,
122    String.raw`\bcurl\b[^\n]*(?:https?:\/\/|localhost)`,
123    String.raw`\bgit\s+(?:fetch|ls-remote)\b`,
124    String.raw`\bssh\b[^\n]*\b(?:cat|ls|readlink|stat|tail|head|systemctl\s+status|docker\s+(?:ps|logs)|journalctl)\b`,
125  ].join('|'),
126)
127
128const WRITES =
129  /\b(?:git\s+(?:push|commit|merge|pull|rebase|reset|checkout|switch)|gh\s+pr\s+(?:merge|create|edit|close)|rsync|scp|deploy)\b/
130
131/** A request that changes something is no status check, however often it is repeated. */
132const isMutating = (command: string) =>
133  /\bgh\s+api\b/.test(command)
134    ? /(?:^|\s)(?:-X|--method|-f|-F|--field|--raw-field|--input)(?=[\s=]|$)/.test(command)
135    : /(?:^|\s)(?:-X\s*(?:POST|PUT|PATCH|DELETE)|--request[=\s]+(?:POST|PUT|PATCH|DELETE)|-d|--data\S*|-F|--form\S*|-T|--upload-file)(?=[\s=]|$)/.test(command)
136
137/**
138 * A stable key for "the same check": the status-style part of the command, without
139 * the sleeps, echoes, `2>&1` and `| tail` a model varies from try to try.
140 */
141export const statusKey = (command: string): string | null => {
142  const key = executable(command)
143    .split(/&&|\|\||;|\n/)
144    .map(part => part.trim())
145    .filter(part => part !== '' && !FILLER.test(part))
146    .join(' && ')
147    .replace(/\s*2>&1/g, '')
148    .replace(/\s*\|\s*(?:tail|head)\b[^|]*$/, '')
149    .replace(/\s+/g, ' ')
150    .trim()
151  if (!key || !STATUS_CHECK.test(key) || WRITES.test(key) || isMutating(key)) return null
152  return key.slice(0, 400)
153}
154
155/** What counts as "the same result": JSON by meaning, text by its distinct lines, noise masked. */
156export const normalizeOutput = outputSignature
157
158export type Strike = { output: string; count: number }
159
160/** Counts consecutive identical results per check; a changed result starts over at 1. */
161export const recordStrike = (strikes: Map<string, Strike>, key: string, output: string): number => {
162  const prior = strikes.get(key)
163  const count = prior && prior.output === output ? prior.count + 1 : 1
164  strikes.set(key, { output, count })
165  return count
166}
167
hooks/galaxy.tsx 278 lines
1/**
2 * Intent Galaxy (github.com/stephen-taipei/intent-galaxy) behind the iG button. With its MCP server
3 * connected, the button hands the main agent the two-step flow on that server's tools. Without it, the
4 * first press offers to install the npm package into Deckhand's own folder (bin/galaxy.py); once the
5 * person agrees, Deckhand registers the same two tools itself and runs the package behind them, so iG
6 * works in the same conversation, with no change to the person's MCP config. While a galaxy waits for
7 * its lock, the band says how to drive it.
8 */
9import { atom, read, update } from 'claude-code'
10import type { On } from 'claude-code'
11
12import type { GalaxyView } from '../types'
13import { handOverWhenIdle } from './actions'
14import { currentLocale, msgs, msgsForDrawing, resolveBin } from './core'
15import type { Engine } from './core'
16import { LANGUAGE_NAME } from './locales'
17import { errorText, lastLine } from './state'
18import { TOAST, TONE } from './ui'
19
20/** The two tools, whatever the person named the server: `mcp__<server>__intent_spawner_prompt` and `..._open_galaxy`. */
21export const SPAWNER_SUFFIX = '__intent_spawner_prompt'
22export const OPEN_SUFFIX = '__intent_open_galaxy'
23
24/** Deckhand's own pair, registered once the package is installed in its folder. */
25const OWN_SPAWNER = 'mcp__deckhand__intent_spawner_prompt'
26const OWN_OPEN = 'mcp__deckhand__intent_open_galaxy'
27
28/** The install pane's id: declared here, beside the hook whose matcher names it. */
29export const GALAXY_PANE = 'deckhand-galaxy'
30
31const galaxyAtom = atom({ plugin: 'deckhand', key: 'galaxy' } as const, {
32  spawner: '',
33  open: '',
34  isOpen: false,
35  setup: 'checking',
36  node: '',
37  needs: '22.18',
38  error: '',
39} as GalaxyView)
40
41/** The pair of tools one server offers, a connected Intent Galaxy server before Deckhand's own; null when none offers both. */
42export const galaxyTools = (names: readonly string[]): { spawner: string; open: string } | null => {
43  const pairs = names
44    .filter(open => open.startsWith('mcp__') && open.endsWith(OPEN_SUFFIX))
45    .map(open => ({ spawner: open.slice(0, -OPEN_SUFFIX.length) + SPAWNER_SUFFIX, open }))
46    .filter(p => names.includes(p.spawner))
47  return pairs.find(p => p.open !== OWN_OPEN) ?? pairs[0] ?? null
48}
49
50export async function galaxyState($: Engine) {
51  return read($, galaxyAtom)
52}
53
54/** Looks for the tools again: MCP servers connect after the session starts, and may come and go. */
55export async function detectGalaxy($: Engine) {
56  const tools = await $.tool.list().catch(() => null)
57  if (!tools) return
58  const found = galaxyTools(tools.filter(t => t.mcp).map(t => t.name))
59  await update($, galaxyAtom, (g): GalaxyView => ({ ...g, spawner: found?.spawner ?? '', open: found?.open ?? '' }))
60}
61
62/** While intent_open_galaxy waits for the lock, the band says so. */
63export async function markGalaxyOpen($: Engine, isOpen: boolean) {
64  await update($, galaxyAtom, (g): GalaxyView => ({ ...g, isOpen }))
65}
66
67type HelperStatus = { node: string | null; nodeOk: boolean; needs: string; npm: boolean; installed: boolean; version: string; error?: string; detail?: string[] }
68
69async function helperStatus($: Engine, args: string[] = ['status'], timeoutMs = 30_000): Promise<HelperStatus | null> {
70  const ran = await $.process.run([await resolveBin($, 'python3'), `${$.plugin.root}/bin/galaxy.py`, ...args], { timeoutMs }).catch(() => null)
71  try {
72    return ran ? (JSON.parse(lastLine(ran.stdout)) as HelperStatus) : null
73  } catch {
74    return null
75  }
76}
77
78/** Offers Deckhand's own pair of tools: called once the package is in Deckhand's folder. */
79export async function registerOwnTools($: Engine) {
80  await $.tool.register({
81    name: 'intent_spawner_prompt',
82    description:
83      'Step 1 of the Intent Galaxy flow (run by Deckhand). Returns the INTENT-SPAWNER system prompt and wire schema for a goal. ' +
84      'Generate the IntentAnalysisResponse JSON yourself by following it exactly, then call mcp__deckhand__intent_open_galaxy with that JSON.',
85    inputSchema: {
86      type: 'object',
87      properties: { goal: { type: 'string', description: "The user's fuzzy goal, verbatim." } },
88      required: ['goal'],
89    },
90  })
91  await $.tool.register({
92    name: 'intent_open_galaxy',
93    description:
94      'Step 2 of the Intent Galaxy flow (run by Deckhand). Validates and repairs an IntentAnalysisResponse JSON, opens the 12-node galaxy ' +
95      'in the browser, waits until the user locks it with Enter, and returns the LOCKED INTENT AST markdown. Follow the AST as hard constraints.',
96    inputSchema: {
97      type: 'object',
98      properties: {
99        goal: { type: 'string', description: "The user's goal, verbatim." },
100        analysis: { description: 'IntentAnalysisResponse object (or its JSON string) produced from intent_spawner_prompt.' },
101      },
102      required: ['analysis'],
103    },
104  })
105}
106
107/** At session start: when the package is already in Deckhand's folder, its tools are offered again. */
108export async function offerInstalled($: Engine) {
109  const s = await helperStatus($)
110  if (s?.installed && s.nodeOk) await registerOwnTools($)
111}
112
113/** What the iG button hands the main agent. English: only the model reads it; it answers in the person's language. */
114export const galaxyBrief = (o: { goal: string; spawner: string; open: string; languageName: string }) =>
115  [
116    "[iG] I (the user) pressed Deckhand's iG button: run Intent Galaxy on the goal below. Don't ask me first.",
117    '',
118    o.goal
119      ? `Goal (my words; pass it verbatim):\n<goal>\n${o.goal}\n</goal>`
120      : `Goal: I gave none. State the goal of the current work in this conversation in one sentence, in ${o.languageName}, show it to me, and use that sentence verbatim as the goal.`,
121    '',
122    'Steps',
123    `1. Call \`${o.spawner}\` with { "goal": <the goal> }.`,
124    `2. Follow the rules it returns exactly and write the IntentAnalysisResponse JSON yourself, its human-readable text in ${o.languageName}. Don't call another model for it.`,
125    `3. Tell me in one line that the galaxy opens in my browser and how to drive it: 1 / 2 / 3 apply a strategy, Space adopts a node, x excludes one, Enter locks. Then call \`${o.open}\` with { "goal": <the goal>, "analysis": <that JSON> }; it waits until I lock the galaxy.`,
126    '4. If it rejects the JSON, fix the findings it lists and call it again, at most twice; then stop and tell me why.',
127    "5. When it returns the LOCKED INTENT AST: show the AST, then sum it up in at most 3 lines. From then on, follow the AST as hard constraints. Don't start the work until I say so.",
128    '',
129    `Answer in ${o.languageName}.`,
130  ].join('\n')
131
132/** The goal the press took from the prompt box, kept while the install pane is up so it goes once the install is done. */
133let pendingGoal: string | null = null
134
135let lastGalaxyAt = 0
136
137async function handOverGalaxy($: Engine, goal: string, isWorking: boolean) {
138  const m = await msgs($)
139  const g = await read($, galaxyAtom)
140  $.ui.toast(isWorking ? m.galaxy.queued : m.galaxy.sent, { timeoutMs: TOAST.info })
141  const brief = galaxyBrief({ goal, spawner: g.spawner, open: g.open, languageName: LANGUAGE_NAME[await currentLocale($)] })
142  await handOverWhenIdle($, m.galaxy.visible(goal || m.delegate.currentTask), brief, isWorking)
143}
144
145/**
146 * The iG button: the draft in the prompt box is the goal (it leaves the box now, so it is not sent twice);
147 * with none, the conversation's current work. Without the tools, the install pane asks first.
148 */
149export async function startGalaxy($: Engine, isWorking: boolean) {
150  const m = await msgs($)
151  const now = await $.clock.now()
152  if (now - lastGalaxyAt < 8_000) {
153    $.ui.toast(m.galaxy.guard, { timeoutMs: TOAST.problem })
154    return false
155  }
156  lastGalaxyAt = now
157  const draft = (await $.prompt.read().catch(() => ({ text: '', cursor: 0 }))).text.trim()
158  if (draft) await $.prompt.fill({ text: '' }).catch(() => undefined)
159  try {
160    await detectGalaxy($)
161    if (!(await read($, galaxyAtom)).open) {
162      // Installed in an earlier session but not offered yet: offer the tools and look again.
163      const s = await helperStatus($)
164      if (s?.installed && s.nodeOk) {
165        await registerOwnTools($)
166        await detectGalaxy($)
167      }
168    }
169    if ((await read($, galaxyAtom)).open) {
170      await handOverGalaxy($, draft, isWorking)
171      return true
172    }
173    pendingGoal = draft
174    await openSetup($)
175    return false
176  } catch (error) {
177    lastGalaxyAt = 0
178    if (draft) await $.prompt.fill({ text: draft }).catch(() => undefined)
179    $.ui.toast(m.galaxy.failed(errorText(error)), { timeoutMs: TOAST.problem })
180    return false
181  }
182}
183
184/** The install pane: what Deckhand found, and an install that waits for the person's press. */
185export async function openSetup($: Engine) {
186  const m = await msgs($)
187  await update($, galaxyAtom, (g): GalaxyView => ({ ...g, setup: 'checking', error: '' }))
188  await $.ui.open({ id: GALAXY_PANE, title: m.galaxy.setupTitle, focus: true })
189  const s = await helperStatus($)
190  await update($, galaxyAtom, (g): GalaxyView => ({
191    ...g,
192    node: s?.node ?? '',
193    needs: s?.needs ?? g.needs,
194    setup: !s ? 'failed' : s.nodeOk && s.npm ? 'ready' : 'no-node',
195    error: s ? '' : m.galaxy.helperFailed,
196  }))
197}
198
199/** The press on Install: npm puts the package in Deckhand's folder, the tools are offered, and the held goal goes. */
200export async function installGalaxy($: Engine) {
201  const m = await msgs($)
202  await update($, galaxyAtom, (g): GalaxyView => ({ ...g, setup: 'installing', error: '' }))
203  const s = await helperStatus($, ['install'], 360_000)
204  if (!s?.installed) {
205    const why = s?.error === 'node' || s?.error === 'npm' ? m.galaxy.setupNoNode(s.needs) : (s?.detail ?? []).join(' ') || m.galaxy.helperFailed
206    await update($, galaxyAtom, (g): GalaxyView => ({ ...g, setup: 'failed', error: why }))
207    return false
208  }
209  await registerOwnTools($)
210  await detectGalaxy($)
211  await $.ui.close({ id: GALAXY_PANE }).catch(() => undefined)
212  $.ui.toast(m.galaxy.installed(s.version), { timeoutMs: TOAST.done })
213  const goal = pendingGoal ?? ''
214  pendingGoal = null
215  if ((await read($, galaxyAtom)).open) await handOverGalaxy($, goal, false)
216  return true
217}
218
219/** One of Deckhand's own tools: bin/galaxy.py starts the package's server, calls the tool once, and answers. */
220async function callOwn($: Engine, tool: string, args: Record<string, unknown>, isLong: boolean) {
221  const argv = [await resolveBin($, 'python3'), `${$.plugin.root}/bin/galaxy.py`, 'call', tool, '--cwd', await $.session.cwd(), '--lang', await currentLocale($)]
222  const input = JSON.stringify({ goal: args.goal, analysis: args.analysis })
223  let out = ''
224  if (isLong) {
225    // The galaxy waits for the person's lock, up to 30 minutes: longer than a one-shot run may take.
226    for await (const piece of $.process.spawn({ argv, input })) if (piece.stream === 'stdout') out += piece.text
227  } else {
228    out = (await $.process.run(argv, { stdin: input, timeoutMs: 60_000 })).stdout
229  }
230  const answer = JSON.parse(lastLine(out) || '{}') as { text?: string; isError?: boolean }
231  return answer.isError || typeof answer.text !== 'string' ? { deny: answer.text || 'Intent Galaxy gave no answer.' } : { result: answer.text }
232}
233
234/** The hooks of this part of the plugin; register.tsx calls this first. */
235export function registerGalaxy(on: On) {
236  // The galaxy's tool blocks until the person locks it in the browser: the band shows a row meanwhile.
237  on('tool.call', async ($, e, next) => {
238    if (!e.tool.startsWith('mcp__') || !e.tool.endsWith(OPEN_SUFFIX)) return next(e)
239    await markGalaxyOpen($, true)
240    try {
241      return await next(e)
242    } finally {
243      await markGalaxyOpen($, false)
244    }
245  })
246
247  on('tool.call', { tool: OWN_SPAWNER }, async ($, e) => callOwn($, 'intent_spawner_prompt', e as unknown as Record<string, unknown>, false)).catch(
248    async ($, _e, next) => ({ deny: (await msgs($)).galaxy.failed(errorText(next.error)) }),
249  )
250
251  on('tool.call', { tool: OWN_OPEN }, async ($, e) => callOwn($, 'intent_open_galaxy', e as unknown as Record<string, unknown>, true)).catch(
252    async ($, _e, next) => ({ deny: (await msgs($)).galaxy.failed(errorText(next.error)) }),
253  )
254
255  on('ui.render', { component: 'Pane', requestId: GALAXY_PANE }, async ($, e) => {
256    const { Box, Text, Button } = $.ui.resolve(e)
257    const m = await msgsForDrawing($)
258    const g = await read($, galaxyAtom)
259    return (
260      <Box flexDirection="column" gap={1}>
261        <Text>{m.galaxy.setupIntro}</Text>
262        <Text dimColor>{m.galaxy.setupWhat}</Text>
263        {g.setup === 'checking' && <Text dimColor>{m.galaxy.setupChecking}</Text>}
264        {g.setup === 'no-node' && <Text color={TONE.warn}>{m.galaxy.setupNoNode(g.needs)}</Text>}
265        {g.setup === 'ready' && <Text color={TONE.ok}>{m.galaxy.setupNode(g.node)}</Text>}
266        {g.setup === 'installing' && <Text dimColor>{m.galaxy.setupInstalling}</Text>}
267        {g.setup === 'failed' && <Text color={TONE.bad}>{m.galaxy.installFailed(g.error)}</Text>}
268        <Box gap={1}>
269          {(g.setup === 'ready' || g.setup === 'failed') && (
270            <Button key="galaxy-install" label={m.galaxy.setupInstall} variant="primary" onPress={() => void installGalaxy($).catch(() => undefined)} />
271          )}
272          <Button key="galaxy-cancel" label={m.galaxy.setupCancel} variant="secondary" role="dismiss" onPress={() => void $.ui.close({ id: GALAXY_PANE })} />
273        </Box>
274      </Box>
275    )
276  })
277}
278
hooks/handoff.tsx 193 lines
1/** Claude ↔ Codex: the handoff commands, the shared handoff tool and the Codex inbox pane. */
2import { atom, read, update } from 'claude-code'
3import type { On } from 'claude-code'
4
5import type { CodexThread } from '../types'
6import { ago, parseChecked, parseWritten, pastePrompt, stateLine, threadsArgv, unfence } from './codex'
7import { cfg, currentLocale, msgs, msgsForDrawing, resolveBin } from './core'
8import type { Engine } from './core'
9import { errorText, lastLine } from './state'
10import { listRoom, TOAST, TONE } from './ui'
11
12export async function loadCodexThreads($: Engine): Promise<CodexThread[]> {
13  await update($, codexLoadingAtom, () => true)
14  try {
15    const s = await cfg($)
16    const [, ...args] = threadsArgv($.plugin.root, await $.session.root(), await read($, codexAllAtom), s.paths.codexHome)
17    const ran = await $.process.run([await resolveBin($, 'python3'), ...args], { timeoutMs: 30_000 })
18    if (ran.exitCode !== 0) throw new Error(ran.stderr.trim().split('\n').pop() || `exit ${ran.exitCode}`)
19    const threads = JSON.parse(ran.stdout) as CodexThread[]
20    await update($, codexThreadsAtom, () => threads)
21    await update($, codexErrorAtom, () => null)
22    return threads
23  } catch (error) {
24    await update($, codexErrorAtom, () => errorText(error))
25    return []
26  } finally {
27    await update($, codexLoadingAtom, () => false)
28  }
29}
30
31/** Runs bin/handoff-state.py (the tool Codex runs too) in the session's working tree. */
32export async function handoffTool($: Engine, args: string[], stdin?: string) {
33  const locale = await currentLocale($)
34  return $.process.run(
35    [await resolveBin($, 'python3'), `${$.plugin.root}/bin/handoff-state.py`, ...args, '--cwd', await $.session.cwd(), '--lang', locale],
36    { stdin, timeoutMs: 60_000 },
37  )
38}
39
40/**
41 * Keeps ~/.agent-handoff/bin/handoff-state.py equal to the plugin's copy: Codex's AGENTS.md names that
42 * path, so it must not go stale when the plugin is updated. The folder is made private (700) when new.
43 * Its sibling i18n.py goes along, since the tool imports it.
44 */
45export async function syncSharedTool($: Engine) {
46  try {
47    const home = (await $.env.get('HOME')) ?? ''
48    await $.process.run(['mkdir', '-p', '-m', '700', `${home}/.agent-handoff`])
49    await $.process.run(['mkdir', '-p', `${home}/.agent-handoff/bin`])
50    for (const name of ['handoff-state.py', 'i18n.py']) {
51      const sourcePath = `${$.plugin.root}/bin/${name}`
52      if (!(await $.fs.exists(sourcePath))) continue
53      const source = await $.fs.read(sourcePath)
54      const target = `${home}/.agent-handoff/bin/${name}`
55      if ((await $.fs.exists(target)) && (await $.fs.read(target)) === source) continue
56      await $.fs.write(target, source)
57    }
58  } catch (error) {
59    $.ui.log((await msgs($)).codex.syncFailed(errorText(error)))
60  }
61}
62
63export const CODEX_PANE = 'deckhand-codex'
64
65const codexThreadsAtom = atom({ plugin: 'deckhand', key: 'codexThreads' } as const, [] as CodexThread[])
66
67const codexErrorAtom = atom({ plugin: 'deckhand', key: 'codexError' } as const, null as string | null)
68
69const codexLoadingAtom = atom({ plugin: 'deckhand', key: 'isCodexLoading' } as const, false)
70
71const codexAllAtom = atom({ plugin: 'deckhand', key: 'codexAllProjects' } as const, false)
72
73/** The hooks of this part of the plugin; register.tsx calls this first. */
74export function registerHandoff(on: On) {
75  // ── Claude ↔ Codex ──────────────────────────────────────────────────────
76
77  // Codex's file is read by the tool, which compares its recorded git facts with the repo as it is
78  // now; the differences go into the prompt, so the model starts from them instead of re-deriving.
79  on('command.run', { command: 'handoff-in' }, async $ => {
80    const m = await msgs($)
81    const ran = await handoffTool($, ['check', '--from', 'codex', '--to', 'claude', '--format', 'json'])
82    const checked = parseChecked(ran.stdout)
83    if (!checked) return { text: m.codex.checkFailed(lastLine(ran.stderr || ran.stdout) || `exit ${ran.exitCode}`) }
84    if ('error' in checked) {
85      return { text: checked.error === 'missing' ? m.codex.noHandoff(checked.path) : m.codex.notToolFile(checked.path) }
86    }
87    await $.prompt.fill({ text: checked.nextPrompt })
88    return { text: m.codex.handoffInFilled(checked.report) }
89  })
90
91  // The model writes only the narrative; the tool adds the git facts from real git, masks secrets,
92  // and names the file, the same way for Codex.
93  on('command.run', { command: 'handoff' }, async ($, e) => {
94    const m = await msgs($)
95    const forked = await $.model.fork({ prompt: m.codex.handoffPrompt(e.args.trim(), m.languageName) })
96    if (!forked.isAnswered) return { text: m.codex.handoffFailed(forked.reason) }
97    const ran = await handoffTool($, ['write', '--from', 'claude', '--to', 'codex'], unfence(forked.text))
98    const written = ran.exitCode === 0 ? parseWritten(ran.stdout) : null
99    if (!written) return { text: m.codex.writeFailed(lastLine(ran.stderr || ran.stdout) || `exit ${ran.exitCode}`) }
100    const copied = await $.ui.copy({ text: written.nextPrompt }).catch(() => ({ isCopied: false as const }))
101    return {
102      text: [
103        m.codex.file(written.path),
104        stateLine(written.state, m),
105        ...(written.redacted > 0 ? [m.codex.masked(written.redacted)] : []),
106        m.codex.copyThis(copied.isCopied),
107        '',
108        written.nextPrompt,
109      ].join('\n'),
110    }
111  })
112
113  on('command.run', { command: 'codex' }, async ($, e) => {
114    const m = await msgs($)
115    await update($, codexAllAtom, () => e.args.trim() === 'all')
116    await $.ui.open({ id: CODEX_PANE, title: m.codex.paneTitle })
117    void loadCodexThreads($)
118    return { text: m.codex.opened }
119  })
120
121  on('command.run', { command: 'codex-latest' }, async $ => {
122    const m = await msgs($)
123    await update($, codexAllAtom, () => false)
124    const [latest] = await loadCodexThreads($)
125    if (!latest) return { text: m.codex.noThreads((await read($, codexErrorAtom)) ?? '') }
126    await $.prompt.fill({ text: pastePrompt(latest, m) })
127    return { text: m.codex.latestFilled(latest.name) }
128  })
129
130  on('ui.render', { component: 'Pane', requestId: CODEX_PANE }, async ($, e) => {
131    const { Box, Text, Button } = $.ui.resolve(e)
132    const m = await msgsForDrawing($)
133    const threads = await read($, codexThreadsAtom)
134    const isLoading = await read($, codexLoadingAtom)
135    const isAll = await read($, codexAllAtom)
136    const error = await read($, codexErrorAtom)
137    const now = await $.clock.now()
138    const room = listRoom(e.viewport?.rows, 8, 5)
139
140    return (
141      <Box flexDirection="column" gap={1}>
142        <Box gap={1} alignItems="center" flexWrap="wrap">
143          <Text bold>
144            {isAll ? m.codex.allProjects : m.codex.thisProject} · {m.codex.last7}
145          </Text>
146          <Button key="refresh" label={m.codex.refresh} variant="secondary" onPress={() => void loadCodexThreads($)} />
147          <Button
148            key="scope"
149            label={isAll ? m.codex.onlyThis : m.codex.showAll}
150            variant="secondary"
151            onPress={async () => {
152              await update($, codexAllAtom, all => !all)
153              await loadCodexThreads($)
154            }}
155          />
156        </Box>
157        {isLoading && <Text dimColor>{m.codex.loading}</Text>}
158        {error !== null && <Text color={TONE.bad}>{m.codex.loadFailed(error)}</Text>}
159        {!isLoading && error === null && threads.length === 0 && <Text dimColor>{m.codex.none}</Text>}
160        {threads.slice(0, room).map((t, i) => (
161          <Box key={`t-${i}`} flexDirection="column">
162            <Text bold wrap="truncate">
163              {t.name}
164            </Text>
165            <Text dimColor wrap="truncate">
166              {ago(t.updatedAt, now, m)} · {t.cwd.split('/').slice(-2).join('/')}
167            </Text>
168            <Text wrap="truncate">{t.lastAssistant.replace(/\s+/g, ' ').slice(0, 200)}</Text>
169            <Box gap={1} flexWrap="wrap">
170              <Button key={`fill-${i}`} label={m.codex.fill} variant="secondary" onPress={() => void $.prompt.fill({ text: pastePrompt(t, m) })} />
171              <Button
172                key={`copy-${i}`}
173                label={m.codex.copyReply}
174                variant="secondary"
175                onPress={async press => {
176                  const copied = await $.ui.copy({ text: t.lastAssistant, surface: press.surface }).catch(() => ({ isCopied: false }))
177                  if (copied.isCopied) $.ui.toast(m.common.copied, { timeoutMs: TOAST.done })
178                }}
179              />
180            </Box>
181          </Box>
182        ))}
183        {threads.length > room ? <Text dimColor>{m.common.more(threads.length - room)}</Text> : null}
184        {e.surface !== 'desktop' && (
185          <Box>
186            <Button key="close" label={m.common.close} role="dismiss" onPress={() => void $.ui.close({ id: CODEX_PANE })} />
187          </Box>
188        )}
189      </Box>
190    )
191  })
192}
193
hooks/i18n.ts 105 lines
1/**
2 * Which language the band, the panes, the toasts and the briefs speak. `auto` follows Claude Code's own
3 * `language` setting, a free-text value (`正體中文`, `japanese`, `pt-BR`), so names and tags both count.
4 * Pure: the catalogs are data, `messages(locale)` picks one; locales.ts lists the languages.
5 */
6import type { Locale } from '../types'
7import { en } from './i18n/en'
8import type { Messages } from './i18n/en'
9import { ar } from './i18n/ar'
10import { ca } from './i18n/ca'
11import { cs } from './i18n/cs'
12import { da } from './i18n/da'
13import { de } from './i18n/de'
14import { el } from './i18n/el'
15import { es } from './i18n/es'
16import { esMX } from './i18n/es-MX'
17import { fi } from './i18n/fi'
18import { fil } from './i18n/fil'
19import { fr } from './i18n/fr'
20import { he } from './i18n/he'
21import { hi } from './i18n/hi'
22import { hr } from './i18n/hr'
23import { hu } from './i18n/hu'
24import { id } from './i18n/id'
25import { it } from './i18n/it'
26import { ja } from './i18n/ja'
27import { km } from './i18n/km'
28import { ko } from './i18n/ko'
29import { lo } from './i18n/lo'
30import { ms } from './i18n/ms'
31import { my } from './i18n/my'
32import { nb } from './i18n/nb'
33import { nl } from './i18n/nl'
34import { pl } from './i18n/pl'
35import { pt } from './i18n/pt'
36import { ptBR } from './i18n/pt-BR'
37import { ro } from './i18n/ro'
38import { ru } from './i18n/ru'
39import { sk } from './i18n/sk'
40import { sv } from './i18n/sv'
41import { th } from './i18n/th'
42import { tr } from './i18n/tr'
43import { uk } from './i18n/uk'
44import { vi } from './i18n/vi'
45import { zhHans } from './i18n/zh-Hans'
46import { zhHant } from './i18n/zh-Hant'
47import { zhHantHK } from './i18n/zh-Hant-HK'
48import { zhHantTW } from './i18n/zh-Hant-TW'
49import { normalizeLocale } from './locales'
50
51export type { Messages } from './i18n/en'
52export type { Locale } from '../types'
53export { LANGUAGE_NAME, LOCALES, normalizeLocale } from './locales'
54
55export const CATALOG: Readonly<Partial<Record<Locale, Messages>>> = {
56  en,
57  'zh-Hant-TW': zhHantTW,
58  'zh-Hans': zhHans,
59  ja,
60  ko,
61  'zh-Hant': zhHant,
62  'zh-Hant-HK': zhHantHK,
63  vi,
64  uk,
65  tr,
66  th,
67  sv,
68  sk,
69  ru,
70  ro,
71  pt,
72  'pt-BR': ptBR,
73  pl,
74  nl,
75  nb,
76  my,
77  ms,
78  lo,
79  km,
80  it,
81  id,
82  hu,
83  hr,
84  hi,
85  he,
86  fr,
87  fil,
88  fi,
89  es,
90  'es-MX': esMX,
91  el,
92  de,
93  da,
94  cs,
95  ca,
96  ar,
97}
98
99/** A locale's catalog; English for a locale that has none. */
100export const messages = (locale: Locale): Messages => CATALOG[locale] ?? en
101
102/** `auto` reads Claude Code's language, then the environment; a pick in settings wins. */
103export const resolveLocale = (choice: 'auto' | Locale, claudeLanguage: unknown, envLang = ''): Locale =>
104  choice !== 'auto' ? choice : (normalizeLocale(claudeLanguage, envLang) ?? normalizeLocale(envLang) ?? 'en')
105
hooks/leftovers.tsx 138 lines
1/** Sub5 leftovers: what interrupted runs left behind, listed and cleaned through bin/sub5.py, in a pane of their own. */
2import { atom, read, update } from 'claude-code'
3import type { On } from 'claude-code'
4
5import type { Sub5Leftover, Sub5Leftovers } from '../types'
6import { currentLocale, msgs, msgsForDrawing, resolveBin } from './core'
7import type { Engine } from './core'
8import { errorText } from './state'
9import { isActionable, leftoverLine, leftoversArgv, parseCleaned, parseLeftovers } from './sub5'
10import { listRoom, TOAST, TONE } from './ui'
11
12/** What the leftovers check found, for the settings pane's line. */
13export async function leftoversState($: Engine) {
14  return read($, leftoversAtom)
15}
16
17/** `sub5.py list|clean` in the session's folder; clean never with `--force` (Sub5 cleanup never forces). */
18export async function runLeftovers($: Engine, action: 'list' | 'clean') {
19  return $.process.run(
20    leftoversArgv({
21      python: await resolveBin($, 'python3'),
22      tool: `${$.plugin.root}/bin/sub5.py`,
23      action,
24      cwd: await $.session.cwd(),
25      locale: await currentLocale($),
26    }),
27    { timeoutMs: action === 'clean' ? 180_000 : 60_000 },
28  )
29}
30
31export async function loadLeftovers($: Engine): Promise<Sub5Leftover[] | null> {
32  await update($, leftoversAtom, v => ({ ...v, status: 'loading' as const, error: null }))
33  try {
34    const ran = await runLeftovers($, 'list')
35    const entries = ran.exitCode === 0 ? parseLeftovers(ran.stdout) : null
36    if (!entries) throw new Error(failureOf(ran))
37    await update($, leftoversAtom, v => ({ ...v, status: 'done' as const, entries, error: null }))
38    return entries
39  } catch (error) {
40    await update($, leftoversAtom, v => ({ ...v, status: 'error' as const, entries: [], error: errorText(error), isArmed: false }))
41    return null
42  }
43}
44
45/** `/sub5-clean` and the Sub5 tab's button: the pane with the list; nothing is removed until its confirm press. */
46export async function openLeftovers($: Engine) {
47  const m = await msgs($)
48  await update($, leftoversAtom, v => ({ ...v, isArmed: false }))
49  await $.ui.open({ id: SUB5_CLEAN_PANE, title: m.sub5.cleanTitle })
50  return loadLeftovers($)
51}
52
53export async function cleanLeftovers($: Engine) {
54  const m = await msgs($)
55  if ((await read($, leftoversAtom)).isCleaning) return
56  await update($, leftoversAtom, v => ({ ...v, isArmed: false, isCleaning: true }))
57  try {
58    // Exit 1 means something was kept: the JSON is still the answer.
59    const ran = await runLeftovers($, 'clean')
60    const done = parseCleaned(ran.stdout)
61    if (!done) throw new Error(failureOf(ran))
62    $.ui.toast(m.sub5.cleaned(done.worktrees, done.branches, done.kept + done.failed), { timeoutMs: TOAST.info })
63  } catch (error) {
64    $.ui.toast(m.sub5.cleanError(errorText(error)), { timeoutMs: TOAST.problem })
65  } finally {
66    await update($, leftoversAtom, v => ({ ...v, isCleaning: false }))
67  }
68  await loadLeftovers($)
69}
70
71export const SUB5_CLEAN_PANE = 'deckhand-sub5-clean'
72
73const leftoversAtom = atom({ plugin: 'deckhand', key: 'sub5Leftovers' } as const, {
74  status: 'idle',
75  entries: [],
76  error: null,
77  isArmed: false,
78  isCleaning: false,
79} as Sub5Leftovers)
80
81const failureOf = (ran: { exitCode: number; stdout: string; stderr: string }) =>
82  ((ran.stderr || ran.stdout).trim().split('\n').pop() ?? '').replace(/^sub5: /, '') || `exit ${ran.exitCode}`
83
84/** The hooks of this part of the plugin; register.tsx calls this first. */
85export function registerLeftovers(on: On) {
86  // ── Sub5 leftovers pane ─────────────────────────────────────────────────
87
88  on('command.run', { command: 'sub5-clean' }, async $ => {
89    const m = await msgs($)
90    const entries = await openLeftovers($)
91    if (entries === null) return { text: m.sub5.cleanFailed((await read($, leftoversAtom)).error ?? '') }
92    if (!entries.length) return { text: m.sub5.cleanNone }
93    return { text: `${m.sub5.cleanSummary(entries.length, entries.filter(isActionable).length)}\n${m.sub5.cleanOpened}` }
94  })
95
96  on('ui.render', { component: 'Pane', requestId: SUB5_CLEAN_PANE }, async ($, e) => {
97    const { Box, Text, Button } = $.ui.resolve(e)
98    const m = await msgsForDrawing($)
99    const state = await read($, leftoversAtom)
100    const actionable = state.entries.filter(isActionable).length
101    const room = listRoom(e.viewport?.rows, 8, 2)
102    return (
103      <Box flexDirection="column" gap={1}>
104        <Text dimColor>{m.sub5.cleanHint}</Text>
105        {state.status === 'loading' && <Text dimColor>{m.sub5.cleanLoading}</Text>}
106        {state.isCleaning && <Text dimColor>{m.sub5.cleaning}</Text>}
107        {state.status === 'error' && <Text color={TONE.bad}>{m.sub5.cleanFailed(state.error ?? '')}</Text>}
108        {state.status === 'done' && (
109          <Text bold>{state.entries.length ? m.sub5.cleanSummary(state.entries.length, actionable) : m.sub5.cleanNone}</Text>
110        )}
111        {state.entries.slice(0, room).map((x, i) => (
112          <Box key={`lo-${i}`} flexDirection="column">
113            <Text wrap="truncate">{x.path ?? x.branch}</Text>
114            {/* What the clean-up would remove reads as a warning, not as a success. */}
115            <Text dimColor={!isActionable(x)} color={isActionable(x) ? TONE.warn : undefined} wrap="truncate">
116              {leftoverLine(x, m)}
117            </Text>
118          </Box>
119        ))}
120        {state.entries.length > room ? <Text dimColor>{m.common.more(state.entries.length - room)}</Text> : null}
121        <Box gap={1} flexWrap="wrap">
122          {state.isArmed ? (
123            <Button key="clean-confirm" label={m.sub5.cleanConfirm(actionable)} variant="primary" onPress={() => void cleanLeftovers($).catch(() => undefined)} />
124          ) : null}
125          {state.isArmed ? (
126            <Button key="clean-cancel" label={m.sub5.cleanCancel} variant="secondary" onPress={() => void update($, leftoversAtom, v => ({ ...v, isArmed: false }))} />
127          ) : null}
128          {!state.isArmed && actionable > 0 && !state.isCleaning ? (
129            <Button key="clean" label={m.sub5.cleanButton(actionable)} variant="secondary" onPress={() => void update($, leftoversAtom, v => ({ ...v, isArmed: true }))} />
130          ) : null}
131          <Button key="refresh" label={m.sub5.cleanRefresh} variant="secondary" onPress={() => void loadLeftovers($).catch(() => undefined)} />
132          {e.surface !== 'desktop' && <Button key="close" label={m.sub5.cleanClose} role="dismiss" onPress={() => void $.ui.close({ id: SUB5_CLEAN_PANE })} />}
133        </Box>
134      </Box>
135    )
136  })
137}
138
hooks/models.tsx 320 lines
1/** The usage readout and the model buttons: the 5h, weekly and context gauges, their warnings, and switching the main model while keeping its effort. */
2import { atom, read, update } from 'claude-code'
3import type { On, RenderSurface } from 'claude-code'
4
5import { asRecord, cfg, knownScoped, msgs, rememberScoped } from './core'
6import type { Engine } from './core'
7import type { Messages } from './i18n'
8import { errorText } from './state'
9import { TOAST } from './ui'
10import {
11  describeSources,
12  desktopModelArg,
13  learnModelId,
14  MODEL_BUTTONS,
15  modelFamily,
16  parseAccountUsage,
17  planSwitch,
18  scopedFamily,
19  shownPercent,
20  usageSegments,
21} from './usage'
22import type { AccountLimits, EngineLimit, Family, Segment } from './usage'
23
24export async function storeUsage($: Engine, m: Measured) {
25  await update($, engineLimitsAtom, () => m.rateLimits.map(r => ({ kind: r.kind, percent: r.percentUsed, resetsAt: r.resetsAt })))
26  await update($, contextPercentAtom, () => m.context.percent ?? null)
27  await update($, contextTokensAtom, () => m.context.tokens ?? null)
28}
29
30export async function refreshModel($: Engine) {
31  const model = await $.session.model().catch(() => '')
32  if (model) await update($, modelAtom, () => model)
33  await rememberModelId($, model)
34}
35
36/** Full model ids the engine has named, by family: what the desktop model buttons send. Kept across sessions. */
37export async function knownModelIds($: Engine): Promise<Partial<Record<Family, string>>> {
38  const stored = asRecord(await $.store.get('modelIds').catch(() => undefined))
39  const out: Partial<Record<Family, string>> = {}
40  for (const b of MODEL_BUTTONS) {
41    const id = stored[b.family]
42    if (typeof id === 'string' && learnModelId(id)?.family === b.family) out[b.family] = id
43  }
44  return out
45}
46
47export async function rememberModelId($: Engine, text: string) {
48  const learned = learnModelId(text)
49  if (!learned) return
50  const known = await knownModelIds($)
51  if (known[learned.family] === learned.id) return
52  await $.store.set('modelIds', { ...known, [learned.family]: learned.id }).catch(() => undefined)
53}
54
55/**
56 * The weekly windows are nowhere in the engine's figures, so the account's own usage is asked for,
57 * through the engine: it holds the credential and sets the header, the plugin never sees the secret.
58 * Rare on purpose; a failure keeps the last good reading and backs off.
59 */
60export async function refreshAccountUsage($: Engine, force = false) {
61  const now = await $.clock.now()
62  if (!force && (now - lastAccountTry < ACCOUNT_MIN_MS || now < accountBackoffUntil)) return
63  lastAccountTry = now
64  const fail = async (status: string) => {
65    accountBackoffUntil = now + ACCOUNT_BACKOFF_MS
66    const current = await read($, accountLimitsAtom)
67    if (current && current.status === 'ok') return
68    await update($, accountLimitsAtom, () => ({ windows: [], fetchedAt: now, status }))
69    // 7d has no other source: say once per session why it reads – (no credential is no news: an API key has no plan limits).
70    if (status !== 'no-credential' && !accountWarned) {
71      accountWarned = true
72      $.ui.toast((await msgs($)).usage.unreadable(status), { timeoutMs: TOAST.problem })
73    }
74  }
75  try {
76    const auth = await $.session.authorize()
77    if (!auth || auth.kind !== 'bearer') return await fail('no-credential')
78    const res = await $.http.fetch(USAGE_URL, {
79      auth: auth.handle,
80      headers: { accept: 'application/json', 'anthropic-beta': 'oauth-2025-04-20' },
81    })
82    if (!res.ok) return await fail(`http-${res.status}`)
83    const parsed = parseAccountUsage(JSON.parse(res.text), now, 'ok', res.text.slice(0, 1500))
84    if (!parsed) return await fail('no-windows')
85    accountBackoffUntil = 0
86    await update($, accountLimitsAtom, () => parsed)
87    // Remember which model windows this account has, so they read – (not vanish) while unreadable.
88    const families = [...new Set(parsed.windows.map(scopedFamily).filter((f): f is string => f !== null))]
89    const known = await knownScoped($)
90    if (families.some(f => !known.includes(f))) {
91      const merged = [...new Set([...known, ...families])]
92      await rememberScoped($, merged)
93    }
94  } catch (error) {
95    await fail(`error: ${errorText(error).slice(0, 80)}`)
96  }
97}
98
99export async function loadUsage($: Engine) {
100  await storeUsage($, await $.session.usage())
101}
102
103export async function currentSegments($: Engine, warnAt: number, withContext: boolean): Promise<Segment[]> {
104  return usageSegments({
105    engine: await read($, engineLimitsAtom),
106    account: await read($, accountLimitsAtom),
107    contextPercent: withContext ? await read($, contextPercentAtom) : null,
108    now: await $.clock.now(),
109    warnAt,
110    knownScoped: await knownScoped($),
111  })
112}
113
114/** One toast per limit and level, for the highest level crossed; it speaks again after the window resets. */
115export async function warnWhenHigh($: Engine) {
116  const warnAt = (await cfg($)).usage.warnPercent
117  const m = await msgs($)
118  for (const s of await currentSegments($, warnAt, false)) {
119    if (s.percent === null) continue
120    const crossed = [95, warnAt].find(level => s.percent! >= level)
121    if (crossed === undefined) continue
122    const key = `${s.id}@${crossed}@${s.resetsAt ?? ''}`
123    if (warned.has(key)) continue
124    warned.add(key)
125    if (crossed === 95) warned.add(`${s.id}@${warnAt}@${s.resetsAt ?? ''}`)
126    const reset = s.resetsAt ? m.usage.resets(s.resetsAt.slice(11, 16)) : ''
127    $.ui.toast(m.usage.warn(limitName(s, m), shownPercent(s.percent), reset), { timeoutMs: TOAST.problem })
128  }
129}
130
131/**
132 * A /model ran (the command hook, or the app's own path reported by PostModelSwitch): when it is the one
133 * a model button wrote, the effort the last turn ran at comes back, from a timer since a hook may not
134 * run a command. The record is cleared on the first of the two events, so the effort is put back once.
135 */
136export async function settleSwitch($: Engine, requested: string) {
137  const pending = pendingSwitch
138  if (!pending) return
139  const now = await $.clock.now()
140  const asked = requested.trim().toLowerCase()
141  const isOurs = asked === pending.alias.toLowerCase() || modelFamily(asked) === modelFamily(pending.alias)
142  if (!isOurs) return
143  pendingSwitch = null
144  if (pending.level && now - pending.at < 10 * 60_000) {
145    const level = pending.level
146    $.clock.after(10, () => void (async () => {
147      await restoreEffort($, level, await msgs($))
148    })().catch(() => undefined))
149  }
150}
151
152/** The session's model id, as the last switch or session start left it. */
153export async function currentModel($: Engine) {
154  return read($, modelAtom)
155}
156
157/** The effort the last main turn really ran at: what a model switch puts back. */
158export async function rememberEffort($: Engine, level: string) {
159  await update($, effortAtom, () => level)
160}
161
162/**
163 * A click on O / F / S / H.
164 *
165 * The desktop app owns the session's model: it applies its own menu's pick to every turn, and its menu
166 * follows only a /model the person sends. A switch made behind its back is undone on the next turn,
167 * and no plugin call reaches its menu: `$.prompt.submit` refuses a text starting with `/`, the app
168 * refuses a session setting its own model, and no call moves the focus into the composer. So there
169 * the button writes `/model <family>` into the prompt box and the person presses Enter: the app's own
170 * path, menu included. Where the box cannot take it, the command goes to the clipboard instead.
171 *
172 * Elsewhere (the terminal) the engine owns the model: `/model <family>` runs at once, then the effort
173 * the last turn ran at is put back, because switching models otherwise loads the new model's own level.
174 */
175export async function pressModel($: Engine, family: Family, isWorking: boolean, surface: RenderSurface) {
176  const m = await msgs($)
177  const current = await $.session.model().catch(() => '')
178  const plan = planSwitch(current, family, await read($, contextTokensAtom), m)
179  if (!plan.ok) {
180    $.ui.toast(plan.reason, { timeoutMs: TOAST.problem })
181    return
182  }
183  const name = MODEL_BUTTONS.find(b => b.family === family)!.name
184  if (surface === 'desktop') {
185    // The app's menu knows models by full id only: `/model opus` would leave it on "unsupported model".
186    const target = desktopModelArg(plan.alias, await knownModelIds($))
187    const command = `/model ${target}`
188    const box = await $.prompt.read().catch(() => ({ text: '', cursor: 0 }))
189    if (box.text.trim() && !/^\/model\b/.test(box.text.trim())) {
190      $.ui.toast(m.model.boxBusy, { timeoutMs: TOAST.problem })
191      return
192    }
193    const level = plan.keepEffort ? await read($, effortAtom) : null
194    const effort = level ? m.model.effortKept(level) : ''
195    // Whichever way the command reaches the person, the effort comes back once they send it.
196    pendingSwitch = { alias: target, level, at: await $.clock.now() }
197    const filled = await $.prompt.fill({ text: command, mode: 'replace' }).catch(() => ({ isFilled: false }))
198    if (filled.isFilled) {
199      $.ui.toast(m.model.fillReady(name, command, effort), { timeoutMs: TOAST.action })
200      return
201    }
202    const copied = await $.ui.copy({ text: command, surface }).catch(() => ({ isCopied: false }))
203    $.ui.toast(copied.isCopied ? m.model.copied(name, command, effort) : m.model.fillFailed(command), { timeoutMs: TOAST.action })
204    return
205  }
206  if (isWorking) {
207    $.ui.toast(m.model.busy, { timeoutMs: TOAST.problem })
208    return
209  }
210  const level = plan.keepEffort ? await read($, effortAtom) : null
211  let after = current
212  let said = ''
213  for (const alias of plan.alias === family ? [family] : [plan.alias, family]) {
214    try {
215      said = (await $.command.run({ command: 'model', args: alias })).text ?? said
216    } catch (error) {
217      said = errorText(error)
218    }
219    after = await $.session.model()
220    if (modelFamily(after) === family) break
221  }
222  await update($, modelAtom, () => after)
223  if (modelFamily(after) !== family) {
224    $.ui.toast(m.model.failed(said), { timeoutMs: TOAST.problem })
225    return
226  }
227  $.ui.toast(m.model.switched(after, level ? await restoreEffort($, level, m) : ''), { timeoutMs: TOAST.done })
228}
229
230/** Puts the effort back; says so when this version has no /effort, instead of claiming it was kept. */
231export async function restoreEffort($: Engine, level: string, m: Messages) {
232  try {
233    const commands = await $.command.list()
234    if (!commands.some(c => c.name === 'effort')) throw new Error(m.model.noEffortCommand)
235    await $.command.run({ command: 'effort', args: level })
236    return m.model.effortKept(level)
237  } catch (error) {
238    return m.model.effortNotKept(level, errorText(error))
239  }
240}
241
242const engineLimitsAtom = atom({ plugin: 'deckhand', key: 'engineLimits' } as const, [] as EngineLimit[])
243
244const accountLimitsAtom = atom({ plugin: 'deckhand', key: 'accountLimits' } as const, null as AccountLimits | null)
245
246const contextPercentAtom = atom({ plugin: 'deckhand', key: 'contextPercent' } as const, null as number | null)
247
248const contextTokensAtom = atom({ plugin: 'deckhand', key: 'contextTokens' } as const, null as number | null)
249
250const modelAtom = atom({ plugin: 'deckhand', key: 'model' } as const, '')
251
252const effortAtom = atom({ plugin: 'deckhand', key: 'effort' } as const, null as string | null)
253
254const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
255
256/** The account's usage is asked for at most this often; after a failure, not before the backoff. */
257const ACCOUNT_MIN_MS = 5 * 60_000
258
259const ACCOUNT_BACKOFF_MS = 15 * 60_000
260
261let lastAccountTry = 0
262
263let accountBackoffUntil = 0
264
265let accountWarned = false
266
267type Measured = {
268  rateLimits: readonly { kind: string; percentUsed: number; resetsAt?: string }[]
269  context: { percent?: number; tokens?: number }
270}
271
272const limitName = (s: Segment, m: Messages) =>
273  s.id === 'fiveHour' ? m.usage.fiveHour : s.id === 'weekly' ? m.usage.weekly : m.usage.scoped(s.name ?? s.id)
274
275/** The limits already warned about, so each warning is toasted once per window. */
276const warned = new Set<string>()
277
278/** A /model the desktop app is about to send for the person: the effort to put back once it ran. */
279let pendingSwitch: { alias: string; level: string | null; at: number } | null = null
280
281/** The hooks of this part of the plugin; register.tsx calls this first. */
282export function registerModels(on: On) {
283  on('session.measure', async ($, e, next) => {
284    await storeUsage($, e)
285    await refreshModel($)
286    if (e.changed.includes('rateLimits')) void refreshAccountUsage($).catch(() => undefined)
287    await warnWhenHigh($)
288    return next(e)
289  }).catch(($, e, next) => next(e))
290
291  // A /model the person sent moves the lit button; one the model button wrote (desktop) also puts the
292  // effort back, from a timer since a command hook may not run another command.
293  on('command.run', { command: 'model' }, async ($, e, next) => {
294    const result = await next(e)
295    await rememberModelId($, result.text ?? '')
296    await refreshModel($)
297    await settleSwitch($, e.args)
298    return result
299  }).catch(($, e, next) => next(e))
300
301  // The desktop app runs its /model itself, outside the command hook, and applies it to the engine
302  // headlessly: this event is where the lit button moves and the effort comes back there.
303  on('classic.PostModelSwitch', async ($, e, next) => {
304    await update($, modelAtom, () => e.to_model)
305    await rememberModelId($, e.to_model)
306    await settleSwitch($, e.requested_model ?? e.to_model)
307    return next(e)
308  }).catch(($, e, next) => next(e))
309
310  on('command.run', { command: 'usage-raw' }, async $ => {
311    const m = await msgs($)
312    const s = await cfg($)
313    await loadUsage($).catch(() => undefined)
314    await refreshAccountUsage($, true)
315    const lines = describeSources(await read($, engineLimitsAtom), await read($, accountLimitsAtom), await $.clock.now(), m)
316    const shown = (await currentSegments($, s.usage.warnPercent, true)).map(seg => seg.text).join(' · ')
317    return { text: [...lines, '', m.usage.barShows(shown)].join('\n') }
318  })
319}
320