SLOPSHOPPER

SimpleCORE Accounts

Switch between saved Claude logins and watch every account's rate limits

panebandspinnerrowsguardcommand
★ 2v0.7.2MITupdated 2026-10-20simplecore-inc/claude-mods/mods/accounts
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · sc-accounts
│ ┃ account-switch ✕ › fix the failing auth test and add an audit log call │ ┃ [SC] Accounts ✕ Close │ ┃ 1: Accounts ● sc-accounts: account-switch: cannot read the release: ENOENT: no su │ ┃ ● sc-accounts: account-switch: ENOENT: no such file /Users/dev/.claud │ ┃ No saved accounts yet. Reading the ⏺ Read(src/auth.ts) │ ┃ current login. ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ ╭──────────────────────────────────────────╮ ⎿ Added 2 lines, removed 1 line │ ┃ │ Codex │ ⏺ Bash(bun test) │ ┃ │ loading │ ⎿ 3 pass, 1 fail │ ┃ ╰──────────────────────────────────────────╯ │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ Refresh Add account W │ ✻ Worked for 42s · done 4:20 PM │ │ › /codex-model │ ⎿ sc-accounts: Open a codex agent's view to use /codex-model. │ │ ──────────────────────────────────────────────────────────────────────────────────────────────────── ▐Opus5.5▌ band-place band-toolbox ▐ctx ━━━━━━ 61%▌ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
──────────────────────────────────────────────────────────────────────────────────────────────────── ▐Opus5.5▌ band-place band-toolbox ▐ctx ━━━━━━ 61%▌
Pane · account-switch
[SC] Accounts ✕ Close 1: Accounts No saved accounts yet. Reading the current login. ╭──────────────────────────────────────────────────────────╮ │ Codex │ │ loading │ ╰──────────────────────────────────────────────────────────╯ Refresh Add account Webhook
README

SimpleCORE Claude Mods

macOS: tested Linux: untested WSL: tested Windows: untested License: MIT

Plugins for Claude Code that add panes, a status band and slash commands to the terminal: switch between several Claude accounts, watch their usage limits and token use, see and clean up what Claude Code keeps on the machine, and keep agents, worktrees, checkpoints, diffs and memory files in one pane, and run a project's builds and commands from buttons. Install one plugin, sc, and you get them all.

[!IMPORTANT] Clicking needs Claude Code's fullscreen mode. The buttons, tabs, tiles and status band cells answer a mouse click only while Claude Code draws in fullscreen mode. Turn it on once with /tui fullscreen, which is kept as "tui": "fullscreen" in ~/.claude/settings.json. In the default mode Claude Code passes no click to the plugins, on every platform, Windows and WSL included. See Clicking and the keyboard.

What's inside

Accounts · /sc:accounts

The accounts pane

The status band above the prompt

  • Keep several Claude logins and switch every running session to another in one step.
  • See each account's five-hour, weekly and per-model usage, with reset times, and what it spent past its plan when Claude reports it.
  • See the Codex login the session's Codex uses, with its limits and credits, on a card of its own where the Codex CLI is installed.
  • Usage: the tokens used on this machine by day, model and project, counted from Claude Code's transcripts.
  • Storage: what ~/.claude holds by kind and project, and a cleanup of idle sessions confirmed by typing a word.
  • A status band above the prompt: account, model and effort, task, context and usage, branch and PR, lines changed. Press the account's name to open the accounts pane, or the branch or the lines changed to open the workspace.
  • Each subagent's model and effort after its task in Claude Code's agent list: Review auth · Opus 5.5 (high).
  • Where the Codex CLI is installed, OpenAI Codex as a subagent: Claude starts it with the Agent tool (sc-accounts:codex-read, codex-write, codex-run) and sc-accounts drives codex app-server in its place.
  • An optional webhook sends the status to an external system. It is off by default; leave it off if you have nothing to send to.

Workspace · /sc:workspace

The workspace pane

  • Agents: the session's subagents, what each did last and the answers of those that finished, and the repository's worktrees; stop an agent, open a worktree's changes, remove a merged one.
  • Checkpoints: a snapshot of the working tree before every prompt; compare with one, see one turn's changes, name and pin one, or restore it.
  • Notes: numbered notes kept per project, optionally sent to Claude with every prompt; Claude can mark one done for you to confirm.
  • Diff: the files changed since the session started or since a checkpoint, up to now or a later checkpoint; each file's diff, restoring one file, and a request for a commit message.
  • Memory: the memory files Claude Code reads, global and project apart, to read as Markdown and search line by line.

Toolbox · /sc:toolbox

The toolbox buttons

  • The project's commands as buttons of one size, from ⚒ Toolbox on the status band.
  • Run and stop shell commands, and watch their log live in a dialog.
  • Add tasks found in npm, Vite, Maven, Gradle, Cargo, make, just, Compose, Go and Python projects, or Claude's own commands such as /clear and /compact.
  • Values fixed or asked at each run, with paths completed as you type.
  • Kept in .toolbox/toolbox.json in the project; share it or ignore it in git. A skill lets Claude write it for you.

Anything that cannot be taken back asks in a dialog first; Esc cancels.

Clicking and the keyboard

RequirementWhy
Claude Code in fullscreen mode: /tui fullscreen, or "tui": "fullscreen" in ~/.claude/settings.jsonOnly the fullscreen mode reads the mouse; in the default mode no click reaches a plugin
A terminal that passes mouse events to the program running in it; inside tmux, set -g mouse onA terminal that keeps the mouse for its own text selection sends Claude Code no click to pass on

Without a click, every control is reached from the keyboard:

  • ctrl+x then Tab gives the open pane, or the status band, the keyboard.
  • Tab and the arrow keys move between buttons; Enter presses the one with the ring.
  • A digit picks a tab; Esc goes back from a dialog and closes a pane.
  • Every pane also opens from its command: /sc:accounts, /sc:workspace, /sc:toolbox.

The first pane a command opens outside fullscreen mode says so in its reply.

In the Claude desktop app the panes and the band draw with the app's own buttons, tabs and font: rows wrap by the app's measure rather than the terminal's cells, the Usage chart is a picture, and a pane closes from its own title bar.

Install

claude plugin marketplace add simplecore-inc/claude-mods
claude plugin install sc@simplecore-mods

sc installs sc-accounts, sc-workspace and sc-toolbox with it. The plugins are installed for your user, so they run in every session. Run /reload-plugins in a session that was already open.

To use a local clone instead, add its folder as the marketplace:

git clone https://github.com/simplecore-inc/claude-mods.git
claude plugin marketplace add ./claude-mods
claude plugin install sc@simplecore-mods

Update

claude plugin marketplace update simplecore-mods
claude plugin update sc@simplecore-mods
claude plugin update sc-accounts@simplecore-mods
claude plugin update sc-workspace@simplecore-mods
claude plugin update sc-toolbox@simplecore-mods

Then run /reload-plugins in each open session. With a local clone, git pull in the clone and /reload-plugins are enough: a plugin from a folder marketplace is read from that folder.

Uninstall

claude plugin uninstall sc@simplecore-mods
claude plugin prune
claude plugin marketplace remove simplecore-mods

prune removes sc-accounts, sc-workspace and sc-toolbox, which were installed as dependencies of sc; uninstall them by name instead if you installed them yourself. marketplace remove is only needed when you will not install from it again.

The mods leave some data behind, which you can delete by hand:

WhatWhere
Saved loginsmacOS: keychain items of the service account-switch. Elsewhere: ~/.claude/account-switch/
Webhook tokenmacOS: the keychain item of the service sc-webhook. Elsewhere: ~/.claude/sc-accounts/webhook-token
Webhook template~/.claude/sc-accounts/
Settings, account index~/.claude/plugins/store/sc-*.json
Tools, their logs and remembered valuesin each project: .toolbox/
Notes and checkpoint listsin each repository's git folder: .git/sc-workspace/, a pair of files per worktree
Checkpointsin each repository: the refs under refs/sc/, and the files sc-snapshot-*.index in the git folder and in each worktree's folder under .git/worktrees/

~/.claude is CLAUDE_CONFIG_DIR when that is set. To delete a repository's checkpoints, and its notes with them, run in the repository:

