project-brain 0.44.0 → 0.46.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,283 @@
1
+ import type { Hook } from 'claude-code'
2
+ import { atom, read, update } from 'claude-code'
3
+ import type { ContextCategory, Register, SessionCompactResult, SessionContextBreakdown, SessionContextUsage } from 'claude-code'
4
+
5
+ import type { Api, Row, Span, Tone } from './register'
6
+ import { clean, compact, contextPercentOf, fit, span } from './register'
7
+
8
+ /** One breakdown row the pane keeps: deferred schemas sit outside the window and are dropped. */
9
+ export type ContextRowKind = 'used' | 'free' | 'buffer'
10
+ export type ContextRowRecord = { name: string; tokens: number; kind: ContextRowKind }
11
+
12
+ /** The last breakdown read, against the window its categories sum to (the compaction window). */
13
+ export type ContextBreakdownState = {
14
+ rows: ContextRowRecord[]
15
+ window: number
16
+ total: number
17
+ autoCompactAt?: number
18
+ at: number
19
+ }
20
+
21
+ /** Compactions of the main conversation this session. */
22
+ export type CompactionRecord = { count: number; lastAt: number; before?: number; after?: number }
23
+
24
+ export type ContextPart = {
25
+ breakdown: ContextBreakdownState
26
+ compactions: CompactionRecord
27
+ /** The session's live figures, measured against the model's window. */
28
+ usage: { tokens?: number; window: number; percent?: number }
29
+ now: number
30
+ }
31
+
32
+ type On = Parameters<Register>[0]
33
+
34
+ const REFRESH_MS = 15_000
35
+ const MAX_ROWS = 20
36
+ const WARN_PERCENT = 80
37
+ const ERROR_PERCENT = 90
38
+ const BAR_CELLS = 8
39
+ const SECTION_KEY = 'ctxb-section'
40
+
41
+ const EMPTY_BREAKDOWN: ContextBreakdownState = { rows: [], window: 0, total: 0, at: 0 }
42
+ const EMPTY_COMPACTIONS: CompactionRecord = { count: 0, lastAt: 0 }
43
+ const EMPTY_LIVE: ContextPart['usage'] = { window: 0 }
44
+
45
+ const breakdownAtom = atom({ plugin: 'project-brain-activity', key: 'contextBreakdown' } as const, EMPTY_BREAKDOWN, { shape: 'context-breakdown-1' })
46
+ const compactionsAtom = atom({ plugin: 'project-brain-activity', key: 'contextCompactions' } as const, EMPTY_COMPACTIONS, { shape: 'context-compactions-1' })
47
+ const liveAtom = atom({ plugin: 'project-brain-activity', key: 'contextLive' } as const, EMPTY_LIVE, { shape: 'context-live-1' })
48
+
49
+ const LABELS: Record<string, string> = {
50
+ 'System prompt': 'Sistema',
51
+ 'System tools': 'Herramientas',
52
+ 'MCP tools': 'MCP',
53
+ Messages: 'Mensajes',
54
+ 'Memory files': 'Memoria (CLAUDE.md)',
55
+ Skills: 'Skills',
56
+ 'Free space': 'Libre',
57
+ 'Autocompact buffer': 'Reserva de compactación',
58
+ }
59
+
60
+ // A reload resets these: it only costs one extra breakdown read.
61
+ let lastRefreshAt = 0
62
+ let refreshing: Promise<void> | undefined
63
+
64
+ /** The Spanish label for an engine category name; unknown names pass through, cleaned. */
65
+ export const contextLabelOf = (name: string): string => LABELS[name] ?? clean(name).slice(0, 60)
66
+
67
+ const isKept = (row: ContextCategory): row is ContextCategory & { kind: ContextRowKind } =>
68
+ !row.isDeferred && (row.kind === 'used' || row.kind === 'free' || row.kind === 'buffer')
69
+
70
+ /** The engine's breakdown as the pane stores it: bounded, deferred rows dropped, numbers only. */
71
+ export const breakdownOf = (raw: SessionContextBreakdown, at: number): ContextBreakdownState => {
72
+ const rows = raw.categories
73
+ .filter(isKept)
74
+ .slice(0, MAX_ROWS)
75
+ .map(row => ({ name: clean(String(row.name)).slice(0, 60), tokens: Math.max(0, Number(row.tokens) || 0), kind: row.kind }))
76
+ const state: ContextBreakdownState = { rows, window: Math.max(0, raw.rawMaxTokens || 0), total: Math.max(0, raw.totalTokens || 0), at }
77
+ if (raw.isAutoCompactEnabled && typeof raw.autoCompactThreshold === 'number') state.autoCompactAt = raw.autoCompactThreshold
78
+ return state
79
+ }
80
+
81
+ /** Folds one `session.compact` result into the record; skips and precomputes change nothing. */
82
+ export const recordCompaction = (
83
+ record: CompactionRecord,
84
+ result: SessionCompactResult | undefined,
85
+ trigger: string,
86
+ at: number,
87
+ ): CompactionRecord => {
88
+ if (result === undefined || result.skip !== undefined || trigger === 'precompute') return record
89
+ const next: CompactionRecord = { count: record.count + 1, lastAt: at }
90
+ if (typeof result.tokensBefore === 'number') next.before = result.tokensBefore
91
+ if (typeof result.tokensAfter === 'number') next.after = result.tokensAfter
92
+ return next
93
+ }
94
+
95
+ /** "hace 40 s", "hace 5 min", "hace 2 h", "hace 3 d". */
96
+ export const agoLabel = (ms: number): string => {
97
+ const secs = Math.max(0, Math.round(ms / 1000))
98
+ if (secs < 60) return `hace ${secs} s`
99
+ const mins = Math.round(secs / 60)
100
+ if (mins < 60) return `hace ${mins} min`
101
+ const hours = Math.round(mins / 60)
102
+ return hours < 48 ? `hace ${hours} h` : `hace ${Math.round(hours / 24)} d`
103
+ }
104
+
105
+ export const compactionLabel = (record: CompactionRecord, now: number): string => {
106
+ if (record.count === 0) return 'Sin compactaciones en esta sesión'
107
+ const times = record.count === 1 ? '1 vez' : `${record.count} veces`
108
+ const parts = [`Compactado ${times}`]
109
+ if (record.lastAt > 0) parts.push(`última ${agoLabel(now - record.lastAt)}`)
110
+ if (record.before !== undefined && record.after !== undefined) parts.push(`${compact(record.before)}→${compact(record.after)}`)
111
+ return parts.join(' · ')
112
+ }
113
+
114
+ /** The live fill against the session's measured window; the breakdown's own figure only before a response came back. */
115
+ export const livePercent = (part: Pick<ContextPart, 'usage' | 'breakdown'>): number | undefined => {
116
+ const measured = contextPercentOf(part.usage)
117
+ if (measured !== undefined) return measured
118
+ const { total, window } = part.breakdown
119
+ return window > 0 && total > 0 ? (total / window) * 100 : undefined
120
+ }
121
+
122
+ const miniBar = (percent: number): string => {
123
+ const filled = Math.min(BAR_CELLS, Math.max(0, Math.round((percent / 100) * BAR_CELLS)))
124
+ return '▰'.repeat(filled) + '▱'.repeat(BAR_CELLS - filled)
125
+ }
126
+
127
+ const ROW_TONE: Record<ContextRowKind, Tone | undefined> = { used: undefined, free: 'subtle', buffer: 'subtle' }
128
+
129
+ /** Below these widths a breakdown row sheds its bar, then its percent. */
130
+ const BAR_FROM = 29
131
+ const PERCENT_FROM = 20
132
+ const INDENT_FROM = 12
133
+
134
+ /** Which parts of a breakdown row fit, and how wide its name is; the whole row is never wider than `width`. */
135
+ export const breakdownLayout = (width: number): { indent: string; nameWidth: number; hasPercent: boolean; hasBar: boolean } => {
136
+ if (width >= BAR_FROM) return { indent: ' ', nameWidth: Math.max(6, Math.min(26, width - (BAR_CELLS + 16))), hasPercent: true, hasBar: true }
137
+ if (width >= PERCENT_FROM) return { indent: ' ', nameWidth: Math.min(26, width - 14), hasPercent: true, hasBar: false }
138
+ const indent = width >= INDENT_FROM ? ' ' : ''
139
+ return { indent, nameWidth: Math.max(1, width - indent.length - 5), hasPercent: false, hasBar: false }
140
+ }
141
+
142
+ export const rowsContext = (
143
+ part: ContextPart,
144
+ ctx: { width: number; accent: string; isOpen: (key: string, byDefault: boolean) => boolean },
145
+ ): Row[] => {
146
+ const width = Math.max(1, ctx.width)
147
+ const { breakdown, compactions } = part
148
+ const percent = livePercent(part)
149
+ const headParts = ['Contexto']
150
+ if (breakdown.window > 0) headParts.push(`${compact(breakdown.total)} / ${compact(breakdown.window)}`)
151
+ if (percent !== undefined) headParts.push(`${Math.round(percent)} %`)
152
+ if (compactions.count > 0) headParts.push(`${compactions.count}× compactado`)
153
+ const label = headParts.join(' · ')
154
+ const open = ctx.isOpen(SECTION_KEY, true)
155
+ const header: Row = {
156
+ key: SECTION_KEY,
157
+ cells: [{ spans: [span(fit(`${open ? '▼' : '▶'} ${label}`, width))], action: { kind: 'toggle', key: SECTION_KEY }, label, key: `btn-${SECTION_KEY}` }],
158
+ }
159
+ if (!open) return [header]
160
+
161
+ const line = (key: string, value: string, style: Omit<Span, 'text'> = {}): Row => ({ key, cells: [{ spans: [span(fit(value, width), style)] }] })
162
+ const body: Row[] = []
163
+ if (breakdown.rows.length === 0 || breakdown.window <= 0) {
164
+ body.push(line('ctxb-empty', ' Desglose aún sin medir', { dim: true }))
165
+ } else {
166
+ const ordered = [
167
+ ...breakdown.rows.filter(row => row.kind === 'used'),
168
+ ...breakdown.rows.filter(row => row.kind === 'free'),
169
+ ...breakdown.rows.filter(row => row.kind === 'buffer'),
170
+ ]
171
+ const layout = breakdownLayout(width)
172
+ ordered.forEach((row, index) => {
173
+ const share = (row.tokens / breakdown.window) * 100
174
+ const name = fit(contextLabelOf(row.name), layout.nameWidth).padEnd(layout.nameWidth)
175
+ const tokens = compact(row.tokens).padStart(layout.hasPercent ? 6 : 5)
176
+ const percent = layout.hasPercent ? ` ${`${Math.round(share)} %`.padStart(5)}` : ''
177
+ const figures = `${tokens}${percent}${layout.hasBar ? ' ' : ''}`
178
+ const dim = row.kind !== 'used'
179
+ const tone = ROW_TONE[row.kind]
180
+ body.push({
181
+ key: `ctxb-row-${index}`,
182
+ cells: [{
183
+ spans: [
184
+ span(`${layout.indent}${name}`, { dim }),
185
+ span(figures, { dim }),
186
+ ...(layout.hasBar ? [span(miniBar(share), dim ? { dim, ...(tone ? { color: tone } : {}) } : { color: ctx.accent })] : []),
187
+ ],
188
+ }],
189
+ })
190
+ })
191
+ if (breakdown.autoCompactAt !== undefined) {
192
+ body.push(line('ctxb-threshold', ` Compacta al llegar a ${compact(breakdown.autoCompactAt)} tokens`, { dim: true }))
193
+ }
194
+ }
195
+ body.push(line('ctxb-compactions', ` ${compactionLabel(compactions, part.now)}`, compactions.count > 0 ? {} : { dim: true }))
196
+ return [header, ...body]
197
+ }
198
+
199
+ export const footerContext = (part: Pick<ContextPart, 'usage' | 'breakdown'>): Span[] => {
200
+ const measured = livePercent(part)
201
+ if (measured === undefined) return []
202
+ const percent = Math.round(measured)
203
+ if (percent < WARN_PERCENT) return []
204
+ const isError = percent >= ERROR_PERCENT
205
+ return [span(`⚠ ${percent} % · se compactará pronto`, { color: isError ? 'error' : 'warning', bold: isError })]
206
+ }
207
+
208
+ /** The session's live figures as the pane stores them: numbers only, no breakdown. */
209
+ export const liveOf = (usage: SessionContextUsage): ContextPart['usage'] => {
210
+ const live: ContextPart['usage'] = { window: usage.window }
211
+ if (usage.tokens !== undefined) live.tokens = usage.tokens
212
+ if (usage.percent !== undefined) live.percent = usage.percent
213
+ return live
214
+ }
215
+
216
+ /** Atoms only: the live figures arrive through `session.measure` and the refreshes below, never from a draw. */
217
+ export async function readContext($: Api): Promise<ContextPart> {
218
+ const [breakdown, compactions, usage, now] = await Promise.all([
219
+ read($, breakdownAtom).catch(() => EMPTY_BREAKDOWN),
220
+ read($, compactionsAtom).catch(() => EMPTY_COMPACTIONS),
221
+ read($, liveAtom).catch(() => EMPTY_LIVE),
222
+ $.clock.now().catch(() => 0),
223
+ ])
224
+ return { breakdown, compactions, usage, now }
225
+ }
226
+
227
+ /** `session.measure` pushes what `$.session.usage()` would answer: kept so a draw never asks. */
228
+ export async function contextMeasured($: Api, usage: SessionContextUsage): Promise<void> {
229
+ await update($, liveAtom, () => liveOf(usage))
230
+ }
231
+
232
+ /** One `$.session.usage` read per event: the live figures always, the breakdown when forced or due. */
233
+ async function refreshContext($: Api, force: boolean): Promise<void> {
234
+ const now = await $.clock.now()
235
+ if (refreshing) return
236
+ const isDue = force || now - lastRefreshAt >= REFRESH_MS
237
+ if (isDue) lastRefreshAt = now
238
+ refreshing = (async () => {
239
+ const found = await $.session.usage(isDue ? { breakdown: 'summary' } : undefined)
240
+ await update($, liveAtom, () => liveOf(found.context))
241
+ const raw = found.context.breakdown
242
+ if (isDue && raw) await update($, breakdownAtom, () => breakdownOf(raw, now))
243
+ })()
244
+ .catch(() => undefined)
245
+ .finally(() => {
246
+ refreshing = undefined
247
+ })
248
+ await refreshing
249
+ }
250
+
251
+ /** The live figures now, the breakdown when due: for a pane opened before any event filled them. */
252
+ export async function contextKick($: Api): Promise<void> {
253
+ await refreshContext($, false)
254
+ }
255
+
256
+ export const registerContext = (on: On): void => {
257
+
258
+
259
+ on('session.compact', async ($, e, next) => {
260
+ const result = await next(e)
261
+ if (e.agentId !== undefined) return result
262
+ try {
263
+ const at = await $.clock.now()
264
+ await update($, compactionsAtom, record => recordCompaction(record, result, e.trigger, at))
265
+ if (result.skip === undefined && e.trigger !== 'precompute') void refreshContext($ as Api, true).catch(() => undefined)
266
+ } catch {
267
+ // Bookkeeping only: the compaction stands either way.
268
+ }
269
+ return result
270
+ })
271
+ }
272
+
273
+ export async function contextSessionStart($: Api, e: Parameters<Hook<'session.start'>>[1], next: Parameters<Hook<'session.start'>>[2]): Promise<Awaited<ReturnType<Hook<'session.start'>>>> {
274
+ const result = await next(e)
275
+ void refreshContext($ as Api, true).catch(() => undefined)
276
+ return result
277
+ }
278
+
279
+ export async function contextTurnComplete($: Api, e: Parameters<Hook<'turn.complete'>>[1], next: Parameters<Hook<'turn.complete'>>[2]): Promise<Awaited<ReturnType<Hook<'turn.complete'>>>> {
280
+ const result = await next(e)
281
+ if (e.agentId === undefined) void refreshContext($, false).catch(() => undefined)
282
+ return result
283
+ }
@@ -0,0 +1,145 @@
1
+ import type { Hook } from 'claude-code'
2
+ import { atom, read, update } from 'claude-code'
3
+
4
+ import type { Api } from './register'
5
+ import { oneLine } from './register'
6
+ import { elapsed } from './feat-running'
7
+
8
+ /** One finished thing worth telling the person about, keyed so it is told once. */
9
+ export type NotifyItem = { key: string; text: string }
10
+
11
+ /** What is waiting to go out, and the keys already told. */
12
+ export type NotifyQueue = { pending: NotifyItem[]; seen: string[] }
13
+
14
+ export const COALESCE_MS = 5000
15
+ export const LONG_TURN_MS = 120_000
16
+ export const NOTIFY_TITLE = 'Claude · Actividad'
17
+ const SEEN_MAX = 200
18
+ const LINE_MAX = 240
19
+ const SHOWN_IN_BURST = 3
20
+
21
+ const notifyOn = atom({ plugin: 'project-brain-activity', key: 'notify' } as const, true, { shape: 'notify-1' })
22
+
23
+ // A reload drops these: what was pending is lost, and the transitions that raise items are not replayed.
24
+ let queue: NotifyQueue = { pending: [], seen: [] }
25
+ let flushTimer: { cancel: () => void } | undefined
26
+ let osKind: 'darwin' | 'linux' | 'other' | undefined
27
+
28
+ // ---------------------------------------------------------------- queue
29
+
30
+ /** Adds an item unless its key was already told or is waiting; `isFirst` says a new burst starts. */
31
+ export const enqueue = (state: NotifyQueue, item: NotifyItem): { queue: NotifyQueue; isAdded: boolean; isFirst: boolean } => {
32
+ if (state.seen.includes(item.key) || state.pending.some(one => one.key === item.key)) return { queue: state, isAdded: false, isFirst: false }
33
+ return { queue: { ...state, pending: [...state.pending, item] }, isAdded: true, isFirst: state.pending.length === 0 }
34
+ }
35
+
36
+ /** Empties the pending list into one message, remembering its keys. */
37
+ export const drain = (state: NotifyQueue): { queue: NotifyQueue; text: string | undefined } => {
38
+ const text = burstText(state.pending)
39
+ const seen = [...state.seen, ...state.pending.map(one => one.key)].slice(-SEEN_MAX)
40
+ return { queue: { pending: [], seen }, text }
41
+ }
42
+
43
+ /** One item reads as itself; a burst reads as a count and its first few lines. */
44
+ export const burstText = (items: NotifyItem[]): string | undefined => {
45
+ if (items.length === 0) return undefined
46
+ if (items.length === 1) return items[0]?.text
47
+ const shown = items.slice(0, SHOWN_IN_BURST).map(one => one.text)
48
+ const rest = items.length - shown.length
49
+ return `${items.length} terminaron: ${shown.join(' · ')}${rest > 0 ? ` · y ${rest} más` : ''}`
50
+ }
51
+
52
+ // ---------------------------------------------------------------- text
53
+
54
+ /** The line a main turn of over two minutes raises; nothing for a short or interrupted one. */
55
+ export const turnLine = (e: { reason: string; durationMs: number; agentId?: string }): string | undefined => {
56
+ if (e.agentId !== undefined || e.reason === 'aborted' || e.durationMs < LONG_TURN_MS) return undefined
57
+ const took = elapsed(e.durationMs)
58
+ if (e.reason === 'error') return `✗ El turno falló por un error de la API · ${took}`
59
+ if (e.reason === 'refusal') return `✗ El modelo rechazó el turno · ${took}`
60
+ return `✓ Claude terminó el turno · ${took}`
61
+ }
62
+
63
+ /** AppleScript string literal body: backslashes and quotes escaped, one line. */
64
+ export const appleScriptText = (value: string): string => oneLine(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"')
65
+
66
+ /** The argv that raises a desktop notification on this system; none where there is no known command. */
67
+ export const osNotifyArgv = (kind: 'darwin' | 'linux' | 'other', title: string, text: string): string[] | undefined => {
68
+ if (kind === 'darwin') return ['/usr/bin/osascript', '-e', `display notification "${appleScriptText(text)}" with title "${appleScriptText(title)}"`]
69
+ if (kind === 'linux') return ['notify-send', '--app-name=Claude', oneLine(title), oneLine(text)]
70
+ return undefined
71
+ }
72
+
73
+ /** `/<pane command> notify on|off|test`: the new setting, a test, or a status read; undefined for any other args. */
74
+ export const parseNotifyArgs = (args: string): 'on' | 'off' | 'test' | 'status' | undefined => {
75
+ const words = args.trim().toLowerCase().split(/\s+/)
76
+ if (words[0] !== 'notify') return undefined
77
+ const word = words[1] ?? ''
78
+ if (word === '') return 'status'
79
+ if (word === 'on' || word === 'off' || word === 'test') return word
80
+ return undefined
81
+ }
82
+
83
+ // ---------------------------------------------------------------- engine
84
+
85
+ /** Queues one finished thing; the first of a burst starts the 5 s window that coalesces the rest. */
86
+ export async function notify($: Api, item: NotifyItem): Promise<void> {
87
+ const added = enqueue(queue, { key: item.key, text: oneLine(item.text).slice(0, LINE_MAX) })
88
+ queue = added.queue
89
+ if (!added.isFirst) return
90
+ flushTimer?.cancel()
91
+ flushTimer = $.clock.after(COALESCE_MS, () => {
92
+ flushTimer = undefined
93
+ void flushNotify($).catch(() => undefined)
94
+ })
95
+ }
96
+
97
+ /** Sends what the window gathered, unless the person turned notifications off. */
98
+ export async function flushNotify($: Api): Promise<void> {
99
+ const drained = drain(queue)
100
+ queue = drained.queue
101
+ if (drained.text === undefined || !(await read($, notifyOn))) return
102
+ await sendNotification($, drained.text)
103
+ }
104
+
105
+ /** The engine's own channel first; the system's notifier when that channel shows no text. */
106
+ export async function sendNotification($: Api, text: string): Promise<string> {
107
+ const sent = await $.ui.notify(text, { title: NOTIFY_TITLE }).catch(() => undefined)
108
+ if (sent?.isSent === true && sent.channel !== 'terminal_bell') return sent.channel
109
+ if (sent?.isSent === false && sent.reason !== 'no-channel') return sent.reason
110
+ const argv = osNotifyArgv(await systemKind($), NOTIFY_TITLE, text)
111
+ if (argv === undefined) return sent?.isSent === true ? sent.channel : 'no-channel'
112
+ const ran = await $.process.run(argv, { timeoutMs: 5000 }).catch(() => undefined)
113
+ return ran?.exitCode === 0 ? argv[0] ?? 'os' : 'os-failed'
114
+ }
115
+
116
+ export async function systemKind($: Api): Promise<'darwin' | 'linux' | 'other'> {
117
+ if (osKind !== undefined) return osKind
118
+ const ran = await $.process.run(['uname', '-s'], { timeoutMs: 3000 }).catch(() => undefined)
119
+ const name = ran?.exitCode === 0 ? ran.stdout.trim() : ''
120
+ osKind = name === 'Darwin' ? 'darwin' : name === 'Linux' ? 'linux' : 'other'
121
+ return osKind
122
+ }
123
+
124
+ /** Answers `/<pane command> notify …`; undefined when the args are not about notifications. */
125
+ export async function notifyCommand($: Api, command: string, args: string): Promise<{ text: string } | undefined> {
126
+ const asked = parseNotifyArgs(args)
127
+ if (asked === undefined) return undefined
128
+ if (asked === 'on' || asked === 'off') {
129
+ await update($, notifyOn, () => asked === 'on')
130
+ return { text: asked === 'on' ? 'Notificaciones del sistema activadas.' : 'Notificaciones del sistema desactivadas.' }
131
+ }
132
+ if (asked === 'test') {
133
+ const channel = await sendNotification($, '✓ Prueba de notificación del panel de actividad')
134
+ return { text: `Notificación de prueba enviada (${channel}).` }
135
+ }
136
+ const isOn = await read($, notifyOn)
137
+ return { text: `Notificaciones del sistema: ${isOn ? 'activadas' : 'desactivadas'}. Usa /${command} notify on|off|test.` }
138
+ }
139
+
140
+ export async function notifyTurnComplete($: Api, e: Parameters<Hook<'turn.complete'>>[1], next: Parameters<Hook<'turn.complete'>>[2]): Promise<Awaited<ReturnType<Hook<'turn.complete'>>>> {
141
+ const done = await next(e)
142
+ const line = turnLine(e)
143
+ if (line !== undefined) await notify($, { key: `turn:${e.turnId}`, text: line }).catch(() => undefined)
144
+ return done
145
+ }