dsh-session-matrix 0.0.0-stage → 0.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,1431 @@
1
+ /**
2
+ * DSH Session Matrix — host half.
3
+ *
4
+ * Responsibility: read Session/Context facts through public DSH services and
5
+ * serve them as one normalized JSON contract. The browser half never touches
6
+ * DSH internals; it only consumes this contract.
7
+ *
8
+ * Boundaries (deliberate):
9
+ * - ContextAdapter : `sessionProjections.snapshot()` — never re-parses jsonl
10
+ * - SessionAdapter : `sessionQuery.listSessions()` — never owns sessions
11
+ * - WorkspaceAdapter: `workspaceRegistry` — never duplicates project data
12
+ * - RiskEngine : pure function over the normalized DTO
13
+ * - Store : view preferences only, never conversation content
14
+ *
15
+ * Degradation: when a projection is absent (e.g. dsh-context not installed),
16
+ * the affected fields are reported as unavailable instead of being invented.
17
+ *
18
+ * @module dsh-session-matrix
19
+ */
20
+
21
+ /** Stable Cordis plugin name. */
22
+ export const name = 'dsh-session-matrix'
23
+
24
+ import { decompressFrames, splitUsageEvents, splitUsageText } from './usage-split.js'
25
+
26
+ /**
27
+ * Services required to answer anything at all. Optional capabilities
28
+ * (`sessionProjections`, `workspaceRegistry`) are probed with `ctx.get()`
29
+ * so the plugin still loads when they are missing.
30
+ */
31
+ export const inject = ['webServer', 'sessionQuery', 'sessions', 'connection']
32
+
33
+ /** Always-registered projections: the panel has nothing without these. */
34
+ const BASE_KEYS = ['contextTimeline', 'contextActivity', 'title', 'sessionListMetadata', 'modelSelection']
35
+
36
+ /**
37
+ * session id → `{ mtime, size, peak, off }`, rebuilt from the session logs.
38
+ * Filled by `collect()` (budgeted) and read by `toDto()`, so a host without
39
+ * time-bucketed projections can still price peak hours instead of guessing.
40
+ */
41
+ const LOG_SPLITS = new Map()
42
+
43
+ /**
44
+ * Projections that a trimmed Host profile may not register. They are requested
45
+ * in the same snapshot for speed, and dropped on retry so one missing key does
46
+ * not cost the panel every number it has.
47
+ */
48
+ const OPTIONAL_KEYS = ['contextPressure', 'contextBreakdown', 'tokenUsage', 'sessionStats']
49
+
50
+ /** Category breakdown read from `contextTimeline.current`. */
51
+ const PART_KEYS = ['system', 'tools', 'user', 'inject', 'skill', 'assistant', 'tool']
52
+
53
+ /** Every part except the fixed system prompt and tool definitions. */
54
+ const MESSAGE_KEYS = ['user', 'inject', 'skill', 'assistant', 'tool']
55
+
56
+ /** Number guard: anything that is not a finite number is "unknown". */
57
+ const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : null)
58
+ /** Number guard for samples that must be present to mean anything (0 = absent). */
59
+ const positive = v => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : null)
60
+
61
+ /**
62
+ * Bundled handoff prompts: one markdown file per protocol version.
63
+ *
64
+ * Kept out of the browser half on purpose. Changing the wording of a handoff
65
+ * protocol is a content edit, not a code change, and the panel must never ship
66
+ * a stale copy because the browser bundle was cached.
67
+ */
68
+ const HANDOFF_VERSIONS = { v1: './handoff/v1.md' }
69
+ const HANDOFF_DEFAULT = 'v1'
70
+ /** Tokens the panel fills in before the text reaches the clipboard. */
71
+ const HANDOFF_PLACEHOLDERS = ['SESSION_TITLE', 'HANDOFF_ID', 'DATE']
72
+
73
+ /**
74
+ * Billing constants, chosen to match dsh-context exactly so the two panels never
75
+ * disagree about the same session:
76
+ * - models.dev lists DeepSeek's **off-peak** price; peak windows cost twice.
77
+ * - CNY is derived at `1 CNY = 0.15 USD`.
78
+ */
79
+ const PEAK_FACTOR = 2
80
+ const CNY_PER_USD = 1 / 0.15
81
+
82
+ /**
83
+ * DeepSeek's official price list, CNY per 1M tokens, **off-peak**.
84
+ *
85
+ * Source: platform.deepseek.com pricing page, checked 2026-11-17. Peak hours
86
+ * (Beijing time, Mon–Fri 09:00–12:00 and 14:00–18:00, holidays excluded) bill at
87
+ * exactly twice these numbers, which `PEAK_FACTOR` applies per bucket.
88
+ *
89
+ * `deepseek-flash` is the current id and serves V4.1-Flash; `deepseek-v4-flash`
90
+ * is the **old name of the same model** (still accepted, routed to V4.1), so it
91
+ * shares the price. `deepseek-v4-pro` bills separately and is not routed.
92
+ */
93
+ const DEEPSEEK_CNY = {
94
+ 'deepseek-flash': { hit: 0.02, miss: 1, out: 4 },
95
+ 'deepseek-v4-flash': { hit: 0.02, miss: 1, out: 4 },
96
+ 'deepseek-v4.1-flash': { hit: 0.02, miss: 1, out: 4 },
97
+ 'deepseek-v4-pro': { hit: 0.15, miss: 4.5, out: 13.5 },
98
+ 'deepseek-chat': { hit: 0.02, miss: 1, out: 4 },
99
+ 'deepseek-reasoner': { hit: 0.02, miss: 1, out: 4 },
100
+ }
101
+
102
+ /**
103
+ * Official CNY price for a DeepSeek model, or null for third-party routes.
104
+ * @param provider - routing id from the timeline.
105
+ * @param model - model id.
106
+ * @returns `{ hit, miss, out }` or null.
107
+ */
108
+ function deepseekCny(provider, model) {
109
+ if (!String(provider ?? '').includes('deepseek')) return null
110
+ return DEEPSEEK_CNY[String(model ?? '')] ?? null
111
+ }
112
+
113
+ /** `tokenUsage` is read in the same snapshot when the Host registers it. */
114
+ const USAGE_KEY = 'tokenUsage'
115
+
116
+ /**
117
+ * Auto-compaction boundaries, taken from `dsh-compaction-basic` itself:
118
+ *
119
+ * messageBudget = contextWindow − reservedCompletionTokens
120
+ * pressureBudget = messageBudget − policy.headroomTokens
121
+ *
122
+ * `headroomTokens` defaults to 4096 in the shipped policy, and
123
+ * `reservedCompletionTokens` is the output reserved by one routed request —
124
+ * the model's max output. An earlier version of this file used a 64K headroom
125
+ * plus a 0.8× ceiling, which warned earlier than DSH actually compacts; that
126
+ * was a guess, not a mirror.
127
+ */
128
+ const COMPACT_HEADROOM = 4_096
129
+ /** Share of (window − output) kept verbatim after compaction (retainRatio). */
130
+ const COMPACT_RETAIN = 0.16
131
+
132
+ /** Defaults; the row config may override them later. */
133
+ const DEFAULTS = {
134
+ cacheTtlMs: 45_000,
135
+ coldConcurrency: 4,
136
+ coldBudgetMs: 20_000,
137
+ /**
138
+ * Warning thresholds as a fraction of the **real** compaction point, not of
139
+ * the window. A flat 70% would only warn after a 1M-window session with a
140
+ * 393k output reservation had already compacted at 56%.
141
+ */
142
+ warnFactor: 0.8,
143
+ criticalFactor: 0.92,
144
+ /** Fetch models.dev list prices for the cost estimate. */
145
+ prices: true,
146
+ /**
147
+ * Multiplier applied when usage has no peak/off-peak split (a host without
148
+ * dsh-context). 1 = price everything at the off-peak rate, 1.5 = assume half
149
+ * the usage happened in peak hours, 2 = all peak. Only affects the estimate.
150
+ */
151
+ peakFactor: 1,
152
+ /**
153
+ * Rebuild the peak/off split from session logs when the host exposes no
154
+ * time-bucketed usage. Off = price everything at the off-peak rate.
155
+ */
156
+ peakFromLogs: true,
157
+ /** Log files parsed per collect, smallest first. */
158
+ logBudget: 6,
159
+ /** Bytes of log parsed per collect; keeps one poll from stalling on a big file. */
160
+ logBudgetBytes: 8 * 1024 * 1024,
161
+ priceTtlMs: 24 * 60 * 60 * 1000,
162
+ }
163
+
164
+ /**
165
+ * Where this session's history would actually be compressed.
166
+ *
167
+ * `dsh-compaction-basic` triggers at `floor(min(window × 0.8,
168
+ * window − output − headroom))`; for a 1M window with a 393k output
169
+ * reservation that is 56%, not 80%. Thresholds derived from the window alone
170
+ * would therefore arrive after the fact.
171
+ * @param window - context window in tokens.
172
+ * @param output - max output reservation in tokens.
173
+ * @returns `{ tokens, ratio, retain }` or null when the window is unknown.
174
+ */
175
+ function compactPointOf(window, output) {
176
+ if (!(window > 0)) return null
177
+ const byBudget = window - (output ?? 0) - COMPACT_HEADROOM
178
+ // A window smaller than the output reservation would yield a negative point;
179
+ // treat it as "unknown" rather than reporting a nonsense percentage.
180
+ if (!(byBudget > 0)) return null
181
+ const tokens = Math.floor(byBudget)
182
+ if (!(tokens > 0)) return null
183
+ return {
184
+ tokens,
185
+ ratio: tokens / window,
186
+ // How much history survives verbatim after a compaction run. The client
187
+ // renders this number, so it is computed here rather than duplicated there.
188
+ retain: Math.round(Math.max(0, window - (output ?? 0)) * COMPACT_RETAIN),
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Classify one ratio into the three capacity levels.
194
+ * @param ratio - used / capacity, or null when capacity is unknown.
195
+ * @param point - this session's compaction point (or null).
196
+ * @param cfg - thresholds as fractions of `point`.
197
+ * @returns risk level.
198
+ */
199
+ function riskLevel(ratio, point, cfg) {
200
+ if (ratio == null) return 'unknown'
201
+ if (!point) {
202
+ if (ratio >= 0.85) return 'crit'
203
+ if (ratio >= 0.7) return 'warn'
204
+ return 'ok'
205
+ }
206
+ if (ratio >= point.ratio * cfg.criticalFactor) return 'crit'
207
+ if (ratio >= point.ratio * cfg.warnFactor) return 'warn'
208
+ return 'ok'
209
+ }
210
+
211
+ /**
212
+ * Optimal-string-alignment distance, enough for "is this folder name a typo of
213
+ * that workspace name" (a transposition counts as one edit).
214
+ * @param a - lowercase token.
215
+ * @param b - lowercase token.
216
+ * @returns edit distance.
217
+ */
218
+ function editDistance(a, b) {
219
+ const m = a.length
220
+ const n = b.length
221
+ const d = Array.from({ length: m + 1 }, (_, i) => {
222
+ const row = new Array(n + 1).fill(0)
223
+ row[0] = i
224
+ return row
225
+ })
226
+ for (let j = 0; j <= n; j += 1) d[0][j] = j
227
+ for (let i = 1; i <= m; i += 1) {
228
+ for (let j = 1; j <= n; j += 1) {
229
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1
230
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
231
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
232
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1)
233
+ }
234
+ }
235
+ }
236
+ return d[m][n]
237
+ }
238
+
239
+ /** Normalize a filesystem path for comparison: forward slashes, no trailing
240
+ * separator, lowercase (Windows workspaces are case-insensitive). */
241
+ const normPath = value => String(value ?? '').replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
242
+
243
+ /**
244
+ * Token accounting for one session, from the provider's own counters.
245
+ *
246
+ * Preferred source is the core `tokenUsage` projection; when a Host does not
247
+ * register it, the same four buckets are recoverable from
248
+ * `contextActivity.days[*].cost`, which dsh-context fills from the same usage
249
+ * events. Nothing is inferred from message counts.
250
+ * @param values - projection values for one session.
251
+ * @returns `{uncached, cacheRead, cacheWrite, output}` or null.
252
+ */
253
+ function usageOf(values) {
254
+ // The projection value arrives wrapped as `{ ver, seq, val }`; older hosts
255
+ // hand over the bare object. Unwrap once, then read `totals`.
256
+ const raw = values?.[USAGE_KEY]
257
+ const unwrapped = raw && typeof raw === 'object' && 'val' in raw ? raw.val : raw
258
+ const flat = unwrapped?.totals ?? unwrapped
259
+ const num = v => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0)
260
+ if (flat && (typeof flat.cacheReadTokens === 'number' || typeof flat.uncachedInputTokens === 'number')) {
261
+ const usage = {
262
+ uncached: num(flat.uncachedInputTokens),
263
+ cacheRead: num(flat.cacheReadTokens),
264
+ cacheWrite: num(flat.cacheWriteTokens),
265
+ output: num(flat.outputTokens),
266
+ }
267
+ return usage.uncached + usage.cacheRead + usage.cacheWrite + usage.output > 0 ? usage : null
268
+ }
269
+
270
+ const usage = { uncached: 0, cacheRead: 0, cacheWrite: 0, output: 0 }
271
+ for (const day of Object.values(values?.contextActivity?.days ?? {})) {
272
+ for (const provider of Object.values(day?.cost ?? {})) {
273
+ for (const model of Object.values(provider ?? {})) {
274
+ for (const bucket of Object.values(model ?? {})) {
275
+ usage.uncached += num(bucket?.uncached)
276
+ usage.cacheRead += num(bucket?.cacheRead)
277
+ usage.cacheWrite += num(bucket?.cacheWrite)
278
+ usage.output += num(bucket?.output)
279
+ }
280
+ }
281
+ }
282
+ }
283
+ return usage.uncached + usage.cacheRead + usage.cacheWrite + usage.output > 0 ? usage : null
284
+ }
285
+
286
+ /** Provider ids the DSH model catalogue uses, mapped onto models.dev ids. */
287
+ const PROVIDER_ALIAS = {
288
+ 'deepseek-official': 'deepseek',
289
+ 'deepseek-api': 'deepseek',
290
+ 'deepseek-platform': 'deepseek',
291
+ 'deepseek-account': 'deepseek',
292
+ }
293
+
294
+ /**
295
+ * Normalize a provider id for price lookup.
296
+ * @param provider - provider id from the session timeline.
297
+ * @returns lowercase catalogue key.
298
+ */
299
+ function normalizeProvider(provider) {
300
+ const value = String(provider ?? '').toLowerCase()
301
+ return PROVIDER_ALIAS[value] ?? value.replace(/-(official|api|platform|account|cloud)$/, '')
302
+ }
303
+
304
+ /**
305
+ * Price book over models.dev's public catalogue.
306
+ *
307
+ * models.dev is the same source dsh-context prices against, and it is the only
308
+ * public machine-readable list of per-model token prices. The request is
309
+ * optional (config `prices: false` disables it), made at most once a day, and
310
+ * cached under `storages/agent-workspace/` when the Host exposes a home path.
311
+ * The directory keeps its pre-rename name on purpose: renaming it would orphan
312
+ * the price table every existing install already has on disk.
313
+ * @param ctx - Cordis context (for `dshHomePath`).
314
+ * @param cfg - plugin config.
315
+ * @param logger - host logger.
316
+ * @returns `{ ready, ensure, lookup, info }`.
317
+ */
318
+ function createPriceBook(ctx, cfg, logger) {
319
+ const state = { book: null, at: 0, failed: false, inflight: null, source: 'models.dev' }
320
+
321
+ /** @returns directory of the plugin's own storage, or null. */
322
+ function storageDir() {
323
+ try {
324
+ const home = ctx.get?.('dshHomePath') ?? ctx.dshHomePath
325
+ if (typeof home !== 'function') return null
326
+ return home('storages', 'agent-workspace')
327
+ } catch {
328
+ return null
329
+ }
330
+ }
331
+
332
+ /**
333
+ * @param raw - parsed models.dev payload.
334
+ * @returns lookup tables.
335
+ */
336
+ function index(raw) {
337
+ const byProvider = new Map()
338
+ const byModel = new Map()
339
+ for (const [pid, prov] of Object.entries(raw ?? {})) {
340
+ const models = prov?.models
341
+ if (!models || typeof models !== 'object') continue
342
+ const table = new Map()
343
+ for (const [mid, model] of Object.entries(models)) {
344
+ const cost = model?.cost
345
+ if (!cost || typeof cost.input !== 'number') continue
346
+ const price = {
347
+ input: cost.input,
348
+ output: typeof cost.output === 'number' ? cost.output : cost.input,
349
+ cacheRead: typeof cost.cache_read === 'number' ? cost.cache_read : cost.input,
350
+ cacheWrite: typeof cost.cache_write === 'number' ? cost.cache_write : cost.input,
351
+ }
352
+ table.set(mid, price)
353
+ const seen = byModel.get(mid) ?? []
354
+ seen.push({ provider: pid, price })
355
+ byModel.set(mid, seen)
356
+ }
357
+ if (table.size) byProvider.set(pid, table)
358
+ }
359
+ return { byProvider, byModel }
360
+ }
361
+
362
+ async function load() {
363
+ const dir = storageDir()
364
+ let raw = null
365
+ if (dir) {
366
+ try {
367
+ const fs = await import('node:fs/promises')
368
+ const path = `${dir}/prices.json`
369
+ const stat = await fs.stat(path)
370
+ if (Date.now() - stat.mtimeMs < cfg.priceTtlMs) {
371
+ raw = JSON.parse(await fs.readFile(path, 'utf8'))
372
+ }
373
+ } catch { /* no cache yet */ }
374
+ }
375
+ if (!raw) {
376
+ const res = await fetch('https://models.dev/api.json', {
377
+ headers: { accept: 'application/json' },
378
+ signal: AbortSignal.timeout(8000),
379
+ })
380
+ if (!res.ok) throw new Error(`models.dev ${res.status}`)
381
+ raw = await res.json()
382
+ if (dir) {
383
+ try {
384
+ const fs = await import('node:fs/promises')
385
+ await fs.mkdir(dir, { recursive: true })
386
+ await fs.writeFile(`${dir}/prices.json`, JSON.stringify(raw))
387
+ } catch { /* cache is a bonus, not a requirement */ }
388
+ }
389
+ }
390
+ state.book = index(raw)
391
+ state.at = Date.now()
392
+ state.failed = false
393
+ }
394
+
395
+ /** Kick off a load if the book is stale. Never throws, never blocks. */
396
+ function ensure() {
397
+ if (!cfg.prices || state.inflight) return
398
+ if (state.book && Date.now() - state.at < cfg.priceTtlMs) return
399
+ if (!state.book && state.failed && Date.now() - state.at < 60_000) return
400
+ state.inflight = load()
401
+ .catch(error => {
402
+ state.failed = true
403
+ state.at = Date.now()
404
+ logger.debug?.(`dsh-session-matrix: price book unavailable: ${error?.message ?? error}`)
405
+ })
406
+ .finally(() => { state.inflight = null })
407
+ }
408
+
409
+ /**
410
+ * @param provider - session provider id.
411
+ * @param model - session model id.
412
+ * @returns `{input, output, cacheRead, cacheWrite}` per 1M tokens, or null.
413
+ */
414
+ function lookup(provider, model) {
415
+ const book = state.book
416
+ if (!book || !model) return null
417
+ const prov = normalizeProvider(provider)
418
+ const direct = book.byProvider.get(prov)?.get(model)
419
+ if (direct) return direct
420
+ for (const [pid, table] of book.byProvider) {
421
+ if (!(pid.includes(prov) || prov.includes(pid))) continue
422
+ const hit = table.get(model)
423
+ if (hit) return hit
424
+ }
425
+ const list = book.byModel.get(model)
426
+ return list && list.length === 1 ? list[0].price : null
427
+ }
428
+
429
+ function info() {
430
+ return {
431
+ ready: Boolean(state.book),
432
+ enabled: Boolean(cfg.prices),
433
+ failed: state.failed,
434
+ source: state.source,
435
+ providers: state.book?.byProvider.size ?? 0,
436
+ fetchedAt: state.at || null,
437
+ }
438
+ }
439
+
440
+ return { ensure, lookup, info }
441
+ }
442
+
443
+ /**
444
+ * Estimate what the usage would cost at list price.
445
+ * @param usage - `{uncached, cacheRead, cacheWrite, output}`.
446
+ * @param price - per-million-token prices.
447
+ * @returns USD amount, or null.
448
+ */
449
+ function costOf(usage, price) {
450
+ if (!usage || !price) return null
451
+ return (usage.uncached * price.input
452
+ + usage.cacheRead * price.cacheRead
453
+ + usage.cacheWrite * price.cacheWrite
454
+ + usage.output * price.output) / 1_000_000
455
+ }
456
+
457
+ /**
458
+ * Cost from the timeline's peak / off-peak buckets.
459
+ *
460
+ * `contextTimeline.cost` keeps usage split by provider, model and billing
461
+ * window. DeepSeek bills its peak windows (Beijing time, Mon–Fri 09:00–12:00
462
+ * and 14:00–18:00) at twice the listed rate — models.dev publishes the off-peak
463
+ * rate — so the two buckets cannot be priced identically.
464
+ *
465
+ * The result is also converted to CNY with the same `1 CNY = 0.15 USD` the
466
+ * dsh-context plugin uses, so both panels show the same number for the same
467
+ * session instead of disagreeing by a rounding convention.
468
+ * @param timeline - `contextTimeline` wire value.
469
+ * @param lookup - `(provider, model) => price | null`.
470
+ * @returns `{ usd, cny, buckets, peakBuckets }` or null when nothing is priced.
471
+ */
472
+ export function costOfBuckets(timeline, lookup, cnyLookup = () => null) {
473
+ const cost = timeline?.cost
474
+ if (!cost || typeof cost !== 'object') return null
475
+ let cny = 0
476
+ let buckets = 0
477
+ let peakBuckets = 0
478
+ let official = 0
479
+ for (const [provider, models] of Object.entries(cost)) {
480
+ for (const [model, byKind] of Object.entries(models ?? {})) {
481
+ // DeepSeek's own price list is quoted in CNY and is authoritative for its
482
+ // models; models.dev only covers third-party routes, and converting it at
483
+ // a fixed rate is off by ~2% on v4-pro. Prefer the official table.
484
+ const local = cnyLookup(provider, model)
485
+ const remote = local ? null : lookup(provider, model)
486
+ if (!local && !remote) continue
487
+ if (local) official += 1
488
+ for (const [kind, used] of Object.entries(byKind ?? {})) {
489
+ if (!used) continue
490
+ buckets += 1
491
+ if (kind === 'peak') peakBuckets += 1
492
+ const factor = kind === 'peak' ? PEAK_FACTOR : 1
493
+ if (local) {
494
+ cny += factor * (used.uncached * local.miss
495
+ + used.cacheRead * local.hit
496
+ + used.cacheWrite * local.hit
497
+ + used.output * local.out) / 1_000_000
498
+ } else {
499
+ cny += factor * costOf(used, remote) * CNY_PER_USD
500
+ }
501
+ }
502
+ }
503
+ }
504
+ if (!buckets) return null
505
+ return { cny, usd: cny / CNY_PER_USD, buckets, peakBuckets, officialModels: official }
506
+ }
507
+
508
+ /**
509
+ * Build the plugin.
510
+ * @param ctx - Cordis context.
511
+ * @param config - row config (all fields optional).
512
+ */
513
+ export function apply(ctx, config = {}) {
514
+ const cfg = { ...DEFAULTS, ...config }
515
+ const logger = ctx.logger ?? console
516
+ /** List prices for the cost estimate; optional and never blocking. */
517
+ const priceBook = createPriceBook(ctx, cfg, logger)
518
+
519
+ /** id → { at, dto } */
520
+ const cache = new Map()
521
+
522
+ // sessionPersistence is optional: get() throws for a service that is not in
523
+ // the inject list, and an older host may not mount it at all. Reads prefer it
524
+ // and fall back to the file scanner.
525
+ let persistence = null
526
+ try {
527
+ persistence = ctx.get?.('sessionPersistence') ?? ctx.sessionPersistence ?? null
528
+ } catch {
529
+ persistence = null
530
+ }
531
+
532
+ /** `${id}|${revision}` → in-flight read, so two collects never open two handles. */
533
+ const inflightSplits = new Map()
534
+
535
+ /** Session-log index and its timestamp; see indexSessionLogs(). */
536
+ let logIndex = null
537
+ let logIndexAt = 0
538
+
539
+ let inflight = null
540
+ let lastCollectedAt = 0
541
+ let dirty = true
542
+
543
+ const projections = () => ctx.get?.('sessionProjections') ?? ctx.sessionProjections
544
+ const registry = () => ctx.get?.('workspaceRegistry') ?? ctx.workspaceRegistry
545
+ const titles = () => ctx.get?.('sessionTitle') ?? ctx.sessionTitle
546
+
547
+ /**
548
+ * Read the authoritative title for a session that is currently live.
549
+ *
550
+ * The `title` projection value is a **plain string** (`string | null`), not
551
+ * an object — reading `.title` off it silently yields `undefined` and used to
552
+ * turn every row into the "Untitled session" fallback. The `sessionTitle`
553
+ * service is the same fold, exposed without the projection envelope, so it is
554
+ * preferred for live sessions and costs one in-memory lookup.
555
+ * @param rec - session record.
556
+ * @returns title text, or undefined when the session is cold / untitled.
557
+ */
558
+ function liveTitle(rec) {
559
+ if (rec.live !== true) return undefined
560
+ const id = rec.header?.id
561
+ const sessions = ctx.get?.('sessions') ?? ctx.sessions
562
+ if (!id || typeof sessions?.get !== 'function') return undefined
563
+ try {
564
+ const session = sessions.get(id)
565
+ if (!session) return undefined
566
+ const text = titles()?.get?.(session)?.title
567
+ return typeof text === 'string' && text.trim() ? text.trim() : undefined
568
+ } catch {
569
+ return undefined
570
+ }
571
+ }
572
+
573
+ /**
574
+ * Read projections for one session. Uses the public `inspectSession` read
575
+ * face so cold (not-yet-live) sessions work too.
576
+ * @param id - session id.
577
+ * @returns projection snapshot values, or null.
578
+ */
579
+ async function readProjections(id) {
580
+ const sp = projections()
581
+ if (!sp || typeof sp.snapshot !== 'function') return null
582
+ const read = keys => ctx.sessionQuery.inspectSession(id, session => sp.snapshot(session, keys))
583
+ try {
584
+ const snap = await read([...BASE_KEYS, ...OPTIONAL_KEYS])
585
+ return snap?.values ?? null
586
+ } catch {
587
+ // One unregistered key makes the whole snapshot throw. Retry with the
588
+ // optional ones dropped rather than losing every context number.
589
+ for (const keys of [[...BASE_KEYS, 'tokenUsage'], BASE_KEYS]) {
590
+ try {
591
+ const snap = await read(keys)
592
+ return snap?.values ?? null
593
+ } catch { /* try the next, narrower key set */ }
594
+ }
595
+ logger.debug?.(`dsh-session-matrix: projection read failed for ${id}`)
596
+ return null
597
+ }
598
+ }
599
+
600
+ /**
601
+ * The prompt size the panel speaks in.
602
+ *
603
+ * `contextTimeline` counts tokens by estimating every event, and that estimate
604
+ * runs ~1.4× low on Chinese-heavy logs. The provider reports the real prompt
605
+ * on every request, and `contextPressure` keeps it, so the same precedence
606
+ * dsh-context uses applies here:
607
+ *
608
+ * 1. `projectedTokens` — what the *next* request would cost
609
+ * 2. `pressureTokens` — what the last request actually cost
610
+ * 3. last request `prompt` + the heuristic delta since that sample
611
+ * 4. the heuristic total (no provider sample yet)
612
+ * @param timeline - `contextTimeline` wire value.
613
+ * @param pressure - `contextPressure` wire value.
614
+ * @returns `{ tokens, source }`; tokens is null when nothing is known.
615
+ */
616
+ function pressureOf(timeline, pressure) {
617
+ const projected = positive(pressure?.projectedTokens)
618
+ if (projected != null) return { tokens: projected, source: 'projected' }
619
+ const sampled = positive(pressure?.pressureTokens)
620
+ if (sampled != null) return { tokens: sampled, source: 'pressure' }
621
+ const last = timeline?.last
622
+ const total = num(timeline?.current?.total)
623
+ if (last && num(last.prompt) != null && num(last.total) != null && total != null) {
624
+ return { tokens: last.prompt + (total - last.total), source: 'prompt+delta' }
625
+ }
626
+ if (total != null) return { tokens: total, source: 'estimate' }
627
+ return { tokens: null, source: null }
628
+ }
629
+
630
+ /**
631
+ * Category breakdown, calibrated to the measured prompt size.
632
+ *
633
+ * The split between categories can only come from the event estimates, but the
634
+ * *sum* must match the number shown everywhere else — otherwise the panel says
635
+ * "4.8M used" while its own parts add up to 3.2M. So: build the estimate (using
636
+ * `contextBreakdown` for the system / tools / message totals, which are more
637
+ * accurate than the per-event sums), then scale the whole set onto `total`.
638
+ * @param current - `contextTimeline.current`.
639
+ * @param breakdown - `contextBreakdown` wire value.
640
+ * @param total - measured prompt size.
641
+ * @returns part → tokens, or null.
642
+ */
643
+ function partsOf(current, breakdown, total) {
644
+ if (!current) return null
645
+ const messageSum = MESSAGE_KEYS.reduce((n, k) => n + (num(current[k]) ?? 0), 0)
646
+ const messages = num(breakdown?.messageTokens) ?? messageSum
647
+ const parts = {
648
+ system: num(breakdown?.systemTokens) ?? (num(current.system) ?? 0),
649
+ tools: num(breakdown?.toolsTokens) ?? (num(current.tools) ?? 0),
650
+ }
651
+ let assigned = 0
652
+ for (const k of MESSAGE_KEYS) {
653
+ const value = messageSum > 0 ? Math.round(messages * ((num(current[k]) ?? 0) / messageSum)) : 0
654
+ parts[k] = value
655
+ assigned += value
656
+ }
657
+ if (messageSum > 0 && assigned !== messages) {
658
+ const biggest = MESSAGE_KEYS.reduce((a, b) => (parts[b] > parts[a] ? b : a), MESSAGE_KEYS[0])
659
+ parts[biggest] = Math.max(0, parts[biggest] + (messages - assigned))
660
+ }
661
+ const sum = PART_KEYS.reduce((n, k) => n + (parts[k] ?? 0), 0)
662
+ const measured = positive(total)
663
+ if (measured != null && sum > 0 && measured !== sum) {
664
+ const scale = measured / sum
665
+ for (const k of PART_KEYS) parts[k] = Math.round((parts[k] ?? 0) * scale)
666
+ }
667
+ return parts
668
+ }
669
+
670
+ /**
671
+ * Normalize one session record into the wire DTO.
672
+ * @param rec - `SessionRecord` from `sessionQuery.listSessions()`.
673
+ * @param values - projection values (may be null).
674
+ * @param projectOf - resolver mapping a session id to its project title.
675
+ * @returns normalized row.
676
+ */
677
+ function toDto(rec, values, projectOf, liveTitleText) {
678
+ const header = rec.header ?? {}
679
+ const id = header.id
680
+ const timeline = values?.contextTimeline ?? null
681
+ const current = timeline?.current ?? null
682
+ const pressure = values?.contextPressure ?? null
683
+ const breakdown = values?.contextBreakdown ?? null
684
+
685
+ // Capacity comes from the newest recorded route; the pressure projection is
686
+ // fresher than the timeline's copy when a model switch happened.
687
+ const capacity = positive(pressure?.contextWindow) ?? positive(timeline?.contextWindow) ?? null
688
+ const pressureTokens = pressureOf(timeline, pressure)
689
+ // `total` is the number the panel, the threshold and the tooltip all speak
690
+ // in: the provider-reported prompt size (or the documented fallback chain).
691
+ const total = pressureTokens.tokens ?? current?.total ?? null
692
+ const estimatedTotal = current?.total ?? null
693
+ const ratio = capacity && total != null ? total / capacity : null
694
+ const point = compactPointOf(capacity, timeline?.maxOutputTokens ?? null)
695
+
696
+ const parts = partsOf(current, breakdown, total)
697
+
698
+ // The model picker is a core projection; `contextTimeline` is not (it comes
699
+ // from dsh-context). Resolve once and use it for both the label and pricing,
700
+ // so a host without that plugin still prices what it can.
701
+ const modelName = timeline?.model ?? values?.modelSelection?.lastUsed?.model ?? null
702
+ const providerName = timeline?.provider ?? values?.modelSelection?.lastUsed?.provider ?? null
703
+
704
+ const usage = usageOf(values)
705
+ // Prefer the projection's own peak/off buckets. When the host has none (no
706
+ // dsh-context), use the split reconstructed from the session log; the
707
+ // lifetime totals times `peakFactor` is the last resort.
708
+ const projectionBuckets = costOfBuckets(timeline, priceBook.lookup, deepseekCny)
709
+ const split = projectionBuckets ? null : LOG_SPLITS.get(id)
710
+ const logBuckets = !projectionBuckets && split && (split.peak || split.off)
711
+ ? costOfBuckets(
712
+ { cost: { [providerName ?? 'deepseek']: { [modelName ?? 'unknown']: { peak: split.peak, off: split.off } } } },
713
+ priceBook.lookup,
714
+ deepseekCny,
715
+ )
716
+ : null
717
+ const buckets = projectionBuckets ?? logBuckets
718
+ const fallbackUsd = costOf(usage, priceBook.lookup(providerName, modelName))
719
+ // No time buckets in core projections: the caller decides how much of the
720
+ // usage to treat as peak rather than guessing here.
721
+ const peakFactor = Number.isFinite(cfg.peakFactor) ? Math.min(2, Math.max(1, cfg.peakFactor)) : 1
722
+ const costCny = buckets ? buckets.cny : (fallbackUsd == null ? null : fallbackUsd * CNY_PER_USD * peakFactor)
723
+ // Which path priced this session: the projection's own buckets, the split
724
+ // rebuilt from the log, or lifetime totals × peakFactor.
725
+ const costSource = projectionBuckets ? 'projection' : logBuckets ? 'log' : (fallbackUsd == null ? null : 'totals')
726
+ const costUsd = costCny == null ? null : costCny / CNY_PER_USD
727
+
728
+ // Turns and steps are NOT on the timeline's wire view: `sessionStats` is
729
+ // where the Host keeps them (it is the same fold the conversation footer
730
+ // renders "55 轮 406 步" from). Reading `timeline.turns` produced a wall of
731
+ // "— / —" for every session.
732
+ const stats = values?.sessionStats ?? null
733
+ const turns = num(stats?.turns) ?? num(timeline?.last?.turn) ?? null
734
+ const steps = num(stats?.steps) ?? null
735
+
736
+ const activity = values?.contextActivity?.days ?? null
737
+ const activityDays = {}
738
+ if (activity) {
739
+ for (const [day, v] of Object.entries(activity)) {
740
+ activityDays[day] = { tokens: v?.tokens ?? 0, requests: v?.requests ?? 0 }
741
+ }
742
+ }
743
+
744
+ // The `title` projection folds to `string | null`; older snapshots and
745
+ // `sessionListMetadata` may still carry an object, so accept both shapes.
746
+ const projected = values?.title
747
+ const fromProjection = typeof projected === 'string'
748
+ ? projected
749
+ : (projected?.title ?? values?.sessionListMetadata?.title ?? null)
750
+ const fromPrompt = values?.sessionListMetadata?.lastPrompt
751
+ ? String(values.sessionListMetadata.lastPrompt).slice(0, 64)
752
+ : null
753
+ const blank = values?.sessionListMetadata?.blank === true
754
+ const created = header.createdAt ? new Date(header.createdAt) : null
755
+ const stamp = created && !Number.isNaN(created.getTime())
756
+ ? `${String(created.getMonth() + 1).padStart(2, '0')}-${String(created.getDate()).padStart(2, '0')}`
757
+ : null
758
+ const title =
759
+ (typeof liveTitleText === 'string' && liveTitleText.trim()) ? liveTitleText.trim()
760
+ : (typeof fromProjection === 'string' && fromProjection.trim()) ? fromProjection.trim()
761
+ : (fromPrompt && fromPrompt.trim()) ? fromPrompt.trim()
762
+ : blank ? '新会话'
763
+ : header.origin === 'subagent'
764
+ ? `子代理${stamp ? ' · ' + stamp : ''}`
765
+ : `未命名会话${stamp ? ' · ' + stamp : ''}`
766
+
767
+ return {
768
+ id,
769
+ title,
770
+ project: projectOf(id, header),
771
+ origin: header.origin === 'subagent' ? 'subagent' : 'user',
772
+ parentId: header.parentSession ?? null,
773
+ cwd: header.cwd ?? null,
774
+ createdAt: header.createdAt ?? null,
775
+ live: rec.live === true,
776
+ persisted: rec.persisted === true,
777
+ blank: values?.sessionListMetadata?.blank === true,
778
+ model: modelName,
779
+ provider: providerName,
780
+ contextWindow: capacity,
781
+ maxOutputTokens: timeline?.maxOutputTokens ?? null,
782
+ total,
783
+ ratio,
784
+ /** Where `total` came from: projected | pressure | prompt+delta | estimate. */
785
+ contextSource: pressureTokens.source,
786
+ /** The event-estimate total, kept only to explain the gap in a tooltip. */
787
+ estimatedTotal,
788
+ /** Where this session compacts; the panel colours against this, not 100%. */
789
+ compactRatio: point?.ratio ?? null,
790
+ compactTokens: point?.tokens ?? null,
791
+ compactRetain: point?.retain ?? null,
792
+ parts,
793
+ turns,
794
+ steps,
795
+ usage,
796
+ costUsd,
797
+ costCny,
798
+ costSource,
799
+ costBuckets: buckets ? buckets.buckets : 0,
800
+ costPeakBuckets: buckets ? buckets.peakBuckets : 0,
801
+ updatedAt: values?.sessionListMetadata?.lastPromptAt ?? header.createdAt ?? null,
802
+ activityDays,
803
+ risk: riskLevel(ratio, point, cfg),
804
+ contextAvailable: total != null,
805
+ }
806
+ }
807
+
808
+ /**
809
+ * Resolve project membership for every session: direct workspace membership
810
+ * first, then the parent chain, then a cwd tail, then "Ungrouped".
811
+ * @param records - session records.
812
+ * @returns resolver + project rows.
813
+ */
814
+ function buildProjects(records) {
815
+ const reg = registry()
816
+ const workspaces = typeof reg?.list === 'function' ? (reg.list() ?? []) : []
817
+
818
+ const direct = new Map()
819
+ const projects = []
820
+ for (const w of workspaces) {
821
+ const title = w.title ?? w.path ?? w.id
822
+ projects.push({ id: w.id, title, path: w.path ?? null, count: w.sessionIds?.length ?? 0 })
823
+ for (const sid of w.sessionIds ?? []) direct.set(sid, title)
824
+ }
825
+
826
+ const headerById = new Map()
827
+ for (const rec of records) {
828
+ const h = rec.header ?? {}
829
+ if (h.id) headerById.set(h.id, h)
830
+ }
831
+
832
+ /**
833
+ * @param id - session id.
834
+ * @param header - its header.
835
+ * @returns project title.
836
+ */
837
+ /** Workspaces with a usable path, for cwd-based attribution. */
838
+ const byPath = projects
839
+ .map(w => ({ title: w.title, path: normPath(w.path) }))
840
+ .filter(w => w.path)
841
+
842
+ /**
843
+ * Attribute a cwd to a workspace: contained path first, then a near-name
844
+ * match (a typo'd folder such as `D:////AIVdeio` next to `D:////AIVideo`).
845
+ * Without this, every stray directory invented its own "project" and the
846
+ * chip row no longer matched the workspaces the user actually has.
847
+ * @param cwd - the session's working directory.
848
+ * @returns workspace title, or '' when it belongs to no workspace.
849
+ */
850
+ function projectFromCwd(cwd) {
851
+ const value = normPath(cwd)
852
+ if (!value) return ''
853
+ for (const w of byPath) {
854
+ if (value === w.path || value.startsWith(`${w.path}/`)) return w.title
855
+ }
856
+ const base = value.split('/').pop() ?? ''
857
+ let best = null
858
+ for (const w of byPath) {
859
+ const other = w.path.split('/').pop() ?? ''
860
+ if (!other || Math.abs(other.length - base.length) > 2) continue
861
+ const distance = editDistance(base, other)
862
+ if (distance <= 2 && (best === null || distance < best.distance)) {
863
+ best = { distance, title: w.title }
864
+ }
865
+ }
866
+ return best ? best.title : ''
867
+ }
868
+
869
+ function projectOf(id, header) {
870
+ let cursor = id
871
+ for (let depth = 0; depth < 12 && cursor; depth += 1) {
872
+ if (direct.has(cursor)) return direct.get(cursor)
873
+ const h = headerById.get(cursor)
874
+ cursor = h?.parentSession ?? (cursor === id ? header?.parentSession : undefined)
875
+ }
876
+ return projectFromCwd(header?.cwd)
877
+ }
878
+
879
+ return { projectOf, projects }
880
+ }
881
+
882
+ /**
883
+ * Run `worker` over `items` with a concurrency cap and a wall-clock budget.
884
+ * Items not reached within the budget keep their previous cache entry.
885
+ * @param items - work items.
886
+ * @param worker - async perform.
887
+ * @param limit - max in flight.
888
+ * @param budgetMs - soft deadline.
889
+ */
890
+ async function mapLimited(items, worker, limit, budgetMs) {
891
+ const started = Date.now()
892
+ let index = 0
893
+ const runners = Array.from({ length: Math.min(limit, items.length || 1) }, async () => {
894
+ while (index < items.length) {
895
+ if (Date.now() - started > budgetMs) return
896
+ const current = index
897
+ index += 1
898
+ try {
899
+ await worker(items[current], current)
900
+ } catch (error) {
901
+ // One malformed session must not cost every other session its row:
902
+ // collect() would otherwise serve the last good payload forever.
903
+ logger.debug?.(`dsh-session-matrix: session collect failed: ${error?.message ?? error}`)
904
+ }
905
+ }
906
+ })
907
+ await Promise.all(runners)
908
+ }
909
+
910
+ /**
911
+ * Archived sessions, as the native sidebar sees them.
912
+ *
913
+ * DSH keeps this out of the session records: it lives in the workspace storage
914
+ * table (`storages/workspace.json`) as `archivedSessionIds`. The native list
915
+ * hides those sessions, so this panel must hide them too — otherwise the two
916
+ * lists disagree about what exists.
917
+ *
918
+ * Read defensively: an older or newer host may move the table, so the walk looks
919
+ * for the key at any depth, and a missing file simply means "nothing archived".
920
+ * @returns set of archived session ids.
921
+ */
922
+ async function archivedSessionIds() {
923
+ const home = ctx.get?.('dshHomePath') ?? ctx.dshHomePath
924
+ if (typeof home !== 'function') return new Set()
925
+ try {
926
+ const fs = await import('node:fs/promises')
927
+ const file = home('storages', 'workspace.json')
928
+ const raw = JSON.parse(await fs.readFile(file, 'utf8'))
929
+ const ids = new Set()
930
+ const walk = (node, depth) => {
931
+ if (!node || typeof node !== 'object' || depth > 6) return
932
+ for (const [key, value] of Object.entries(node)) {
933
+ if (key === 'archivedSessionIds' && Array.isArray(value)) {
934
+ for (const id of value) if (typeof id === 'string') ids.add(id)
935
+ continue
936
+ }
937
+ walk(value, depth + 1)
938
+ }
939
+ }
940
+ walk(raw, 0)
941
+ return ids
942
+ } catch {
943
+ return new Set()
944
+ }
945
+ }
946
+
947
+ /**
948
+ * Map every session id to its log file. Rebuilt at most once a minute: the
949
+ * directory layout is `sessions/<workspace>/<sessionId>/session.v4.jsonl.zstd`.
950
+ * @returns Map id → absolute path.
951
+ */
952
+ async function indexSessionLogs() {
953
+ if (logIndex && Date.now() - logIndexAt < 60_000) return logIndex
954
+ const fs = await import('node:fs/promises')
955
+ const path = await import('node:path')
956
+ const map = new Map()
957
+ const home = ctx.get?.('dshHomePath') ?? ctx.dshHomePath
958
+ if (typeof home !== 'function') return map
959
+ try {
960
+ const root = home('sessions')
961
+ for (const ws of await fs.readdir(root, { withFileTypes: true })) {
962
+ if (!ws.isDirectory()) continue
963
+ const wsPath = path.join(root, ws.name)
964
+ for (const entry of await fs.readdir(wsPath, { withFileTypes: true })) {
965
+ if (!entry.isDirectory()) continue
966
+ // The directory is the bare uuid; session ids carry a `session-` prefix.
967
+ const file = path.join(wsPath, entry.name, 'session.v4.jsonl.zstd')
968
+ map.set(entry.name, file)
969
+ map.set(entry.name.startsWith('session-') ? entry.name : `session-${entry.name}`, file)
970
+ }
971
+ }
972
+ } catch {
973
+ // No sessions directory (fresh install) is not an error.
974
+ }
975
+ logIndex = map
976
+ logIndexAt = Date.now()
977
+ return map
978
+ }
979
+
980
+ /**
981
+ * Rebuild the peak/off split for sessions whose log changed.
982
+ *
983
+ * Budgeted on purpose: each file costs a few dozen milliseconds, and a cold
984
+ * start must not block the first paint for seconds. Smallest files go first
985
+ * so the common case warms up within one or two polls.
986
+ * @param records - session records about to be collected.
987
+ */
988
+ /**
989
+ * Read one session's split through the official persistence service.
990
+ *
991
+ * `open(id,'read')` returns events that are already parsed, so this path skips
992
+ * zstd entirely, and `stat().revision` is the change token DSH documents for
993
+ * caching (equal revisions may be treated as unchanged). Returns null when the
994
+ * service is absent, the session is not materialized, or the read fails — the
995
+ * caller then falls back to the file scanner.
996
+ * @param id - session id.
997
+ * @returns cached or freshly computed entry, or null.
998
+ */
999
+ /**
1000
+ * Read one session's split through the official persistence service.
1001
+ *
1002
+ * `open(id,'read')` returns events that are already parsed, so this path needs
1003
+ * neither zstd nor the log-file index. `stat().revision` is the documented
1004
+ * change token: an equal revision is a cache hit, a different revision is a
1005
+ * real change and must be re-read — the 256 KB / 60 s throttle that used to
1006
+ * sit here belonged to the file path and contradicted the token's meaning.
1007
+ * Cost control lives in the caller (per-collect budget) and in `inflight`,
1008
+ * which collapses concurrent reads of the same revision into one handle.
1009
+ * @param id - session id.
1010
+ * @returns `{ entry, read }`, or null when persistence cannot answer.
1011
+ */
1012
+ async function splitFromPersistence(id) {
1013
+ if (!persistence?.stat || !persistence?.open) return null
1014
+ let snapshot
1015
+ try {
1016
+ snapshot = await persistence.stat(id)
1017
+ } catch {
1018
+ return null
1019
+ }
1020
+ if (!snapshot) return null
1021
+ const revision = String(snapshot.revision ?? '')
1022
+ const size = Number(snapshot.sizeBytes) || 0
1023
+ const hit = LOG_SPLITS.get(id)
1024
+ if (revision && hit?.revision === revision) return { entry: hit, read: false, size }
1025
+
1026
+ const key = `${id}|${revision}`
1027
+ const running = inflightSplits.get(key)
1028
+ if (running) {
1029
+ const entry = await running
1030
+ return entry ? { entry, read: false, size } : null
1031
+ }
1032
+
1033
+ const job = (async () => {
1034
+ const handle = await persistence.open(id, 'read')
1035
+ try {
1036
+ const result = await handle.read()
1037
+ const split = splitUsageEvents(result?.events ?? [])
1038
+ const entry = {
1039
+ revision,
1040
+ size,
1041
+ at: Date.now(),
1042
+ peak: split?.peak ?? null,
1043
+ off: split?.off ?? null,
1044
+ }
1045
+ LOG_SPLITS.set(id, entry)
1046
+ cache.delete(id)
1047
+ return entry
1048
+ } finally {
1049
+ try { await handle.close?.() } catch { /* already closed */ }
1050
+ }
1051
+ })()
1052
+
1053
+ inflightSplits.set(key, job)
1054
+ try {
1055
+ const entry = await job
1056
+ return { entry, read: true, size }
1057
+ } catch {
1058
+ return null
1059
+ } finally {
1060
+ inflightSplits.delete(key)
1061
+ }
1062
+ }
1063
+
1064
+ async function refreshLogSplits(records) {
1065
+ if (!cfg.peakFromLogs) return
1066
+ const maxFiles = Math.max(1, cfg.logBudget)
1067
+ const maxBytes = Math.max(1, cfg.logBudgetBytes)
1068
+ let parsed = 0
1069
+ let bytes = 0
1070
+
1071
+ // Phase 1 — official persistence. This must not require zstd, and it must
1072
+ // not require the log-file index: an installed host can answer entirely
1073
+ // from parsed events. Only a changed revision costs a read.
1074
+ const remaining = []
1075
+ for (const rec of records) {
1076
+ const id = rec.header?.id
1077
+ if (!id) continue
1078
+ if (parsed >= maxFiles || bytes >= maxBytes) { remaining.push(rec); continue }
1079
+ const official = await splitFromPersistence(id)
1080
+ if (!official) { remaining.push(rec); continue }
1081
+ if (official.read) {
1082
+ parsed += 1
1083
+ bytes += official.size ?? 0
1084
+ }
1085
+ }
1086
+ if (!remaining.length) return
1087
+
1088
+ // Phase 2 — file fallback. Only now do zstd and the directory index matter.
1089
+ const zlib = await import('node:zlib')
1090
+ const zstd = zlib.zstdDecompressSync
1091
+ if (typeof zstd !== 'function') return
1092
+ const fs = await import('node:fs/promises')
1093
+ const index = await indexSessionLogs()
1094
+ const todo = []
1095
+ for (const rec of remaining) {
1096
+ const id = rec.header?.id
1097
+ const file = id ? index.get(id) : null
1098
+ if (!file) continue
1099
+ try {
1100
+ const stat = await fs.stat(file)
1101
+ const hit = LOG_SPLITS.get(id)
1102
+ if (hit && hit.mtime === stat.mtimeMs && hit.size === stat.size) continue
1103
+ // The fallback has no revision token, so it keeps the growth throttle:
1104
+ // an active session appends constantly and a 20 MB decompress per poll
1105
+ // would cost a second. The persistence path above does not need this.
1106
+ if (hit && stat.size - hit.size < 256 * 1024 && Date.now() - (hit.at ?? 0) < 60_000) continue
1107
+ todo.push({ id, file, stat })
1108
+ } catch {
1109
+ // A session without a log file simply has no usage to split.
1110
+ }
1111
+ }
1112
+ todo.sort((a, b) => a.stat.size - b.stat.size)
1113
+ for (const item of todo) {
1114
+ if (parsed >= maxFiles || bytes >= maxBytes) break
1115
+ parsed += 1
1116
+ bytes += item.stat.size
1117
+ const stamp = { mtime: item.stat.mtimeMs, size: item.stat.size }
1118
+ try {
1119
+ const buf = await fs.readFile(item.file)
1120
+ const split = splitUsageText(decompressFrames(buf, zstd))
1121
+ LOG_SPLITS.set(item.id, { ...stamp, at: Date.now(), peak: split?.peak ?? null, off: split?.off ?? null })
1122
+ // The DTO cache may hold a totals-priced copy: drop it so the next
1123
+ // collect re-prices with the buckets we just found.
1124
+ cache.delete(item.id)
1125
+ } catch {
1126
+ LOG_SPLITS.set(item.id, { ...stamp, at: Date.now(), peak: null, off: null })
1127
+ cache.delete(item.id)
1128
+ }
1129
+ }
1130
+ }
1131
+
1132
+ /**
1133
+ * Collect the full overview. Live sessions read first; cold sessions fill in
1134
+ * under the concurrency/budget caps and reuse the projection cache.
1135
+ * @returns overview payload.
1136
+ */
1137
+ async function collect() {
1138
+ // Fire-and-forget: the price book may need the network, and an overview
1139
+ // must never wait on it. First call reports `costUsd: null`, the next one
1140
+ // (15s later, from the panel's own poll) has the numbers.
1141
+ priceBook.ensure()
1142
+ let records = (await ctx.sessionQuery.listSessions()) ?? []
1143
+ const { projectOf, projects } = buildProjects(records)
1144
+ // Hide what the native sidebar hides. The set is re-read every collect, so
1145
+ // un-archiving a session brings it back within one refresh.
1146
+ const archived = await archivedSessionIds()
1147
+ const archivedCount = records.filter(rec => archived.has(rec.header?.id)).length
1148
+ if (archivedCount) records = records.filter(rec => !archived.has(rec.header?.id))
1149
+
1150
+ // Price peak hours from the logs when the host has no buckets for them.
1151
+ // Budgeted, so this costs a few dozen ms per collect, not seconds.
1152
+ await refreshLogSplits(records)
1153
+
1154
+ // Live first: their projection cells are already warm, reads are cheap.
1155
+ const ordered = [...records].sort((a, b) => Number(b.live === true) - Number(a.live === true))
1156
+
1157
+ await mapLimited(ordered, async rec => {
1158
+ const id = rec.header?.id
1159
+ if (!id) return
1160
+ const cached = cache.get(id)
1161
+ if (cached && Date.now() - cached.at < cfg.cacheTtlMs) {
1162
+ return
1163
+ }
1164
+ const values = await readProjections(id)
1165
+ const dto = toDto(rec, values, projectOf, liveTitle(rec))
1166
+ cache.set(id, { at: Date.now(), values, dto })
1167
+ }, cfg.coldConcurrency, cfg.coldBudgetMs)
1168
+
1169
+ // Drop cache entries for sessions that no longer exist: this module lives
1170
+ // as long as the window, and deleted sessions would otherwise pin their
1171
+ // DTOs for the whole day.
1172
+ const alive = new Set(records.map(rec => rec.header?.id).filter(Boolean))
1173
+ for (const key of [...cache.keys()]) if (!alive.has(key)) cache.delete(key)
1174
+
1175
+ const sessions = []
1176
+ let pending = 0
1177
+ for (const rec of records) {
1178
+ const id = rec.header?.id
1179
+ if (!id) continue
1180
+ const hit = cache.get(id)
1181
+ if (hit?.dto) sessions.push({ ...hit.dto, project: projectOf(id, rec.header) })
1182
+ else {
1183
+ pending += 1
1184
+ sessions.push({ ...toDto(rec, null, projectOf, liveTitle(rec)), pending: true })
1185
+ }
1186
+ }
1187
+
1188
+ // A session created but never used is a stub, not a conversation: the
1189
+ // native sidebar does not list it either. `blank` comes from the host's own
1190
+ // list metadata, so this matches what the shell counts as a real session.
1191
+ const stubs = sessions.filter(x => x.blank === true && (x.turns ?? 0) === 0)
1192
+ const stubIds = new Set(stubs.map(x => x.id))
1193
+ const listed = stubs.length ? sessions.filter(x => !stubIds.has(x.id)) : sessions
1194
+
1195
+ listed.sort((a, b) => (b.ratio ?? -1) - (a.ratio ?? -1))
1196
+
1197
+ // Project rows must cover every project a session actually resolved to —
1198
+ // including ones derived from cwd or the parent chain rather than the
1199
+ // Workspace registry — otherwise the filter bar silently loses entries.
1200
+ const byTitle = new Map()
1201
+ for (const p of projects) {
1202
+ byTitle.set(p.title, { ...p, count: 0, derived: false })
1203
+ }
1204
+ for (const s of listed) {
1205
+ let row = byTitle.get(s.project)
1206
+ if (!row) {
1207
+ row = { id: null, title: s.project, path: null, count: 0, derived: true }
1208
+ byTitle.set(s.project, row)
1209
+ }
1210
+ row.count += 1
1211
+ }
1212
+ const mergedProjects = [...byTitle.values()]
1213
+ .sort((a, b) => b.count - a.count || String(a.title).localeCompare(String(b.title)))
1214
+
1215
+ const sp = projections()
1216
+ const cap = {
1217
+ contextProjections: Boolean(sp),
1218
+ projectionKeys: typeof sp?.summaryKeys === 'function' ? [...sp.summaryKeys()] : [],
1219
+ workspaceRegistry: typeof registry()?.list === 'function',
1220
+ coldPending: pending,
1221
+ emptyStubs: stubs.length,
1222
+ }
1223
+
1224
+ lastCollectedAt = Date.now()
1225
+ dirty = false
1226
+
1227
+ return {
1228
+ version: 1,
1229
+ generatedAt: lastCollectedAt,
1230
+ thresholds: { warnFactor: cfg.warnFactor, criticalFactor: cfg.criticalFactor },
1231
+ pricing: priceBook.info(),
1232
+ capabilities: cap,
1233
+ projects: mergedProjects,
1234
+ sessions: listed,
1235
+ totals: {
1236
+ all: listed.length,
1237
+ user: listed.filter(s => s.origin === 'user').length,
1238
+ subagent: listed.filter(s => s.origin === 'subagent').length,
1239
+ unknownContext: listed.filter(s => !s.contextAvailable).length,
1240
+ archived: archivedCount,
1241
+ },
1242
+ }
1243
+ }
1244
+
1245
+ /**
1246
+ * Serve one overview request, coalescing concurrent callers onto one collect.
1247
+ * @param force - bypass the TTL.
1248
+ * @returns overview payload.
1249
+ */
1250
+ /** Last good payload, served when a collect throws. */
1251
+ let lastOverview = null
1252
+
1253
+ function overview(force = false) {
1254
+ if (!force && !dirty && lastCollectedAt > 0 && Date.now() - lastCollectedAt < cfg.cacheTtlMs) {
1255
+ return Promise.resolve(lastOverview)
1256
+ }
1257
+ if (inflight) return inflight
1258
+ inflight = collect()
1259
+ .then(payload => {
1260
+ lastOverview = payload
1261
+ return payload
1262
+ })
1263
+ .catch(error => {
1264
+ logger.warn?.(`dsh-session-matrix: collect failed: ${error?.stack ?? error}`)
1265
+ return lastOverview ?? {
1266
+ version: 1,
1267
+ generatedAt: Date.now(),
1268
+ error: String(error?.message ?? error),
1269
+ thresholds: { warnFactor: cfg.warnFactor, criticalFactor: cfg.criticalFactor },
1270
+ pricing: priceBook.info(),
1271
+ capabilities: { contextProjections: false, projectionKeys: [], workspaceRegistry: false },
1272
+ projects: [],
1273
+ sessions: [],
1274
+ totals: { all: 0, user: 0, subagent: 0, unknownContext: 0 },
1275
+ }
1276
+ })
1277
+ .finally(() => { inflight = null })
1278
+ return inflight
1279
+ }
1280
+
1281
+ /**
1282
+ * Answer one JSON resource read.
1283
+ * @param body - JSON-serializable payload.
1284
+ * @param status - HTTP status.
1285
+ * @returns Fetch response.
1286
+ */
1287
+ function json(body, status = 200) {
1288
+ return new Response(JSON.stringify(body), {
1289
+ status,
1290
+ headers: {
1291
+ 'content-type': 'application/json; charset=utf-8',
1292
+ 'cache-control': 'no-store',
1293
+ },
1294
+ })
1295
+ }
1296
+
1297
+ /** Bundled prompts, read once per process. */
1298
+ const handoffCache = new Map()
1299
+
1300
+ /**
1301
+ * Read one bundled handoff prompt and describe it for the panel.
1302
+ * @param version - key of `HANDOFF_VERSIONS`.
1303
+ * @returns `{ version, text, bytes, hash, placeholders, versions }`.
1304
+ */
1305
+ async function handoffPrompt(version) {
1306
+ const cached = handoffCache.get(version)
1307
+ if (cached) return cached
1308
+ const fs = await import('node:fs/promises')
1309
+ const { createHash } = await import('node:crypto')
1310
+ const text = await fs.readFile(new URL(HANDOFF_VERSIONS[version], import.meta.url), 'utf8')
1311
+ const entry = {
1312
+ version,
1313
+ text,
1314
+ bytes: Buffer.byteLength(text, 'utf8'),
1315
+ // Short digest so a bug report can name the exact prompt it ran.
1316
+ hash: createHash('sha256').update(text).digest('hex').slice(0, 12),
1317
+ placeholders: HANDOFF_PLACEHOLDERS,
1318
+ versions: Object.keys(HANDOFF_VERSIONS),
1319
+ }
1320
+ handoffCache.set(version, entry)
1321
+ return entry
1322
+ }
1323
+
1324
+ // ── Routes ────────────────────────────────────────────────────────────────
1325
+ ctx.effect(() => {
1326
+ const disposers = []
1327
+
1328
+ // Exact routes must ride the shared /api channel: Connection runs
1329
+ // admit(request) before dispatching to them (401 without a token, 403 for a
1330
+ // non-owner principal). Registering straight on the web server skips that
1331
+ // step entirely, which is how an unauthenticated GET used to return 200.
1332
+ // Cordis throws on get() for a service that is not in the inject list, so the
1333
+ // probe has to tolerate that rather than assume the service exists.
1334
+ let connection = null
1335
+ try {
1336
+ connection = ctx.get?.('connection') ?? ctx.connection ?? null
1337
+ } catch {
1338
+ connection = null
1339
+ }
1340
+ /**
1341
+ * Mount one authenticated GET route.
1342
+ *
1343
+ * There is deliberately no unauthenticated fallback: a webServer exact route
1344
+ * matches before the /api prefix and therefore skips Connection admission,
1345
+ * which would expose session titles, projects and usage to anything that can
1346
+ * reach the port. If Connection is missing the panel loses its API, and that
1347
+ * is the correct failure mode.
1348
+ */
1349
+ const mountGet = (path, handler) => {
1350
+ if (typeof connection?.fetch?.register !== 'function') {
1351
+ logger.error?.('dsh-session-matrix: connection.fetch unavailable; routes not registered')
1352
+ return () => {}
1353
+ }
1354
+ // The path carries the /api prefix: assertFetchRoute() validates it via
1355
+ // endpointFromPath('/api', path), so a bare /session-matrix/... is rejected.
1356
+ return connection.fetch.register({
1357
+ path,
1358
+ methods: ['GET', 'HEAD'],
1359
+ requestBody: 'buffered',
1360
+ fetch: async request => handler(request),
1361
+ })
1362
+ }
1363
+
1364
+
1365
+ // Overview: the whole workbench contract in one read.
1366
+ disposers.push(mountGet('/api/session-matrix/overview', async request => {
1367
+ const url = new URL(request.url, 'http://localhost')
1368
+ const force = url.searchParams.get('refresh') === '1'
1369
+ return json(await overview(force))
1370
+ }))
1371
+
1372
+ // Reported in capabilities so a bug report can name the exact build, and
1373
+ // so an install can be verified from the outside without opening the UI.
1374
+ let cachedVersion = null
1375
+ const packageVersion = async () => {
1376
+ if (cachedVersion) return cachedVersion
1377
+ try {
1378
+ const fs = await import('node:fs/promises')
1379
+ const pkg = JSON.parse(await fs.readFile(new URL('../package.json', import.meta.url), 'utf8'))
1380
+ cachedVersion = typeof pkg.version === 'string' ? pkg.version : 'unknown'
1381
+ } catch {
1382
+ cachedVersion = 'unknown'
1383
+ }
1384
+ return cachedVersion
1385
+ }
1386
+ // Capability probe: lets the panel decide what to hide before the first
1387
+ // heavy collect finishes.
1388
+ disposers.push(mountGet('/api/session-matrix/capabilities', async () => {
1389
+ const sp = projections()
1390
+ return json({
1391
+ version: 1,
1392
+ contextProjections: Boolean(sp),
1393
+ projectionKeys: typeof sp?.summaryKeys === 'function' ? [...sp.summaryKeys()] : [],
1394
+ workspaceRegistry: typeof registry()?.list === 'function',
1395
+ dshVersion: ctx.get?.('appBoot')?.version ?? null,
1396
+ pluginVersion: await packageVersion(),
1397
+ persistenceReads: (() => { try { return Boolean(ctx.get?.('sessionPersistence')?.stat) } catch { return false } })(),
1398
+ logSplits: LOG_SPLITS.size,
1399
+ logSplitsWithUsage: [...LOG_SPLITS.values()].filter(v => v.peak || v.off).length,
1400
+ })
1401
+ }))
1402
+
1403
+ // Handoff prompt: one bundled markdown file per protocol version. The panel
1404
+ // fetches it at click time, so editing the prompt never requires touching
1405
+ // the browser half — and `hash` lets a bug report name the exact text.
1406
+ disposers.push(mountGet('/api/session-matrix/handoff', async request => {
1407
+ const url = new URL(request.url, 'http://localhost')
1408
+ const version = url.searchParams.get('v') || HANDOFF_DEFAULT
1409
+ if (!Object.hasOwn(HANDOFF_VERSIONS, version)) {
1410
+ return json({ error: 'unknown version', versions: Object.keys(HANDOFF_VERSIONS) }, 404)
1411
+ }
1412
+ try {
1413
+ return json(await handoffPrompt(version))
1414
+ } catch (error) {
1415
+ logger.warn?.(`dsh-session-matrix: handoff prompt unreadable: ${error?.message ?? error}`)
1416
+ return json({ error: 'prompt unavailable' }, 500)
1417
+ }
1418
+ }))
1419
+
1420
+ return () => { for (const dispose of disposers) { try { dispose() } catch { /* ignore */ } } }
1421
+ }, 'dsh-session-matrix: routes')
1422
+
1423
+ // ── Change signal ────────────────────────────────────────────────────────
1424
+ // Any committed session event invalidates the snapshot; the next request
1425
+ // re-collects. No timer, no polling from this side.
1426
+ ctx.on('session/event', () => { dirty = true })
1427
+ ctx.on('session/created', () => { dirty = true })
1428
+ ctx.on('session/disposed', () => { dirty = true })
1429
+
1430
+ logger.info?.('dsh-session-matrix: host ready (/api/session-matrix/*)')
1431
+ }