git for-each-ref --format='%(refname)' refs/sc/ | xargs -n 1 git update-ref -d
common="$(git rev-parse --git-common-dir)"
rm -f "$common"/sc-snapshot-*.index "$common"/worktrees/*/sc-snapshot-*.index
rm -rf "$common/sc-workspace"

The account you are logged in with stays logged in; only the saved copies go.

Language

The mods show English, and Korean where Claude Code's language setting is Korean; any other language falls back to English. Without that setting, LC_ALL, LC_MESSAGES and LANG decide, in that order.

Developing

Developing a mod covers the layout, the rules the engine enforces, the checks and how to release.

License

MIT

Source 58 files
hooks/register.tsx 740 lines
1import { atom, read, update } from 'claude-code'
2import type { AgentSpawnInput, EngineInterface, Register } from 'claude-code'
3
4import { USAGE_KEY, hostAccount, syncLive, tickOrca } from './accounts'
5import type { AccountsContext } from './accounts'
6import { agentDefinitionNamed, agentLabel } from './agentModels'
7import { TYPES as CODEX_TYPES, codexInstalled, specsOf as codexAgentSpecs } from './codex/agents'
8import { HINT as CODEX_HINT, commandSpecs as codexCommandSpecs, isCommand as isCodexCommand, isOwnCommand as isOwnCodexCommand } from './codex/commands'
9import { flagsOf as codexFlagsOf } from './codex/flags'
10import { codexConfig, codexModels, labelOf as codexLabel } from './codex/model'
11import { closeHeld as closeHeldCodex, command as codexCommand, step as codexStep, steer as steerCodex } from './codex/step'
12import type { CodexContext } from './codex/step'
13import { refreshCodexAccount } from './codexAccount'
14import type { CodexAccountContext } from './codexAccount'
15import { openView as openCodexView, replyIn as codexReplyIn, setOpenView as setOpenCodexView } from './codex/view'
16import { lookedUpOnly } from './anthropic'
17import type { CleanupContext } from './cleanup'
18import type { CountContext } from './count'
19import { claudeDirectory, homeDirectory } from './credentials'
20import type { FeedContext } from './feed'
21import { releaseDateOf } from './format'
22import { messagesFor, resolveLocale } from './i18n'
23import type { Locale, Messages } from './i18n'
24import type { Cell, EnvName, Io } from './io'
25import { message } from './io'
26import { adoptMeasured, pollLive } from './lookups'
27import { keepOrcaCopiesFresh } from './orcaCopies'
28import { adoptSession, answerCommand, openPane, paneActions, paneModel, refresh, syncPaneOpen, toggle } from './paneControl'
29import type { PaneContext } from './paneControl'
30import { collectStatus, countLines, noteEffortCommand, noteRequestEffort, startStatus } from './sessionStatus'
31import type { StatusContext } from './sessionStatus'
32import { LATEST_RELEASE_KEY, RELEASE_CHECK_MS, latestReleaseUrl, latestVersion } from './shared/release'
33import type { RunningRelease } from './shared/release'
34import { surfaceTable } from './shared/kit'
35import { isBesideOtherPanes } from './shared/panes'
36import { editedPath, lineChanges } from './status'
37import type { EffortSettings } from './status'
38import { StatusBand, toolboxCell } from './views/band'
39import { CodexReplyBand } from './views/codexReply'
40import { AccountsPane } from './views/pane'
41
42const accounts = atom({ plugin: 'sc-accounts', key: 'accounts' } as const, [])
43const usage = atom({ plugin: 'sc-accounts', key: 'usage' } as const, {})
44const live = atom({ plugin: 'sc-accounts', key: 'live' } as const, null)
45const dialog = atom({ plugin: 'sc-accounts', key: 'dialog' } as const, null)
46const focused = atom({ plugin: 'sc-accounts', key: 'focused' } as const, null)
47const isRefreshing = atom({ plugin: 'sc-accounts', key: 'isRefreshing' } as const, false)
48const isGuideOpen = atom({ plugin: 'sc-accounts', key: 'isGuideOpen' } as const, false)
49const statusInfo = atom({ plugin: 'sc-accounts', key: 'status' } as const, null)
50const sessionEffort = atom({ plugin: 'sc-accounts', key: 'sessionEffort' } as const, null)
51const tick = atom({ plugin: 'sc-accounts', key: 'tick' } as const, 0)
52const webhookDraft = atom({ plugin: 'sc-accounts', key: 'webhookDraft' } as const, null)
53const webhookLast = atom({ plugin: 'sc-accounts', key: 'webhookLast' } as const, null)
54const paneOpen = atom({ plugin: 'sc-accounts', key: 'paneOpen' } as const, false)
55const tab = atom({ plugin: 'sc-accounts', key: 'tab' } as const, 'accounts')
56const usagePeriod = atom({ plugin: 'sc-accounts', key: 'usagePeriod' } as const, 30)
57const usageSummary = atom({ plugin: 'sc-accounts', key: 'usageSummary' } as const, null)
58const usageScan = atom({ plugin: 'sc-accounts', key: 'usageScan' } as const, null)
59const usageError = atom({ plugin: 'sc-accounts', key: 'usageError' } as const, null)
60const storage = atom({ plugin: 'sc-accounts', key: 'storage' } as const, null)
61const cleanupDays = atom({ plugin: 'sc-accounts', key: 'cleanupDays' } as const, 30)
62/** What each codex agent has passed to Codex, was spawned with, set by its commands, and last ran with. */
63const codexSent = atom({ plugin: 'sc-accounts', key: 'codexSent' } as const, {})
64const codexOpenings = atom({ plugin: 'sc-accounts', key: 'codexOpenings' } as const, {})
65const codexOptions = atom({ plugin: 'sc-accounts', key: 'codexOptions' } as const, {})
66const codexRuns = atom({ plugin: 'sc-accounts', key: 'codexRuns' } as const, {})
67/** The Codex account this session's Codex uses, for the Accounts tab's Codex card. */
68const codexAccount = atom({ plugin: 'sc-accounts', key: 'codexAccount' } as const, null)
69/** The toolbox's counts for its band cell; all zero when the toolbox is not installed. */
70const toolboxSummary = atom({ plugin: 'sc-toolbox', key: 'summary' } as const, { running: 0, waiting: 0, failed: 0 })
71
72const PANE = 'account-switch'
73/** The pane's label on the engine's tab row, shown while another pane is open beside it. */
74const TAB_LABEL = 'Accounts'
75/** The plugin's name, as `ui.press` names the plugin that drew a pressed Button. */
76const PLUGIN = 'sc-accounts'
77/** The plugin `sc` declares /sc:accounts in `commands/accounts.md`; this hook answers it. */
78const COMMAND = 'sc:accounts'
79/** The band cell that toggles the accounts pane: the Button holding the session account's name. */
80const BAND_ACCOUNT = 'band-account'
81/** The `/config` row of the plugin's `showStatusBand` setting. */
82const BAND_SETTING = 'sc-accounts.showStatusBand'
83/** Every session wakes this often: to adopt a new login, and to share or take the automatic lookup. */
84const TICK_MS = 60 * 1000
85/** How often the session's status is read: the model, effort, branch, task and the rest the band shows. */
86const STATUS_POLL_MS = 2000
87/** How often the open pane redraws, so each account's "updated N min ago" is at most this late. */
88const PANE_TICK_MS = 10 * 1000
89/** How long after a /clear ends the old session the new one is taken up, once the engine has switched ids. */
90const CLEAR_SETTLE_MS = 300
91/** The largest file whose edit is counted; `$.fs.read` refuses bigger ones. */
92const MAX_COUNTED_FILE = 4 * 1024 * 1024
93
94/** The display language, settled at every session start (a reload starts one). */
95let locale: Locale = 'en'
96let m: Messages = messagesFor(locale)
97/** This build's version and release date, read from the plugin's own files at session start. */
98let release: RunningRelease = {}
99/** When this session's current model turn began; 0 before the first. */
100let turnStartedAt = 0
101let sessionId = ''
102let homePath = ''
103let hostname: string | null = null
104let engineVersion: string | null = null
105/** The effort of each loop's latest request, by agent id; '' is the main loop. */
106const requestEfforts = new Map<string, string>()
107
108function debugLog($: EngineInterface, error: unknown): void {
109  $.ui.log(`account-switch: ${message(error)}`, { to: 'debug' })
110}
111
112// ── what the modules reach the machine and the session through ─────────────
113
114/** One environment variable the modules read, each by its literal name, as the engine lists them. */
115function variable($: EngineInterface, name: EnvName): Promise<string | undefined> {
116  switch (name) {
117    case 'OS':
118      return $.env.get('OS')
119    case 'HOME':
120      return $.env.get('HOME')
121    case 'USERPROFILE':
122      return $.env.get('USERPROFILE')
123    case 'USER':
124      return $.env.get('USER')
125    case 'CLAUDE_CONFIG_DIR':
126      return $.env.get('CLAUDE_CONFIG_DIR')
127    case 'CLAUDE_SECURESTORAGE_CONFIG_DIR':
128      return $.env.get('CLAUDE_SECURESTORAGE_CONFIG_DIR')
129    case 'ORCA_USER_DATA_PATH':
130      return $.env.get('ORCA_USER_DATA_PATH')
131    case 'XDG_CONFIG_HOME':
132      return $.env.get('XDG_CONFIG_HOME')
133    case 'APPDATA':
134      return $.env.get('APPDATA')
135    case 'CODEX_HOME':
136      return $.env.get('CODEX_HOME')
137    case 'CLAUDE_CODE_ACCOUNT_UUID':
138      return $.env.get('CLAUDE_CODE_ACCOUNT_UUID')
139    case 'CLAUDE_CODE_USER_EMAIL':
140      return $.env.get('CLAUDE_CODE_USER_EMAIL')
141  }
142}
143
144function machine($: EngineInterface): Io {
145  return {
146    run: (argv, init) => $.process.run(argv, init),
147    read: path => $.fs.read(path),
148    write: (path, text) => $.fs.write(path, text),
149    exists: path => $.fs.exists(path),
150    stat: path => $.fs.stat(path),
151    list: path => $.fs.list(path),
152    env: name => variable($, name),
153    now: () => $.clock.now(),
154    sleep: ms => $.clock.sleep(ms),
155    after: (ms, fn) => {
156      const timer = $.clock.after(ms, fn)
157
158      return () => timer.cancel()
159    },
160    fetch: (url, init) => $.http.fetch(url, init),
161    store: {
162      get: key => $.store.get(key),
163      set: async (key, value) => {
164        await $.store.set(key, value)
165      },
166      delete: async key => {
167        await $.store.delete(key)
168      },
169      keys: () => $.store.keys(),
170    },
171    log: text => $.ui.log(`account-switch: ${text}`, { to: 'debug' }),
172  }
173}
174
175/** Each agent's type by id, as the engine listed it: an agent's type never changes, so the band asks once per agent. */
176const agentTypes = new Map<string, string>()
177
178/** When an agent a view showed was last missing from the engine's list, by id. */
179const missedAgents = new Map<string, number>()
180/** How long the band takes a missing agent (a finished one the engine dropped) as missing before asking again. */
181const AGENT_MISS_MS = 10_000
182
183/**
184 * The type of the agent whose view the band draws: asked once per agent, and
185 * a missing one at most every `AGENT_MISS_MS`. A list that cannot be read
186 * leaves the band as it is, with no codex reply.
187 */
188async function viewedAgentType($: EngineInterface, id: string): Promise<string | undefined> {
189  const known = agentTypes.get(id)
190  if (known !== undefined) return known
191  const missedAt = missedAgents.get(id)
192  if (missedAt !== undefined && (await $.clock.now()) - missedAt < AGENT_MISS_MS) return undefined
193  const type = await codexContext($)
194    .agentType(id)
195    .catch(() => undefined)
196  if (type === undefined) missedAgents.set(id, await $.clock.now())
197  else missedAgents.delete(id)
198
199  return type
200}
201
202function codexContext($: EngineInterface): CodexContext {
203  return {
204    agentType: async id => {
205      const known = agentTypes.get(id)
206      if (known !== undefined) return known
207      const type = (await $.agent.list()).find(agent => agent.id === id)?.type
208      if (type !== undefined) agentTypes.set(id, type)
209
210      return type
211    },
212    messages: async agentId => {
213      const api = await $.session.messages({ as: 'api', agentId })
214      if ('deny' in api) throw new Error(api.deny)
215
216      return api
217    },
218    cwd: () => $.session.cwd(),
219    host: { spawn: request => $.process.spawn(request), write: (path, text) => $.fs.write(path, text), stat: path => $.fs.stat(path) },
220    read: path => $.fs.read(path),
221    note: async (agentId, text) => {
222      await $.session.append({ agentId, message: { type: 'system', content: [{ type: 'text', text }] } })
223    },
224    invalidate: () => $.ui.invalidate('ui.render'),
225    sent: { get: () => read($, codexSent), update: async change => void (await update($, codexSent, change)) },
226    openings: { get: () => read($, codexOpenings), update: async change => void (await update($, codexOpenings, change)) },
227    options: { get: () => read($, codexOptions), update: async change => void (await update($, codexOptions, change)) },
228    runs: { get: () => read($, codexRuns), update: async change => void (await update($, codexRuns, change)) },
229  }
230}
231
232function accountsContext($: EngineInterface): AccountsContext {
233  return {
234    io: machine($),
235    accounts: { get: () => read($, accounts), set: async list => void (await update($, accounts, () => list)) },
236    live: { get: () => read($, live), set: async uuid => void (await update($, live, () => uuid)) },
237    usage: { get: () => read($, usage), update: async change => void (await update($, usage, change)) },
238    isRefreshing: { get: () => read($, isRefreshing), set: async value => void (await update($, isRefreshing, () => value)) },
239    toast: text => $.ui.toast(text),
240    messages: () => m,
241    session: { id: () => sessionId, cwd: () => $.session.cwd(), version: () => release.version ?? '' },
242  }
243}
244
245function countContext($: EngineInterface): CountContext {
246  return {
247    io: machine($),
248    messages: () => m,
249    usagePeriod: () => read($, usagePeriod),
250    usageSummary: async summary => void (await update($, usageSummary, () => summary)),
251    usageScan: async scan => void (await update($, usageScan, () => scan)),
252    usageError: { get: () => read($, usageError), set: async error => void (await update($, usageError, () => error)) },
253    isUsageShown: async () => (await $.ui.panes()).some(pane => pane.id === PANE) && (await read($, tab)) === 'usage',
254  }
255}
256
257function cleanupContext($: EngineInterface): CleanupContext {
258  return {
259    io: machine($),
260    count: countContext($),
261    storage: async view => void (await update($, storage, () => view)),
262    cleanupDays: () => read($, cleanupDays),
263    sessionId: () => $.session.id(),
264    autoCleanupDays: async () => {
265      const { cleanupPeriodDays } = (await $.settings.read()) as { cleanupPeriodDays?: unknown }
266
267      return typeof cleanupPeriodDays === 'number' ? cleanupPeriodDays : undefined
268    },
269    homePath: () => homePath,
270  }
271}
272
273function feedContext($: EngineInterface): FeedContext {
274  return {
275    io: machine($),
276    messages: () => m,
277    webhookLast: async last => void (await update($, webhookLast, () => last)),
278    liveFigures: async () => {
279      const liveUuid = await read($, live)
280
281      return {
282        email: (await read($, accounts)).find(one => one.uuid === liveUuid)?.email ?? null,
283        limits: liveUuid ? ((await read($, usage))[liveUuid]?.limits ?? []) : [],
284      }
285    },
286    session: { id: () => sessionId, hostname: () => hostname, version: () => engineVersion },
287  }
288}
289
290function statusContext($: EngineInterface): StatusContext {
291  return {
292    accounts: accountsContext($),
293    feed: feedContext($),
294    cwd: () => $.session.cwd(),
295    model: () => $.session.model(),
296    usage: () => $.session.usage(),
297    settings: async () => (await $.settings.read()) as { fastMode?: unknown },
298    settingsOf: async source => (await $.settings.read({ source })) as EffortSettings,
299    status: { get: () => read($, statusInfo), set: async next => void (await update($, statusInfo, () => next)) },
300    sessionEffort: { get: () => read($, sessionEffort), set: async next => void (await update($, sessionEffort, () => next)) },
301    turnStartedAt: () => turnStartedAt,
302  }
303}
304
305function codexAccountContext($: EngineInterface): CodexAccountContext {
306  return {
307    io: machine($),
308    host: { spawn: request => $.process.spawn(request), write: (path, text) => $.fs.write(path, text), stat: path => $.fs.stat(path) },
309    cwd: () => $.session.cwd(),
310    cell: { get: () => read($, codexAccount), set: async value => void (await update($, codexAccount, () => value)) },
311    messages: () => m,
312  }
313}
314
315function paneContext($: EngineInterface): PaneContext {
316  const cell = <T,>(get: () => Promise<T>, set: (value: T) => Promise<unknown>): Cell<T> => ({ get, set: async value => void (await set(value)) })
317
318  return {
319    accounts: accountsContext($),
320    count: countContext($),
321    cleanup: cleanupContext($),
322    feed: feedContext($),
323    status: statusContext($),
324    codex: codexAccountContext($),
325    cells: {
326      dialog: cell(() => read($, dialog), value => update($, dialog, () => value)),
327      focused: cell(() => read($, focused), value => update($, focused, () => value)),
328      tab: cell(() => read($, tab), value => update($, tab, () => value)),
329      paneOpen: cell(() => read($, paneOpen), value => update($, paneOpen, () => value)),
330      isGuideOpen: cell(() => read($, isGuideOpen), value => update($, isGuideOpen, () => value)),
331      webhookDraft: cell(() => read($, webhookDraft), value => update($, webhookDraft, () => value)),
332      webhookLast: cell(() => read($, webhookLast), value => update($, webhookLast, () => value)),
333      usagePeriod: cell(() => read($, usagePeriod), value => update($, usagePeriod, () => value)),
334      usageSummary: cell(() => read($, usageSummary), value => update($, usageSummary, () => value)),
335      usageScan: cell(() => read($, usageScan), value => update($, usageScan, () => value)),
336      usageError: cell(() => read($, usageError), value => update($, usageError, () => value)),
337      storage: cell(() => read($, storage), value => update($, storage, () => value)),
338      cleanupDays: cell(() => read($, cleanupDays), value => update($, cleanupDays, () => value)),
339      tick: cell(() => read($, tick), value => update($, tick, () => value)),
340      statusInfo: cell(() => read($, statusInfo), value => update($, statusInfo, () => value)),
341    },
342    ui: {
343      open: async (rows, focus) => {
344        await $.ui.open({ id: PANE, title: TAB_LABEL, rows, ...(focus ? { focus: true, closeOnEscape: true } : {}) })
345      },
346      close: async () => {
347        await $.ui.close({ id: PANE })
348      },
349      pane: async () => (await $.ui.panes()).find(pane => pane.id === PANE),
350      toast: text => $.ui.toast(text),
351      runCommand: (command, args) => $.command.run({ command, args }),
352      isUnderTabs: async () =>
353        isBesideOtherPanes('sc-accounts', {
354          'sc-accounts': (await $.state.get({ plugin: 'sc-accounts', key: 'paneOpen' })).value === true,
355          'sc-workspace': (await $.state.get({ plugin: 'sc-workspace', key: 'paneOpen' })).value === true,
356          'sc-toolbox': (await $.state.get({ plugin: 'sc-toolbox', key: 'paneOpen' })).value === true,
357        }),
358    },
359    session: { model: () => $.session.model(), cwd: () => $.session.cwd(), cost: async () => (await $.session.usage()).cost?.usd ?? null },
360    view: { locale: () => locale, messages: () => m, release: () => release, homePath: () => homePath },
361  }
362}
363
364// ── the session ────────────────────────────────────────────────────────────
365
366/** The version `plugin.json` states and the date `CHANGELOG.md` gives that version. */
367async function readRelease($: EngineInterface): Promise<RunningRelease> {
368  try {
369    const manifest = JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)) as { version?: string; repository?: string }
370    if (typeof manifest.version !== 'string') return {}
371    const changelogPath = `${$.plugin.root}/CHANGELOG.md`
372    const changelog = (await $.fs.exists(changelogPath)) ? await $.fs.read(changelogPath) : ''
373
374    return { version: manifest.version, date: releaseDateOf(changelog, manifest.version), repository: manifest.repository }
375  } catch (error) {
376    $.ui.log(`account-switch: cannot read the release: ${message(error)}`, { to: 'debug' })
377
378    return {}
379  }
380}
381
382/** Hears of the latest published release, so the pane header says when an update is due. */
383async function followLatestRelease($: EngineInterface): Promise<void> {
384  const url = latestReleaseUrl(release.repository)
385  if (url === null) return
386  const latest = await latestVersion(
387    {
388      now: () => $.clock.now(),
389      get: () => $.store.get(LATEST_RELEASE_KEY),
390      set: value => $.store.set(LATEST_RELEASE_KEY, value),
391      fetch: (target, init) => $.http.fetch(target, init),
392    },
393    url,
394  )
395  release = { ...release, latest }
396}
397
398/** A file's text, or null when it is missing or too big to read. */
399async function readSmallFile($: EngineInterface, path: string): Promise<string | null> {
400  if (!(await $.fs.exists(path))) return null
401  const { size } = await $.fs.stat(path)
402
403  return size > MAX_COUNTED_FILE ? null : $.fs.read(path)
404}
405
406/** The label for a spawn, from the agent file its type names where it is not built in or a fork. */
407async function spawnLabel($: EngineInterface, e: AgentSpawnInput): Promise<string | undefined> {
408  if (e.subagentType.includes(':')) return undefined
409  const isBuiltIn = e.provider.plugin === 'engine'
410  const definition = e.fork || isBuiltIn ? undefined : await agentDefinitionNamed(machine($), await $.session.root(), e.subagentType, e.provider.plugin)
411  const parentEffort = requestEfforts.get(e.parentAgentId ?? '')
412
413  return agentLabel({ type: e.subagentType, model: e.model, fork: e.fork, isBuiltIn, parentModel: e.parentModel, parentEffort }, definition)
414}
415
416/** The accounts' part of a session's start: the language, the release, the status and the timers. */
417async function startAccounts($: EngineInterface): Promise<void> {
418  const { language } = await $.settings.read()
419  const localeVariables = [await $.env.get('LC_ALL'), await $.env.get('LC_MESSAGES'), await $.env.get('LANG')]
420  locale = resolveLocale(language, localeVariables)
421  m = messagesFor(locale)
422  release = await readRelease($)
423  // A later published release turns the header's date into Update Required: asked now and every few hours.
424  void followLatestRelease($).catch((error: unknown) => debugLog($, error))
425  $.clock.every(RELEASE_CHECK_MS, () => {
426    void followLatestRelease($).catch((error: unknown) => debugLog($, error))
427  })
428  $.ui.status(undefined)
429  // Readings no lookup produced (a figure copied from another login, a message an older build kept) go.
430  await $.store.set(USAGE_KEY, lookedUpOnly(await $.store.get(USAGE_KEY)))
431  const io = machine($)
432  homePath = await homeDirectory(io)
433  engineVersion = (await $.session.version()).version
434  const host = await $.process.run(['hostname'], { timeoutMs: 2000 })
435  hostname = host.exitCode === 0 ? host.stdout.trim() : null
436  // The session's status: read every two seconds from the engine, git, gh and the transcript.
437  startStatus(
438    {
439      run: (argv, init) => $.process.run(argv, init),
440      read: async path => ((await $.fs.exists(path)) ? $.fs.read(path) : null),
441      list: async path => ((await $.fs.exists(path)) ? $.fs.list(path) : []),
442      size: async path => ((await $.fs.exists(path)) ? (await $.fs.stat(path)).size : null),
443    },
444    { configPath: await claudeDirectory(io), sessionRoot: await $.session.root() },
445  )
446  sessionId = await $.session.id()
447  await adoptSession(paneContext($), sessionId, false)
448  $.clock.every(STATUS_POLL_MS, () => {
449    void collectStatus(statusContext($)).catch((error: unknown) => debugLog($, error))
450  })
451  $.clock.every(PANE_TICK_MS, () => {
452    void (async () => {
453      const pane = paneContext($)
454      if (!(await syncPaneOpen(pane))) return
455      const now = await $.clock.now()
456      await update($, tick, () => now)
457      // The Codex card is looked up while the pane is open, at most every five minutes.
458      await refreshCodexAccount(pane.codex, false)
459    })().catch((error: unknown) => debugLog($, error))
460  })
461  $.clock.every(TICK_MS, () => {
462    const pane = paneContext($)
463    const ctx = pane.accounts
464    void syncLive(ctx)
465      .catch((error: unknown) => debugLog($, error))
466      .then(() => tickOrca(ctx))
467      // Orca writes a copy as it is while a Claude terminal runs in it: each is kept from expiring.
468      .then(claude => (claude ? keepOrcaCopiesFresh(ctx, claude) : undefined))
469      .catch((error: unknown) => debugLog($, error))
470      .then(() => refresh(pane, false))
471      // The live account is kept current between Claude Code's own readings too.
472      .then(() => pollLive(ctx))
473      .catch((error: unknown) => debugLog($, error))
474  })
475}
476
477/** Codex as subagent types, and the commands of a codex agent's view, where the Codex CLI runs. */
478async function offerCodex($: EngineInterface): Promise<void> {
479  const io = machine($)
480  if (!(await codexInstalled(io))) return
481  // The Accounts tab draws a Codex card from now on; a reload keeps the one it has.
482  if ((await read($, codexAccount)) === null) await update($, codexAccount, () => ({ lookedAt: 0 }))
483  for (const spec of codexAgentSpecs(await codexModels(io))) await $.agent.register(spec)
484  for (const spec of codexCommandSpecs(m)) await $.command.register(spec)
485}
486
487// ── hooks ─────────────────────────────────────────────────────────────────
488
489export const register: Register = (on, options) => {
490  // The `showStatusBand` setting; a change in /config reloads the module with the new value.
491  const isBandShown = options.showStatusBand !== false
492
493  on('session.start', async ($, e, next) => {
494    const starting = startAccounts($)
495    // Codex is offered once the language is settled, beside the start rather than inside it:
496    // it never holds the start up, and a start that fails, which the engine reports, still offers it.
497    void starting
498      .catch(() => undefined)
499      .then(() => offerCodex($))
500      .catch((error: unknown) => debugLog($, error))
501    await starting
502
503    return next(e)
504  })
505
506  // A /clear goes on in this process under a new session id, and no session.start fires for
507  // it: the new session's state is filled here, once the old one has ended.
508  on('session.end', async ($, e, next) => {
509    // A Codex turn left waiting on a question ends with the session.
510    closeHeldCodex()
511    const result = await next(e)
512    if (e.reason === 'clear') {
513      $.clock.after(CLEAR_SETTLE_MS, () => {
514        void (async () => {
515          sessionId = await $.session.id()
516          await adoptSession(paneContext($), sessionId, true)
517        })().catch((error: unknown) => debugLog($, error))
518        // The emptied state drops the Codex card; registering again keeps the codex agents and
519        // commands whatever /clear did to the session's. Apart, so a failed adoption keeps Codex.
520        void offerCodex($).catch((error: unknown) => debugLog($, error))
521      })
522    }
523
524    return result
525  })
526
527  on('turn.start', async ($, e, next) => {
528    turnStartedAt = await $.clock.now()
529
530    return next(e)
531  })
532
533  // The effort each main-loop request asks for, as the engine settled it (a subagent's are its own).
534  // Every loop's latest effort is kept for the agents it spawns.
535  on('turn.step', async function* ($, e, next) {
536    if (e.effort === undefined) requestEfforts.delete(e.agentId ?? '')
537    else requestEfforts.set(e.agentId ?? '', String(e.effort))
538    if (!e.agentId) await noteRequestEffort(statusContext($), e.effort).catch((error: unknown) => debugLog($, error))
539
540    // A codex agent's model request is answered by driving `codex app-server`; any other goes on.
541    return yield* codexStep(codexContext($), e, next)
542  })
543
544  // A Claude subagent's model and effort after its task in the agent list: ` · Opus 5.5 (high)`.
545  // The label is decoration: the agent starts whether or not it can be made.
546  on('agent.spawn', async ($, e, next) => {
547    const codex = CODEX_TYPES[e.subagentType]
548    if (codex) {
549      // A codex agent keeps the stand-in's Claude model, so a run this module does not
550      // answer reaches one the Anthropic API serves; its row names Codex's model.
551      // The label is decoration, as for a Claude agent: Codex's config unread, the row goes without one.
552      const flags = codexFlagsOf(e.prompt, codex.pin)
553      const config = await codexConfig(machine($)).catch((error: unknown) => {
554        debugLog($, error)
555
556        return undefined
557      })
558      const label = config ? codexLabel(config, 'error' in flags ? {} : flags) : undefined
559      const started = await next(label ? { ...e, description: `${e.description} · ${label}` } : e)
560      const agentId = started.agentId
561      // The spawn prompt carries the agent's options, wherever the engine later places it.
562      if (agentId) await update($, codexOpenings, all => ({ ...all, [agentId]: e.prompt }))
563
564      return started
565    }
566    const label = await spawnLabel($, e).catch((error: unknown) => {
567      debugLog($, error)
568
569      return undefined
570    })
571
572    return next(label ? { ...e, description: `${e.description} · ${label}` } : e)
573  })
574
575  // A /codex- command acts on the codex agent whose view is open and answers in its band.
576  on('command.run', async ($, e, next) => {
577    if (!isOwnCodexCommand(e.command)) return next(e)
578
579    return (await codexCommand(codexContext($), e.command, e.args)) ? {} : { text: m.codexOpenView(e.command) }
580  })
581
582  // A message sent to a codex agent while Codex works joins Codex's running turn, so Codex
583  // reads it now; the agent is not also sent it, which would start another Codex turn.
584  on('session.send', async ($, e, next) => {
585    const agent = (await $.agent.list()).find(one => one.id === e.to || one.name === e.to)
586    if (!agent || !CODEX_TYPES[agent.type] || isCodexCommand(e.text)) return next(e)
587
588    return (await steerCodex(agent.id, e.text)) ? { isDelivered: true } : next(e)
589  })
590
591  // The transcript's Agent row names a codex type in words, not `sc-accounts:codex-read`.
592  on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
593    const input = e.props.input as { subagent_type?: unknown } | undefined
594    const type = e.props.tool === 'Agent' && typeof input?.subagent_type === 'string' ? CODEX_TYPES[input.subagent_type] : undefined
595    if (!type) return next(e)
596
597    return next({ ...e, props: { ...e.props, input: { ...input, subagent_type: type.shown } } })
598  })
599
600  // In a codex agent's view the footer names its commands and the "/" menu lists them alone:
601  // Claude Code's own act on the main session rather than the agent. Elsewhere they are left out.
602  on('ui.render', { component: 'PromptHint' }, async ($, e, next) =>
603    openCodexView(e.surface) ? next({ ...e, props: { ...e.props, tail: e.props.tail ? `${e.props.tail} · ${CODEX_HINT}` : CODEX_HINT } }) : next(e),
604  )
605  on('command.describe', async ($, e, next) => (Boolean(openCodexView()) !== isOwnCodexCommand(e.command) ? next({ ...e, isHidden: true }) : next(e)))
606
607  // This session's `/effort`: the level it names shows at once, a default picked from its list once saved.
608  on('command.run', { command: 'effort' }, async ($, e, next) => {
609    const userBefore = (await $.settings.read({ source: 'user' })) as EffortSettings
610    const result = await next(e)
611    await noteEffortCommand(statusContext($), e.args, userBefore).catch((error: unknown) => debugLog($, error))
612
613    return result
614  })
615
616  // Lines a file-changing tool call adds and removes: the file before and after, compared.
617  // A failure here never stands in the tool call's way: the call goes on, run once.
618  on('tool.call', async ($, e, next) => {
619    const path = editedPath(String(e.tool), e)
620    if (path === null) return next(e)
621    const before = await readSmallFile($, path).catch(() => undefined)
622    const result = await next(e)
623    if (before !== undefined && !('deny' in result) && !(result as { isError?: boolean }).isError) {
624      const after = await readSmallFile($, path).catch(() => undefined)
625      if (after !== undefined) await countLines(statusContext($), lineChanges(before, after)).catch((error: unknown) => debugLog($, error))
626    }
627
628    return result
629  }).catch(($, e, next) => next(e))
630
631  // Claude Code's own response reported its windows: filed under the live account when they are its.
632  on('session.measure', async ($, e, next) => {
633    await adoptMeasured(accountsContext($), e.rateLimits, turnStartedAt).catch((error: unknown) => debugLog($, error))
634
635    return next(e)
636  })
637
638  on('command.run', { command: COMMAND }, async ($, e) => ({
639    text: await answerCommand(paneContext($), e.args, {
640      isFullscreen: e.presentation?.isFullscreen,
641      setBand: async isShown => (await $.config.set({ key: BAND_SETTING, value: isShown })).deny,
642    }),
643  }))
644
645  // The status on the band above the prompt, left-aligned under a dim rule: the
646  // model, effort, fast mode and task, the live account, the context and usage
647  // gauges, the place and PR, and the lines changed. Cells move to a new row
648  // when the band is too narrow.
649  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
650    // The band is drawn for the view on screen: in a codex agent's, the reply to the last
651    // /codex- command run there shows over it.
652    const viewed = e.props.view?.agentId
653    const viewedType = viewed === undefined ? undefined : await viewedAgentType($, viewed)
654    if (setOpenCodexView(e.surface, viewedType && CODEX_TYPES[viewedType] ? viewed : undefined)) {
655      $.ui.invalidate('ui.render')
656      $.ui.invalidate('command.describe')
657    }
658    const codexView = openCodexView(e.surface)
659    const reply = codexView === undefined ? undefined : codexReplyIn(codexView)
660    // A band that cannot be drawn leaves the engine's own, under the reply all the same.
661    const band = await (async () => {
662      if (e.props.hasSurvey || !isBandShown) return next(e)
663      const status = await read($, statusInfo)
664      // The account this session's requests go out under: the app's own where the app runs it.
665      const host = await hostAccount(machine($))
666      const sessionUuid = host?.uuid ?? (await read($, live))
667      const account =
668        (await read($, accounts)).find(one => one.uuid === sessionUuid) ?? (host?.email ? { uuid: host.uuid, email: host.email, savedAt: 0 } : undefined)
669      const reading = sessionUuid ? (await read($, usage))[sessionUuid] : undefined
670      const windows = (reading?.limits ?? []).filter(limit => limit.label === '5h' || limit.label === 'wk')
671      const contextUsed = (await $.session.usage()).context.percent ?? status?.contextUsed ?? null
672      if (!status && contextUsed === null && (!account || windows.length === 0)) return next(e)
673
674      return StatusBand(surfaceTable($.ui.resolve(e), e.surface), {
675        status,
676        account,
677        reading,
678        windows,
679        contextUsed,
680        now: await $.clock.now(),
681        locale,
682        room: Math.max(20, e.props.bodyColumns),
683        toolbox: toolboxCell(await read($, toolboxSummary)),
684        // The ui.press hook below takes the account, and the workspace's the place and the lines;
685        // this runs for a press neither took (the workspace without its hook).
686        onPress: target => {
687          void toggle(paneContext($), target).catch((error: unknown) => $.ui.toast(message(error)))
688        },
689      })
690    })().catch((error: unknown) => {
691      // Without a reply to show, the failure is the engine's to report, as it always was.
692      if (!reply) throw error
693      debugLog($, error)
694
695      return next(e)
696    })
697
698    return reply ? CodexReplyBand(surfaceTable($.ui.resolve(e), e.surface), reply, band) : band
699  })
700
701  // A band press is taken here, inside the person's press, and toggled before the chain
702  // settles: a pane opened there counts as asked for and is placed at any width.
703  on('ui.press', async ($, e, next) => {
704    if (e.plugin !== PLUGIN || e.component !== 'AbovePrompt' || e.element !== BAND_ACCOUNT) return next(e)
705    await toggle(paneContext($), 'accounts')
706
707    return { element: e.element }
708  })
709
710  // Where the keyboard is in the pane, so the dialog's outlined tiles can show it.
711  on('ui.focus', async ($, e, next) => {
712    const result = await next(e)
713    if (e.requestId === PANE) await update($, focused, () => e.element ?? null)
714
715    return result
716  }).catch(($, e, next) => next(e))
717
718  // Esc (or the close mark) while the dialog asks cancels the dialog and keeps the pane.
719  on('ui.close', async ($, e, next) => {
720    if (e.id === PANE && e.origin.kind === 'person' && (await read($, dialog)) !== null) {
721      const wasWebhook = (await read($, dialog))?.kind === 'webhook'
722      await update($, dialog, () => null)
723      await update($, focused, () => null)
724      if (wasWebhook) await openPane(paneContext($), true)
725
726      return { value: undefined }
727    }
728    const result = await next(e)
729    if (e.id === PANE && (await read($, paneOpen))) await update($, paneOpen, () => false)
730
731    return result
732  }).catch(($, e, next) => next(e))
733
734  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
735    const pane = paneContext($)
736
737    return AccountsPane(surfaceTable($.ui.resolve(e), e.surface), await paneModel(pane, e.props.bodyColumns ?? 60, e.surface !== 'mobile'), paneActions(pane))
738  })
739}
740
hooks/accounts.ts 441 lines
1import type { AccountView, UsageView } from '../types'
2import { PROFILE_URL, mayHeal, parseProfile, usageInit } from './anthropic'
3import {
4  claudeDirectory,
5  keepCredentialFileInStep,
6  liveCredentialPath,
7  liveOauthAccount,
8  platformOf,
9  readLiveCredential,
10  readVault,
11  writeLiveFile,
12  writeLiveKeychain,
13  writeVault,
14} from './credentials'
15import type { OauthAccount } from './credentials'
16import type { Messages } from './i18n'
17import type { Cell, Io } from './io'
18import { message, within } from './io'
19import { isOlderGrant } from './keychain'
20import type { Credential } from './keychain'
21import { withLock } from './lock'
22import { pendingStep, planFollow } from './orca'
23import type { OrcaClaude } from './orca'
24import { isOrcaCheckDue, orcaClaude, orcaSelect, returnPending, takePending } from './orcaClient'
25import { serialQueue } from './queue'
26import { isOwnSwitch, parseChanges, withChange } from './switchlog'
27import type { LoginChange } from './switchlog'
28import { writeAtomic } from './writes'
29
30/**
31 * The saved accounts and the login Claude Code uses: reading the live login
32 * and filing it, putting a rejected login back, and saying who changed the
33 * login, Orca included; switching and removing are in `switching.ts`. What the
34 * session's state holds
35 * is reached through the context the hooks module builds.
36 */
37
38/** What the account work reads and writes beyond the machine: the session's state, its toasts and its words. */
39export type AccountsContext = {
40  io: Io
41  accounts: Cell<AccountView[]>
42  live: Cell<string | null>
43  usage: { get: () => Promise<Record<string, UsageView>>; update: (change: (map: Record<string, UsageView>) => Record<string, UsageView>) => Promise<void> }
44  isRefreshing: Cell<boolean>
45  toast: (text: string) => void
46  messages: () => Messages
47  session: { id: () => string; cwd: () => Promise<string>; version: () => string }
48}
49
50export const USAGE_KEY = 'usage'
51const INDEX_KEY = 'accounts'
52export const oauthAccountKey = (uuid: string) => `oauthAccount:${uuid}`
53/** The `$.store` key of the session selecting in Orca a login changed outside it, so the others leave it to that one. */
54const ORCA_FOLLOW_KEY = 'orcaFollow'
55const ORCA_FOLLOW_CLAIM_MS = 60 * 1000
56/** How long a change of the login stands before it is explained: Orca writes a login in steps over a few seconds, passing through another. */
57const SETTLE_MS = 10_000
58/** How long the profile endpoint may take to say whose a token is. */
59const PROFILE_TIMEOUT_MS = 15_000
60/** How long after putting a login back this session leaves a login rejected again alone, so two writers never loop. */
61const HEAL_GAP_MS = 60 * 1000
62/** How long Claude Code keeps a keychain login cached when no credentials file tells it of a change. */
63const KEYCHAIN_CACHE_MS = 35 * 1000
64/** This mod's lock over the change record, which every session writes. */
65const CHANGES_LOCK = { staleMs: 10_000, tries: 12 }
66
67/**
68 * A switch and each account's token work run one at a time in this session:
69 * a lookup refreshing an account's token while a switch makes it the live
70 * login would refresh it twice with one refresh token.
71 */
72export const exclusive = serialQueue()
73
74/** When this session last saw the live account change, by a switch or a login. */
75let liveChangedAt = 0
76/** Whose the live token is, as the last read found: a lookup of the live account checks the token it sends is still this one. */
77let liveOwner: { accessToken: string; uuid: string } | null = null
78/** The live account this session last said or took up: a change that settles back to it was a passing write, said to nobody. */
79let announcedLive: string | null = null
80/** The changes of the login this session has found, counted, so only the latest one's settling is explained. */
81let changeCount = 0
82let healedAt = 0
83/** The read of the live login in progress, which every caller meanwhile shares: two at once would file one token twice. */
84let syncing: Promise<string | null> | null = null
85
86/** Takes up a login this session wrote itself: a later change away from it, Orca's included, is one to explain. */
87export function noteInstalled(uuid: string, accessToken: string, at: number): void {
88  liveChangedAt = at
89  liveOwner = { accessToken, uuid }
90  announcedLive = uuid
91}
92
93export function lastLiveChange(): number {
94  return liveChangedAt
95}
96
97/**
98 * The account a host signed this session in with, when it did: the desktop
99 * app runs its Claude Code sessions on the app's own login and names it in
100 * `CLAUDE_CODE_ACCOUNT_UUID`, whatever Claude Code's login on this machine
101 * (the live account) is. Null where Claude Code signs itself in.
102 */
103export async function hostAccount(io: Io): Promise<{ uuid: string; email: string | null } | null> {
104  const uuid = (await io.env('CLAUDE_CODE_ACCOUNT_UUID'))?.trim() ?? ''
105  if (uuid === '') return null
106  const email = (await io.env('CLAUDE_CODE_USER_EMAIL'))?.trim() ?? ''
107
108  return { uuid, email: email === '' ? null : email }
109}
110
111/** The account this session's requests go out under: the host's, else the live account. */
112export async function sessionAccount(ctx: AccountsContext): Promise<string | null> {
113  return (await hostAccount(ctx.io))?.uuid ?? ctx.live.get()
114}
115
116/** Whether the live login is still the token the last read filed under `uuid`. */
117export function isLiveTokenOf(credential: Credential, uuid: string): boolean {
118  return liveOwner?.uuid === uuid && liveOwner.accessToken === credential.claudeAiOauth.accessToken
119}
120
121/** The organization of a login's details, as Orca matches accounts by it too; null when the details name none. */
122export function organizationOf(account: OauthAccount | undefined): string | null {
123  return typeof account?.organizationUuid === 'string' && account.organizationUuid !== '' ? account.organizationUuid : null
124}
125
126/**
127 * The saved accounts: the list the store holds, with every account it lost
128 * put back. An account is saved when both its details (`oauthAccount:<id>`)
129 * and its credential are kept, so a session running an older build that wrote
130 * back a shorter list cannot drop one; removing an account deletes both.
131 */
132async function storedIndex(ctx: AccountsContext): Promise<AccountView[]> {
133  const { io } = ctx
134  const stored = await io.store.get(INDEX_KEY)
135  const list = Array.isArray(stored) ? (stored as AccountView[]) : []
136  const listed = new Set(list.map(one => one.uuid))
137  const lost: AccountView[] = []
138  for (const key of await io.store.keys()) {
139    if (!key.startsWith('oauthAccount:')) continue
140    const uuid = key.slice('oauthAccount:'.length)
141    if (listed.has(uuid)) continue
142    const account = (await io.store.get(key)) as OauthAccount | undefined
143    const credential = account ? await readVault(io, uuid).catch(() => null) : null
144    if (!account || !credential) continue
145    lost.push({ uuid, email: account.emailAddress, organizationName: account.organizationName, subscriptionType: credential.claudeAiOauth.subscriptionType, savedAt: 0 })
146  }
147
148  return [...list, ...lost.sort((a, b) => a.email.localeCompare(b.email))]
149}
150
151/**
152 * Changes the saved accounts. The change is applied to the list the store
153 * holds now, never to this session's copy: a session that has not loaded the
154 * list yet, or holds an older one, would otherwise write back only the
155 * accounts it knows and drop the rest.
156 */
157export async function changeIndex(ctx: AccountsContext, change: (list: AccountView[]) => AccountView[]): Promise<AccountView[]> {
158  const list = change(await storedIndex(ctx))
159  await ctx.io.store.set(INDEX_KEY, list)
160  await ctx.accounts.set(list)
161
162  return list
163}
164
165export async function loadIndex(ctx: AccountsContext): Promise<void> {
166  await ctx.accounts.set(await storedIndex(ctx))
167}
168
169/** The ids of the accounts saved now, as the list every session shares holds them: one another session removed is not among them, whatever this session still shows. */
170export async function savedIds(ctx: AccountsContext): Promise<Set<string>> {
171  return new Set((await storedIndex(ctx)).map(one => one.uuid))
172}
173
174/**
175 * Whose login a token is, as the profile endpoint answers: the account;
176 * `rejected` when the token is empty or the endpoint refuses it (401, 403),
177 * so it can never work again; `unknown` when no answer came (offline, 5xx,
178 * no answer within its time).
179 */
180async function tokenCheck(ctx: AccountsContext, credential: Credential): Promise<OauthAccount | 'rejected' | 'unknown'> {
181  if (credential.claudeAiOauth.accessToken === '') return 'rejected'
182  try {
183    const response = await within(ctx.io, ctx.io.fetch(PROFILE_URL, usageInit({ token: credential.claudeAiOauth.accessToken })), PROFILE_TIMEOUT_MS, ctx.messages().profileNoAnswer(PROFILE_TIMEOUT_MS / 1000))
184    if (response.status === 401 || response.status === 403) return 'rejected'
185    if (!response.ok) return 'unknown'
186
187    return parseProfile(response.text)
188  } catch (error) {
189    ctx.io.log(message(error))
190
191    return 'unknown'
192  }
193}
194
195/**
196 * Reads the login Claude Code uses now and files it in the vault: a new
197 * account is added, a known one gets the credential Claude Code last
198 * refreshed. A copy older than the one saved for its account (another grant
199 * that expires sooner) is used but never filed over the newer one.
200 *
201 * @returns the live account's uuid, or null with no Claude login
202 */
203export async function syncLive(ctx: AccountsContext): Promise<string | null> {
204  syncing ??= syncLiveOnce(ctx).finally(() => {
205    syncing = null
206  })
207
208  return syncing
209}
210
211async function syncLiveOnce(ctx: AccountsContext): Promise<string | null> {
212  const { io } = ctx
213  const [configured, credential] = await Promise.all([liveOauthAccount(io), readLiveCredential(io)])
214  if (configured === null || credential === null) {
215    liveOwner = null
216    await ctx.live.set(null)
217
218    return null
219  }
220  await keepCredentialFileInStep(io, credential)
221
222  let account = configured
223  const stored = await readVault(io, configured.accountUuid)
224  if (JSON.stringify(stored) !== JSON.stringify(credential)) {
225    // The token changed: ask whose it is. During a login the config and the
226    // keychain can name different accounts for a moment, and filing a token
227    // under the wrong account would show one account's usage as another's.
228    const check = await tokenCheck(ctx, credential)
229    // Rejected: a login written into Claude Code that can never work again, its refresh token spent elsewhere.
230    if (check === 'rejected') return healLogin(ctx, configured, credential)
231    if (check === 'unknown') return ctx.live.get()
232    account = check.accountUuid === configured.accountUuid ? configured : (((await io.store.get(oauthAccountKey(check.accountUuid))) as OauthAccount | undefined) ?? check)
233    const saved = account.accountUuid === configured.accountUuid ? stored : await readVault(io, account.accountUuid)
234    if (!isOlderGrant(credential, saved)) await writeVault(io, account.accountUuid, credential)
235  }
236  liveOwner = { accessToken: credential.claudeAiOauth.accessToken, uuid: account.accountUuid }
237  const previous = await ctx.live.get()
238  if (previous !== account.accountUuid) {
239    liveChangedAt = await io.now()
240    if (previous !== null) await noteChange(ctx, previous, account)
241    else announcedLive ??= account.accountUuid
242  }
243  await ctx.live.set(account.accountUuid)
244  await io.store.set(oauthAccountKey(account.accountUuid), account)
245
246  const now = await io.now()
247  let isNew = false
248  await changeIndex(ctx, list => {
249    const known = list.find(one => one.uuid === account.accountUuid)
250    const view: AccountView = {
251      uuid: account.accountUuid,
252      email: account.emailAddress,
253      organizationName: account.organizationName,
254      subscriptionType: credential.claudeAiOauth.subscriptionType,
255      savedAt: known?.savedAt ?? now,
256    }
257    isNew = known === undefined
258
259    return known ? list.map(one => (one.uuid === view.uuid ? view : one)) : [...list, view]
260  })
261  if (isNew) ctx.toast(ctx.messages().saved(account.emailAddress))
262
263  return account.accountUuid
264}
265
266/**
267 * Puts the configured account's saved login back when the one Claude Code
268 * holds was rejected: a login written into Claude Code whose refresh token was
269 * already spent elsewhere. Only a saved login that works as it is: one that
270 * needs refreshing is left to /login, as several sessions refreshing it at
271 * once would spend it too.
272 *
273 * @returns the live account's uuid, or the one shown when nothing was put back
274 */
275async function healLogin(ctx: AccountsContext, configured: OauthAccount, rejected: Credential): Promise<string | null> {
276  const { io } = ctx
277  const now = await io.now()
278  const saved = await readVault(io, configured.accountUuid)
279  if (!mayHeal(saved, rejected, now, healedAt, HEAL_GAP_MS)) return ctx.live.get()
280  const check = await tokenCheck(ctx, saved)
281  if (typeof check === 'string' || check.accountUuid !== configured.accountUuid) return ctx.live.get()
282  healedAt = now
283  await recordChange(ctx, { kind: 'heal', from: null, to: configured.emailAddress })
284  await writeLiveKeychain(io, saved)
285  await writeLiveFile(io, saved)
286  liveChangedAt = now
287  liveOwner = { accessToken: saved.claudeAiOauth.accessToken, uuid: configured.accountUuid }
288  await ctx.live.set(configured.accountUuid)
289  ctx.toast(ctx.messages().loginHealed(configured.emailAddress))
290
291  return configured.accountUuid
292}
293
294/** The file that records every change of the live login, this mod's switches and the ones from outside it. */
295async function changesPath(io: Io): Promise<string> {
296  return `${await claudeDirectory(io)}/sc-accounts/login-changes.jsonl`
297}
298
299async function readChanges(io: Io): Promise<string> {
300  const path = await changesPath(io)
301
302  return (await io.exists(path)) ? io.read(path) : ''
303}
304
305/**
306 * Adds a change to the record. Every session writes it, so the record is read
307 * and written whole under a lock of its own, and replaced at once: a line
308 * written by another session at the same moment is never lost. A record that
309 * cannot be written never stops a switch.
310 */
311export async function recordChange(ctx: AccountsContext, change: Omit<LoginChange, 'at' | 'session' | 'cwd' | 'version'>): Promise<void> {
312  const { io } = ctx
313  try {
314    const full: LoginChange = { at: await io.now(), session: ctx.session.id(), cwd: await ctx.session.cwd(), version: ctx.session.version(), ...change }
315    const path = await changesPath(io)
316    const { isWindows } = await platformOf(io)
317    await withLock(io, `${path}.lock`, { ...CHANGES_LOCK, isWindows }, async () => {
318      await writeAtomic(io, path, withChange(await readChanges(io), full), { isPrivate: false, isWindows })
319    })
320  } catch (error) {
321    io.log(message(error))
322  }
323}
324
325/**
326 * A change of the live login this session found. A switch, heal or Orca
327 * selection of this mod's, in any session, says nothing; any other change is
328 * explained once the login has stood still for `SETTLE_MS`, so writes that pass
329 * through another login on their way back say nothing either.
330 */
331async function noteChange(ctx: AccountsContext, previousUuid: string, account: OauthAccount): Promise<void> {
332  announcedLive ??= previousUuid
333  if (isOwnSwitch(parseChanges(await readChanges(ctx.io)), account.emailAddress, await ctx.io.now())) {
334    announcedLive = account.accountUuid
335
336    return
337  }
338  changeCount += 1
339  const count = changeCount
340  ctx.io.after(SETTLE_MS, () => {
341    if (count === changeCount) void settleChange(ctx).catch((error: unknown) => ctx.io.log(message(error)))
342  })
343}
344
345/** Explains a change of the login once it has stood still: who made it, and what Orca does about it. */
346async function settleChange(ctx: AccountsContext): Promise<void> {
347  const count = changeCount
348  const liveUuid = await syncLive(ctx)
349  // Another change came meanwhile, and its own settling explains both; or the login is back where it was.
350  if (count !== changeCount || liveUuid === null || liveUuid === announcedLive) return
351  const from = (await ctx.accounts.get()).find(one => one.uuid === announcedLive)?.email ?? null
352  announcedLive = liveUuid
353  const account = (await ctx.io.store.get(oauthAccountKey(liveUuid))) as OauthAccount | undefined
354  if (!account || isOwnSwitch(parseChanges(await readChanges(ctx.io)), account.emailAddress, await ctx.io.now())) return
355  await explainChange(ctx, from, account)
356}
357
358/** Records and says who changed the login, and has Orca keep a login changed outside it rather than put its own back. */
359async function explainChange(ctx: AccountsContext, from: string | null, to: OauthAccount): Promise<void> {
360  const m = ctx.messages()
361  const reach = await orcaClaude(ctx.io, m)
362  const claude = reach.kind === 'ok' ? reach.claude : null
363  // Orca has just started and put back the login it wrote before, over the one a switch chose while it was closed.
364  if (claude && (await applyPendingOrca(ctx, claude))) return
365  const plan = planFollow(claude, to.emailAddress, organizationOf(to))
366  if (plan.kind === 'orca') {
367    await recordChange(ctx, { kind: 'orca', from, to: to.emailAddress })
368    ctx.toast(m.loginChangedByOrca(from ?? '?', to.emailAddress))
369
370    return
371  }
372  if (plan.kind === 'follow') {
373    // Another session found the same change a moment ago and is selecting it in Orca.
374    if (!(await claimFollow(ctx.io, to.emailAddress))) return
375    await recordChange(ctx, { kind: 'follow', from, to: to.emailAddress })
376    try {
377      await orcaSelect(ctx.io, m, plan.account.id)
378      ctx.toast(m.orcaFollowed(to.emailAddress))
379    } catch (error) {
380      ctx.toast(m.orcaFollowFailed(to.emailAddress, message(error)))
381    }
382
383    return
384  }
385  await recordChange(ctx, { kind: 'outside', from, to: to.emailAddress })
386  ctx.toast(plan.kind === 'revert' ? m.orcaWillRevert(to.emailAddress, plan.activeEmail ?? '?') : m.loginChangedOutside(from ?? '?', to.emailAddress))
387}
388
389/** Takes, for this session, selecting a login in Orca, unless another session took the same one within a minute. */
390async function claimFollow(io: Io, email: string): Promise<boolean> {
391  const now = await io.now()
392  const claim = (await io.store.get(ORCA_FOLLOW_KEY)) as { email?: unknown; at?: unknown } | undefined
393  if (claim?.email === email && typeof claim.at === 'number' && now - claim.at < ORCA_FOLLOW_CLAIM_MS) return false
394  await io.store.set(ORCA_FOLLOW_KEY, { email, at: now })
395
396  return true
397}
398
399/** Selects in Orca the account a switch chose while Orca was not running; true when it was asked to. */
400async function applyPendingOrca(ctx: AccountsContext, claude: OrcaClaude): Promise<boolean> {
401  const { io } = ctx
402  const pending = await takePending(io)
403  if (!pending || pendingStep(pending, claude, await io.now()) !== 'apply') return false
404  await recordChange(ctx, { kind: 'follow', from: claude.accounts.find(account => account.id === claude.activeId)?.email ?? null, to: pending.email })
405  try {
406    await orcaSelect(io, ctx.messages(), pending.accountId)
407    ctx.toast(ctx.messages().orcaAppliedPending(pending.email))
408  } catch (error) {
409    await returnPending(io, pending)
410    io.log(message(error))
411  }
412
413  return true
414}
415
416/**
417 * Keeps what Orca says current, machine-wide every few minutes, and makes a
418 * selection that waits for Orca once it answers.
419 *
420 * @returns what Orca said, when it was asked now and answered; null otherwise
421 */
422export async function tickOrca(ctx: AccountsContext): Promise<OrcaClaude | null> {
423  if (!(await isOrcaCheckDue(ctx.io))) return null
424  const reach = await orcaClaude(ctx.io, ctx.messages())
425  if (reach.kind !== 'ok') return null
426  await applyPendingOrca(ctx, reach.claude)
427
428  return reach.claude
429}
430
431/**
432 * From when a response's figures are the live account's: the moment it last
433 * changed, and on macOS without a credentials file, the keychain cache after
434 * it, during which a running session may still ask with the previous login.
435 */
436export async function figuresTrustedFrom(io: Io): Promise<number> {
437  const cached = (await platformOf(io)).backend === 'keychain' && !(await io.exists(await liveCredentialPath(io)))
438
439  return liveChangedAt + (cached ? KEYCHAIN_CACHE_MS : 0)
440}
441
hooks/agentModels.ts 96 lines
1/**
2 * Each Claude subagent's model and effort in Claude Code's agent list, as
3 * ` · Opus 5.5 (high)` after its task. The agent list shows the spawn's
4 * description, so the label is worked out before the subagent starts.
5 *
6 * Adapted from the agent-models plugin of alex2481kobe/claude-mods
7 * (https://github.com/alex2481kobe/claude-mods), Apache License 2.0; see
8 * THIRD_PARTY_NOTICES.md in this plugin.
9 */
10
11import { claudeDirectory } from './credentials'
12import type { Io } from './io'
13import { displayModel } from './status'
14
15/** An agent file's frontmatter, as far as the label needs it. */
16export type AgentDefinition = { name: string; model?: string; effort?: string }
17
18/** What the engine says of a spawn, and the effort of the parent's latest request. */
19export type AgentSpawn = {
20  type: string
21  /** The Agent tool's `model` parameter, when given. */
22  model?: string
23  fork: boolean
24  isBuiltIn: boolean
25  parentModel: string
26  /** The effort of the parent's latest request, when its model takes one. */
27  parentEffort?: string
28}
29
30/** Built-in types that run on the parent's model and effort. */
31const INHERITS = new Set(['general-purpose'])
32
33/** A YAML scalar as written on one line: a quoted value's inside, or a plain one without its ` # comment`. */
34function scalarOf(raw: string): string {
35  const quoted = /^(["'])(.*?)\1(?:\s+#.*)?$/.exec(raw)
36
37  return quoted ? (quoted[2] ?? '') : raw.replace(/\s+#.*$/, '')
38}
39
40/**
41 * The frontmatter of an agent file: its `name` (else the file's name), and
42 * `model` and `effort` when set. A file without frontmatter is no agent.
43 */
44export function agentDefinitionOf(text: string, fileName: string): AgentDefinition | undefined {
45  const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)
46  if (!match) return undefined
47  const fields: Record<string, string> = {}
48  for (const line of (match[1] ?? '').split(/\r?\n/)) {
49    const field = /^([A-Za-z]+):\s*(.*?)\s*$/.exec(line)
50    if (field?.[1] !== undefined) fields[field[1]] = scalarOf(field[2] ?? '')
51  }
52  const name = fields.name || fileName.replace(/\.md$/, '')
53
54  return { name, model: fields.model || undefined, effort: fields.effort || undefined }
55}
56
57/**
58 * The label for the agent list, e.g. `Opus 5.5 (high)`, or undefined when
59 * the model cannot be known before the agent starts. A plugin's type
60 * (`codex:read`) labels itself. The effort shows only where it is known to
61 * carry over: the definition sets it, or the agent runs on the parent's model.
62 */
63export function agentLabel(spawn: AgentSpawn, definition?: AgentDefinition): string | undefined {
64  if (spawn.type.includes(':')) return undefined
65  const chosen = spawn.fork ? undefined : (spawn.model ?? definition?.model)
66  const inherits = spawn.fork || chosen === 'inherit' || (!chosen && spawn.isBuiltIn && INHERITS.has(spawn.type))
67  // An alias of the parent's family (`opus` under Opus 5.5) is the parent's model.
68  const isParentAlias = chosen !== undefined && /^[a-z]+$/.test(chosen) && spawn.parentModel.startsWith(`claude-${chosen}-`)
69  const model = inherits || isParentAlias ? spawn.parentModel : chosen
70  if (!model) return undefined
71  const effort = definition?.effort ?? (model === spawn.parentModel ? spawn.parentEffort : undefined)
72
73  return effort ? `${displayModel(model)} (${effort})` : displayModel(model)
74}
75
76/**
77 * The agent file whose `name` is `type`: the project's `.claude/agents/`
78 * first, then the person's (`CLAUDE_CONFIG_DIR/agents`, else
79 * `~/.claude/agents`); only the person's for a user agent. A definition from
80 * anywhere else (settings, a flag, policy, a subfolder) is not read.
81 */
82export async function agentDefinitionNamed(io: Io, projectRoot: string, type: string, provider: string): Promise<AgentDefinition | undefined> {
83  const user = `${await claudeDirectory(io)}/agents`
84  const folders = provider === 'user' ? [user] : [`${projectRoot}/.claude/agents`, user]
85  for (const folder of folders) {
86    if (!(await io.exists(folder))) continue
87    for (const entry of await io.list(folder)) {
88      if (entry.kind !== 'file' || !entry.name.endsWith('.md')) continue
89      const definition = agentDefinitionOf(await io.read(`${folder}/${entry.name}`), entry.name)
90      if (definition?.name === type) return definition
91    }
92  }
93
94  return undefined
95}
96
hooks/codex/agents.ts 62 lines
1// Adapted from the codex plugin of alex2481kobe/claude-mods (Apache License 2.0); see THIRD_PARTY_NOTICES.md.
2
3import type { AgentSpec } from 'claude-code'
4
5import type { Io } from '../io'
6import { FLAG_NAMES, type Pin } from './flags'
7
8// The three codex agent types: what each pins, how it is shown, and how it
9// is offered to the model.
10
11export const TYPES: Record<string, { pin?: Pin; shown: string }> = {
12  'sc-accounts:codex-read': { pin: { sandbox: 'read-only' }, shown: 'Codex read-only' },
13  'sc-accounts:codex-write': { pin: { sandbox: 'workspace-write' }, shown: 'Codex workspace-write' },
14  'sc-accounts:codex-run': { shown: 'Codex' },
15}
16
17// The agent's system prompt, which no model reads while the mod answers its
18// turns. The agent list still summarises a running agent from it, so it opens
19// with what the agent does; a stand-in model, reached only if the turn.step
20// hook fails, reports that instead of answering.
21const FALLBACK = `This agent passes its task to OpenAI Codex, which does the work in its place: sc-accounts runs Codex and reports Codex's answer. A model reading this means the mod did not run, so do nothing else and give as your final report that Codex did not run and that this agent's transcript and the debug log say why.`
22
23const CHOOSING = (models: string[]) =>
24  ` Codex CLI flags may open the prompt, one per line as \`codex exec --help\` names them without dashes (\`model: <id>\`, \`effort: <level>\`` +
25  (models.length > 0 ? `; models: ${models.join(', ')}` : '') +
26  `); left out, Codex uses its own config. When Codex asks for an approval or an answer, the agent reports the question; send it the reply as a message.`
27
28// The agent types as `$.agent.register` takes them, offering these models.
29export function specsOf(models: string[]): AgentSpec[] {
30  const common = { prompt: FALLBACK, tools: ['Read'], model: 'haiku', omitClaudeMd: true } as const
31  const choosing = CHOOSING(models)
32  return [
33    {
34      ...common,
35      name: 'codex-read',
36      description:
37        'OpenAI Codex in a read-only sandbox: a second opinion, review, research or scoping by a different model. Give it a self-contained prompt; it cannot see this conversation.' + choosing,
38    },
39    {
40      ...common,
41      name: 'codex-write',
42      description:
43        'OpenAI Codex with workspace-write in the working directory: bounded implementation by a different model. Give it a self-contained prompt naming the files it owns; it cannot see this conversation.' + choosing,
44    },
45    {
46      ...common,
47      name: 'codex-run',
48      description:
49        `OpenAI Codex as your Codex config sets it up (sandbox, approvals, reviewer), changed per call by any of its flags: ${FLAG_NAMES.join(', ')}. Give it a self-contained prompt; it cannot see this conversation.` + choosing,
50    },
51  ]
52}
53
54// Whether the Codex CLI can run here: a POSIX shell finds `codex` on the
55// PATH Claude Code started with. Windows proper has no such shell, and the
56// mod needs one and a named pipe.
57export async function codexInstalled(io: Io): Promise<boolean> {
58  if ((await io.env('OS')) === 'Windows_NT') return false
59  const found = await io.run(['sh', '-c', 'command -v codex'], { timeoutMs: 5000 })
60  return found.exitCode === 0
61}
62
hooks/codex/commands.ts 125 lines
1// Adapted from the codex plugin of alex2481kobe/claude-mods (Apache License 2.0); see THIRD_PARTY_NOTICES.md.
2
3import type { CodexOptionName, CodexRun } from '../../types'
4import { groupDigits } from '../format'
5import type { Messages } from '../i18n'
6import { APPROVALS, flagsOf, SANDBOXES, type Pin } from './flags'
7
8// `/codex-*` messages, which a codex agent answers itself and never passes to
9// Codex: settings for its next Codex turns, its status, and help. They are
10// typed in the agent's view, where Claude Code hands a command it does not
11// know to the agent as a message. A setting is the Codex option line it
12// names, so it is checked by the option rules and the agent type's pin.
13
14export type Options = Partial<Record<CodexOptionName, string>>
15
16// The reply, and the agent's settings when the command changed them.
17export type Answer = { reply: string; options?: Options }
18
19const SETTINGS: Record<string, { option: CodexOptionName; value: string }> = {
20  model: { option: 'model', value: '<id>' },
21  effort: { option: 'effort', value: '<level>' },
22  sandbox: { option: 'sandbox', value: `<${SANDBOXES.join('|')}>` },
23  approvals: { option: 'ask-for-approval', value: `<${APPROVALS.join('|')}>` },
24}
25
26// The commands as Claude Code registers them, listed in a codex agent's view,
27// described in the person's language.
28export function commandSpecs(m: Messages): { name: string; description: string; argumentHint?: string; immediate: true }[] {
29  return [
30    ...Object.entries(SETTINGS).map(([name, { value }]) => ({
31      name: `codex-${name}`,
32      description: m.codexCommands[name as keyof Messages['codexCommands']],
33      argumentHint: value,
34      immediate: true as const,
35    })),
36    { name: 'codex-status', description: m.codexCommands.status, immediate: true },
37    { name: 'codex-help', description: m.codexCommands.help, immediate: true },
38  ]
39}
40
41const NAMES = [...Object.keys(SETTINGS), 'status', 'help'].map(name => `/codex-${name}`)
42
43const HELP = [
44  'Codex commands for this agent (a setting applies from its next Codex turn):',
45  ...Object.entries(SETTINGS).map(([name, { value }]) => `  /codex-${name} ${value}`),
46  '  /codex-status   what Codex runs with, the session and its tokens',
47  '  /codex-help     this list',
48].join('\n')
49
50// The footer hint while a codex agent's view is open.
51export const HINT = NAMES.join(' ')
52
53const COMMAND = /^\/codex-(\S*)(?:\s+([\s\S]*))?$/
54
55export function isCommand(text: string): boolean {
56  return text.trimStart().startsWith('/codex-')
57}
58
59// Whether a slash command is one this plugin registers (`codex-model`); a
60// command of another's that only starts the same (`codex-review`) is not.
61export function isOwnCommand(command: string): boolean {
62  return NAMES.includes(`/${command}`)
63}
64
65export function answerOf(text: string, options: Options, pin: Pin | undefined, run: CodexRun | undefined): Answer {
66  const match = COMMAND.exec(text.trim())
67  const name = match?.[1] ?? ''
68  const value = (match?.[2] ?? '').trim()
69  if (name === 'status') return { reply: statusOf(options, run) }
70  const setting = SETTINGS[name]
71  if (!setting || value === '') {
72    const why = name === 'help' ? '' : setting ? `codex: /codex-${name} needs a value.\n\n` : `codex: no /codex-${name}.\n\n`
73    return { reply: `${why}${HELP}` }
74  }
75  // One plain word: a value that spans lines would carry option lines of its own.
76  if (/\s/.test(value)) return { reply: `codex: /codex-${name} takes one plain value, not "${value}".` }
77  const parsed = flagsOf(`${setting.option}: ${value}`, pin)
78  if ('error' in parsed) return { reply: `codex: ${parsed.error}` }
79  if (parsed.prompt !== '') return { reply: `codex: /codex-${name} takes one plain value, not "${value}".` }
80  return { reply: `codex: ${name} ${value} from the next Codex turn.`, options: { ...options, [setting.option]: value } }
81}
82
83// Commands answered in order, each seeing the settings the ones before it
84// left; the replies, and the agent's settings after them.
85export function answersOf(texts: readonly string[], options: Options, pin: Pin | undefined, run: CodexRun | undefined): { replies: string[]; options: Options } {
86  let mine = options
87  const replies = texts.map(text => {
88    const answer = answerOf(text, mine, pin, run)
89    mine = answer.options ?? mine
90    return answer.reply
91  })
92  return { replies, options: mine }
93}
94
95// The settings as thread/start and thread/resume take them: a resumed
96// session keeps the model, sandbox and approvals it ran with unless the call
97// names others, so they go with every call.
98export function threadParamsOf(options: Options): { model?: string; sandbox?: string; approvalPolicy?: string; config?: Record<string, string> } {
99  return {
100    ...(options.model ? { model: options.model } : {}),
101    ...(options.sandbox ? { sandbox: options.sandbox } : {}),
102    ...(options['ask-for-approval'] ? { approvalPolicy: options['ask-for-approval'] } : {}),
103    ...(options.effort ? { config: { model_reasoning_effort: options.effort } } : {}),
104  }
105}
106
107const count = groupDigits
108
109function statusOf(options: Options, run: CodexRun | undefined): string {
110  const now: Record<CodexOptionName, string | undefined> = {
111    model: run?.model,
112    effort: run ? (run.effort ?? 'default') : undefined,
113    sandbox: run?.sandbox,
114    'ask-for-approval': run?.approvals,
115  }
116  const rows = Object.entries(SETTINGS).flatMap(([name, { option }]) => {
117    const next = options[option]
118    if (next !== undefined && next !== now[option]) return [`${name.padEnd(10)}${next} from the next Codex turn${now[option] ? ` (now ${now[option]})` : ''}`]
119    return now[option] ? [`${name.padEnd(10)}${now[option]}`] : []
120  })
121  if (!run) return ['codex: no Codex turn yet.', ...rows].join('\n')
122  const { input, cached, output } = run.tokens
123  return [...rows, `${'session'.padEnd(10)}${run.threadId}`, `${'tokens'.padEnd(10)}${count(input)} in (${count(cached)} cached), ${count(output)} out, running total`].join('\n')
124}
125
hooks/codex/flags.ts 162 lines
1// Adapted from the codex plugin of alex2481kobe/claude-mods (Apache License 2.0); see THIRD_PARTY_NOTICES.md.
2
3// A codex agent's prompt may open with Codex CLI flags, one per line, spelled
4// as `codex exec --help` spells them without the dashes: `model: gpt-6-astra`,
5// `sandbox: workspace-write`, `approve-for-me`, `config: key=value`. They
6// choose how Codex runs and are not part of the task. Codex's own config fills
7// in everything not chosen.
8
9export type Flags = {
10  // Arguments for `codex app-server`: config overrides and feature switches.
11  args: string[]
12  model?: string
13  effort?: string
14  cwd?: string
15  ephemeral?: boolean
16  images: string[]
17  outputSchema?: string
18  addDirs: string[]
19  prompt: string
20}
21
22export type Parsed = Flags | { error: string }
23
24// What the read and write types pin: a flag that changes it is refused there.
25export type Pin = { sandbox: string }
26
27const WORD = /^[A-Za-z0-9._/:@+-]+$/
28const CONFIG = /^[A-Za-z0-9_.-]+=.+$/
29const PINNED = /^(sandbox_mode|approval_policy|approvals_reviewer|sandbox_workspace_write)\b/
30
31export const SANDBOXES = ['read-only', 'workspace-write', 'danger-full-access']
32// The approval policies `codex --ask-for-approval` takes (codex-cli 0.160); an older
33// `untrusted` is refused by Codex itself, so it is refused here first with the choices.
34export const APPROVALS = ['on-request', 'never']
35
36// `codex exec` flags that have no meaning for a session the mod drives.
37const EXEC_ONLY: Record<string, string> = {
38  profile: 'codex app-server takes no --profile; set the values with config: lines',
39  json: 'the mod already reads Codex events',
40  'output-last-message': 'the report goes back to Claude',
41  color: 'there is no terminal',
42  'skip-git-repo-check': 'the mod never needs a git repo',
43  worktree: 'codex app-server takes no --worktree',
44  'ignore-user-config': 'codex app-server takes no --ignore-user-config',
45  'ignore-rules': 'codex app-server takes no --ignore-rules',
46  'dangerously-bypass-hook-trust': 'codex app-server takes no --dangerously-bypass-hook-trust',
47  oss: 'name the provider with local-provider: lmstudio or ollama',
48}
49
50const ALIASES: Record<string, string> = {
51  m: 'model',
52  s: 'sandbox',
53  a: 'ask-for-approval',
54  approval: 'ask-for-approval',
55  c: 'config',
56  C: 'cd',
57  i: 'image',
58  auto: 'approve-for-me',
59  'reasoning-effort': 'effort',
60}
61
62// `--sandbox read-only`, `-s=read-only`, `sandbox: read-only`, or a flag that
63// takes no value alone on its line (`approve-for-me`). "search the code" has
64// neither the dashes nor the colon; see isOptionLine for prose that has one.
65const DASHED = /^--?([A-Za-z][A-Za-z-]*)(?:[ =]\s*(.*))?$/
66const PLAIN = /^([A-Za-z][A-Za-z-]*)(?::\s*(.*))?$/
67
68type Apply = (flags: Flags, value: string) => string | undefined
69
70function quoted(key: string, value: string, flags: Flags): string | undefined {
71  if (!WORD.test(value)) return `${key} needs a plain value, not "${value}"`
72  flags.args.push('-c', `${key}="${value}"`)
73}
74
75function oneOf(key: string, allowed: string[]): Apply {
76  return (flags, value) => (allowed.includes(value) ? quoted(key, value, flags) : `${key} is one of ${allowed.join(', ')}`)
77}
78
79// `path`: the value is a path, which may hold spaces when it starts like one.
80const FLAGS: Record<string, { apply: Apply; pinned?: true; bare?: true; path?: true }> = {
81  model: { apply: (f, v) => quoted('model', v, f) ?? void (f.model = v) },
82  effort: { apply: (f, v) => quoted('model_reasoning_effort', v, f) ?? void (f.effort = v) },
83  sandbox: { apply: oneOf('sandbox_mode', SANDBOXES), pinned: true },
84  'ask-for-approval': { apply: oneOf('approval_policy', APPROVALS), pinned: true },
85  // As `codex exec --approve-for-me`: Codex's automatic reviewer decides, in
86  // the workspace-write sandbox.
87  'approve-for-me': {
88    apply: f => void f.args.push('-c', 'approvals_reviewer="auto_review"', '-c', 'sandbox_mode="workspace-write"'),
89    pinned: true,
90    bare: true,
91  },
92  'dangerously-bypass-approvals-and-sandbox': {
93    apply: f => void f.args.push('-c', 'sandbox_mode="danger-full-access"', '-c', 'approval_policy="never"'),
94    pinned: true,
95    bare: true,
96  },
97  'add-dir': { apply: (f, v) => void f.addDirs.push(v), pinned: true, path: true },
98  search: { apply: f => void f.args.push('-c', 'web_search="live"'), bare: true },
99  'local-provider': { apply: (f, v) => quoted('model_provider', v, f) },
100  config: {
101    apply: (f, v) => (CONFIG.test(v) ? void f.args.push('-c', v) : `config takes key=value, not "${v}"`),
102  },
103  enable: { apply: (f, v) => (WORD.test(v) ? void f.args.push('--enable', v) : `enable takes a feature name`) },
104  disable: { apply: (f, v) => (WORD.test(v) ? void f.args.push('--disable', v) : `disable takes a feature name`) },
105  'strict-config': { apply: f => void f.args.push('--strict-config'), bare: true },
106  ephemeral: { apply: f => void (f.ephemeral = true), bare: true },
107  // Pinned like add-dir: moving the folder moves the writable root.
108  cd: { apply: (f, v) => void (f.cwd = v), pinned: true, path: true },
109  image: { apply: (f, v) => void f.images.push(v), path: true },
110  'output-schema': { apply: (f, v) => void (f.outputSchema = v), path: true },
111}
112
113export const FLAG_NAMES = Object.keys(FLAGS)
114
115// Whether a line is shaped as an option line for this flag: a bare flag
116// alone (or `true`), a config `key=value`, a path, or one plain value. A line
117// of prose that only starts with a flag's name ("search: every call") is not,
118// and is the task's.
119function isOptionLine(name: string, value: string): boolean {
120  const flag = FLAGS[name]
121  if (flag?.bare) return value === '' || /^(true|yes|on)$/i.test(value)
122  if (name === 'config') return CONFIG.test(value)
123  if (flag?.path && /^[/~.]/.test(value)) return true
124  return value !== '' && !/\s/.test(value)
125}
126
127// `Model:` and `Effort:` read in any case, as 0.2.5 read them; every other
128// name as `codex exec --help` spells it, since `-C` and `-c` differ.
129function nameOf(raw: string): string {
130  const lower = raw.toLowerCase()
131  if (lower === 'model' || lower === 'effort') return lower
132  return ALIASES[raw] ?? raw
133}
134
135// Reads the leading option lines of a prompt. The first line that is not one
136// ends them, and it and the rest are the task. An option line used wrongly,
137// or one a pinned type refuses, is an error for the caller rather than a
138// silent change of what Codex runs with.
139export function flagsOf(text: string, pin?: Pin): Parsed {
140  const flags: Flags = { args: [], images: [], addDirs: [], prompt: text }
141  if (pin) flags.args.push('-c', `sandbox_mode="${pin.sandbox}"`, '-c', 'approval_policy="never"')
142  const lines = text.split('\n')
143  let used = 0
144  for (const line of lines) {
145    const match = DASHED.exec(line.trim()) ?? PLAIN.exec(line.trim())
146    if (!match) break
147    const name = nameOf(match[1]!)
148    const value = (match[2] ?? '').trim()
149    if (!(name in FLAGS || name in EXEC_ONLY) || !isOptionLine(name, value)) break
150    if (name in EXEC_ONLY) return { error: `${name}: ${EXEC_ONLY[name]}` }
151    const flag = FLAGS[name]!
152    if (pin && (flag.pinned || (name === 'config' && PINNED.test(value)))) {
153      return { error: `${name}: this agent type pins the ${pin.sandbox} sandbox; use sc-accounts:codex-run to choose` }
154    }
155    const error = flag.apply(flags, value)
156    if (error) return { error }
157    used++
158  }
159  flags.prompt = lines.slice(used).join('\n').trim()
160  return flags
161}
162
hooks/codex/model.ts 76 lines
1// Adapted from the codex plugin of alex2481kobe/claude-mods (Apache License 2.0); see THIRD_PARTY_NOTICES.md.
2
3import { homeDirectory } from '../credentials'
4import type { Io } from '../io'
5
6// What Codex runs with: its config.toml's top-level model and reasoning
7// effort, under what a codex agent's prompt chose.
8
9export type Choice = { model?: string; effort?: string }
10
11export function configOf(toml: string): Choice {
12  const choice: Choice = {}
13  for (const line of toml.split('\n')) {
14    const text = line.trim()
15    if (text.startsWith('[')) break
16    const pair = /^([A-Za-z_]+)\s*=\s*["']([^"']+)["']/.exec(text)
17    if (pair?.[1] === 'model') choice.model = pair[2]
18    if (pair?.[1] === 'model_reasoning_effort') choice.effort = pair[2]
19  }
20  return choice
21}
22
23// Codex model ids as people say them: `gpt-6.1-sol` reads `Sol 6.1`. An id
24// of another shape is shown as it is.
25export function nameOf(id: string): string {
26  const match = /^gpt-([\d.]+)-([a-z]+)$/i.exec(id)
27  const word = match?.[2]
28  if (!match || !word) return id
29  return `${word.charAt(0).toUpperCase()}${word.slice(1)} ${match[1]}`
30}
31
32// `Sol 6.1 (high)`: the chosen model and effort over the config's. With
33// neither naming a model, Codex picks its own; which one is known only once
34// Codex runs (each turn's header names it), so the label says so.
35export function labelOf(config: Choice, options: Choice): string {
36  const id = options.model ?? config.model
37  const model = id ? nameOf(id) : 'Codex default'
38  const effort = options.effort ?? config.effort
39  return effort ? `${model} (${effort})` : model
40}
41
42// The model ids Codex's model cache lists, newest first as it keeps them;
43// empty when the cache is missing or its shape is not the one read here.
44export function modelsOf(json: string): string[] {
45  try {
46    const cache = JSON.parse(json)
47    const list = Array.isArray(cache) ? cache : (cache?.models ?? cache?.data)
48    if (!Array.isArray(list)) return []
49    return list.map((m: any) => m?.slug ?? m?.id).filter((s: unknown): s is string => typeof s === 'string')
50  } catch (error) {
51    if (error instanceof SyntaxError) return []
52    throw error
53  }
54}
55
56// Codex's own folder: `CODEX_HOME`, else `~/.codex`.
57export async function codexHome(io: Io): Promise<string> {
58  return (await io.env('CODEX_HOME')) || `${await homeDirectory(io)}/.codex`
59}
60
61// A file of Codex's folder; empty when it is not there.
62async function readOr(io: Io, name: string): Promise<string> {
63  const path = `${await codexHome(io)}/${name}`
64  return (await io.exists(path)) ? io.read(path) : ''
65}
66
67// The model and effort Codex's config.toml names; empty when it names none.
68export async function codexConfig(io: Io): Promise<Choice> {
69  return configOf(await readOr(io, 'config.toml'))
70}
71
72// The model ids Codex's model cache lists.
73export async function codexModels(io: Io): Promise<string[]> {
74  return modelsOf(await readOr(io, 'models_cache.json'))
75}
76
hooks/codex/step.ts 312 lines
1// Adapted from the codex plugin of alex2481kobe/claude-mods (Apache License 2.0); see THIRD_PARTY_NOTICES.md.
2
3import type { Hook, TurnStepChunk, TurnUsage } from 'claude-code'
4
5import type { CodexOpenings, CodexOptions, CodexRun, CodexRuns, CodexSent } from '../../types'
6import { TYPES } from './agents'
7import { answersOf, isCommand, threadParamsOf } from './commands'
8import { answerOf, apply, reportOf, STOPPED, type Run } from './events'
9import { flagsOf, type Flags, type Pin } from './flags'
10import { labelOf } from './model'
11import { expiredAnswer, questionOf, replyOf, type Asked } from './questions'
12import { HANDBACK, handsBack, lastAnswer, requestOf, rowsOf, undeliveredReport, type ApiTurn } from './request'
13import { NO_CODEX, open, type Host, type Server } from './server'
14import { openView, setReply } from './view'
15
16// One step of a codex agent's loop: its model request answered by driving
17// `codex app-server`, Codex's steps streamed as the agent's text, and Codex's
18// answer or question handed back.
19
20// A value of the session's state, read whole and changed in one step.
21export type Shared<T> = { get: () => Promise<T>; update: (change: (value: T) => T) => Promise<void> }
22
23// What a codex agent's step reaches the engine through. The hooks module
24// builds it over `$`; a test drives the step through the engine instead.
25export type CodexContext = {
26  // The agent's type, from the engine's agent list; undefined for no such agent.
27  agentType: (agentId: string) => Promise<string | undefined>
28  // The agent's conversation as the model would be sent it.
29  messages: (agentId: string) => Promise<readonly ApiTurn[]>
30  cwd: () => Promise<string>
31  host: Host
32  read: (path: string) => Promise<string>
33  // Appends a notice to the agent's conversation, which refreshes its row's activity line.
34  note: (agentId: string, text: string) => Promise<void>
35  // Redraws the band, where a command's reply shows.
36  invalidate: () => void
37  sent: Shared<CodexSent>
38  openings: Shared<CodexOpenings>
39  options: Shared<CodexOptions>
40  runs: Shared<CodexRuns>
41}
42
43type StepInput = Parameters<Hook<'turn.step'>>[1]
44type StepNext = Parameters<Hook<'turn.step'>>[2]
45
46// A Codex turn paused on a question, by agent id: the server stays up until
47// the agent's next message answers it.
48const held = new Map<string, { server: Server; asked: Asked; threadId: string }>()
49
50// The Codex turn each codex agent is running now, by agent id, so a message
51// sent to the agent meanwhile can join it rather than wait for it to end.
52const working = new Map<string, { server: Server; threadId: string; turnId: string }>()
53
54// Adds a message to the agent's running Codex turn; false when no turn runs
55// or Codex refused (the turn had just ended), so the message takes the usual
56// way: the agent's next turn.
57export async function steer(agentId: string, text: string): Promise<boolean> {
58  const turn = working.get(agentId)
59  if (!turn) return false
60  try {
61    await turn.server.call('turn/steer', { threadId: turn.threadId, expectedTurnId: turn.turnId, input: [{ type: 'text', text }] })
62    return true
63  } catch (error) {
64    if (!(error instanceof Error)) throw error
65    return false
66  }
67}
68
69// Ends every Codex turn left waiting on a question.
70export function closeHeld(): void {
71  for (const { server } of held.values()) server.close()
72  held.clear()
73}
74
75// Records what Codex reported the agent's session runs with (or keeps the
76// last), with its token total once Codex has counted it.
77async function record(ctx: CodexContext, agentId: string, report: Omit<CodexRun, 'tokens'> | undefined, tokens?: CodexRun['tokens']): Promise<void> {
78  await ctx.runs.update(all => {
79    const base = report ?? all[agentId]
80    return base ? { ...all, [agentId]: { ...base, tokens: tokens ?? all[agentId]?.tokens ?? { input: 0, cached: 0, output: 0 } } } : all
81  })
82}
83
84const shown = (text: string): TurnStepChunk => ({ kind: 'text', index: 0, text })
85
86// Codex's progress also as notices in the agent's conversation, appended as
87// it happens: a notice is what refreshes the agent list's activity line, while
88// the agent's view shows the step's text. The model never reads a notice, and
89// only the detailed transcript (ctrl+o) shows both. Display only, so a refused
90// append changes nothing else.
91async function note(ctx: CodexContext, agentId: string, text: string): Promise<void> {
92  await ctx.note(agentId, text.trimEnd()).catch(() => undefined)
93}
94
95// Resolves undefined when the step is aborted first; the listener goes once
96// the wait settles, so a long turn does not pile them up on the signal.
97export function unlessAborted<T>(signal: AbortSignal, promise: Promise<T>): Promise<T | undefined> {
98  if (signal.aborted) return Promise.resolve(undefined)
99  let stop = () => {}
100  const aborted = new Promise<undefined>(resolve => {
101    stop = () => resolve(undefined)
102    signal.addEventListener('abort', stop, { once: true })
103  })
104  return Promise.race([promise, aborted]).finally(() => signal.removeEventListener('abort', stop))
105}
106
107const EXPIRED =
108  'codex: the question Codex asked has expired: the Codex turn that asked it is gone (Codex exited, the session was resumed, or the mod reloaded), so nothing was answered. Send the task again to start a new turn.'
109
110// The agent's `/codex-*` commands, answered in order; a setting is kept for
111// its next Codex turn.
112async function answered(ctx: CodexContext, agentId: string, commands: string[], pin?: Pin): Promise<string[]> {
113  const last = (await ctx.runs.get())[agentId]
114  let replies: string[] = []
115  await ctx.options.update(all => {
116    const answers = answersOf(commands, all[agentId] ?? {}, pin, last)
117    replies = answers.replies
118    return { ...all, [agentId]: answers.options }
119  })
120  return replies
121}
122
123// A registered /codex- command acts on the agent whose view is open and
124// answers in that view's band; the main conversation is not sent the reply.
125// Undefined when the open view is no codex agent's: the caller says so.
126export async function command(ctx: CodexContext, name: string, args: string): Promise<'answered' | undefined> {
127  const id = openView()
128  const type = id === undefined ? undefined : TYPES[(await ctx.agentType(id)) ?? '']
129  if (id === undefined || !type) return undefined
130  const [reply = ''] = await answered(ctx, id, [`/${name} ${args}`.trim()], type.pin)
131  setReply(id, reply)
132  ctx.invalidate()
133  return 'answered'
134}
135
136// Whether the agent is a codex agent, whose loop `step` answers.
137export async function isCodexAgent(ctx: CodexContext, agentId: string | undefined): Promise<boolean> {
138  return agentId !== undefined && TYPES[(await ctx.agentType(agentId)) ?? ''] !== undefined
139}
140
141export async function* step(ctx: CodexContext, e: StepInput, next: StepNext) {
142  const agentId = e.agentId
143  if (!agentId) return yield* next(e)
144  const type = TYPES[(await ctx.agentType(agentId)) ?? '']
145  if (!type) return yield* next(e)
146
147  const rows = rowsOf(await ctx.messages(agentId))
148  const given = (await ctx.sent.get())[agentId] ?? []
149  const request = requestOf(rows, given, (await ctx.openings.get())[agentId])
150  // Codex's progress is the transcript's text; the report goes back with a
151  // handback call, or as the final text where the loop has no such tool.
152  const handback = handsBack(rows)
153
154  const run: Run = {}
155  let progress = ''
156  let question: string | undefined
157  let model = 'codex'
158  let server: Server | undefined
159  const show = (text: string) => {
160    progress += text
161    return shown(text)
162  }
163  // A `/codex-*` message is the mod's to answer; the rest is Codex's.
164  const asked = request?.texts.filter(text => !isCommand(text)) ?? []
165  const replies = request ? await answered(ctx, agentId, request.texts.filter(isCommand), type.pin) : []
166  for (const reply of replies) {
167    yield show(`${reply}\n\n`)
168    await note(ctx, agentId, reply)
169  }
170  let report: Omit<CodexRun, 'tokens'> | undefined
171  // Whether Codex took this step's messages: it started their turn, or its
172  // question was answered. From then they are passed on, finished or not.
173  let isTaken = false
174  if (request) {
175    const prompt = asked.join('\n\n')
176    // A question whose Codex has gone holds nothing: a decision sent to it
177    // expires below, and a new task starts a new turn of the session.
178    const waiting = held.get(agentId)
179    if (waiting?.server.isEnded()) held.delete(agentId)
180    const pending = waiting?.server.isEnded() ? undefined : waiting
181    const reply = pending && replyOf(pending.asked, prompt)
182    const cwd = await ctx.cwd()
183    try {
184      if (asked.length === 0) {
185        // Commands alone: Codex is not asked, and a question it asked still waits.
186      } else if (!pending && expiredAnswer(lastAnswer(rows), prompt)) {
187        question = EXPIRED
188      } else if (pending && !reply) {
189        // Not an answer: ask again, Codex still waiting.
190        question = `That does not answer Codex.\n\n${questionOf(pending.asked)}`
191      } else if (pending && reply) {
192        held.delete(agentId)
193        server = pending.server
194        run.threadId = pending.threadId
195        await server.respond(pending.asked.id, reply)
196        isTaken = true
197        yield show(`answered Codex\n`)
198        await note(ctx, agentId, 'answered Codex')
199      } else {
200        // Once Codex has taken a message the agent's session goes on, even
201        // where the conversation keeps no session line (a step stopped first).
202        const sessionId = given.length > 0 ? (request.sessionId ?? (await ctx.runs.get())[agentId]?.threadId) : undefined
203        const first = sessionId === undefined
204        // The spawn prompt's flags hold for every run of the agent; they are
205        // not part of the task.
206        const flags = flagsOf(request.opening, type.pin)
207        if ('error' in flags) throw new Error(flags.error)
208        const set = threadParamsOf((await ctx.options.get())[agentId] ?? {})
209        server = await open(ctx.host, flags.args, cwd)
210        const where = flags.cwd ?? cwd
211        const config = { ...set.config, ...(await rootsOf(server, flags.addDirs)) }
212        const overrides = { ...set, ...(Object.keys(config).length > 0 ? { config } : {}) }
213        const thread = first
214          ? await server.call('thread/start', { cwd: where, ...(flags.ephemeral ? { ephemeral: true } : {}), ...overrides })
215          : await server.call('thread/resume', { threadId: sessionId, cwd: where, ...overrides })
216        // What the session runs on, as Codex reports it.
217        report = reportOf(thread)
218        run.threadId = report.threadId
219        // Known now, for /codex-status while the turn runs.
220        await record(ctx, agentId, report)
221        model = report.model
222        yield show(`codex ${labelOf({}, { model: report.model, effort: report.effort ?? undefined })} · ${type.shown}\ncodex session ${run.threadId}\n\n`)
223        const images = flags.images.map(path => ({ type: 'localImage', path }))
224        const schema = flags.outputSchema ? { outputSchema: JSON.parse(await ctx.read(flags.outputSchema)) } : {}
225        const opens = asked[0] === request.opening
226        const text = opens ? (flagsOf(prompt, type.pin) as Flags).prompt : prompt
227        // The spawn prompt's images go with its own turn, not again with each follow-up.
228        const started = await server.call('turn/start', { threadId: run.threadId, input: [{ type: 'text', text }, ...(opens ? images : [])], ...schema })
229        isTaken = true
230        if (started?.turn?.id) working.set(agentId, { server, threadId: run.threadId!, turnId: started.turn.id })
231      }
232      while (server && !question) {
233        const message = await unlessAborted(next.signal, server.next())
234        if (!message) {
235          if (!next.signal.aborted) run.error = `codex app-server exited: ${server.stderr().trim().split('\n').at(-1) || 'no reason given'}`
236          break
237        }
238        if (message.id !== undefined) {
239          const asked = { id: message.id, method: message.method, params: message.params }
240          question = questionOf(asked)
241          if (question) held.set(agentId, { server, asked, threadId: run.threadId! })
242          else await server.respond(message.id, replyOf(asked, '')!)
243          continue
244        }
245        const step = apply(run, message.method, message.params)
246        if (step !== undefined) {
247          yield show(step)
248          await note(ctx, agentId, step)
249        }
250        if (run.isDone) break
251      }
252    } catch (err) {
253      // Stopped while Codex was starting (the engine ends the child, and the
254      // wait fails with it): a cut-off, not a failure, so nothing untaken is
255      // marked passed on.
256      if (!next.signal.aborted) {
257        run.error = (err as Error).message
258        // Only a missing CLI, or one too old for app-server, earns the hint.
259        if (`${run.error}\n${server?.stderr() ?? ''}`.includes(NO_CODEX) || /unrecognized subcommand '?app-server/.test(`${run.error}\n${server?.stderr() ?? ''}`)) {
260          run.error += '. sc-accounts needs the Codex CLI with `codex app-server` (0.159 or newer): `npm install -g @openai/codex`, then `codex login`.'
261        }
262      }
263    } finally {
264      working.delete(agentId)
265      if (server && !held.has(agentId)) server.close()
266      // A step cut off (interrupted, or closed) before Codex took its messages,
267      // asked or failed has passed nothing on: the next step sends them again.
268      const isCutOff = asked.length > 0 && !isTaken && !question && !run.error
269      // The commands were answered either way, so they are never answered again.
270      const passed = isCutOff ? request.texts.filter(isCommand) : request.texts
271      if (passed.length > 0) await ctx.sent.update(all => ({ ...all, [agentId]: [...(all[agentId] ?? []), ...passed] }))
272      // What Codex reported this session runs with, and its token total.
273      await record(ctx, agentId, report, run.tokens)
274    }
275  }
276
277  // Codex's own token counts, so the agent's row shows what the run cost.
278  const usage: TurnUsage | null = run.usage ? { ...run.usage, model } : null
279  const codexSaid = question || (asked.length > 0 ? answerOf(run) : undefined)
280  // A report that never reached the caller goes ahead of this step's answer;
281  // with nothing new (the engine ran the loop again) the loop says only that.
282  // A stopped step says only that it stopped, which is never such a report.
283  const undelivered = undeliveredReport(rows)
284  const message =
285    codexSaid === STOPPED
286      ? STOPPED
287      : request
288        ? [...(undelivered ? [undelivered] : []), ...replies, ...(codexSaid ? [codexSaid] : [])].join('\n\n')
289        : (undelivered ?? 'codex: nothing new to send to Codex.')
290  if (!handback) {
291    // The session line lets a follow-up resume this run (see requestOf).
292    const text = run.threadId ? `${message}\n\ncodex session ${run.threadId}` : message
293    yield { kind: 'text', index: 1, text }
294    yield { kind: 'stop', stopReason: 'end_turn', usage }
295    return { turnId: e.turnId, index: e.index, answer: text, toolUses: [], stopReason: 'end_turn', usage }
296  }
297  if (progress === '' && !question) yield show(run.error ? `codex: ${run.error}\n` : 'codex: nothing to run.\n')
298  const input = { message }
299  yield { kind: 'tool', index: 1, id: `toolu_codex_${crypto.randomUUID().replaceAll('-', '')}`, name: HANDBACK }
300  yield { kind: 'input', index: 1, json: JSON.stringify(input) }
301  yield { kind: 'stop', stopReason: 'tool_use', usage }
302  return { turnId: e.turnId, index: e.index, answer: progress, toolUses: [{ name: HANDBACK, input }], stopReason: 'tool_use', usage }
303}
304
305// `add-dir`: the config's writable roots plus the ones asked for, since a
306// thread's setting replaces the config's list rather than adding to it.
307async function rootsOf(server: Server, dirs: readonly string[]): Promise<Record<string, unknown>> {
308  if (dirs.length === 0) return {}
309  const { config } = await server.call('config/read', {})
310  return { 'sandbox_workspace_write.writable_roots': [...(config?.sandbox_workspace_write?.writable_roots ?? []), ...dirs] }
311}
312
hooks/codexAccount.ts 152 lines
1import type { CodexAccountView, CodexLogin, LimitView } from '../types'
2import { open } from './codex/server'
3import type { Host } from './codex/server'
4import type { Messages } from './i18n'
5import type { Cell, Io } from './io'
6import { message, within } from './io'
7import { truncate } from './shared/layout'
8
9/** How old a Codex reading may get while the pane is open before it is looked up again. */
10export const CODEX_LOOKUP_MS = 5 * 60 * 1000
11/** How long the Codex lookup waits for `codex app-server`, from its start to both answers. */
12export const CODEX_TIMEOUT_MS = 15_000
13
14/**
15 * What the Codex card reaches the machine through: the Codex server is
16 * started in the session's folder, and the card's state is this session's
17 * own, as the Codex login depends on the environment the session started in
18 * (`CODEX_HOME`).
19 */
20export type CodexAccountContext = {
21  io: Io
22  host: Host
23  cwd: () => Promise<string>
24  cell: Cell<CodexAccountView | null>
25  messages: () => Messages
26}
27
28/**
29 * Cells a limit's own name may take: every card's gauges share the widest
30 * label's width, so a long name from Codex would widen the Claude cards' too.
31 */
32const LIMIT_NAME_CELLS = 12
33
34/** A window's label as the Claude cards name theirs: `5h`, `wk`, else its hours or days. */
35export function windowLabel(minutes: number): string {
36  if (minutes === 300) return '5h'
37  if (minutes === 10_080) return 'wk'
38  if (minutes % 1440 === 0) return `${minutes / 1440}d`
39
40  return `${Math.round(minutes / 60)}h`
41}
42
43type Window = { usedPercent?: unknown; windowDurationMins?: unknown; resetsAt?: unknown }
44type Limit = { limitId?: unknown; limitName?: unknown; primary?: Window | null; secondary?: Window | null; credits?: unknown }
45
46function limitOf(window: Window | null | undefined, label?: string): LimitView[] {
47  if (!window || typeof window.usedPercent !== 'number') return []
48  const minutes = typeof window.windowDurationMins === 'number' ? window.windowDurationMins : null
49  const resetsAt = typeof window.resetsAt === 'number' ? new Date(window.resetsAt * 1000).toISOString() : undefined
50
51  return [{ label: label ?? (minutes === null ? '?' : windowLabel(minutes)), percent: Math.max(0, Math.min(100, window.usedPercent)), ...(resetsAt ? { resetsAt } : {}) }]
52}
53
54/** `account/read`'s answer as the card names the login. */
55export function loginOf(answer: unknown): CodexLogin {
56  const account = (answer as { account?: { type?: unknown; email?: unknown; planType?: unknown } | null } | null)?.account
57  if (account?.type === 'chatgpt') {
58    return { kind: 'chatgpt', email: typeof account.email === 'string' ? account.email : null, plan: typeof account.planType === 'string' ? account.planType : null }
59  }
60
61  return account?.type === 'apiKey' ? { kind: 'apiKey' } : { kind: 'none' }
62}
63
64/**
65 * `account/rateLimits/read`'s answer as the card draws it: the main limit's
66 * windows by their length, then each other limit's windows under its name,
67 * and the credits when the account has them.
68 */
69export function limitsOf(answer: unknown): { limits: LimitView[]; credits?: CodexAccountView['credits'] } {
70  const read = answer as { rateLimits?: Limit | null; rateLimitsByLimitId?: Record<string, Limit> | null } | null
71  const main = read?.rateLimits
72  const limits = [...limitOf(main?.primary), ...limitOf(main?.secondary)]
73  // The main limit is also listed by its id; without an id it is known by its windows.
74  const windowsOf = (limit: Limit) => JSON.stringify([limit.primary ?? null, limit.secondary ?? null])
75  const isMain = (id: string, other: Limit) => (typeof main?.limitId === 'string' ? id === main.limitId : main != null && windowsOf(other) === windowsOf(main))
76  for (const [id, other] of Object.entries(read?.rateLimitsByLimitId ?? {})) {
77    if (isMain(id, other)) continue
78    const name = truncate(typeof other.limitName === 'string' && other.limitName !== '' ? other.limitName : id, LIMIT_NAME_CELLS)
79    // Each of its windows: the first under its name, a second also under the window's length.
80    const windows = [other.primary, other.secondary].filter((window): window is Window => window != null)
81    windows.forEach((window, index) => {
82      const length = typeof window.windowDurationMins === 'number' ? ` ${windowLabel(window.windowDurationMins)}` : ` ${index + 1}`
83      limits.push(...limitOf(window, index === 0 ? name : `${name}${length}`))
84    })
85  }
86  const credits = main?.credits as { hasCredits?: unknown; unlimited?: unknown; balance?: unknown } | undefined
87  if (credits?.hasCredits !== true) return { limits }
88  const balance = typeof credits.balance === 'string' || typeof credits.balance === 'number' ? Number(credits.balance) : NaN
89
90  return { limits, credits: { isUnlimited: credits.unlimited === true, balance: Number.isFinite(balance) ? balance : null } }
91}
92
93/** Asks one `codex app-server` for the login and its limits, and ends it however the asking ends. */
94async function lookUp(ctx: CodexAccountContext): Promise<{ login: CodexLogin; limits: LimitView[]; credits?: CodexAccountView['credits'] }> {
95  let stop: (() => void) | undefined
96  let isOver = false
97  const asking = (async () => {
98    const cwd = await ctx.cwd()
99    // A wait given up before the server is spawned spawns none.
100    if (isOver) throw new Error('the Codex lookup was given up')
101    const started = await open(ctx.host, [], cwd, end => (stop = end))
102    const login = loginOf(await started.call('account/read', { refreshToken: false }))
103    // A signed-out Codex has no limits to read.
104    if (login.kind === 'none') return { login, limits: [] }
105
106    return { login, ...limitsOf(await started.call('account/rateLimits/read')) }
107  })()
108  try {
109    return await within(ctx.io, asking, CODEX_TIMEOUT_MS, ctx.messages().codexNoAnswer(CODEX_TIMEOUT_MS / 1000))
110  } finally {
111    // Ends the server however far it got, a start still waiting on Codex included.
112    isOver = true
113    stop?.()
114  }
115}
116
117/** Whether a lookup runs in this process now: a second one waits for the next tick. */
118let isLooking = false
119
120/**
121 * Looks the Codex account up when asked (Refresh), or when the last lookup is
122 * older than `CODEX_LOOKUP_MS`. A failed lookup keeps the figures before it,
123 * says why, and is tried again after the same time. Nothing runs where the
124 * Codex CLI does not (the cell is null).
125 */
126export async function refreshCodexAccount(ctx: CodexAccountContext, isAsked: boolean): Promise<void> {
127  // Taken before the first wait, so a Refresh and the tick never run two lookups at once.
128  if (isLooking) return
129  isLooking = true
130  try {
131    await lookUpWhenDue(ctx, isAsked)
132  } finally {
133    isLooking = false
134  }
135}
136
137async function lookUpWhenDue(ctx: CodexAccountContext, isAsked: boolean): Promise<void> {
138  const before = await ctx.cell.get()
139  if (before === null) return
140  const now = await ctx.io.now()
141  if (!isAsked && before.lookedAt > 0 && now - before.lookedAt < CODEX_LOOKUP_MS) return
142  try {
143    const found = await lookUp(ctx)
144    const at = await ctx.io.now()
145    await ctx.cell.set({ login: found.login, reading: { limits: found.limits, fetchedAt: at }, ...(found.credits ? { credits: found.credits } : {}), lookedAt: at })
146  } catch (error) {
147    const at = await ctx.io.now()
148    const reading = { limits: before.reading?.limits ?? [], fetchedAt: before.reading?.fetchedAt ?? at, error: message(error) }
149    await ctx.cell.set({ ...before, reading, lookedAt: at })
150  }
151}
152
hooks/codex/view.ts 38 lines
1// Adapted from the codex plugin of alex2481kobe/claude-mods (Apache License 2.0); see THIRD_PARTY_NOTICES.md.
2
3// The codex agent whose view is open on each surface, if any, and the reply
4// to the last /codex- command run in each such view. The band above the
5// prompt sees the view (a render hook may not write $.state, so it is kept
6// here) and draws the reply; a command reads the view. Display only: a reload
7// drops both, and the next draw sets the view again. Each surface keeps its
8// own, so a terminal and a desktop showing different views never flip one
9// value back and forth, each redrawing the other.
10
11// Surface by surface, the latest to open a codex view last.
12const opens = new Map<string, string>()
13const replies = new Map<string, string>()
14
15// The codex agent whose view the surface shows; with no surface named (a
16// command, the menu), the one opened last on a surface that still shows it.
17export function openView(surface?: string): string | undefined {
18  return surface === undefined ? [...opens.values()].at(-1) : opens.get(surface)
19}
20
21// Says whether the surface's view changed; a view no surface shows any more drops its reply.
22export function setOpenView(surface: string, agentId: string | undefined): boolean {
23  const was = opens.get(surface)
24  if (agentId === was) return false
25  opens.delete(surface)
26  if (agentId !== undefined) opens.set(surface, agentId)
27  if (was !== undefined && ![...opens.values()].includes(was)) replies.delete(was)
28  return true
29}
30
31export function replyIn(agentId: string): string | undefined {
32  return replies.get(agentId)
33}
34
35export function setReply(agentId: string, reply: string): void {
36  replies.set(agentId, reply)
37}
38
hooks/anthropic.ts 254 lines
1import type { HttpInit } from 'claude-code'
2
3import type { LimitView, Money, SpendView, UsageView } from '../types'
4import type { Messages } from './i18n'
5import { isAccountId } from './keychain'
6import type { Credential } from './keychain'
7
8export const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
9export const TOKEN_URL = 'https://platform.claude.com/v1/oauth/token'
10export const PROFILE_URL = 'https://api.anthropic.com/api/oauth/profile'
11const CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e'
12const OAUTH_BETA = 'oauth-2025-04-20'
13/** Refresh this long before the access token expires. */
14const EXPIRY_MARGIN_MS = 5 * 60 * 1000
15
16export class AnthropicError extends Error {
17  constructor(
18    message: string,
19    readonly status?: number,
20    /** The response's `Retry-After` header, when it sent one. */
21    readonly retryAfter?: string,
22  ) {
23    super(message)
24  }
25}
26
27type RawLimit = {
28  kind?: string
29  percent?: number
30  resets_at?: string | null
31  scope?: { model?: { display_name?: string | null } | null } | null
32}
33
34type RawWindow = { utilization?: number | null; resets_at?: string | null } | null
35
36type RawUsage = {
37  limits?: RawLimit[]
38  five_hour?: RawWindow
39  seven_day?: RawWindow
40}
41
42function labelOf(limit: RawLimit): string {
43  if (limit.kind === 'session') return '5h'
44  if (limit.kind === 'weekly_all') return 'wk'
45
46  return limit.scope?.model?.display_name ?? limit.kind ?? '?'
47}
48
49/** Turns the usage endpoint's body into the windows the pane draws. */
50export function parseUsage(body: unknown): LimitView[] {
51  const raw = (body ?? {}) as RawUsage
52  if (Array.isArray(raw.limits) && raw.limits.length > 0) {
53    return raw.limits
54      .filter(limit => typeof limit.percent === 'number')
55      .map(limit => ({ label: labelOf(limit), percent: limit.percent as number, resetsAt: limit.resets_at ?? undefined }))
56  }
57  const windows: [string, RawWindow | undefined][] = [
58    ['5h', raw.five_hour],
59    ['wk', raw.seven_day],
60  ]
61
62  return windows.flatMap(([label, window]) =>
63    typeof window?.utilization === 'number'
64      ? [{ label, percent: window.utilization, resetsAt: window.resets_at ?? undefined }]
65      : [],
66  )
67}
68
69type RawMoney = { amount_minor?: unknown; currency?: unknown; exponent?: unknown } | null
70
71/** An amount as the endpoint writes it, or undefined when any part is missing. */
72function moneyOf(raw: RawMoney | undefined): Money | undefined {
73  if (!raw || typeof raw.amount_minor !== 'number' || typeof raw.currency !== 'string' || typeof raw.exponent !== 'number') return undefined
74
75  return { minor: raw.amount_minor, currency: raw.currency, exponent: raw.exponent }
76}
77
78/**
79 * What the account spent past its plan, from the usage endpoint's `spend`:
80 * shown only when spending is on or something was spent, and only with every
81 * part of the amount given. Nothing is estimated.
82 */
83export function parseSpend(body: unknown): SpendView | undefined {
84  const spend = (body as { spend?: { used?: RawMoney; limit?: RawMoney; enabled?: unknown } | null } | null)?.spend
85  const used = moneyOf(spend?.used)
86  if (!spend || !used || (spend.enabled !== true && used.minor === 0)) return undefined
87  const limit = moneyOf(spend.limit)
88
89  return limit ? { used, limit } : { used }
90}
91
92/** An amount in its currency's units, as many decimals as the endpoint says: `12.34 USD`. */
93export function moneyText(money: Money): string {
94  return `${(money.minor / 10 ** money.exponent).toFixed(money.exponent)} ${money.currency}`
95}
96
97/** The usage request: with a bearer token, or with the session's own credential handle. */
98export function usageInit(auth: { token: string } | { handle: string }): HttpInit {
99  if ('handle' in auth) return { headers: { 'anthropic-beta': OAUTH_BETA }, auth: auth.handle }
100
101  return { headers: { 'anthropic-beta': OAUTH_BETA, Authorization: `Bearer ${auth.token}` } }
102}
103
104/** Whether a token expires within `marginMs` (five minutes unless said): refreshed before it is used. */
105export function needsRefresh(credential: Credential, now: number, marginMs = EXPIRY_MARGIN_MS): boolean {
106  return credential.claudeAiOauth.expiresAt - marginMs <= now
107}
108
109export function refreshInit(credential: Credential): HttpInit {
110  const oauth = credential.claudeAiOauth
111
112  return {
113    method: 'POST',
114    headers: { 'Content-Type': 'application/json' },
115    body: JSON.stringify({
116      grant_type: 'refresh_token',
117      refresh_token: oauth.refreshToken,
118      client_id: CLIENT_ID,
119      scope: (oauth.scopes ?? []).join(' '),
120    }),
121  }
122}
123
124/** The credential after a refresh; the server rotates the refresh token, so it must be saved. */
125export function applyRefresh(credential: Credential, responseText: string, now: number): Credential {
126  const body = JSON.parse(responseText) as { access_token?: string; refresh_token?: string; expires_in?: number }
127  if (typeof body.access_token !== 'string' || typeof body.expires_in !== 'number') {
128    throw new AnthropicError('token refresh returned no access token')
129  }
130  const oauth = credential.claudeAiOauth
131
132  return {
133    ...credential,
134    claudeAiOauth: {
135      ...oauth,
136      accessToken: body.access_token,
137      refreshToken: body.refresh_token ?? oauth.refreshToken,
138      expiresAt: now + body.expires_in * 1000,
139    },
140  }
141}
142
143/** Whose a token is, as the profile endpoint answers. */
144export type TokenOwner = {
145  accountUuid: string
146  emailAddress: string
147  organizationUuid?: string
148  organizationName?: string
149}
150
151export function parseProfile(text: string): TokenOwner {
152  const body = JSON.parse(text) as {
153    account?: { uuid?: string; email?: string }
154    organization?: { uuid?: string; name?: string }
155  }
156  if (typeof body.account?.uuid !== 'string' || typeof body.account.email !== 'string') {
157    throw new AnthropicError('profile endpoint named no account')
158  }
159  // The id names a keychain item and a vault file: one that could reach elsewhere is no account.
160  if (!isAccountId(body.account.uuid)) throw new AnthropicError(`profile endpoint named an account id this mod cannot file: ${JSON.stringify(body.account.uuid)}`)
161
162  return {
163    accountUuid: body.account.uuid,
164    emailAddress: body.account.email,
165    organizationUuid: body.organization?.uuid,
166    organizationName: body.organization?.name,
167  }
168}
169
170/**
171 * The reading after a failed lookup. A 429 keeps the previous reading as it
172 * was, only marked stale: the next lookup recovers by itself, so it is no
173 * message the person must read. Any other failure is said in words.
174 */
175export function failedReading(previous: UsageView | undefined, error: unknown, now: number, m: Messages): UsageView {
176  const kept = isLookedUp(previous) ? previous : undefined
177  // The spend kept is the last lookup's too, as the limits are.
178  const spend = kept?.spend ? { spend: kept.spend } : {}
179  if (error instanceof AnthropicError && error.status === 429) {
180    return { limits: kept?.limits ?? [], fetchedAt: kept?.fetchedAt ?? now, isStale: true, source: 'lookup', ...spend }
181  }
182
183  // The limits kept are the last lookup's, and so is the time they were looked up.
184  return { limits: kept?.limits ?? [], fetchedAt: kept?.fetchedAt ?? now, error: describeFailure(error, m), source: 'lookup', ...spend }
185}
186
187/**
188 * The reading of an inactive account whose token Orca keeps and this mod does
189 * not refresh: the last lookup's figures and time stay, marked held, and no
190 * error is said, as nothing failed.
191 */
192export function heldReading(previous: UsageView | undefined, now: number): UsageView {
193  const kept = isLookedUp(previous) ? previous : undefined
194
195  return { limits: kept?.limits ?? [], fetchedAt: kept?.fetchedAt ?? now, isHeld: true, source: 'lookup', ...(kept?.spend ? { spend: kept.spend } : {}) }
196}
197
198/** Whether a reading came from its own account's lookup, the one source trusted for its figures. */
199export function isLookedUp(reading: UsageView | undefined): reading is UsageView {
200  return reading?.source === 'lookup'
201}
202
203/** The readings that came from lookups; whatever else a store or a session held is dropped. */
204export function lookedUpOnly(readings: unknown): Record<string, UsageView> {
205  if (!readings || typeof readings !== 'object') return {}
206
207  return Object.fromEntries(Object.entries(readings as Record<string, UsageView>).filter(([, reading]) => isLookedUp(reading)))
208}
209
210/** One window as Claude Code's own response reported it. */
211export type MeasuredWindow = { kind: string; percentUsed: number; resetsAt?: string }
212
213/**
214 * The reading after Claude Code's own response reported its windows: the
215 * five-hour and weekly figures replaced, every other window (a model's
216 * weekly limit, which responses do not carry) kept from the last lookup.
217 * Only for a response the account in question answered.
218 */
219export function withMeasured(previous: UsageView | undefined, windows: MeasuredWindow[], now: number): UsageView {
220  const measured: LimitView[] = windows.flatMap(window => {
221    if (window.kind === 'five_hour') return [{ label: '5h', percent: window.percentUsed, resetsAt: window.resetsAt }]
222    if (window.kind === 'seven_day') return [{ label: 'wk', percent: window.percentUsed, resetsAt: window.resetsAt }]
223
224    return []
225  })
226  const labels = new Set(measured.map(limit => limit.label))
227  const kept = (isLookedUp(previous) ? previous.limits : []).filter(limit => !labels.has(limit.label))
228
229  // A measured window says nothing of spending: the last lookup's spend stays.
230  const spend = isLookedUp(previous) && previous.spend ? { spend: previous.spend } : {}
231
232  return { limits: [...measured, ...kept], fetchedAt: now, source: 'lookup', ...spend }
233}
234
235/** A failure as the pane shows it. */
236export function describeFailure(error: unknown, m: Messages): string {
237  if (error instanceof AnthropicError && (error.status === 400 || error.status === 401)) return m.authExpired
238  if (error instanceof AnthropicError && error.status !== undefined) return m.serverError(error.status)
239
240  return error instanceof Error ? error.message : String(error)
241}
242
243/**
244 * Whether the configured account's saved login may be put back in place of a
245 * rejected one: there is one, it is not the token rejected, it works without a
246 * refresh (several sessions refreshing it at once would spend it), and this
247 * session did not put one back within `gapMs`.
248 */
249export function mayHeal(saved: Credential | null, rejected: Credential, now: number, healedAt: number, gapMs: number): saved is Credential {
250  if (saved === null || now - healedAt < gapMs) return false
251
252  return saved.claudeAiOauth.accessToken !== rejected.claudeAiOauth.accessToken && !needsRefresh(saved, now)
253}
254
hooks/cleanup.ts 208 lines
1import type { StorageView } from '../types'
2import { countUsage, forgetTranscripts, loadUsageIndex } from './count'
3import type { CountContext } from './count'
4import { claudeDirectory, platformOf } from './credentials'
5import type { Io } from './io'
6import { message } from './io'
7import { removeTreeArgv } from './shared/files'
8import { byteSize, cleanupPlan, cleanupTargets, confirmedSessions, sessionIdsInCommands, sessionsOf, summarizeStorage } from './storage'
9import type { StorageFile, StorageSession } from './storage'
10import { projectOf } from './usage'
11
12/**
13 * What Claude Code keeps under its config directory, and the cleanup of idle
14 * sessions. A cleanup deletes only the sessions its dialog named when the
15 * person confirmed it, never this session nor one a running Claude Code
16 * process resumed, and counts every transcript first so their tokens stay.
17 */
18
19/** What the Storage tab reads and shows beyond the machine. */
20export type CleanupContext = {
21  io: Io
22  count: CountContext
23  storage: (view: StorageView) => Promise<void>
24  cleanupDays: () => Promise<number>
25  sessionId: () => Promise<string>
26  /** `cleanupPeriodDays` from Claude Code's settings, when set. */
27  autoCleanupDays: () => Promise<number | undefined>
28  homePath: () => string
29}
30
31/** Claude Code's own default for `cleanupPeriodDays`. */
32const AUTO_CLEANUP_DEFAULT_DAYS = 30
33/** How deep the Storage tab walks the projects folder: tool output sits in `<project>/<session>/tool-results/`. */
34const STORAGE_DEPTH = 6
35/** Project folders the Storage tab names: as many as it lists. */
36const STORAGE_PROJECTS_NAMED = 8
37/** Other folders the Storage tab lists, the largest first, and the smallest it lists. */
38const STORAGE_FOLDERS_SHOWN = 8
39const STORAGE_FOLDER_MIN_BYTES = 1024 * 1024
40/** Paths one deletion command takes at a time. */
41const DELETE_BATCH = 40
42
43/** The files under the projects folder as last measured, for the cleanup to choose from. */
44let storageFiles: StorageFile[] = []
45/** The sessions the cleanup dialog named, as `<folder>/<session>`: all a cleanup may delete. */
46let confirmed = new Set<string>()
47
48/** Every file under the projects folder, with its size and when it last changed. */
49async function projectFiles(io: Io, root: string): Promise<StorageFile[]> {
50  if (!(await io.exists(root))) return []
51  const files: StorageFile[] = []
52  const walk = async (relative: string, depth: number): Promise<void> => {
53    for (const entry of await io.list(relative === '' ? root : `${root}/${relative}`)) {
54      const child = relative === '' ? entry.name : `${relative}/${entry.name}`
55      if (entry.kind === 'dir' && !entry.isLink && depth < STORAGE_DEPTH) await walk(child, depth + 1)
56      else if (entry.kind === 'file') files.push({ relative: child, size: entry.size, mtimeMs: entry.mtimeMs })
57    }
58  }
59  await walk('', 1)
60
61  return files
62}
63
64/** The sizes of the config directory's other folders, by `du`; none where there is no POSIX shell. */
65async function otherFolders(io: Io, directory: string): Promise<{ name: string; bytes: number }[]> {
66  const names = (await io.list(directory)).filter(entry => entry.kind === 'dir' && entry.name !== 'projects').map(entry => entry.name)
67  if (names.length === 0) return []
68  const { exitCode, stdout } = await io.run(['du', '-sk', '--', ...names.map(name => `${directory}/${name}`)], { timeoutMs: 60_000 })
69  if (exitCode !== 0 && stdout.trim() === '') return []
70
71  return stdout
72    .split('\n')
73    .map(line => line.split('\t'))
74    .filter(parts => parts.length === 2 && /^\d+$/.test(parts[0] ?? ''))
75    .map(([kb = '0', path = '']) => ({ name: path.slice(directory.length + 1), bytes: Number(kb) * 1024 }))
76    .filter(folder => folder.bytes >= STORAGE_FOLDER_MIN_BYTES)
77    .sort((a, b) => b.bytes - a.bytes)
78    .slice(0, STORAGE_FOLDERS_SHOWN)
79}
80
81/** The project a folder's newest session transcript worked in, read from its first `cwd`; undefined when none is found. */
82async function recordedProject(io: Io, root: string, folder: string, files: StorageFile[]): Promise<string | undefined> {
83  const newest = files
84    // A session's own transcript: a subagent's may have worked in a worktree of its own.
85    .filter(file => file.relative.startsWith(`${folder}/`) && file.relative.endsWith('.jsonl') && file.relative.split('/').length === 2)
86    .sort((a, b) => b.mtimeMs - a.mtimeMs)[0]
87  if (!newest) return undefined
88  const { exitCode, stdout } = await io.run(['sh', '-c', 'head -c 262144 "$1" | grep -a -o -m 1 \'"cwd":"[^"]*"\'', 'sh', `${root}/${newest.relative}`], { timeoutMs: 10_000 })
89  const cwd = exitCode === 0 ? /"cwd":"([^"]*)"/.exec(stdout)?.[1] : undefined
90
91  return cwd ? projectOf(cwd.replace(/\\\\/g, '\\')) : undefined
92}
93
94/** Measures what the config directory holds, for the Storage tab. */
95export async function measureStorage(ctx: CleanupContext): Promise<void> {
96  const { io } = ctx
97  const directory = await claudeDirectory(io)
98  const files = await projectFiles(io, `${directory}/projects`)
99  storageFiles = files
100  const summary = summarizeStorage(files)
101  // A folder is named after the project its sessions worked in, as the usage count recorded it.
102  const { index } = await loadUsageIndex(ctx.count)
103  const votes = new Map<string, Map<string, number>>()
104  for (const session of sessionsOf(files)) {
105    const project = index.sessions[session.session]?.projects[0]
106    if (!project) continue
107    const tally = votes.get(session.folder) ?? new Map<string, number>()
108    tally.set(project, (tally.get(project) ?? 0) + 1)
109    votes.set(session.folder, tally)
110  }
111  const voted = (folder: string) => [...(votes.get(folder)?.entries() ?? [])].sort((a, b) => b[1] - a[1])[0]?.[0]
112  // A folder the count knows nothing of is named from the directory its newest transcript records.
113  const names = new Map<string, string>()
114  for (const project of summary.projects.slice(0, STORAGE_PROJECTS_NAMED)) {
115    const name = voted(project.folder) ?? (await recordedProject(io, `${directory}/projects`, project.folder, files))
116    if (name) names.set(project.folder, name)
117  }
118  const configured = await ctx.autoCleanupDays()
119  let folders: { name: string; bytes: number }[] = []
120  try {
121    folders = await otherFolders(io, directory)
122  } catch (error) {
123    io.log(message(error))
124  }
125  await ctx.storage({
126    ...summary,
127    projects: summary.projects.map(project => ({ ...project, name: names.get(project.folder) ?? project.folder })),
128    folders,
129    autoDays: configured ?? AUTO_CLEANUP_DEFAULT_DAYS,
130    isAutoDefault: configured === undefined,
131    root: directory.replace(ctx.homePath(), '~'),
132  })
133}
134
135/** The sessions running Claude Code processes resumed by id; none where the processes cannot be listed. */
136async function runningSessions(io: Io): Promise<string[]> {
137  const { isWindows } = await platformOf(io)
138  const argv = isWindows
139    ? ['powershell.exe', '-NoProfile', '-NonInteractive', '-Command', 'Get-CimInstance Win32_Process | ForEach-Object { $_.CommandLine }']
140    : ['ps', '-axo', 'command=']
141  try {
142    const listed = await io.run(argv, { timeoutMs: 10_000 })
143
144    return listed.exitCode === 0 ? sessionIdsInCommands(listed.stdout) : []
145  } catch (error) {
146    io.log(message(error))
147
148    return []
149  }
150}
151
152/** The sessions a cleanup at the chosen age would delete, as last measured: never this one, nor one a running process resumed. */
153export async function plannedCleanup(ctx: CleanupContext): Promise<{ sessions: StorageSession[]; bytes: number }> {
154  const keep = [await ctx.sessionId(), ...(await runningSessions(ctx.io))]
155
156  return cleanupPlan(sessionsOf(storageFiles), await ctx.cleanupDays(), await ctx.io.now(), keep)
157}
158
159/** What the cleanup dialog names: the sessions and their bytes as measured when it opened. */
160let asked: { count: number; bytes: number } = { count: 0, bytes: 0 }
161
162/** Names what the dialog shows, measured now, as all a cleanup confirmed from it may delete. */
163export async function askCleanup(ctx: CleanupContext): Promise<{ count: number; bytes: number }> {
164  await measureStorage(ctx)
165  const plan = await plannedCleanup(ctx)
166  confirmed = new Set(plan.sessions.map(session => `${session.folder}/${session.session}`))
167  asked = { count: plan.sessions.length, bytes: plan.bytes }
168
169  return asked
170}
171
172/** What the open cleanup dialog names. */
173export function askedCleanup(): { count: number; bytes: number } {
174  return asked
175}
176
177/**
178 * Deletes the sessions the confirmed dialog named that are still idle now:
179 * each transcript and the session's folder. Every path is checked to lie
180 * under the projects folder first; one that does not stops the whole cleanup
181 * before anything is deleted. The usage figures already counted stay.
182 */
183export async function cleanUp(ctx: CleanupContext, words: { nothing: (days: number) => string; uncounted: (files: number) => string; needsShell: string; done: (count: number, size: string) => string }): Promise<string> {
184  const { io } = ctx
185  // Measured again now: a session resumed since the dialog opened is no longer idle.
186  await measureStorage(ctx)
187  const sessions = confirmedSessions((await plannedCleanup(ctx)).sessions, confirmed)
188  confirmed = new Set()
189  if (sessions.length === 0) return words.nothing(await ctx.cleanupDays())
190  // Every transcript is counted before any is deleted, so the usage figures keep their tokens;
191  // one that could not be counted stops the cleanup.
192  const uncounted = await countUsage(ctx.count, true)
193  if ((await ctx.count.usageError.get()) !== null) throw new Error(words.needsShell)
194  if (uncounted.length > 0) throw new Error(words.uncounted(uncounted.length))
195  const root = `${await claudeDirectory(io)}/projects`
196  const paths = cleanupTargets(root, sessions.flatMap(session => session.paths))
197  const { isWindows } = await platformOf(io)
198  for (let start = 0; start < paths.length; start += DELETE_BATCH) {
199    const { exitCode, stderr } = await io.run(removeTreeArgv(paths.slice(start, start + DELETE_BATCH), isWindows), { timeoutMs: 120_000 })
200    if (exitCode !== 0) throw new Error(`deleting sessions exited ${exitCode}: ${stderr.trim()}`)
201  }
202  // The count forgets the deleted transcripts' offsets; their tokens stay counted.
203  await forgetTranscripts(ctx.count, paths)
204  await measureStorage(ctx)
205
206  return words.done(sessions.length, byteSize(sessions.reduce((sum, session) => sum + session.bytes, 0)))
207}
208