@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,373 @@
1
+ // Pure helpers for the band: no `$`, so the tests call them directly.
2
+
3
+ import { duration, elapsed, fmtTokens, parseCsv, testsText } from './board'
4
+ import { fill } from './i18n'
5
+ import type { Strings } from './i18n'
6
+ import type { Band, Cache, Tokens } from './types'
7
+
8
+ export { duration, elapsed, fmtTokens }
9
+
10
+ // Same skip rules as 2cmd-map.js: tests, vendored and generated code are not "reuse".
11
+ const SKIP_DIR = /(^|\/)(node_modules|\.git|dist|build|out|vendor|venv|\.venv|__pycache__|coverage|\.next|target|migrations|fixtures|tests?|__tests__|spec)(\/|$)/
12
+ const SKIP_FILE = /(^|\/)(test_[^/]*|[^/]*(_test|\.test|\.spec|\.gen|\.min|\.d)\.[a-z]+)$/
13
+
14
+ // Top-level definitions per language, close to 2cmd-map.js, plus plain JS functions.
15
+ // shortcut: regex, not a parser; nested and dynamic definitions are missed. Use tree-sitter if it matters.
16
+ const DEFS: [RegExp, RegExp[]][] = [
17
+ [/\.py$/, [/^(?:async\s+)?def\s+([A-Za-z]\w*)/gm, /^class\s+([A-Za-z]\w*)/gm]],
18
+ [/\.[cm]?[jt]sx?$/, [
19
+ /^export\s+(?:default\s+)?(?:async\s+)?(?:function\*?|class|const|let|var)\s+([A-Za-z_$][\w$]*)/gm,
20
+ /^(?:async\s+)?function\*?\s+([A-Za-z_$][\w$]*)/gm,
21
+ ]],
22
+ [/\.go$/, [/^func\s+(?:\([^)]*\)\s*)?([A-Za-z]\w*)/gm]],
23
+ [/\.rs$/, [/^(?:pub\s+)?(?:async\s+)?fn\s+(\w+)/gm]],
24
+ [/\.rb$/, [/^\s*def\s+(?:self\.)?([A-Za-z]\w*[?!]?)/gm]],
25
+ ]
26
+
27
+ // Lines worth a closer look; the per-language regexes above decide.
28
+ export const GREP_DEFS = '^[[:space:]]*(export|async|def|class|function|func|pub|fn)[[:space:]]'
29
+
30
+ // Names too generic to say anything about reuse.
31
+ const GENERIC = new Set(['main', 'init', 'run', 'get', 'set', 'test', 'setup', 'open', 'close', 'read', 'write', 'start', 'stop', 'load', 'save', 'update', 'create', 'delete', 'handle', 'render', 'index', 'new', 'call', 'apply'])
32
+
33
+ export const isCode = (file: string) => DEFS.some(([ext]) => ext.test(file))
34
+
35
+ export const isSource = (file: string) => isCode(file) && !SKIP_DIR.test(file) && !SKIP_FILE.test(file)
36
+
37
+ export function defsIn(file: string, text: string): string[] {
38
+ const rules = DEFS.find(([ext]) => ext.test(file))?.[1] ?? []
39
+ const names = new Set<string>()
40
+ for (const re of rules) for (const m of text.matchAll(re)) if (m[1]) names.add(m[1])
41
+ return [...names]
42
+ }
43
+
44
+ export type Hit = { file: string; line: string; text: string }
45
+
46
+ // `git grep -n` output, one "file:line:text" row each.
47
+ export const hits = (stdout: string): Hit[] =>
48
+ stdout.split('\n').flatMap(row => {
49
+ const m = /^(.+?):(\d+):(.*)$/.exec(row)
50
+ return m ? [{ file: m[1] ?? '', line: m[2] ?? '', text: m[3] ?? '' }] : []
51
+ })
52
+
53
+ // Existing definitions, name -> "file:line".
54
+ export function parseDefs(stdout: string): Map<string, string> {
55
+ const known = new Map<string, string>()
56
+ for (const hit of hits(stdout)) {
57
+ if (!isSource(hit.file)) continue
58
+ for (const name of defsIn(hit.file, hit.text.trimStart())) {
59
+ if (!known.has(name)) known.set(name, `${hit.file}:${hit.line}`)
60
+ }
61
+ }
62
+ return known
63
+ }
64
+
65
+ // Lines of `after` that `before` did not have: what an edit added.
66
+ export function addedLines(before: string, after: string): string {
67
+ const old = new Set(before.split('\n'))
68
+ return after.split('\n').filter(line => !old.has(line)).join('\n')
69
+ }
70
+
71
+ // Known names the added code calls, skipping its own new definitions.
72
+ export function callsIn(text: string, known: Map<string, string>, own: string[]): string[] {
73
+ const names = new Set<string>()
74
+ for (const m of text.matchAll(/(?<![\w$])([A-Za-z_$][\w$]*)\s*\(/g)) {
75
+ const name = m[1] ?? ''
76
+ if (known.has(name) && !own.includes(name) && !GENERIC.has(name.toLowerCase())) names.add(name)
77
+ }
78
+ return [...names]
79
+ }
80
+
81
+ // Whether a file lies under the project root; Windows paths may use either slash.
82
+ export function inProject(file: string, root: string): boolean {
83
+ const f = file.replace(/\\/g, '/')
84
+ const r = root.replace(/\\/g, '/').replace(/\/+$/, '')
85
+ return f === r || f.startsWith(`${r}/`)
86
+ }
87
+
88
+ const TEST_CMD = /\b(npm (run )?test|pnpm (run )?test|yarn test|bun test|npx (jest|vitest)|jest|vitest|pytest|python3? -m pytest|go test|cargo test|mvn test|gradle test|rspec|phpunit|dotnet test|node --test|deno test|make test)\b/
89
+
90
+ export const isTestCommand = (command: string) => TEST_CMD.test(command)
91
+
92
+ // Pass and fail counts from common runners: pytest, jest/vitest, cargo, node --test, TAP.
93
+ export function testCounts(output: string): { passed?: number; failed?: number } {
94
+ const num = (re: RegExp) => {
95
+ const m = re.exec(output)
96
+ return m ? Number(m[1]) : undefined
97
+ }
98
+ return {
99
+ passed: num(/(\d+) (?:passed|passing)\b/) ?? num(/(?:ℹ |# )pass (\d+)/),
100
+ failed: num(/(\d+) (?:failed|failing)\b/) ?? num(/(?:ℹ |# )fail (\d+)/),
101
+ }
102
+ }
103
+
104
+ export type Col = { key: string; label: string; value: string; sub: string; tone?: 'warning' | 'success' | 'error' }
105
+
106
+ const esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
107
+ const fit = (s: string, max: number) => (s.length > max ? `${s.slice(0, Math.max(1, max - 1))}…` : s)
108
+
109
+ const FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif"
110
+ // The image cannot read the app's theme, so it follows the system's.
111
+ // shortcut: an app theme that differs from the system theme gets the wrong text color; pass the theme in if that bites.
112
+ const STYLE = `.l,.s{fill:#87867f;font:12px ${FONT}}.v{fill:#1f1e1d;font:600 16px ${FONT}}.d{stroke:#1f1e1d;stroke-opacity:.12}.tl{fill:none;stroke:#87867f;stroke-width:1.5;stroke-linejoin:round;stroke-linecap:round}.ta{fill:#87867f;fill-opacity:.15}.warning{fill:#a86400}.success{fill:#2e7d32}.error{fill:#c62828}@media (prefers-color-scheme:dark){.v{fill:#ecebe6}.d{stroke:#fff;stroke-opacity:.14}.warning{fill:#e3a03d}.success{fill:#6abf69}.error{fill:#ef6a5a}}`
113
+
114
+ // Rough text width at the row's font sizes: wide (CJK) characters take a full em, others about half.
115
+ const span = (s: string, size: number) => [...s].reduce((n, c) => n + (c > '⹿' ? size : size * 0.58), 0)
116
+
117
+ /** The last ten turns' costs as a line right of a label, from x to x + w; the area under it is shaded. */
118
+ function trend(costs: number[], x: number, w: number): string {
119
+ const max = Math.max(...costs)
120
+ if (costs.length < 2 || max <= 0 || w < 24) return ''
121
+ const top = 12
122
+ const bottom = 24
123
+ const step = w / (costs.length - 1)
124
+ const points = costs.map((v, j) => `${(x + j * step).toFixed(1)},${(bottom - (v / max) * (bottom - top)).toFixed(1)}`)
125
+ return `<path class="ta" d="M${x},${bottom}L${points.join('L')}L${x + w},${bottom}Z"/><polyline class="tl" points="${points.join(' ')}"/>`
126
+ }
127
+
128
+ // The details row as one SVG for surfaces that draw it: real 1px dividers and exact columns.
129
+ export function metricsSvg(cols: Col[], turnCosts: number[], width = 720): string {
130
+ const height = 64
131
+ const colW = width / Math.max(1, cols.length)
132
+ let body = `<line class="d" x1="0" y1="0.5" x2="${width}" y2="0.5"/>`
133
+ cols.forEach((c, i) => {
134
+ const x = i * colW + (i === 0 ? 0 : 12)
135
+ const tone = c.tone ? ` ${c.tone}` : ''
136
+ if (i > 0) body += `<line class="d" x1="${i * colW}" y1="14" x2="${i * colW}" y2="${height - 2}"/>`
137
+ body += `<text class="l" x="${x}" y="24">${esc(c.label)}</text>`
138
+ body += `<text class="v${tone}" x="${x}" y="44">${esc(fit(c.value, Math.floor((colW - 16) / 9)))}</text>`
139
+ if (c.sub) body += `<text class="s${c.tone === 'warning' ? tone : ''}" x="${x}" y="61">${esc(fit(c.sub, Math.floor((colW - 16) / 6.2)))}</text>`
140
+ // On the label's line, which has room to spare, so the value and its note stay whole.
141
+ if (c.key === 'cost') {
142
+ const from = x + span(c.label, 12) + 10
143
+ body += trend(turnCosts.slice(-10), from, (i + 1) * colW - 16 - from)
144
+ }
145
+ })
146
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"><style>${STYLE}</style>${body}</svg>`
147
+ }
148
+
149
+ // 桌面端按钮不支持文字颜色,所以颜色画在底图上:绿、蓝、珊瑚橙、紫,对应 hindsight、reuse、pushback、scout。
150
+ // 四种颜色的亮度相近;太亮会让按钮上的浅色文字看不清。
151
+ export const SWITCH_COLORS = ['#45a16b', '#598ad9', '#d97757', '#9a73d9']
152
+
153
+ // 按钮宽度 = 语言包里量好的文字宽度 + 左右共 20 像素边距。
154
+ const slots = (widths: number[]) => widths.map(w => w + 20)
155
+ export const switchWidth = (widths: number[]) => slots(widths).reduce((a, b) => a + b, 0)
156
+
157
+ const SWITCH_HEIGHT = 28
158
+
159
+ // 展开的切换条和收起的档位共用:rect 是滑块形状,slide 是滑动动画,track 是滑块下面的底色;没有 color 时不画滑块。
160
+ // 斜纹:45°,每 20 像素重复,1.6 秒一轮;深色叠黑、浅色叠白,再整体半透明,颜色才不发灰。
161
+ // live 为 false(等下条消息生效)时,斜纹不动;系统要求减少动态效果时都静止。
162
+ function stripedSvg(width: number, color: string | undefined, rect: string, live: boolean, slide = '', track = ''): string {
163
+ const h = SWITCH_HEIGHT
164
+ // 左边多画几条,右移 20 像素时不会露出空白。
165
+ const path = Array.from({ length: Math.ceil(width / 20) + 3 }, (_, i) => `M${i * 20 - 60} 0h10l${h} ${h}h-10z`).join('')
166
+ const stripes = color ? `<clipPath id="c"><rect ${rect}/></clipPath><g class="g" clip-path="url(#c)"><rect width="${width}" height="${h}" fill="${color}"/><path class="m" d="${path}"/></g>` : ''
167
+ const flow = color && live ? '@keyframes m{to{transform:translateX(20px)}}.m{animation:m 1.6s linear infinite}' : ''
168
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${h}" viewBox="0 0 ${width} ${h}"><style>.t{fill:#000;fill-opacity:.06}.g{opacity:.5}.m{fill:#fff;fill-opacity:.5}@media (prefers-color-scheme:dark){.t{fill:#fff;fill-opacity:.06}.g{opacity:.5}.m{fill:#000;fill-opacity:.4}}${slide}${flow}@media (prefers-reduced-motion:reduce){.k,.m{animation:none}}</style>${track}${stripes}</svg>`
169
+ }
170
+
171
+ // 切换条的底图:滑块从 from 滑到 to,宽度跟着变。from 为 -1(刚启用)时直接出现,to 为 -1(停用)时没有滑块。
172
+ export function switchSvg(widths: number[], from: number, to: number, live = true): string {
173
+ const total = switchWidth(widths)
174
+ const left = (i: number) => slots(widths).slice(0, i).reduce((a, b) => a + b, 0)
175
+ // 滑块左右各收 1 像素,和旁边按钮的悬停颜色隔开;按钮本身不动。
176
+ const thumb = (i: number) => (slots(widths)[i] ?? 2) - 2
177
+ const rect = `class="k" x="${left(to) + 1}" width="${thumb(to)}" height="${SWITCH_HEIGHT}" rx="7"`
178
+ const slide = from < 0 || to < 0 || from === to ? '' : `@keyframes s{from{transform:translateX(${left(from) - left(to)}px);width:${thumb(from)}px}}.k{animation:s .2s ease-out}`
179
+ return stripedSvg(total, SWITCH_COLORS[to], rect, live, slide, `<rect class="t" width="${total}" height="${SWITCH_HEIGHT}" rx="7"/>`)
180
+ }
181
+
182
+ // 收起后当前档位的背景;停用时不显示。
183
+ export const chipWidth = (widths: number[], mode: number) => slots(widths)[mode] ?? 0
184
+ export const chipSvg = (widths: number[], mode: number, live: boolean) =>
185
+ stripedSvg(chipWidth(widths, mode), SWITCH_COLORS[mode], `width="${chipWidth(widths, mode)}" height="${SWITCH_HEIGHT}" rx="7"`, live)
186
+
187
+ export const NO_TOKENS: Tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
188
+
189
+ type Usage = { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }
190
+
191
+ export const addTokens = (t: Tokens, u: Usage): Tokens => ({
192
+ input: t.input + u.input_tokens,
193
+ output: t.output + u.output_tokens,
194
+ cacheRead: t.cacheRead + u.cache_read_input_tokens,
195
+ cacheWrite: t.cacheWrite + u.cache_creation_input_tokens,
196
+ })
197
+
198
+ export const NO_CACHE: Cache = { last: null, read: 0, input: 0, turns: 0 }
199
+
200
+ // 只舍不入,没到 100% 就不会显示 100%。
201
+ export const hitRate = (read: number, input: number) => Math.floor((read / input) * 1000) / 10
202
+
203
+ // 没有输入数据的一轮不算,避免显示成 0%。
204
+ export function addCache(c: Cache, u: Usage): Cache {
205
+ const input = u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
206
+ if (input === 0) return c
207
+ const read = u.cache_read_input_tokens
208
+ return { last: hitRate(read, input), read: c.read + read, input: c.input + input, turns: c.turns + 1 }
209
+ }
210
+
211
+ export const totalTokens = (t: Tokens) => t.input + t.output + t.cacheRead + t.cacheWrite
212
+
213
+ export const stamp = (ms: number) => {
214
+ const d = new Date(ms)
215
+ const two = (n: number) => String(n).padStart(2, '0')
216
+ return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`
217
+ }
218
+
219
+ export const testsLabel = (t: Band['tests']) =>
220
+ t.state === 'pass' ? `${t.passed ?? ''} passed`.trim() : t.state === 'fail' ? `${t.failed ?? ''} failed`.trim() : t.state === 'stale' ? 'stale' : 'not run'
221
+
222
+ // Claude Code writes the session's sidebar name into its transcript on every rename.
223
+ export const TITLE_RECORD = '"type":"custom-title"'
224
+ // grep -o pattern for the model of every reply in a transcript.
225
+ export const MODEL_PATTERN = '"model":"claude-[^"]*"'
226
+
227
+ // The model that wrote most replies, from grep -o lines like "model":"claude-opus-5-5". Empty when none.
228
+ export function mainModel(grepOut: string): string {
229
+ const count = new Map<string, number>()
230
+ for (const m of grepOut.matchAll(/"model":"(claude-[^"]+)"/g)) count.set(m[1], (count.get(m[1]) ?? 0) + 1)
231
+ return [...count].sort((a, b) => b[1] - a[1])[0]?.[0] ?? ''
232
+ }
233
+
234
+ // The newest sidebar name in transcript lines, or undefined when the session has none.
235
+ export function sessionTitle(jsonl: string): string | undefined {
236
+ for (const line of jsonl.split('\n').reverse()) {
237
+ if (!line.includes(TITLE_RECORD)) continue
238
+ try {
239
+ const r = JSON.parse(line) as { type?: unknown; customTitle?: unknown }
240
+ if (r.type !== 'custom-title') continue
241
+ const title = typeof r.customTitle === 'string' ? r.customTitle.trim() : ''
242
+ return title === '' ? undefined : title.slice(0, 60)
243
+ } catch {
244
+ continue
245
+ }
246
+ }
247
+ return undefined
248
+ }
249
+
250
+ // One session (one task) as it is exported, copied and sent.
251
+ export type Snapshot = {
252
+ key: string
253
+ started: string
254
+ project: string
255
+ name: string
256
+ session: string
257
+ level: string
258
+ model: string
259
+ cost: number
260
+ lastTurn: number | null
261
+ turns: number
262
+ agentMs: number
263
+ tokens: Tokens
264
+ reuse: number | null
265
+ reused: number
266
+ created: number
267
+ callersOpen: number
268
+ tests: string
269
+ }
270
+
271
+ // A task's row in the ledger: the session and when it started (a /clear starts a new one).
272
+ export const taskKey = (session: string, startedAt: number) => `${session.slice(0, 8)}-${startedAt}`
273
+
274
+ // A band that starts again mid-session (a reload, an update, a second copy) picks up the session's
275
+ // row, so what only the band counts (tokens, agent time, the name) goes on instead of starting at zero.
276
+ // shortcut: the ledger keeps only the token total and output, so a resumed band books the rest as input.
277
+ export function resume(b: Band, csv: string, key: string): Band {
278
+ const [head, ...rows] = parseCsv(csv)
279
+ const row = head ? rows.find(r => r[head.indexOf('key')] === key) : undefined
280
+ if (!head || !row) return b
281
+ const at = (col: string) => row[head.indexOf(col)] ?? ''
282
+ const total = Number(at('tokens_total')) || 0
283
+ const output = Number(at('tokens_output')) || 0
284
+ return {
285
+ ...b,
286
+ name: b.name || at('name'),
287
+ busyMs: Math.max(b.busyMs, (Number(at('agent_minutes')) || 0) * 60000),
288
+ tokens: total > totalTokens(b.tokens) ? { input: total - output, output, cacheRead: 0, cacheWrite: 0 } : b.tokens,
289
+ }
290
+ }
291
+
292
+ export function snapshot(b: Band, startedAt: number): Snapshot {
293
+ return {
294
+ key: taskKey(b.session, startedAt),
295
+ started: stamp(startedAt),
296
+ project: b.project,
297
+ name: b.name,
298
+ session: b.session,
299
+ level: b.level,
300
+ model: b.model,
301
+ // The session's cost as /cost totals it, since its start or the last /clear.
302
+ cost: +b.spent.toFixed(4),
303
+ lastTurn: b.turnCosts[b.turnCosts.length - 1] ?? null,
304
+ turns: b.turns,
305
+ agentMs: b.busyMs,
306
+ tokens: b.tokens,
307
+ reuse: percent(b.reused.length, b.created.length) ?? null,
308
+ reused: b.reused.length,
309
+ created: b.created.length,
310
+ callersOpen: b.openCallers.length,
311
+ tests: testsLabel(b.tests),
312
+ }
313
+ }
314
+
315
+ const per = (total: number, n: number) => (n > 0 ? total / n : 0)
316
+
317
+ export function markdown(s: Snapshot, t: Strings): string {
318
+ const k = s.tokens
319
+ const rows = [
320
+ [t.project, s.project],
321
+ [t.started, s.started],
322
+ [t.model, s.model || '–'],
323
+ [t.cost, `$${s.cost.toFixed(2)}${s.lastTurn === null ? '' : ` · ${fill(t.last, { v: `$${s.lastTurn.toFixed(2)}` })}`} · ${fill(t.avgTurn, { t: `$${per(s.cost, s.turns).toFixed(2)}` })}`],
324
+ [t.turns, `${s.turns}`],
325
+ [t.time, `${elapsed(s.agentMs)} · ${fill(t.avgTurn, { t: elapsed(per(s.agentMs, s.turns)) })}`],
326
+ [t.tokens, `${fmtTokens(totalTokens(k))} (${fill(t.tokenDetail, { i: fmtTokens(k.input), o: fmtTokens(k.output), r: fmtTokens(k.cacheRead), w: fmtTokens(k.cacheWrite) })})`],
327
+ [t.callers, `${s.callersOpen}`],
328
+ [t.tests, testsText(s.tests, t)],
329
+ [t.mode, s.level],
330
+ [t.session, `\`${s.session}\``],
331
+ ]
332
+ const cell = (v: string) => v.replace(/\|/g, '\\|')
333
+ return [`## ${cell(s.name || t.untitled)}`, '', '| | |', '|---|---|', ...rows.map(([k, v]) => `| ${k} | ${cell(v ?? '')} |`)].join('\n')
334
+ }
335
+
336
+ export const CSV_HEADER = 'key,started,project,name,cost_usd,turns,agent_minutes,tokens_total,tokens_output,reuse_pct,reused,new,callers_open,tests,level,model'
337
+
338
+ const csvField = (v: string | number | null) => {
339
+ const s = v === null ? '' : String(v)
340
+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s
341
+ }
342
+
343
+ export const csvRow = (s: Snapshot) =>
344
+ [s.key, s.started, s.project, s.name, s.cost.toFixed(2), s.turns, (s.agentMs / 60000).toFixed(1), totalTokens(s.tokens), s.tokens.output, s.reuse, s.reused, s.created, s.callersOpen, s.tests, s.level, s.model]
345
+ .map(csvField)
346
+ .join(',')
347
+
348
+ // One row per session, replaced on every turn, so the file stays a table of tasks.
349
+ export function upsertCsv(existing: string, s: Snapshot): string {
350
+ const rows = existing.split('\n').filter(line => line !== '' && !line.startsWith('key,') && !line.startsWith(`${s.key},`))
351
+ return [CSV_HEADER, ...rows, csvRow(s)].join('\n') + '\n'
352
+ }
353
+
354
+ // 至少成功复用过一个现有函数才显示,避免只新建时显示 0%。
355
+ export const percent = (reused: number, created: number) =>
356
+ reused === 0 ? undefined : Math.round((reused / (reused + created)) * 100)
357
+
358
+ export type WebhookRequest = { url: string; init: { method: 'POST'; headers: Record<string, string>; body: string } }
359
+
360
+ // The token travels only over HTTPS; plain http is allowed for a board on this machine.
361
+ export function webhookRequest(url: string, token: string, sendNames: boolean, row: Snapshot): WebhookRequest | { refused: 'hookInvalid' | 'hookHttps' } {
362
+ let target: URL
363
+ try {
364
+ target = new URL(url)
365
+ } catch {
366
+ return { refused: 'hookInvalid' }
367
+ }
368
+ const local = ['localhost', '127.0.0.1', '[::1]'].includes(target.hostname)
369
+ if (target.protocol !== 'https:' && !(target.protocol === 'http:' && local)) return { refused: 'hookHttps' }
370
+ const headers: Record<string, string> = { 'content-type': 'application/json' }
371
+ if (token !== '') headers.authorization = `Bearer ${token}`
372
+ return { url: target.href, init: { method: 'POST', headers, body: JSON.stringify(sendNames ? row : { ...row, name: '' }) } }
373
+ }