@2cmddev/2cmd 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/.opencode/command/2cmd-audit.md +5 -0
  2. package/.opencode/command/2cmd-debt.md +5 -0
  3. package/.opencode/command/2cmd-gain.md +5 -0
  4. package/.opencode/command/2cmd-help.md +5 -0
  5. package/.opencode/command/2cmd-review.md +5 -0
  6. package/.opencode/command/2cmd.md +5 -0
  7. package/.opencode/plugins/2cmd-frontmatter.cjs +63 -0
  8. package/.opencode/plugins/2cmd.mjs +206 -0
  9. package/.opencode/plugins/index.js +4 -0
  10. package/.qoder/rules/2cmd.md +31 -0
  11. package/.qoder-plugin/plugin.json +16 -0
  12. package/.zcode-plugin/plugin.json +13 -0
  13. package/AGENTS.md +33 -0
  14. package/LICENSE +22 -0
  15. package/README.md +133 -2
  16. package/codex/answer.mjs +164 -0
  17. package/codex/data.mjs +31 -0
  18. package/codex/pty.py +80 -0
  19. package/codex/stats.mjs +105 -0
  20. package/codex/terminal.mjs +388 -0
  21. package/dsh/LICENSE +22 -0
  22. package/dsh/board.js +782 -0
  23. package/dsh/build.mjs +47 -0
  24. package/dsh/bundle.json +2104 -0
  25. package/dsh/client.js +877 -0
  26. package/dsh/cordis.patch.yml +3 -0
  27. package/dsh/index.js +185 -0
  28. package/dsh/ledger.js +50 -0
  29. package/dsh/market.js +152 -0
  30. package/dsh/package.json +24 -0
  31. package/dsh/prices.json +1812 -0
  32. package/dsh/settings-text.mjs +520 -0
  33. package/dsh/settings.js +42 -0
  34. package/dsh/stats.js +106 -0
  35. package/dsh/store.js +32 -0
  36. package/dsh/update-prices.mjs +9 -0
  37. package/dsh/update.js +27 -0
  38. package/dsh/voice-helper/Info.plist +13 -0
  39. package/dsh/voice-helper/Transcript.swift +21 -0
  40. package/dsh/voice-helper/build.sh +10 -0
  41. package/dsh/voice-helper/main.swift +70 -0
  42. package/dsh/voice-helper/test.swift +17 -0
  43. package/dsh/voice.js +63 -0
  44. package/hooks/2cmd-activate.js +219 -0
  45. package/hooks/2cmd-antigravity.js +64 -0
  46. package/hooks/2cmd-band-import.js +305 -0
  47. package/hooks/2cmd-config.js +186 -0
  48. package/hooks/2cmd-instructions.js +104 -0
  49. package/hooks/2cmd-map.js +200 -0
  50. package/hooks/2cmd-mode-tracker.js +248 -0
  51. package/hooks/2cmd-runtime.js +245 -0
  52. package/hooks/2cmd-statusline.ps1 +24 -0
  53. package/hooks/2cmd-statusline.sh +18 -0
  54. package/hooks/2cmd-subagent.js +100 -0
  55. package/hooks/band/board.ts +720 -0
  56. package/hooks/band/buttons.ts +60 -0
  57. package/hooks/band/i18n/de.ts +149 -0
  58. package/hooks/band/i18n/en.ts +150 -0
  59. package/hooks/band/i18n/es.ts +149 -0
  60. package/hooks/band/i18n/fr.ts +149 -0
  61. package/hooks/band/i18n/index.ts +42 -0
  62. package/hooks/band/i18n/ja.ts +149 -0
  63. package/hooks/band/i18n/ko.ts +149 -0
  64. package/hooks/band/i18n/pt.ts +149 -0
  65. package/hooks/band/i18n/ru.ts +149 -0
  66. package/hooks/band/i18n/vi.ts +149 -0
  67. package/hooks/band/i18n/zh-Hans.ts +149 -0
  68. package/hooks/band/i18n/zh-Hant.ts +149 -0
  69. package/hooks/band/logo.ts +3 -0
  70. package/hooks/band/metrics.ts +373 -0
  71. package/hooks/band/register.tsx +681 -0
  72. package/hooks/band/types.d.ts +45 -0
  73. package/hooks/band/windows-board.mjs +20 -0
  74. package/hooks/claude-band.json +6 -0
  75. package/hooks/claude-codex-hooks.json +41 -0
  76. package/hooks/codebuddy-hooks.json +20 -0
  77. package/hooks/copilot-hooks.json +21 -0
  78. package/hooks/cursor-hooks.json +17 -0
  79. package/hooks/qoder-hooks.json +26 -0
  80. package/hooks/zcode-hooks.json +26 -0
  81. package/package.json +56 -4
  82. package/pi-extension/index.js +258 -0
  83. package/pi-extension/names.js +19 -0
  84. package/pi-extension/package.json +8 -0
  85. package/scripts/cursor-hooks.js +145 -0
  86. package/scripts/uninstall.js +92 -0
  87. package/skills/2cmd/SKILL.md +55 -0
  88. package/skills/2cmd-audit/SKILL.md +105 -0
  89. package/skills/2cmd-debt/SKILL.md +46 -0
  90. package/skills/2cmd-gain/SKILL.md +53 -0
  91. package/skills/2cmd-help/SKILL.md +87 -0
  92. package/skills/2cmd-review/SKILL.md +143 -0
  93. package/skills/plugin.json +5 -0
