@genesislcap/ai-assistant 15.12.0 → 15.13.1

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.
Files changed (50) hide show
  1. package/dist/ai-assistant.api.json +245 -3
  2. package/dist/ai-assistant.d.ts +127 -7
  3. package/dist/chat-driver.cjs +79 -13
  4. package/dist/chat-driver.cjs.map +2 -2
  5. package/dist/chat-driver.mjs +76 -12
  6. package/dist/chat-driver.mjs.map +2 -2
  7. package/dist/custom-elements.json +99 -6
  8. package/dist/dts/chat-driver-node.d.ts +2 -2
  9. package/dist/dts/chat-driver-node.d.ts.map +1 -1
  10. package/dist/dts/components/chat-driver/chat-driver.d.ts +45 -1
  11. package/dist/dts/components/chat-driver/chat-driver.d.ts.map +1 -1
  12. package/dist/dts/components/chat-driver/chat-driver.turn-usage.test.d.ts +2 -0
  13. package/dist/dts/components/chat-driver/chat-driver.turn-usage.test.d.ts.map +1 -0
  14. package/dist/dts/main/main.d.ts +20 -1
  15. package/dist/dts/main/main.d.ts.map +1 -1
  16. package/dist/dts/state/debug-event-log.d.ts.map +1 -1
  17. package/dist/dts/state/persistence/diagnostics.d.ts +65 -8
  18. package/dist/dts/state/persistence/diagnostics.d.ts.map +1 -1
  19. package/dist/dts/state/persistence/index.d.ts +1 -1
  20. package/dist/dts/state/persistence/index.d.ts.map +1 -1
  21. package/dist/dts/state/persistence/session-persister.d.ts +4 -3
  22. package/dist/dts/state/persistence/session-persister.d.ts.map +1 -1
  23. package/dist/dts/utils/sum-usage.d.ts +20 -0
  24. package/dist/dts/utils/sum-usage.d.ts.map +1 -1
  25. package/dist/esm/chat-driver-node.js +12 -2
  26. package/dist/esm/components/chat-driver/chat-driver.js +60 -5
  27. package/dist/esm/components/chat-driver/chat-driver.turn-usage.test.js +268 -0
  28. package/dist/esm/main/main.js +53 -28
  29. package/dist/esm/state/debug-event-log.js +7 -2
  30. package/dist/esm/state/persistence/diagnostics.js +79 -16
  31. package/dist/esm/state/persistence/diagnostics.test.js +174 -1
  32. package/dist/esm/state/persistence/index.js +1 -1
  33. package/dist/esm/state/persistence/session-persister.js +13 -5
  34. package/dist/esm/state/persistence/session-persister.test.js +31 -0
  35. package/dist/esm/utils/sum-usage.js +43 -0
  36. package/dist/esm/utils/sum-usage.test.js +45 -1
  37. package/dist/tsconfig.tsbuildinfo +1 -1
  38. package/package.json +17 -17
  39. package/src/chat-driver-node.ts +12 -2
  40. package/src/components/chat-driver/chat-driver.ts +107 -6
  41. package/src/components/chat-driver/chat-driver.turn-usage.test.ts +362 -0
  42. package/src/main/main.ts +52 -23
  43. package/src/state/debug-event-log.ts +7 -2
  44. package/src/state/persistence/diagnostics.test.ts +208 -1
  45. package/src/state/persistence/diagnostics.ts +117 -15
  46. package/src/state/persistence/index.ts +1 -1
  47. package/src/state/persistence/session-persister.test.ts +37 -0
  48. package/src/state/persistence/session-persister.ts +13 -5
  49. package/src/utils/sum-usage.test.ts +52 -1
  50. package/src/utils/sum-usage.ts +45 -0
@@ -43,7 +43,7 @@ import { AssistantAppSettingsProvider, } from '../provider/assistant-app-setting
43
43
  import { recordMetaEvent, getMetaEvents, clearSession as clearMetaSession, DEBUG_LOG_README, } from '../state/debug-event-log';
44
44
  import { getOrCreateDriver, getDriver, getDriverAgentsKey, deleteDriver, } from '../state/driver-registry';
45
45
  import { buildTimelineEntries } from '../state/persistence/build-timeline-entries';
46
- import { assembleDebugLog } from '../state/persistence/diagnostics';
46
+ import { assembleDebugLog, withFreshMetaSnapshot } from '../state/persistence/diagnostics';
47
47
  import { deleteDiagnosticsCursorsFor, resetDiagnosticsCursorsFor, } from '../state/persistence/diagnostics-cursors';
48
48
  import { getOrCreatePersister, getPersister, deletePersister, } from '../state/persistence/persister-registry';
49
49
  import { SessionPersister, } from '../state/persistence/session-persister';
@@ -3690,7 +3690,7 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
3690
3690
  // an already-enabled non-style animation (e.g. `halo`) would otherwise duplicate.
3691
3691
  this.enabledAnimations = resolveExclusiveLoadingStyle([...new Set(animations)], this.enabledAnimations);
3692
3692
  }
3693
- /** The live current-page debug log (`{ readme, timeline, meta }`). @public */
3693
+ /** The live current-page debug log (`{ readme, sessionUsage, timeline, meta }`). @public */
3694
3694
  getDebugLog() {
3695
3695
  return assembleDebugLog(this.buildDiagnosticEntries(), DEBUG_LOG_README);
3696
3696
  }
@@ -3703,7 +3703,38 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
3703
3703
  * been appended to the persisted stream.
3704
3704
  */
