opencode-context-indicator 1.1.4 → 1.1.6

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/index.js CHANGED
@@ -70,9 +70,10 @@
70
70
  * plugin runtime). Two commands:
71
71
  * - /context — a 3-line summary of THIS session only (model, tokens, %,
72
72
  * updated + category line). Main only: NO subagent traversal and NO live
73
- * RPC (cache + state.json only), so it is instant. Delivered as a
74
- * resume:false notice; the chip label (`description`) is self-contained:
75
- * "Context: 41.5k (25%) · Auto · 12:36".
73
+ * RPC (cache + state.json only), so it is instant. Delivered with
74
+ * resume:true (like /context-breakdown), so the model echoes the summary
75
+ * into the transcript; the chip label (`description`) is self-contained:
76
+ * "Context: 41.5k (25%) · your-model · 12:36".
76
77
  * - /context-breakdown — the full markdown table (main + all subagent
77
78
  * descendants), collected in parallel under one budget. Delivered with
78
79
  * resume:true and a verbatim instruction prefix, so the agent echoes the
@@ -147,2798 +148,30 @@
147
148
  * for session.compacted; file truncated at ~1MB). Flip to false to disable.
148
149
  */
149
150
 
150
- import { tmpdir } from "node:os";
151
+ import { makeV1 } from "./lib/v1.js";
152
+ import { handleV2Event, onV2Context } from "./lib/v2.js";
151
153
  import {
152
- appendFileSync,
153
- mkdirSync,
154
- readFileSync,
155
- renameSync,
156
- statSync,
157
- writeFileSync,
158
- } from "node:fs";
159
- import { join } from "node:path";
160
- import { claimOnce, pruneMap } from "./lib/dedup.js";
161
-
162
- const THROTTLE_MS = 2500; // min gap between toasts
163
- const MIN_GROWTH_TOKENS = 2048; // only re-toast if context grew by this many tokens
164
- const MAX_TRACKED_SESSIONS = 256; // LRU cap for maps
165
- const BREAKDOWN_THROTTLE_MS = 7500; // min gap between live breakdown writes
166
- const MSG_FETCH_THROTTLE_MS = 30000; // min gap between fallback session.messages calls
167
- const SUBAGENT_THROTTLE_MS = 30000; // min gap between subagent aggregations
168
- const TOOL_SCHEMA_TTL_MS = 3600 * 1000; // tool schemas rarely change
169
- const MAX_FINAL_SUMMARIES = 50; // bound the in-memory final-summary log
170
- // Token-estimate densities by script (unicode heuristic — estimate, not a
171
- // tokenizer): Latin/ASCII ~4 chars/token, Cyrillic ~2.5, CJK ~1.5.
172
- const CHARS_PER_TOKEN_OTHER = 4;
173
- const CHARS_PER_TOKEN_CYRILLIC = 2.5;
174
- const CHARS_PER_TOKEN_CJK = 1.5;
175
- const CRITICAL_RATIO = 0.9; // > this fill: bypass growth gate, shorter throttle
176
- const CRITICAL_THROTTLE_MS = 10000; // min gap between critical (>90%) toasts
177
- const ERROR_TOAST_DEDUP_MS = 60000; // same error -> at most one toast / window
178
- const COMPACTED_TOAST_DEDUP_MS = 60000; // compacted-toast dedup window
179
- const PROVIDERS_TTL_MS = 5 * 60 * 1000; // providers()/model.list() cache TTL after SUCCESS
180
- const PROVIDERS_FAIL_TTL_MS = 30 * 1000; // retry-no-sooner base after FAILURE (doubles per consecutive miss)
181
- const V2_LIMITS_MAX_BACKOFF_MS = 5 * 60 * 1000; // cap for the model.list retry backoff
182
- const PROVIDERS_FETCH_TIMEOUT_MS = 2000; // hard cap for one providers() call (V1)
183
- const V2_MODEL_FETCH_TIMEOUT_MS = 8000; // hard cap for one ctx.model.list() call (V2)
184
- const TOAST_MS_ERROR = 8000; // duration for error / overflow toasts
185
-
186
- // --- DEBUG instrumentation (behaviour probing on Desktop) ---
187
- // When true, every incoming event.type is appended to %TEMP%\context-events.log
188
- // (full JSON payload for session.error, sessionID for session.compacted).
189
- // The file is truncated once it exceeds ~1MB. Flip to false to disable.
190
- const DEBUG_EVENTS = false;
191
- const EVENT_LOG_MAX_BYTES = 1024 * 1024; // ~1MB truncate threshold
192
-
193
- const LOG_FILE = join(tmpdir(), "context-breakdown.log");
194
-
195
- // Machine-readable snapshot consumed by the optional TUI sidebar (./tui.tsx,
196
- // package entry "./tui"). Written next to each log update — same moment, same
197
- // data. See writeStateFile() below.
198
- // State file path — overridable via env for test isolation.
199
- // In production the env is never set, so behaviour is unchanged.
200
- // In tests: export OPENCODE_CONTEXT_INDICATOR_STATE_FILE=/tmp/test-state.json
201
- // and the harness writes a controlled seed; no live file is touched.
202
- const STATE_FILE =
203
- process.env.OPENCODE_CONTEXT_INDICATOR_STATE_FILE ||
204
- join(tmpdir(), "opencode-context-indicator-state.json");
205
-
206
- // Separate tap log for raw events (written only when DEBUG_EVENTS is true).
207
- const EVENT_LOG_FILE = join(tmpdir(), "context-events.log");
208
-
209
- // Cross-instance dedup markers for the context-indicator (see ./lib/dedup.js).
210
- // Used for final summaries / compacted / error notes: the live snapshot itself
211
- // is an idempotent rewrite and needs no claim.
212
- const DEDUP_DIR = join(tmpdir(), "context-indicator.dedup");
213
-
214
- // sessionID -> { at, tokens }
215
- const lastShown = new Map();
216
-
217
- // `<providerID>:<modelID>` -> { context, input, output, reserved } limit record,
218
- // populated lazily from the merged config / providers() / model.list.
219
- const modelLimits = new Map();
220
-
221
- // `<providerID>:<modelID>` -> { input, output, cacheRead, cacheWrite } — ONLY
222
- // when the model config carries explicit pricing (custom providers usually omit).
223
- const modelPrices = new Map();
224
-
225
- // sessionID -> captured breakdown from transform hooks / context hook / fallback
226
- // { systemChars, userChars, assistantChars, reasoningTokens, reasoningChars,
227
- // toolArgsChars, toolSchemasChars, capturedAt, source }
228
- // NOTE: the *Chars fields are TOKEN estimates (unicode heuristic — see
229
- // estimateTokens); the name is kept from the original plugin for 1:1 diffability.
230
- const breakdownCache = new Map();
231
-
232
- // `<providerID>:<modelID>` -> { chars, at } — cached tool-schema estimate (V1 path)
233
- const toolSchemaCache = new Map();
234
-
235
- // sessionID -> { count, input, output, reasoning, at } — subagent aggregation (V1)
236
- const subagentCache = new Map();
237
-
238
- // sessionID -> last time we called the expensive session.messages fallback
239
- const msgFetchTimes = new Map();
240
-
241
- // sessionID -> last modelID / providerID / input tokens / reasoning seen.
242
- // The modelID/providerID pair is turned into a `<providerID>:<modelID>` limit
243
- // lookup key at every modelLimits/modelPrices access site (the maps themselves
244
- // are model-keyed, these caches are session-keyed by design).
245
- const lastKnownModelCache = new Map();
246
- const lastKnownProviderCache = new Map();
247
- const lastKnownInputCache = new Map();
248
- const lastKnownReasoningCache = new Map();
249
- // sessionID -> last native opencode overflow count (tokens.total, else
250
- // input + output + cache.read + cache.write)
251
- const lastKnownCtxCache = new Map();
252
-
253
- // sessionID -> last time we wrote a live breakdown snapshot
254
- const lastBdWrite = new Map();
255
-
256
- // sessionID -> { sig, at } — dedup for session.error / info.error toasts
257
- const lastErrorToast = new Map();
258
-
259
- // sessionID -> timestamp — dedup for session.compacted toasts
260
- const lastCompactedToast = new Map();
261
-
262
- // sessionID -> parentID (null = main session) — [main]/[sub] attribution cache
263
- const sessionParentCache = new Map();
264
-
265
- // V2: sessionID -> { input, output, reasoning, ctx, modelID, at } accumulated
266
- // from session.step.ended, used to fold child-session totals into the parent.
267
- const sessionTotals = new Map();
268
-
269
- // V2: sessionID -> agent name (session.created data.agent). Used only as the
270
- // role label ("sub:<agent>") in the /context-breakdown table.
271
- const sessionAgentCache = new Map();
272
-
273
- // Gating for client.config.providers() (V1) fetches:
274
- // providersLoadedAt — last SUCCESSFUL fetch (full PROVIDERS_TTL_MS cache);
275
- // providersFailAt — last FAILED/timed-out fetch (short fail TTL, so a
276
- // broken/hung client does not freeze limits for the
277
- // full 5 minutes);
278
- // providersInFlight — in-flight fetch promise (dedups parallel callers).
279
- let providersLoadedAt = 0;
280
- let providersFailAt = 0;
281
- let providersInFlight = null;
282
-
283
- // Gating for ctx.model.list() (V2) — success TTL + in-flight dedup. Failures
284
- // are retried after the short gate; limit lookups then simply fall back to
285
- // absolute tokens (as in V1).
286
- let v2LimitsLoadedAt = 0;
287
- let v2LimitsFailAt = 0;
288
- let v2LimitsFailCount = 0; // consecutive soft-failures -> exponential retry backoff
289
- let v2LimitsInFlight = null;
290
-
291
- // Bounded list of final summaries written on session.idle
292
- const finalSummaries = [];
293
-
294
- function fmt(n) {
295
- return n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n);
296
- }
297
-
298
- // Unicode-aware TOKEN estimate (heuristic, NOT a tokenizer). The string is
299
- // scanned ONCE by code point and split into three density buckets:
300
- // - Cyrillic (U+0400–U+04FF + supplements/extensions): ~2.5 chars/token
301
- // - CJK / Japanese / Korean (U+4E00–U+9FFF, U+3040–U+30FF, …): ~1.5
302
- // - everything else (latin/ASCII/digits/punct): ~4
303
- // tokens = cyr/2.5 + cjk/1.5 + other/4. Single O(n) pass, no intermediate
304
- // arrays (these strings can be 100k+ chars). Guards against absurd input.
305
- function estimateTokens(text) {
306
- if (!text) return 0;
307
- const s = typeof text === "string" ? text : String(text);
308
- const len = s.length;
309
- if (len === 0) return 0;
310
- let other = 0;
311
- let cyr = 0;
312
- let cjk = 0;
313
- for (let i = 0; i < len; i++) {
314
- const cp = s.codePointAt(i);
315
- if (cp > 0xffff) i++; // astral pair — consume the low surrogate
316
- if (cp < 0x80) {
317
- other++;
318
- } else if (
319
- (cp >= 0x0400 && cp <= 0x04ff) || // Cyrillic
320
- (cp >= 0x0500 && cp <= 0x052f) || // Cyrillic Supplement
321
- (cp >= 0x2de0 && cp <= 0x2dff) || // Cyrillic Extended-A
322
- (cp >= 0xa640 && cp <= 0xa69f) || // Cyrillic Extended-B
323
- (cp >= 0x1c80 && cp <= 0x1c8f) // Cyrillic Extended-C
324
- ) {
325
- cyr++;
326
- } else if (
327
- (cp >= 0x4e00 && cp <= 0x9fff) || // CJK Unified Ideographs
328
- (cp >= 0x3400 && cp <= 0x4dbf) || // CJK Extension A
329
- (cp >= 0xf900 && cp <= 0xfaff) || // CJK Compatibility Ideographs
330
- (cp >= 0x3040 && cp <= 0x30ff) || // Hiragana + Katakana
331
- (cp >= 0xac00 && cp <= 0xd7af) || // Hangul Syllables
332
- (cp >= 0x3000 && cp <= 0x303f) || // CJK Symbols and Punctuation
333
- (cp >= 0xff00 && cp <= 0xffef) // Halfwidth/Fullwidth Forms
334
- ) {
335
- cjk++;
336
- } else {
337
- other++;
338
- }
339
- }
340
- return Math.round(
341
- other / CHARS_PER_TOKEN_OTHER +
342
- cyr / CHARS_PER_TOKEN_CYRILLIC +
343
- cjk / CHARS_PER_TOKEN_CJK,
344
- );
345
- }
346
-
347
- // Token estimate from a serializable value (tool args / params).
348
- function estJson(value) {
349
- if (value == null) return 0;
350
- try {
351
- return estimateTokens(JSON.stringify(value));
352
- } catch {
353
- return 0;
354
- }
355
- }
356
-
357
- // Native opencode overflow count for a tokens object:
358
- // count = tokens.total || input + output + cache.read + cache.write
359
- // (with legacy flat cacheRead/cacheWrite fallbacks) — the exact value opencode
360
- // compares against the model's usable window in its overflow check.
361
- function tokenCountOf(tokens) {
362
- if (!tokens) return 0;
363
- if (typeof tokens.total === "number" && tokens.total > 0) return tokens.total;
364
- const cacheRead =
365
- typeof tokens.cache?.read === "number"
366
- ? tokens.cache.read
367
- : typeof tokens.cacheRead === "number"
368
- ? tokens.cacheRead
369
- : 0;
370
- const cacheWrite =
371
- typeof tokens.cache?.write === "number"
372
- ? tokens.cache.write
373
- : typeof tokens.cacheWrite === "number"
374
- ? tokens.cacheWrite
375
- : 0;
376
- return (tokens.input || 0) + (tokens.output || 0) + cacheRead + cacheWrite;
377
- }
378
-
379
- // ---------------------------------------------------------------------------
380
- // Logging helpers (all fault-tolerant; never throw into the caller).
381
- // ---------------------------------------------------------------------------
382
-
383
- function logErr(msg, err) {
384
- try {
385
- console.error(`[context-indicator] ${msg}:`, err);
386
- } catch {
387
- /* ignore */
388
- }
389
- }
390
-
391
- // Build the full file content: header + live snapshot + final summaries.
392
- function renderFile(liveLines) {
393
- const lines = [];
394
- lines.push(
395
- "# context-breakdown.log",
396
- `# generated ${new Date().toISOString()} by context-indicator plugin`,
397
- "# estimates: unicode heuristic (cyrillic 2.5, CJK 1.5, other 4 chars/token) — estimate, not a tokenizer",
398
- "# live snapshot is rewritten; final summaries are preserved (bounded)",
399
- "",
400
- "## live snapshot",
401
- ...liveLines,
402
- "",
403
- "## final summaries",
404
- );
405
- if (finalSummaries.length === 0) {
406
- lines.push("(none yet)");
407
- } else {
408
- for (const s of finalSummaries) lines.push(s);
409
- }
410
- return lines.join("\n") + "\n";
411
- }
412
-
413
- // Atomically rewrite the whole log file (bounded by design). The temp+rename
414
- // makes concurrent writers from multiple plugin instances safe: a reader sees
415
- // either the previous or the new file, never a half-written one.
416
- function writeLog(liveLines) {
417
- try {
418
- const content = renderFile(liveLines);
419
- const tmp = `${LOG_FILE}.${process.pid}.tmp`;
420
- writeFileSync(tmp, content, "utf8");
421
- renameSync(tmp, LOG_FILE);
422
- } catch (err) {
423
- logErr("writeLog failed", err);
424
- }
425
- }
426
-
427
- // Append a single line to the file (used for final summaries / notes).
428
- function appendLogLine(line) {
429
- try {
430
- appendFileSync(LOG_FILE, line + "\n", "utf8");
431
- } catch (err) {
432
- logErr("appendLogLine failed", err);
433
- }
434
- }
435
-
436
- // ---------------------------------------------------------------------------
437
- // TUI state bridge (opencode-context-indicator)
438
- // ---------------------------------------------------------------------------
439
- // Persist a tiny machine-readable snapshot of the CURRENT breakdown for one
440
- // session so the optional TUI sidebar (./tui.tsx, package entry "./tui") can
441
- // render it without talking to the server. The file is one JSON object keyed by
442
- // sessionID, rewritten atomically (temp + rename) at every log write — same
443
- // moment, same data. Strictly additive: any failure is swallowed and must never
444
- // affect the log / toast / event paths.
445
- function writeStateFile(
446
- sessionID,
447
- modelID,
448
- providerID,
449
- inputTokens,
450
- ctxTokens,
451
- reasoningTokens,
452
- ) {
453
- try {
454
- if (!sessionID) return;
455
- const bd = breakdownCache.get(sessionID) || null;
456
- const limit = getModelLimit(providerID, modelID);
457
- const usableInfo = getUsableContext(providerID, modelID);
458
- const denom =
459
- usableInfo != null
460
- ? usableInfo.usable
461
- : limit != null && limit > 0
462
- ? limit
463
- : null;
464
- const total =
465
- typeof ctxTokens === "number" && ctxTokens > 0
466
- ? ctxTokens
467
- : inputTokens || 0;
468
-
469
- // Read the existing file FIRST: when THIS instance has no fresh breakdown
470
- // (the context hook did not fire here — e.g. the request was served by
471
- // another plugin instance whose event stream is mirrored to us), keep the
472
- // values already persisted instead of clobbering them with nulls/zeros.
473
- let all = {};
474
- try {
475
- all = JSON.parse(readFileSync(STATE_FILE, "utf8"));
476
- } catch {
477
- all = {}; // missing / empty / corrupt -> start fresh
478
- }
479
- if (!all || typeof all !== "object" || Array.isArray(all)) all = {};
480
- const prevEntry = all[sessionID] || null;
481
- const pc = all[sessionID]?.categories || null;
482
-
483
- // Same model AND provider? Only then is a previously persisted denominator
484
- // meaningful — a session that switched model (or provider, even with the
485
- // same modelID) must not inherit the old window.
486
- const sameModelAsPrev =
487
- prevEntry != null &&
488
- prevEntry.model === (modelID || "unknown") &&
489
- (prevEntry.providerID || "") === (providerID || "");
490
-
491
- const catUser = bd ? bd.userChars || 0 : pc?.user ?? 0;
492
- const catAssistant = bd ? bd.assistantChars || 0 : pc?.assistant ?? 0;
493
- const catReasoning = bd ? bd.reasoningChars || 0 : pc?.reasoning ?? 0;
494
- const catToolArgs = bd ? bd.toolArgsChars || 0 : pc?.toolArgs ?? 0;
495
- // system / tool schemas are hook-only; a fallback breakdown has them null
496
- // and must not erase a value the hook already persisted.
497
- const catSystem =
498
- bd && bd.systemChars != null ? bd.systemChars : pc?.system ?? null;
499
- const catToolSchemas =
500
- bd && bd.toolSchemasChars != null
501
- ? bd.toolSchemasChars
502
- : pc?.toolSchemas ?? null;
503
-
504
- const sumEstimates =
505
- catUser +
506
- catAssistant +
507
- catReasoning +
508
- catToolArgs +
509
- (catSystem || 0) +
510
- (catToolSchemas || 0);
511
- const other = Math.max(0, (inputTokens || 0) - sumEstimates);
512
- // Parent link for the /context-breakdown command. Prefer the live cache;
513
- // fall back to the previously persisted value (backward compatible with
514
- // snapshots written before parentID existed -> null). role mirrors it.
515
- const parentID =
516
- sessionParentCache.has(sessionID)
517
- ? sessionParentCache.get(sessionID) ?? null
518
- : prevEntry?.parentID ?? null;
519
- const entry = {
520
- sessionID,
521
- parentID,
522
- role: parentID ? "sub" : "main",
523
- agent: sessionAgentCache.get(sessionID) || prevEntry?.agent || null,
524
- model: modelID || "unknown",
525
- providerID: providerID || "",
526
- ctx: total,
527
- input: inputTokens || 0,
528
- // Do NOT clobber a known denominator with null: multiple plugin instances
529
- // share this file and one of them may lack modelLimits (its ctx.model.list
530
- // returned nothing). Keep the previous model's known value when the live
531
- // lookup came back empty, so a transient miss never becomes permanent.
532
- usable:
533
- denom != null ? denom : sameModelAsPrev ? prevEntry.usable ?? null : null,
534
- limit:
535
- limit != null
536
- ? limit
537
- : sameModelAsPrev && typeof prevEntry.limit === "number"
538
- ? prevEntry.limit
539
- : null,
540
- reasoning: typeof reasoningTokens === "number" ? reasoningTokens : 0,
541
- categories: {
542
- user: catUser,
543
- assistant: catAssistant,
544
- reasoning: catReasoning,
545
- toolArgs: catToolArgs,
546
- system: catSystem,
547
- toolSchemas: catToolSchemas,
548
- other,
549
- },
550
- updatedAt: new Date().toISOString(),
551
- };
552
- all[sessionID] = entry;
553
- // Bound the file: keep the most recently updated MAX_TRACKED_SESSIONS.
554
- const keys = Object.keys(all);
555
- if (keys.length > MAX_TRACKED_SESSIONS) {
556
- keys
557
- .sort((a, b) =>
558
- String(all[b]?.updatedAt || "").localeCompare(
559
- String(all[a]?.updatedAt || ""),
560
- ),
561
- )
562
- .slice(MAX_TRACKED_SESSIONS)
563
- .forEach((k) => delete all[k]);
564
- }
565
- const tmp = `${STATE_FILE}.${process.pid}.tmp`;
566
- writeFileSync(tmp, JSON.stringify(all), "utf8");
567
- renameSync(tmp, STATE_FILE);
568
- } catch (err) {
569
- logErr("writeStateFile failed", err);
570
- }
571
- }
572
-
573
- // ---------------------------------------------------------------------------
574
- // DEBUG event tap (DEBUG_EVENTS only; fully fault-tolerant — any failure here
575
- // is swallowed and must never affect the main path).
576
- // ---------------------------------------------------------------------------
577
-
578
- // Append one line to the event log, truncating it when it grows past ~1MB.
579
- function appendEventLog(line) {
580
- try {
581
- try {
582
- const st = statSync(EVENT_LOG_FILE);
583
- if (st.size > EVENT_LOG_MAX_BYTES) {
584
- writeFileSync(EVENT_LOG_FILE, "", "utf8"); // truncate, keep it bounded
585
- }
586
- } catch {
587
- // file does not exist yet — nothing to truncate
588
- }
589
- appendFileSync(EVENT_LOG_FILE, line + "\n", "utf8");
590
- } catch (err) {
591
- logErr("appendEventLog failed", err);
592
- }
593
- }
594
-
595
- // Tap every incoming event: timestamp + type. session.error gets the full
596
- // JSON payload, session.compacted gets the sessionID. Never throws.
597
- function debugEvent(event) {
598
- if (!DEBUG_EVENTS || !event) return;
599
- try {
600
- let line = `[${new Date().toISOString()}] ${event.type}`;
601
- if (event.type === "session.error") {
602
- try {
603
- line += ` ${JSON.stringify(event.properties ?? event.data ?? {})}`.slice(
604
- 0,
605
- 4000,
606
- );
607
- } catch {
608
- line += " <unserializable payload>";
609
- }
610
- } else if (event.type === "session.compacted") {
611
- const sid =
612
- event.properties?.sessionID ?? event.data?.sessionID ?? "?";
613
- line += ` sessionID=${sid}`;
614
- }
615
- appendEventLog(line);
616
- } catch (err) {
617
- logErr("debugEvent failed", err);
618
- }
619
- }
620
-
621
- // Reject when `promise` has not settled within `ms`. The underlying promise
622
- // is not cancellable in JS — its late result is simply discarded. The timer
623
- // is always cleared; never leaves a dangling timeout.
624
- function withTimeout(promise, ms, label) {
625
- let timer;
626
- const gate = new Promise((_, reject) => {
627
- timer = setTimeout(
628
- () => reject(new Error(`${label}: no response within ${ms}ms`)),
629
- ms,
630
- );
631
- });
632
- return Promise.race([promise, gate]).finally(() => clearTimeout(timer));
633
- }
634
-
635
- // Stable lookup key for the model-keyed limit/price/schema maps. providerID may
636
- // be unknown ("" ) — the result is still unique per modelID, but different
637
- // providers never share a cache slot.
638
- function modelKey(providerID, modelID) {
639
- if (typeof modelID !== "string" || modelID.length === 0) return null;
640
- const p = typeof providerID === "string" && providerID.length > 0 ? providerID : "";
641
- return `${p}:${modelID}`;
642
- }
643
-
644
- // Raw limit record for a model: { context, input, output, reserved } or null.
645
- function getModelLimitRecord(providerID, modelID) {
646
- const key = modelKey(providerID, modelID);
647
- if (!key) return null;
648
- const v = modelLimits.get(key);
649
- return v && typeof v === "object" ? v : null;
650
- }
651
-
652
- // Context window for a model (null when unknown). Used for subagent ratios and
653
- // as the degraded denominator when the native usable window is not derivable.
654
- function getModelLimit(providerID, modelID) {
655
- const rec = getModelLimitRecord(providerID, modelID);
656
- if (!rec) return null;
657
- return typeof rec.context === "number" && rec.context > 0 ? rec.context : null;
658
- }
659
-
660
- // Native opencode usable window (see packages/opencode/src/session/overflow.ts):
661
- // usable = limit.input ? limit.input − reserved : limit.context − maxOutput
662
- // reserved = compaction.reserved ?? min(20_000, maxOutput)
663
- // maxOutput = model.limit.output
664
- // Returns { usable, limit, maxOutput, reserved } or null when not derivable
665
- // (callers then degrade to count / limit.context, or to no percentage at all).
666
- function getUsableContext(providerID, modelID) {
667
- const rec = getModelLimitRecord(providerID, modelID);
668
- if (!rec) return null;
669
- const context =
670
- typeof rec.context === "number" && rec.context > 0 ? rec.context : null;
671
- const input =
672
- typeof rec.input === "number" && rec.input > 0 ? rec.input : null;
673
- const maxOutput =
674
- typeof rec.output === "number" && rec.output > 0 ? rec.output : 0;
675
- if (input == null && context == null) return null;
676
- // Mirrors opencode overflow.ts: reserved = min(20000, maxOutput), i.e. 0 when
677
- // the model declares no output limit (NOT a 20000 default — that would
678
- // understate the usable window).
679
- const reserved =
680
- typeof rec.reserved === "number" && rec.reserved >= 0
681
- ? rec.reserved
682
- : Math.min(20000, maxOutput);
683
- const usable = input != null ? input - reserved : context - maxOutput;
684
- if (!(usable > 0)) return null;
685
- return { usable, limit: context, maxOutput, reserved };
686
- }
687
-
688
- // Store a model limit record under `<providerID>:<modelID>`. Written by
689
- // `ensureModelLimits` (V2: ctx.model.list()) and `ensureProviderLimits` (V1:
690
- // client.config.providers()), both carrying the effective merged config.
691
- function setModelLimit(providerID, modelID, rec) {
692
- const key = modelKey(providerID, modelID);
693
- if (!key) return false;
694
- modelLimits.set(key, rec);
695
- return true;
696
- }
697
-
698
- // ---------------------------------------------------------------------------
699
- // V1 breakdown estimation from messages (Array<{info, parts}>).
700
- // ---------------------------------------------------------------------------
701
-
702
- function estimateBreakdown(messages) {
703
- let userChars = 0;
704
- let assistantChars = 0;
705
- let reasoningTokens = 0;
706
- let reasoningChars = 0;
707
- let toolArgsChars = 0;
708
-
709
- for (const { info, parts } of messages || []) {
710
- const partsArr = parts || [];
711
- if (info?.role === "user") {
712
- for (const p of partsArr) {
713
- if (p?.type === "text") userChars += estimateTokens(p.text);
714
- }
715
- } else if (info?.role === "assistant") {
716
- // Exact reasoning token count straight from the message metadata.
717
- if (typeof info?.tokens?.reasoning === "number") {
718
- reasoningTokens += info.tokens.reasoning;
719
- }
720
- for (const p of partsArr) {
721
- if (p?.type === "text") {
722
- assistantChars += estimateTokens(p.text);
723
- } else if (p?.type === "reasoning") {
724
- reasoningChars += estimateTokens(p.text);
725
- } else if (p?.type === "tool") {
726
- // ONLY the call arguments (state.input). Deliberately NOT summing
727
- // state.output — in some sessions tool output reached ~29 MB of
728
- // chars, which a naive char-based estimate turns into "7 million tokens" and a
729
- // negative remainder. Tool output is not part of the sent prompt.
730
- toolArgsChars += estJson(p.state?.input);
731
- }
732
- }
733
- }
734
- }
735
-
736
- return {
737
- userChars,
738
- assistantChars,
739
- reasoningTokens,
740
- reasoningChars,
741
- toolArgsChars,
742
- };
743
- }
744
-
745
- // ---------------------------------------------------------------------------
746
- // V1 tool schema estimate (cached per modelID).
747
- // ---------------------------------------------------------------------------
748
-
749
- async function getToolSchemas(client, providerID, modelID) {
750
- const key = modelKey(providerID, modelID);
751
- const cached = key ? toolSchemaCache.get(key) : null;
752
- if (cached && Date.now() - cached.at < TOOL_SCHEMA_TTL_MS) {
753
- return cached.chars;
754
- }
755
- let chars = 0;
756
- try {
757
- const res = await client.tool.list({ query: { provider: providerID, model: modelID } });
758
- const tools = Array.isArray(res) ? res : res?.data;
759
- if (Array.isArray(tools)) {
760
- for (const t of tools) {
761
- chars += estimateTokens(t?.description) + estJson(t?.parameters);
762
- }
763
- }
764
- } catch (err) {
765
- logErr(`tool.list failed for ${modelID}`, err);
766
- }
767
- if (key) {
768
- toolSchemaCache.set(key, { chars, at: Date.now() });
769
- pruneMap(toolSchemaCache, MAX_TRACKED_SESSIONS);
770
- }
771
- return chars;
772
- }
773
-
774
- // ---------------------------------------------------------------------------
775
- // V1 model limits: effective values from client.config.providers(), cached.
776
- // ---------------------------------------------------------------------------
777
-
778
- // Load effective limits for ALL providers from the server config. Preferred
779
- // over the config() hook snapshot because it reflects live overrides.
780
- // Gating: a SUCCESSFUL fetch is cached for PROVIDERS_TTL_MS; a failed or
781
- // timed-out attempt only blocks retries for PROVIDERS_FAIL_TTL_MS, so limits
782
- // recover quickly instead of staying stale for the full 5 minutes. All
783
- // failures are caught here — the function never rejects; callers fall back to
784
- // whatever the config() hook loaded.
785
- async function ensureProviderLimits(client) {
786
- const now = Date.now();
787
- if (now - providersLoadedAt < PROVIDERS_TTL_MS) return; // fresh success
788
- if (now - providersFailAt < PROVIDERS_FAIL_TTL_MS) return; // recent failure
789
- if (providersInFlight) return providersInFlight; // dedup parallel callers
790
- providersInFlight = (async () => {
791
- try {
792
- const res = await withTimeout(
793
- client.config.providers(),
794
- PROVIDERS_FETCH_TIMEOUT_MS,
795
- "config.providers",
796
- );
797
- const providers = Array.isArray(res)
798
- ? res
799
- : res?.data?.providers ?? res?.providers ?? res?.data;
800
- if (!Array.isArray(providers)) {
801
- providersFailAt = Date.now(); // malformed payload -> retry soon
802
- return;
803
- }
804
- for (const p of providers) {
805
- const models = p?.models;
806
- if (!models || typeof models !== "object") continue;
807
- // providerID is on the top level of each provider entry (fall back to
808
- // `id`; both are accepted across builds).
809
- const providerID =
810
- typeof p?.providerID === "string" && p.providerID
811
- ? p.providerID
812
- : typeof p?.id === "string"
813
- ? p.id
814
- : "";
815
- for (const [modelID, def] of Object.entries(models)) {
816
- const key = modelKey(providerID, modelID);
817
- if (!key) continue;
818
- const lim = def?.limit;
819
- if (!lim || typeof lim !== "object") continue;
820
- const context =
821
- typeof lim.context === "number" && lim.context > 0 ? lim.context : null;
822
- const input =
823
- typeof lim.input === "number" && lim.input > 0 ? lim.input : null;
824
- const output =
825
- typeof lim.output === "number" && lim.output > 0 ? lim.output : null;
826
- if (context == null && input == null) continue;
827
- const prevRec = modelLimits.get(key);
828
- setModelLimit(providerID, modelID, {
829
- context,
830
- input,
831
- output,
832
- reserved:
833
- typeof def?.compaction?.reserved === "number"
834
- ? def.compaction.reserved
835
- : (prevRec?.reserved ?? null),
836
- });
837
- }
838
- }
839
- providersLoadedAt = Date.now(); // set ONLY on success
840
- } catch (err) {
841
- providersFailAt = Date.now(); // failed attempt -> short retry gate
842
- logErr("config.providers failed", err);
843
- } finally {
844
- providersInFlight = null;
845
- }
846
- })();
847
- return providersInFlight;
848
- }
849
-
850
- // ---------------------------------------------------------------------------
851
- // V1 subagent (child session) aggregation — throttled + cached.
852
- // ---------------------------------------------------------------------------
853
-
854
- async function aggregateSubagents(client, sessionID) {
855
- const now = Date.now();
856
- const cached = subagentCache.get(sessionID);
857
- if (cached && now - cached.at < SUBAGENT_THROTTLE_MS) {
858
- return cached;
859
- }
860
- const result = { count: 0, input: 0, output: 0, reasoning: 0, perChild: [], at: now };
861
- try {
862
- const res = await client.session.children({ path: { id: sessionID } });
863
- const children = Array.isArray(res) ? res : res?.data;
864
- if (Array.isArray(children)) {
865
- result.count = children.length;
866
- for (const child of children) {
867
- try {
868
- const msgsRes = await client.session.messages({ path: { id: child.id } });
869
- const msgs = Array.isArray(msgsRes) ? msgsRes : msgsRes?.data;
870
- let childInput = 0;
871
- let childModelID = null;
872
- let childProviderID = "";
873
- for (const { info } of msgs || []) {
874
- if (info?.role === "assistant" && info?.tokens) {
875
- result.input += info.tokens.input || 0;
876
- result.output += info.tokens.output || 0;
877
- result.reasoning += info.tokens.reasoning || 0;
878
- // Per-child fill: the LAST assistant message's native overflow
879
- // count (tokens.total, else input + output + cache.read +
880
- // cache.write, incl. legacy cacheRead/cacheWrite) + that child's
881
- // model — same formula as the main path, so cache-heavy children
882
- // are not under-reported and still get the ⚠ marker.
883
- if (typeof info.tokens.input === "number") {
884
- childInput = tokenCountOf(info.tokens);
885
- childModelID = info.modelID || childModelID;
886
- childProviderID = info.providerID || childProviderID;
887
- }
888
- }
889
- }
890
- const childLimit = getModelLimit(childProviderID, childModelID);
891
- result.perChild.push({
892
- id: child.id,
893
- input: childInput,
894
- limit: childLimit,
895
- ratio: childLimit ? childInput / childLimit : null,
896
- });
897
- } catch (err) {
898
- logErr(`subagent messages failed for ${child.id}`, err);
899
- }
900
- }
901
- }
902
- } catch (err) {
903
- logErr(`session.children failed for ${sessionID}`, err);
904
- }
905
- subagentCache.set(sessionID, result);
906
- pruneMap(subagentCache, MAX_TRACKED_SESSIONS);
907
- return result;
908
- }
909
-
910
- // ---------------------------------------------------------------------------
911
- // V1 toast helpers: attribution, safe showing, error/overflow toasts.
912
- // ---------------------------------------------------------------------------
913
-
914
- // "[main]" / "[sub]" prefix from Session.parentID. Cached from
915
- // session.created/updated; falls back to client.session.get once per session.
916
- // Unknown attribution -> "" (never blocks the toast).
917
- async function sessionPrefix(client, sessionID) {
918
- if (!sessionID) return "";
919
- try {
920
- if (!sessionParentCache.has(sessionID)) {
921
- const res = await client.session.get({ path: { id: sessionID } });
922
- const info = res?.data?.info ?? res?.data ?? res?.info ?? res;
923
- sessionParentCache.set(sessionID, info?.parentID || null);
924
- pruneMap(sessionParentCache, MAX_TRACKED_SESSIONS);
925
- }
926
- return sessionParentCache.get(sessionID) ? "[sub]" : "[main]";
927
- } catch (err) {
928
- logErr(`session.get failed for ${sessionID}`, err);
929
- return "";
930
- }
931
- }
932
-
933
- // Show a toast; on failure retry once with the "warning" variant (in case the
934
- // build rejects "error"). Never throws.
935
- async function showToastSafe(client, message, variant, duration) {
936
- try {
937
- await client.tui.showToast({ body: { message, variant, duration } });
938
- } catch (err) {
939
- if (variant !== "warning") {
940
- try {
941
- await client.tui.showToast({ body: { message, variant: "warning", duration } });
942
- return;
943
- } catch (err2) {
944
- logErr(`toast fallback failed (variant ${variant})`, err2);
945
- return;
946
- }
947
- }
948
- logErr("toast error", err);
949
- }
950
- }
951
-
952
- function truncate(text, max) {
953
- const s = String(text ?? "");
954
- return s.length > max ? `${s.slice(0, max - 1)}…` : s;
955
- }
956
-
957
- // Short session id for toasts (last 6 chars).
958
- function shortID(sessionID) {
959
- if (!sessionID) return "";
960
- const s = String(sessionID);
961
- return s.length > 8 ? `…${s.slice(-6)}` : s;
962
- }
963
-
964
- // Best-effort message extraction from an arbitrary error payload.
965
- function errMessageOf(err) {
966
- if (!err) return "";
967
- if (typeof err === "string") return err;
968
- return err?.data?.message || err.message || "";
969
- }
970
-
971
- // Dedup for error-ish toasts: identical signature for the same session is
972
- // suppressed within ERROR_TOAST_DEDUP_MS. Returns true when allowed.
973
- function errorToastDedup(sessionID, sig) {
974
- const key = sessionID || "__unknown__";
975
- const now = Date.now();
976
- const prev = lastErrorToast.get(key);
977
- if (prev && prev.sig === sig && now - prev.at < ERROR_TOAST_DEDUP_MS) {
978
- return false;
979
- }
980
- lastErrorToast.set(key, { sig, at: now });
981
- pruneMap(lastErrorToast, MAX_TRACKED_SESSIONS);
982
- return true;
983
- }
984
-
985
- // session.error payload: { sessionID?, error?: { name, data: { message,
986
- // statusCode?, isRetryable? } } } — sessionID is optional, handle undefined.
987
- async function toastSessionError(client, event) {
988
- const props = event.properties || {};
989
- const sessionID =
990
- typeof props.sessionID === "string" ? props.sessionID : undefined;
991
- const error = props.error || {};
992
- const name = error.name || error?.data?.name || "session error";
993
- const detail = errMessageOf(error);
994
- const status = error?.data?.statusCode;
995
- const sig = `${name}|${status ?? ""}|${String(detail).slice(0, 120)}`;
996
- if (!errorToastDedup(sessionID, sig)) return;
997
-
998
- let text = name;
999
- try {
1000
- const prefix = await sessionPrefix(client, sessionID);
1001
- if (prefix) text = `${prefix} ${text}`;
1002
- if (status != null) text += ` (HTTP ${status})`;
1003
- if (detail) text += `: ${truncate(detail, 160)}`;
1004
- if (sessionID) text += ` · ${shortID(sessionID)}`;
1005
- } catch (err) {
1006
- logErr("session.error message build failed", err);
1007
- }
1008
- await showToastSafe(client, text.trim(), "error", TOAST_MS_ERROR);
1009
- }
1010
-
1011
- // Assistant message with info.error: force a warning toast bypassing the
1012
- // throttle gates (same dedup as session.error).
1013
- async function toastMessageError(client, sessionID, error) {
1014
- const name = (error && (error.name || error?.data?.name)) || "model error";
1015
- const detail = errMessageOf(error);
1016
- const sig = `msg|${name}|${String(detail).slice(0, 120)}`;
1017
- if (!errorToastDedup(sessionID, sig)) return;
1018
-
1019
- let text = name;
1020
- try {
1021
- const prefix = await sessionPrefix(client, sessionID);
1022
- if (prefix) text = `${prefix} ${text}`;
1023
- } catch (err) {
1024
- logErr("message.error prefix failed", err);
1025
- }
1026
- if (detail) text += `: ${truncate(detail, 160)}`;
1027
- await showToastSafe(client, text.trim(), "warning", TOAST_MS_ERROR);
1028
- }
1029
-
1030
- // session.compacted (and compaction parts): auto-compaction usually means the
1031
- // context window was exceeded. MUST run BEFORE clearSessionTracking — it reads
1032
- // the last known input/model, which are wiped right after.
1033
- async function toastCompactedSignal(client, sessionID) {
1034
- if (!sessionID) return;
1035
- const now = Date.now();
1036
- const prev = lastCompactedToast.get(sessionID);
1037
- if (prev && now - prev < COMPACTED_TOAST_DEDUP_MS) return;
1038
- lastCompactedToast.set(sessionID, now);
1039
- pruneMap(lastCompactedToast, MAX_TRACKED_SESSIONS);
1040
-
1041
- let text = "session compacted (auto) — возможно, контекст был переполнен";
1042
- try {
1043
- const prefix = await sessionPrefix(client, sessionID);
1044
- const ctx = lastKnownCtx(sessionID) || lastKnownInput(sessionID);
1045
- const limit = getModelLimit(lastKnownProvider(sessionID), lastKnownModel(sessionID));
1046
- if (ctx > 0) text += ` (ctx ${fmt(ctx)}${limit ? ` / ${fmt(limit)}` : ""})`;
1047
- if (prefix) text = `${prefix} ${text}`;
1048
- } catch (err) {
1049
- logErr("compacted message build failed", err);
1050
- }
1051
- await showToastSafe(client, text.trim(), "warning", TOAST_MS_ERROR);
1052
- }
1053
-
1054
- // Best-effort mid-turn hints from message.part.updated: compaction parts
1055
- // mirror session.compacted; retry parts surface provider errors when they
1056
- // carry one. Never blocks the main path.
1057
- async function maybeToastPartSignal(client, event) {
1058
- const part = event.properties?.part;
1059
- if (!part || !part.type) return;
1060
- const sessionID = part.sessionID || event.properties?.sessionID || undefined;
1061
- if (!sessionID) return;
1062
-
1063
- if (part.type === "compaction") {
1064
- try {
1065
- await toastCompactedSignal(client, sessionID); // shared dedup window
1066
- } catch (err) {
1067
- logErr("compaction part toast failed", err);
1068
- }
1069
- return;
1070
- }
1071
-
1072
- if (part.type !== "retry") return;
1073
- const err = part.error ?? part.state?.error;
1074
- const detail = errMessageOf(err);
1075
- if (!detail) return;
1076
- const name = (err && (err.name || err?.data?.name)) || "retry";
1077
- const sig = `part|${name}|${String(detail).slice(0, 120)}`;
1078
- if (!errorToastDedup(sessionID, sig)) return;
1079
- let text = `${name}: ${truncate(detail, 160)}`;
1080
- try {
1081
- const prefix = await sessionPrefix(client, sessionID);
1082
- if (prefix) text = `${prefix} ${text}`;
1083
- } catch {
1084
- // attribution is optional here
1085
- }
1086
- await showToastSafe(client, text.trim(), "warning", TOAST_MS_ERROR);
1087
- }
1088
-
1089
- // ---------------------------------------------------------------------------
1090
- // V1 fallback: fetch messages via client.session.messages (expensive, throttled).
1091
- // ---------------------------------------------------------------------------
1092
-
1093
- async function fetchBreakdownFallback(client, sessionID) {
1094
- const now = Date.now();
1095
- const last = msgFetchTimes.get(sessionID) || 0;
1096
- if (now - last < MSG_FETCH_THROTTLE_MS) return null; // too soon -> skip
1097
- msgFetchTimes.set(sessionID, now);
1098
- pruneMap(msgFetchTimes, MAX_TRACKED_SESSIONS);
1099
-
1100
- try {
1101
- const res = await client.session.messages({ path: { id: sessionID } });
1102
- const msgs = Array.isArray(res) ? res : res?.data;
1103
- const estParts = estimateBreakdown(msgs);
1104
- return { ...estParts, capturedAt: now, source: "fallback" };
1105
- } catch (err) {
1106
- logErr(`session.messages fallback failed for ${sessionID}`, err);
1107
- return null;
1108
- }
1109
- }
1110
-
1111
- // ---------------------------------------------------------------------------
1112
- // Clear per-session tracking. Full wipe on session.idle / session.deleted;
1113
- // on session.compacted (keepToastDedup=true) the toast-dedup entries survive
1114
- // the cleanup so consecutive compacted events still dedup.
1115
- // ---------------------------------------------------------------------------
1116
-
1117
- function clearSessionTracking(sessionID, keepToastDedup = false) {
1118
- if (!sessionID) return;
1119
- lastShown.delete(sessionID);
1120
- breakdownCache.delete(sessionID);
1121
- subagentCache.delete(sessionID);
1122
- msgFetchTimes.delete(sessionID);
1123
- // Error/overflow + compacted toast dedup entries.
1124
- if (!keepToastDedup) {
1125
- lastErrorToast.delete(sessionID);
1126
- lastCompactedToast.delete(sessionID);
1127
- }
1128
- // Attribution cache (re-resolved on the next toast if needed).
1129
- sessionParentCache.delete(sessionID);
1130
- // Idle-summary caches were previously left dirty — clean them too.
1131
- lastKnownModelCache.delete(sessionID);
1132
- lastKnownProviderCache.delete(sessionID);
1133
- lastKnownInputCache.delete(sessionID);
1134
- lastKnownReasoningCache.delete(sessionID);
1135
- lastKnownCtxCache.delete(sessionID);
1136
- lastBdWrite.delete(sessionID);
1137
- // V2 subagent accumulation for this session.
1138
- sessionTotals.delete(sessionID);
1139
- }
1140
-
1141
- // ---------------------------------------------------------------------------
1142
- // V1: assemble the live breakdown lines for the log file.
1143
- // ---------------------------------------------------------------------------
1144
-
1145
- async function buildLiveLines(client, sessionID, modelID, providerID, inputTokens, ctxTokens) {
1146
- const lines = [];
1147
- const ts = new Date().toISOString();
1148
- const limit = getModelLimit(providerID, modelID);
1149
- const usableInfo = getUsableContext(providerID, modelID);
1150
- // Total context = native overflow count (tokens.total, else input + output +
1151
- // cache.read + cache.write); pct has NO upper clamp — exceeding the window
1152
- // must stay visible in the log too. Denominator is the native usable window
1153
- // when derivable, else the raw context window.
1154
- const total = typeof ctxTokens === "number" && ctxTokens > 0 ? ctxTokens : inputTokens;
1155
- const denom =
1156
- usableInfo != null
1157
- ? usableInfo.usable
1158
- : limit != null && limit > 0
1159
- ? limit
1160
- : null;
1161
- const pct =
1162
- denom != null ? ` (${((total / denom) * 100).toFixed(1)}%)` : "";
1163
-
1164
- lines.push(
1165
- `[${ts}] session=${sessionID} model=${modelID} ctx=${fmt(total)}/${denom != null ? fmt(denom) : "?"}${pct} count=${fmt(total)} usable=${usableInfo != null ? fmt(usableInfo.usable) : "?"} limit=${limit != null ? fmt(limit) : "?"} maxOutput=${usableInfo != null ? fmt(usableInfo.maxOutput) : "?"} reserved=${usableInfo != null ? fmt(usableInfo.reserved) : "?"} input=${fmt(inputTokens)}`,
1166
- );
1167
-
1168
- // --- breakdown from cache (transform hooks) or fallback fetch ---
1169
- let bd = breakdownCache.get(sessionID);
1170
- let source = bd?.source || "none";
1171
-
1172
- if (!bd || Date.now() - bd.capturedAt > MSG_FETCH_THROTTLE_MS) {
1173
- // Try to refresh via fallback if we have nothing fresh.
1174
- const fb = await fetchBreakdownFallback(client, sessionID);
1175
- if (fb) {
1176
- bd = fb;
1177
- source = fb.source;
1178
- breakdownCache.set(sessionID, fb);
1179
- pruneMap(breakdownCache, MAX_TRACKED_SESSIONS);
1180
- }
1181
- }
1182
-
1183
- // Tool schemas: cached per modelID (rarely change). Stored into the session
1184
- // breakdown so the estimate is stable across writes.
1185
- let toolSchemasChars = bd?.toolSchemasChars;
1186
- if (toolSchemasChars == null) {
1187
- try {
1188
- toolSchemasChars = await getToolSchemas(client, providerID, modelID);
1189
- if (bd) {
1190
- bd.toolSchemasChars = toolSchemasChars;
1191
- breakdownCache.set(sessionID, bd);
1192
- }
1193
- } catch (err) {
1194
- logErr("tool schema estimate failed", err);
1195
- toolSchemasChars = null;
1196
- }
1197
- }
1198
-
1199
- const sumEstimates = (bd?.userChars || 0) +
1200
- (bd?.assistantChars || 0) +
1201
- (bd?.reasoningChars || 0) +
1202
- (bd?.toolArgsChars || 0) +
1203
- (bd?.systemChars || 0) +
1204
- (bd?.toolSchemasChars || 0);
1205
- const other = Math.max(0, inputTokens - sumEstimates);
1206
-
1207
- if (bd) {
1208
- lines.push(` user ${fmt(bd.userChars || 0)} (est tokens)`);
1209
- lines.push(` assistant ${fmt(bd.assistantChars || 0)} (est tokens)`);
1210
- const reasoningNote =
1211
- bd.reasoningTokens > 0
1212
- ? ` (exact ${fmt(bd.reasoningTokens)})`
1213
- : "";
1214
- lines.push(` reasoning ${fmt(bd.reasoningChars || 0)} (est tokens)${reasoningNote}`);
1215
- lines.push(` tool args ${fmt(bd.toolArgsChars || 0)} (est tokens, input only)`);
1216
- lines.push(
1217
- bd.systemChars != null
1218
- ? ` system ${fmt(bd.systemChars)} (est tokens)`
1219
- : ` system n/a (hook не сработал)`,
1220
- );
1221
- lines.push(
1222
- bd.toolSchemasChars != null
1223
- ? ` tool schemas ${fmt(bd.toolSchemasChars)} (est tokens)`
1224
- : ` tool schemas n/a`,
1225
- );
1226
- } else {
1227
- lines.push(` user n/a (no breakdown captured yet)`);
1228
- lines.push(` assistant n/a`);
1229
- lines.push(` reasoning n/a`);
1230
- lines.push(` tool args n/a`);
1231
- lines.push(` system n/a (hook не сработал)`);
1232
- lines.push(` tool schemas n/a`);
1233
- }
1234
- lines.push(` other ${fmt(other)} (= input - sum of estimates)`);
1235
- lines.push(` source ${source}`);
1236
-
1237
- // --- subagent aggregation (informational only, own context window) ---
1238
- try {
1239
- const sub = await aggregateSubagents(client, sessionID);
1240
- if (sub.count > 0) {
1241
- const ratios = (sub.perChild || [])
1242
- .map((c) => c?.ratio)
1243
- .filter((r) => typeof r === "number");
1244
- const worst =
1245
- ratios.length > 0
1246
- ? ` worst=${(Math.max(...ratios) * 100).toFixed(0)}%`
1247
- : "";
1248
- lines.push(
1249
- ` subagents ${sub.count} session(s): in=${fmt(sub.input)} out=${fmt(sub.output)} r=${fmt(sub.reasoning)}${worst}`,
1250
- );
1251
- } else {
1252
- lines.push(` subagents 0`);
1253
- }
1254
- } catch (err) {
1255
- logErr("subagent aggregation failed", err);
1256
- lines.push(` subagents n/a`);
1257
- }
1258
-
1259
- return lines;
1260
- }
1261
-
1262
- // ---------------------------------------------------------------------------
1263
- // V1 entrypoint (event handler + hooks), preserved unchanged.
1264
- // ---------------------------------------------------------------------------
1265
-
1266
- function makeV1(client) {
1267
- // Fire-and-forget prefetch of effective model limits (fault-tolerant; the
1268
- // config() hook below stays as the fallback source).
1269
- ensureProviderLimits(client).catch((err) =>
1270
- logErr("provider limits prefetch failed", err),
1271
- );
1272
-
1273
- return {
1274
- config(cfg) {
1275
- try {
1276
- // Provider-agnostic: iterate EVERY provider in the config, regardless
1277
- // of name. V1 configs expose `provider`; some shapes use `providers`.
1278
- const buckets = [cfg?.provider, cfg?.providers].filter(
1279
- (b) => b && typeof b === "object",
1280
- );
1281
- if (buckets.length === 0) return;
1282
- for (const bucket of buckets) {
1283
- for (const [providerID, pdef] of Object.entries(bucket)) {
1284
- const models = pdef?.models;
1285
- if (!models || typeof models !== "object") continue;
1286
- for (const [modelID, def] of Object.entries(models)) {
1287
- const key = modelKey(providerID, modelID);
1288
- if (!key) continue;
1289
- const lim = def?.limit;
1290
- const context =
1291
- typeof lim?.context === "number" && lim.context > 0 ? lim.context : null;
1292
- const input =
1293
- typeof lim?.input === "number" && lim.input > 0 ? lim.input : null;
1294
- const output =
1295
- typeof lim?.output === "number" && lim.output > 0 ? lim.output : null;
1296
- if (context != null || input != null) {
1297
- const prevRec = modelLimits.get(key);
1298
- modelLimits.set(key, {
1299
- context,
1300
- input,
1301
- output,
1302
- reserved:
1303
- typeof def?.compaction?.reserved === "number"
1304
- ? def.compaction.reserved
1305
- : (prevRec?.reserved ?? null),
1306
- });
1307
- }
1308
- // Capture explicit pricing ONLY when present (custom providers
1309
- // usually omit it).
1310
- const c = def?.cost;
1311
- if (
1312
- c &&
1313
- typeof c === "object" &&
1314
- (typeof c.input === "number" || typeof c.output === "number")
1315
- ) {
1316
- modelPrices.set(key, {
1317
- input: typeof c.input === "number" ? c.input : 0,
1318
- output: typeof c.output === "number" ? c.output : 0,
1319
- cacheRead: typeof c?.cache?.read === "number" ? c.cache.read : 0,
1320
- cacheWrite: typeof c?.cache?.write === "number" ? c.cache.write : 0,
1321
- });
1322
- }
1323
- }
1324
- }
1325
- }
1326
- } catch {
1327
- // keep whatever we already have
1328
- }
1329
- },
1330
-
1331
- // Capture the final messages right before they are sent to the LLM.
1332
- // We only READ here — never mutate the outgoing messages.
1333
- "experimental.chat.messages.transform"(_input, { messages }) {
1334
- try {
1335
- if (!Array.isArray(messages) || messages.length === 0) return;
1336
- const sid = messages[0]?.info?.sessionID;
1337
- if (!sid) return;
1338
- const estParts = estimateBreakdown(messages);
1339
- const prev = breakdownCache.get(sid) || {};
1340
- breakdownCache.set(sid, {
1341
- ...prev,
1342
- ...estParts,
1343
- capturedAt: Date.now(),
1344
- source: "transform",
1345
- });
1346
- pruneMap(breakdownCache, MAX_TRACKED_SESSIONS);
1347
- } catch (err) {
1348
- logErr("messages.transform failed", err);
1349
- }
1350
- },
1351
-
1352
- // Capture the assembled system prompt (string[]) before send.
1353
- "experimental.chat.system.transform"({ sessionID }, { system }) {
1354
- try {
1355
- const sid = sessionID;
1356
- if (!sid) return;
1357
- let systemChars = 0;
1358
- if (Array.isArray(system)) {
1359
- for (const s of system) systemChars += estimateTokens(s);
1360
- }
1361
- const prev = breakdownCache.get(sid) || {};
1362
- breakdownCache.set(sid, {
1363
- ...prev,
1364
- systemChars,
1365
- capturedAt: Date.now(),
1366
- source: prev.source || "system-transform",
1367
- });
1368
- pruneMap(breakdownCache, MAX_TRACKED_SESSIONS);
1369
- } catch (err) {
1370
- logErr("system.transform failed", err);
1371
- }
1372
- },
1373
-
1374
- async event({ event }) {
1375
- if (!event) return;
1376
-
1377
- // DEBUG: log every incoming event type (fault-tolerant, off via flag).
1378
- debugEvent(event);
1379
-
1380
- // Cache parent links for [main]/[sub] attribution from lifecycle events
1381
- // (properties.info carries parentID when present).
1382
- if (
1383
- event.type === "session.created" ||
1384
- event.type === "session.updated"
1385
- ) {
1386
- try {
1387
- const sinfo = event.properties?.info;
1388
- if (sinfo?.id && sinfo.parentID) {
1389
- sessionParentCache.set(sinfo.id, sinfo.parentID);
1390
- pruneMap(sessionParentCache, MAX_TRACKED_SESSIONS);
1391
- }
1392
- } catch (err) {
1393
- logErr("session parent tracking failed", err);
1394
- }
1395
- return;
1396
- }
1397
-
1398
- // Cleanup tracked sessions when they end / are deleted / are compacted.
1399
- if (
1400
- event.type === "session.idle" ||
1401
- event.type === "session.deleted" ||
1402
- event.type === "session.compacted"
1403
- ) {
1404
- // session.idle / session.compacted -> properties.sessionID;
1405
- // session.deleted -> properties.info.id
1406
- const sid =
1407
- event.properties?.sessionID ?? event.properties?.info?.id;
1408
- if (!sid) return;
1409
-
1410
- // session.compacted: toast BEFORE clearing tracking — it needs the
1411
- // last known input/model, which clearSessionTracking wipes below.
1412
- if (event.type === "session.compacted") {
1413
- try {
1414
- await toastCompactedSignal(client, sid);
1415
- } catch (err) {
1416
- logErr("session.compacted toast failed", err);
1417
- }
1418
- }
1419
-
1420
- if (event.type === "session.idle") {
1421
- // Final summary to the log (best effort; never breaks anything).
1422
- // Timestamp captured BEFORE the async build so the cross-instance
1423
- // dedup key is stable across plugin instances.
1424
- const idleAt = Date.now();
1425
- try {
1426
- const modelID = lastKnownModel(sid);
1427
- const providerID = lastKnownProvider(sid);
1428
- const inputTokens = lastKnownInput(sid);
1429
- const lines = await buildLiveLines(
1430
- client,
1431
- sid,
1432
- modelID,
1433
- providerID,
1434
- inputTokens,
1435
- lastKnownCtx(sid),
1436
- );
1437
- writeStateFile(
1438
- sid,
1439
- modelID,
1440
- providerID,
1441
- inputTokens,
1442
- lastKnownCtx(sid),
1443
- lastKnownReasoning(sid),
1444
- );
1445
- // Claim once across instances: without this, every plugin instance
1446
- // appends its own FINAL line. V1 events carry no `id`, so fall back
1447
- // to a short time bucket (same strategy as the error-toast dedup).
1448
- const eventKey = event.id ?? event.properties?.id;
1449
- const claimKey = eventKey
1450
- ? `final:${eventKey}`
1451
- : `final:${sid}:${Math.floor(idleAt / 5000)}`;
1452
- pushFinalSummary(claimKey, [
1453
- `[${new Date().toISOString()}] FINAL session=${sid}`,
1454
- ...lines.slice(1),
1455
- ]);
1456
- } catch (err) {
1457
- logErr("final summary on idle failed", err);
1458
- }
1459
- }
1460
-
1461
- // session.compacted keeps the toast-dedup entries: two consecutive
1462
- // session.compacted events must not produce two toasts (60s window).
1463
- clearSessionTracking(sid, event.type === "session.compacted");
1464
- return;
1465
- }
1466
-
1467
- // Session-level errors (provider failures etc.). sessionID is optional
1468
- // in the payload — handled gracefully inside.
1469
- if (event.type === "session.error") {
1470
- try {
1471
- await toastSessionError(client, event);
1472
- } catch (err) {
1473
- logErr("session.error handling failed", err);
1474
- }
1475
- return;
1476
- }
1477
-
1478
- // Mid-turn overflow / retry hints from compaction & retry parts.
1479
- if (event.type === "message.part.updated") {
1480
- try {
1481
- await maybeToastPartSignal(client, event);
1482
- } catch (err) {
1483
- logErr("message.part.updated signal failed", err);
1484
- }
1485
- return;
1486
- }
1487
-
1488
- if (event.type !== "message.updated") return;
1489
-
1490
- const info = event?.properties?.info;
1491
- if (!info || info.role !== "assistant") return;
1492
-
1493
- const sessionID = info.sessionID;
1494
-
1495
- // Assistant message carrying an error (when present in this build):
1496
- // force a warning toast, bypassing the throttle gates. Same dedup as
1497
- // session.error.
1498
- if (info.error) {
1499
- try {
1500
- await toastMessageError(client, sessionID, info.error);
1501
- } catch (err) {
1502
- logErr("info.error toast failed", err);
1503
- }
1504
- return;
1505
- }
1506
-
1507
- const tokens = info.tokens;
1508
- if (!tokens || typeof tokens.input !== "number") return;
1509
-
1510
- // Context size components. The "how full is the window" metric is the
1511
- // native opencode overflow count: tokens.total when present, else
1512
- // input + output + cache.read + cache.write (cache tokens included).
1513
- const cacheRead =
1514
- typeof tokens.cache?.read === "number"
1515
- ? tokens.cache.read
1516
- : typeof tokens.cacheRead === "number"
1517
- ? tokens.cacheRead
1518
- : 0;
1519
- const cacheWrite =
1520
- typeof tokens.cache?.write === "number"
1521
- ? tokens.cache.write
1522
- : typeof tokens.cacheWrite === "number"
1523
- ? tokens.cacheWrite
1524
- : 0;
1525
- const contextTokens = tokenCountOf(tokens);
1526
-
1527
- // Remember last known model/provider/input for the idle final summary.
1528
- if (info.modelID) lastKnownModelCache.set(sessionID, info.modelID);
1529
- if (info.providerID) lastKnownProviderCache.set(sessionID, info.providerID);
1530
- lastKnownInputCache.set(sessionID, tokens.input);
1531
- if (typeof tokens.reasoning === "number") {
1532
- lastKnownReasoningCache.set(sessionID, tokens.reasoning);
1533
- }
1534
- lastKnownCtxCache.set(sessionID, contextTokens);
1535
- pruneMap(lastKnownModelCache, MAX_TRACKED_SESSIONS);
1536
- pruneMap(lastKnownProviderCache, MAX_TRACKED_SESSIONS);
1537
- pruneMap(lastKnownInputCache, MAX_TRACKED_SESSIONS);
1538
- pruneMap(lastKnownReasoningCache, MAX_TRACKED_SESSIONS);
1539
- pruneMap(lastKnownCtxCache, MAX_TRACKED_SESSIONS);
1540
-
1541
- // Resolve the limit for THIS message's model, keyed by
1542
- // providerID:modelID. Prefer the effective limits from
1543
- // client.config.providers(); the config() hook remains the fallback.
1544
- const mkey = modelKey(info.providerID, info.modelID);
1545
- let limit = getModelLimit(info.providerID, info.modelID);
1546
- let usableInfo = getUsableContext(info.providerID, info.modelID);
1547
- if (limit == null && usableInfo == null) {
1548
- try {
1549
- await ensureProviderLimits(client);
1550
- } catch {
1551
- // ignore — fall back to whatever the config() hook provided
1552
- }
1553
- limit = getModelLimit(info.providerID, info.modelID);
1554
- usableInfo = getUsableContext(info.providerID, info.modelID);
1555
- }
1556
-
1557
- const now = Date.now();
1558
- const prev = lastShown.get(sessionID);
1559
- // Native usable window when derivable; else the raw context window; else
1560
- // no percentage at all (legacy behaviour).
1561
- const denom =
1562
- usableInfo != null
1563
- ? usableInfo.usable
1564
- : limit != null && limit > 0
1565
- ? limit
1566
- : null;
1567
- const ratio = denom != null ? contextTokens / denom : 0;
1568
- const critical = ratio > CRITICAL_RATIO;
1569
- // Throttle: suppress if NOT enough time has passed OR growth is small.
1570
- // Critical (>90%) toasts skip the growth gate and use a shorter gap so
1571
- // threshold crossings are not silenced by MIN_GROWTH_TOKENS.
1572
- if (
1573
- prev &&
1574
- (now - prev.at < (critical ? CRITICAL_THROTTLE_MS : THROTTLE_MS) ||
1575
- (!critical && contextTokens - prev.tokens < MIN_GROWTH_TOKENS))
1576
- ) {
1577
- return;
1578
- }
1579
-
1580
- lastShown.set(sessionID, { at: now, tokens: contextTokens });
1581
- pruneMap(lastShown, MAX_TRACKED_SESSIONS);
1582
-
1583
- let message;
1584
- let variant = "info";
1585
- if (denom != null) {
1586
- // No upper clamp: exceeding the window must stay visible (>100%).
1587
- const pct = ((contextTokens / denom) * 100).toFixed(1);
1588
- message = `ctx ${fmt(contextTokens)} / ${fmt(denom)} (${pct}%)`;
1589
- if (ratio > 0.75) variant = "warning";
1590
- } else {
1591
- message = `ctx ${fmt(contextTokens)}`;
1592
- }
1593
-
1594
- // F2: extend the toast with reasoning / cache.read when nonzero
1595
- // (raw reported values, unchanged).
1596
- const extras = [];
1597
- const reasoning = typeof tokens.reasoning === "number" ? tokens.reasoning : 0;
1598
- if (reasoning > 0) extras.push(`r ${fmt(reasoning)}`);
1599
- if (cacheRead > 0) extras.push(`c ${fmt(cacheRead)}`);
1600
-
1601
- // Cost: only when the model config carries explicit pricing. Each token
1602
- // class is priced with its OWN rate; reasoning is already counted inside
1603
- // `output` (opencode reports output inclusive of reasoning), so it is NOT
1604
- // added separately. Absent rates are simply skipped.
1605
- const price = mkey ? modelPrices.get(mkey) : null;
1606
- if (price) {
1607
- const inputTok = typeof tokens.input === "number" ? tokens.input : 0;
1608
- const outputTok = typeof tokens.output === "number" ? tokens.output : 0;
1609
- const cost =
1610
- (inputTok / 1000) * (price.input || 0) +
1611
- (outputTok / 1000) * (price.output || 0) +
1612
- (cacheRead / 1000) * (price.cacheRead || 0) +
1613
- (cacheWrite / 1000) * (price.cacheWrite || 0);
1614
- if (cost > 0) extras.push(`${cost.toFixed(4)}$`);
1615
- }
1616
- if (extras.length > 0) {
1617
- message = `${message} · ${extras.join(" · ")}`;
1618
- }
1619
-
1620
- // F3: compact subagent info in the toast (fresh cached value only).
1621
- // Per-child ratios come from the cached aggregation — no extra calls.
1622
- try {
1623
- const sub = subagentCache.get(sessionID);
1624
- if (sub && sub.count > 0 && now - sub.at < SUBAGENT_THROTTLE_MS) {
1625
- const perChild = Array.isArray(sub.perChild) ? sub.perChild : [];
1626
- const ratios = perChild
1627
- .map((c) => c?.ratio)
1628
- .filter((r) => typeof r === "number");
1629
- if (ratios.length > 0) {
1630
- const worst = Math.max(...ratios);
1631
- const worstPct = `${(worst * 100).toFixed(0)}%`;
1632
- const hot = perChild.filter(
1633
- (c) => typeof c?.ratio === "number" && c.ratio > CRITICAL_RATIO,
1634
- ).length;
1635
- message = hot > 0
1636
- ? `${message} · sub ${sub.count}, ${hot}⚠ (${worstPct})`
1637
- : `${message} · sub ${sub.count}, worst ${worstPct}`;
1638
- } else {
1639
- // No known limits for the children -> legacy cumulative total.
1640
- const subTotal = sub.input + sub.output + sub.reasoning;
1641
- message = `${message} · sub ${fmt(subTotal)}`;
1642
- }
1643
- }
1644
- } catch (err) {
1645
- logErr("toast subagent suffix failed", err);
1646
- }
1647
-
1648
- // Attribution: [main]/[sub] by Session.parentID (cached; faults ignored).
1649
- try {
1650
- const prefix = await sessionPrefix(client, sessionID);
1651
- if (prefix) message = `${prefix} ${message}`;
1652
- } catch (err) {
1653
- logErr("attribution prefix failed", err);
1654
- }
1655
-
1656
- try {
1657
- await showToastSafe(client, message, variant, 3500);
1658
- } catch (err) {
1659
- logErr("toast error", err);
1660
- }
1661
-
1662
- // F1: live breakdown to the log (throttled separately, fault-tolerant).
1663
- // Writes whenever enough wall-clock time has passed since the last write;
1664
- // the breakdown cache itself may be fresh (from transform hooks) or stale
1665
- // (then buildLiveLines refreshes it via the fallback fetch).
1666
- try {
1667
- const lastWrite = lastBdWrite.get(sessionID) || 0;
1668
- if (now - lastWrite >= BREAKDOWN_THROTTLE_MS) {
1669
- lastBdWrite.set(sessionID, now);
1670
- pruneMap(lastBdWrite, MAX_TRACKED_SESSIONS);
1671
- const lines = await buildLiveLines(
1672
- client,
1673
- sessionID,
1674
- info.modelID,
1675
- info.providerID,
1676
- tokens.input,
1677
- contextTokens,
1678
- );
1679
- writeStateFile(
1680
- sessionID,
1681
- info.modelID,
1682
- info.providerID,
1683
- tokens.input,
1684
- contextTokens,
1685
- reasoning,
1686
- );
1687
- writeLog(lines);
1688
- }
1689
- } catch (err) {
1690
- logErr("live breakdown write failed", err);
1691
- }
1692
- },
1693
- };
1694
- }
1695
-
1696
- function lastKnownModel(sessionID) {
1697
- return lastKnownModelCache.get(sessionID) || "unknown";
1698
- }
1699
- function lastKnownProvider(sessionID) {
1700
- return lastKnownProviderCache.get(sessionID) || "";
1701
- }
1702
- function lastKnownInput(sessionID) {
1703
- return lastKnownInputCache.get(sessionID) || 0;
1704
- }
1705
- function lastKnownReasoning(sessionID) {
1706
- return lastKnownReasoningCache.get(sessionID) || 0;
1707
- }
1708
- function lastKnownCtx(sessionID) {
1709
- return lastKnownCtxCache.get(sessionID) || 0;
1710
- }
1711
-
1712
- // ---------------------------------------------------------------------------
1713
- // V2 (OpenCode >= 2.0.16) — context hook + event stream, no toasts.
1714
- // ---------------------------------------------------------------------------
1715
-
1716
- // Estimate the per-category breakdown directly from a V2 SessionContext.
1717
- // `context.messages` are @opencode/ai Message objects:
1718
- // { role, content: [ {type:"text",text} | {type:"media"} |
1719
- // {type:"tool-call",input} | {type:"tool-result"} |
1720
- // {type:"reasoning",text} | ... ] }
1721
- // `context.system` are SystemPart[] { type:"text", text }.
1722
- // `context.tools` is Record<name, { description, input: JsonSchema }>.
1723
- // As in V1, tool RESULTS are deliberately not counted (only call args), and
1724
- // every returned *Chars value is a TOKEN estimate (unicode heuristic).
1725
- function estimateBreakdownFromContext(context) {
1726
- let userChars = 0;
1727
- let assistantChars = 0;
1728
- let reasoningChars = 0;
1729
- let toolArgsChars = 0;
1730
-
1731
- const messages = Array.isArray(context?.messages) ? context.messages : [];
1732
- for (const msg of messages) {
1733
- const parts = Array.isArray(msg?.content) ? msg.content : [];
1734
- if (msg?.role === "user") {
1735
- for (const p of parts) {
1736
- if (p?.type === "text") userChars += estimateTokens(p.text);
1737
- }
1738
- } else if (msg?.role === "assistant") {
1739
- for (const p of parts) {
1740
- if (p?.type === "text") {
1741
- assistantChars += estimateTokens(p.text);
1742
- } else if (p?.type === "reasoning") {
1743
- reasoningChars += estimateTokens(p.text);
1744
- } else if (p?.type === "tool-call") {
1745
- toolArgsChars += estJson(p.input);
1746
- }
1747
- }
1748
- }
1749
- }
1750
-
1751
- let systemChars = 0;
1752
- const system = Array.isArray(context?.system) ? context.system : [];
1753
- for (const s of system) systemChars += estimateTokens(s?.text);
1754
-
1755
- let toolSchemasChars = 0;
1756
- const tools = context?.tools;
1757
- if (tools && typeof tools === "object") {
1758
- for (const t of Object.values(tools)) {
1759
- toolSchemasChars += estimateTokens(t?.description) + estJson(t?.input);
1760
- }
1761
- }
1762
-
1763
- return {
1764
- userChars,
1765
- assistantChars,
1766
- reasoningChars,
1767
- toolArgsChars,
1768
- systemChars,
1769
- toolSchemasChars,
1770
- };
1771
- }
1772
-
1773
- // V2 context hook handler: capture the final messages / system prompt / tool
1774
- // schemas + the request model. READ-ONLY — the context object is never mutated.
1775
- function onV2Context(context) {
1776
- try {
1777
- if (!context || typeof context !== "object") return;
1778
- const sid = context.sessionID;
1779
- if (!sid) return;
1780
-
1781
- const parts = estimateBreakdownFromContext(context);
1782
- breakdownCache.set(sid, {
1783
- ...parts,
1784
- capturedAt: Date.now(),
1785
- source: "context-hook",
1786
- });
1787
- pruneMap(breakdownCache, MAX_TRACKED_SESSIONS);
1788
-
1789
- const model = context.model;
1790
- if (model && typeof model === "object") {
1791
- if (typeof model.id === "string") lastKnownModelCache.set(sid, model.id);
1792
- if (typeof model.providerID === "string") {
1793
- lastKnownProviderCache.set(sid, model.providerID);
1794
- }
1795
- pruneMap(lastKnownModelCache, MAX_TRACKED_SESSIONS);
1796
- pruneMap(lastKnownProviderCache, MAX_TRACKED_SESSIONS);
1797
- }
1798
- } catch (err) {
1799
- logErr("v2 context hook failed", err);
1800
- }
1801
- }
1802
-
1803
- // ---------------------------------------------------------------------------
1804
- // V2 fallback: derive the message-based categories from the session's persisted
1805
- // message list when the context hook did NOT populate the cache for this
1806
- // session. This happens when the request was served by a DIFFERENT plugin
1807
- // instance (the public event stream is mirrored to every instance, but the
1808
- // breakdown cache is process-local) or when the hook did not fire at all.
1809
- //
1810
- // Only user / assistant / reasoning / tool-args can be derived from the
1811
- // persisted SessionMessageInfo[]: the ASSEMBLED system prompt and the tool
1812
- // schemas are exclusive to the context hook, so they stay null ("n/a" in the
1813
- // sidebar) unless the hook ran. Tool RESULTS are deliberately not counted
1814
- // (only call args), exactly like the hook / V1 estimator.
1815
- function estimateBreakdownFromClientMessages(messages) {
1816
- let userChars = 0;
1817
- let assistantChars = 0;
1818
- let reasoningChars = 0;
1819
- let toolArgsChars = 0;
1820
- for (const m of messages || []) {
1821
- if (!m || typeof m !== "object") continue;
1822
- if (m.type === "user") {
1823
- userChars += estimateTokens(m.text);
1824
- } else if (m.type === "assistant") {
1825
- const parts = Array.isArray(m.content) ? m.content : [];
1826
- for (const p of parts) {
1827
- if (p?.type === "text") {
1828
- assistantChars += estimateTokens(p.text);
1829
- } else if (p?.type === "reasoning") {
1830
- reasoningChars += estimateTokens(p.text);
1831
- } else if (p?.type === "tool") {
1832
- // state.input is a string while streaming; only count the resolved
1833
- // object (running/completed/error) to avoid partial counts.
1834
- const input = p?.state?.input;
1835
- if (input && typeof input === "object") toolArgsChars += estJson(input);
1836
- }
1837
- }
1838
- }
1839
- }
1840
- return {
1841
- userChars,
1842
- assistantChars,
1843
- reasoningChars,
1844
- toolArgsChars,
1845
- systemChars: null,
1846
- toolSchemasChars: null,
1847
- };
1848
- }
1849
-
1850
- // sessionID -> last time we hit the client session.context() fallback.
1851
- const v2ContextFetchTimes = new Map();
1852
- const V2_CONTEXT_FETCH_THROTTLE_MS = 5000; // min gap between fallback fetches
1853
- // Background fallback requests are fire-and-forget (see the callers in the
1854
- // event handlers): cap each at 3s so a slow/hung client cannot pin resources.
1855
- const V2_FALLBACK_TIMEOUT_MS = 3000;
1856
-
1857
- // Cumulative wall-clock budget for one /context-breakdown collection (root +
1858
- // every descendant, fetched in PARALLEL). Each per-session live lookup is
1859
- // additionally capped at V2_FALLBACK_TIMEOUT_MS, so the command costs about the
1860
- // per-session cap (not the sum) instead of N × 3s for N subagents. A session
1861
- // with no cached/snapshot categories whose bounded session.context lookup fails
1862
- // or never gets any budget is tagged "no-data": ctx/model/updatedAt still come
1863
- // from state.json / live, but the category cells stay n/a.
1864
- const COMMAND_COLLECT_BUDGET_MS = 3500;
1865
-
1866
- // `resume` for the full /context-breakdown command. resume:true admits the
1867
- // payload to the transcript AND wakes the session, so the agent echoes the table
1868
- // as a normal message that the Desktop renders in full (the notice chip only
1869
- // shows `description`). Set to false to fall back to a plain inbox notice if a
1870
- // given runtime renders the model answer worse than the notice.
1871
- const CONTEXT_BREAKDOWN_RESUME = true;
1872
-
1873
- // Fill breakdownCache for a session when the context hook has not already done
1874
- // so. Throttled, fault-tolerant, READ-ONLY. Hook data always wins.
1875
- async function ensureV2Breakdown(ctx, sessionID) {
1876
- if (!sessionID) return;
1877
- const cached = breakdownCache.get(sessionID);
1878
- if (cached && cached.source === "context-hook") return; // hook data wins
1879
- const now = Date.now();
1880
- if (
1881
- now - (v2ContextFetchTimes.get(sessionID) || 0) <
1882
- V2_CONTEXT_FETCH_THROTTLE_MS
1883
- ) {
1884
- return;
1885
- }
1886
- v2ContextFetchTimes.set(sessionID, now);
1887
- pruneMap(v2ContextFetchTimes, MAX_TRACKED_SESSIONS);
1888
- try {
1889
- const res = await withTimeout(
1890
- ctx.session.context({ sessionID }),
1891
- V2_FALLBACK_TIMEOUT_MS,
1892
- "session.context",
1893
- );
1894
- const msgs = Array.isArray(res) ? res : res?.data;
1895
- if (Array.isArray(msgs)) {
1896
- // Re-check AFTER the await: the context hook may have populated the cache
1897
- // while this fetch was in flight — hook data must win and must never be
1898
- // overwritten by a late fallback.
1899
- const latest = breakdownCache.get(sessionID);
1900
- if (!latest || latest.source !== "context-hook") {
1901
- breakdownCache.set(sessionID, {
1902
- ...estimateBreakdownFromClientMessages(msgs),
1903
- capturedAt: Date.now(),
1904
- source: "client-context",
1905
- });
1906
- pruneMap(breakdownCache, MAX_TRACKED_SESSIONS);
1907
- }
1908
- }
1909
- } catch (err) {
1910
- logErr("v2 session.context fallback failed", err);
1911
- }
1912
- // Opportunistically resolve the model: Desktop selects it AFTER
1913
- // session.created, so without this (or session.model.selected) a session can
1914
- // stay "unknown" even though its limit is resolvable.
1915
- if (
1916
- !lastKnownModelCache.has(sessionID) ||
1917
- !lastKnownProviderCache.has(sessionID)
1918
- ) {
1919
- try {
1920
- const info = await withTimeout(
1921
- ctx.session.get({ sessionID }),
1922
- V2_FALLBACK_TIMEOUT_MS,
1923
- "session.get",
1924
- );
1925
- const model = info?.model ?? info?.data?.model;
1926
- if (model && typeof model === "object") {
1927
- if (typeof model.id === "string") lastKnownModelCache.set(sessionID, model.id);
1928
- if (typeof model.providerID === "string") {
1929
- lastKnownProviderCache.set(sessionID, model.providerID);
1930
- }
1931
- pruneMap(lastKnownModelCache, MAX_TRACKED_SESSIONS);
1932
- pruneMap(lastKnownProviderCache, MAX_TRACKED_SESSIONS);
1933
- }
1934
- } catch (err) {
1935
- logErr("v2 session.get model fallback failed", err);
1936
- }
1937
- }
1938
- }
1939
-
1940
- // V2 model limits: effective values from ctx.model.list(), cached + gated.
1941
- // { data: ModelInfo[] } where ModelInfo = { modelID, providerID, limit:{context} }.
1942
- async function ensureModelLimits(ctx) {
1943
- const now = Date.now();
1944
- if (now - v2LimitsLoadedAt < PROVIDERS_TTL_MS) return; // fresh success
1945
- // Recent failure: back off exponentially (30s, 60s, 120s … capped at 5 min)
1946
- // so a registry that is slow to expose the provider is retried without
1947
- // hammering it, while a one-off blip still recovers quickly.
1948
- const failBackoff = Math.min(
1949
- PROVIDERS_FAIL_TTL_MS * Math.pow(2, Math.max(0, v2LimitsFailCount - 1)),
1950
- V2_LIMITS_MAX_BACKOFF_MS,
1951
- );
1952
- if (now - v2LimitsFailAt < failBackoff) return; // recent failure
1953
- if (v2LimitsInFlight) return v2LimitsInFlight; // dedup parallel callers
1954
- v2LimitsInFlight = (async () => {
1955
- try {
1956
- const res = await withTimeout(
1957
- ctx.model.list(),
1958
- V2_MODEL_FETCH_TIMEOUT_MS,
1959
- "model.list",
1960
- );
1961
- const models = Array.isArray(res) ? res : res?.data;
1962
- if (!Array.isArray(models)) {
1963
- v2LimitsFailCount++;
1964
- v2LimitsFailAt = Date.now(); // malformed payload -> retry soon
1965
- const seeded = hydrateModelLimitsFromState();
1966
- logErr(
1967
- "model.list returned no model array — limits unavailable, will retry",
1968
- { payloadType: typeof res, hydratedFromState: seeded },
1969
- );
1970
- return;
1971
- }
1972
- let found = 0;
1973
- for (const m of models) {
1974
- const modelID = m?.modelID ?? m?.id;
1975
- const providerID =
1976
- typeof m?.providerID === "string" && m.providerID
1977
- ? m.providerID
1978
- : typeof m?.provider?.id === "string"
1979
- ? m.provider.id
1980
- : "";
1981
- const key = modelKey(providerID, modelID);
1982
- const lim = m?.limit;
1983
- if (!key || !lim || typeof lim !== "object") continue;
1984
- const context =
1985
- typeof lim.context === "number" && lim.context > 0 ? lim.context : null;
1986
- const input =
1987
- typeof lim.input === "number" && lim.input > 0 ? lim.input : null;
1988
- const output =
1989
- typeof lim.output === "number" && lim.output > 0 ? lim.output : null;
1990
- if (context == null && input == null) continue;
1991
- const prevRec = modelLimits.get(key);
1992
- setModelLimit(providerID, modelID, {
1993
- context,
1994
- input,
1995
- output,
1996
- reserved:
1997
- typeof m?.compaction?.reserved === "number"
1998
- ? m.compaction.reserved
1999
- : (prevRec?.reserved ?? null),
2000
- });
2001
- found++;
2002
- }
2003
- // An empty / limit-less payload right after boot (registry not ready yet)
2004
- // must NOT be cached as success, or limits would stay unknown for the
2005
- // full TTL — treat it as a soft failure and retry after the fail gate.
2006
- if (found > 0) {
2007
- v2LimitsLoadedAt = Date.now();
2008
- v2LimitsFailCount = 0; // recovered
2009
- } else {
2010
- // Soft failure: the registry answered but carried no usable limit for
2011
- // any model (provider not registered yet, or `limit` absent). Log WHY
2012
- // once per backoff window, and fall back to the shared snapshot so
2013
- // denominators do not vanish meanwhile.
2014
- const withLimit = models.filter(
2015
- (m) => m?.limit && typeof m.limit === "object",
2016
- ).length;
2017
- const withProvider = models.filter(
2018
- (m) => m?.providerID || m?.provider?.id,
2019
- ).length;
2020
- const seeded = hydrateModelLimitsFromState();
2021
- v2LimitsFailCount++;
2022
- v2LimitsFailAt = Date.now();
2023
- logErr(
2024
- "model.list yielded 0 usable limits — retrying",
2025
- { models: models.length, withLimit, withProvider, hydratedFromState: seeded },
2026
- );
2027
- }
2028
- } catch (err) {
2029
- v2LimitsFailCount++;
2030
- v2LimitsFailAt = Date.now(); // failed attempt -> backoff gate
2031
- const seeded = hydrateModelLimitsFromState();
2032
- logErr(
2033
- `model.list failed (hydrated ${seeded} limit(s) from state.json)`,
2034
- err,
2035
- );
2036
- } finally {
2037
- v2LimitsInFlight = null;
2038
- }
2039
- })();
2040
- return v2LimitsInFlight;
2041
- }
2042
-
2043
- // V2 subagent aggregation: children are discovered from session.created
2044
- // (parentID), their totals accumulated from session.step.ended. No
2045
- // session.children/messages API needed. Synchronous (in-memory only).
2046
- function aggregateSubagentsV2(sessionID) {
2047
- const result = { count: 0, input: 0, output: 0, reasoning: 0, perChild: [] };
2048
- for (const [childID, parentID] of sessionParentCache) {
2049
- if (parentID !== sessionID) continue;
2050
- result.count++;
2051
- const t = sessionTotals.get(childID);
2052
- if (t) {
2053
- result.input += t.input || 0;
2054
- result.output += t.output || 0;
2055
- result.reasoning += t.reasoning || 0;
2056
- const lim = getModelLimit(t.providerID, t.modelID);
2057
- const ctxTokens = typeof t.ctx === "number" ? t.ctx : 0;
2058
- result.perChild.push({
2059
- id: childID,
2060
- input: ctxTokens,
2061
- limit: lim,
2062
- ratio: lim ? ctxTokens / lim : null,
2063
- });
2064
- } else {
2065
- result.perChild.push({ id: childID, input: 0, limit: null, ratio: null });
2066
- }
2067
- }
2068
- return result;
2069
- }
2070
-
2071
- // V2: assemble the live breakdown lines (no client, no fallback fetch —
2072
- // the context hook fills breakdownCache on every request).
2073
- function buildLiveLinesV2(sessionID, modelID, providerID, inputTokens, ctxTokens, reasoningTokens) {
2074
- const lines = [];
2075
- const ts = new Date().toISOString();
2076
- const limit = getModelLimit(providerID, modelID);
2077
- const usableInfo = getUsableContext(providerID, modelID);
2078
- const total = typeof ctxTokens === "number" && ctxTokens > 0 ? ctxTokens : inputTokens;
2079
- const denom =
2080
- usableInfo != null
2081
- ? usableInfo.usable
2082
- : limit != null && limit > 0
2083
- ? limit
2084
- : null;
2085
- const pct =
2086
- denom != null ? ` (${((total / denom) * 100).toFixed(1)}%)` : "";
2087
-
2088
- lines.push(
2089
- `[${ts}] session=${sessionID} model=${modelID} ctx=${fmt(total)}/${denom != null ? fmt(denom) : "?"}${pct} count=${fmt(total)} usable=${usableInfo != null ? fmt(usableInfo.usable) : "?"} limit=${limit != null ? fmt(limit) : "?"} maxOutput=${usableInfo != null ? fmt(usableInfo.maxOutput) : "?"} reserved=${usableInfo != null ? fmt(usableInfo.reserved) : "?"} input=${fmt(inputTokens)}`,
2090
- );
2091
-
2092
- const bd = breakdownCache.get(sessionID);
2093
- const source = bd?.source || "none";
2094
- const rt = typeof reasoningTokens === "number" ? reasoningTokens : 0;
2095
-
2096
- const sumEstimates = (bd?.userChars || 0) +
2097
- (bd?.assistantChars || 0) +
2098
- (bd?.reasoningChars || 0) +
2099
- (bd?.toolArgsChars || 0) +
2100
- (bd?.systemChars || 0) +
2101
- (bd?.toolSchemasChars || 0);
2102
- const other = Math.max(0, inputTokens - sumEstimates);
2103
-
2104
- if (bd) {
2105
- lines.push(` user ${fmt(bd.userChars || 0)} (est tokens)`);
2106
- lines.push(` assistant ${fmt(bd.assistantChars || 0)} (est tokens)`);
2107
- const reasoningNote = rt > 0 ? ` (exact ${fmt(rt)})` : "";
2108
- lines.push(` reasoning ${fmt(bd.reasoningChars || 0)} (est tokens)${reasoningNote}`);
2109
- lines.push(` tool args ${fmt(bd.toolArgsChars || 0)} (est tokens, input only)`);
2110
- lines.push(
2111
- bd.systemChars != null
2112
- ? ` system ${fmt(bd.systemChars)} (est tokens)`
2113
- : ` system n/a (hook не сработал)`,
2114
- );
2115
- lines.push(
2116
- bd.toolSchemasChars != null
2117
- ? ` tool schemas ${fmt(bd.toolSchemasChars)} (est tokens)`
2118
- : ` tool schemas n/a`,
2119
- );
2120
- } else {
2121
- lines.push(` user n/a (no breakdown captured yet)`);
2122
- lines.push(` assistant n/a`);
2123
- lines.push(` reasoning n/a`);
2124
- lines.push(` tool args n/a`);
2125
- lines.push(` system n/a (hook не сработал)`);
2126
- lines.push(` tool schemas n/a`);
2127
- }
2128
- lines.push(` other ${fmt(other)} (= input - sum of estimates)`);
2129
- lines.push(` source ${source}`);
2130
-
2131
- try {
2132
- const sub = aggregateSubagentsV2(sessionID);
2133
- if (sub.count > 0) {
2134
- const ratios = (sub.perChild || [])
2135
- .map((c) => c?.ratio)
2136
- .filter((r) => typeof r === "number");
2137
- const worst =
2138
- ratios.length > 0
2139
- ? ` worst=${(Math.max(...ratios) * 100).toFixed(0)}%`
2140
- : "";
2141
- lines.push(
2142
- ` subagents ${sub.count} session(s): in=${fmt(sub.input)} out=${fmt(sub.output)} r=${fmt(sub.reasoning)}${worst}`,
2143
- );
2144
- } else {
2145
- lines.push(` subagents 0`);
2146
- }
2147
- } catch (err) {
2148
- logErr("v2 subagent aggregation failed", err);
2149
- lines.push(` subagents n/a`);
2150
- }
2151
-
2152
- return lines;
2153
- }
2154
-
2155
- // Append a note to the persisted final-summaries section (claimed once across
2156
- // instances). Never throws.
2157
- function pushFinalSummary(claimKey, summaryLines) {
2158
- try {
2159
- if (!claimOnce(claimKey, DEDUP_DIR)) return;
2160
- finalSummaries.push(summaryLines.join("\n"));
2161
- if (finalSummaries.length > MAX_FINAL_SUMMARIES) {
2162
- finalSummaries.splice(0, finalSummaries.length - MAX_FINAL_SUMMARIES);
2163
- }
2164
- writeLog([]); // persist final summaries
2165
- } catch (err) {
2166
- logErr("pushFinalSummary failed", err);
2167
- }
2168
- }
2169
-
2170
- // V2 event handler. `event` is a V2Event ({ type, data, ... }).
2171
- async function handleV2Event(ctx, event) {
2172
- if (!event || typeof event.type !== "string") return;
2173
-
2174
- // DEBUG tap (fault-tolerant, off via flag).
2175
- debugEvent(event);
2176
-
2177
- // --- session lifecycle: parent links + model hints ---
2178
- if (event.type === "session.created") {
2179
- const data = event.data || {};
2180
- const sid = data.sessionID;
2181
- if (!sid) return;
2182
- const parentID = data.parentID || null;
2183
- // sessionParentCache is the durable parent link used when WRITING the
2184
- // state.json entry (writeStateFile); discovery itself reads the persisted
2185
- // parentID chain — see collectDescendantSessionIDs.
2186
- sessionParentCache.set(sid, parentID);
2187
- pruneMap(sessionParentCache, MAX_TRACKED_SESSIONS);
2188
- if (typeof data.agent === "string" && data.agent) {
2189
- sessionAgentCache.set(sid, data.agent);
2190
- pruneMap(sessionAgentCache, MAX_TRACKED_SESSIONS);
2191
- }
2192
- if (data.model && typeof data.model === "object") {
2193
- if (typeof data.model.id === "string") lastKnownModelCache.set(sid, data.model.id);
2194
- if (typeof data.model.providerID === "string") {
2195
- lastKnownProviderCache.set(sid, data.model.providerID);
2196
- }
2197
- pruneMap(lastKnownModelCache, MAX_TRACKED_SESSIONS);
2198
- pruneMap(lastKnownProviderCache, MAX_TRACKED_SESSIONS);
2199
- }
2200
- return;
2201
- }
2202
-
2203
- // Model chosen after session creation (the normal Desktop flow: the user
2204
- // picks the model in the UI). Without this the session stays "unknown"
2205
- // because session.created carries no model and session.step.ended has no
2206
- // model field.
2207
- if (event.type === "session.model.selected") {
2208
- const d = event.data || {};
2209
- const sid = d.sessionID;
2210
- if (!sid) return;
2211
- if (d.model && typeof d.model === "object") {
2212
- if (typeof d.model.id === "string") lastKnownModelCache.set(sid, d.model.id);
2213
- if (typeof d.model.providerID === "string") {
2214
- lastKnownProviderCache.set(sid, d.model.providerID);
2215
- }
2216
- pruneMap(lastKnownModelCache, MAX_TRACKED_SESSIONS);
2217
- pruneMap(lastKnownProviderCache, MAX_TRACKED_SESSIONS);
2218
- }
2219
- return;
2220
- }
2221
-
2222
- if (event.type === "session.deleted") {
2223
- const sid = event.data?.sessionID;
2224
- if (!sid) return;
2225
- // Discovery reads the persisted parentID chain, so a deleted session drops
2226
- // out of the table as soon as its state.json entry is gone (or, while the
2227
- // stale entry lingers, via the phantom filter — a deleted session has no
2228
- // step). No dedicated in-memory index to clean up.
2229
- clearSessionTracking(sid);
2230
- return;
2231
- }
2232
-
2233
- if (event.type === "session.compacted") {
2234
- const sid = event.data?.sessionID;
2235
- if (!sid) return;
2236
- try {
2237
- const lines = buildLiveLinesV2(
2238
- sid,
2239
- lastKnownModel(sid),
2240
- lastKnownProvider(sid),
2241
- lastKnownInput(sid),
2242
- lastKnownCtx(sid),
2243
- lastKnownReasoning(sid),
2244
- );
2245
- writeStateFile(
2246
- sid,
2247
- lastKnownModel(sid),
2248
- lastKnownProvider(sid),
2249
- lastKnownInput(sid),
2250
- lastKnownCtx(sid),
2251
- lastKnownReasoning(sid),
2252
- );
2253
- pushFinalSummary(
2254
- `compacted:${event.id ?? sid}`,
2255
- [
2256
- `[${new Date().toISOString()}] COMPACTED session=${sid} (auto — возможно, контекст был переполнен)`,
2257
- ...lines.slice(1),
2258
- ],
2259
- );
2260
- } catch (err) {
2261
- logErr("v2 session.compacted handling failed", err);
2262
- }
2263
- clearSessionTracking(sid, true);
2264
- return;
2265
- }
2266
-
2267
- if (event.type === "session.idle") {
2268
- const sid = event.data?.sessionID;
2269
- if (!sid) return;
2270
- try {
2271
- // Fire-and-forget: the client-API fallback must NOT block this
2272
- // instance's event loop (it would delay every other session's events).
2273
- // The result is picked up by a later state write; the 5s throttle bounds
2274
- // the cost. Never rejects.
2275
- void ensureV2Breakdown(ctx, sid).catch(() => {});
2276
- const lines = buildLiveLinesV2(
2277
- sid,
2278
- lastKnownModel(sid),
2279
- lastKnownProvider(sid),
2280
- lastKnownInput(sid),
2281
- lastKnownCtx(sid),
2282
- lastKnownReasoning(sid),
2283
- );
2284
- writeStateFile(
2285
- sid,
2286
- lastKnownModel(sid),
2287
- lastKnownProvider(sid),
2288
- lastKnownInput(sid),
2289
- lastKnownCtx(sid),
2290
- lastKnownReasoning(sid),
2291
- );
2292
- pushFinalSummary(`final:${event.id ?? sid}`, [
2293
- `[${new Date().toISOString()}] FINAL session=${sid}`,
2294
- ...lines.slice(1),
2295
- ]);
2296
- } catch (err) {
2297
- logErr("v2 final summary on idle failed", err);
2298
- }
2299
- clearSessionTracking(sid);
2300
- return;
2301
- }
2302
-
2303
- // --- finished LLM step: tokens + live breakdown snapshot ---
2304
- if (event.type === "session.step.ended") {
2305
- const data = event.data || {};
2306
- const sid = data.sessionID;
2307
- if (!sid) return;
2308
- const t = data.tokens || {};
2309
- const input = typeof t.input === "number" ? t.input : 0;
2310
- const output = typeof t.output === "number" ? t.output : 0;
2311
- const reasoning = typeof t.reasoning === "number" ? t.reasoning : 0;
2312
- const contextTokens = tokenCountOf(t);
2313
-
2314
- lastKnownInputCache.set(sid, input);
2315
- lastKnownCtxCache.set(sid, contextTokens);
2316
- lastKnownReasoningCache.set(sid, reasoning);
2317
- if (!lastKnownModelCache.has(sid) && data.model) {
2318
- // Some builds put the model on the step payload; harmless when absent.
2319
- if (typeof data.model.id === "string") lastKnownModelCache.set(sid, data.model.id);
2320
- if (typeof data.model.providerID === "string") {
2321
- lastKnownProviderCache.set(sid, data.model.providerID);
2322
- }
2323
- }
2324
- pruneMap(lastKnownInputCache, MAX_TRACKED_SESSIONS);
2325
- pruneMap(lastKnownCtxCache, MAX_TRACKED_SESSIONS);
2326
- pruneMap(lastKnownReasoningCache, MAX_TRACKED_SESSIONS);
2327
- pruneMap(lastKnownModelCache, MAX_TRACKED_SESSIONS);
2328
- pruneMap(lastKnownProviderCache, MAX_TRACKED_SESSIONS);
2329
-
2330
- // Accumulate per-session totals for parent subagent roll-up.
2331
- const tot = sessionTotals.get(sid) || {
2332
- input: 0,
2333
- output: 0,
2334
- reasoning: 0,
2335
- ctx: 0,
2336
- modelID: null,
2337
- providerID: "",
2338
- at: 0,
2339
- };
2340
- tot.input += input;
2341
- tot.output += output;
2342
- tot.reasoning += reasoning;
2343
- tot.ctx = contextTokens;
2344
- tot.modelID = lastKnownModel(sid);
2345
- tot.providerID = lastKnownProvider(sid);
2346
- tot.at = Date.now();
2347
- sessionTotals.set(sid, tot);
2348
- pruneMap(sessionTotals, MAX_TRACKED_SESSIONS);
2349
-
2350
- // Ensure limits are available (fault-tolerant; await is cheap after warm).
2351
- try {
2352
- await ensureModelLimits(ctx);
2353
- } catch {
2354
- // ignore — absolute token figures only
2355
- }
2356
-
2357
- // Make sure a breakdown exists for this session even if the context hook
2358
- // did not fire here (cross-instance mirror / hook gap). Fire-and-forget on
2359
- // purpose: awaiting it would serialize this instance's event handling
2360
- // behind up to the full client timeout. The cached result is written on the
2361
- // NEXT event; the 5s throttle bounds the cost. Never rejects.
2362
- void ensureV2Breakdown(ctx, sid).catch(() => {});
2363
-
2364
- const now = Date.now();
2365
- const lastWrite = lastBdWrite.get(sid) || 0;
2366
- if (now - lastWrite >= BREAKDOWN_THROTTLE_MS) {
2367
- lastBdWrite.set(sid, now);
2368
- pruneMap(lastBdWrite, MAX_TRACKED_SESSIONS);
2369
- try {
2370
- const lines = buildLiveLinesV2(
2371
- sid,
2372
- lastKnownModel(sid),
2373
- lastKnownProvider(sid),
2374
- input,
2375
- contextTokens,
2376
- reasoning,
2377
- );
2378
- writeStateFile(
2379
- sid,
2380
- lastKnownModel(sid),
2381
- lastKnownProvider(sid),
2382
- input,
2383
- contextTokens,
2384
- reasoning,
2385
- );
2386
- writeLog(lines);
2387
- } catch (err) {
2388
- logErr("v2 live breakdown write failed", err);
2389
- }
2390
- }
2391
- return;
2392
- }
2393
-
2394
- // --- failed step / execution: persist a claimed one-line note ---
2395
- if (
2396
- event.type === "session.step.failed" ||
2397
- event.type === "session.execution.failed" ||
2398
- event.type === "session.execution.interrupted"
2399
- ) {
2400
- const data = event.data || {};
2401
- const sid = data.sessionID || "?";
2402
- const interrupted = event.type === "session.execution.interrupted";
2403
- const err = data.error || {};
2404
- const name = interrupted
2405
- ? "Interrupted"
2406
- : typeof err.type === "string"
2407
- ? err.type
2408
- : "session error";
2409
- const detail = String(err.message || data.reason || "").slice(0, 200);
2410
- const bucket = Math.floor(Date.now() / ERROR_TOAST_DEDUP_MS);
2411
- pushFinalSummary(`err:${sid}:${name}:${bucket}`, [
2412
- `[${new Date().toISOString()}] ERROR session=${sid} ${name}${detail ? `: ${detail}` : ""}`,
2413
- ]);
2414
- }
2415
- }
2416
-
2417
- // ---------------------------------------------------------------------------
2418
- // V2 slash commands: /context and /context-breakdown
2419
- // ---------------------------------------------------------------------------
2420
- // /context prints a 3-line summary of the CURRENT session only (cache +
2421
- // state.json, no subagents, no RPC); /context-breakdown prints a compact
2422
- // markdown table for the CURRENT session plus EVERY descendant (subagent)
2423
- // session. Both deliver via ctx.session.synthetic({sessionID, text, ...}):
2424
- // resume:true -> wake / agent turn (the model renders the table);
2425
- // resume:false -> a durable notice, no LLM call. Works in the Desktop v2 app
2426
- // (which has no TUI slots, issue #49380) and in the TUI. Registered only on
2427
- // the V2 path.
2428
- //
2429
- // Session resolution cascade (per task): in-memory breakdownCache -> the
2430
- // state.json snapshot -> a throttled/3s ctx.session.context() fallback. The
2431
- // fallback cannot see the assembled system prompt or the tool schemas, so those
2432
- // two cells stay "n/a" and the row's source is labelled honestly.
2433
-
2434
- // Read the whole state.json snapshot ({ sessionID: entry }) or {} on any error.
2435
- function readStateSnapshot() {
2436
- try {
2437
- const all = JSON.parse(readFileSync(STATE_FILE, "utf8"));
2438
- return all && typeof all === "object" && !Array.isArray(all) ? all : {};
2439
- } catch {
2440
- return {};
2441
- }
2442
- }
2443
-
2444
- // Seed `modelLimits` from previously persisted state.json entries. state.json is
2445
- // a SHARED cross-instance snapshot rewritten at every live step, so it carries a
2446
- // model's window even when THIS instance's ctx.model.list() came back empty (a
2447
- // cold instance, or one whose model registry did not expose the provider).
2448
- // Without this, a transient list miss degraded every denominator to "?" — and
2449
- // because writeStateFile used to rewrite usable/limit from the (empty) in-memory
2450
- // map, the degradation became permanent.
2451
- //
2452
- // The snapshot also holds history: during an earlier outage some instances wrote
2453
- // a WRONG usable window (e.g. 168000 instead of 1015808). A naive
2454
- // first-match seed would then re-inject that stale garbage. Therefore, per
2455
- // `<provider>:<model>`:
2456
- // * candidates are sanity-filtered (drop `usable >= limit`, `usable <= 0`);
2457
- // * when any candidate carries a precise `usable`, only those are considered;
2458
- // * the FRESHEST (max `updatedAt`) candidate wins;
2459
- // * a divergent spread (max > 3× min usable) is logged for diagnosis.
2460
- // Strictly additive: real in-memory records always win (never overwritten).
2461
- // Returns the number of records seeded.
2462
- function hydrateModelLimitsFromState() {
2463
- try {
2464
- const all = readStateSnapshot();
2465
- // Group candidate entries by key first, so "freshest" is decided against
2466
- // ALL records of that model — not the first one encountered.
2467
- const byKey = new Map(); // key -> [ { usable, limit, updatedAt } ]
2468
- for (const entry of Object.values(all)) {
2469
- const providerID =
2470
- typeof entry?.providerID === "string" ? entry.providerID : "";
2471
- const modelID = entry?.model;
2472
- const key = modelKey(providerID, modelID);
2473
- if (!key || !modelID || modelID === "unknown") continue;
2474
- if (modelLimits.has(key)) continue; // a real in-memory record always wins
2475
- const usable =
2476
- typeof entry?.usable === "number" && entry.usable > 0
2477
- ? entry.usable
2478
- : null;
2479
- const limit =
2480
- typeof entry?.limit === "number" && entry.limit > 0 ? entry.limit : null;
2481
- if (usable == null && limit == null) continue;
2482
- let arr = byKey.get(key);
2483
- if (!arr) {
2484
- arr = [];
2485
- byKey.set(key, arr);
2486
- }
2487
- arr.push({
2488
- usable,
2489
- limit,
2490
- updatedAt: typeof entry?.updatedAt === "string" ? entry.updatedAt : "",
2491
- });
2492
- }
2493
-
2494
- let added = 0;
2495
- for (const [key, candidates] of byKey) {
2496
- // (b) Sanity: drop impossible records (usable >= limit, usable <= 0).
2497
- // Candidates without a usable (context-only) are kept as-is.
2498
- const sane = candidates.filter(
2499
- (c) =>
2500
- c.usable == null ||
2501
- (c.usable > 0 && (c.limit == null || c.usable <= c.limit)),
2502
- );
2503
- if (sane.length === 0) continue; // every record was impossible -> skip
2504
-
2505
- // (a) Prefer the precise variant (a recorded usable) when any exists.
2506
- const precise = sane.filter((c) => c.usable != null);
2507
- const pool = precise.length > 0 ? precise : sane;
2508
-
2509
- // (1) Freshest wins (ISO timestamps compare lexicographically).
2510
- let best = pool[0];
2511
- for (const c of pool) {
2512
- if (String(c.updatedAt) > String(best.updatedAt)) best = c;
2513
- }
2514
-
2515
- // (c) Diagnostic: a >3× spread means the snapshot is polluted by a
2516
- // limited/fallback instance — log the numbers once for this model.
2517
- const usables = pool.map((c) => c.usable).filter((u) => u != null);
2518
- if (usables.length > 1) {
2519
- const max = Math.max(...usables);
2520
- const min = Math.min(...usables);
2521
- if (min > 0 && max / min > 3) {
2522
- logErr(
2523
- `limit seed spread for ${key} — using freshest`,
2524
- { min, max, candidates: pool.length, chosen: best.usable ?? best.limit },
2525
- );
2526
- }
2527
- }
2528
-
2529
- // Build the record: precise usable-as-input when known (so getUsableContext
2530
- // re-derives EXACTLY the persisted window), else the raw context window.
2531
- let rec = null;
2532
- if (best.usable != null) {
2533
- rec = { context: best.limit, input: best.usable, output: null, reserved: 0 };
2534
- } else if (best.limit != null) {
2535
- rec = { context: best.limit, input: null, output: null, reserved: null };
2536
- }
2537
- if (rec == null) continue;
2538
- modelLimits.set(key, rec);
2539
- added++;
2540
- // (3) One seed line per model: chosen value + provenance.
2541
- console.log(
2542
- `[context-indicator] limit seed ${key} -> usable=${
2543
- best.usable != null ? best.usable : best.limit
2544
- } (from ${best.updatedAt || "unknown"}, ${pool.length} candidates)`,
2545
- );
2546
- }
2547
- return added;
2548
- } catch {
2549
- return 0;
2550
- }
2551
- }
2552
-
2553
- // True when a state.json entry carries no measured tokens at all: a session
2554
- // registered (session.created) but with no served step. `writeStateFile` always
2555
- // persists `categories` as an object, so the emptiness test must SUM those
2556
- // fields — a missing/`undefined` categories must not be the only trigger.
2557
- // Note: `system` / `toolSchemas` may legitimately be null (hook-only), so they
2558
- // are coerced with `|| 0`.
2559
- function isEmptyStateEntry(entry) {
2560
- const c = entry?.categories || {};
2561
- const sum =
2562
- (c.user || 0) +
2563
- (c.assistant || 0) +
2564
- (c.reasoning || 0) +
2565
- (c.toolArgs || 0) +
2566
- (c.system || 0) +
2567
- (c.toolSchemas || 0) +
2568
- (c.other || 0);
2569
- return (
2570
- sum === 0 &&
2571
- (!entry?.ctx || entry.ctx === 0) &&
2572
- (!entry?.input || entry.input === 0)
2573
- );
2574
- }
2575
-
2576
- // ALL descendant session IDs of `rootID` (breadth-first over the parentID chain
2577
- // in the state.json snapshot), de-duplicated. The snapshot is the ONLY source:
2578
- // each entry is keyed by its own sessionID and carries the parentID recorded
2579
- // when it was written, so the chain is root-consistent — entries of OTHER roots
2580
- // are unreachable from `rootID` (their parentID points at their own root). The
2581
- // earlier cross-root leakage came from the in-memory index, which is no longer
2582
- // consulted here.
2583
- //
2584
- // The BFS visits every level (subagents of subagents included). A phantom node
2585
- // (no tokens, see isEmptyStateEntry) is never emitted, but traversal still
2586
- // descends through it so real grandchildren behind a phantom parent are found.
2587
- // `seen` guards against cycles (parentID loops) and double-listing.
2588
- function collectDescendantSessionIDs(rootID, state) {
2589
- const seen = new Set([rootID]);
2590
- const out = [];
2591
- const queue = [rootID];
2592
- // Index the snapshot by parentID once (O(n)) instead of an O(n) scan per
2593
- // visited node.
2594
- const byParent = new Map();
2595
- for (const [id, entry] of Object.entries(state || {})) {
2596
- const pid = entry?.parentID;
2597
- if (!pid) continue;
2598
- let set = byParent.get(pid);
2599
- if (!set) {
2600
- set = new Set();
2601
- byParent.set(pid, set);
2602
- }
2603
- set.add(id);
2604
- }
2605
- while (queue.length > 0) {
2606
- const cur = queue.shift();
2607
- const kids = byParent.get(cur);
2608
- if (!kids) continue;
2609
- for (const c of kids) {
2610
- if (!c || seen.has(c)) continue; // cycle + dedup guard
2611
- seen.add(c);
2612
- if (!isEmptyStateEntry(state[c])) out.push(c);
2613
- queue.push(c); // descend through phantom parents too
2614
- }
2615
- }
2616
- return out;
2617
- }
2618
-
2619
- // Normalise a breakdown record (cache or state entry) into the 7 categories.
2620
- // `inputTokens` is used only for the residual "other".
2621
- function breakdownCategories(rec, inputTokens) {
2622
- const user = rec?.userChars ?? rec?.user ?? 0;
2623
- const assistant = rec?.assistantChars ?? rec?.assistant ?? 0;
2624
- const reasoning = rec?.reasoningChars ?? rec?.reasoning ?? 0;
2625
- const toolArgs = rec?.toolArgsChars ?? rec?.toolArgs ?? 0;
2626
- const system = rec?.systemChars !== undefined ? rec.systemChars : rec?.system ?? null;
2627
- const toolSchemas =
2628
- rec?.toolSchemasChars !== undefined ? rec.toolSchemasChars : rec?.toolSchemas ?? null;
2629
- const sum =
2630
- user + assistant + reasoning + toolArgs + (system || 0) + (toolSchemas || 0);
2631
- const other = Math.max(0, (inputTokens || 0) - sum);
2632
- return { user, assistant, reasoning, toolArgs, system, toolSchemas, other };
2633
- }
2634
-
2635
- // Short source tag for the table (kept tiny on purpose).
2636
- function sourceTag(source) {
2637
- switch (source) {
2638
- case "context-hook":
2639
- return "live";
2640
- case "client-context":
2641
- return "fallback";
2642
- case "snapshot":
2643
- return "snap";
2644
- case "no-data":
2645
- return "no-data";
2646
- default:
2647
- return source || "none";
2648
- }
2649
- }
2650
-
2651
- function timeOnly(iso) {
2652
- if (!iso) return "-";
2653
- try {
2654
- const d = new Date(iso);
2655
- if (Number.isNaN(d.getTime())) return "-";
2656
- return d.toTimeString().slice(0, 8); // HH:MM:SS
2657
- } catch {
2658
- return "-";
2659
- }
2660
- }
2661
-
2662
- // Resolve one session's report: totals, model, categories + honest source.
2663
- // `deadline` is the shared wall-clock budget for the whole command collection
2664
- // (see commandContextBreakdown): the per-session live lookups are capped by
2665
- // whatever remains of it and skipped once it is exhausted. A session that ends
2666
- // up with no category data is tagged "no-data" (see the branch below).
2667
- async function collectSessionReport(ctx, sessionID, state, deadline) {
2668
- const entry = state?.[sessionID] || null;
2669
- const bd = breakdownCache.get(sessionID) || null;
2670
-
2671
- const remaining = Math.max(0, (deadline || 0) - Date.now());
2672
- const budget = Math.min(V2_FALLBACK_TIMEOUT_MS, remaining);
2673
-
2674
- // The attribution/model caches survive across requests for the lifetime of a
2675
- // plugin instance. When cold — and while budget remains — resolve the session
2676
- // live so the [sub:<agent>] attribution and the model stay correct even if
2677
- // state.json is stale. ParentID comes from state.json ONLY (entry?.parentID)
2678
- // so the table is root-consistent; in-memory sessionParentCache is cross-session
2679
- // and must NOT be used for attribution.
2680
- const needEnrich =
2681
- !sessionAgentCache.has(sessionID) ||
2682
- lastKnownModel(sessionID) === "unknown";
2683
-
2684
- // Fallback categories only when neither the live cache nor a state snapshot
2685
- // has them: derive user/assistant/reasoning/tool-args from the persisted
2686
- // message list (system/tool-schemas stay null there).
2687
- const needFallback = !bd && !entry?.categories;
2688
-
2689
- // Enrichment and the context fallback run CONCURRENTLY, both bounded by the
2690
- // shared budget. Non-fatal: any failure resolves to null and keeps whatever
2691
- // the cache / state.json already provides.
2692
- const [live, contextMsgs] = await Promise.all([
2693
- needEnrich && budget > 0
2694
- ? withTimeout(ctx.session.get({ sessionID }), budget, "session.get").then(
2695
- (info) => info?.data ?? info ?? null,
2696
- (err) => {
2697
- logErr(`context-breakdown: session.get enrichment failed for ${sessionID}`, err);
2698
- return null;
2699
- },
2700
- )
2701
- : null,
2702
- needFallback && budget > 0
2703
- ? withTimeout(ctx.session.context({ sessionID }), budget, "session.context").then(
2704
- (res) => (Array.isArray(res) ? res : res?.data),
2705
- (err) => {
2706
- logErr(`context-breakdown: session.context fallback failed for ${sessionID}`, err);
2707
- return null;
2708
- },
2709
- )
2710
- : null,
2711
- ]);
2712
-
2713
- let categories = null;
2714
- let source = "none";
2715
- if (bd) {
2716
- categories = breakdownCategories(bd, lastKnownInput(sessionID) || entry?.input || 0);
2717
- source = bd.source || "live";
2718
- } else if (entry?.categories) {
2719
- categories = entry.categories;
2720
- source = "snapshot";
2721
- } else if (Array.isArray(contextMsgs)) {
2722
- categories = breakdownCategories(
2723
- estimateBreakdownFromClientMessages(contextMsgs),
2724
- 0,
2725
- );
2726
- source = "client-context";
2727
- } else if (needFallback) {
2728
- // No live cache, no state.json categories, and the bounded session.context
2729
- // fallback produced no usable messages (it failed or had no budget left).
2730
- // The category cells stay n/a; ctx/model/updatedAt still come from
2731
- // state.json / the live lookup.
2732
- source = "no-data";
2733
- }
2734
-
2735
- const liveModel =
2736
- live?.model && typeof live.model === "object" ? live.model : null;
2737
- const cachedModel = lastKnownModel(sessionID);
2738
- const modelID =
2739
- cachedModel !== "unknown"
2740
- ? cachedModel
2741
- : liveModel?.id || entry?.model || "unknown";
2742
- const providerID =
2743
- lastKnownProvider(sessionID) || liveModel?.providerID || entry?.providerID || "";
2744
- const ctxTokens = lastKnownCtx(sessionID) || entry?.ctx || 0;
2745
- const usableInfo = getUsableContext(providerID, modelID);
2746
- const usable =
2747
- usableInfo?.usable ?? entry?.usable ?? getModelLimit(providerID, modelID) ?? null;
2748
- const parentID = entry?.parentID ?? null;
2749
- const updatedAt =
2750
- entry?.updatedAt ||
2751
- (bd?.capturedAt ? new Date(bd.capturedAt).toISOString() : null);
2752
- return {
2753
- sessionID,
2754
- parentID,
2755
- agent: sessionAgentCache.get(sessionID) || entry?.agent || null,
2756
- modelID,
2757
- providerID,
2758
- ctxTokens,
2759
- usable,
2760
- categories,
2761
- source,
2762
- updatedAt,
2763
- };
2764
- }
2765
-
2766
- function fmtCell(n) {
2767
- return n == null ? "n/a" : fmt(n);
2768
- }
2769
-
2770
- // One markdown table row. Categories sit in columns (short headers) to keep the
2771
- // table compact; the ctx column already carries the percentage.
2772
- function renderSessionRow(r, isMain) {
2773
- const c = r.categories || {};
2774
- const role = isMain ? "main" : r.agent ? `sub:${r.agent}` : "sub";
2775
- const pct =
2776
- r.usable && r.usable > 0
2777
- ? ` (${((r.ctxTokens / r.usable) * 100).toFixed(0)}%)`
2778
- : "";
2779
- const ctx = `${fmt(r.ctxTokens)}${pct}`;
2780
- const upd = `${timeOnly(r.updatedAt)} ${sourceTag(r.source)}`;
2781
- return `| ${role} | ${r.modelID} | ${ctx} | ${fmtCell(c.user)} | ${fmtCell(c.assistant)} | ${fmtCell(c.reasoning)} | ${fmtCell(c.toolArgs)} | ${fmtCell(c.system)} | ${fmtCell(c.toolSchemas)} | ${fmtCell(c.other)} | ${upd} |`;
2782
- }
2783
-
2784
- function renderBreakdownTable(rows, childCount) {
2785
- const lines = [];
2786
- lines.push("### Context breakdown");
2787
- lines.push("");
2788
- lines.push(
2789
- "| role | model | ctx | usr | asst | rsn | tool | sys | schm | oth | updated (src) |",
2790
- );
2791
- lines.push("| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |");
2792
- for (const row of rows) lines.push(row);
2793
- lines.push("");
2794
- lines.push(
2795
- `_${childCount} subagent session(s). Tokens are estimates (unicode heuristic). ` +
2796
- `usr=user, asst=assistant, rsn=reasoning, tool=tool args, sys=system prompt, ` +
2797
- `schm=tool schemas, oth=residual input. src: live=context hook, snap=state.json, ` +
2798
- `fallback=session.context (no system/schemas → n/a), no-data=categories unavailable._`,
2799
- );
2800
- return lines.join("\n");
2801
- }
2802
-
2803
- // Shared delivery via ctx.session.synthetic — a synthetic message ALWAYS enters
2804
- // the session inbox; `resume` only gates whether the session is woken:
2805
- // resume:false -> durable notice, session NOT woken (LLM context unchanged);
2806
- // resume:true -> same inbox item PLUS a wake, i.e. an agent turn runs and the
2807
- // session context grows (a real LLM request is issued).
2808
- // Returns true on success. On failure the user sees nothing, so we log a loud,
2809
- // actionable error; the payload is still written to the human-readable log by the
2810
- // caller (there is no other verified delivery channel: no noReply/prompt option
2811
- // exists in this runtime).
2812
- async function deliverSynthetic(ctx, sid, text, description, resume) {
2813
- try {
2814
- await ctx.session.synthetic({ sessionID: sid, text, description, resume });
2815
- return true;
2816
- } catch (err) {
2817
- logErr(
2818
- `context command: session.synthetic FAILED (session=${sid}, ` +
2819
- `resume=${resume}) — no message delivered; payload preserved in the context log`,
2820
- err,
2821
- );
2822
- return false;
2823
- }
2824
- }
2825
-
2826
- // ---- /context : quick summary of THIS session only (no subagents, no RPC) ----
2827
-
2828
- // The one-line description is what the Desktop notice chip shows, so it must be
2829
- // self-contained (model + tokens + % + time).
2830
- function shortSummaryDescription(r) {
2831
- const pct =
2832
- r.usable && r.usable > 0
2833
- ? ` (${((r.ctxTokens / r.usable) * 100).toFixed(0)}%)`
2834
- : "";
2835
- const hhmm = timeOnly(r.updatedAt).slice(0, 5);
2836
- const model = r.modelID && r.modelID !== "unknown" ? r.modelID : "model?";
2837
- return `Context: ${fmt(r.ctxTokens)}${pct} · ${model} · ${hhmm}`;
2838
- }
2839
-
2840
- // Three short lines, built from cache/state only (see commandContextSummary).
2841
- function shortSummaryText(r) {
2842
- const model =
2843
- r.modelID && r.modelID !== "unknown" ? r.modelID : "unknown model";
2844
- const total =
2845
- r.usable && r.usable > 0
2846
- ? ` / ${fmt(r.usable)} (${((r.ctxTokens / r.usable) * 100).toFixed(0)}%)`
2847
- : "";
2848
- const lines = [`**Context** — ${model} · ${fmt(r.ctxTokens)}${total}`];
2849
- const c = r.categories;
2850
- if (c) {
2851
- lines.push(
2852
- `usr ${fmtCell(c.user)} · asst ${fmtCell(c.assistant)} · rsn ${fmtCell(c.reasoning)} · ` +
2853
- `tool ${fmtCell(c.toolArgs)} · sys ${fmtCell(c.system)} · schm ${fmtCell(c.toolSchemas)} · ` +
2854
- `oth ${fmtCell(c.other)}`,
2855
- );
2856
- } else {
2857
- lines.push("_category breakdown unavailable (no cache/state entry yet)_");
2858
- }
2859
- lines.push(`updated ${timeOnly(r.updatedAt)} (${sourceTag(r.source)})`);
2860
- return lines.join("\n");
2861
- }
2862
-
2863
- // /context handler: main session only, cache + state.json only (NO enrichment,
2864
- // NO child traversal) -> instant. Delivered as resume:true so the model
2865
- // renders the 3-line summary as a normal assistant message (the Desktop
2866
- // notice chip only shows `description`).
2867
- async function commandContextSummary(ctx, invocation, opts) {
2868
- const name = opts?.name || "context";
2869
- const sid = invocation?.sessionID || invocation?.session?.id;
2870
- if (!sid) {
2871
- logErr("context: invocation carried no sessionID");
2872
- return;
2873
- }
2874
- try {
2875
- const state = readStateSnapshot();
2876
- // Deadline in the past => collectSessionReport performs no live RPC at all
2877
- // (cache + state.json only), which keeps this command instant.
2878
- const report = await collectSessionReport(ctx, sid, state, 0);
2879
- const body = shortSummaryText(report);
2880
- // Reproduce verbatim so the model echoes the 3 lines as the assistant
2881
- // answer; the Desktop renders that answer in full (the notice chip only
2882
- // shows `description`).
2883
- const text = `${BREAKDOWN_MODEL_INSTRUCTION}\n\n${body}`;
2884
- const description = shortSummaryDescription(report);
2885
- const delivered = await deliverSynthetic(ctx, sid, text, description, true);
2886
- pushFinalSummary(`cmd:${sid}:${Date.now()}`, [
2887
- `[${new Date().toISOString()}] COMMAND ${name} session=${sid} delivered=${delivered}`,
2888
- ...text.split("\n"),
2889
- ]);
2890
- } catch (err) {
2891
- logErr("context command failed", err);
2892
- }
2893
- }
2894
-
2895
- // ---- /context-breakdown : full table (main + subagents), model-rendered ----
2896
-
2897
- // Prefixed to the table for resume:true so the agent echoes it verbatim into the
2898
- // transcript (the Desktop renders the model's answer as a normal message).
2899
- const BREAKDOWN_MODEL_INSTRUCTION =
2900
- "Reproduce the markdown table below exactly, verbatim, with no changes and no commentary:";
2901
-
2902
- // Command handler shared by both slash commands. Registered via
2903
- // ctx.command.transform in setup(); invoked by opencode with
2904
- // { sessionID, prompt:{text,...}, delivery }. `opts` = { resume, name }.
2905
- async function commandContextBreakdown(ctx, invocation, opts) {
2906
- const resume = !!opts?.resume;
2907
- const name = opts?.name || "context-breakdown";
2908
- const sid = invocation?.sessionID || invocation?.session?.id;
2909
- if (!sid) {
2910
- logErr("context-breakdown: invocation carried no sessionID");
2911
- return;
2912
- }
2913
- try {
2914
- // state.json is read immediately and synchronously; the root and every
2915
- // descendant are then collected IN PARALLEL under one cumulative budget, so
2916
- // the command costs ~budget regardless of the subagent count (not N × 3s).
2917
- const state = readStateSnapshot();
2918
- const childIDs = collectDescendantSessionIDs(sid, state);
2919
- const deadline = Date.now() + COMMAND_COLLECT_BUDGET_MS;
2920
- const [root, ...children] = await Promise.all([
2921
- collectSessionReport(ctx, sid, state, deadline),
2922
- ...childIDs.map((cid) => collectSessionReport(ctx, cid, state, deadline)),
2923
- ]);
2924
- const rows = [renderSessionRow(root, true)];
2925
- for (const rep of children) rows.push(renderSessionRow(rep, false));
2926
- const table = renderBreakdownTable(rows, childIDs.length);
2927
- const payload = resume ? `${BREAKDOWN_MODEL_INSTRUCTION}\n\n${table}` : table;
2928
- const description = `Full context breakdown — ${1 + childIDs.length} session(s)`;
2929
-
2930
- const delivered = await deliverSynthetic(ctx, sid, payload, description, resume);
2931
-
2932
- // Persist the table itself (not the instruction) to the human-readable log
2933
- // (survives rewrites, bounded) so it is always recoverable.
2934
- pushFinalSummary(`cmd:${sid}:${Date.now()}`, [
2935
- `[${new Date().toISOString()}] COMMAND ${name} session=${sid} delivered=${delivered}`,
2936
- ...table.split("\n"),
2937
- ]);
2938
- } catch (err) {
2939
- logErr("context-breakdown command failed", err);
2940
- }
2941
- }
154
+ commandContextBreakdown,
155
+ commandContextSummary,
156
+ CONTEXT_BREAKDOWN_RESUME,
157
+ collectSessionReport,
158
+ renderSessionRow,
159
+ shortSummaryText,
160
+ shortSummaryDescription,
161
+ } from "./lib/commands.js";
162
+ import {
163
+ ensureModelLimits,
164
+ getModelLimit,
165
+ getUsableContext,
166
+ hydrateModelLimitsFromState,
167
+ modelLimits,
168
+ } from "./lib/limits.js";
169
+ import { sessionAgentCache, sessionParentCache } from "./lib/cache.js";
170
+ import {
171
+ logErr,
172
+ readStateSnapshot,
173
+ writeStateFile,
174
+ } from "./lib/state.js";
2942
175
 
2943
176
  // ---------------------------------------------------------------------------
2944
177
  // Named exports for the prepublish unit harness (test/prepublish.mjs).
@@ -2946,6 +179,7 @@ async function commandContextBreakdown(ctx, invocation, opts) {
2946
179
  // (modelLimits, sessionAgentCache, etc.) and functions it needs to call
2947
180
  // directly (hydrateModelLimitsFromState, writeStateFile, etc.).
2948
181
  // The plugin itself works without any of these — they are additive.
182
+ // Every name is re-exported from the extracted lib/* modules.
2949
183
  // ---------------------------------------------------------------------------
2950
184
  export {
2951
185
  modelLimits,