dshgo-context-panel 0.0.0-stage → 0.1.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.
package/lib/collect.js ADDED
@@ -0,0 +1,503 @@
1
+ // Data adapters for the context panel. Pure logic plus thin reads of the
2
+ // engine services — no view code, no timers, so every branch is unit-testable
3
+ // with a plain fake ctx.
4
+ //
5
+ // Sources, in the order the panel prefers them:
6
+ // 1. `sessionProjections.snapshot(session, ['contextPressure', 'contextBreakdown'])`
7
+ // — the engine's own projection of the prompt the next turn would send.
8
+ // 2. `tokenMeter.contextPressure(session)` — the same pressure, no breakdown.
9
+ // 3. nothing: index.js falls back to the last assistant/message usage and
10
+ // says so in the footnote.
11
+
12
+ import { remember, tail } from './config.js'
13
+
14
+ /** Positive finite number, else 0. */
15
+ const count = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0)
16
+ const known = (v) => Number.isSafeInteger(v) && v >= 0 ? v : null
17
+ // Only draw complete input/output samples. A normalized legacy zero does not
18
+ // establish field presence; explicit reported zero does.
19
+ function usageCounts(raw) {
20
+ const evidence = raw?.reported ?? raw
21
+ const input = known(evidence?.inputTokens ?? evidence?.uncachedInputTokens)
22
+ const output = known(evidence?.outputTokens)
23
+ if (input === null || output === null || (!raw?.reported && (input === 0 || output === 0))) return null
24
+ const cacheRead = evidence?.cacheReadTokens == null ? 0 : known(evidence.cacheReadTokens)
25
+ const cacheWrite = evidence?.cacheWriteTokens == null ? 0 : known(evidence.cacheWriteTokens)
26
+ if (cacheRead === null || cacheWrite === null || !Number.isSafeInteger(input + cacheRead + cacheWrite)) return null
27
+ return { input: input + cacheRead + cacheWrite, output, cacheRead }
28
+ }
29
+
30
+
31
+ /** A service by name, or undefined when the host has not loaded it. */
32
+ function service(ctx, name) {
33
+ try {
34
+ return ctx?.get?.(name) ?? undefined
35
+ } catch {
36
+ return undefined
37
+ }
38
+ }
39
+
40
+ /**
41
+ * One projection out of a snapshot. The projection store answers either a
42
+ * `key -> value` map or a list of entries carrying their own key.
43
+ */
44
+ function pick(snapshot, key) {
45
+ if (snapshot === null || typeof snapshot !== 'object') return undefined
46
+ const direct = snapshot[key]
47
+ if (direct !== undefined) return direct
48
+ const list = Array.isArray(snapshot) ? snapshot : snapshot.projections
49
+ if (!Array.isArray(list)) return undefined
50
+ for (const entry of list) {
51
+ if (entry !== null && typeof entry === 'object' && (entry.key === key || entry.id === key)) {
52
+ return entry.value ?? entry.data ?? entry
53
+ }
54
+ }
55
+ return undefined
56
+ }
57
+
58
+ /** The session object behind a scope, when the host has it loaded. */
59
+ export function sessionOf(ctx, sessionId) {
60
+ if (typeof sessionId !== 'string') return undefined
61
+ const sessions = service(ctx, 'sessions')
62
+ try {
63
+ return sessions?.get?.(sessionId) ?? undefined
64
+ } catch {
65
+ return undefined
66
+ }
67
+ }
68
+
69
+ /**
70
+ * The context pressure of one session.
71
+ * @returns {{ pressureTokens: number, projectedTokens: number | null, contextWindow: number | null,
72
+ * system: number | null, tools: number | null, message: number | null, estimated: boolean } | null}
73
+ */
74
+ export function readPressure(ctx, session) {
75
+ if (session === undefined || session === null) return null
76
+ const projections = service(ctx, 'sessionProjections')
77
+ if (typeof projections?.snapshot === 'function') {
78
+ let snapshot
79
+ try {
80
+ // The projections may be keyed by session; fall back to the id form.
81
+ snapshot = projections.snapshot(session, ['contextPressure', 'contextBreakdown'])
82
+ if (snapshot === undefined || snapshot === null) {
83
+ snapshot = projections.snapshot(session?.id ?? session, ['contextPressure', 'contextBreakdown'])
84
+ }
85
+ } catch {
86
+ snapshot = undefined
87
+ }
88
+ const pressure = pick(snapshot, 'contextPressure')
89
+ if (pressure !== null && typeof pressure === 'object' && Number.isFinite(pressure.pressureTokens) && pressure.pressureTokens >= 0) {
90
+ const breakdown = pick(snapshot, 'contextBreakdown')
91
+ const window = count(pressure.contextWindow)
92
+ return {
93
+ pressureTokens: count(pressure.pressureTokens),
94
+ projectedTokens: Number.isFinite(pressure.projectedTokens) ? pressure.projectedTokens : null,
95
+ contextWindow: window > 0 ? window : null,
96
+ system: breakdown === null || typeof breakdown !== 'object' ? null : known(breakdown.systemTokens),
97
+ tools: breakdown === null || typeof breakdown !== 'object' ? null : known(breakdown.toolsTokens),
98
+ message: breakdown === null || typeof breakdown !== 'object' ? null : known(breakdown.messageTokens),
99
+ estimated: false,
100
+ }
101
+ }
102
+ }
103
+
104
+ const meter = service(ctx, 'tokenMeter')
105
+ if (typeof meter?.contextPressure === 'function') {
106
+ let pressure
107
+ try {
108
+ pressure = meter.contextPressure(session)
109
+ } catch {
110
+ pressure = undefined
111
+ }
112
+ if (pressure !== null && typeof pressure === 'object' && Number.isFinite(pressure.pressureTokens) && pressure.pressureTokens >= 0) {
113
+ const window = count(pressure.contextWindow)
114
+ return {
115
+ pressureTokens: count(pressure.pressureTokens),
116
+ projectedTokens: null,
117
+ contextWindow: window > 0 ? window : null,
118
+ system: null,
119
+ tools: null,
120
+ message: null,
121
+ estimated: true, source: 'meter',
122
+ }
123
+ }
124
+ }
125
+
126
+ return null
127
+ }
128
+
129
+ /** The context window of the model this session would call, or null. */
130
+ export function readWindow(ctx, sessionId) {
131
+ const session = sessionOf(ctx, sessionId)
132
+ let request
133
+ try {
134
+ request = typeof session?.requestContext === 'function' ? session.requestContext() : undefined
135
+ } catch {
136
+ request = undefined
137
+ }
138
+ const window = count(request?.contextWindow)
139
+ return window > 0 ? window : null
140
+ }
141
+
142
+ /** The first non-empty string among the candidates, or null. */
143
+ export function firstText(...candidates) {
144
+ for (const value of candidates) {
145
+ if (typeof value === 'string' && value.trim() !== '') return value
146
+ }
147
+ return null
148
+ }
149
+
150
+ /**
151
+ * What this session would send, and under which model: the name, the context
152
+ * window and the request/output ceiling with an explicit kind. Numeric values are null when the engine does
153
+ * not expose it, so the panel shows an em dash instead of a guess.
154
+ * @returns {{ name: string | null, window: number | null, requestLimit: number | null, requestLimitKind: "output" | "request", provider: string | null }}
155
+ */
156
+ export function requestInfo(session) {
157
+ let request
158
+ try {
159
+ request = typeof session?.requestContext === 'function' ? session.requestContext() : undefined
160
+ } catch {
161
+ request = undefined
162
+ }
163
+ const model = request?.model
164
+ const name = firstText(
165
+ typeof model === 'object' && model !== null ? model.id : undefined,
166
+ typeof model === 'object' && model !== null ? model.name : undefined,
167
+ typeof model === 'string' ? model : undefined,
168
+ request?.modelName,
169
+ request?.modelId,
170
+ session?.header?.model,
171
+ )
172
+ const window = count(request?.contextWindow)
173
+ const outputLimit = count(request?.maxOutputTokens) || count(request?.maxTokens)
174
+ const limit = outputLimit || count(request?.requestTokenLimit)
175
+ return {
176
+ name,
177
+ window: window > 0 ? window : null,
178
+ requestLimit: limit > 0 ? limit : null,
179
+ requestLimitKind: outputLimit > 0 ? 'output' : 'request',
180
+ provider: firstText(request?.provider, request?.providerId),
181
+ }
182
+ }
183
+
184
+ /**
185
+ * The last `n` model calls of a session, oldest first: the prompt the call
186
+ * sent and what it answered with.
187
+ * @returns {Array<{ turn: number | null, input: number, output: number, cacheRead: number }>}
188
+ */
189
+ export function recentTurns(session, n = 12) {
190
+ return tail(usagePoints(session).filter(point => point.committed), n)
191
+
192
+ }
193
+
194
+ /** How many compaction events the panel remembers. */
195
+ export const COMPACTION_HISTORY = 12
196
+
197
+ /** What a compaction looks like from the outside. */
198
+ export const emptyCompaction = () => ({ active: false, turn: null, tokens: 0, at: null, count: 0, error: null, history: [] })
199
+
200
+ /**
201
+ * Follow `compaction/*` on the session event bus. `onState` runs after every
202
+ * change; the returned handle keeps the current state and the unsubscribe.
203
+ */
204
+ export function trackCompaction(ctx, onState, maxSessions = 128) {
205
+ const states = new Map()
206
+ let latestId
207
+ let state = emptyCompaction()
208
+ const notify = () => {
209
+ states.set(latestId, state)
210
+ if (typeof onState === 'function') onState(state, latestId)
211
+ }
212
+ const off = ctx.on('session/event', (session, event) => {
213
+ const type = event?.type
214
+ const id = typeof session === 'string' ? session : session?.id ?? session?.header?.id
215
+ if (!id || !type?.startsWith('compaction/')) return
216
+ latestId = id
217
+ state = remember(states, id, emptyCompaction, maxSessions)
218
+ if (type === 'compaction/start') {
219
+ state = { ...state, active: true, turn: Number.isInteger(event.data?.turn) ? event.data.turn : state.turn, error: null }
220
+ return notify()
221
+ }
222
+ if (type === 'compaction/end') {
223
+ const error = event.data?.error
224
+ state = {
225
+ ...state,
226
+ active: false,
227
+ turn: Number.isInteger(event.data?.turn) ? event.data.turn : state.turn,
228
+ error: error === undefined || error === null ? null : String(error),
229
+ }
230
+ return notify()
231
+ }
232
+ if (type === 'compaction/prune' || type === 'compaction/summary') {
233
+ const at = typeof event.time === 'number' ? event.time : Date.now()
234
+ const release = {
235
+ kind: type === 'compaction/prune' ? 'prune' : 'summary',
236
+ turn: Number.isInteger(event.data?.turn) ? event.data.turn : state.turn,
237
+ tokens: count(event.data?.shadowedTokenCount),
238
+ at,
239
+ }
240
+ state = {
241
+ ...state,
242
+ tokens: release.tokens,
243
+ at,
244
+ count: state.count + 1,
245
+ history: [release, ...state.history].slice(0, COMPACTION_HISTORY),
246
+ }
247
+ return notify()
248
+ }
249
+ return undefined
250
+ })
251
+ return {
252
+ current: (id) => states.get(id) ?? emptyCompaction(),
253
+ dispose: () => {
254
+ states.clear()
255
+ if (typeof off === 'function') off()
256
+ },
257
+ }
258
+ }
259
+
260
+ /** Pressure as a share of the window, 0–1; null when either side is unknown. */
261
+ export function ratio(pressureTokens, contextWindow) {
262
+ if (!Number.isFinite(pressureTokens) || pressureTokens < 0) return null
263
+ if (!Number.isFinite(contextWindow) || contextWindow <= 0) return null
264
+ return pressureTokens / contextWindow
265
+ }
266
+
267
+ /** ok < 0.6 ≤ warn ≤ 0.85 < danger; unknown without a ratio. */
268
+ export function level(r) {
269
+ if (r === null || !Number.isFinite(r)) return 'unknown'
270
+ if (r < 0.6) return 'ok'
271
+ if (r <= 0.85) return 'warn'
272
+ return 'danger'
273
+ }
274
+
275
+ /** The view's tone vocabulary for a level. */
276
+ export const toneOf = (l) => ({ ok: 'good', warn: 'warn', danger: 'bad' })[l] ?? 'muted'
277
+
278
+ /** 980 · 12.4k · 186k · 1.25M */
279
+ export function compact(n) {
280
+ if (!Number.isFinite(n) || n < 0) return '—'
281
+ if (n < 1000) return String(Math.round(n))
282
+ if (n < 1e5) return `${(n / 1e3).toFixed(1).replace(/\.0$/, '')}k`
283
+ if (n < 1e6) return `${Math.round(n / 1e3)}k`
284
+ return `${(n / 1e6).toFixed(2).replace(/\.?0+$/, '')}M`
285
+ }
286
+
287
+ /** 0.634 → "63%"; null → "—". */
288
+ export const percent = (r) => (r === null || !Number.isFinite(r) ? '—' : `${Math.round(r * 100)}%`)
289
+
290
+ /* ────────────────────────── session-wide views ────────────────────────── */
291
+
292
+ /** Every event a session has, or an empty list when the host cannot answer. */
293
+ export function eventsOf(session, limit = Infinity) {
294
+ if (limit <= 0) return []
295
+ let events
296
+ try {
297
+ events = typeof session?.snapshotEvents === 'function' ? session.snapshotEvents() : undefined
298
+ } catch {
299
+ events = undefined
300
+ }
301
+ return Array.isArray(events) ? (Number.isFinite(limit) ? events.slice(-limit) : events).filter((e) => e !== null && typeof e === 'object') : []
302
+ }
303
+
304
+ /** `arguments` of a tool-call block, as an object; a JSON string is parsed. */
305
+ function callArgs(block) {
306
+ const raw = block?.arguments ?? block?.args ?? block?.input
307
+ if (raw !== null && typeof raw === 'object') return raw
308
+ if (typeof raw === 'string' && raw.trim() !== '') {
309
+ try {
310
+ const parsed = JSON.parse(raw)
311
+ return parsed !== null && typeof parsed === 'object' ? parsed : {}
312
+ } catch {
313
+ return {}
314
+ }
315
+ }
316
+ return {}
317
+ }
318
+
319
+ /** Every `{type:'tool-call'}` block in one event, whatever nesting it uses. */
320
+ export function toolCallBlocks(event) {
321
+ const data = event?.data ?? {}
322
+ const lists = [data.content, data.blocks, data.message?.content, data.message?.blocks]
323
+ const blocks = []
324
+ const seen = new Set()
325
+ for (const list of lists) {
326
+ if (!Array.isArray(list)) continue
327
+ for (const block of list) {
328
+ if (block !== null && typeof block === 'object' && block.type === 'tool-call' && typeof block.name === 'string') {
329
+ const key = block.id ?? block.toolCallId ?? block
330
+ if (seen.has(key)) continue
331
+ seen.add(key)
332
+ blocks.push(block)
333
+ }
334
+ }
335
+ }
336
+ return blocks
337
+ }
338
+
339
+ /** A path-ish argument, or null. */
340
+ function pathOf(args) {
341
+ for (const key of ['path', 'file_path', 'filePath', 'file', 'notebook_path', 'target']) {
342
+ const value = args?.[key]
343
+ if (typeof value === 'string' && value.trim() !== '') return value.trim()
344
+ }
345
+ return null
346
+ }
347
+
348
+ /** Newest-first list of `{ name, count, last }` for every tool the session called. */
349
+ export function toolCalls(session) {
350
+ const calls = new Map()
351
+ for (const event of eventsOf(session)) {
352
+ for (const block of toolCallBlocks(event)) {
353
+ const seen = calls.get(block.name) ?? { name: block.name, count: 0, last: 0 }
354
+ seen.count += 1
355
+ seen.last = Math.max(seen.last, Number.isFinite(event.time) ? event.time : 0)
356
+ calls.set(block.name, seen)
357
+ }
358
+ }
359
+ return [...calls.values()]
360
+ }
361
+
362
+ /** `{ path, count, lines, last }` per file touched by a tool call. */
363
+ export function fileActivity(session) {
364
+ const files = new Map()
365
+ for (const event of eventsOf(session)) {
366
+ for (const block of toolCallBlocks(event)) {
367
+ const args = callArgs(block)
368
+ const path = pathOf(args)
369
+ if (path === null) continue
370
+ const entry = files.get(path) ?? { path, count: 0, lines: 0, last: 0 }
371
+ entry.count += 1
372
+ entry.lines += lineCount(args, block)
373
+ entry.last = Math.max(entry.last, Number.isFinite(event.time) ? event.time : 0)
374
+ files.set(path, entry)
375
+ }
376
+ }
377
+ return [...files.values()]
378
+ }
379
+
380
+ /** Lines a call claims to touch: an explicit count, else the content it wrote. */
381
+ function lineCount(args, block) {
382
+ for (const key of ['line_count', 'linesTouched', 'lines']) {
383
+ if (Number.isFinite(args?.[key])) return count(args[key])
384
+ }
385
+ const body = args?.content ?? args?.new_string ?? args?.text ?? block?.result
386
+ return typeof body === 'string' ? body.split('\n').length : 0
387
+ }
388
+
389
+ /** The last `n` events as `{ type, seq, tokens, time }`, newest first. */
390
+ export function eventFeed(session, n = 20) {
391
+ const usage = (event) => {
392
+ const u = event.data?.usage ?? event.data?.chunk?.usage
393
+ if (u === null || typeof u !== 'object') return 0
394
+ return count(u.inputTokens) + count(u.cacheReadTokens) + count(u.cacheWriteTokens) + count(u.outputTokens)
395
+ }
396
+ return eventsOf(session)
397
+ .map((event, index) => ({
398
+ type: typeof event.type === 'string' ? event.type : '—',
399
+ seq: Number.isInteger(event.seq) ? event.seq : index + 1,
400
+ tokens: usage(event) || count(event.data?.shadowedTokenCount),
401
+ time: Number.isFinite(event.time) ? event.time : null,
402
+ }))
403
+ .reverse()
404
+ .slice(0, n)
405
+ }
406
+
407
+ /**
408
+ * One usage sample per committed model call: `{ turn, step, input, output, cacheRead }`.
409
+ * `assistant/chunk` carries per-step samples; `assistant/message` settles the call.
410
+ */
411
+ export function usagePoints(session) {
412
+ const events = eventsOf(session)
413
+ const points = []
414
+ // Chunks are provisional cumulative samples. Terminal events supersede them.
415
+ const sampleKey = (data) => `${data?.turn}:${data?.step ?? 'unknown'}`
416
+ const rawUsage = (data) => data?.usage ?? (Array.isArray(data?.stream) ? data.stream.findLast(row => row.type === 'chunk' && row.chunk?.type === 'usage')?.chunk.usage : undefined)
417
+ const settled = new Set(events.filter(e => ['assistant/message', 'assistant/attempt'].includes(e.type) && Number.isInteger(e.data?.turn) && usageCounts(rawUsage(e.data)) !== null).map(e => sampleKey(e.data)))
418
+ const provisional = new Map()
419
+ const seen = new Set()
420
+ for (const [index, event] of events.entries()) {
421
+ const data = event.data ?? {}
422
+ const terminal = event.type === 'assistant/message' || event.type === 'assistant/attempt'
423
+ const chunk = event.type === 'assistant/chunk' && data.chunk?.type === 'usage'
424
+ if (!terminal && !chunk) continue
425
+ const stream = Array.isArray(data.stream) ? data.stream : []
426
+ const usage = chunk ? data.chunk.usage : data.usage ?? stream.findLast((row) => row.type === 'chunk' && row.chunk?.type === 'usage')?.chunk.usage
427
+ const counts = usageCounts(usage)
428
+ if (counts === null) continue
429
+ const turn = Number.isInteger(data.turn) ? data.turn : null
430
+ const step = Number.isInteger(data.step) ? data.step : null
431
+ if (chunk && turn !== null && settled.has(sampleKey(data))) continue
432
+ const id = Number.isInteger(event.seq) ? `seq:${event.seq}` : `event:${index}`
433
+ if (seen.has(id)) continue
434
+ seen.add(id)
435
+ const point = {
436
+ turn, step, id, order: index, at: Number.isFinite(event.time) ? event.time : null,
437
+ committed: event.type === 'assistant/message' && data.interrupted !== true,
438
+ ...counts,
439
+ }
440
+ if (chunk) provisional.set(turn === null ? id : `${turn}:${step}`, point)
441
+ else points.push(point)
442
+ }
443
+ return [...points, ...provisional.values()].sort((a, b) => a.order - b.order).map(({ order, ...point }) => point)
444
+ }
445
+
446
+ /** Group samples by `turn` or `step`, summing the two buckets. */
447
+ export function foldPoints(points, granularity = 'turn') {
448
+ const key = granularity === 'step' ? 'step' : 'turn'
449
+ const rows = []
450
+ const index = new Map()
451
+ for (const [i, point] of points.entries()) {
452
+ const id = point[key]
453
+ const label = granularity === 'step' ? `${point.turn ?? '—'}.${id ?? '—'}` : String(id ?? '—')
454
+ const group = point.turn == null ? `unknown:${i}` : label
455
+ const at = index.get(group)
456
+ if (at === undefined) {
457
+ index.set(group, rows.length)
458
+ rows.push({ label, input: point.input, output: point.output, cacheRead: point.cacheRead })
459
+ } else {
460
+ rows[at].input += point.input
461
+ rows[at].output += point.output
462
+ rows[at].cacheRead += point.cacheRead
463
+ }
464
+ }
465
+ return rows
466
+ }
467
+
468
+ /** `total` keeps the values, `delta` shows the step-to-step change (never negative). */
469
+ export function seriesOf(rows, mode = 'total') {
470
+ if (mode !== 'delta') return rows.map((row) => row)
471
+ return rows.map((row, i) => {
472
+ const prev = i === 0 ? { input: 0, output: 0, cacheRead: 0 } : rows[i - 1]
473
+ return {
474
+ label: row.label,
475
+ input: Math.max(row.input - prev.input, 0),
476
+ output: Math.max(row.output - prev.output, 0),
477
+ cacheRead: Math.max(row.cacheRead - prev.cacheRead, 0),
478
+ }
479
+ })
480
+ }
481
+
482
+ /** Live sessions as `{ id, short, tokens, fraction, current }`, current first. */
483
+ export function fleet(ctx, currentId) {
484
+ const sessions = service(ctx, 'sessions')
485
+ let list
486
+ try {
487
+ list = typeof sessions?.list === 'function' ? sessions.list() : (sessions?.sessions ?? sessions?.all?.())
488
+ } catch {
489
+ list = undefined
490
+ }
491
+ const items = Array.isArray(list) ? list : list !== null && typeof list === 'object' ? [...(list.values?.() ?? [])] : []
492
+ const rows = []
493
+ for (const item of items) {
494
+ const id = firstText(typeof item === 'string' ? item : (item?.id ?? item?.sessionId))
495
+ if (id === null) continue
496
+ const pressure = readPressure(ctx, sessionOf(ctx, id) ?? item)
497
+ const tokens = pressure === null ? null : pressure.pressureTokens
498
+ const window = pressure === null ? null : pressure.contextWindow
499
+ rows.push({ id, tokens, fraction: window === null ? null : ratio(tokens, window), current: id === currentId })
500
+ }
501
+ return rows.sort((a, b) => Number(b.current) - Number(a.current) || b.tokens - a.tokens)
502
+ }
503
+
package/lib/config.js ADDED
@@ -0,0 +1,40 @@
1
+ // One source of truth for plugin display/storage bounds. Never changes engine history.
2
+ export const DEFAULTS = Object.freeze({
3
+ maxNodes: 2000,
4
+ maxKeptTurns: 12,
5
+ maxRequestSteps: 12,
6
+ maxEvents: 20,
7
+ maxFileOps: 12,
8
+ maxArchiveNodes: 5000,
9
+ maxCommandChars: 160,
10
+ maxSessions: 128,
11
+ archiveEnabled: false,
12
+ archivePath: '',
13
+ promptPrefix: '',
14
+ promptSuffix: '',
15
+ })
16
+ const LIMITS = { maxNodes: [0, 20000], maxKeptTurns: [0, 60], maxRequestSteps: [0, 60], maxEvents: [0, 20], maxFileOps: [0, 12], maxArchiveNodes: [0, 20000], maxCommandChars: [16, 240], maxSessions: [1, 256] }
17
+ export function normalizeConfig(options = {}) {
18
+ const config = { ...DEFAULTS }
19
+ for (const [key, [min, max]] of Object.entries(LIMITS)) {
20
+ const value = options?.[key]
21
+ if (typeof value === 'number' && Number.isFinite(value)) config[key] = Math.max(min, Math.min(max, Math.floor(value)))
22
+ }
23
+ config.archiveEnabled = options?.archiveEnabled === true
24
+ for (const key of ['archivePath', 'promptPrefix', 'promptSuffix']) {
25
+ if (typeof options?.[key] === 'string') config[key] = options[key]
26
+ }
27
+ return Object.freeze(config)
28
+ }
29
+ export function tail(rows, n) { return n <= 0 ? [] : rows.slice(-n) }
30
+ export function clip(value, limit) {
31
+ const chars = Array.from(String(value ?? ''))
32
+ return chars.length <= limit ? chars.join('') : chars.slice(0, limit - 1).join('') + '…'
33
+ }
34
+ // Bounded insertion-order map; reading refreshes the entry's lease.
35
+ export function remember(map, key, create, max = DEFAULTS.maxSessions) {
36
+ const value = map.has(key) ? map.get(key) : create()
37
+ map.delete(key); map.set(key, value)
38
+ while (map.size > max) map.delete(map.keys().next().value)
39
+ return value
40
+ }
package/lib/index.js ADDED
@@ -0,0 +1,73 @@
1
+ // Host orchestration. Collect once per read; state is scoped to one session.
2
+ import { eventFeed, eventsOf, fileActivity, fleet, foldPoints, readPressure, readWindow, recentTurns, requestInfo, seriesOf, sessionOf, toolCalls, trackCompaction, usagePoints } from './collect.js'
3
+ import { contextData, contextView, stripData, summaryText, words } from './view.js'
4
+ import { applyWebPanel, SWITCHES } from './web-panel.js'
5
+ import { normalizeConfig, remember, tail } from './config.js'
6
+ import { createArchive } from './archive.js'
7
+ import { registerPrompts } from './prompts.js'
8
+
9
+ export const name = 'dshgo-context-panel'
10
+ const UI = Object.freeze({ granularity: 'turn', trendMode: 'total', toolSort: 'count', fileSort: 'count' })
11
+ const REFRESH_ON = new Set(['assistant/message', 'assistant/attempt', 'compaction/start', 'compaction/end', 'compaction/prune', 'compaction/summary'])
12
+
13
+ export function apply(ctx, options = {}) {
14
+ const config = normalizeConfig(options)
15
+ const listeners = new Set()
16
+ const preferences = new Map()
17
+ const changed = () => { for (const notify of listeners) notify() }
18
+ const archive = createArchive(config)
19
+ registerPrompts(ctx, config)
20
+ archive.ready.then(changed)
21
+ const compaction = trackCompaction(ctx, changed, config.maxSessions)
22
+ ctx.on('session/event', (session, event) => {
23
+ const id = typeof session === 'string' ? session : session?.id ?? session?.header?.id
24
+ if (archive.record(id, event)) archive.flush().then(changed)
25
+ if (REFRESH_ON.has(event?.type)) changed()
26
+ })
27
+ ctx.effect(() => () => { compaction.dispose(); preferences.clear(); listeners.clear(); return archive.flush() })
28
+
29
+ function snapshot(scope) {
30
+ const sessionId = typeof scope?.sessionId === 'string' ? scope.sessionId : undefined
31
+ const session = sessionOf(ctx, sessionId)
32
+ const events = eventsOf(session, config.maxNodes)
33
+ const bounded = { snapshotEvents: () => events }
34
+ const turns = recentTurns(bounded, config.maxKeptTurns)
35
+ const contextWindow = readWindow(ctx, sessionId)
36
+ let pressure = readPressure(ctx, session)
37
+ if (pressure === null && turns.length > 0) {
38
+ const last = turns[turns.length - 1]
39
+ pressure = { pressureTokens: last.input + last.output, projectedTokens: null, contextWindow, system: null, tools: null, message: null, estimated: true, source: 'last-call' }
40
+ }
41
+ // Web supplies its own choices. Native choices are bounded and session-keyed.
42
+ const ui = { ...UI, ...(scope?.ui === undefined ? preferences.get(sessionId) ?? {} : scope.ui) }
43
+ const points = tail(foldPoints(usagePoints(bounded), ui.granularity), ui.granularity === 'step' ? config.maxRequestSteps : config.maxKeptTurns)
44
+ return { pressure, contextWindow, compaction: compaction.current(sessionId), turns, hasSession: sessionId !== undefined,
45
+ model: requestInfo(session), ui, config, insights: archive.insights(),
46
+ series: { granularity: ui.granularity, mode: ui.trendMode, rows: seriesOf(points, ui.trendMode) },
47
+ tools: toolCalls(bounded), files: fileActivity(bounded).slice(0, config.maxFileOps), events: eventFeed(bounded, config.maxEvents), fleet: fleet(ctx, sessionId).slice(0, 12) }
48
+ }
49
+ const watch = (push) => { push(); listeners.add(push); return () => listeners.delete(push) }
50
+ const choose = (scope, key, value) => {
51
+ if (SWITCHES[key]?.includes(value)) {
52
+ const ui = remember(preferences, scope?.sessionId, () => ({ ...UI }), config.maxSessions)
53
+ if (ui[key] !== value) { ui[key] = value; changed() }
54
+ }
55
+ }
56
+ ctx.inject(['dshGo'], (sctx) => {
57
+ sctx.dshGo.panel('context', {
58
+ view: (scope, caps) => contextView(scope, caps),
59
+ data: (scope, emit) => watch(() => emit(contextData(snapshot(scope)))),
60
+ actions: {
61
+ refresh: () => [{ type: 'refresh' }],
62
+ 'trend-granularity': (scope, event) => choose(scope, 'granularity', event?.value),
63
+ 'trend-mode': (scope, event) => choose(scope, 'trendMode', event?.value),
64
+ 'tool-sort': (scope, event) => choose(scope, 'toolSort', event?.value),
65
+ 'file-sort': (scope, event) => choose(scope, 'fileSort', event?.value),
66
+ copy: (scope, event) => ({ copy: summaryText(contextData(snapshot(scope)), event?.locale), toast: event?.locale?.startsWith('en') ? 'Copied' : '已复制' }),
67
+ },
68
+ })
69
+ sctx.dshGo.strip('context-strip', (scope, emit, caps) => watch(() => emit(stripData(contextData(snapshot(scope)), caps?.locale))))
70
+ })
71
+ applyWebPanel(ctx, { data: (scope) => contextData(snapshot(scope)), sessions: () => fleet(ctx).slice(0, 12).map(({ id, tokens, fraction }) => ({ id, tokens, fraction })) })
72
+ }
73
+ export { words }
package/lib/prompts.js ADDED
@@ -0,0 +1,10 @@
1
+ // Host-managed lifetime; literal text, no interpolation of user-configured values.
2
+ export function registerPrompts(ctx, config) {
3
+ if (![config.promptPrefix, config.promptSuffix].some((text) => text?.trim())) return
4
+ ctx.inject(['systemPrompt'], (sctx) => {
5
+ for (const [key, order] of [['promptPrefix', 'DEPLOYMENT_PERSONA_PREFIX'], ['promptSuffix', 'DEPLOYMENT_PERSONA_SUFFIX']]) {
6
+ if (!config[key]?.trim()) continue
7
+ sctx.systemPrompt.section({ name: `dshgo-context-panel:${key}`, order: sctx.systemPrompt.getSectionOrder(order), interpolate: false, text: () => config[key] })
8
+ }
9
+ })
10
+ }