3705
3705
  buildDiagnosticEntries() {
3706
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
3706
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
3707
+ const stateKey = this.getStateKey();
3708
+ // The message/turn/event timeline entries — built by the shared, pure `buildTimelineEntries`
3709
+ // (the same helper a headless consumer uses to harvest its own log), from the driver's pull
3710
+ // surfaces. Prefer the driver's raw history (carries sub-agent traces) over the redux projection.
3711
+ const timelineEntries = buildTimelineEntries({
3712
+ turnSnapshots: (_c = (_b = (_a = this.driver) === null || _a === void 0 ? void 0 : _a.getTurnSnapshots) === null || _b === void 0 ? void 0 : _b.call(_a)) !== null && _c !== void 0 ? _c : [],
3713
+ messages: (_f = (_e = (_d = this.driver) === null || _d === void 0 ? void 0 : _d.getRawHistory) === null || _e === void 0 ? void 0 : _e.call(_d)) !== null && _f !== void 0 ? _f : this.messages,
3714
+ metaEvents: stateKey ? getMetaEvents(stateKey) : [],
3715
+ });
3716
+ // Fold in any external diagnostics harvested from an out-of-band driver (e.g. a server-side
3717
+ // ChatDriver whose collated log an interaction widget returned on its result). They ride the
3718
+ // same download + persisted-diagnostics path; `assembleDebugLog` sorts the whole timeline by
3719
+ // timestamp so they interleave chronologically. (GENC-1461 unified diagnostics.)
3720
+ return [
3721
+ ...timelineEntries,
3722
+ ...((_j = (_h = (_g = this.driver) === null || _g === void 0 ? void 0 : _g.getExternalDiagnostics) === null || _h === void 0 ? void 0 : _h.call(_g)) !== null && _j !== void 0 ? _j : []),
3723
+ this.buildMetaSnapshot(),
3724
+ ];
3725
+ }
3726
+ /**
3727
+ * The single `meta-snapshot` entry for right now — the export-time `meta` block
3728
+ * (agent summary, active prompt/state, context + cost) plus the `dedupSignature`
3729
+ * the forward-capture delta keys on.
3730
+ *
3731
+ * Separate from `buildDiagnosticEntries` because the download path needs a
3732
+ * FRESH one on its own: the persisted stream only re-appends this block when the
3733
+ * near-static config changes, so the newest stored snapshot's volatile half — the
3734
+ * `context` figures especially — is typically frozen at the session's first flush.
3735
+ */
3736
+ buildMetaSnapshot() {
3737
+ var _a, _b, _c, _d, _e, _f, _g, _h;
3707
3738
  const timestamp = new Date().toISOString().replace(/:/g, '-');
3708
3739
  // Snapshot the live active agent from the DRIVER — the instance whose
3709
3740
  // `onActivate` ran, so its `getDebugSnapshot` closure holds state.
@@ -3720,15 +3751,6 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
3720
3751
  const contextUsagePercent = this.contextTokens != null && this.contextLimit != null && this.contextLimit > 0
3721
3752
  ? Math.round((this.contextTokens / this.contextLimit) * 100)
3722
3753
  : undefined;
3723
- const stateKey = this.getStateKey();
3724
- // The message/turn/event timeline entries — built by the shared, pure `buildTimelineEntries`
3725
- // (the same helper a headless consumer uses to harvest its own log), from the driver's pull
3726
- // surfaces. Prefer the driver's raw history (carries sub-agent traces) over the redux projection.
3727
- const timelineEntries = buildTimelineEntries({
3728
- turnSnapshots: (_f = (_e = (_d = this.driver) === null || _d === void 0 ? void 0 : _d.getTurnSnapshots) === null || _e === void 0 ? void 0 : _e.call(_d)) !== null && _f !== void 0 ? _f : [],
3729
- messages: (_j = (_h = (_g = this.driver) === null || _g === void 0 ? void 0 : _g.getRawHistory) === null || _h === void 0 ? void 0 : _h.call(_g)) !== null && _j !== void 0 ? _j : this.messages,
3730
- metaEvents: stateKey ? getMetaEvents(stateKey) : [],
3731
- });
3732
3754
  // The export-time `meta` block, carried on a `meta-snapshot` entry so it lives
3733
3755
  // in the same forward stream (the latest one wins on reassembly, and the
3734
3756
  // accumulated history exposes config/state evolution across the lifetime).
@@ -3743,7 +3765,7 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
3743
3765
  // like an object-form `toolHandlers`, and recurses subAgents — no manual
3744
3766
  // exclusion list to keep in sync. We only override toolDefinitions
3745
3767
  // afterwards to expand the fold tree for the log.
3746
- agentSummary: (_k = this.agents) === null || _k === void 0 ? void 0 : _k.map((a) => {
3768
+ agentSummary: (_d = this.agents) === null || _d === void 0 ? void 0 : _d.map((a) => {
3747
3769
  var _a;
3748
3770
  return (Object.assign(Object.assign({}, stripAgentHandlers(a)), { toolDefinitions: Array.isArray(a.toolDefinitions)
3749
3771
  ? typeof a.toolHandlers === 'function'
@@ -3755,10 +3777,10 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
3755
3777
  ? '<dynamic — resolved per turn>'
3756
3778
  : [] }));
3757
3779
  }),
3758
- activeSystemPrompt: typeof ((_l = this.activeAgent) === null || _l === void 0 ? void 0 : _l.systemPrompt) === 'function'
3780
+ activeSystemPrompt: typeof ((_e = this.activeAgent) === null || _e === void 0 ? void 0 : _e.systemPrompt) === 'function'
3759
3781
  ? '<dynamic — resolved per turn>'
3760
- : (_m = this.activeAgent) === null || _m === void 0 ? void 0 : _m.systemPrompt,
3761
- activePrimerHistory: (_o = this.activeAgent) === null || _o === void 0 ? void 0 : _o.primerHistory,
3782
+ : (_f = this.activeAgent) === null || _f === void 0 ? void 0 : _f.systemPrompt,
3783
+ activePrimerHistory: (_g = this.activeAgent) === null || _g === void 0 ? void 0 : _g.primerHistory,
3762
3784
  activeFoldStack: this.driver instanceof ChatDriver ? this.driver.getActiveFoldNames() : undefined,
3763
3785
  // Context window + cost snapshot. `sessionCostUsd` is the chat-scoped
3764
3786
  // total (per-message `cost` summed); the transport's lifetime cost is
@@ -3780,7 +3802,7 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
3780
3802
  // Snapshot captured fresh at log-export time — reflects state NOW, which
3781
3803
  // may have transitioned since the last LLM call.
3782
3804
  activeDebugSnapshot,
3783
- debug: (_p = this.debugStateFactory) === null || _p === void 0 ? void 0 : _p.call(this),
3805
+ debug: (_h = this.debugStateFactory) === null || _h === void 0 ? void 0 : _h.call(this),
3784
3806
  },
3785
3807
  };
3786
3808
  // Stable dedup signature for the forward-capture stream (GENC-1351 §5.8 / #12):
@@ -3791,6 +3813,8 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
3791
3813
  // instead of "only when the block actually changed". The volatile evolution is
3792
3814
  // already in the timeline (turn snapshots + `context.updated` events), so the
3793
3815
  // persister only needs a fresh meta-snapshot when the config/prompt changes.
3816
+ // Consequence for the download path: the newest STORED snapshot's context/cost
3817
+ // figures are stale, which is why `buildDownloadLog` appends a fresh one.
3794
3818
  const m = metaSnapshot.meta;
3795
3819
  metaSnapshot.dedupSignature = JSON.stringify({
3796
3820
  host: m.host,
@@ -3799,15 +3823,7 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
3799
3823
  activePrimerHistory: m.activePrimerHistory,
3800
3824
  activeFoldStack: m.activeFoldStack,
3801
3825
  });
3802
- // Fold in any external diagnostics harvested from an out-of-band driver (e.g. a server-side
3803
- // ChatDriver whose collated log an interaction widget returned on its result). They ride the
3804
- // same download + persisted-diagnostics path; `assembleDebugLog` sorts the whole timeline by
3805
- // timestamp so they interleave chronologically. (GENC-1461 unified diagnostics.)
3806
- return [
3807
- ...timelineEntries,
3808
- ...((_s = (_r = (_q = this.driver) === null || _q === void 0 ? void 0 : _q.getExternalDiagnostics) === null || _r === void 0 ? void 0 : _r.call(_q)) !== null && _s !== void 0 ? _s : []),
3809
- metaSnapshot,
3810
- ];
3826
+ return metaSnapshot;
3811
3827
  }