@@ -0,0 +1,681 @@
1
+ import { atom, read, update } from 'claude-code'
2
+ import type { EngineInterface, Register } from 'claude-code'
3
+
4
+ import { boardHtml, tasksFrom, testsText as translateTests } from './board'
5
+ import { DEFAULT_BUTTONS, buttonText, commandDraft, normalizeButtons } from './buttons'
6
+ import type { PanelButton } from './buttons'
7
+ import { fill, locale } from './i18n'
8
+ import type { Locale } from './i18n'
9
+ import type { Band } from './types'
10
+ import { windowsBoardCommand } from './windows-board.mjs'
11
+ import type { Col } from './metrics'
12
+ import {
13
+ GREP_DEFS,
14
+ NO_CACHE,
15
+ NO_TOKENS,
16
+ addCache,
17
+ addTokens,
18
+ addedLines,
19
+ chipSvg,
20
+ chipWidth,
21
+ callsIn,
22
+ defsIn,
23
+ elapsed,
24
+ fmtTokens,
25
+ hitRate,
26
+ hits,
27
+ inProject,
28
+ isCode,
29
+ isSource,
30
+ isTestCommand,
31
+ mainModel,
32
+ markdown,
33
+ metricsSvg,
34
+ MODEL_PATTERN,
35
+ parseDefs,
36
+ resume,
37
+ snapshot,
38
+ switchSvg,
39
+ switchWidth,
40
+ testCounts,
41
+ sessionTitle,
42
+ taskKey,
43
+ testsLabel,
44
+ TITLE_RECORD,
45
+ totalTokens,
46
+ upsertCsv,
47
+ webhookRequest,
48
+ } from './metrics'
49
+
50
+ const LEVELS = ['off', 'hindsight', 'reuse', 'pushback', 'scout']
51
+ const MODES = LEVELS.slice(1)
52
+ // 主题色,只在支持按钮文字颜色的界面生效,桌面端的颜色画在 switchSvg 里;pushback 用橙色(claude),红色会让人以为出错。
53
+ const LEVEL_COLORS: Record<string, string> = { off: 'inactive', hindsight: 'success', reuse: 'suggestion', pushback: 'claude', scout: 'autoAccept' }
54
+ const EMPTY: Band = {
55
+ level: 'off',
56
+ pending: '',
57
+ lastLevel: 'reuse',
58
+ model: '',
59
+ cost: 0,
60
+ spent: 0,
61
+ turns: 0,
62
+ turnCosts: [],
63
+ tokens: NO_TOKENS,
64
+ cache: NO_CACHE,
65
+ busyMs: 0,
66
+ name: '',
67
+ project: '',
68
+ session: '',
69
+ transcript: '',
70
+ reused: [],
71
+ created: [],
72
+ removed: [],
73
+ openCallers: [],
74
+ tests: { state: 'none' },
75
+ details: false,
76
+ buttons: [...DEFAULT_BUTTONS],
77
+ }
78
+ // The counters of one task: what a new session or /clear starts over.
79
+ const TASK = {
80
+ spent: 0,
81
+ turns: 0,
82
+ turnCosts: [],
83
+ tokens: NO_TOKENS,
84
+ cache: NO_CACHE,
85
+ busyMs: 0,
86
+ name: '',
87
+ model: '',
88
+ reused: [],
89
+ created: [],
90
+ removed: [],
91
+ openCallers: [],
92
+ tests: { state: 'none' as const },
93
+ }
94
+ const band = atom({ plugin: '2cmd', key: 'band' } as const, EMPTY)
95
+ // State kept from an older version of the band lacks newer fields.
96
+ const load = async ($: EngineInterface): Promise<Band> => ({ ...EMPTY, ...(await read($, band)) })
97
+
98
+ // 所有更新档位的地方都用它,选择停用时保留最近选过的启用档位。
99
+ const withLevel = (b: Band, level: string, pending: string): Band => {
100
+ const chosen = pending || level
101
+ return { ...b, level, pending, lastLevel: chosen === 'off' ? b.lastLevel : chosen }
102
+ }
103
+
104
+ const union = (a: string[], b: string[]) => [...new Set([...a, ...b])]
105
+ const base = (path: string) => path.replace(/\/+$/, '').split('/').pop() ?? path
106
+
107
+ // Windows sets USERPROFILE, not HOME.
108
+ const home = async ($: EngineInterface) => (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
109
+ const claudeDir = async ($: EngineInterface) => (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${await home($)}/.claude`
110
+
111
+ // `/2cmd band` (the mode tracker) leaves "off" here to hide the band. Absent flag = shown.
112
+ async function bandHidden($: EngineInterface): Promise<boolean> {
113
+ try {
114
+ return (await $.fs.read(`${await claudeDir($)}/.2cmd-band`)).trim() === 'off'
115
+ } catch {
116
+ return false
117
+ }
118
+ }
119
+
120
+ // The level 2cmd's own hooks write. Absent flag = off.
121
+ // shortcut: the shared flag the statusline reads, so two sessions in different repos show the last switch; read the per-project flag if that matters.
122
+ async function readLevel($: EngineInterface): Promise<string> {
123
+ const dir = await claudeDir($)
124
+ try {
125
+ const level = (await $.fs.read(`${dir}/.2cmd-active`)).trim()
126
+ return LEVELS.includes(level) ? level : 'off'
127
+ } catch {
128
+ return 'off'
129
+ }
130
+ }
131
+
132
+ // 点击只把选择存到这里,下次发消息时由 2cmd-mode-tracker.js 读取、应用并删除;每个会话一个文件。
133
+ const pendingFile = async ($: EngineInterface) => `${await claudeDir($)}/2cmd-pending/${await $.session.id()}`
134
+
135
+ async function readPending($: EngineInterface, level: string): Promise<string> {
136
+ const pending = (await $.fs.read(await pendingFile($)).catch(() => '')).trim()
137
+ return LEVELS.includes(pending) && pending !== level ? pending : ''
138
+ }
139
+
140
+ // The same commands a person types, so 2cmd's own skills and hooks stay the only logic.
141
+
142
+ type Options = { readonly [field: string]: unknown }
143
+
144
+ // The session's sidebar name. grep, because $.fs.read refuses files over 4 MiB and transcripts grow past that.
145
+ // shortcut: without grep (Windows) only a transcript under 4 MiB is read; findstr would lift that.
146
+ async function readTitle($: EngineInterface, transcript: string): Promise<string | undefined> {
147
+ if (transcript === '') return undefined
148
+ const grep = await $.process.run(['grep', '-F', TITLE_RECORD, transcript]).catch(() => undefined)
149
+ const text = grep !== undefined && grep.exitCode <= 1 ? grep.stdout : await $.fs.read(transcript).catch(() => '')
150
+ return sessionTitle(text)
151
+ }
152
+
153
+ // The model that wrote most of the session's replies, so the board can tell models apart.
154
+ async function readModel($: EngineInterface, transcript: string): Promise<string> {
155
+ if (transcript === '') return ''
156
+ const grep = await $.process.run(['grep', '-o', MODEL_PATTERN, transcript]).catch(() => undefined)
157
+ return grep?.exitCode === 0 ? mainModel(grep.stdout) : ''
158
+ }
159
+
160
+ // Where Claude Code keeps the session's transcript: on managed, Team and Enterprise machines its cc-plugin-sec-default skips every classic.* hook, so no hook hands the path over.
161
+ // First the folder its rule names, then every project folder: it hashes names past 200 characters, and /cd, worktrees and /resume can put the file elsewhere.
162
+ // shortcut: with persistence off there is no file, so every turn checks every folder, read the path from the engine once it offers one.
163
+ async function findTranscript($: EngineInterface, session: string): Promise<string> {
164
+ const projects = `${await claudeDir($)}/projects`
165
+ const exists = (file: string) => $.fs.exists(file).catch(() => false)
166
+ const root = await $.session.root().catch(() => '')
167
+ const named = `${projects}/${root.replace(/[^a-zA-Z0-9]/g, '-')}/${session}.jsonl`
168
+ if (root !== '' && (await exists(named))) return named
169
+ const dirs = (await $.fs.list(projects).catch(() => [])).filter(d => d.kind === 'dir')
170
+ // One at a time: thousands of checks in flight at once are slower than in turn.
171
+ for (const dir of dirs) {
172
+ const file = `${projects}/${dir.name}/${session}.jsonl`
173
+ if (await exists(file)) return file
174
+ }
175
+ return ''
176
+ }
177
+
178
+ // Where the task ledgers and the board live.
179
+ // shortcut: ~/.config only (XDG respected); Windows would want %APPDATA%.
180
+ async function ledgerDir($: EngineInterface) {
181
+ return `${(await $.env.get('XDG_CONFIG_HOME')) ?? `${await home($)}/.config`}/2cmd/band`
182
+ }
183
+
184
+ const ledgerFile = (dir: string, project: string) => `${dir}/${project.replace(/[^\w.-]/g, '_')}.csv`
185
+
186
+ // After every turn: the task's row in a CSV per project, and the same row to a webhook if one is set.
187
+ async function record($: EngineInterface, b: Band, options: Options, loc: Locale) {
188
+ const { t } = loc
189
+ const startedAt = (await $.session.usage()).startedAt
190
+ const row = snapshot(b, startedAt)
191
+ if (options.ledger !== false && b.project !== '') {
192
+ const dir = await ledgerDir($)
193
+ const file = ledgerFile(dir, b.project)
194
+ const existing = await $.fs.read(file).catch(() => '')
195
+ // $.fs.write creates the directory: no mkdir, which Windows does not have.
196
+ await $.fs.write(file, upsertCsv(existing, row))
197
+ // The board is a plain file a refresh rereads, so it is rebuilt with every row.
198
+ await writeBoard($, dir, loc)
199
+ }
200
+ const url = typeof options.webhookUrl === 'string' ? options.webhookUrl.trim() : ''
201
+ if (url !== '') {
202
+ const token = typeof options.webhookToken === 'string' ? options.webhookToken.trim() : ''
203
+ const request = webhookRequest(url, token, options.sendNames !== false, row)
204
+ if ('refused' in request) {
205
+ $.ui.status(`2Cmd: ${t[request.refused]}`)
206
+ return
207
+ }
208
+ // Not awaited: a slow endpoint must never hold up the turn.
209
+ void $.http
210
+ .fetch(request.url, request.init)
211
+ .then(r => $.ui.status(r.ok ? undefined : `2Cmd: ${fill(t.hookStatus, { n: r.status })}`))
212
+ .catch(() => $.ui.status(`2Cmd: ${t.hookDown}`))
213
+ }
214
+ }
215
+
216
+ // Builds board.html from every project's ledger.
217
+ async function writeBoard($: EngineInterface, dir: string, loc: Locale) {
218
+ const entries = await $.fs.list(dir).catch(() => [])
219
+ const texts = await Promise.all(entries.filter(f => f.kind === 'file' && f.name.endsWith('.csv')).map(f => $.fs.read(`${dir}/${f.name}`).catch(() => '')))
220
+ const file = `${dir}/board.html`
221
+ const buttons = normalizeButtons(await $.store.get('buttons'), 'claude')
222
+ await $.fs.write(file, boardHtml(texts.flatMap(tasksFrom), await $.clock.now(), loc, undefined, { host: 'claude', buttons }))
223
+ return file
224
+ }
225
+
226
+ // Builds the board fresh and opens it in the browser.
227
+ async function openBoard($: EngineInterface, loc: Locale) {
228
+ const file = await writeBoard($, await ledgerDir($), loc)
229
+ const windows = (await $.env.get('OS')) === 'Windows_NT'
230
+ if (windows) {
231
+ const { argv, env } = windowsBoardCommand(file)
232
+ if ((await $.process.run(argv, { env })).exitCode !== 0) throw new Error('Could not open the Windows board')
233
+ return
234
+ }
235
+ const mac = (await $.process.run(['uname'])).stdout.trim() === 'Darwin'
236
+ await $.process.run([mac ? 'open' : 'xdg-open', file])
237
+ }
238
+
239
+ // Sets the band up for a session (level, project, task row, cost baseline); returns the definitions that exist now.
240
+ async function start($: EngineInterface): Promise<Map<string, string>> {
241
+ const grep = await $.process.run(['git', 'grep', '--untracked', '-nE', GREP_DEFS]).catch(() => undefined)
242
+ const level = await readLevel($)
243
+ const pending = await readPending($, level)
244
+ const details = (await $.store.get('details')) === true
245
+ const buttons = normalizeButtons(await $.store.get('buttons'), 'claude')
246
+ const repo = await $.session.repo().catch(() => null)
247
+ const project = base(repo?.root ?? (await $.session.cwd()))
248
+ const session = await $.session.id()
249
+ // The cost so far is the baseline for the last turn's own cost.
250
+ const usage = await $.session.usage().catch(() => undefined)
251
+ const csv = usage ? await $.fs.read(ledgerFile(await ledgerDir($), project)).catch(() => '') : ''
252
+ const key = usage ? taskKey(session, usage.startedAt) : ''
253
+ await update($, band, b => resume({ ...withLevel({ ...EMPTY, ...b }, level, pending), details, buttons, project, session, cost: usage?.cost?.usd ?? b.cost }, csv, key))
254
+ return grep?.exitCode === 0 ? parseDefs(grep.stdout) : new Map()
255
+ }
256
+
257
+ export const register: Register = (on, options) => {
258
+ const loc = locale(options.language)
259
+ const { t, widths } = loc
260
+ const names: Record<string, string> = { off: t.modeOff, hindsight: t.hindsight, reuse: t.reuse, pushback: t.pushback, scout: t.scout }
261
+ const tips: Record<string, string> = {
262
+ on: t.tipOn,
263
+ off: t.tipOff,
264
+ hindsight: t.tipHindsight,
265
+ reuse: t.tipReuse,
266
+ pushback: t.tipPushback,
267
+ scout: t.tipScout,
268
+ level: t.tipLevel,
269
+ fix: t.tipFix,
270
+ commit: t.tipCommit,
271
+ push: t.tipPush,
272
+ copy: t.tipCopy,
273
+ review: t.tipReview,
274
+ audit: t.tipAudit,
275
+ board: t.tipBoard,
276
+ expand: t.tipExpand,
277
+ collapse: t.tipCollapse,
278
+ }
279
+ // Definitions that existed when the session started: what new code can reuse.
280
+ let known = new Map<string, string>()
281
+ // 滑块动画的起点、终点和开始时间。桌面端刷新时可能重新加载底图并重播动画,所以滑完(0.2 秒)后要去掉起点。
282
+ let slide = { from: '', to: '', live: true, at: 0 }
283
+
284
+ on('session.start', async ($, e, next) => {
285
+ known = await start($)
286
+ // The board's Buttons page makes this command; pasting it sets the panel buttons without asking the AI.
287
+ await $.command.register({ name: '2cmd-buttons', description: 'Set the 2Cmd panel buttons (from the board)', argumentHint: '<from the board> | reset' }).catch(() => undefined)
288
+ return next(e)
289
+ }).catch(($, e, next) => next(e))
290
+
291
+ on('command.run', { command: '2cmd-buttons' }, async ($, e) => {
292
+ const args = e.args.trim()
293
+ let value: unknown = []
294
+ if (args !== 'reset' && args !== '') {
295
+ try {
296
+ value = JSON.parse(args)
297
+ } catch {
298
+ return { text: `2Cmd: ${t.btnInvalid}`, isTextDisplayOnly: true as const }
299
+ }
300
+ }
301
+ const buttons = normalizeButtons(value, 'claude')
302
+ await $.store.set('buttons', buttons)
303
+ await update($, band, b => ({ ...EMPTY, ...b, buttons }))
304
+ await writeBoard($, await ledgerDir($), loc).catch(() => undefined)
305
+ return { text: `2Cmd: ${t.btnApplied}`, isTextDisplayOnly: true as const }
306
+ })
307
+
308
+ // /clear, /resume and /branch go on under another session id with an empty band and no session.start, so the band
309
+ // showed "off" until the first turn ended. Set it up again once one of them has moved the session.
310
+ // Only these commands: the engine labels a command's output with every plugin its hook chain ran through, so a hook on
311
+ // every command printed "2cmd+<plugin>:" before other plugins' commands.
312
+ // shortcut: after /clear, 2cmd-activate.js may reset the flag to the default level after this, so a level switched
313
+ // before /clear can show until the first turn ends; a session skips a plugin's classic.SessionStart hook, the one later point.
314
+ on('command.run', { command: ['clear', 'resume', 'branch'] }, async ($, e, next) => {
315
+ const session = await $.session.id()
316
+ const result = await next(e)
317
+ if ((await $.session.id()) !== session) known = await start($).catch(() => known)
318
+ return result
319
+ }).catch(($, e, next) => next(e))
320
+
321
+ // /clear starts a new task: the counters start over, the cost baseline stays.
322
+ on('session.end', async ($, e, next) => {
323
+ if (e.reason === 'clear') await update($, band, b => ({ ...EMPTY, ...b, ...TASK }))
324
+ return next(e)
325
+ }).catch(($, e, next) => next(e))
326
+
327
+ // The first prompt names the task until the session has a sidebar name.
328
+ on('prompt.submit', async ($, e, next) => {
329
+ const text = e.text.trim()
330
+ if (e.origin.kind !== 'plugin' && text !== '' && !text.startsWith('/')) {
331
+ const name = (text.split('\n')[0] ?? '').slice(0, 60)
332
+ await update($, band, b => (b.name === '' ? { ...EMPTY, ...b, name } : b))
333
+ }
334
+ if ((await load($)).pending === '') return next(e)
335
+ const result = await next(e)
336
+ // 钩子已经处理完这条消息:按实际文件更新,钩子没运行时仍显示等待生效。
337
+ const level = await readLevel($)
338
+ const pending = await readPending($, level)
339
+ await update($, band, b => withLevel({ ...EMPTY, ...b }, level, pending))
340
+ return result
341
+ }).catch(($, e, next) => next(e))
342
+
343
+ on('tool.call', async ($, e, next) => {
344
+ if (e.tool === 'Bash') {
345
+ const ran = await next(e)
346
+ if (ran.deny === undefined && isTestCommand(e.command)) {
347
+ const tests = { state: ran.isError ? ('fail' as const) : ('pass' as const), ...testCounts(ran.text ?? '') }
348
+ await update($, band, b => ({ ...b, tests }))
349
+ }
350
+ return ran
351
+ }
352
+
353
+ if (e.tool !== 'Edit' && e.tool !== 'Write') return next(e)
354
+
355
+ const file = e.file_path
356
+ // A scratch script outside the project is never reused or called by it (#1300).
357
+ const repo = await $.session.repo().catch(() => null)
358
+ if (!inProject(file, repo?.root ?? (await $.session.cwd()))) return next(e)
359
+ const before = e.tool === 'Write' ? await $.fs.read(file).catch(() => '') : e.old_string
360
+ const after = e.tool === 'Write' ? e.content : e.new_string
361
+ const ran = await next(e)
362
+ if (ran.deny !== undefined || ran.isError) return ran
363
+
364
+ const oldDefs = defsIn(file, before)
365
+ const newDefs = defsIn(file, after)
366
+ // 没读到已有函数时(比如不在 Git 仓库里),算不出复用率,也不记新建,避免误报 0%。
367
+ const created = known.size > 0 && isSource(file) ? newDefs.filter(n => !oldDefs.includes(n)) : []
368
+ const removed = oldDefs.filter(n => !newDefs.includes(n))
369
+ const reused = isSource(file) ? callsIn(addedLines(before, after), known, newDefs) : []
370
+
371
+ await update($, band, b => ({
372
+ ...b,
373
+ reused: union(b.reused, reused),
374
+ created: union(b.created, created),
375
+ removed: union(b.removed, removed),
376
+ tests: isCode(file) && b.tests.state !== 'none' ? { ...b.tests, state: 'stale' as const } : b.tests,
377
+ }))
378
+
379
+ return ran
380
+ }).catch(($, e, next) => next(e))
381
+
382
+ on('turn.complete', async ($, e, next) => {
383
+ const used = e.usage
384
+ if (e.agentId !== undefined) {
385
+ // A subagent's tokens count; its cost is already in the session cost the main turn reads.
386
+ if (used) await update($, band, b => ({ ...EMPTY, ...b, tokens: addTokens(b.tokens ?? NO_TOKENS, used) }))
387
+ return next(e)
388
+ }
389
+
390
+ const usage = await $.session.usage()
391
+ const turns = await $.session.turns()
392
+ const level = await readLevel($)
393
+ const pending = await readPending($, level)
394
+ const { removed, transcript: saved } = await load($)
395
+ const session = await $.session.id()
396
+ // Here, not at start: the first turn writes the file, and a new id (/clear, /resume) or a move (/cd, a worktree) changes it.
397
+ const kept = base(saved) === `${session}.jsonl` && (await $.fs.exists(saved).catch(() => false))
398
+ const transcript = kept ? saved : await findTranscript($, session)
399
+ const title = await readTitle($, transcript)
400
+ const model = await readModel($, transcript)
401
+
402
+ // A removed or renamed definition that is not defined again but still called somewhere.
403
+ // shortcut: name match with git grep, so a same-named call in another module counts too.
404
+ const stillRemoved: string[] = []
405
+ const open: string[] = []
406
+ for (const name of removed) {
407
+ const grep = await $.process.run(['git', 'grep', '--untracked', '-nw', '-e', name]).catch(() => undefined)
408
+ const rows = hits(grep?.stdout ?? '')
409
+ if (rows.some(r => defsIn(r.file, r.text.trimStart()).includes(name))) continue
410
+ const call = new RegExp(`(?<![\\w$])${name.replace(/\$/g, '\\$')}\\s*\\(`)
411
+ const refs = rows.filter(r => call.test(r.text)).map(r => `${r.file}:${r.line}`)
412
+ if (refs.length > 0) {
413
+ stillRemoved.push(name)
414
+ open.push(...refs)
415
+ }
416
+ }
417
+
418
+ const b = await update($, band, x => {
419
+ const b = { ...EMPTY, ...x }
420
+ const cost = usage.cost?.usd ?? b.cost
421
+ // A cost below the baseline means the engine started its ledger over.
422
+ const turn = cost >= b.cost ? cost - b.cost : cost
423
+ return {
424
+ ...withLevel(b, level, pending),
425
+ transcript,
426
+ cost,
427
+ // Cost and turns are the session's own totals, so a reload or a second band never starts them over.
428
+ spent: usage.cost?.usd ?? b.spent + turn,
429
+ turns,
430
+ turnCosts: [...b.turnCosts, turn].slice(-20),
431
+ tokens: used ? addTokens(b.tokens, used) : b.tokens,
432
+ cache: used ? addCache(b.cache, used) : b.cache,
433
+ busyMs: b.busyMs + e.durationMs,
434
+ name: title ?? b.name,
435
+ model: model || b.model,
436
+ removed: stillRemoved,
437
+ openCallers: open,
438
+ }
439
+ })
440
+ await record($, b, options, loc).catch(() => $.ui.status(`2Cmd: ${t.ledgerFail}`))
441
+
442
+ return next(e)
443
+ }).catch(($, e, next) => next(e))
444
+
445
+ on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
446
+ if (e.props.hasSurvey || (await bandHidden($))) return next(e)
447
+ // Other mods share this slot: draw theirs below ours instead of replacing it.
448
+ // next(e) rejects only when nothing answers beneath (the test harness): the band still draws.
449
+ const below = await next(e).catch(() => undefined)
450
+
451
+ const b = await load($)
452
+ const shown = b.pending || b.level
453
+ const live = b.pending === ''
454
+ const now = await $.clock.now()
455
+ if (shown !== slide.to) slide = { from: slide.to || shown, to: shown, live, at: now }
456
+ else if (live !== slide.live || now - slide.at > 300) slide = { ...slide, from: shown, live }
457
+ const startedAt = (await $.session.usage().catch(() => undefined))?.startedAt ?? now
458
+ const avg = b.turns > 0 ? b.spent / b.turns : 0
459
+ const last = b.turnCosts[b.turnCosts.length - 1]
460
+
461
+ const setLevel = async (level: string) => {
462
+ const { level: current } = await load($)
463
+ const pending = level === current ? '' : level
464
+ try {
465
+ // 先写文件再更新面板;$.fs 不能删除文件,所以用空内容表示取消。
466
+ await $.fs.write(await pendingFile($), pending)
467
+ } catch {
468
+ $.ui.toast(`2Cmd: ${t.saveFail}`)
469
+ return
470
+ }
471
+ await update($, band, x => withLevel({ ...EMPTY, ...x }, x.level, pending))
472
+ }
473
+ const toggle = async () => {
474
+ await update($, band, x => ({ ...x, details: !x.details }))
475
+ await $.store.set('details', !b.details)
476
+ }
477
+ // A button never sends: a command goes before the draft, any other text at the cursor.
478
+ const put = async (text: string) => {
479
+ const { text: draft } = await $.prompt.read()
480
+ const command = commandDraft(text, draft)
481
+ await $.prompt.fill(command === undefined ? { text, mode: 'insert' } : { text: command })
482
+ }
483
+ const board = () => openBoard($, loc).catch(() => $.ui.toast(`2Cmd: ${t.boardFail}`))
484
+ const copy = async () => {
485
+ const done = await $.ui.copy({ text: markdown(snapshot(await load($), startedAt), t), surface: e.surface })
486
+ $.ui.toast(done.isCopied ? t.copied : fill(t.copyFail, { r: done.reason }))
487
+ }
488
+
489
+ const { Box, Text, Button } = $.ui.resolve(e)
490
+ // bodyColumns counts terminal cells; a graphical surface draws Buttons wider than their cells, so a row sized to it wraps there.
491
+ const width = e.surface === 'terminal' ? e.props.bodyColumns : undefined
492
+ // No frame of our own: on the desktop the host already draws one around this area, and a second looked doubled.
493
+ const stack = (mine: NonNullable<typeof below>) => (below ? <Box flexDirection="column">{mine}{below}</Box> : mine)
494
+
495
+ // 桌面端自己决定说明卡片的位置和宽度,不占行;下面的定位只用于其他界面,并为它们预留两行。
496
+ // Collapsed in a terminal, the band sits right on the prompt: no rows kept for hover tips, so no tips.
497
+ const bare = !b.details && e.surface !== 'desktop'
498
+ const tip = (id: string, button: any) => bare ? <Box key={`tip-${id}`}>{button}</Box> : (
499
+ <Box key={`tip-${id}`}>
500
+ {button}
501
+ <Box
502
+ position="absolute"
503
+ bottom={-2}
504
+ {...([...LEVELS, 'on', 'level'].includes(id) ? { left: 0 } : { right: 0 })}
505
+ width={48}
506
+ height={2}
507
+ display="none"
508
+ hover={{ display: 'flex' }}
509
+ >
510
+ <Text dimColor>{tips[id]}</Text>
511
+ </Box>
512
+ </Box>
513
+ )
514
+ const labels: Record<string, string> = { fix: t.reviewFix, commit: t.reviewCommit, push: t.reviewPush, copy: t.copy, review: t.review, audit: t.audit, tool: t.toolReview }
515
+ const hints: Record<string, string> = { fix: t.tipFix, commit: t.tipCommit, push: t.tipPush, copy: t.tipCopy, review: t.tipReview, audit: t.tipAudit, tool: t.tipTool }
516
+ const shownButtons = (b.buttons ?? DEFAULT_BUTTONS)
517
+ const actions = shownButtons.flatMap((button: PanelButton, i) => {
518
+ const text = buttonText(button, 'claude')
519
+ if (button.kind === 'none' || (button.kind !== 'copy' && text === undefined)) return []
520
+ // A built-in keeps its own key; a second copy of it or a custom button gets the slot's.
521
+ const id = button.kind !== 'prompt' && shownButtons.findIndex(x => x.kind === button.kind) === i ? button.kind : `button${i}`
522
+ // A custom button's hint is the start of its text.
523
+ tips[id] = button.kind === 'prompt' ? `${(button.text ?? '').slice(0, 40)}${(button.text ?? '').length > 40 ? '…' : ''}` : hints[button.kind] ?? ''
524
+ const label = button.kind === 'prompt' ? button.label ?? '' : labels[button.kind] ?? ''
525
+ return [{ kind: button.kind, node: tip(id, <Button key={id} plain label={label} onPress={button.kind === 'copy' ? copy : () => put(text ?? '')} />) }]
526
+ })
527
+ const tipRows = e.surface === 'desktop' ? null : <Box key="tips" height={2} />
528
+
529
+ const testsText =
530
+ b.tests.state === 'pass'
531
+ ? `✓ ${b.tests.passed ?? ''} ${t.passed}`
532
+ : b.tests.state === 'fail'
533
+ ? `✗ ${b.tests.failed ?? ''} ${t.failed}`
534
+ : b.tests.state === 'stale'
535
+ ? t.untested
536
+ : ''
537
+ const testsColor = b.tests.state === 'pass' ? 'success' : b.tests.state === 'fail' ? 'error' : undefined
538
+ const hasOpen = b.openCallers.length > 0
539
+
540
+ // 绝对定位不占位置;放在按钮前面,所以画在按钮下层。按钮可能比所在行高,所以上下居中,不能只对齐顶部。
541
+ const behind = (source: string, imageWidth: number) => {
542
+ if (e.surface !== 'desktop') return null
543
+ const { Svg } = $.ui.resolve(e)
544
+ return (
545
+ <Box key="track" position="absolute" top={0} bottom={0} left={0} flexDirection="row" alignItems="center">
546
+ <Svg source={source} width={imageWidth} height={28} alt={`${live ? t.current : t.pending}: ${names[shown] ?? shown}`} />
547
+ </Box>
548
+ )
549
+ }
550
+
551
+ if (!b.details) {
552
+ const mode = MODES.indexOf(shown)
553
+ return stack(
554
+ <Box flexDirection="column" width={width}>
555
+ {/* 桌面端按钮自带内边距,间隔 1 就够,省下的位置让最右边的按钮不被截掉。 */}
556
+ <Box flexDirection="row" alignItems="center" gap={e.surface === 'desktop' ? 1 : 2} width={width}>
557
+ {/* A click opens the four levels: one click, one turn, no stops on levels nobody wanted. */}
558
+ {/* 桌面端用和滑块一样的背景;其他界面显示不了背景,用圆点。 */}
559
+ <Box key="chip" flexDirection="row" alignItems="center">
560
+ {mode >= 0 && behind(chipSvg(widths, mode, live), chipWidth(widths, mode))}
561
+ {tip('level', <Button key="level" plain onPress={toggle}>
562
+ <Text color={LEVEL_COLORS[shown]}>{e.surface === 'desktop' ? '' : '● '}{names[shown] ?? shown}</Text>
563
+ </Button>)}
564
+ </Box>
565
+ {/* 数字不换行:这一组不被挤窄,每项只占一行;位置不够时由右边的空白让出。 */}
566
+ <Box key="metrics" flexDirection="row" alignItems="center" gap={2} flexShrink={0}>
567
+ {!live && <Text dimColor wrap="truncate-end">{t.pending}</Text>}
568
+ <Text wrap="truncate-end">${b.spent.toFixed(2)}</Text>
569
+ {last !== undefined && <Text dimColor wrap="truncate-end">{fill(t.last, { v: `$${last.toFixed(2)}` })}</Text>}
570
+ <Text dimColor wrap="truncate-end">{elapsed(b.busyMs)}</Text>
571
+ {hasOpen && <Text color="warning" wrap="truncate-end">⚠ {fill(t.callersWarn, { n: b.openCallers.length })}</Text>}
572
+ {testsText !== '' && (
573
+ <Text color={testsColor} dimColor={b.tests.state === 'stale'} wrap="truncate-end">
574
+ {testsText}
575
+ </Text>
576
+ )}
577
+ </Box>
578
+ <Box flexGrow={1} />
579
+ {/* 收起时位置不够,不放复制。 */}
580
+ {actions.filter(a => a.kind !== 'copy').map(a => a.node)}
581
+ {tip('board', <Button key="board" plain label={t.board} onPress={board} />)}
582
+ {tip('expand', <Button key="details" plain label={t.expand} onPress={toggle} />)}
583
+ </Box>
584
+ </Box>
585
+ )
586
+ }
587
+
588
+ // Only columns that say something; callers and tests appear once there is something to report.
589
+ const cols: Col[] = [
590
+ { key: 'cost', label: t.cost, value: `$${b.spent.toFixed(2)}`, sub: last === undefined ? '' : fill(t.costSub, { last: `$${last.toFixed(2)}`, avg: `$${avg.toFixed(2)}` }) },
591
+ { key: 'tokens', label: t.tokens, value: fmtTokens(totalTokens(b.tokens)), sub: fill(t.turnsN, { n: b.turns }) },
592
+ // 平均值只算面板记录到的轮数,所以写明是几轮。
593
+ {
594
+ key: 'cache',
595
+ label: t.cache,
596
+ value: b.cache.last === null ? '–' : `${b.cache.last}%`,
597
+ sub: b.cache.turns > 0 ? fill(t.cacheSub, { n: b.cache.turns, v: hitRate(b.cache.read, b.cache.input) }) : '',
598
+ },
599
+ { key: 'time', label: t.time, value: elapsed(b.busyMs), sub: b.turns > 0 ? fill(t.avgTurn, { t: elapsed(b.busyMs / b.turns) }) : '' },
600
+ ]
601
+ if (hasOpen) {
602
+ cols.push({ key: 'callers', label: t.callers, value: `${b.openCallers.length}`, sub: b.openCallers.slice(0, 2).join(', '), tone: 'warning' })
603
+ }
604
+ if (b.tests.state !== 'none') {
605
+ cols.push({
606
+ key: 'tests',
607
+ label: t.tests,
608
+ value: translateTests(testsLabel(b.tests), t),
609
+ sub: b.tests.state === 'pass' ? t.afterChange : b.tests.state === 'fail' ? t.lastRun : t.changedSince,
610
+ tone: b.tests.state === 'pass' ? 'success' : b.tests.state === 'fail' ? 'error' : undefined,
611
+ })
612
+ }
613
+
614
+ let metrics = (
615
+ <Box flexDirection="column">
616
+ <Text dimColor wrap="truncate-end">
617
+ {'─'.repeat(e.props.bodyColumns)}
618
+ </Text>
619
+ <Box flexDirection="row" gap={2}>
620
+ {cols.map(c => (
621
+ // Off the terminal the columns share the row; a width in cells would leave most of it empty and cut the text.
622
+ <Box key={c.key} flexDirection="column" {...(width === undefined ? { flexGrow: 1 } : { width: Math.max(10, Math.floor(width / cols.length) - 2) })}>
623
+ <Text dimColor>{c.label}</Text>
624
+ <Text bold color={c.tone}>
625
+ {c.value}
626
+ </Text>
627
+ <Text dimColor wrap="truncate-end">
628
+ {c.sub}
629
+ </Text>
630
+ </Box>
631
+ ))}
632
+ </Box>
633
+ </Box>
634
+ )
635
+ // Text glyphs make broken lines in the desktop's proportional font; an SVG draws real ones.
636
+ if (e.surface === 'desktop') {
637
+ const { Svg } = $.ui.resolve(e)
638
+ metrics = <Svg source={metricsSvg(cols, b.turnCosts)} alt={cols.map(c => `${c.label} ${c.value}`).join(', ')} />
639
+ }
640
+
641
+ return stack(
642
+ // The desktop's SVG draws its own line at the top, which would touch the buttons without the gap.
643
+ <Box flexDirection="column" width={width} gap={e.surface === 'desktop' ? 1 : 0}>
644
+ <Box flexDirection="row" alignItems="center" gap={1}>
645
+ {/* 开关上写的是点了会做什么,不是当前状态。 */}
646
+ {shown === 'off'
647
+ ? tip('on', <Button key="power" plain label={t.turnOn} onPress={() => setLevel(b.lastLevel)} />)
648
+ : tip('off', <Button key="power" plain label={t.turnOff} onPress={() => setLevel('off')} />)}
649
+ {/* 四选一:桌面端在按钮下面垫一张滑块底图,按钮大小不变;其他界面保持原样。 */}
650
+ <Box
651
+ key="levels"
652
+ flexDirection="row"
653
+ alignItems="center"
654
+ gap={e.surface === 'desktop' ? 0 : 1}
655
+ >
656
+ {behind(switchSvg(widths, MODES.indexOf(slide.from), MODES.indexOf(slide.to), live), switchWidth(widths))}
657
+ {MODES.map(level => (
658
+ tip(level, <Button
659
+ key={`level-${level}`}
660
+ label={names[level] ?? level}
661
+ {...(level === shown
662
+ ? e.surface === 'desktop' ? { plain: true as const } : { variant: 'primary' as const }
663
+ : { plain: true as const, dimColor: true })}
664
+ onPress={() => setLevel(level)}
665
+ >
666
+ <Text color={LEVEL_COLORS[level]} bold={level === shown}>{names[level] ?? level}</Text>
667
+ </Button>)
668
+ ))}
669
+ </Box>
670
+ {!live && <Text dimColor>{t.pending}</Text>}
671
+ <Box flexGrow={1} />
672
+ {actions.map(a => a.node)}
673
+ {tip('board', <Button key="board" plain label={t.board} onPress={board} />)}
674
+ {tip('collapse', <Button key="details" plain label={t.collapse} onPress={toggle} />)}
675
+ </Box>
676
+ {tipRows}
677
+ {metrics}
678
+ </Box>
679
+ )
680
+ }).catch(($, e, next) => next(e))
681
+ }