project-brain 0.43.0 → 0.44.0

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.
@@ -0,0 +1,1982 @@
1
+ import { atom, read, update } from 'claude-code'
2
+ import type { Hook, Register } from 'claude-code'
3
+
4
+ import type {
5
+ AgentRecord,
6
+ AgentState,
7
+ BranchCommit,
8
+ BranchView,
9
+ CallStatus,
10
+ CambiosScope,
11
+ CommitCall,
12
+ CommitRecord,
13
+ ContextUsage,
14
+ StepContext,
15
+ Decision,
16
+ DiffPatch,
17
+ DiffRow,
18
+ EditorState,
19
+ FileChange,
20
+ HistoryFiles,
21
+ HistoryRow,
22
+ HistoryView,
23
+ PaneScroll,
24
+ Tab,
25
+ TestFile,
26
+ ToolEntry,
27
+ } from '../types'
28
+
29
+ const PANE = 'activity'
30
+ const PANE_ARGS = { id: PANE, title: 'Actividad', columns: 1000 } as const
31
+ const MAIN = 'main'
32
+ const KEEP = 300
33
+ const OUTPUT_LINES = 40
34
+ const DIFF_LINES = 120
35
+ const TEST_FILES = 30
36
+ const UNTRACKED_MAX = 100
37
+ const COMMIT_FILES = 100
38
+ const BRANCH_COMMITS = 100
39
+ const OPEN_DIFFS = 40
40
+ const REFRESH_MS = 400
41
+ const RESCAN_MS = 800
42
+ const SCAN_COMMITS = 200
43
+ const COMMIT_CALLS = 100
44
+ const HISTORY_COMMITS = 400
45
+ const HISTORY_FILES = 40
46
+ const WINDOW_SLACK_MS = 2000
47
+ const SUMMARY_FIELDS = ['command', 'file_path', 'notebook_path', 'pattern', 'url', 'query', 'description', 'prompt', 'skill'] as const
48
+ const ENVELOPE_FIELDS = new Set(['tool', 'tool_use_id', 'agentId', 'consent', 'requestMeta'])
49
+ const CHANGE_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit'])
50
+ const READ_TOOLS = new Set(['Read', 'Grep', 'Glob'])
51
+ export const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
52
+
53
+ export const ICONS = {
54
+ summary: '\u{F0756}',
55
+ commands: '\u{E795}',
56
+ diff: '\u{F4D2}',
57
+ history: '\u{F02A2}',
58
+ ok: '\u{F00C}',
59
+ error: '\u{F00D}',
60
+ running: '\u{F0996}',
61
+ denied: '\u{F05E}',
62
+ interrupted: '\u{F073A}',
63
+ waiting: '\u{F252}',
64
+ agent: '\u{F06A9}',
65
+ cost: '\u{F01C1}',
66
+ time: '\u{F051B}',
67
+ files: '\u{F0222}',
68
+ gauge: '\u{F029A}',
69
+ brain: '\u{F09D1}',
70
+ question: '\u{F02D7}',
71
+ decision: '\u{F062C}',
72
+ read: '\u{F0349}',
73
+ edit: '\u{F03EB}',
74
+ validate: '\u{F0668}',
75
+ command: '\u{E795}',
76
+ other: '\u{F0EB}',
77
+ log: '\u{F1DA}',
78
+ folder: '\u{F07C}',
79
+ file: '\u{F016}',
80
+ commit: '\u{E729}',
81
+ merge: '\u{E727}',
82
+ branch: '\u{E725}',
83
+ uncommitted: '\u{F11E7}',
84
+ hunk: '\u{F4D2}',
85
+ ts: '\u{F06E6}',
86
+ tsx: '\u{E7BA}',
87
+ json: '\u{F0626}',
88
+ md: '\u{F0354}',
89
+ sh: '\u{E691}',
90
+ } as const
91
+
92
+ const FILE_ICONS: Record<string, string> = {
93
+ ts: ICONS.ts,
94
+ mts: ICONS.ts,
95
+ cts: ICONS.ts,
96
+ tsx: ICONS.tsx,
97
+ jsx: ICONS.tsx,
98
+ json: ICONS.json,
99
+ md: ICONS.md,
100
+ sh: ICONS.sh,
101
+ zsh: ICONS.sh,
102
+ bash: ICONS.sh,
103
+ }
104
+
105
+ const entries = atom({ plugin: 'project-brain-activity', key: 'entries' } as const, [] as ToolEntry[], { shape: 'entries-4' })
106
+ const tabs = atom({ plugin: 'project-brain-activity', key: 'tabs' } as const, {} as Record<string, Tab>, { shape: 'tabs-1' })
107
+ const toggled = atom({ plugin: 'project-brain-activity', key: 'toggled' } as const, [] as string[], { shape: 'toggled-2' })
108
+ const changes = atom({ plugin: 'project-brain-activity', key: 'changes' } as const, [] as FileChange[], { shape: 'changes-2' })
109
+ const openFiles = atom({ plugin: 'project-brain-activity', key: 'openFiles' } as const, [] as string[], { shape: 'open-files-2' })
110
+ const diffs = atom({ plugin: 'project-brain-activity', key: 'diffs' } as const, {} as Record<string, DiffPatch>, { shape: 'diffs-2' })
111
+ const costUsd = atom({ plugin: 'project-brain-activity', key: 'costUsd' } as const, 0, { shape: 'cost-1' })
112
+ const stepContext = atom({ plugin: 'project-brain-activity', key: 'stepContext' } as const, {} as Record<string, StepContext>, { shape: 'step-context-1' })
113
+ const contextUsage = atom({ plugin: 'project-brain-activity', key: 'context' } as const, { window: 0 } as ContextUsage, { shape: 'context-2' })
114
+ const agents = atom({ plugin: 'project-brain-activity', key: 'agents' } as const, [] as AgentRecord[], { shape: 'agents-1' })
115
+ const pickedAgent = atom({ plugin: 'project-brain-activity', key: 'pickedAgent' } as const, '', { shape: 'picked-1' })
116
+ const working = atom({ plugin: 'project-brain-activity', key: 'working' } as const, false, { shape: 'working-1' })
117
+ const scroll = atom({ plugin: 'project-brain-activity', key: 'scroll' } as const, { offset: 0, follow: false } as PaneScroll, { shape: 'scroll-1' })
118
+ const commits = atom({ plugin: 'project-brain-activity', key: 'commits' } as const, [] as CommitRecord[], { shape: 'commits-1' })
119
+ const scopes = atom({ plugin: 'project-brain-activity', key: 'scopes' } as const, {} as Record<string, CambiosScope>, { shape: 'scopes-1' })
120
+ const branch = atom({ plugin: 'project-brain-activity', key: 'branch' } as const, { isLoaded: false, files: [], commits: [] } as BranchView, { shape: 'branch-1' })
121
+ const autoOpen = atom({ plugin: 'project-brain-activity', key: 'autoOpen' } as const, true, { shape: 'auto-open-1' })
122
+ const editor = atom({ plugin: 'project-brain-activity', key: 'editor' } as const, { dir: '', tab: '' } as EditorState, { shape: 'editor-1' })
123
+ const accentColor = atom({ plugin: 'project-brain-activity', key: 'accent' } as const, 'claude' as string, { shape: 'accent-1' })
124
+
125
+ /** Claude Code's session colours (/color) in the default theme; 'default' and unknown names keep the claude tone. */
126
+ const SESSION_COLORS: Record<string, string> = {
127
+ red: 'rgb(220,38,38)', blue: 'rgb(106,155,204)', green: 'rgb(22,163,74)', yellow: 'rgb(202,138,4)',
128
+ purple: 'rgb(130,125,189)', orange: 'rgb(217,119,87)', pink: 'rgb(196,102,134)', cyan: 'rgb(8,145,178)',
129
+ }
130
+
131
+ /** The last `"agentColor":"<name>"` grep match in the transcript, as a colour the pane can paint. */
132
+ export const accentOf = (grepOutput: string): string => {
133
+ const names = [...grepOutput.matchAll(/"agentColor":"([a-z]+)"/g)].map(match => match[1] ?? '')
134
+ return SESSION_COLORS[names.at(-1) ?? ''] ?? 'claude'
135
+ }
136
+
137
+ /** Reads the session colour Claude Code writes into the transcript as an `agent-color` entry. */
138
+ const refreshAccent = async ($: Api): Promise<void> => {
139
+ const [id, root, home] = await Promise.all([
140
+ $.session.id(),
141
+ $.session.root(),
142
+ $.process.run(['/usr/bin/printenv', 'HOME']).then(out => out.stdout.trim()).catch(() => ''),
143
+ ])
144
+ if (!home || !/^[0-9a-f-]{36}$/.test(id)) return
145
+ const transcript = `${home}/.claude/projects/${root.replace(/[^A-Za-z0-9]/g, '-')}/${id}.jsonl`
146
+ const found = await $.process.run(['/usr/bin/grep', '-a', '-o', '"agentColor":"[a-z]*"', transcript], { timeoutMs: 3000 }).catch(() => undefined)
147
+ if (!found) return
148
+ const next = accentOf(found.stdout)
149
+ if (next !== (await read($, accentColor))) await update($, accentColor, () => next)
150
+ }
151
+
152
+ const sessionStart = atom({ plugin: 'project-brain-activity', key: 'sessionStart' } as const, 0, { shape: 'session-start-1' })
153
+ const commitCalls = atom({ plugin: 'project-brain-activity', key: 'commitCalls' } as const, [] as CommitCall[], { shape: 'commit-calls-1' })
154
+ const history = atom({ plugin: 'project-brain-activity', key: 'history' } as const, { state: 'idle', rows: [], more: 0, loadedAt: 0 } as HistoryView, { shape: 'history-1' })
155
+ const historyFiles = atom({ plugin: 'project-brain-activity', key: 'historyFiles' } as const, {} as Record<string, HistoryFiles>, { shape: 'history-files-1' })
156
+
157
+ type Api = Parameters<Hook<'turn.complete'>>[0]
158
+
159
+ // Timers are not drawn state: a reload dropping them only loses one debounce.
160
+ let refreshTimer: { cancel: () => void } | undefined
161
+ let autoOpenSent = false
162
+ let rescanTimer: { cancel: () => void } | undefined
163
+ let scanning: Promise<void> | undefined
164
+ let scanAgain = false
165
+ let historyLoading: Promise<void> | undefined
166
+
167
+ // ---------------------------------------------------------------- text
168
+
169
+ const ANSI = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007]*(?:\u0007|\u001b\\)|\u001b[@-_]/g
170
+ const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g
171
+ export const clean = (value: string): string => value.replace(ANSI, '').replace(/\t/g, ' ').replace(CONTROL, '')
172
+
173
+ const text = (value: unknown): string | undefined => (typeof value === 'string' && value !== '' ? value : undefined)
174
+
175
+ export const oneLine = (raw: string): string => clean(raw).replace(/\s+/g, ' ').trim()
176
+
177
+ const cleanText = (value: unknown): string | undefined => {
178
+ const found = text(value)
179
+ return found === undefined ? undefined : oneLine(found)
180
+ }
181
+
182
+ export const summarize = (input: Record<string, unknown>): string => {
183
+ const field = SUMMARY_FIELDS.find(name => text(input[name]) !== undefined)
184
+ if (field) return oneLine(String(input[field])).slice(0, 200)
185
+ const own = Object.fromEntries(Object.entries(input).filter(([name]) => !ENVELOPE_FIELDS.has(name)))
186
+ return oneLine(JSON.stringify(own)).slice(0, 200)
187
+ }
188
+
189
+ const lastLines = (raw: string | undefined, count: number): string =>
190
+ clean(raw ?? '')
191
+ .split('\n')
192
+ .map(line => line.trimEnd())
193
+ .filter(line => line !== '')
194
+ .slice(-count)
195
+ .map(line => line.slice(0, 300))
196
+ .join('\n')
197
+
198
+ export const dollars = (usd: number): string => `~$${usd < 10 ? usd.toFixed(2) : usd.toFixed(1)}`
199
+
200
+ export const seconds = (ms: number | undefined): string => (ms === undefined ? '' : `${(ms / 1000).toFixed(1)} s`)
201
+
202
+ export const fit = (value: string, width: number): string => {
203
+ const room = Math.max(1, width)
204
+ return value.length <= room ? value : `${value.slice(0, Math.max(0, room - 1))}…`
205
+ }
206
+
207
+ const baseName = (path: string): string => path.split('/').pop() ?? path
208
+
209
+ const stem = (path: string): string => baseName(path).replace(/\.[^.]+$/, '')
210
+
211
+ const joinY = (parts: string[]): string =>
212
+ parts.length <= 1 ? (parts[0] ?? '') : `${parts.slice(0, -1).join(', ')} y ${parts.at(-1)}`
213
+
214
+ const distinct = (values: (string | undefined)[]): string[] => [...new Set(values.filter((one): one is string => one !== undefined))]
215
+
216
+ export const fileIcon = (path: string): string => FILE_ICONS[baseName(path).split('.').pop()?.toLowerCase() ?? ''] ?? ICONS.file
217
+
218
+ export const compact = (count: number): string => {
219
+ const trimmed = (value: number) => value.toFixed(1).replace(/\.0$/, '')
220
+ if (count < 1000) return String(Math.round(count))
221
+ if (count < 1_000_000) return count < 10_000 ? `${trimmed(count / 1000)}k` : `${Math.round(count / 1000)}k`
222
+ return `${trimmed(count / 1_000_000)}M`
223
+ }
224
+
225
+ export const contextPercentOf = (usage: ContextUsage): number | undefined =>
226
+ usage.tokens === undefined || usage.window <= 0 ? undefined : (usage.percent ?? (usage.tokens / usage.window) * 100)
227
+
228
+ export const contextLabel = (usage: ContextUsage): string => {
229
+ if (usage.window <= 0) return usage.tokens === undefined ? 'Contexto: sin medir' : `Contexto: ${compact(usage.tokens)} tokens`
230
+ const percent = contextPercentOf(usage)
231
+ const tokens = usage.tokens === undefined ? '—' : compact(usage.tokens)
232
+ return `Contexto: ${tokens} / ${compact(usage.window)} tokens${percent === undefined ? '' : ` (${Math.round(percent)} %)`}`
233
+ }
234
+
235
+ /**
236
+ * The context of the selected loop: the session's own figures for the main loop; for a subagent, its last
237
+ * model request (input + cache written + cache read) over the main window when it runs the same model.
238
+ */
239
+ export const scopedContext = (snap: Pick<Snapshot, 'context' | 'steps'>, scope: string): ContextUsage => {
240
+ if (scope === MAIN) return snap.context
241
+ const own = snap.steps[scope]
242
+ if (own === undefined) return { window: snap.context.window }
243
+ const sameModel = snap.steps[MAIN] !== undefined && snap.steps[MAIN].model === own.model
244
+ return sameModel ? { tokens: own.tokens, window: snap.context.window } : { tokens: own.tokens, window: 0 }
245
+ }
246
+
247
+ export const contextBar = (percent: number | undefined): string => {
248
+ const filled = percent === undefined ? 0 : Math.min(10, Math.max(0, Math.round(percent / 10)))
249
+ return '▰'.repeat(filled) + '▱'.repeat(10 - filled)
250
+ }
251
+
252
+ const contextTone = (percent: number | undefined): Tone =>
253
+ percent === undefined ? 'subtle' : percent < 60 ? 'success' : percent <= 85 ? 'warning' : 'error'
254
+
255
+ // ---------------------------------------------------------------- commands
256
+
257
+ const SEGMENT_SPLIT = /\s*(?:&&|\|\||;|\||\n)\s*/
258
+
259
+ export const commandHeads = (command: string): string[] =>
260
+ command
261
+ .split(SEGMENT_SPLIT)
262
+ .map(segment => segment.trim().replace(/^(?:[A-Za-z_]\w*=\S*\s+)*/, '').replace(/^(?:time|exec|command)\s+/, ''))
263
+ .filter(Boolean)
264
+
265
+ const TEST_HEADS = [
266
+ /^bun\s+(?:run\s+)?test\b/,
267
+ /^(?:npx\s+|bunx\s+|yarn\s+|pnpm\s+(?:exec\s+|dlx\s+)?)?(?:vitest|jest)\b/,
268
+ /^(?:python3?\s+-m\s+|uv\s+run\s+)?pytest\b/,
269
+ /^go\s+test\b/,
270
+ /^cargo\s+test\b/,
271
+ /^(?:pnpm|npm|yarn)\s+(?:run\s+)?test\b/,
272
+ ]
273
+
274
+ const CHECK_HEADS = [
275
+ /^(?:npx\s+|bunx\s+|yarn\s+|pnpm\s+(?:exec\s+)?)?(?:tsc|eslint|biome)\b/,
276
+ /^(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?(?:lint|typecheck|check)\b/,
277
+ ]
278
+
279
+ export const isTestCommand = (command: string): boolean => commandHeads(command).some(head => TEST_HEADS.some(pattern => pattern.test(head)))
280
+
281
+ export const isCheckCommand = (command: string): boolean => commandHeads(command).some(head => CHECK_HEADS.some(pattern => pattern.test(head)))
282
+
283
+ export const isValidationCommand = (command: string): boolean => isTestCommand(command) || isCheckCommand(command)
284
+
285
+ const WORD = String.raw`(?:'[^']*'|"[^"]*"|[^\s'"]+)`
286
+ const GIT_OPTION = String.raw`(?:\s+-[Cc]\s+${WORD}|\s+--?[\w-]+(?:=${WORD})?)`
287
+ const GIT_VERB = new RegExp(String.raw`^\(*\s*git(${GIT_OPTION}*)\s+(commit|merge|cherry-pick|revert)\b`)
288
+ const CD_HEAD = new RegExp(String.raw`^\(*\s*(?:cd|pushd)\s+(${WORD})\s*\)?$`)
289
+ const DASH_C = new RegExp(String.raw`\s-C\s+(${WORD})`, 'g')
290
+
291
+ const unquote = (word: string): string => word.replace(/^'([\s\S]*)'$/, '$1').replace(/^"([\s\S]*)"$/, '$1')
292
+
293
+ const joinDir = (base: string | undefined, next: string): string =>
294
+ base === undefined || next.startsWith('/') || next.startsWith('~') ? next : `${base.replace(/\/+$/, '')}/${next}`
295
+
296
+ /** The git verbs that make a commit, in a command with any `cd`, `git -C` or global option before them. */
297
+ export const gitCommitVerbs = (command: string): string[] =>
298
+ distinct(commandHeads(command).map(head => GIT_VERB.exec(head)?.[2]))
299
+
300
+ /**
301
+ * The directory the first commit verb runs in, as the command names it: every
302
+ * `cd` before it, then its own `-C` options. Undefined when it names none.
303
+ */
304
+ export const commitDirOf = (command: string): string | undefined => {
305
+ let dir: string | undefined
306
+ for (const head of commandHeads(command)) {
307
+ const cd = CD_HEAD.exec(head)
308
+ if (cd?.[1] !== undefined) {
309
+ dir = joinDir(dir, unquote(cd[1]))
310
+ continue
311
+ }
312
+ const verb = GIT_VERB.exec(head)
313
+ if (verb === null) continue
314
+ for (const option of (verb[1] ?? '').matchAll(DASH_C)) dir = joinDir(dir, unquote(option[1] ?? ''))
315
+ return dir
316
+ }
317
+ return undefined
318
+ }
319
+
320
+ export const exitCodeOf = (output: string | undefined, isError: boolean): number | undefined => {
321
+ if (!isError) return 0
322
+ const stated = /^\s*Exit code:?\s*(\d+)/i.exec(output ?? '')?.[1]
323
+ return stated === undefined ? undefined : Number(stated)
324
+ }
325
+
326
+ export type TestCounts = { passed?: number; failed?: number; pending?: number }
327
+
328
+ const countOf = (output: string, pattern: RegExp): number | undefined => {
329
+ const found = pattern.exec(output)?.[1]
330
+ return found === undefined ? undefined : Number(found)
331
+ }
332
+
333
+ export const testCounts = (output: string): TestCounts => ({
334
+ passed: countOf(output, /(\d+)\s+(?:pass(?:ed)?|passing)\b/i),
335
+ failed: countOf(output, /(\d+)\s+(?:fail(?:ed)?|failing)\b/i),
336
+ pending: countOf(output, /(\d+)\s+(?:skip(?:ped)?|todo|pending)\b/i),
337
+ })
338
+
339
+ const TEST_PATH = String.raw`[\w./@-]+\.(?:test|spec)\.[cm]?[jt]sx?`
340
+ const JEST_LINE = new RegExp(String.raw`^\s*(PASS|FAIL)\s+(${TEST_PATH})`)
341
+ const VITEST_LINE = new RegExp(String.raw`^\s*([✓✔]|[×✗❯])\s+(${TEST_PATH})`)
342
+ const BUN_HEADER = new RegExp(String.raw`^(${TEST_PATH}):\s*$`)
343
+
344
+ export const testFilesOf = (output: string): TestFile[] => {
345
+ const found = new Map<string, boolean>()
346
+ let bunFile: string | undefined
347
+ for (const line of clean(output).split('\n')) {
348
+ const jest = JEST_LINE.exec(line)
349
+ if (jest?.[2]) { found.set(jest[2], jest[1] === 'PASS'); continue }
350
+ const vitest = VITEST_LINE.exec(line)
351
+ if (vitest?.[2]) { found.set(vitest[2], /[✓✔]/.test(vitest[1] ?? '')); continue }
352
+ const header = BUN_HEADER.exec(line.trim())
353
+ if (header?.[1]) { bunFile = header[1]; found.set(bunFile, found.get(bunFile) ?? true); continue }
354
+ if (bunFile !== undefined && /^\s*(?:\(fail\)|✗)/.test(line)) found.set(bunFile, false)
355
+ }
356
+ return [...found].slice(0, TEST_FILES).map(([file, ok]) => ({ file, ok }))
357
+ }
358
+
359
+ export const verdictOf = (entry: ToolEntry): 'PASS' | 'FAIL' | undefined => {
360
+ if (entry.status === 'running' || entry.command === undefined) return undefined
361
+ const counts = testCounts(entry.output)
362
+ const validates = isValidationCommand(entry.command)
363
+ if (validates && counts.failed !== undefined && counts.failed > 0) return 'FAIL'
364
+ if (validates) return entry.exitCode === 0 ? 'PASS' : 'FAIL'
365
+ return undefined
366
+ }
367
+
368
+ export const resultLine = (entry: ToolEntry): string => {
369
+ const counts = isTestCommand(entry.command ?? '') ? testCounts(entry.output) : {}
370
+ const parts: string[] = []
371
+ if (counts.passed !== undefined) parts.push(`${counts.passed} pruebas`)
372
+ if (counts.failed !== undefined && counts.failed > 0) parts.push(`${counts.failed} fallaron`)
373
+ if (counts.pending !== undefined && counts.pending > 0) parts.push(`${counts.pending} ${counts.pending === 1 ? 'pendiente' : 'pendientes'}`)
374
+ if (entry.exitCode !== undefined) parts.push(`exit ${entry.exitCode}`)
375
+ return parts.join(' · ')
376
+ }
377
+
378
+ // ---------------------------------------------------------------- git parsing
379
+
380
+ const SHA = /^[0-9a-f]{7,40}$/
381
+
382
+ export const parseNumstatZ = (stdout: string): FileChange[] =>
383
+ stdout
384
+ .split('\0')
385
+ .map(record => record.replace(/^\n+/, ''))
386
+ .map(record => /^(-|\d+)\t(-|\d+)\t([\s\S]+)$/.exec(record))
387
+ .filter((found): found is RegExpExecArray => found !== null)
388
+ .map(([, added, removed, path]) => ({
389
+ path: path ?? '',
390
+ added: added === '-' ? 0 : Number(added),
391
+ removed: removed === '-' ? 0 : Number(removed),
392
+ ...(added === '-' ? { binary: true } : {}),
393
+ }))
394
+
395
+ export const lineCount = (body: string): number => (body === '' ? 0 : body.split('\n').length - (body.endsWith('\n') ? 1 : 0))
396
+
397
+ export type FoundCommit = { sha: string; subject: string; branch: string }
398
+
399
+ const COMMIT_LINE = /^\[(.+?) ([0-9a-f]{7,40})\] (.*)$/
400
+
401
+ export const commitsIn = (command: string, output: string): FoundCommit[] => {
402
+ if (gitCommitVerbs(command).length === 0) return []
403
+ return clean(output)
404
+ .split('\n')
405
+ .map(line => COMMIT_LINE.exec(line.trim()))
406
+ .filter((found): found is RegExpExecArray => found !== null)
407
+ .map(([, name, sha, subject]) => ({ sha: sha ?? '', subject: oneLine(subject ?? ''), branch: oneLine((name ?? '').replace(/ \(root-commit\)$/, '')) }))
408
+ }
409
+
410
+ export const madeMergeCommit = (command: string, output: string): boolean =>
411
+ gitCommitVerbs(command).includes('merge') && /^Merge made by/m.test(output)
412
+
413
+ export const addCommits = (list: CommitRecord[], found: FoundCommit[], agentId: string | undefined, at: number): CommitRecord[] => {
414
+ const fresh = found.filter(one => SHA.test(one.sha) && !list.some(known => known.sha === one.sha))
415
+ return [...list, ...fresh.map(one => ({ ...one, at, ...(agentId === undefined ? {} : { agentId }) }))].slice(-200)
416
+ }
417
+
418
+ export const parseLogZ = (stdout: string): BranchCommit[] =>
419
+ stdout
420
+ .split('\0')
421
+ .map(record => record.replace(/^\n+/, '').split('\u001f'))
422
+ .filter(([sha]) => sha !== undefined && SHA.test(sha))
423
+ .map(([sha, subject]) => ({ sha: sha ?? '', subject: oneLine(subject ?? '') }))
424
+
425
+ export const diffRows = (patch: string): DiffRow[] => {
426
+ const rows: DiffRow[] = []
427
+ let oldLine = 0
428
+ let newLine = 0
429
+ for (const raw of patch.split('\n')) {
430
+ const hunk = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@(.*)$/.exec(raw)
431
+ if (hunk) {
432
+ oldLine = Number(hunk[1])
433
+ newLine = Number(hunk[2])
434
+ rows.push({ gutter: '', sign: '@@', text: clean(`línea ${newLine}${hunk[3] ?? ''}`), kind: 'hunk' })
435
+ continue
436
+ }
437
+ if (rows.length === 0 || raw.startsWith('\\')) continue
438
+ const sign = raw.charAt(0)
439
+ const body = clean(raw.slice(1))
440
+ if (sign === '+') rows.push({ gutter: String(newLine++), sign: '+', text: body, kind: 'add' })
441
+ else if (sign === '-') rows.push({ gutter: String(oldLine++), sign: '-', text: body, kind: 'del' })
442
+ else if (sign === ' ') { rows.push({ gutter: String(newLine), sign: ' ', text: body, kind: 'same' }); oldLine++; newLine++ }
443
+ }
444
+ return rows
445
+ }
446
+
447
+ // ---------------------------------------------------------------- git loaders
448
+
449
+ export type RunResult = { exitCode: number; stdout: string; stderr: string }
450
+ export type Run = (argv: readonly string[], init?: { cwd?: string; timeoutMs?: number; stdin?: string }) => Promise<RunResult>
451
+ export type ReadText = (path: string) => Promise<string>
452
+
453
+ const quietly = (run: Run, argv: readonly string[], cwd?: string, stdin?: string): Promise<RunResult | undefined> =>
454
+ run(argv, cwd === undefined && stdin === undefined ? undefined : { ...(cwd === undefined ? {} : { cwd }), ...(stdin === undefined ? {} : { stdin }) }).catch(() => undefined)
455
+
456
+ export const gitTop = async (run: Run, cwd?: string): Promise<string | undefined> => {
457
+ const found = await quietly(run, ['git', 'rev-parse', '--show-toplevel'], cwd)
458
+ return found?.exitCode === 0 ? found.stdout.replace(/\n$/, '') : undefined
459
+ }
460
+
461
+ export const loadUncommitted = async (run: Run, top: string, readText: ReadText): Promise<FileChange[] | undefined> => {
462
+ const head = await quietly(run, ['git', 'rev-parse', '--verify', '-q', 'HEAD'], top)
463
+ const base = head?.exitCode === 0 ? 'HEAD' : EMPTY_TREE
464
+ const tracked = await quietly(run, ['git', 'diff', '--numstat', '-z', '--no-renames', base], top)
465
+ if (tracked?.exitCode !== 0) return undefined
466
+ const others = await quietly(run, ['git', 'ls-files', '--others', '--exclude-standard', '-z'], top)
467
+ const paths = others?.exitCode === 0 ? others.stdout.split('\0').filter(Boolean).slice(0, UNTRACKED_MAX) : []
468
+ const untracked = await Promise.all(
469
+ paths.map(async (path): Promise<FileChange> => {
470
+ const body = await readText(`${top}/${path}`).catch(() => undefined)
471
+ const isBinary = body === undefined || body.includes('\0')
472
+ return { path, added: isBinary ? 0 : lineCount(body), removed: 0, untracked: true, ...(isBinary ? { binary: true } : {}) }
473
+ }),
474
+ )
475
+ return [...parseNumstatZ(tracked.stdout), ...untracked]
476
+ }
477
+
478
+ export type CommitStats = { added: number; removed: number; files: FileChange[]; isMerge: boolean }
479
+
480
+ export const loadCommitStats = async (run: Run, top: string, sha: string): Promise<CommitStats | undefined> => {
481
+ if (!SHA.test(sha)) return undefined
482
+ const shown = await quietly(run, ['git', 'show', '--numstat', '-z', '--no-renames', '--diff-merges=first-parent', '--format=', sha], top)
483
+ if (shown?.exitCode !== 0) return undefined
484
+ const parents = await quietly(run, ['git', 'show', '-s', '--format=%P', sha], top)
485
+ const files = parseNumstatZ(shown.stdout)
486
+ return {
487
+ added: files.reduce((sum, one) => sum + one.added, 0),
488
+ removed: files.reduce((sum, one) => sum + one.removed, 0),
489
+ files: files.slice(0, COMMIT_FILES),
490
+ isMerge: (parents?.stdout.trim().split(/\s+/).filter(Boolean).length ?? 0) > 1,
491
+ }
492
+ }
493
+
494
+ export const loadHeadCommit = async (run: Run, top: string): Promise<FoundCommit | undefined> => {
495
+ const head = await quietly(run, ['git', 'log', '-1', '--format=%h%x1f%s', 'HEAD'], top)
496
+ const name = await quietly(run, ['git', 'rev-parse', '--abbrev-ref', 'HEAD'], top)
497
+ const [sha, subject] = (head?.stdout ?? '').replace(/\n$/, '').split('\u001f')
498
+ if (head?.exitCode !== 0 || sha === undefined || !SHA.test(sha)) return undefined
499
+ return { sha, subject: oneLine(subject ?? ''), branch: oneLine(name?.stdout ?? '') }
500
+ }
501
+
502
+ const BASE_REFS = ['main', 'master', 'origin/main', 'origin/master']
503
+
504
+ export const loadBranch = async (run: Run, top: string): Promise<BranchView> => {
505
+ for (const ref of BASE_REFS) {
506
+ const exists = await quietly(run, ['git', 'rev-parse', '--verify', '-q', `${ref}^{commit}`], top)
507
+ if (exists?.exitCode !== 0) continue
508
+ const merged = await quietly(run, ['git', 'merge-base', 'HEAD', ref], top)
509
+ const base = merged?.stdout.trim() ?? ''
510
+ if (merged?.exitCode !== 0 || !/^[0-9a-f]{40,64}$/.test(base)) continue
511
+ const numstat = await quietly(run, ['git', 'diff', '--numstat', '-z', '--no-renames', `${base}...HEAD`], top)
512
+ const log = await quietly(run, ['git', 'log', '-z', `-n${BRANCH_COMMITS}`, '--format=%h%x1f%s', `${base}..HEAD`], top)
513
+ return { isLoaded: true, baseRef: ref, base, files: parseNumstatZ(numstat?.stdout ?? ''), commits: parseLogZ(log?.stdout ?? '') }
514
+ }
515
+ return { isLoaded: true, files: [], commits: [], error: 'No encontré main ni master para comparar la rama.' }
516
+ }
517
+
518
+ // ---------------------------------------------------------------- session commits
519
+
520
+ export type ScannedCommit = { sha: string; subject: string; at: number; isMerge: boolean; branch: string; agentId?: string }
521
+ export type Worktree = { path: string; branch?: string; head?: string }
522
+
523
+ export const SCAN_FORMAT = '--format=%H%x1f%ct%x1f%P%x1f%s'
524
+
525
+ export const parseScanZ = (stdout: string): Omit<ScannedCommit, 'branch'>[] =>
526
+ stdout
527
+ .split('\0')
528
+ .map(record => record.replace(/^\n+/, '').split('\u001f'))
529
+ .filter(([sha, at]) => sha !== undefined && /^[0-9a-f]{40,64}$/.test(sha) && /^\d+$/.test(at ?? ''))
530
+ .map(([sha, at, parents, ...subject]) => ({
531
+ sha: sha ?? '',
532
+ at: Number(at) * 1000,
533
+ isMerge: (parents ?? '').trim().split(/\s+/).filter(Boolean).length > 1,
534
+ subject: oneLine(subject.join(' ')),
535
+ }))
536
+
537
+ export const parseWorktrees = (porcelain: string): Worktree[] =>
538
+ porcelain
539
+ .split(/\n\s*\n/)
540
+ .map(block => {
541
+ const lines = block.split('\n')
542
+ const value = (name: string) => lines.find(one => one.startsWith(`${name} `))?.slice(name.length + 1)
543
+ const path = value('worktree')
544
+ const branchRef = value('branch')
545
+ const head = value('HEAD')
546
+ return path === undefined || !SAFE_PATH.test(path)
547
+ ? undefined
548
+ : { path, ...(branchRef ? { branch: oneLine(branchRef.replace(/^refs\/heads\//, '')) } : {}), ...(head ? { head } : {}) }
549
+ })
550
+ .filter((one): one is Worktree => one !== undefined)
551
+
552
+ /** `git name-rev --name-only` lines, one per sha in order: `main~2` names `main`. */
553
+ export const parseNameRev = (stdout: string, shas: string[]): Record<string, string> => {
554
+ const names = stdout.split('\n')
555
+ return Object.fromEntries(
556
+ shas
557
+ .map((sha, index) => [sha, oneLine((names[index] ?? '').replace(/[~^].*$/, ''))] as const)
558
+ .filter(([, name]) => name !== '' && name !== 'undefined'),
559
+ )
560
+ }
561
+
562
+ /**
563
+ * Who made a commit the rescan found: the agent whose commit-verb call was
564
+ * running when it was made (preferring one in the commit's worktree); else the
565
+ * agent whose latest commit-verb call ran in that worktree; else the main loop.
566
+ */
567
+ export const attributeCommit = (commit: Pick<ScannedCommit, 'at' | 'branch'>, calls: CommitCall[], worktrees: Worktree[]): string | undefined => {
568
+ const tree = worktrees.find(one => one.branch !== undefined && one.branch === commit.branch)?.path
569
+ const during = calls.filter(call => call.startedAt - WINDOW_SLACK_MS <= commit.at && commit.at <= call.endedAt + WINDOW_SLACK_MS)
570
+ const inTree = tree === undefined ? [] : during.filter(call => call.top === tree)
571
+ const owners = distinct((inTree.length > 0 ? inTree : during).map(call => call.agentId ?? MAIN))
572
+ if (owners.length === 1) return owners[0] === MAIN ? undefined : owners[0]
573
+ if (tree === undefined) return undefined
574
+ const there = calls.filter(call => call.top === tree).sort((a, b) => a.startedAt - b.startedAt)
575
+ const latest = there.filter(call => call.startedAt <= commit.at + WINDOW_SLACK_MS).at(-1) ?? there.at(-1)
576
+ return latest?.agentId
577
+ }
578
+
579
+ const sameSha = (a: string, b: string): boolean => a.length > 0 && b.length > 0 && (a.startsWith(b) || b.startsWith(a))
580
+
581
+ /** Adds what the rescan found to the list, keyed by sha: a commit already known keeps its agent. */
582
+ export const mergeScanned = (list: CommitRecord[], found: ScannedCommit[]): CommitRecord[] => {
583
+ const merged = list.map(known => {
584
+ const same = found.find(one => sameSha(known.sha, one.sha))
585
+ return same !== undefined && known.branch === '' ? { ...known, branch: same.branch } : known
586
+ })
587
+ for (const one of found) {
588
+ if (merged.some(known => sameSha(known.sha, one.sha))) continue
589
+ merged.push({
590
+ sha: one.sha,
591
+ subject: one.subject,
592
+ branch: one.branch,
593
+ at: one.at,
594
+ ...(one.isMerge ? { isMerge: true } : {}),
595
+ ...(one.agentId === undefined ? {} : { agentId: one.agentId }),
596
+ })
597
+ }
598
+ return merged.sort((a, b) => a.at - b.at).slice(-SCAN_COMMITS)
599
+ }
600
+
601
+ export type SessionScan = { repo: string; commits: ScannedCommit[] }
602
+
603
+ /** Every commit this user made since `since`, on any branch of any worktree of the session's repository. */
604
+ export const scanSessionCommits = async (run: Run, since: number, calls: CommitCall[]): Promise<SessionScan | undefined> => {
605
+ const top = await gitTop(run)
606
+ if (top === undefined) return undefined
607
+ const common = await quietly(run, ['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'], top)
608
+ const repo = common?.exitCode === 0 && SAFE_PATH.test(common.stdout.trim()) ? common.stdout.trim() : top
609
+ const email = (await quietly(run, ['git', 'config', 'user.email'], top))?.stdout.trim() ?? ''
610
+ const author = email !== '' && SAFE_PATH.test(email) ? ['-F', `--author=<${email}>`] : []
611
+ const log = await quietly(run, ['git', 'log', '--all', `--since=@${Math.floor(since / 1000)}`, ...author, '-z', `-n${SCAN_COMMITS}`, SCAN_FORMAT], repo)
612
+ if (log?.exitCode !== 0) return undefined
613
+ const found = parseScanZ(log.stdout)
614
+ if (found.length === 0) return { repo, commits: [] }
615
+ const listed = await quietly(run, ['git', 'worktree', 'list', '--porcelain'], repo)
616
+ const worktrees = listed?.exitCode === 0 ? parseWorktrees(listed.stdout) : []
617
+ const shas = found.map(one => one.sha)
618
+ const named = await quietly(run, ['git', 'name-rev', '--name-only', '--refs=refs/heads/*', ...shas], repo)
619
+ const branches = named?.exitCode === 0 ? parseNameRev(named.stdout, shas) : {}
620
+ return {
621
+ repo,
622
+ commits: found.map(one => {
623
+ const branchName = branches[one.sha] ?? ''
624
+ const agentId = attributeCommit({ at: one.at, branch: branchName }, calls, worktrees)
625
+ return { ...one, branch: branchName, ...(agentId === undefined ? {} : { agentId }) }
626
+ }),
627
+ }
628
+ }
629
+
630
+ // ---------------------------------------------------------------- history
631
+
632
+ export const HISTORY_FORMAT = '--format=%x1e%h%x1f%D%x1f%ct%x1f%an%x1f%s'
633
+
634
+ export const parseGraphLog = (stdout: string): HistoryRow[] =>
635
+ stdout
636
+ .split('\n')
637
+ .filter(raw => raw.trim() !== '')
638
+ .map((raw): HistoryRow => {
639
+ const mark = raw.indexOf('\u001e')
640
+ const [sha, refs, at, author, ...subject] = mark < 0 ? [] : raw.slice(mark + 1).split('\u001f')
641
+ if (mark < 0 || sha === undefined || !SHA.test(sha)) return { graph: clean(raw).trimEnd() }
642
+ return {
643
+ graph: clean(raw.slice(0, mark)),
644
+ sha,
645
+ refs: (refs ?? '').split(', ').map(oneLine).filter(Boolean),
646
+ subject: oneLine(subject.join(' ')),
647
+ ...(/^\d+$/.test(at ?? '') ? { at: Number(at) } : {}),
648
+ author: oneLine(author ?? ''),
649
+ }
650
+ })
651
+
652
+ export const loadHistory = async (run: Run, now: number): Promise<HistoryView> => {
653
+ const top = await gitTop(run)
654
+ if (top === undefined) return { state: 'error', rows: [], more: 0, loadedAt: now, error: 'No hay repositorio git aquí.' }
655
+ const log = await quietly(run, ['git', 'log', '--graph', '--all', '--date-order', '--no-color', `-n${HISTORY_COMMITS}`, HISTORY_FORMAT], top)
656
+ if (log?.exitCode !== 0) {
657
+ const reason = oneLine(log?.stderr ?? '').slice(0, 160)
658
+ return { state: 'error', rows: [], more: 0, loadedAt: now, error: `git log falló${reason ? `: ${reason}` : '.'}` }
659
+ }
660
+ const rows = parseGraphLog(log.stdout)
661
+ const shown = rows.filter(row => row.sha !== undefined).length
662
+ const counted = await quietly(run, ['git', 'rev-list', '--all', '--count'], top)
663
+ const total = counted?.exitCode === 0 ? Number(counted.stdout.trim()) : shown
664
+ return { state: 'ready', rows, more: Number.isFinite(total) ? Math.max(0, total - shown) : 0, loadedAt: now }
665
+ }
666
+
667
+ export const ago = (atSeconds: number | undefined, nowMs: number): string => {
668
+ if (atSeconds === undefined) return ''
669
+ const minutes = Math.max(0, Math.round((nowMs / 1000 - atSeconds) / 60))
670
+ if (minutes < 1) return 'ahora'
671
+ if (minutes < 60) return `hace ${minutes} min`
672
+ const hours = Math.round(minutes / 60)
673
+ if (hours < 24) return `hace ${hours} h`
674
+ const days = Math.round(hours / 24)
675
+ if (days < 14) return `hace ${days} d`
676
+ if (days < 60) return `hace ${Math.round(days / 7)} sem`
677
+ if (days < 365) return `hace ${Math.round(days / 30)} meses`
678
+ const years = Math.round(days / 365)
679
+ return `hace ${years} ${years === 1 ? 'año' : 'años'}`
680
+ }
681
+
682
+ export type DiffTarget = { scope: 'uncommitted' | 'commit' | 'branch'; path: string; sha?: string; untracked?: boolean }
683
+
684
+ export const targetKey = (target: DiffTarget): string =>
685
+ target.scope === 'commit' ? `c:${target.sha ?? ''}:${target.path}` : `${target.scope === 'branch' ? 'b' : 'u'}:${target.path}`
686
+
687
+ export const diffArgv = (target: DiffTarget): string[] | undefined => {
688
+ const plain = ['--no-color', '--no-ext-diff']
689
+ if (target.scope === 'uncommitted' && target.untracked) return ['git', 'diff', '--no-index', ...plain, '--', '/dev/null', target.path]
690
+ if (target.scope === 'uncommitted') return ['git', '--literal-pathspecs', 'diff', ...plain, 'HEAD', '--', target.path]
691
+ if (target.sha === undefined || !/^[0-9a-f]{7,64}$/.test(target.sha)) return undefined
692
+ if (target.scope === 'commit') return ['git', '--literal-pathspecs', 'show', ...plain, '--diff-merges=first-parent', '--format=', target.sha, '--', target.path]
693
+ return ['git', '--literal-pathspecs', 'diff', ...plain, `${target.sha}...HEAD`, '--', target.path]
694
+ }
695
+
696
+ export const fetchDiff = async (run: Run, top: string, target: DiffTarget): Promise<DiffPatch> => {
697
+ const argv = diffArgv(target)
698
+ const shown = argv ? await quietly(run, argv, top) : undefined
699
+ const rows = shown !== undefined && shown.exitCode <= 1 ? diffRows(shown.stdout) : []
700
+ return { rows: rows.slice(0, DIFF_LINES), total: rows.length }
701
+ }
702
+
703
+ // ---------------------------------------------------------------- editor
704
+
705
+ /** POSIX single quoting: the one quoting helper every command string uses. */
706
+ export const shQuote = (value: string): string => `'${value.replace(/'/g, `'\\''`)}'`
707
+
708
+ const SAFE_PATH = /^[^\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]+$/
709
+ const SAFE_DIR = /^[\w./-]+$/
710
+ const SAFE_BASE = /^(?:HEAD|[0-9a-f]{7,64})(?:~1)?$/
711
+ const SAFE_TAB = /^[\w-]{1,64}$/
712
+
713
+ export const diffCommand = (base: string): string =>
714
+ `lua vim.defer_fn(function() pcall(vim.cmd, "Gitsigns diffthis ${base}") end, 200)`
715
+
716
+ export const RESET_KEYS = '<C-\\><C-n>:silent! diffoff! | only<CR>'
717
+
718
+ export const diffKeys = (base: string): string => `<C-\\><C-n>:${diffCommand(base)}<CR>`
719
+
720
+ export type EditorRequest = { top: string; path: string; base: string; editor: EditorState }
721
+ export type EditorOutcome = { ok: boolean; message?: string; editor?: EditorState }
722
+
723
+ const ENV_NAMES = ['TMPDIR', 'XDG_RUNTIME_DIR', 'SUPACODE_SOCKET_PATH', 'TMUX'] as const
724
+
725
+ const readEnv = async (run: Run): Promise<Record<(typeof ENV_NAMES)[number], string>> => {
726
+ const values = await Promise.all(ENV_NAMES.map(name => quietly(run, ['printenv', name])))
727
+ return Object.fromEntries(ENV_NAMES.map((name, index) => [name, values[index]?.exitCode === 0 ? (values[index]?.stdout ?? '').replace(/\n$/, '') : ''])) as Record<(typeof ENV_NAMES)[number], string>
728
+ }
729
+
730
+ /**
731
+ * Opens `path` in one nvim per session, reused on every call. Every piece of
732
+ * data travels as its own argv item; the only command string is the one a
733
+ * terminal multiplexer needs, and every item in it goes through shQuote.
734
+ */
735
+ export const openInEditor = async (run: Run, exists: (path: string) => Promise<boolean>, request: EditorRequest): Promise<EditorOutcome> => {
736
+ if (!SAFE_PATH.test(request.path) || !SAFE_PATH.test(request.top)) return { ok: false, message: 'Ese nombre de archivo no se puede abrir en el editor.' }
737
+ if (!SAFE_BASE.test(request.base)) return { ok: false, message: 'Referencia de git no válida.' }
738
+ const file = `${request.top}/${request.path}`
739
+ const env = await readEnv(run)
740
+
741
+ let dir = request.editor.dir
742
+ if (dir !== '' && !(await isPrivateDir(run, dir))) dir = ''
743
+ if (dir === '' || !(await exists(dir).catch(() => false))) {
744
+ const base = (env.XDG_RUNTIME_DIR || env.TMPDIR || '/tmp').replace(/\/+$/, '')
745
+ const made = await quietly(run, ['mktemp', '-d', `${base}/pb-nvim.XXXXXX`])
746
+ dir = made?.exitCode === 0 ? made.stdout.trim() : ''
747
+ if (dir === '' || !SAFE_DIR.test(dir)) return { ok: false, message: 'No se pudo crear la carpeta privada del editor.' }
748
+ }
749
+ const sock = `${dir}/nvim.sock`
750
+ const state: EditorState = { dir, tab: dir === request.editor.dir ? request.editor.tab : '' }
751
+
752
+ const alive = await quietly(run, ['nvim', '--server', sock, '--remote-expr', '1'])
753
+ if (alive?.exitCode === 0) {
754
+ await quietly(run, ['nvim', '--server', sock, '--remote-send', RESET_KEYS])
755
+ const opened = await quietly(run, ['nvim', '--server', sock, '--remote', file])
756
+ if (opened?.exitCode !== 0) return { ok: false, message: 'nvim no pudo abrir el archivo.', editor: state }
757
+ await quietly(run, ['nvim', '--server', sock, '--remote-send', diffKeys(request.base)])
758
+ if (state.tab !== '' && env.SUPACODE_SOCKET_PATH !== '') await quietly(run, ['supacode', 'tab', 'focus', '-t', state.tab])
759
+ return { ok: true, editor: state }
760
+ }
761
+
762
+ await quietly(run, ['rm', '-f', '--', sock])
763
+ const launcher = `${dir}/open.sh`
764
+ const script = `#!/bin/sh\ncd ${shQuote(request.top)} && exec nvim --listen ${shQuote(sock)} ${shQuote(`+${diffCommand(request.base)}`)} -- ${shQuote(file)}\n`
765
+ const written = await quietly(run, ['sh', '-c', 'umask 077 && cat > "$1"', 'write-launcher', launcher], undefined, script)
766
+ if (written?.exitCode !== 0) return { ok: false, message: 'No se pudo preparar el editor.', editor: state }
767
+ const start = `/bin/sh ${launcher}`
768
+ if (env.SUPACODE_SOCKET_PATH !== '') {
769
+ const split = await quietly(run, ['supacode', 'pane', 'split', '-d', 'h', '-i', start])
770
+ if (split?.exitCode === 0) {
771
+ const tab = split.stdout.trim()
772
+ return { ok: true, editor: { dir, tab: SAFE_TAB.test(tab) ? tab : '' } }
773
+ }
774
+ }
775
+ if (env.TMUX !== '') {
776
+ const split = await quietly(run, ['tmux', 'split-window', '-h', start])
777
+ if (split?.exitCode === 0) return { ok: true, editor: { dir, tab: '' } }
778
+ }
779
+ const terminal = await quietly(run, [
780
+ 'osascript',
781
+ '-e', 'on run argv',
782
+ '-e', 'tell application "Terminal" to do script (item 1 of argv)',
783
+ '-e', 'end run',
784
+ start,
785
+ ])
786
+ return terminal?.exitCode === 0
787
+ ? { ok: true, editor: { dir, tab: '' } }
788
+ : { ok: false, message: 'No se pudo abrir el editor (sin Supacode, tmux ni Terminal).', editor: { dir, tab: '' } }
789
+ }
790
+
791
+ /** The socket directory is reused only while it is still ours: a directory, owned by this user, mode 0700. */
792
+ const isPrivateDir = async (run: Run, dir: string): Promise<boolean> => {
793
+ if (!SAFE_DIR.test(dir)) return false
794
+ const uid = (await quietly(run, ['id', '-u']))?.stdout.trim() ?? ''
795
+ if (!/^\d+$/.test(uid)) return false
796
+ const found = await quietly(run, ['find', dir, '-maxdepth', '0', '-type', 'd', '-user', uid, '-perm', '700'])
797
+ return found?.exitCode === 0 && found.stdout.trim() === dir
798
+ }
799
+
800
+ export const editorBase = (target: DiffTarget): string =>
801
+ target.scope === 'commit' ? `${target.sha ?? ''}~1` : target.scope === 'branch' ? (target.sha ?? '') : 'HEAD'
802
+
803
+ // ---------------------------------------------------------------- steps
804
+
805
+ export type StepKind = 'read' | 'edit' | 'validate' | 'command' | 'agent' | 'question' | 'other'
806
+
807
+ export type Step = {
808
+ key: string
809
+ kind: StepKind
810
+ title: string
811
+ detail: string
812
+ status: CallStatus
813
+ durationMs?: number
814
+ }
815
+
816
+ export const stepKindOf = (entry: ToolEntry): StepKind => {
817
+ if (READ_TOOLS.has(entry.tool)) return 'read'
818
+ if (CHANGE_TOOLS.has(entry.tool)) return 'edit'
819
+ if (entry.tool === 'Bash') return isValidationCommand(entry.command ?? '') ? 'validate' : 'command'
820
+ if (entry.tool === 'Agent' || entry.tool === 'Task') return 'agent'
821
+ if (entry.tool === 'AskUserQuestion') return 'question'
822
+ return 'other'
823
+ }
824
+
825
+ const SOLO_KINDS = new Set<StepKind>(['agent', 'question', 'other'])
826
+
827
+ const groupStatus = (group: ToolEntry[]): CallStatus => {
828
+ if (group.some(one => one.status === 'running')) return 'running'
829
+ if (group.some(one => one.status === 'error')) return 'error'
830
+ if (group.some(one => one.status === 'interrupted')) return 'interrupted'
831
+ if (group.some(one => one.status === 'denied')) return 'denied'
832
+ return 'ok'
833
+ }
834
+
835
+ export const wallTime = (group: ToolEntry[]): number | undefined => {
836
+ if (group.length === 0 || group.some(one => one.durationMs === undefined)) return undefined
837
+ const start = Math.min(...group.map(one => one.startedAt))
838
+ const end = Math.max(...group.map(one => one.startedAt + (one.durationMs ?? 0)))
839
+ return end - start
840
+ }
841
+
842
+ const filesLine = (files: string[], verb: string): string =>
843
+ files.length > 3 ? `${files.length} archivos ${verb}` : files.map(baseName).join(' · ')
844
+
845
+ const describeRead = (group: ToolEntry[], running: boolean) => {
846
+ const files = distinct(group.filter(one => one.tool === 'Read').map(one => one.file))
847
+ const searches = group.filter(one => one.tool !== 'Read')
848
+ const topic = files.length === 0 ? 'el código' : files.length > 2 ? `${files.length} archivos` : joinY(files.map(stem))
849
+ const parts = [files.length > 0 ? filesLine(files, 'consultados') : '', searches.length > 0 ? `${searches.length} ${searches.length === 1 ? 'búsqueda' : 'búsquedas'}` : '']
850
+ return { title: `${running ? 'Revisando' : 'Revisó'} ${topic}`, detail: parts.filter(Boolean).join(' · ') }
851
+ }
852
+
853
+ const describeEdit = (group: ToolEntry[], running: boolean) => {
854
+ const files = distinct(group.map(one => one.file))
855
+ const title =
856
+ files.length === 1
857
+ ? `${running ? 'Actualizando' : 'Actualizó'} ${stem(files[0] ?? '')}`
858
+ : files.length > 1
859
+ ? `${running ? 'Actualizando' : 'Actualizó'} ${files.length} archivos`
860
+ : running ? 'Aplicando cambios' : 'Aplicó cambios'
861
+ return { title, detail: filesLine(files, 'modificados') }
862
+ }
863
+
864
+ const describeValidate = (group: ToolEntry[], running: boolean) => {
865
+ const commands = group.map(one => one.command ?? '')
866
+ const hasTests = commands.some(isTestCommand)
867
+ const passed = group.reduce((sum, one) => sum + (isTestCommand(one.command ?? '') ? (testCounts(one.output).passed ?? 0) : 0), 0)
868
+ const parts = distinct([
869
+ commands.some(command => commandHeads(command).some(head => /\btsc\b|typecheck/.test(head))) ? 'tipos' : undefined,
870
+ commands.some(command => commandHeads(command).some(head => /\b(?:lint|eslint|biome)\b/.test(head))) ? 'lint' : undefined,
871
+ hasTests ? (passed > 0 ? `${passed} pruebas` : 'pruebas') : undefined,
872
+ ])
873
+ const title = running ? (hasTests ? 'Ejecutando pruebas' : 'Ejecutando validaciones') : 'Ejecutó validaciones'
874
+ return { title, detail: parts.join(' · ') }
875
+ }
876
+
877
+ const describeCommand = (group: ToolEntry[], running: boolean) => {
878
+ const commands = group.map(one => one.command ?? '')
879
+ const detail = commands.length === 1 ? (commands[0] ?? '') : `${commands.length} comandos: ${distinct(commands.map(command => command.split(' ')[0])).join(' · ')}`
880
+ return { title: running ? 'Ejecutando comandos' : 'Ejecutó comandos', detail }
881
+ }
882
+
883
+ const TITLES: Record<string, string> = {
884
+ Bash: 'Ejecución de comando',
885
+ Read: 'Lectura de archivo',
886
+ Edit: 'Edición de archivo',
887
+ Write: 'Escritura de archivo',
888
+ Grep: 'Búsqueda en código',
889
+ Glob: 'Búsqueda de archivos',
890
+ Agent: 'Subagente',
891
+ WebFetch: 'Consulta web',
892
+ WebSearch: 'Búsqueda web',
893
+ Skill: 'Skill',
894
+ }
895
+
896
+ const titleOf = (tool: string): string => TITLES[tool] ?? (tool.startsWith('mcp__') ? `MCP · ${tool.split('__').pop()}` : tool)
897
+
898
+ const describeStep = (kind: StepKind, group: ToolEntry[], running: boolean): { title: string; detail: string } => {
899
+ const first = group[0]
900
+ if (kind === 'read') return describeRead(group, running)
901
+ if (kind === 'edit') return describeEdit(group, running)
902
+ if (kind === 'validate') return describeValidate(group, running)
903
+ if (kind === 'command') return describeCommand(group, running)
904
+ if (kind === 'agent') return { title: `${running ? 'Delegando' : 'Delegó'}: ${first?.summary ?? ''}`, detail: first?.note ?? 'subagente' }
905
+ if (kind === 'question') {
906
+ const asked = first?.decisions ?? []
907
+ return { title: running ? 'Esperando tu respuesta' : 'Preguntó al usuario', detail: asked.map(one => one.question).join(' · ') }
908
+ }
909
+ return { title: titleOf(first?.tool ?? ''), detail: first?.summary ?? '' }
910
+ }
911
+
912
+ export const groupSteps = (list: ToolEntry[]): Step[] => {
913
+ const groups: { kind: StepKind; items: ToolEntry[] }[] = []
914
+ for (const entry of list) {
915
+ const kind = stepKindOf(entry)
916
+ const last = groups.at(-1)
917
+ if (last && last.kind === kind && !SOLO_KINDS.has(kind)) last.items.push(entry)
918
+ else groups.push({ kind, items: [entry] })
919
+ }
920
+ return groups.map(({ kind, items }) => {
921
+ const status = groupStatus(items)
922
+ return { key: items[0]?.id ?? kind, kind, status, durationMs: wallTime(items), ...describeStep(kind, items, status === 'running') }
923
+ })
924
+ }
925
+
926
+ // ---------------------------------------------------------------- agents
927
+
928
+ export const shortName = (record: Pick<AgentRecord, 'description' | 'name'>): string => {
929
+ if (record.name) return fit(record.name, 16)
930
+ const words = record.description.replace(/^\s*[\w-]+:\s*/, '').split(/\s+/).filter(Boolean)
931
+ const pair = words.slice(0, 2).join(' ')
932
+ const short = pair.length <= 16 && (words[1] ?? '').length > 3 ? pair : (words[0] ?? '')
933
+ const named = short === '' ? 'Agente' : short.charAt(0).toUpperCase() + short.slice(1)
934
+ return fit(named, 16)
935
+ }
936
+
937
+ export const defaultAgent = (records: AgentRecord[], picked: string): string => {
938
+ if (picked !== '' && (picked === MAIN || records.some(one => one.id === picked))) return picked
939
+ const running = records.filter(one => one.state === 'running').sort((a, b) => b.startedAt - a.startedAt)
940
+ return running[0]?.id ?? MAIN
941
+ }
942
+
943
+ export const mergeAgent = (list: AgentRecord[], record: AgentRecord): AgentRecord[] => {
944
+ const known = list.find(one => one.id === record.id)
945
+ const merged = known ? { ...known, ...record, startedAt: known.startedAt, description: record.description || known.description } : record
946
+ return [...list.filter(one => one.id !== record.id), merged].slice(-30)
947
+ }
948
+
949
+ export const setAgentState = (list: AgentRecord[], id: string, state: AgentState): AgentRecord[] =>
950
+ list.map(one => (one.id === id ? { ...one, state } : one))
951
+
952
+ const agentStateOf = (status: string): AgentState =>
953
+ status === 'completed' || status === 'idle' ? 'done' : status === 'failed' || status === 'killed' ? 'failed' : 'running'
954
+
955
+ /** The Agent tool's own result: only a completed run is done; a launch is still running. */
956
+ export const agentResultState = (status: CallStatus, result: unknown): AgentState | undefined => {
957
+ if (status !== 'ok') return 'failed'
958
+ const reported = (result as { status?: unknown } | undefined)?.status
959
+ if (reported === 'completed') return 'done'
960
+ if (reported === 'async_launched' || reported === 'remote_launched' || reported === 'teammate_spawned') return 'running'
961
+ return undefined
962
+ }
963
+
964
+ export const turnEndState = (reason: string): AgentState => (reason === 'answer' ? 'done' : 'failed')
965
+
966
+ export const decisionsOf = (input: Record<string, unknown>): Decision[] =>
967
+ rawQuestions(input).map(question => ({ question: oneLine(question), answer: '' }))
968
+
969
+ const rawQuestions = (input: Record<string, unknown>): string[] =>
970
+ (Array.isArray(input.questions) ? input.questions : [])
971
+ .map(one => text((one as { question?: unknown }).question))
972
+ .filter((question): question is string => question !== undefined)
973
+
974
+ /** Answers are keyed by the question text exactly as the model sent it. */
975
+ export const answered = (input: Record<string, unknown>, status: CallStatus, result: unknown): Decision[] => {
976
+ const record = (result ?? {}) as { answers?: unknown; response?: unknown }
977
+ const answers = (record.answers ?? {}) as Record<string, unknown>
978
+ const response = cleanText(record.response)
979
+ return rawQuestions(input).map(raw => {
980
+ if (status !== 'ok') return { question: oneLine(raw), answer: 'rechazada', refused: true }
981
+ const given = answers[raw]
982
+ return { question: oneLine(raw), answer: given !== undefined && given !== '' ? oneLine(String(given)) : (response ?? '') }
983
+ })
984
+ }
985
+
986
+ // ---------------------------------------------------------------- scroll
987
+
988
+ export const scrolled = (state: PaneScroll, by: number, total: number, room: number, isJump: boolean): PaneScroll => {
989
+ const maxOffset = Math.max(0, total - room)
990
+ const from = state.follow ? maxOffset : Math.min(state.offset, maxOffset)
991
+ const step = isJump ? Math.sign(by) * total : Math.abs(by) >= room ? Math.sign(by) * Math.max(1, room - 1) : by
992
+ const offset = Math.min(maxOffset, Math.max(0, from + step))
993
+ return { offset, follow: maxOffset > 0 && offset === maxOffset }
994
+ }
995
+
996
+ export const windowStart = (state: PaneScroll, total: number, room: number): number => {
997
+ const maxOffset = Math.max(0, total - room)
998
+ return state.follow ? maxOffset : Math.min(state.offset, maxOffset)
999
+ }
1000
+
1001
+ // ---------------------------------------------------------------- pane model
1002
+
1003
+ export type Tone = 'success' | 'error' | 'warning' | 'subtle' | 'permission' | 'claude' | 'suggestion' | 'diffAdded' | 'diffRemoved'
1004
+ export type Span = { text: string; color?: Tone | (string & {}); dim?: boolean; bold?: boolean; inverse?: boolean }
1005
+ export type Action =
1006
+ | { kind: 'toggle'; key: string }
1007
+ | { kind: 'tab'; tab: Tab }
1008
+ | { kind: 'agent'; id: string }
1009
+ | { kind: 'scope'; scope: CambiosScope }
1010
+ | { kind: 'diff'; target: DiffTarget }
1011
+ | { kind: 'open'; target: DiffTarget }
1012
+ | { kind: 'commit'; sha: string }
1013
+ export type Cell = { spans: Span[]; action?: Action; label?: string; key?: string }
1014
+ export type Row = { key: string; cells: Cell[]; right?: Span[] }
1015
+
1016
+ export type Snapshot = {
1017
+ list: ToolEntry[]
1018
+ tabByAgent: Record<string, Tab>
1019
+ flipped: string[]
1020
+ files: FileChange[]
1021
+ usd: number
1022
+ context: ContextUsage
1023
+ steps: Record<string, StepContext>
1024
+ accent: string
1025
+ opened: string[]
1026
+ patches: Record<string, DiffPatch>
1027
+ records: AgentRecord[]
1028
+ picked: string
1029
+ isWorking: boolean
1030
+ commitList: CommitRecord[]
1031
+ scopeByAgent: Record<string, CambiosScope>
1032
+ branchView: BranchView
1033
+ view: PaneScroll
1034
+ historyView: HistoryView
1035
+ historyFiles: Record<string, HistoryFiles>
1036
+ }
1037
+
1038
+ export type PaneModel = { header: Row[]; body: Row[]; footer: Row[]; scope: string; cambios: CambiosScope; tab: Tab }
1039
+
1040
+ type Look = { icon: string; color: Tone }
1041
+
1042
+ const STATUS_LOOK: Record<CallStatus, Look> = {
1043
+ running: { icon: ICONS.running, color: 'warning' },
1044
+ ok: { icon: ICONS.ok, color: 'success' },
1045
+ error: { icon: ICONS.error, color: 'error' },
1046
+ denied: { icon: ICONS.denied, color: 'subtle' },
1047
+ interrupted: { icon: ICONS.interrupted, color: 'subtle' },
1048
+ }
1049
+
1050
+ const AGENT_LOOK: Record<AgentState, Look & { label: string }> = {
1051
+ running: { icon: ICONS.running, color: 'warning', label: 'ejecutando' },
1052
+ done: { icon: ICONS.ok, color: 'success', label: 'terminó' },
1053
+ failed: { icon: ICONS.error, color: 'error', label: 'falló' },
1054
+ }
1055
+
1056
+ const KIND_ICONS: Record<StepKind, string> = {
1057
+ read: ICONS.read,
1058
+ edit: ICONS.edit,
1059
+ validate: ICONS.validate,
1060
+ command: ICONS.command,
1061
+ agent: ICONS.agent,
1062
+ question: ICONS.question,
1063
+ other: ICONS.other,
1064
+ }
1065
+
1066
+ const TAB_LABELS: { value: Tab; icon: string; label: string }[] = [
1067
+ { value: 'summary', icon: ICONS.summary, label: 'Resumen' },
1068
+ { value: 'commands', icon: ICONS.commands, label: 'Comandos' },
1069
+ { value: 'diff', icon: ICONS.diff, label: 'Cambios' },
1070
+ { value: 'history', icon: ICONS.history, label: 'Historial' },
1071
+ ]
1072
+
1073
+ const SCOPE_LABELS: { value: CambiosScope; icon: string; label: string }[] = [
1074
+ { value: 'commits', icon: ICONS.commit, label: 'Commits' },
1075
+ { value: 'uncommitted', icon: ICONS.uncommitted, label: 'Sin commitear' },
1076
+ { value: 'branch', icon: ICONS.branch, label: 'Rama' },
1077
+ ]
1078
+
1079
+ const span = (value: string, style: Omit<Span, 'text'> = {}): Span => ({ text: value, ...style })
1080
+
1081
+ const touches = (change: FileChange, edited: string[]): boolean =>
1082
+ edited.some(path => path === change.path || path.endsWith(`/${change.path}`))
1083
+
1084
+ /** The main loop's view lists every session commit; an agent's, its own. */
1085
+ export const commitsFor = (list: CommitRecord[], scope: string): CommitRecord[] =>
1086
+ scope === MAIN ? list : list.filter(one => (one.agentId ?? MAIN) === scope)
1087
+
1088
+ /** Which loop made each session commit, by its first seven hex digits; the caller checks the full sha. */
1089
+ export const sessionOwners = (list: CommitRecord[]): Map<string, CommitRecord[]> => {
1090
+ const owners = new Map<string, CommitRecord[]>()
1091
+ for (const commit of list) owners.set(commit.sha.slice(0, 7), [...(owners.get(commit.sha.slice(0, 7)) ?? []), commit])
1092
+ return owners
1093
+ }
1094
+
1095
+ export const ownerOf = (owners: Map<string, CommitRecord[]>, sha: string): CommitRecord | undefined =>
1096
+ owners.get(sha.slice(0, 7))?.find(one => sameSha(one.sha, sha))
1097
+
1098
+ export const cambiosScopeOf = (snap: Pick<Snapshot, 'scopeByAgent' | 'commitList'>, scope: string): CambiosScope =>
1099
+ snap.scopeByAgent[scope] ?? (commitsFor(snap.commitList, scope).length > 0 ? 'commits' : 'uncommitted')
1100
+
1101
+ export const buildPane = (snap: Snapshot, width: number): PaneModel => {
1102
+ const { list, flipped, opened, patches, records } = snap
1103
+ const accent = snap.accent
1104
+ const scope = defaultAgent(records, snap.picked)
1105
+ const current: Tab = snap.tabByAgent[scope] ?? 'summary'
1106
+ const cambios = cambiosScopeOf(snap, scope)
1107
+ const agent = records.find(one => one.id === scope)
1108
+ const scoped = list.filter(one => (one.agentId ?? MAIN) === scope)
1109
+ const commands = scoped.filter(one => one.command !== undefined)
1110
+ const lastCommand = commands.at(-1)
1111
+ const edited = distinct(scoped.filter(one => CHANGE_TOOLS.has(one.tool)).map(one => one.file))
1112
+ const sessionEdited = distinct(list.filter(one => CHANGE_TOOLS.has(one.tool)).map(one => one.file))
1113
+ const visibleFiles = snap.files.filter(change => !change.untracked || touches(change, sessionEdited))
1114
+ const hiddenUntracked = snap.files.length - visibleFiles.length
1115
+ const scopedFiles = scope === MAIN ? visibleFiles : visibleFiles.filter(change => touches(change, edited))
1116
+ const waiting = list.some(one => one.tool === 'AskUserQuestion' && one.status === 'running')
1117
+
1118
+ const isOpen = (key: string, byDefault: boolean): boolean => byDefault !== flipped.includes(key)
1119
+ const line = (key: string, value: string, style: Omit<Span, 'text'> = {}): Row => ({ key, cells: [{ spans: [span(fit(value, width), style)] }] })
1120
+ const blank = (key: string): Row => line(key, ' ')
1121
+ const divider = (key: string): Row => line(key, '─'.repeat(width), { dim: true })
1122
+ const agentTag = (agentId: string | undefined): string => {
1123
+ if (agentId === undefined) return ''
1124
+ const record = records.find(one => one.id === agentId)
1125
+ return ` · ${record ? shortName(record) : 'agente'}`
1126
+ }
1127
+ const toggleRow = (key: string, label: string, open: boolean, indent = ''): Row => ({
1128
+ key,
1129
+ cells: [{ spans: [span(fit(`${indent}${open ? '▼' : '▶'} ${label}`, width))], action: { kind: 'toggle', key }, label, key: `btn-${key}` }],
1130
+ })
1131
+ const section = (key: string, label: string, byDefault: boolean, body: () => Row[]): Row[] => {
1132
+ const open = isOpen(key, byDefault)
1133
+ return [toggleRow(key, label, open), ...(open ? body() : [])]
1134
+ }
1135
+
1136
+ const stepRows = (steps: Step[]): Row[] =>
1137
+ steps.flatMap(step => {
1138
+ const look = STATUS_LOOK[step.status]
1139
+ const right = step.status === 'running' ? '…' : seconds(step.durationMs)
1140
+ return [
1141
+ {
1142
+ key: `step-${step.key}`,
1143
+ cells: [{ spans: [span(`${look.icon} `, { color: look.color }), span(`${KIND_ICONS[step.kind]} ${fit(step.title, width - right.length - 6)}`)] }],
1144
+ right: [span(right, { dim: true })],
1145
+ },
1146
+ ...(step.detail === '' ? [] : [line(`detail-${step.key}`, ` ${step.detail}`, { dim: true })]),
1147
+ ]
1148
+ })
1149
+
1150
+ const commandRows = (entry: ToolEntry, keyPrefix: string): Row[] => {
1151
+ const verdict = verdictOf(entry)
1152
+ const summary = resultLine(entry)
1153
+ const outputOpen = isOpen(`${keyPrefix}-output`, false)
1154
+ const rows: Row[] = [line(`${keyPrefix}-cmd`, `$ ${entry.command ?? ''}`, { color: 'permission' })]
1155
+ if (entry.status === 'running') rows.push(line(`${keyPrefix}-running`, ` ${ICONS.running} ejecutando…`, { color: 'warning' }))
1156
+ for (const test of entry.testFiles ?? []) {
1157
+ rows.push({
1158
+ key: `${keyPrefix}-test-${test.file}`,
1159
+ cells: [{ spans: [span(' '), span(`${test.ok ? ICONS.ok : ICONS.error} `, { color: test.ok ? 'success' : 'error' }), span(fit(test.file, width - 6))] }],
1160
+ })
1161
+ }
1162
+ if (entry.status !== 'running') {
1163
+ const look = entry.status === 'interrupted' ? STATUS_LOOK.interrupted : verdict === 'FAIL' || entry.status !== 'ok' ? STATUS_LOOK.error : STATUS_LOOK.ok
1164
+ const label = entry.status === 'interrupted' ? ' interrumpido' : verdict ? ` ${verdict}` : ''
1165
+ const tail = `${summary}${summary && entry.durationMs !== undefined ? ' · ' : ''}${seconds(entry.durationMs)}`
1166
+ rows.push({
1167
+ key: `${keyPrefix}-verdict`,
1168
+ cells: [{ spans: [span(`${look.icon}${label}`, { color: look.color, bold: true }), span(` ${fit(tail, width - 16)}`, { dim: true })] }],
1169
+ })
1170
+ }
1171
+ if (entry.output !== '') {
1172
+ rows.push(toggleRow(`${keyPrefix}-output`, outputOpen ? 'Ocultar salida' : 'Ver salida completa', outputOpen))
1173
+ if (outputOpen) entry.output.split('\n').forEach((out, index) => rows.push(line(`${keyPrefix}-out-${index}`, ` ${out}`, { dim: true })))
1174
+ }
1175
+ return rows
1176
+ }
1177
+
1178
+ const historyRows = (): Row[] =>
1179
+ commands
1180
+ .slice()
1181
+ .reverse()
1182
+ .map(entry => {
1183
+ const look = STATUS_LOOK[entry.status]
1184
+ const right = entry.status === 'running' ? '…' : `exit ${entry.exitCode ?? '?'} · ${seconds(entry.durationMs)}`
1185
+ return {
1186
+ key: `hist-${entry.id}`,
1187
+ cells: [{ spans: [span(' '), span(`${look.icon} `, { color: look.color }), span(fit(entry.command ?? '', width - right.length - 7))] }],
1188
+ right: [span(right, { dim: true })],
1189
+ }
1190
+ })
1191
+
1192
+ const fileRows = (target: DiffTarget, file: FileChange, indent: string): Row[] => {
1193
+ const key = targetKey(target)
1194
+ const isOpenFile = opened.includes(key)
1195
+ const shown = clean(file.path)
1196
+ const counts = file.binary ? 'bin' : `+${file.added} −${file.removed}`
1197
+ const mark = file.untracked ? ' nuevo' : ''
1198
+ const rows: Row[] = [
1199
+ {
1200
+ key: `file-${key}`,
1201
+ cells: [
1202
+ { spans: [span(`${indent}${isOpenFile ? '▾' : '▸'} `)], action: { kind: 'diff', target }, label: isOpenFile ? 'Ocultar diff' : 'Ver diff aquí', key: `fold-${key}` },
1203
+ {
1204
+ spans: [span(`${fileIcon(file.path)} ${fit(shown, width - counts.length - mark.length - indent.length - 7)}`), ...(mark ? [span(mark, { color: 'success', dim: true })] : [])],
1205
+ action: { kind: 'open', target },
1206
+ label: `Abrir ${shown} en nvim`,
1207
+ key: `open-${key}`,
1208
+ },
1209
+ ],
1210
+ right: file.binary ? [span('bin', { dim: true })] : [span(`+${file.added}`, { color: 'success' }), span(' '), span(`−${file.removed}`, { color: 'error' })],
1211
+ },
1212
+ ]
1213
+ if (!isOpenFile) return rows
1214
+ const patch = patches[key]
1215
+ if (patch === undefined) return [...rows, line(`loading-${key}`, `${indent} Cargando diff…`, { dim: true })]
1216
+ if (patch.rows.length === 0) return [...rows, line(`nodiff-${key}`, `${indent} Sin diferencias.`, { dim: true })]
1217
+ const gutter = Math.max(3, ...patch.rows.map(row => row.gutter.length))
1218
+ patch.rows.forEach((row, index) =>
1219
+ rows.push(
1220
+ row.kind === 'hunk'
1221
+ ? line(`hunk-${key}-${index}`, `${indent} ${ICONS.hunk} ${row.text}`, { color: 'suggestion' })
1222
+ : {
1223
+ key: `row-${key}-${index}`,
1224
+ cells: [{
1225
+ spans: [
1226
+ span(`${indent} ${row.gutter.padStart(gutter)} │`, { dim: true }),
1227
+ span(`${row.sign} ${fit(row.text, width - gutter - indent.length - 8)}`, { color: row.kind === 'add' ? 'diffAdded' : row.kind === 'del' ? 'diffRemoved' : undefined }),
1228
+ ],
1229
+ }],
1230
+ },
1231
+ ),
1232
+ )
1233
+ if (patch.total > patch.rows.length) rows.push(line(`more-${key}`, `${indent} … ${patch.total - patch.rows.length} líneas más`, { dim: true }))
1234
+ return rows
1235
+ }
1236
+
1237
+ const uncommittedRows = (): Row[] => {
1238
+ const hidden = scope === MAIN && hiddenUntracked > 0
1239
+ ? [line('hidden-untracked', `${hiddenUntracked} archivos sin seguimiento de antes de la sesión, ocultos`, { dim: true })]
1240
+ : []
1241
+ if (scopedFiles.length === 0) return [line('no-changes', scope === MAIN ? 'Sin cambios sin commitear.' : 'Este agente no tiene cambios sin commitear.', { dim: true }), ...hidden]
1242
+ return [...scopedFiles.flatMap(file => fileRows({ scope: 'uncommitted', path: file.path, ...(file.untracked ? { untracked: true } : {}) }, file, '')), ...hidden]
1243
+ }
1244
+
1245
+ const commitRows = (): Row[] => {
1246
+ const own = commitsFor(snap.commitList, scope).slice().reverse()
1247
+ const rows: Row[] = []
1248
+ if (own.length === 0) rows.push(line('no-commits', scope === MAIN ? 'Sin commits en esta sesión todavía.' : 'Este agente no ha hecho commits.', { dim: true }))
1249
+ for (const commit of own) {
1250
+ const key = `commit-${commit.sha}`
1251
+ const open = isOpen(key, false)
1252
+ const totals = commit.added === undefined ? (commit.statsFailed ? '?' : '…') : `+${commit.added} −${commit.removed ?? 0}`
1253
+ const tag = scope === MAIN ? agentTag(commit.agentId) : ''
1254
+ rows.push({
1255
+ key,
1256
+ cells: [
1257
+ { spans: [span(`${open ? '▾' : '▸'} `)], action: { kind: 'toggle', key }, label: open ? 'Ocultar archivos' : 'Ver archivos', key: `btn-${key}` },
1258
+ {
1259
+ spans: [
1260
+ span(`${commit.isMerge ? ICONS.merge : ICONS.commit} `, { color: accent }),
1261
+ span(`${commit.sha.slice(0, 7)} `, { color: 'warning' }),
1262
+ span(fit(commit.subject, width - totals.length - tag.length - 14)),
1263
+ ...(tag ? [span(tag, { color: accent, dim: true })] : []),
1264
+ ],
1265
+ },
1266
+ ],
1267
+ right: commit.added === undefined ? [span(totals, { dim: true })] : [span(`+${commit.added}`, { color: 'success' }), span(' '), span(`−${commit.removed ?? 0}`, { color: 'error' })],
1268
+ })
1269
+ if (!open) continue
1270
+ rows.push(line(`${key}-meta`, ` ${ICONS.branch} ${commit.branch}`, { dim: true }))
1271
+ if (commit.files === undefined) rows.push(line(`${key}-loading`, commit.statsFailed ? ' No se pudo leer el commit.' : ' Cargando archivos…', { dim: true }))
1272
+ else commit.files.forEach(file => rows.push(...fileRows({ scope: 'commit', sha: commit.sha, path: file.path }, file, ' ')))
1273
+ }
1274
+ return rows
1275
+ }
1276
+
1277
+ const historyTabRows = (): Row[] => {
1278
+ const view = snap.historyView
1279
+ if (view.state === 'error') return [line('hist-error', view.error ?? 'git falló.', { color: 'warning' })]
1280
+ if (view.rows.length === 0) return [line('hist-loading', view.state === 'ready' ? 'Sin commits todavía.' : 'Cargando historial…', { dim: true })]
1281
+ const owners = sessionOwners(snap.commitList)
1282
+ const shown = view.rows.filter(row => row.sha !== undefined).length
1283
+ const ours = view.rows.filter(row => row.sha !== undefined && ownerOf(owners, row.sha) !== undefined).length
1284
+ const rows: Row[] = [{
1285
+ key: 'hist-legend',
1286
+ cells: [{ spans: [span(`${ICONS.history} ${shown} commits · `, { dim: true }), span('●', { color: accent }), span(` ${ours} de esta sesión`, { dim: true }), ...(view.state === 'loading' ? [span(' · actualizando…', { dim: true })] : [])] }],
1287
+ }]
1288
+ view.rows.forEach((row, index) => {
1289
+ const sha = row.sha
1290
+ if (sha === undefined) {
1291
+ rows.push(line(`hg-${index}`, ` ${row.graph}`, { dim: true }))
1292
+ return
1293
+ }
1294
+ const owner = ownerOf(owners, sha)
1295
+ const loop = owner === undefined ? undefined : (owner.agentId ?? MAIN)
1296
+ const strength = loop === undefined ? 'none' : scope === MAIN || loop === scope ? 'strong' : 'soft'
1297
+ const mark: Omit<Span, 'text'> = strength === 'strong' ? { color: accent } : strength === 'soft' ? { color: accent, dim: true } : {}
1298
+ const key = `hist-${sha}`
1299
+ const open = isOpen(key, false)
1300
+ const right = [ago(row.at, view.loadedAt), fit(row.author ?? '', 14)].filter(Boolean).join(' · ')
1301
+ const tag = owner !== undefined && scope === MAIN ? agentTag(owner.agentId) : ''
1302
+ const refSpans = (row.refs ?? []).flatMap((ref, at): Span[] => {
1303
+ const isHead = ref === 'HEAD' || ref.startsWith('HEAD -> ')
1304
+ return [span(at === 0 ? '(' : ', ', { color: 'suggestion', dim: true }), span(ref, { color: 'suggestion', bold: isHead })]
1305
+ })
1306
+ const refsText = refSpans.length > 0 ? refSpans.map(one => one.text).join('').length + 2 : 0
1307
+ const used = 2 + row.graph.length + sha.length + 1 + refsText + tag.length + right.length + 2
1308
+ rows.push({
1309
+ key,
1310
+ cells: [{
1311
+ spans: [
1312
+ span(strength === 'none' ? ' ' : '● ', { ...mark, bold: strength === 'strong' }),
1313
+ span(row.graph, { dim: true }),
1314
+ span(`${sha} `, strength === 'none' ? { color: 'warning' } : { ...mark, bold: strength === 'strong' }),
1315
+ ...refSpans,
1316
+ ...(refSpans.length > 0 ? [span(') ', { color: 'suggestion', dim: true })] : []),
1317
+ span(fit(row.subject ?? '', width - used), mark),
1318
+ ...(tag ? [span(tag, { color: accent, dim: true })] : []),
1319
+ ],
1320
+ action: { kind: 'commit', sha },
1321
+ label: open ? 'Ocultar archivos' : 'Ver archivos',
1322
+ key: `btn-${key}`,
1323
+ }],
1324
+ right: [span(right, { dim: true })],
1325
+ })
1326
+ if (!open) return
1327
+ const files = owner?.files ?? snap.historyFiles[sha]?.files
1328
+ const failed = owner?.statsFailed === true || snap.historyFiles[sha]?.failed === true
1329
+ if (files === undefined) rows.push(line(`${key}-loading`, failed ? ' No se pudo leer el commit.' : ' Cargando archivos…', { dim: true }))
1330
+ else if (files.length === 0) rows.push(line(`${key}-empty`, ' El commit no cambia archivos.', { dim: true }))
1331
+ else files.forEach(file => rows.push(...fileRows({ scope: 'commit', sha: owner?.sha ?? sha, path: file.path }, file, ' ')))
1332
+ })
1333
+ if (view.more > 0) rows.push(line('hist-more', `… ${view.more} más`, { dim: true }))
1334
+ return rows
1335
+ }
1336
+
1337
+ const branchRows = (): Row[] => {
1338
+ const view = snap.branchView
1339
+ if (!view.isLoaded) return [line('branch-loading', 'Cargando la rama…', { dim: true })]
1340
+ if (view.error !== undefined) return [line('branch-error', view.error, { color: 'warning' })]
1341
+ return [
1342
+ line('branch-base', `${ICONS.branch} vs ${view.baseRef ?? ''} (${(view.base ?? '').slice(0, 7)}) · ${view.commits.length} commits · ${view.files.length} archivos`, { dim: true }),
1343
+ ...section('branch-commits', `Commits de la rama · ${view.commits.length}`, true, () =>
1344
+ view.commits.map(commit => ({
1345
+ key: `bc-${commit.sha}`,
1346
+ cells: [{ spans: [span(` ${ICONS.commit} `, { color: accent }), span(`${commit.sha} `, { color: 'warning' }), span(fit(commit.subject, width - commit.sha.length - 6))] }],
1347
+ })),
1348
+ ),
1349
+ ...(view.files.length === 0 ? [line('branch-nofiles', 'La rama no cambia archivos.', { dim: true })] : view.files.flatMap(file => fileRows({ scope: 'branch', sha: view.base, path: file.path }, file, ''))),
1350
+ ]
1351
+ }
1352
+
1353
+ const cambiosRows = (): Row[] => (cambios === 'commits' ? commitRows() : cambios === 'branch' ? branchRows() : uncommittedRows())
1354
+
1355
+ const decisions = scoped.flatMap(one => one.decisions ?? [])
1356
+ const readFiles = distinct(scoped.filter(one => one.tool === 'Read').map(one => one.file)).reverse()
1357
+ const usage = scopedContext(snap, scope)
1358
+ const percent = contextPercentOf(usage)
1359
+ const contextRow = (key: string, indent: string): Row => {
1360
+ const label = contextLabel(usage)
1361
+ const hint = scope === MAIN ? ' de la última respuesta' : ' de la última respuesta de este agente'
1362
+ const used = indent.length + 2 + 11 + label.length
1363
+ return {
1364
+ key,
1365
+ cells: [{
1366
+ spans: [
1367
+ span(`${indent}${ICONS.gauge} `),
1368
+ span(`${contextBar(percent)} `, { color: contextTone(percent) }),
1369
+ span(fit(label, width - indent.length - 13)),
1370
+ ...(usage.tokens !== undefined && used + hint.length <= width ? [span(hint, { dim: true })] : []),
1371
+ ],
1372
+ }],
1373
+ }
1374
+ }
1375
+
1376
+ const summaryRows = (): Row[] => {
1377
+ const steps = groupSteps(scoped)
1378
+ if (steps.length === 0) return [line('empty', 'Sin actividad todavía.', { dim: true })]
1379
+ return [
1380
+ ...stepRows(steps),
1381
+ ...(lastCommand ? [blank('gap-last'), ...section(`last-cmd-${scope}`, 'Último comando', true, () => commandRows(lastCommand, `last-${scope}`))] : []),
1382
+ blank('gap-changes'),
1383
+ divider('div-changes'),
1384
+ line('changes-title', `${ICONS.uncommitted} SIN COMMITEAR`, { bold: true }),
1385
+ ...uncommittedRows(),
1386
+ blank('gap-sections'),
1387
+ ...section(`decisions-${scope}`, `${ICONS.decision} Decisiones técnicas · ${decisions.length}`, false, () =>
1388
+ decisions.length === 0
1389
+ ? [line('no-decisions', ' Sin preguntas todavía.', { dim: true })]
1390
+ : decisions.flatMap((one, index) => [
1391
+ line(`q-${index}`, ` ${ICONS.question} ${one.question}`),
1392
+ line(`a-${index}`, ` → ${one.answer || 'pendiente'}`, { color: one.refused ? 'error' : one.answer ? 'success' : 'warning' }),
1393
+ ]),
1394
+ ),
1395
+ ...section(`history-${scope}`, `${ICONS.log} ${scope === MAIN ? 'Historial de comandos' : 'Historial de este agente'} · ${commands.length}`, false, historyRows),
1396
+ ...section(`context-${scope}`, `${ICONS.brain} Contexto consultado`, false, () => [
1397
+ contextRow('ctx-usage', ' '),
1398
+ ...readFiles.slice(0, 30).map(path => line(`ctx-${path}`, ` ${fileIcon(path)} ${path}`)),
1399
+ ]),
1400
+ ]
1401
+ }
1402
+
1403
+ const commandsTabRows = (): Row[] => {
1404
+ if (!lastCommand) return [line('no-commands', 'Sin comandos todavía.', { dim: true })]
1405
+ return [
1406
+ line('last-title', `${ICONS.command} Último comando`, { bold: true }),
1407
+ ...commandRows(lastCommand, `cmdtab-${scope}`),
1408
+ blank('gap-history'),
1409
+ line('history-title', `${ICONS.log} Historial · ${commands.length}`, { bold: true }),
1410
+ ...historyRows(),
1411
+ ]
1412
+ }
1413
+
1414
+ const body = current === 'diff' ? cambiosRows() : current === 'commands' ? commandsTabRows() : current === 'history' ? historyTabRows() : summaryRows()
1415
+
1416
+ const status = waiting
1417
+ ? span(`${ICONS.waiting} esperando respuesta`, { color: 'warning' })
1418
+ : snap.isWorking
1419
+ ? span(`${ICONS.running} ejecutando`, { color: 'warning' })
1420
+ : undefined
1421
+
1422
+ const chip = (key: string, label: string, isOn: boolean, action: Action, look?: Look): Cell => ({
1423
+ key,
1424
+ label,
1425
+ action,
1426
+ spans: [span(` ${label}${look ? ' ' : ' '}`, { inverse: isOn, bold: isOn }), ...(look ? [span(`${look.icon} `, { color: look.color, inverse: isOn })] : []), span(' ')],
1427
+ })
1428
+
1429
+ const header: Row[] = [{ key: 'title', cells: [{ spans: [span('ACTIVIDAD', { bold: true })] }], right: status ? [status] : [] }]
1430
+ if (records.length > 0) {
1431
+ header.push({
1432
+ key: 'agents',
1433
+ cells: [
1434
+ chip(`agent-${MAIN}`, 'Principal', scope === MAIN, { kind: 'agent', id: MAIN }),
1435
+ ...records.map(one => chip(`agent-${one.id}`, shortName(one), scope === one.id, { kind: 'agent', id: one.id }, AGENT_LOOK[one.state])),
1436
+ ],
1437
+ })
1438
+ }
1439
+ if (agent) {
1440
+ const look = AGENT_LOOK[agent.state]
1441
+ header.push(
1442
+ { key: 'agent-head', cells: [{ spans: [span(`${ICONS.agent} ${shortName(agent)}`, { color: accent, bold: true }), span(` · ${agent.id.slice(0, 4)} · `, { dim: true }), span(look.label, { color: look.color })] }] },
1443
+ line('agent-task', agent.description, { dim: true }),
1444
+ )
1445
+ }
1446
+ header.push({
1447
+ key: 'tabs',
1448
+ cells: TAB_LABELS.map(tab => ({
1449
+ key: `tab-${tab.value}`,
1450
+ label: tab.label,
1451
+ action: { kind: 'tab', tab: tab.value } as Action,
1452
+ spans: [span(` ${tab.icon} ${tab.label} `, { inverse: current === tab.value, bold: current === tab.value, color: current === tab.value ? 'claude' : undefined }), span(' ')],
1453
+ })),
1454
+ })
1455
+ if (current === 'diff') {
1456
+ const counts: Record<CambiosScope, string> = {
1457
+ commits: String(commitsFor(snap.commitList, scope).length),
1458
+ uncommitted: String(scopedFiles.length),
1459
+ branch: snap.branchView.isLoaded && snap.branchView.error === undefined ? String(snap.branchView.commits.length) : '',
1460
+ }
1461
+ header.push({
1462
+ key: 'scopes',
1463
+ cells: SCOPE_LABELS.map(one => ({
1464
+ key: `scope-${one.value}`,
1465
+ label: one.label,
1466
+ action: { kind: 'scope', scope: one.value } as Action,
1467
+ spans: [
1468
+ span(` ${one.icon} ${one.label}${counts[one.value] ? ` ${counts[one.value]}` : ''} `, { inverse: cambios === one.value, bold: cambios === one.value, color: cambios === one.value ? 'suggestion' : undefined }),
1469
+ span(' '),
1470
+ ],
1471
+ })),
1472
+ })
1473
+ }
1474
+ header.push(divider('div-head'))
1475
+
1476
+ const wall = wallTime(scoped.filter(one => one.durationMs !== undefined))
1477
+ const footer: Row[] = [
1478
+ divider('div-foot'),
1479
+ line(
1480
+ 'footer',
1481
+ `${ICONS.files} ${scopedFiles.length} archivos · ${ICONS.command} ${commands.length} comandos · ${ICONS.time} ${seconds(wall) || '0.0 s'} · ${ICONS.cost} ${dollars(snap.usd)} sesión`,
1482
+ { dim: true },
1483
+ ),
1484
+ contextRow('footer-context', ''),
1485
+ ]
1486
+
1487
+ return { header, body, footer, scope, cambios, tab: current }
1488
+ }
1489
+
1490
+ export type PaneFrame = { rows: Row[]; isWindowed: boolean; total: number; room: number }
1491
+
1492
+ /**
1493
+ * Fixes the header and footer and windows the body between them. When the
1494
+ * frame is too short for even one body row, the tree goes whole and the
1495
+ * engine scrolls it.
1496
+ */
1497
+ export const paneFrame = (model: PaneModel, bodyRows: number, view: PaneScroll, isDock: boolean): PaneFrame => {
1498
+ const total = model.body.length
1499
+ const footer = bodyRows >= model.header.length + model.footer.length + 1 ? model.footer : []
1500
+ const room = bodyRows - model.header.length - footer.length
1501
+ if (room < 1) return { rows: [...model.header, ...model.body, ...model.footer], isWindowed: false, total, room: 0 }
1502
+ const start = windowStart(view, total, room)
1503
+ const visible = model.body.slice(start, start + room)
1504
+ const [title, ...rest] = model.header
1505
+ const indicator = total > room ? [span(` ↕ ${start + 1}-${start + visible.length}/${total}`, { dim: true })] : []
1506
+ const header = title ? [{ ...title, right: [...(title.right ?? []), ...indicator] }, ...rest] : rest
1507
+ const padding = isDock ? Array.from({ length: room - visible.length }, (_, index): Row => ({ key: `pad-${index}`, cells: [{ spans: [span(' ')] }] })) : []
1508
+ return { rows: [...header, ...visible, ...padding, ...footer], isWindowed: true, total, room }
1509
+ }
1510
+
1511
+ // ---------------------------------------------------------------- hooks
1512
+
1513
+ const runOf = ($: Api): Run => (argv, init) => $.process.run(argv, init)
1514
+
1515
+ const readSnapshot = async ($: Api): Promise<Snapshot> => {
1516
+ const [list, tabByAgent, flipped, files, usd, context, opened, patches, records, picked, isWorking, view, commitList, scopeByAgent, branchView, steps, historyView, historyFilesBySha, accent] = await Promise.all([
1517
+ read($, entries), read($, tabs), read($, toggled), read($, changes), read($, costUsd), read($, contextUsage), read($, openFiles), read($, diffs),
1518
+ read($, agents), read($, pickedAgent), read($, working), read($, scroll), read($, commits), read($, scopes), read($, branch), read($, stepContext),
1519
+ read($, history), read($, historyFiles), read($, accentColor),
1520
+ ])
1521
+ return { accent, list, tabByAgent, flipped, files, usd, context, steps, opened, patches, records, picked, isWorking, commitList, scopeByAgent, branchView, view, historyView, historyFiles: historyFilesBySha }
1522
+ }
1523
+
1524
+ /** Fills in the line counts and files of up to ten commits that have none yet. */
1525
+ const fillCommitStats = async ($: Api, run: Run, top: string): Promise<void> => {
1526
+ const pending = (await read($, commits)).filter(one => one.added === undefined && !one.statsFailed).slice(0, 10)
1527
+ for (const commit of pending) {
1528
+ const stats = await loadCommitStats(run, top, commit.sha)
1529
+ await update($, commits, list =>
1530
+ list.map(one => (one.sha !== commit.sha ? one : stats ? { ...one, added: stats.added, removed: stats.removed, files: stats.files, isMerge: stats.isMerge } : { ...one, statsFailed: true })),
1531
+ )
1532
+ }
1533
+ }
1534
+
1535
+ /** One history load at a time; a request while one runs joins it. */
1536
+ const reloadHistory = ($: Api): Promise<void> => {
1537
+ historyLoading ??= (async () => {
1538
+ await update($, history, (view): HistoryView => ({ ...view, state: 'loading' }))
1539
+ const loaded = await loadHistory(runOf($), await $.clock.now())
1540
+ await update($, history, () => loaded)
1541
+ })()
1542
+ .catch(() => undefined)
1543
+ .finally(() => {
1544
+ historyLoading = undefined
1545
+ })
1546
+ return historyLoading
1547
+ }
1548
+
1549
+ const rescanOnce = async ($: Api): Promise<void> => {
1550
+ const [start, calls] = await Promise.all([read($, sessionStart), read($, commitCalls)])
1551
+ if (start <= 0) return
1552
+ const run = runOf($)
1553
+ const scan = await scanSessionCommits(run, start, calls)
1554
+ if (scan === undefined) return
1555
+ if (scan.commits.length > 0) await update($, commits, list => mergeScanned(list, scan.commits))
1556
+ await fillCommitStats($, run, scan.repo)
1557
+ if ((await read($, history)).state !== 'idle') await reloadHistory($)
1558
+ }
1559
+
1560
+ /** Asks git for the session's commits shortly after a trigger; one rescan in flight, at most one queued. */
1561
+ const scheduleRescan = ($: Api): void => {
1562
+ rescanTimer?.cancel()
1563
+ rescanTimer = $.clock.after(RESCAN_MS, () => {
1564
+ rescanTimer = undefined
1565
+ if (scanning !== undefined) {
1566
+ scanAgain = true
1567
+ return
1568
+ }
1569
+ scanning = (async () => {
1570
+ do {
1571
+ scanAgain = false
1572
+ await rescanOnce($)
1573
+ } while (scanAgain)
1574
+ })()
1575
+ .catch(() => undefined)
1576
+ .finally(() => {
1577
+ scanning = undefined
1578
+ })
1579
+ })
1580
+ }
1581
+
1582
+ /** The session's start: stored once; a mod loaded mid-session reaches back to what it already recorded. */
1583
+ export const sessionStartOf = (stored: number, now: number, list: ToolEntry[], known: CommitRecord[]): number =>
1584
+ stored > 0 ? stored : Math.min(now, ...list.map(one => one.startedAt), ...known.map(one => one.at))
1585
+
1586
+ export const register: Register = on => {
1587
+ on('session.start', async ($, e, next) => {
1588
+ await $.command.register({ name: 'activity', description: 'Abre el panel de actividad' })
1589
+ const [stored, list, known] = await Promise.all([read($, sessionStart), read($, entries), read($, commits)])
1590
+ const now = await $.clock.now()
1591
+ await update($, sessionStart, () => sessionStartOf(stored, now, list, known))
1592
+ scheduleRescan($ as Api)
1593
+ void refreshAccent($ as Api).catch(() => undefined)
1594
+ return next(e)
1595
+ })
1596
+
1597
+ on('ui.close', async ($, e, next) => {
1598
+ if (e.id === PANE && e.origin.kind === 'person') await update($, autoOpen, () => false)
1599
+ return next(e)
1600
+ }).catch(($, e, next) => next(e))
1601
+
1602
+ on('session.measure', async ($, e, next) => {
1603
+ if (e.changed.includes('cost') && e.cost !== undefined) await update($, costUsd, () => e.cost?.usd ?? 0)
1604
+ if (e.changed.includes('context')) {
1605
+ const usage: ContextUsage = { window: e.context.window }
1606
+ if (e.context.tokens !== undefined) usage.tokens = e.context.tokens
1607
+ if (e.context.percent !== undefined) usage.percent = e.context.percent
1608
+ await update($, contextUsage, () => usage)
1609
+ }
1610
+ return next(e)
1611
+ })
1612
+
1613
+ on('turn.step', async function* ($, e, next) {
1614
+ const result = yield* next(e)
1615
+ const used = result?.usage
1616
+ if (used) {
1617
+ const tokens = used.input_tokens + used.cache_creation_input_tokens + used.cache_read_input_tokens
1618
+ await update($, stepContext, all => ({ ...all, [e.agentId ?? MAIN]: { tokens, model: used.model } })).catch(() => undefined)
1619
+ }
1620
+ return result
1621
+ })
1622
+
1623
+ on('turn.start', async ($, e, next) => {
1624
+ const loopId = e.agentId
1625
+ if (loopId === undefined) await update($, working, () => true)
1626
+ else await update($, agents, list => setAgentState(list, loopId, 'running'))
1627
+ return next(e)
1628
+ })
1629
+
1630
+ on('turn.complete', async ($, e, next) => {
1631
+ const done = await next(e)
1632
+ const loopId = e.agentId
1633
+ if (loopId === undefined) await update($, working, () => false)
1634
+ else await update($, agents, list => setAgentState(list, loopId, turnEndState(e.reason)))
1635
+ scheduleRescan($)
1636
+ void refreshAccent($).catch(() => undefined)
1637
+ return done
1638
+ })
1639
+
1640
+ on('agent.spawn', async ($, e, next) => {
1641
+ const spawned = await next(e)
1642
+ if (spawned.agentId !== undefined) {
1643
+ const record: AgentRecord = {
1644
+ id: spawned.agentId,
1645
+ description: oneLine(e.description ?? ''),
1646
+ type: oneLine(e.subagentType ?? 'agente'),
1647
+ state: 'running',
1648
+ startedAt: await $.clock.now(),
1649
+ }
1650
+ await update($, agents, list => mergeAgent(list, record))
1651
+ }
1652
+ return spawned
1653
+ }).catch(($, e, next) => next(e))
1654
+
1655
+ on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
1656
+ if (e.viewport?.isFullscreen === true && !autoOpenSent && (await read($, autoOpen))) {
1657
+ autoOpenSent = true
1658
+ void $.ui.open(PANE_ARGS).catch(() => undefined)
1659
+ }
1660
+ const usd = await read($, costUsd)
1661
+ if (usd <= 0) return next(e)
1662
+ return next({ ...e, props: { ...e.props, suffix: `${e.props.suffix} · ${dollars(usd)}` } })
1663
+ })
1664
+
1665
+ on('command.run', { command: 'activity' }, async $ => {
1666
+ const opened = await $.ui.open(PANE_ARGS).catch(() => undefined)
1667
+ return { text: opened?.isPlaced === false ? 'El panel de actividad espera a que haya espacio.' : 'Panel de actividad abierto.' }
1668
+ })
1669
+
1670
+ on('ui.scroll', { requestId: PANE }, async ($, e, next) => {
1671
+ const snap = await readSnapshot($ as Api)
1672
+ const view = snap.view
1673
+ const frame = paneFrame(buildPane(snap, 80), e.bodyRows, view, false)
1674
+ if (!frame.isWindowed) return next(e)
1675
+ const isJump = Math.abs(e.by) === e.contentRows && e.contentRows !== e.bodyRows
1676
+ await update($, scroll, state => scrolled(state, e.by, frame.total, frame.room, isJump))
1677
+ return {}
1678
+ }).catch(($, e, next) => next(e))
1679
+
1680
+ on('tool.call', async ($, e, next) => {
1681
+ const input = e as unknown as Record<string, unknown>
1682
+ const run: Run = (argv, init) => $.process.run(argv, init)
1683
+ const startedAt = await $.clock.now()
1684
+ const loopId = e.agentId
1685
+ const entry: ToolEntry = {
1686
+ id: e.tool_use_id,
1687
+ tool: e.tool,
1688
+ summary: summarize(input),
1689
+ status: 'running',
1690
+ output: '',
1691
+ startedAt,
1692
+ ...(loopId === undefined ? {} : { agentId: loopId }),
1693
+ }
1694
+ if (e.tool === 'Bash') entry.command = cleanText(input.command)
1695
+ const file = cleanText(input.file_path) ?? cleanText(input.notebook_path)
1696
+ if (file !== undefined) entry.file = file
1697
+ if (e.tool === 'Agent') entry.note = cleanText(input.subagent_type)
1698
+ if (e.tool === 'AskUserQuestion') entry.decisions = decisionsOf(input)
1699
+ await update($, entries, list => [...list, entry].slice(-KEEP))
1700
+
1701
+ if (loopId !== undefined && !(await read($, agents)).some(one => one.id === loopId)) {
1702
+ const info = (await $.agent.list().catch(() => [])).find(one => one.id === loopId)
1703
+ if (info) {
1704
+ const record: AgentRecord = { id: loopId, description: oneLine(info.description), type: oneLine(info.type), state: agentStateOf(info.status), startedAt }
1705
+ if (info.name) record.name = oneLine(info.name)
1706
+ await update($, agents, list => mergeAgent(list, record))
1707
+ }
1708
+ }
1709
+
1710
+ const finish = async (finished: Partial<ToolEntry>) => {
1711
+ const durationMs = (await $.clock.now()) - startedAt
1712
+ await update($, entries, list => list.map(one => (one.id === entry.id ? { ...one, durationMs, ...finished } : one)))
1713
+ }
1714
+
1715
+ let ran: Awaited<ReturnType<typeof next>> | undefined
1716
+ try {
1717
+ ran = await next(e)
1718
+ } finally {
1719
+ if (ran === undefined) await finish({ status: 'interrupted', output: 'interrumpido' }).catch(() => undefined)
1720
+ }
1721
+
1722
+ const wasInterrupted = (ran.result as { interrupted?: unknown } | undefined)?.interrupted === true
1723
+ const status: CallStatus = ran.deny !== undefined ? 'denied' : wasInterrupted ? 'interrupted' : ran.isError === true ? 'error' : 'ok'
1724
+ const full = ran.deny ?? ran.text ?? ''
1725
+ const finished: Partial<ToolEntry> = { status, output: lastLines(full, OUTPUT_LINES) }
1726
+ if (entry.command !== undefined) {
1727
+ const exitCode = exitCodeOf(full, ran.isError === true)
1728
+ if (exitCode !== undefined) finished.exitCode = exitCode
1729
+ if (isTestCommand(entry.command)) finished.testFiles = testFilesOf(full)
1730
+ }
1731
+ if (e.tool === 'AskUserQuestion') finished.decisions = answered(input, status, ran.result)
1732
+ const spawnedId = text((ran.result as { agentId?: unknown } | undefined)?.agentId)
1733
+ if (e.tool === 'Agent' && spawnedId !== undefined) {
1734
+ finished.spawned = spawnedId
1735
+ const state = agentResultState(status, ran.result)
1736
+ const known = (await read($, agents)).some(one => one.id === spawnedId) || (await $.agent.list().catch(() => [])).some(one => one.id === spawnedId)
1737
+ if (state !== undefined && known) {
1738
+ const record: AgentRecord = { id: spawnedId, description: cleanText(input.description) ?? '', type: entry.note ?? 'agente', state, startedAt }
1739
+ await update($, agents, list => mergeAgent(list, record))
1740
+ }
1741
+ }
1742
+ await finish(finished)
1743
+
1744
+ const rawCommand = text(input.command)
1745
+ if (e.tool === 'Bash' && status !== 'denied' && rawCommand !== undefined && gitCommitVerbs(rawCommand).length > 0) {
1746
+ const endedAt = await $.clock.now()
1747
+ const dir = commitDirOf(rawCommand)
1748
+ const top = dir === undefined || !SAFE_PATH.test(dir) ? undefined : await gitTop(run, dir)
1749
+ const call: CommitCall = { startedAt, endedAt, ...(loopId === undefined ? {} : { agentId: loopId }), ...(top === undefined ? {} : { top }) }
1750
+ await update($, commitCalls, list => [...list, call].slice(-COMMIT_CALLS))
1751
+ scheduleRescan($ as Api)
1752
+ }
1753
+ if (e.tool === 'Bash' && status === 'ok' && rawCommand !== undefined && ran.text !== undefined) {
1754
+ const found = commitsIn(rawCommand, ran.text)
1755
+ if (found.length > 0) await update($, commits, list => addCommits(list, found, loopId, startedAt))
1756
+ if (madeMergeCommit(rawCommand, ran.text)) {
1757
+ void (async () => {
1758
+ const top = await gitTop(run)
1759
+ const head = top === undefined ? undefined : await loadHeadCommit(run, top)
1760
+ if (head) await update($, commits, list => addCommits(list, [head], loopId, startedAt))
1761
+ })().catch(() => undefined)
1762
+ }
1763
+ }
1764
+
1765
+ const refresh = async () => {
1766
+ const top = await gitTop(run)
1767
+ if (top === undefined) return
1768
+ const fileList = await loadUncommitted(run, top, async path => {
1769
+ const info = await $.fs.stat(path)
1770
+ return info.isLink || info.kind !== 'file' || info.size > 2_000_000 ? Promise.reject(new Error('skipped')) : $.fs.read(path)
1771
+ })
1772
+ if (fileList !== undefined) await update($, changes, () => fileList)
1773
+
1774
+ for (const key of await read($, openFiles)) {
1775
+ if (!key.startsWith('u:') && !key.startsWith('b:')) continue
1776
+ const path = key.slice(2)
1777
+ const change = key.startsWith('u:') ? fileList?.find(one => one.path === path) : undefined
1778
+ if (key.startsWith('u:') && change === undefined) {
1779
+ await update($, openFiles, keys => keys.filter(one => one !== key))
1780
+ await update($, diffs, all => Object.fromEntries(Object.entries(all).filter(([name]) => name !== key)))
1781
+ continue
1782
+ }
1783
+ const target: DiffTarget = key.startsWith('u:')
1784
+ ? { scope: 'uncommitted', path, ...(change?.untracked ? { untracked: true } : {}) }
1785
+ : { scope: 'branch', path, sha: (await read($, branch)).base }
1786
+ const patch = await fetchDiff(run, top, target)
1787
+ await update($, diffs, all => ({ ...all, [key]: patch }))
1788
+ }
1789
+
1790
+ await fillCommitStats($ as Api, run, top)
1791
+
1792
+ if ((await read($, branch)).isLoaded) {
1793
+ const view = await loadBranch(run, top)
1794
+ await update($, branch, () => view)
1795
+ }
1796
+ }
1797
+
1798
+ const touchesFiles = (e.tool === 'Bash' && ran.isReadOnly !== true) || CHANGE_TOOLS.has(e.tool)
1799
+ if (touchesFiles) {
1800
+ refreshTimer?.cancel()
1801
+ refreshTimer = $.clock.after(REFRESH_MS, () => {
1802
+ refreshTimer = undefined
1803
+ void refresh().catch(() => undefined)
1804
+ })
1805
+ }
1806
+ return ran
1807
+ }).catch(($, e, next) => next(e))
1808
+
1809
+ on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
1810
+ if (e.props.isExpanded === true) return next(e)
1811
+ const { Box, Text } = $.ui.resolve(e)
1812
+ const summary = summarize((e.props.input ?? {}) as Record<string, unknown>)
1813
+ if (e.props.isInterrupted) {
1814
+ return <Text dimColor wrap="truncate-end">{ICONS.interrupted} interrumpido: {e.props.tool} {summary}</Text>
1815
+ }
1816
+ if (!e.props.isErrored) return <Box />
1817
+ return (
1818
+ <Text color="error" wrap="truncate-end">
1819
+ {ICONS.error} {e.props.tool} falló: {summary}
1820
+ </Text>
1821
+ )
1822
+ })
1823
+
1824
+ on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
1825
+ if (e.props.isExpanded === true) return next(e)
1826
+ const { Box } = $.ui.resolve(e)
1827
+ return <Box />
1828
+ })
1829
+
1830
+ on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
1831
+ if (e.props.isExpanded) return next(e)
1832
+ const { Box, Text } = $.ui.resolve(e)
1833
+ const notable = e.props.calls.filter(call => call.isErrored || call.isInterrupted)
1834
+ if (notable.length === 0) return <Box />
1835
+ return (
1836
+ <Box flexDirection="column">
1837
+ {notable.map(call => {
1838
+ const summary = summarize((call.input ?? {}) as Record<string, unknown>)
1839
+ return call.isErrored ? (
1840
+ <Text color="error" wrap="truncate-end">{ICONS.error} {call.tool} falló: {summary}</Text>
1841
+ ) : (
1842
+ <Text dimColor wrap="truncate-end">{ICONS.interrupted} interrumpido: {call.tool} {summary}</Text>
1843
+ )
1844
+ })}
1845
+ </Box>
1846
+ )
1847
+ })
1848
+
1849
+ on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
1850
+ if (e.props.origin.kind !== 'composer') return next(e)
1851
+ const { Box, Text } = $.ui.resolve(e)
1852
+ return (
1853
+ <Box flexDirection="column">
1854
+ <Text color="permission" bold>▎ Tú</Text>
1855
+ {await next(e)}
1856
+ </Box>
1857
+ )
1858
+ })
1859
+
1860
+ on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
1861
+ if (!e.props.isFirstOfReply) return next(e)
1862
+ const { Box, Text } = $.ui.resolve(e)
1863
+ return (
1864
+ <Box flexDirection="column">
1865
+ <Text color="claude" bold>▎ Claude</Text>
1866
+ {await next(e)}
1867
+ </Box>
1868
+ )
1869
+ })
1870
+
1871
+ on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1872
+ const { Box, Text, Button } = $.ui.resolve(e)
1873
+ const snap = await readSnapshot($ as Api)
1874
+ const view = snap.view
1875
+ const width = Math.max(1, e.props.bodyColumns)
1876
+ const model = buildPane(snap, width)
1877
+ const frame = paneFrame(model, e.props.scroll.bodyRows, view, e.props.placement === 'dock')
1878
+ const run: Run = (argv, init) => $.process.run(argv, init)
1879
+ if (model.tab === 'history' && snap.historyView.state === 'idle') void reloadHistory($ as Api)
1880
+
1881
+ const resetScroll = () => update($, scroll, () => ({ offset: 0, follow: false }))
1882
+ const toggleDiff = async (target: DiffTarget) => {
1883
+ const key = targetKey(target)
1884
+ let isOpening = false
1885
+ const keys = await update($, openFiles, current => {
1886
+ isOpening = !current.includes(key)
1887
+ return isOpening ? [...current, key].slice(-OPEN_DIFFS) : current.filter(one => one !== key)
1888
+ })
1889
+ if (!isOpening) {
1890
+ await update($, diffs, all => Object.fromEntries(Object.entries(all).filter(([name]) => name !== key)))
1891
+ return
1892
+ }
1893
+ const top = await gitTop(run)
1894
+ const patch = top === undefined ? { rows: [], total: 0 } : await fetchDiff(run, top, target)
1895
+ await update($, diffs, all => ({ ...Object.fromEntries(Object.entries(all).filter(([name]) => keys.includes(name))), [key]: patch }))
1896
+ }
1897
+ const toggleCommit = async (sha: string) => {
1898
+ const key = `hist-${sha}`
1899
+ let isOpening = false
1900
+ await update($, toggled, keys => {
1901
+ isOpening = !keys.includes(key)
1902
+ return isOpening ? [...keys, key].slice(-200) : keys.filter(one => one !== key)
1903
+ })
1904
+ const known = ownerOf(sessionOwners(await read($, commits)), sha)
1905
+ if (!isOpening || known?.files !== undefined || (await read($, historyFiles))[sha]?.files !== undefined) return
1906
+ const top = await gitTop(run)
1907
+ const stats = top === undefined ? undefined : await loadCommitStats(run, top, sha)
1908
+ const loaded: HistoryFiles = stats ? { files: stats.files } : { failed: true }
1909
+ await update($, historyFiles, all => Object.fromEntries([...Object.entries(all).filter(([name]) => name !== sha), [sha, loaded]].slice(-HISTORY_FILES)))
1910
+ }
1911
+ const openTarget = async (target: DiffTarget) => {
1912
+ const top = await gitTop(run)
1913
+ if (top === undefined) {
1914
+ $.ui.toast('No hay repositorio git aquí.')
1915
+ return
1916
+ }
1917
+ const outcome = await openInEditor(run, path => $.fs.exists(path), { top, path: target.path, base: editorBase(target), editor: await read($, editor) })
1918
+ const kept = outcome.editor
1919
+ if (kept) await update($, editor, () => kept)
1920
+ if (!outcome.ok) $.ui.toast(outcome.message ?? 'No se pudo abrir el editor.')
1921
+ }
1922
+ const act = async (action: Action) => {
1923
+ if (action.kind === 'toggle') {
1924
+ await update($, toggled, keys => (keys.includes(action.key) ? keys.filter(one => one !== action.key) : [...keys, action.key].slice(-200)))
1925
+ } else if (action.kind === 'tab') {
1926
+ await update($, tabs, all => ({ ...all, [model.scope]: action.tab }))
1927
+ await resetScroll()
1928
+ if (action.tab === 'history') await reloadHistory($ as Api)
1929
+ } else if (action.kind === 'agent') {
1930
+ await update($, pickedAgent, () => action.id)
1931
+ await resetScroll()
1932
+ } else if (action.kind === 'scope') {
1933
+ await update($, scopes, all => ({ ...all, [model.scope]: action.scope }))
1934
+ await resetScroll()
1935
+ if (action.scope === 'branch') {
1936
+ const top = await gitTop(run)
1937
+ const loaded: BranchView = top === undefined ? { isLoaded: true, files: [], commits: [], error: 'No hay repositorio git aquí.' } : await loadBranch(run, top)
1938
+ await update($, branch, () => loaded)
1939
+ }
1940
+ } else if (action.kind === 'commit') {
1941
+ await toggleCommit(action.sha)
1942
+ } else if (action.kind === 'diff') {
1943
+ await toggleDiff(action.target)
1944
+ } else {
1945
+ await openTarget(action.target)
1946
+ }
1947
+ }
1948
+
1949
+ const spansOf = (spans: Span[]) =>
1950
+ spans.map(one => (
1951
+ <Text color={one.color} dimColor={one.dim} bold={one.bold} inverse={one.inverse}>{one.text}</Text>
1952
+ ))
1953
+ const cellOf = (rowKey: string, cell: Cell, index: number) => {
1954
+ const action = cell.action
1955
+ if (!action) return <Text wrap="truncate-end">{spansOf(cell.spans)}</Text>
1956
+ return (
1957
+ <Button key={cell.key ?? `${rowKey}-${index}`} plain label={cell.label ?? ''} onPress={() => void act(action).catch(() => undefined)}>
1958
+ <Text wrap="truncate-end">{spansOf(cell.spans)}</Text>
1959
+ </Button>
1960
+ )
1961
+ }
1962
+ const rowOf = (row: Row) => {
1963
+ const hasAction = row.cells.some(cell => cell.action !== undefined)
1964
+ const left = hasAction
1965
+ ? <Box flexDirection="row">{row.cells.map((cell, index) => cellOf(row.key, cell, index))}</Box>
1966
+ : <Text wrap="truncate-end">{row.cells.flatMap(cell => spansOf(cell.spans))}</Text>
1967
+ if (row.right === undefined) {
1968
+ return hasAction
1969
+ ? <Box key={row.key} flexDirection="row" width={width}>{row.cells.map((cell, index) => cellOf(row.key, cell, index))}</Box>
1970
+ : <Text key={row.key} wrap="truncate-end">{row.cells.flatMap(cell => spansOf(cell.spans))}</Text>
1971
+ }
1972
+ return (
1973
+ <Box key={row.key} flexDirection="row" justifyContent="space-between" width={width}>
1974
+ {left}
1975
+ <Text>{spansOf(row.right.length > 0 ? row.right : [span(' ')])}</Text>
1976
+ </Box>
1977
+ )
1978
+ }
1979
+
1980
+ return <Box flexDirection="column" width={width}>{frame.rows.map(rowOf)}</Box>
1981
+ })
1982
+ }