3812
3828
  downloadDebugLog() {
3813
3829
  return __awaiter(this, void 0, void 0, function* () {
@@ -3844,6 +3860,14 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
3844
3860
  * chat" — diagnostics are a forensic stream keyed on provider capability, not on
3845
3861
  * whether the *chat* is remembered (like preferences). Falls back to the live
3846
3862
  * current-page log when diagnostics isn't available or the fetch fails.
3863
+ *
3864
+ * The stored `meta-snapshot`s are replaced by a fresh one (`withFreshMetaSnapshot`)
3865
+ * before reassembly. The persisted stream only re-appends that block when the
3866
+ * near-static config signature changes (see `collectDiagnosticsDelta`), so on a session
3867
+ * whose config never changes the newest STORED snapshot is the first one — its
3868
+ * `context` half (session cost/usage, context tokens, live agent state) frozen seconds
3869
+ * into the session, which is how a lifetime log came out reporting near-zero spend
3870
+ * against a transcript full of priced messages.
3847
3871
  */
3848
3872
  buildDownloadLog() {
3849
3873
  return __awaiter(this, void 0, void 0, function* () {
@@ -3855,8 +3879,9 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
3855
3879
  // Land the current page's unflushed delta first so the download includes it.
3856
3880
  yield ((_a = this.persister()) === null || _a === void 0 ? void 0 : _a.flushDiagnostics());
3857
3881
  const stored = yield provider.loadDiagnostics(key);
3858
- if (stored.length)
3859
- return assembleDebugLog(stored, DEBUG_LOG_README);
3882
+ if (stored.length) {
3883
+ return assembleDebugLog(withFreshMetaSnapshot(stored, this.buildMetaSnapshot()), DEBUG_LOG_README);
3884
+ }
3860
3885
  }
3861
3886
  catch (e) {
3862
3887
  logger.error('Diagnostics load failed — using current-page log:', e);
@@ -198,17 +198,22 @@ export function clearSession(key) {
198
198
  */
199
199
  export const DEBUG_LOG_README = [
200
200
  'This is an exported debug log for the Genesis AI assistant. Read it top-to-bottom.',
201
+ "`sessionUsage` is what this session spent: `costUsd` (USD, provider-reported per request and summed, cache discounts already applied) plus the four TOKEN BUCKETS — `uncachedInputTokens`, `cacheReadTokens`, `cacheWriteTokens`, `outputTokens`. Those four are disjoint and safe to add up for a total-tokens figure; the per-message fields further down are NOT (see kind:'message'). Each bucket bills at a different rate — cache reads a fraction of uncached input, cache writes a premium, output highest — so a big token count against a small cost means the prompt was mostly cache hits, not a missing charge. It covers sub-agent turns and spend a compaction banked, so for the CONVERSATION it is the authoritative total: prefer it over re-summing the timeline, which can be short by whatever the ring buffers evicted. The same figures appear under `meta.context`. It is as current as the snapshot it came from: the assistant's own download stamps a fresh one, but a log stitched by another tool can carry an older one — compare `meta.timestamp` with the last timeline entry, and if it is well behind, read these totals as historical and fall back to summing the timeline. One scope caveat: it is derived from the transcript, so it excludes billed calls that produced no message (a blank or refused attempt that was retried — see kind:'turn'.`usage`). Summing the turns can therefore come out HIGHER than this, and the difference is exactly that discarded spend, not a double-count.",
202
+ "What 'session' means for those figures: the CURRENT conversation under this session key (a host-supplied per-project id, or the element id + header title when the host supplies none) — which is not necessarily everything in `timeline`. It is re-derived from the live transcript, so it spans page loads only when the chat is being remembered, and a Clear resets it to zero. `timeline` is append-only regardless: it keeps every page load and the pre-Clear conversation, with the session.cleared event as the boundary. So on a long-lived log, read these totals as the latest conversation's and the earlier sections as history — not as a total of the whole file.",
201
203
  '`timeline` is the entire session as one array, already sorted chronologically by `timestamp` (ISO 8601). Every entry has a `kind`.',
202
204
  'Timestamps are millisecond-resolution; entries that share the same millisecond are ordered by a fixed kind rank (event, then turn, then message), which is a heuristic and may not reflect exact causal order within that millisecond — e.g. a user message and the turn it triggered, or a final assistant message and its turn.end event, can appear in either order depending on whether they landed in the same millisecond. Read the logical structure of a turn rather than over-interpreting the micro-ordering of co-timestamped entries of different kinds.',
203
205
  "kind:'message' — the conversation. `role` is user/assistant/tool/system-event/synthetic-user; `agentName` says which agent produced it; `toolCalls`/`toolResult`/`interaction` carry tool and widget activity; `inputTokens`/`outputTokens`/`cost` are per-message LLM usage, where `inputTokens` is the WHOLE prompt for that request and `cacheReadTokens`/`cacheWriteTokens` BREAK IT DOWN rather than add to it — uncached input is `inputTokens` minus those two, and adding the cache fields to `inputTokens` counts the prompt twice. The cache fields are absent on providers that report no cache split (Gemini reports reads only, since implicit caching bills no write) and on messages persisted before they existed, so read them as 0 when missing. Each bucket bills at a different rate — cache reads a fraction of uncached input, cache writes a premium, output highest — so a large token count at a small cost means the prompt was mostly cache hits. `externalCostUsd` is any non-LLM cost a widget reported for its own external service calls (folded into the session cost total alongside `cost`). On model-produced assistant messages, `model` is the concrete model id that generated it (e.g. 'gemini-2.5-flash-lite') and `providerName` is the registry slot it resolved under (e.g. a tier name like 'high'/'low', or the default); together they attribute the message — and any tool calls it carries — to an exact model even across a mid-session vendor/tier switch, where one slot name can map to different models before and after the switch. Both are undefined on any entry that is NOT an LLM response: non-assistant roles (user/tool/system-event) and 'synthetic-user' echoes; assistant interaction/widget entries (empty content carrying an `interaction` — a rendered widget, not a model turn); driver-authored assistant fallbacks (the timeout, repeated-malformed-call, and empty-response apology messages); and messages restored from a session persisted before these fields existed. One partial case: on a genuine model turn whose provider exposes no `getStatus` (or reports no model), `providerName` is still set but `model` alone is undefined. A 'synthetic-user' message is a display-only echo of an interaction outcome (e.g. the answer a widget reported): it renders on the user's side of the chat and `agentName` is the agent that created it, but it is never sent to the LLM — so it has no matching 'turn' and the model learns the outcome only from the corresponding tool result.",
204
206
  "Sub-agent messages appear inline. When a tool delegates to a sub-agent (via `requestSubAgent`), the sub-agent's whole conversation — its own assistant/tool messages, each with their own `content`/`thinking`/`toolCalls`/`toolResult` and per-message `model`/`providerName`/`inputTokens`/`outputTokens`/`cacheReadTokens`/`cacheWriteTokens`/`cost` — is hoisted into the timeline as ordinary kind:'message' entries, interleaved by timestamp right after the tool call that spawned them (so you read the delegation top-to-bottom). A hoisted entry is marked: `subAgentDepth` is its delegation depth (1 for a sub-agent, 2 for a sub-agent's sub-agent, …), `subAgentOf` is the id of the parent tool call that spawned it (correlates it back even when two sub-agents run in one parent turn), `subAgentName` is the sub-agent's own name, and `agentName` is rewritten to a `\"<parent> › <sub-agent>\"` breadcrumb (composing when nested, e.g. `\"UI Builder › Planner › Grounding\"`). The sub-agent's per-LLM-call snapshots also surface as kind:'turn' entries with an N-M `turnIndex`, and subagent.started/completed (or subagent.failed) events bracket the run. Per-message `cost` on hoisted entries is already part of the session total (it is summed from the un-flattened history), so summing the top-level timeline does NOT double-count.",
205
207
  "kind:'turn' — one LLM call. `turnIndex` is a string: a top-level turn is the bare counter ('0', '1', …); a sub-agent's turns are numbered under the parent turn that activated them ('3-1', '3-2', …, and a nested sub-agent contributes '3-2-1', …), and `agentName` names the agent that ran the turn. `systemPrompt` and `toolNames` are what the model saw. A systemPrompt of '<repeated — identical to turn N>' was byte-identical to turn N and de-duplicated; the full prompt is shown whenever it changes (often because a stateful agent advanced), so prompt evolution is visible.",
208
+ "kind:'turn'.`model`/`providerName`/`provider` — which model ran that call: the concrete model id, the registry slot it resolved under (a tier name like 'high'/'low', or the default), and the vendor. Recorded per CALL, so an agent whose `provider` selector varies by state — a flow that plans on a high tier and executes on a low one — has every step attributed, including calls that produced no message. `model` is the SERVING model where the provider reports one, so a turn answered by a server-side fallback names the model that answered rather than the one requested; it always matches the `model` on the message that call produced. Absent when the provider exposes no `getStatus` and the transport stamped nothing.",
209
+ "kind:'turn'.`usage` — what that ONE call cost, in the same four-bucket + `costUsd` shape as `sessionUsage`. Absent while a call is in flight and on providers that report no usage. This is the SAME money as the message the call produced, not extra money: never add turn usage to message usage, and read a turn plus its message as one charge. Its distinct value is the calls that produced NO message — a blank or refused response is billed and then discarded before the retry, so the turn entry is the only record of that spend, and a turn with `usage` but no message after it is exactly that. `costUsd: 0` alongside a nonzero token count means the provider reported no price, not that the call was free.",
206
210
  "kind:'turn'.`agentSnapshot` — the active agent's own view of its internal state, captured at that turn. An agent opts into this by exposing a `getDebugSnapshot()` that returns JSON-serializable per-state info; stateful/flow agents wire it automatically, so you can watch a flow advance turn-by-turn (e.g. current step, cursor, collected fields, pending changes). Absent for agents that don't expose one.",
207
211
  "kind:'event' — a meta/lifecycle event. `type` names it (see below); `detail` carries structured data. `detail.placement` is the emitting UI instance: 'bubble' (collapsed), 'panel' (popped-out), or 'standalone'.",
208
212
  "Each 'event' also has an `importance`: 'high' (failures/limits — turn.error, tool.failed, subagent.failed, file.read-failed, suggestions.failed, context.threshold-crossed), 'normal' (session flow — connects, turns, retries, handoffs, agent/provider changes, interactions, sub-agent start/complete), or 'low' (skippable UI/bookkeeping noise — panel.toggled, attachment.added, driver.wired/unwired, context.updated, context.condensed). To skim, ignore importance:'low'; to triage a failure, filter to importance:'high' then read the nearby messages and turns. A 'high' turn.error is often preceded by one or more 'normal' turn.retry events for the same reason — read them together to see how many attempts were made before bailing. 'message' and 'turn' entries carry no importance — they are the substance, always read them.",
209
- 'Event types: assistant.connected/disconnected (mount + placement + whether the session was created or restored), assistant.popout/popin (window placement), driver.created/wired/unwired (which driver is live and why it stops/starts responding across a popout), state.changed (idle↔loading), turn.start/turn.end (turn boundary; turn.end carries durationMs), turn.retry (a recoverable in-turn retry — detail.reason plus attempt/maxAttempts; for malformed calls also finishMessage; for empty responses also the provider finishReason + thoughtsTokens + parts breakdown), turn.error (a turn failed or hit a guardrail — detail.reason is one of exception/malformed-function-call/empty-response/unknown-tool-limit/max-iterations/response-truncated/refusal/budget-exhausted, plus reason-specific diagnostics: attempts (for empty-response also finishReason + thoughtsTokens + a parts breakdown, distinguishing a thinking-only STOP from a truly empty turn), finishMessage, for response-truncated the model + maxTokens + outputTokens + tools, unknownTools (split into staleTools — real earlier this activation but retired by the current state or hidden behind an open exclusive fold — and hallucinatedTools — never advertised) + availableTools, iterations + limit, for budget-exhausted the budgetUsd + spentUsd figures reported by the proxy plus the resolved vendor, or name + message for exceptions), tool.failed (a tool threw), tool.unresolved (the model called a tool that could not be dispatched — detail.kind is folded/fold-hidden/stale/unknown, plus tool + agent and, for the counted kinds, the consecutive streak; the recurring lead-up to an unknown-tool-limit turn.error), subagent.started/completed/failed (the lifecycle of a `requestSubAgent` delegation — detail.agent names the sub-agent; these bracket the sub-agent turns that appear as kind:turn entries with an N-M `turnIndex`; subagent.failed also carries detail.reason, one of max_iterations/malformed_tool_call/empty_response/unknown_tool_limit/timeout/response_truncated/refusal/budget_exhausted; budget_exhausted is terminal for the PARENT turn too — the parent stops rather than calling the model again into the same wall), agent.handoff (routing; from=null is the initial activation), agent.pinned/unpinned (forced routing), provider.selected (model/provider for the upcoming turns), interaction.requested/resolved (blocking user widgets — explain quiet gaps; note that when a sub-agent opens a widget, detail.agent — and the agentName on the interaction message — is the HOST agent that owns the widget, NOT the sub-agent that asked, because widgets render and resolve on the host driver), context.updated/threshold-crossed (token + cost), context.condensed (a stale tool payload was collapsed out of the model-bound history by a `condenseWhen` declaration on the tool — detail.tool + toolCallId, target args|response, trigger (superseded:<key> or age:<n>), stubLen, and an estimated tokensSaved; stored history and this log keep the FULL payload, so the model-visible slice at any point is the full history minus the condensations recorded up to then), panel.toggled, attachment.added, file.read-failed, suggestions.failed.',
213
+ 'Event types: assistant.connected/disconnected (mount + placement + whether the session was created or restored), assistant.popout/popin (window placement), driver.created/wired/unwired (which driver is live and why it stops/starts responding across a popout), state.changed (idle↔loading), turn.start/turn.end (turn boundary; turn.end carries durationMs), turn.retry (a recoverable in-turn retry — detail.reason plus attempt/maxAttempts; for malformed calls also finishMessage; for empty responses also the provider finishReason + thoughtsTokens + parts breakdown), turn.error (a turn failed or hit a guardrail — detail.reason is one of exception/malformed-function-call/empty-response/unknown-tool-limit/max-iterations/response-truncated/refusal/budget-exhausted, plus reason-specific diagnostics: attempts (for empty-response also finishReason + thoughtsTokens + a parts breakdown, distinguishing a thinking-only STOP from a truly empty turn), finishMessage, for response-truncated the model + maxTokens + outputTokens + tools, unknownTools (split into staleTools — real earlier this activation but retired by the current state or hidden behind an open exclusive fold — and hallucinatedTools — never advertised) + availableTools, iterations + limit, for budget-exhausted the budgetUsd + spentUsd figures reported by the proxy plus the resolved vendor, or name + message for exceptions), tool.failed (a tool threw), tool.unresolved (the model called a tool that could not be dispatched — detail.kind is folded/fold-hidden/stale/unknown, plus tool + agent and, for the counted kinds, the consecutive streak; the recurring lead-up to an unknown-tool-limit turn.error), subagent.started/completed/failed (the lifecycle of a `requestSubAgent` delegation — detail.agent names the sub-agent; these bracket the sub-agent turns that appear as kind:turn entries with an N-M `turnIndex`; subagent.failed also carries detail.reason, one of max_iterations/malformed_tool_call/empty_response/unknown_tool_limit/timeout/response_truncated/refusal/budget_exhausted; budget_exhausted is terminal for the PARENT turn too — the parent stops rather than calling the model again into the same wall), agent.handoff (routing; from=null is the initial activation), agent.pinned/unpinned (forced routing), provider.selected (the resolved provider for the upcoming turns — detail.provider is the registry SLOT/tier name, detail.model the concrete model behind it and detail.vendor its vendor; emitted only when the slot CHANGES, so read the per-turn `model` for the model of any given call rather than assuming the nearest event still applies), interaction.requested/resolved (blocking user widgets — explain quiet gaps; note that when a sub-agent opens a widget, detail.agent — and the agentName on the interaction message — is the HOST agent that owns the widget, NOT the sub-agent that asked, because widgets render and resolve on the host driver), context.updated/threshold-crossed (token + cost), context.condensed (a stale tool payload was collapsed out of the model-bound history by a `condenseWhen` declaration on the tool — detail.tool + toolCallId, target args|response, trigger (superseded:<key> or age:<n>), stubLen, and an estimated tokensSaved; stored history and this log keep the FULL payload, so the model-visible slice at any point is the full history minus the condensations recorded up to then), panel.toggled, attachment.added, file.read-failed, suggestions.failed.',
210
214
  'Sub-agent meta events: a sub-agent\'s own turn.retry/turn.error/tool.failed/tool.unresolved events are merged into this same timeline, tagged with `detail.subAgent` — a `"<parent> › <sub-agent>"` breadcrumb that composes when nested (e.g. `"UI Builder › Planner › Grounding"`) — and interleaved by their original timestamps within the subagent.started→completed/failed bracket. These are the per-attempt/per-failure signals that do NOT appear among the sub-agent\'s (hoisted) messages: a malformed/empty attempt that gets retried produces no message, and the stale-vs-hallucinated split and streak counts live only on the event. A sub-agent\'s high-volume, message-derivable events (turn.start/turn.end, provider.selected, context.updated) are intentionally NOT merged — read its hoisted messages for model/tokens/cost and turn-by-turn activity, and the bracketing subagent.* events for the run\'s span.',
211
- "`meta` holds context captured at export time: agentSummary (full agent configs), context (active model, token usage, session cost), activeDebugSnapshot (the active agent's `getDebugSnapshot()` taken fresh at export — reflects state NOW, which may have advanced beyond the last turn's agentSnapshot), debug (optional host-supplied debug state), host, and the export timestamp.",
215
+ "`meta` holds context captured at export time: agentSummary (full agent configs), context (active model, contextTokens/contextLimit/contextUsagePercent for the last call, and the session totals — sessionCostUsd, sessionTokensConsumed, and the four-bucket sessionUsage lifted to the top of this log), activeDebugSnapshot (the active agent's `getDebugSnapshot()` taken fresh at export — reflects state NOW, which may have advanced beyond the last turn's agentSnapshot), debug (optional host-supplied debug state), host, and the export timestamp.",
216
+ 'Note the two different scopes in `meta.context`: `contextTokens` is the prompt size of the LAST call (against `contextLimit`, the model context window), while `sessionUsage`/`sessionTokensConsumed` are cumulative BILLED throughput. Every turn resends the conversation, so the cumulative figure counts each turn’s prompt again in the next turn’s and is expected to dwarf the context size — that is not double-counting.',
212
217
  'To debug a failure: find the last turn.error or tool.failed, then read upward for the user message, the turn(s), and the agent/provider/state events that led into it.',
213
218
  ];
214
219
  /**
@@ -2,8 +2,8 @@
2
2
  * Server-saved diagnostics (GENC-1351 §5.8) — the forward-only stream that lets
3
3
  * the debug log persist across a whole session lifetime, not just the current
4
4
  * page load. This module owns the *pure* pieces: the entry type and the
5
- * reassembly back into the `{ readme, timeline, meta }` debug-log shape. The
6
- * element owns capture/cadence; the provider owns storage layout.
5
+ * reassembly back into the `{ readme, sessionUsage, timeline, meta }` debug-log
6
+ * shape. The element owns capture/cadence; the provider owns storage layout.
7
7
  *
8
8
  * @packageDocumentation
9
9
  */
@@ -31,6 +31,28 @@ export function diagnosticsMessageKey(entry) {
31
31
  ? `${entry.timestamp}::${(_a = entry.role) !== null && _a !== void 0 ? _a : ''}::${(_b = entry.subAgentOf) !== null && _b !== void 0 ? _b : ''}::${(_c = entry.category) !== null && _c !== void 0 ? _c : ''}`
32
32
  : null;
33
33
  }
34
+ /**
35
+ * Identity of a `turn` entry — `turnIndex::timestamp::agentName`.
36
+ *
37
+ * Deliberately NOT the serialized entry, which two copies of the same call do not always
38
+ * share. `buildTimelineEntries` renders `systemPrompt` *relative to the preceding
39
+ * snapshots* (collapsing it to `<repeated — identical to turn N>` when it matches the
40
+ * previous full prompt), so if the snapshot holding that full prompt is evicted from the
41
+ * ring buffer between the unpriced flush and the priced one, the surviving turn renders
42
+ * its prompt differently and the two serializations diverge. Both copies are in the
43
+ * stream by then, so nothing would collapse them — and the log whose purpose is per-call
44
+ * cost would show one model call as two turns, one of them unpriced.
45
+ *
46
+ * All three components are fixed when the snapshot is created and never re-derived.
47
+ * `turnIndex` alone is not enough: it restarts at `'0'` on each page load, and a lifetime
48
+ * log legitimately holds one turn `'0'` per load. `agentName` separates two sub-agents
49
+ * invoked in the same parent turn, which share a `turnIndex` prefix by construction (see
50
+ * `forwardSubAgentSnapshots`).
51
+ */
52
+ function turnIdentity(entry) {
53
+ var _a, _b, _c;
54
+ return `turn::${String((_a = entry.turnIndex) !== null && _a !== void 0 ? _a : '')}::${(_b = entry.timestamp) !== null && _b !== void 0 ? _b : ''}::${String((_c = entry.agentName) !== null && _c !== void 0 ? _c : '')}`;
55
+ }
34
56
  // Tie-break co-timestamped entries by cause → call → output (event, turn, message),
35
57
  // matching the original in-place `getDebugLog` sort.
36
58
  const KIND_RANK = { event: 0, turn: 1, message: 2 };
@@ -38,19 +60,26 @@ const KIND_RANK = { event: 0, turn: 1, message: 2 };
38
60
  // are filtered out first) sorts last.
39
61
  const UNKNOWN_KIND_RANK = 99;
40
62
  /**
41
- * Reassemble diagnostic entries into the `{ readme, timeline, meta }` debug-log
42
- * shape (GENC-1351 §5.8). `timeline` = the `message`/`turn`/`event` entries sorted
63
+ * Reassemble diagnostic entries into the `{ readme, sessionUsage, timeline, meta }`
64
+ * debug-log shape (GENC-1351 §5.8). `timeline` = the `message`/`turn`/`event` entries sorted
43
65
  * by ISO `timestamp` (kind-rank tie-break). `meta` = the **newest** `meta-snapshot`'s
44
66
  * block only — a "state at export" photo, matching the single-page log. The older
45
67
  * snapshots are intentionally dropped: the per-turn evolution they would show is
46
68
  * already in the timeline (`turn.agentSnapshot` + `context.updated` events), so
47
69
  * keeping them would just repeat the bulky, near-static `agentSummary`. `readme` =
48
- * the passed (current) constant. Pure reused for both the live current-page log
49
- * and the reassembled lifetime log stitched from the persisted stream, so both
50
- * come out shape-identical.
70
+ * the passed (current) constant. `sessionUsage` = that same newest snapshot's
71
+ * `meta.context.sessionUsage`, lifted to the top level. Pure reused for both the
72
+ * live current-page log and the reassembled lifetime log stitched from the persisted
73
+ * stream, so both come out shape-identical.
74
+ *
75
+ * NOTE for a caller stitching a STORED stream (a headless consumer harvesting its own
76
+ * lifetime log, say): the newest stored `meta-snapshot` is frozen at the last
77
+ * config-signature change, so `meta` and `sessionUsage` are as old as that unless you
78
+ * pass a fresh snapshot of your own — {@link withFreshMetaSnapshot} does exactly that,
79
+ * and the element's download path goes through it.
51
80
  */
52
81
  export function assembleDebugLog(entries, readme) {
53
- var _a, _b;
82
+ var _a, _b, _c;
54
83
  // Safety net for exact-duplicate entries: two element instances sharing one
55
84
  // session (bubble + popped-out panel) can each append the same entry, and a
56
85
  // reload's second instance can re-append restored history. Such copies are
@@ -58,22 +87,32 @@ export function assembleDebugLog(entries, readme) {
58
87
  // (e.g. two real `assistant.connected` from two instances) differ in index /
59
88
  // placement and are kept. (The shared cursor store prevents most of this at
60
89
  // write time; this guards the read path regardless of what's in the stream.)
61
- const seen = new Set();
90
+ //
91
+ // A `turn` is identified by `turnIndex` + `timestamp` + `agentName` instead (see
92
+ // `turnIdentity`), so the unpriced copy a mid-call flush persisted and the priced copy
93
+ // that follows it collapse into ONE turn — the priced one — rather than reading as two
94
+ // model calls.
95
+ const seenAt = new Map();
62
96
  let latestMeta;
63
97
  const timeline = [];
64
98
  for (const entry of entries) {
65
- const id = JSON.stringify(entry);
66
- if (seen.has(id))
67
- continue;
68
- seen.add(id);
69
99
  if (entry.kind === 'meta-snapshot') {
70
100
  if (!latestMeta || ((_a = entry.timestamp) !== null && _a !== void 0 ? _a : '') >= ((_b = latestMeta.timestamp) !== null && _b !== void 0 ? _b : '')) {
71
101
  latestMeta = entry;
72
102
  }
103
+ continue;
73
104
  }
74
- else {
75
- timeline.push(entry);
105
+ const id = entry.kind === 'turn' ? turnIdentity(entry) : JSON.stringify(entry);
106
+ const at = seenAt.get(id);
107
+ if (at !== undefined) {
108
+ // Same entry seen twice — keep the richer copy. `usage` on a turn is the only
109
+ // field that can arrive late, so it is the only upgrade there is to make.
110
+ if (entry.usage && !timeline[at].usage)
111
+ timeline[at] = entry;
112
+ continue;
76
113
  }
114
+ seenAt.set(id, timeline.length);
115
+ timeline.push(entry);
77
116
  }
78
117
  timeline.sort((a, b) => {
79
118
  var _a, _b, _c, _d;
@@ -85,5 +124,29 @@ export function assembleDebugLog(entries, readme) {
85
124
  return 1;
86
125
  return ((_c = KIND_RANK[a.kind]) !== null && _c !== void 0 ? _c : UNKNOWN_KIND_RANK) - ((_d = KIND_RANK[b.kind]) !== null && _d !== void 0 ? _d : UNKNOWN_KIND_RANK);
87
126
  });
88
- return { readme, timeline, meta: latestMeta === null || latestMeta === void 0 ? void 0 : latestMeta.meta };
127
+ // The session totals live inside the newest snapshot's `meta`, which is `unknown` by
128
+ // design (a provider stores these opaquely) — so this narrows just the one path it
129
+ // reads rather than typing the whole block.
130
+ const context = (_c = latestMeta === null || latestMeta === void 0 ? void 0 : latestMeta.meta) === null || _c === void 0 ? void 0 : _c.context;
131
+ return { readme, sessionUsage: context === null || context === void 0 ? void 0 : context.sessionUsage, timeline, meta: latestMeta === null || latestMeta === void 0 ? void 0 : latestMeta.meta };
132
+ }
133
+ /**
134
+ * A stored diagnostics stream with its `meta-snapshot`s replaced by `fresh` — what to
135
+ * pass {@link assembleDebugLog} when reassembling a persisted stream for export.
136
+ *
137
+ * The stored snapshots are dropped rather than out-timestamped. `assembleDebugLog` keeps
138
+ * whichever claims the later time, and a stream written on another machine can carry a
139
+ * skewed clock; `fresh` is built from live state and so is the more current by
140
+ * construction. Only one snapshot ever survives reassembly, so the count is unchanged —
141
+ * though a snapshot taken while the driver is unwired (mid-popout) can leave
142
+ * `activeFoldStack`/`activeDebugSnapshot` unset where a stored one had them. The figures
143
+ * this exists for — the context block and `sessionUsage` — read the session store and
144
+ * element props, which survive an unwire.
145
+ *
146
+ * Pure, and separate from the element for that reason: the swap it performs is the fix
147
+ * for a silent bug (a lifetime log reporting near-zero spend against a transcript full of
148
+ * priced messages), so it needs to be testable without mounting anything.
149
+ */
150
+ export function withFreshMetaSnapshot(stored, fresh) {
151
+ return [...stored.filter((e) => e.kind !== 'meta-snapshot'), fresh];
89
152
  }
@@ -1,5 +1,5 @@
1
1
  import { assert, createLogicSuite } from '@genesislcap/foundation-testing';
2
- import { assembleDebugLog, diagnosticsMessageKey } from './diagnostics';
2
+ import { assembleDebugLog, diagnosticsMessageKey, withFreshMetaSnapshot, } from './diagnostics';
3
3
  // GENC-1351 §5.8: `assembleDebugLog` reassembles the forward-only diagnostics
4
4
  // stream back into the `{ readme, timeline, meta }` debug-log shape — timeline
5
5
  // sorted by timestamp, meta-snapshots pulled out with the latest winning.
@@ -69,7 +69,180 @@ Suite('collapses exact-duplicate entries but keeps genuinely-distinct ones', ()
69
69
  assert.is(timeline.filter((e) => e.kind === 'message').length, 1, 'identical message collapsed');
70
70
  assert.is(timeline.filter((e) => e.type === 'assistant.connected').length, 2, 'two distinct connects (different index) kept; the repeated connA collapsed');
71
71
  });
72
+ Suite('lifts the newest snapshot’s session usage to the top of the log', () => {
73
+ // The four buckets + USD are the headline of a cost investigation, and `meta` is a
74
+ // large block to go digging in — so they surface at the top level. Same object, not a
75
+ // second derivation, and taken from the SAME snapshot that becomes `meta`.
76
+ const usage = {
77
+ costUsd: 1.25,
78
+ uncachedInputTokens: 1000,
79
+ cacheReadTokens: 9000,
80
+ cacheWriteTokens: 500,
81
+ outputTokens: 300,
82
+ };
83
+ const entries = [
84
+ {
85
+ kind: 'meta-snapshot',
86
+ timestamp: '2026-01-01T00:00:01.000Z',
87
+ meta: { context: { sessionUsage: Object.assign(Object.assign({}, usage), { costUsd: 0.01 }) } },
88
+ },
89
+ {
90
+ kind: 'meta-snapshot',
91
+ timestamp: '2026-01-01T00:00:09.000Z',
92
+ meta: { context: { sessionUsage: usage } },
93
+ },
94
+ ];
95
+ assert.equal(assembleDebugLog(entries, README).sessionUsage, usage);
96
+ });
97
+ Suite('leaves session usage undefined when no snapshot carries it', () => {
98
+ // A stream with no meta-snapshot, or one written before the field existed. Absent
99
+ // rather than zeroed: "not recorded" must not read as "this session spent nothing".
100
+ assert.is(assembleDebugLog([], README).sessionUsage, undefined);
101
+ const noContext = [
102
+ { kind: 'meta-snapshot', timestamp: '2026-01-01T00:00:01.000Z', meta: { host: 'localhost' } },
103
+ ];
104
+ assert.is(assembleDebugLog(noContext, README).sessionUsage, undefined);
105
+ });
106
+ Suite('collapses the turn pair even when its rendered systemPrompt differs', () => {
107
+ // The pair is produced by two separate flushes, and `buildTimelineEntries` renders
108
+ // `systemPrompt` relative to the preceding snapshots — so if the snapshot holding the
109
+ // full prompt is evicted from the ring buffer between the two, the surviving turn
110
+ // renders its prompt in full where the earlier copy had the '<repeated>' marker. Any
111
+ // identity derived from the serialized entry breaks here and the log shows one model
112
+ // call as two turns, one unpriced. Identity is turnIndex + timestamp + agentName.
113
+ const unpriced = {
114
+ kind: 'turn',
115
+ turnIndex: '7',
116
+ timestamp: '2026-01-01T00:00:01.000Z',
117
+ agentName: 'Trade Operations',
118
+ systemPrompt: '<repeated — identical to turn 0>',
119
+ toolNames: [],
120
+ };
121
+ const priced = Object.assign(Object.assign({}, unpriced), { systemPrompt: 'the full prompt, now that turn 0 has been evicted', usage: {
122
+ costUsd: 0.5,
123
+ uncachedInputTokens: 100,
124
+ cacheReadTokens: 0,
125
+ cacheWriteTokens: 0,
126
+ outputTokens: 20,
127
+ } });
128
+ const turns = assembleDebugLog([unpriced, priced], README).timeline.filter((e) => e.kind === 'turn');
129
+ assert.is(turns.length, 1, 'still one model call');
130
+ assert.equal(turns[0].usage, priced.usage, 'and it is the priced copy');
131
+ });
132
+ Suite('keeps same-index turns from different loads and different sub-agents apart', () => {
133
+ // `turnIndex` restarts at '0' on every page load, so a lifetime log holds one turn '0'
134
+ // per load; two sub-agents invoked in one parent turn share the index prefix and are
135
+ // separated by `agentName` (see `forwardSubAgentSnapshots`).
136
+ const load1 = {
137
+ kind: 'turn',
138
+ turnIndex: '0',
139
+ timestamp: '2026-01-01T00:00:01.000Z',
140
+ agentName: 'Booker',
141
+ toolNames: [],
142
+ };
143
+ const load2 = Object.assign(Object.assign({}, load1), { timestamp: '2026-01-02T09:00:00.000Z' });
144
+ const sibling = Object.assign(Object.assign({}, load1), { turnIndex: '3-1', agentName: 'Planner' });
145
+ const cousin = Object.assign(Object.assign({}, sibling), { agentName: 'Grounding' });
146
+ const turns = assembleDebugLog([load1, load2, sibling, cousin], README).timeline.filter((e) => e.kind === 'turn');
147
+ assert.is(turns.length, 4, 'four distinct calls, none collapsed');
148
+ });
149
+ Suite('collapses the unpriced and priced copies of one turn onto the priced one', () => {
150
+ // A turn entry is persisted when it is created (before its model call) and again once
151
+ // `usage` is back-filled, so a stitched stream carries both. They are ONE model call
152
+ // and must read as one — with the cost, or the re-emit gained nothing.
153
+ const unpriced = {
154
+ kind: 'turn',
155
+ turnIndex: '0',
156
+ timestamp: '2026-01-01T00:00:01.000Z',
157
+ toolNames: [],
158
+ };
159
+ const priced = Object.assign(Object.assign({}, unpriced), { usage: {
160
+ costUsd: 0.5,
161
+ uncachedInputTokens: 100,
162
+ cacheReadTokens: 0,
163
+ cacheWriteTokens: 0,
164
+ outputTokens: 20,
165
+ } });
166
+ for (const order of [
167
+ [unpriced, priced],
168
+ [priced, unpriced],
169
+ ]) {
170
+ const turns = assembleDebugLog(order, README).timeline.filter((e) => e.kind === 'turn');
171
+ assert.is(turns.length, 1, 'one turn, not two');
172
+ assert.equal(turns[0].usage, priced.usage, 'the priced copy wins regardless of stream order');
173
+ }
174
+ });
175
+ Suite('keeps two genuinely-different turns that differ only in usage', () => {
176
+ // The collapse keys on everything EXCEPT usage, so distinct calls stay distinct — they
177
+ // differ in timestamp (and turnIndex) whatever else they share.
178
+ const a = {
179
+ kind: 'turn',
180
+ turnIndex: '0',
181
+ timestamp: '2026-01-01T00:00:01.000Z',
182
+ toolNames: [],
183
+ };
184
+ const b = Object.assign(Object.assign({}, a), { turnIndex: '1', timestamp: '2026-01-01T00:00:02.000Z' });
185
+ const turns = assembleDebugLog([a, b], README).timeline.filter((e) => e.kind === 'turn');
186
+ assert.is(turns.length, 2);
187
+ });
72
188
  Suite.run();
189
+ // The download path's swap: a stored stream's `meta-snapshot`s replaced by an export-time
190
+ // one. This is the fix for a SILENT bug — the persisted stream only re-appends that block
191
+ // when the config signature changes, so a stitched lifetime log reported the totals frozen
192
+ // at the session's first flush (near-zero spend against a transcript full of priced
193
+ // messages) and nothing about it looked wrong.
194
+ const FreshSuite = createLogicSuite('withFreshMetaSnapshot');
195
+ const storedStream = [
196
+ {
197
+ kind: 'meta-snapshot',
198
+ timestamp: '2026-01-01T00:00:00.000Z',
199
+ meta: { context: { sessionUsage: { costUsd: 0.01 } } },
200
+ dedupSignature: 'cfg-1',
201
+ },
202
+ { kind: 'message', timestamp: '2026-01-01T00:00:01.000Z', role: 'user', content: 'hi' },
203
+ { kind: 'turn', turnIndex: '0', timestamp: '2026-01-01T00:00:02.000Z', toolNames: [] },
204
+ { kind: 'event', index: 0, timestamp: '2026-01-01T00:00:03.000Z', type: 'turn.end' },
205
+ ];
206
+ const freshSnapshot = {
207
+ kind: 'meta-snapshot',
208
+ timestamp: '2026-01-01T02:00:00.000Z',
209
+ meta: {
210
+ context: {
211
+ sessionUsage: {
212
+ costUsd: 1.25,
213
+ uncachedInputTokens: 1000,
214
+ cacheReadTokens: 9000,
215
+ cacheWriteTokens: 500,
216
+ outputTokens: 300,
217
+ },
218
+ },
219
+ },
220
+ dedupSignature: 'cfg-1',
221
+ };
222
+ FreshSuite('reports the export-time totals, not the frozen stored ones', () => {
223
+ var _a, _b;
224
+ const log = assembleDebugLog(withFreshMetaSnapshot(storedStream, freshSnapshot), README);
225
+ assert.is((_a = log.sessionUsage) === null || _a === void 0 ? void 0 : _a.costUsd, 1.25, 'the fresh snapshot supplies the totals');
226
+ assert.is((_b = log.sessionUsage) === null || _b === void 0 ? void 0 : _b.cacheReadTokens, 9000);
227
+ assert.equal(log.meta, freshSnapshot.meta, 'and the whole meta block is the fresh one');
228
+ });
229
+ FreshSuite('keeps every non-snapshot entry', () => {
230
+ const timeline = assembleDebugLog(withFreshMetaSnapshot(storedStream, freshSnapshot), README).timeline;
231
+ assert.equal(timeline.map((e) => e.kind), ['message', 'turn', 'event'], 'the conversation is untouched — only the snapshots are swapped');
232
+ });
233
+ FreshSuite('wins even when the stored snapshot claims a later time', () => {
234
+ var _a;
235
+ // A stream written on another machine can carry a skewed clock, and reassembly keeps
236
+ // whichever snapshot claims the later timestamp — so the stale one must be REMOVED
237
+ // rather than out-timestamped.
238
+ const skewed = [
239
+ Object.assign(Object.assign({}, storedStream[0]), { timestamp: '2099-01-01T00:00:00.000Z' }),
240
+ ...storedStream.slice(1),
241
+ ];
242
+ const log = assembleDebugLog(withFreshMetaSnapshot(skewed, freshSnapshot), README);
243
+ assert.is((_a = log.sessionUsage) === null || _a === void 0 ? void 0 : _a.costUsd, 1.25);
244
+ });
245
+ FreshSuite.run();
73
246
  // GENC-1461: the reasoning/narration/answer split (GENC-1411) emits several messages from ONE model
74
247
  // response, so they share `timestamp` + `role` + `subAgentOf`. The message identity key must still
75
248
  // tell them apart — otherwise the forward-capture dedup treats them as one and drops all but the
@@ -1,3 +1,3 @@
1
1
  export { PERSISTED_SESSION_VERSION } from './session-snapshot';
2
2
  export { WebStorageSessionProvider } from './session-persistence-provider';
3
- export { assembleDebugLog } from './diagnostics';
3
+ export { assembleDebugLog, withFreshMetaSnapshot } from './diagnostics';
@@ -582,9 +582,10 @@ export class SessionPersister {
582
582
  }
583
583
  /**
584
584
  * The diagnostic entries not yet appended this load — the forward-capture delta
585
- * (§5.8). Skips messages present at restore or already appended; emits each turn
586
- * (by turn-index) and meta-event (by index) once; appends a `meta-snapshot` only
587
- * when the block changed. Advances the shared per-session cursors as it goes.
585
+ * (§5.8). Skips messages present at restore or already appended; emits each meta-event
586
+ * (by index) once and each turn (by turn-index) once unpriced plus once more when its
587
+ * per-call `usage` lands; appends a `meta-snapshot` only when the block changed.
588
+ * Advances the shared per-session cursors as it goes.
588
589
  *
589
590
  * TODO(GENC-1461, longer-term): this whole delta step exists only because the element *pulls* the
590
591
  * ENTIRE debug log on every throttled flush (`getDiagnosticEntries()` returns the full timeline),
@@ -613,10 +614,17 @@ export class SessionPersister {
613
614
  delta.push(entry);
614
615
  }
615
616
  else if (entry.kind === 'turn') {
617
+ // A turn entry is created BEFORE its model call and priced when the response
618
+ // lands, so a flush that falls in between persists it unpriced. Emit it a second
619
+ // time once `usage` is there — keyed separately so it happens at most once per
620
+ // turn — and let `assembleDebugLog` collapse the pair onto the priced copy.
621
+ // Without this the stitched lifetime log silently loses per-call cost for any
622
+ // turn that outlived a flush, which is most of the slow ones.
616
623
  const key = String((_a = entry.turnIndex) !== null && _a !== void 0 ? _a : '');
617
- if (cursors.emittedTurnKeys.has(key))
624
+ const emitKey = entry.usage ? `${key}::usage` : key;
625
+ if (cursors.emittedTurnKeys.has(emitKey))
618
626
  continue;
619
- cursors.emittedTurnKeys.add(key);
627
+ cursors.emittedTurnKeys.add(emitKey);
620
628
  delta.push(entry);
621
629
  }
622
630
  else if (entry.kind === 'event') {
@@ -336,6 +336,37 @@ Suite('flushDiagnostics() keeps co-timestamped split messages (reasoning + answe
336
336
  assert.is(f.appended.length, 1, 'one flush');
337
337
  assert.is(f.appended[0].length, 2, 'both the reasoning and the answer message are captured, not collapsed to one');
338
338
  }));
339
+ Suite('flushDiagnostics() re-emits a turn once its per-call usage lands', () => __awaiter(void 0, void 0, void 0, function* () {
340
+ // A turn entry is created BEFORE its model call and priced when the response returns,
341
+ // so a flush landing in between persists it unpriced. Emitting it exactly once more —
342
+ // when `usage` is there — is what keeps per-call cost in a stitched lifetime log;
343
+ // `assembleDebugLog` collapses the pair back onto the priced copy.
344
+ const inFlight = {
345
+ kind: 'turn',
346
+ turnIndex: '0',
347
+ timestamp: '2026-01-01T00:00:01.000Z',
348
+ toolNames: [],
349
+ };
350
+ const { p, f } = makePersister({ diagnosticEntries: [inFlight] });
351
+ yield p.flushDiagnostics();
352
+ assert.is(f.appended.length, 1, 'the unpriced turn is captured');
353
+ assert.is(f.appended[0][0].usage, undefined);
354
+ const priced = Object.assign(Object.assign({}, inFlight), { usage: {
355
+ costUsd: 0.25,
356
+ uncachedInputTokens: 100,
357
+ cacheReadTokens: 900,
358
+ cacheWriteTokens: 0,
359
+ outputTokens: 40,
360
+ } });
361
+ f.diagnosticEntries = [priced];
362
+ yield p.flushDiagnostics();
363
+ assert.is(f.appended.length, 2, 'the priced copy is appended');
364
+ assert.equal(f.appended[1][0].usage, priced.usage);
365
+ // ...and only once. A throttled flush runs on every transcript change, so a turn that
366
+ // re-emitted per flush would multiply the biggest entries in the stream.
367
+ yield p.flushDiagnostics();
368
+ assert.is(f.appended.length, 2, 'no further re-append of the priced turn');
369
+ }));
339
370
  Suite('flushDiagnostics() still dedups a genuine re-append of the same message across flushes', () => __awaiter(void 0, void 0, void 0, function* () {
340
371
  // The dedup must still stop the SAME message being re-appended on every throttled flush.
341
372
  const m = diagMsg({ category: 'reasoning', content: 'thinking…' });