@genesislcap/ai-assistant 15.6.2 → 15.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/ai-assistant.api.json +391 -5
  2. package/dist/ai-assistant.d.ts +613 -6
  3. package/dist/chat-driver.cjs +285 -26
  4. package/dist/chat-driver.cjs.map +3 -3
  5. package/dist/chat-driver.mjs +285 -26
  6. package/dist/chat-driver.mjs.map +3 -3
  7. package/dist/custom-elements.json +254 -10
  8. package/dist/dts/channel/ai-activity-channel.d.ts +51 -1
  9. package/dist/dts/channel/ai-activity-channel.d.ts.map +1 -1
  10. package/dist/dts/components/chat-driver/chat-driver.d.ts +99 -1
  11. package/dist/dts/components/chat-driver/chat-driver.d.ts.map +1 -1
  12. package/dist/dts/components/chat-driver/chat-driver.test.d.ts.map +1 -1
  13. package/dist/dts/components/orchestrating-driver/orchestrating-driver.budget.test.d.ts +2 -0
  14. package/dist/dts/components/orchestrating-driver/orchestrating-driver.budget.test.d.ts.map +1 -0
  15. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts +14 -0
  16. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts.map +1 -1
  17. package/dist/dts/main/blocked-state.test.d.ts +2 -0
  18. package/dist/dts/main/blocked-state.test.d.ts.map +1 -0
  19. package/dist/dts/main/main.d.ts +394 -6
  20. package/dist/dts/main/main.d.ts.map +1 -1
  21. package/dist/dts/main/main.styles.d.ts.map +1 -1
  22. package/dist/dts/main/main.styles.test.d.ts +2 -0
  23. package/dist/dts/main/main.styles.test.d.ts.map +1 -0
  24. package/dist/dts/main/main.template.d.ts +53 -0
  25. package/dist/dts/main/main.template.d.ts.map +1 -1
  26. package/dist/dts/state/ai-assistant-slice.d.ts +162 -6
  27. package/dist/dts/state/ai-assistant-slice.d.ts.map +1 -1
  28. package/dist/dts/state/debug-event-log.d.ts +6 -1
  29. package/dist/dts/state/debug-event-log.d.ts.map +1 -1
  30. package/dist/dts/state/session-store.d.ts +11 -0
  31. package/dist/dts/state/session-store.d.ts.map +1 -1
  32. package/dist/esm/components/chat-driver/chat-driver.js +263 -21
  33. package/dist/esm/components/chat-driver/chat-driver.test.js +464 -1
  34. package/dist/esm/components/orchestrating-driver/orchestrating-driver.budget.test.js +312 -0
  35. package/dist/esm/components/orchestrating-driver/orchestrating-driver.js +89 -4
  36. package/dist/esm/main/blocked-state.test.js +969 -0
  37. package/dist/esm/main/main.js +704 -16
  38. package/dist/esm/main/main.styles.js +47 -0
  39. package/dist/esm/main/main.styles.test.js +86 -0
  40. package/dist/esm/main/main.template.js +121 -4
  41. package/dist/esm/state/ai-assistant-slice.js +145 -7
  42. package/dist/esm/state/ai-assistant-slice.test.js +138 -1
  43. package/dist/esm/state/debug-event-log.js +7 -2
  44. package/dist/esm/state/debug-event-log.test.js +49 -1
  45. package/dist/esm/state/persistence/session-snapshot.test.js +18 -0
  46. package/dist/tsconfig.tsbuildinfo +1 -1
  47. package/docs/migration-GENC-1464.md +562 -0
  48. package/docs/sub_agent.md +20 -3
  49. package/package.json +17 -17
  50. package/src/channel/ai-activity-channel.ts +56 -2
  51. package/src/components/chat-driver/chat-driver.test.ts +549 -0
  52. package/src/components/chat-driver/chat-driver.ts +324 -14
  53. package/src/components/orchestrating-driver/orchestrating-driver.budget.test.ts +438 -0
  54. package/src/components/orchestrating-driver/orchestrating-driver.ts +101 -6
  55. package/src/main/blocked-state.test.ts +1316 -0
  56. package/src/main/main.styles.test.ts +103 -0
  57. package/src/main/main.styles.ts +47 -0
  58. package/src/main/main.template.ts +131 -4
  59. package/src/main/main.ts +704 -10
  60. package/src/state/ai-assistant-slice.test.ts +215 -0
  61. package/src/state/ai-assistant-slice.ts +218 -8
  62. package/src/state/debug-event-log.test.ts +63 -0
  63. package/src/state/debug-event-log.ts +7 -2
  64. package/src/state/persistence/session-snapshot.test.ts +22 -0
@@ -1728,9 +1728,20 @@
1728
1728
  "text": "boolean"
1729
1729
  },
1730
1730
  "privacy": "private",
1731
- "description": "True when a new send must be refused: a turn is running (`busy`), a page-reload\nrestore is loading history that would clobber it (`restoring`), or a manual\ncompaction is rewriting history (`compacting`). Mirrors the composer's\n`?disabled` gate so a **programmatic** `send`/`submitMessage` (e.g. a host's\ncustom input while the built-in composer is hidden) can't slip past it and have\nits message wiped when the restored/compacted history lands (GENC-1351 §6).",
1731
+ "description": "True when a new send must be refused: a turn is running (`busy`), a page-reload\nrestore is loading history that would clobber it (`restoring`), a manual\ncompaction is rewriting history (`compacting`), or a backend condition has\nlocked the assistant outright (`blocked` — e.g. an exhausted AI budget).\nMirrors the composer's `?disabled` gate so a **programmatic**\n`send`/`submitMessage` (e.g. a host's custom input while the built-in composer\nis hidden) can't slip past it and have its message wiped when the\nrestored/compacted history lands (GENC-1351 §6).",
1732
1732
  "readonly": true
1733
1733
  },
1734
+ {
1735
+ "kind": "method",
1736
+ "name": "sendRefusalReason",
1737
+ "privacy": "private",
1738
+ "return": {
1739
+ "type": {
1740
+ "text": "string"
1741
+ }
1742
+ },
1743
+ "description": "Why a programmatic send was refused, for `submitMessage`'s `errors`. A\nbackend block is called out distinctly because — unlike the transient\n\"busy\" cases — waiting and retrying will never clear it, and a caller\nlooping on \"Assistant is busy\" would spin forever."
1744
+ },
1734
1745
  {
1735
1746
  "kind": "method",
1736
1747
  "name": "applyDeferredAgentsSwap",
@@ -1845,6 +1856,142 @@
1845
1856
  },
1846
1857
  "description": "Whether a page-reload restore is in flight (GENC-1351 §6). On the session\nstore (like `compacting`) so the \"Restoring…\" view + input-disable stay in\nsync across pop-in/out. Gating input while true prevents a mid-load send from\nbeing clobbered when the restored history loads."
1847
1858
  },
1859
+ {
1860
+ "kind": "field",
1861
+ "name": "blocked",
1862
+ "type": {
1863
+ "text": "boolean"
1864
+ },
1865
+ "description": "Whether the assistant is blocked by a backend condition and cannot send —\ntoday, an exhausted AI-spend budget (GENC-1464). While true the composer is\ndisabled, `send`/`submitMessage` refuse, suggestions stop being fetched, and\na persistent banner (`part=\"blocked-banner\"`) sits above the composer\nexplaining why. The transcript stays visible and scrollable throughout —\nunlike `compacting` and `restoring`, this does not replace the conversation.\n\n**Latched.** Nothing in the element clears it: not a new turn, not \"Clear\"\n/ \"New chat\", not a pop-in/out. It stays set until the host writes\n`false` — because nothing the user can do inside the assistant refills a\nbudget. Hosts typically set it from their own pre-flight budget check on\nmount, and clear it once a later check shows headroom again.\n\nThe driver also latches it automatically when a turn ends with the\n`'budget-exhausted'` failure reason — off the `tool-loop-end` activity bus\n(which also covers a sub-agent wall, a turn this element did not start, and\nan element swapped in mid-turn) and off the driver's return value (which\ncovers a wall hit during multi-agent classification, where no tool loop ran\nand so no bus event fires). So a host that does no pre-flight at all still\ngets a correct locked UI the moment the first 402 lands. The bus topic is\ntab-scoped, so a wall hit in a popped-out window latches the main window\ntoo — correct for a shared spend cap.\n\n**Lifetime — read this before relying on it as your source of truth.** The\nlatch is in-memory and per-`stateKey`:\n\n- It does **not** survive `switchSession`. Switching away tears the outgoing\n session's store down entirely, so switching back yields a fresh, unblocked\n store.\n- It does **not** survive a page reload. It is deliberately absent from the\n persisted session snapshot: the snapshot is long-lived, so a persisted\n latch would outlive an out-of-band budget raise with no in-element way to\n clear it — a stale lock is worse than re-deriving the state.\n\nThe durable source of truth is therefore the **host's pre-flight**, which\nshould run on mount and on every session switch. See\n`docs/migration-GENC-1464.md` §\"How to adopt\", Option B."
1866
+ },
1867
+ {
1868
+ "kind": "field",
1869
+ "name": "reachableVendors",
1870
+ "type": {
1871
+ "text": "readonly AIProviderType[]"
1872
+ },
1873
+ "description": "The distinct vendors the registry can currently reach, from the provider\nstatuses this element already loads on connect and refreshes on every\nobservable-registry change.\n\nThis is the element's answer to \"which vendor would the next turn use\" — a\nquestion that has **no** correct answer and deliberately gets no API. The\nprovider is resolved per turn AND per agent: `activeProviderInput` may be an\nasync function of the turn's context, an orchestrated turn picks its agent\nwith an LLM `classify()` call, and sub-agents resolve their own providers.\nAny pre-turn \"peek\" would therefore be a guess that is wrong precisely on the\nmulti-agent hosts per-vendor budgets exist for.\n\nAsking instead which vendors are REACHABLE is answerable, synchronous, and\nfree — and it is enough: the composer must stay live while any reachable\nvendor has headroom, and must lock when none does. It also makes vendor-switch\nrecovery a derivation rather than a mutation: a host that swaps its registry\nto another vendor fires the observable, the statuses reload, the walled vendor\ndrops out of this set, and `blocked` goes false with every latch left intact.",
1874
+ "readonly": true
1875
+ },
1876
+ {
1877
+ "kind": "field",
1878
+ "name": "blockedVendors",
1879
+ "type": {
1880
+ "text": "readonly AIProviderType[]"
1881
+ },
1882
+ "description": "Vendors currently walled by the AI-spend budget, in the order they were\nwalled. Empty for a host that never adopts the per-vendor API.\n\nMay include a vendor this registry cannot reach — either because the registry\nmoved on after the wall was latched, or because a 402's\n`otherVendorAvailable: false` walls every vendor the proxy meters (which is\nwhat that verdict is a statement about; see\nFoundationAiAssistant.latchBlockedFrom). Neither costs anything\ninternally — FoundationAiAssistant.blocked asks only about the\nreachable set, and the banner reads the reachability-filtered\nFoundationAiAssistant.relevantBlockedVendors — but a host rendering\nthis list itself should filter it against its own registry.\n\nRead-only on purpose: a settable array would let a host write a partial list\nand silently orphan the per-vendor banner copy.\nFoundationAiAssistant.setVendorBlocked is the write path.",
1883
+ "readonly": true
1884
+ },
1885
+ {
1886
+ "kind": "method",
1887
+ "name": "isVendorBlocked",
1888
+ "return": {
1889
+ "type": {
1890
+ "text": "boolean"
1891
+ }
1892
+ },
1893
+ "parameters": [
1894
+ {
1895
+ "name": "vendor",
1896
+ "type": {
1897
+ "text": "AIProviderType"
1898
+ }
1899
+ }
1900
+ ],
1901
+ "description": "Whether this specific vendor's budget is walled — regardless of whether any\nother vendor still has headroom."
1902
+ },
1903
+ {
1904
+ "kind": "method",
1905
+ "name": "isVendorSwept",
1906
+ "privacy": "private",
1907
+ "return": {
1908
+ "type": {
1909
+ "text": "boolean"
1910
+ }
1911
+ },
1912
+ "parameters": [
1913
+ {
1914
+ "name": "vendor",
1915
+ "type": {
1916
+ "text": "AIProviderType"
1917
+ }
1918
+ }
1919
+ ],
1920
+ "description": "Whether this vendor's wall came from the sweep alone — see the slice's `sweptVendors`."
1921
+ },
1922
+ {
1923
+ "kind": "method",
1924
+ "name": "setVendorBlocked",
1925
+ "return": {
1926
+ "type": {
1927
+ "text": "void"
1928
+ }
1929
+ },
1930
+ "parameters": [
1931
+ {
1932
+ "name": "vendor",
1933
+ "type": {
1934
+ "text": "AIProviderType"
1935
+ }
1936
+ },
1937
+ {
1938
+ "name": "blocked",
1939
+ "type": {
1940
+ "text": "boolean"
1941
+ }
1942
+ },
1943
+ {
1944
+ "name": "reason",
1945
+ "optional": true,
1946
+ "type": {
1947
+ "text": "string | null"
1948
+ }
1949
+ }
1950
+ ]
1951
+ },
1952
+ {
1953
+ "kind": "field",
1954
+ "name": "blockedReason",
1955
+ "type": {
1956
+ "text": "string | null"
1957
+ },
1958
+ "description": "Explanation shown in the blocked banner, or `null` for the element's default\ncopy. Only meaningful while FoundationAiAssistant.blocked is true;\nsetting `blocked = false` clears it.\n\nWritable, and symmetric with every other store-backed accessor on this\nclass: writing it re-latches with the CURRENT `blocked` value, so it changes\nthe copy without disturbing the flag. Assigning `null` clears the\nexplanation while staying blocked (the banner falls back to the default\ncopy). FoundationAiAssistant.setBlocked remains the way to write\nboth in one atomic action."
1959
+ },
1960
+ {
1961
+ "kind": "method",
1962
+ "name": "setBlocked",
1963
+ "return": {
1964
+ "type": {
1965
+ "text": "void"
1966
+ }
1967
+ },
1968
+ "parameters": [
1969
+ {
1970
+ "name": "blocked",
1971
+ "type": {
1972
+ "text": "boolean"
1973
+ }
1974
+ },
1975
+ {
1976
+ "name": "reason",
1977
+ "optional": true,
1978
+ "type": {
1979
+ "text": "string | null"
1980
+ }
1981
+ }
1982
+ ],
1983
+ "description": "Block or unblock the assistant, optionally with custom banner copy.\nEquivalent to the FoundationAiAssistant.blocked setter, plus the\nreason in one atomic write.\n\nBlocking writes the **vendor-agnostic** block — what a host with one budget\npot means — and does not populate\nFoundationAiAssistant.blockedVendors. Unblocking clears the\nper-vendor walls as well, so a host asserting \"the wall is gone\" after its\nown pre-flight cannot be silently overruled by a driver latch it never saw."
1984
+ },
1985
+ {
1986
+ "kind": "field",
1987
+ "name": "transcriptBudgetExhaustedMessage",
1988
+ "type": {
1989
+ "text": "string"
1990
+ },
1991
+ "privacy": "private",
1992
+ "description": "Copy the driver writes into the TRANSCRIPT when a turn hits the budget wall.\n\nA host-set `blockedReason` still wins, so a white-labelled host does not read\nits own explanation in the banner and the shipped default directly below it —\nthat is the whole reason the driver takes this at all.\n\nWhat it deliberately is NOT is\nFoundationAiAssistant.effectiveBlockedReason. That getter\ncomposes advice — `\"…Switch to Gemini to keep going.\"` — which is true only\nwhile that vendor has headroom, and the transcript is a permanent record. The\ndriver reads this once at CONSTRUCTION, and `getOrCreateDriver` keys on the\nagents list, so an agents swap *after* a wall re-runs `createDriver` and would\nfreeze that sentence into every later turn's bubble. Reading the latch's own\ncopy instead is structurally incapable of carrying the advice: the only\nwriter of `blockedReason` is the vendor-agnostic branch of\n`latchBlockedFrom`, whose `formatBlockedReason(budget)` form has no switch\nclause. Per-vendor copy lives in `blockedVendorReasons` and reaches the\nbanner alone.",
1993
+ "readonly": true
1994
+ },
1848
1995
  {
1849
1996
  "kind": "field",
1850
1997
  "name": "pinnedAgentName",
@@ -2375,6 +2522,15 @@
2375
2522
  },
2376
2523
  "privacy": "private"
2377
2524
  },
2525
+ {
2526
+ "kind": "field",
2527
+ "name": "_unsubBudgetLatch",
2528
+ "type": {
2529
+ "text": "() => void | undefined"
2530
+ },
2531
+ "privacy": "private",
2532
+ "description": "Unsubscribe handle for the `tool-loop-end` budget latch (GENC-1464)."
2533
+ },
2378
2534
  {
2379
2535
  "kind": "field",
2380
2536
  "name": "unsubProviderRegistry",
@@ -4475,8 +4631,8 @@
4475
4631
  "type": {
4476
4632
  "text": "readonly string[]"
4477
4633
  },
4478
- "default": "[\n 'This is an exported debug log for the Genesis AI assistant. Read it top-to-bottom.',\n '`timeline` is the entire session as one array, already sorted chronologically by `timestamp` (ISO 8601). Every entry has a `kind`.',\n '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.',\n \"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.\",\n \"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.\",\n \"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.\",\n \"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.\",\n \"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'.\",\n \"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.\",\n '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, 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, 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), 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.',\n '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.',\n \"`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.\",\n '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.',\n]",
4479
- "description": "Human/agent-facing guide emitted as the first key of the exported debug log,\nso whoever opens the JSON (often an AI agent) knows how to read it without\nreverse-engineering the shape. Kept here next to the event catalogue it\ndescribes so the two stay in sync."
4634
+ "default": "[\n 'This is an exported debug log for the Genesis AI assistant. Read it top-to-bottom.',\n '`timeline` is the entire session as one array, already sorted chronologically by `timestamp` (ISO 8601). Every entry has a `kind`.',\n '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.',\n \"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.\",\n \"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.\",\n \"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.\",\n \"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.\",\n \"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'.\",\n \"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.\",\n '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.',\n '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.',\n \"`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.\",\n '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.',\n]",
4635
+ "description": "Human/agent-facing guide emitted as the first key of the exported debug log,\nso whoever opens the JSON (often an AI agent) knows how to read it without\nreverse-engineering the shape. Kept here next to the event catalogue it\ndescribes but proximity alone demonstrably did NOT keep the two in sync\n(`refusal` was missing from both reason lists for a whole release), so\n`debug-event-log.test.ts` now asserts that every `TurnFailureReason` and every\n`SubAgentFailureReason` is named here, and fails the build when one is added\nwithout a matching sentence. Enumerations below read as exhaustive and WILL be\ntrusted by an agent reading the JSON — keep them so."
4480
4636
  }
4481
4637
  ],
4482
4638
  "exports": [
@@ -7254,10 +7410,10 @@
7254
7410
  "kind": "field",
7255
7411
  "name": "subAgentFailure",
7256
7412
  "type": {
7257
- "text": "{ reason: SubAgentFailureReason } | undefined"
7413
+ "text": "{ reason: SubAgentFailureReason; budget?: BudgetDetail } | undefined"
7258
7414
  },
7259
7415
  "privacy": "private",
7260
- "description": "Set when a sub-agent's tool loop ends without `completeSubAgent` being\ncalled. Read by the parent's `invokeSubAgent` to build the `{ ok: false }`\nbranch of `requestSubAgent`. Only ever set when `isSubAgent` is true."
7416
+ "description": "Set when a sub-agent's tool loop ends without `completeSubAgent` being\ncalled. Read by the parent's `invokeSubAgent` to build the `{ ok: false }`\nbranch of `requestSubAgent`. Only ever set when `isSubAgent` is true.\n\n`budget` rides along on a `'budget_exhausted'` failure so the parent inherits\nthe child's ATTRIBUTION, not just the fact of a wall — see\n`budgetWallDetail`."
7261
7417
  },
7262
7418
  {
7263
7419
  "kind": "field",
@@ -7538,6 +7694,46 @@
7538
7694
  "description": "Injected activity bus; defaults to a no-op off-browser (Node/tests/headless).",
7539
7695
  "default": "activityBus"
7540
7696
  },
7697
+ {
7698
+ "kind": "field",
7699
+ "name": "budgetExhaustedMessage",
7700
+ "type": {
7701
+ "text": "string"
7702
+ },
7703
+ "privacy": "private",
7704
+ "readonly": true,
7705
+ "description": "Transcript copy for a budget wall — see `ChatDriverConfig.budgetExhaustedMessage`.",
7706
+ "default": "budgetExhaustedMessage"
7707
+ },
7708
+ {
7709
+ "kind": "field",
7710
+ "name": "budgetExhaustedThisTurn",
7711
+ "type": {
7712
+ "text": "boolean"
7713
+ },
7714
+ "privacy": "private",
7715
+ "default": "false",
7716
+ "description": "Set the moment a budget wall is observed anywhere in this turn — this\ndriver's own 402, or a sub-agent's (which surfaces here only as a\n`'budget_exhausted'` tool result). Read at the top of the tool loop to end\nthe turn before issuing another model call that would hit the same wall.\nReset per turn alongside the other per-turn counters."
7717
+ },
7718
+ {
7719
+ "kind": "field",
7720
+ "name": "budgetWallDetail",
7721
+ "type": {
7722
+ "text": "BudgetDetail | undefined"
7723
+ },
7724
+ "privacy": "private",
7725
+ "description": "The refusing vendor's own attribution for the wall `budgetExhaustedThisTurn`\nrecords, when it was knowable. Kept SEPARATE from the flag rather than\nreplacing it: a figure-less 402 from a transport no vendor claims yields no\ndetail at all (`budgetDetailOf` returns `undefined`), and folding the two\nwould make that case stop ending the turn.\n\nIt matters most for a sub-agent's wall. The child can sit on a different\nvendor from its parent — `applyAgent` reads `config.provider` — so without\nthis the parent's short-circuit reports `lastResolvedProvider`, i.e. the one\nvendor that did NOT refuse. Under a mixed registry that walls Gemini because\nan Anthropic child 402'd, and if those are the only two reachable vendors the\nhost then derives `blocked` and locks a composer that still had headroom."
7726
+ },
7727
+ {
7728
+ "kind": "field",
7729
+ "name": "budgetWallViaSubAgent",
7730
+ "type": {
7731
+ "text": "boolean"
7732
+ },
7733
+ "privacy": "private",
7734
+ "default": "false",
7735
+ "description": "Whether this turn's budget wall came from a SUB-AGENT rather than this\ndriver's own request. Decides whether `lastResolvedProvider` is a valid\nattribution fallback: for an own wall it is the refusing vendor, for a\nchild's wall it is the parent's vendor — the one known NOT to have refused.\nReset per turn alongside `budgetWallDetail`."
7736
+ },
7541
7737
  {
7542
7738
  "kind": "method",
7543
7739
  "name": "dispose",
@@ -7607,6 +7803,13 @@
7607
7803
  "type": {
7608
7804
  "text": "TurnFailureReason"
7609
7805
  }
7806
+ },
7807
+ {
7808
+ "name": "budget",
7809
+ "optional": true,
7810
+ "type": {
7811
+ "text": "BudgetDetail"
7812
+ }
7610
7813
  }
7611
7814
  ],
7612
7815
  "description": "Build the `done` loop result, carrying the typed failure reason when the turn\nbailed (PTC-0). The discriminant stays `'done'` either way — the same value a\nclean turn returns — so consumers matching on `reason === 'done'` are unchanged;\n`failureReason` is simply present on a failure and absent on success. Omitted\n(rather than set to `undefined`) so a happy-path result stays byte-identical to\nthe historical `{ reason: 'done' }`."
@@ -7635,10 +7838,9 @@
7635
7838
  "kind": "method",
7636
7839
  "name": "loopEndDetail",
7637
7840
  "privacy": "private",
7638
- "static": true,
7639
7841
  "return": {
7640
7842
  "type": {
7641
- "text": "{ failureReason: TurnFailureReason } | undefined"
7843
+ "text": "| {\n failureReason: TurnFailureReason;\n vendor?: AIProviderType;\n budget?: BudgetDetail;\n }\n | undefined"
7642
7844
  }
7643
7845
  },
7644
7846
  "parameters": [
@@ -7649,7 +7851,7 @@
7649
7851
  }
7650
7852
  }
7651
7853
  ],
7652
- "description": "Build the `tool-loop-end` event detail for a turn's result. A failure carries a\n`{ failureReason }` detail; a clean turn emits `undefined` — the historical shape,\nkept byte-identical so subscribers see exactly what they always have."
7854
+ "description": "Build the `tool-loop-end` event detail for a turn's result. A failure carries a\n`{ failureReason }` detail; a clean turn emits `undefined` — the historical shape,\nkept byte-identical so subscribers see exactly what they always have.\n\nA budget failure additionally carries `vendor` — the concrete vendor\n(`'anthropic'`/`'gemini'`) the walled turn resolved to, which the driver knows\nand used to discard. Optional and additive: a subscriber reading only\n`failureReason` is unaffected, a non-budget failure still emits the historical\n`{ failureReason }` with no `vendor` key, and the value is a plain string so\nthe detail stays structured-cloneable for the cross-tab hop. It is the field a\nper-vendor budget model needs and the one that would be awkward to retrofit."
7653
7855
  },
7654
7856
  {
7655
7857
  "kind": "method",
@@ -7829,7 +8031,7 @@
7829
8031
  "name": "getSubAgentFailure",
7830
8032
  "return": {
7831
8033
  "type": {
7832
- "text": "{ reason: SubAgentFailureReason } | undefined"
8034
+ "text": "{ reason: SubAgentFailureReason; budget?: BudgetDetail } | undefined"
7833
8035
  }
7834
8036
  },
7835
8037
  "description": "Returns the typed failure recorded when a sub-agent run ended without\n`completeSubAgent`, if any. Called by a parent `ChatDriver` after running\nthis instance as a sub-agent."
@@ -7849,6 +8051,13 @@
7849
8051
  "type": {
7850
8052
  "text": "SubAgentFailureReason"
7851
8053
  }
8054
+ },
8055
+ {
8056
+ "name": "budget",
8057
+ "optional": true,
8058
+ "type": {
8059
+ "text": "BudgetDetail"
8060
+ }
7852
8061
  }
7853
8062
  ],
7854
8063
  "description": "Record a sub-agent failure reason (first one wins). No-op for top-level\nagents, so loop-exit sites can call it unconditionally. The parent reads\nthis via `getSubAgentFailure()` and emits the `subagent.failed` meta event\nunder its *own* session — see `invokeSubAgent`. (A child sub-agent runs\nunder a separate session key, so recording here would orphan the event off\nthe user-visible debug-log timeline.)"
@@ -8867,7 +9076,7 @@
8867
9076
  },
8868
9077
  "privacy": "private",
8869
9078
  "readonly": true,
8870
- "default": "new ChatDriver(providerRegistry, {\n maxToolIterations: options.maxToolIterations,\n maxFoldOperations: options.maxFoldOperations,\n maxTurnSnapshots: options.maxTurnSnapshots,\n sessionKey: this.sessionKey,\n activityBus: options.activityBus,\n })"
9079
+ "default": "new ChatDriver(providerRegistry, {\n maxToolIterations: options.maxToolIterations,\n maxFoldOperations: options.maxFoldOperations,\n maxTurnSnapshots: options.maxTurnSnapshots,\n sessionKey: this.sessionKey,\n activityBus: options.activityBus,\n budgetExhaustedMessage: options.budgetExhaustedMessage,\n })"
8871
9080
  },
8872
9081
  {
8873
9082
  "kind": "field",
@@ -8941,6 +9150,16 @@
8941
9150
  "default": "false",
8942
9151
  "description": "Set by `cancel()` for the duration of a `sendMessage` run. Breaks the\nhandoff loop so we don't classify or start another agent turn after the\nuser stops. Reset at the start of each `sendMessage`."
8943
9152
  },
9153
+ {
9154
+ "kind": "field",
9155
+ "name": "userMessageAppended",
9156
+ "type": {
9157
+ "text": "boolean"
9158
+ },
9159
+ "privacy": "private",
9160
+ "default": "false",
9161
+ "description": "Whether the CURRENT turn's user message has reached the inner driver's\nhistory. False through the pre-first-turn classify (where the only echo of\nthe message is an optimistic `history-updated` dispatch), true from the\nmoment `chatDriver.sendMessage` is entered — including through every later\nhandoff classify. Read by the budget-wall catch in `sendMessage` to decide\nwhether `reportBudgetExhausted` must append the message itself: appending\nit when already appended duplicated it; not appending it when unappended\nmade it vanish. Reset at the top of each `runOrchestratedTurn`."
9162
+ },
8944
9163
  {
8945
9164
  "kind": "field",
8946
9165
  "name": "pinnedAgentName",
@@ -9199,6 +9418,31 @@
9199
9418
  }
9200
9419
  ]
9201
9420
  },
9421
+ {
9422
+ "kind": "method",
9423
+ "name": "runOrchestratedTurn",
9424
+ "privacy": "private",
9425
+ "return": {
9426
+ "type": {
9427
+ "text": "Promise<ChatDriverResult>"
9428
+ }
9429
+ },
9430
+ "parameters": [
9431
+ {
9432
+ "name": "input",
9433
+ "type": {
9434
+ "text": "string"
9435
+ }
9436
+ },
9437
+ {
9438
+ "name": "attachments",
9439
+ "optional": true,
9440
+ "type": {
9441
+ "text": "ChatAttachment[]"
9442
+ }
9443
+ }
9444
+ ]
9445
+ },
9202
9446
  {
9203
9447
  "kind": "method",
9204
9448
  "name": "continueFromHistory",
@@ -1,4 +1,4 @@
1
- import type { TurnFailureReason } from '@genesislcap/foundation-ai';
1
+ import type { AIProviderType, TurnFailureReason } from '@genesislcap/foundation-ai';
2
2
  /**
3
3
  * Event map for the AI activity bus.
4
4
  *
@@ -68,9 +68,59 @@ export interface AgenticActivityEvents {
68
68
  * driver dispose, and an agent handoff the detail is `undefined` — the historical shape,
69
69
  * kept byte-identical so subscribers that only care about the boundary can keep ignoring
70
70
  * it. Structured-cloneable so it survives the cross-tab BroadcastChannel hop.
71
+ *
72
+ * A `'budget-exhausted'` failure additionally carries `vendor` — the concrete
73
+ * vendor the walled turn resolved to (GENC-1464), which is NOT the same thing as
74
+ * the registry alias recorded on the debug-log entry. Optional and additive: a
75
+ * subscriber reading only `failureReason` is unaffected, and every other
76
+ * failure still emits the historical `{ failureReason }` with no `vendor` key.
77
+ * It exists so a later per-vendor budget model is an additive change rather
78
+ * than a retrofit — the vendor is known at the transport and at the driver, and
79
+ * was previously discarded between them.
80
+ *
81
+ * Note this topic is forwarded on the tab-scoped channel, so a wall hit in a
82
+ * popped-out window reaches the main window's subscribers too — which is why
83
+ * the assistant's blocked latch fires there as well. Correct for a shared spend
84
+ * cap; see `docs/migration-GENC-1464.md` §Scope.
71
85
  */
72
86
  'tool-loop-end': {
73
87
  failureReason?: TurnFailureReason;
88
+ vendor?: AIProviderType;
89
+ /**
90
+ * Proxy-reported spend figures, present only on `budget-exhausted`. Carried
91
+ * here because this event — not the driver's return value — is what latches
92
+ * the blocked state for a wall hit INSIDE the tool loop (the common case):
93
+ * the publish happens in `sendMessage`'s `finally`, so it lands before the
94
+ * return-value seam and wins the latch. Without these the banner would fall
95
+ * back to the generic copy in exactly the path the figures were added for.
96
+ * Plain numbers + string keep the detail structured-cloneable for the
97
+ * cross-tab hop.
98
+ */
99
+ budget?: {
100
+ budgetUsd?: number;
101
+ spentUsd?: number;
102
+ vendorLabel: string;
103
+ /**
104
+ * The refusing vendor as a typed value: normalised from `vendorLabel`
105
+ * where a vendor claims that label, otherwise from the proxy's own
106
+ * `vendor` field on the 402 — so it can disagree with `vendorLabel`,
107
+ * which is what keeps attribution working behind a white-labelled or
108
+ * multiplexing gateway.
109
+ *
110
+ * Distinct from the detail's top-level `vendor` (the driver's
111
+ * last-resolved provider): this one comes from the transport that was
112
+ * actually refused, so it is the one a per-vendor latch trusts first.
113
+ */
114
+ vendor?: AIProviderType;
115
+ /**
116
+ * The proxy's verdict on whether any OTHER vendor it meters still has
117
+ * headroom. The one fact here a subscriber cannot work out for itself:
118
+ * the registry says which vendors EXIST, never which still have
119
+ * budget. A `false` is what stops the banner advising a switch to a
120
+ * vendor that is equally spent.
121
+ */
122
+ otherVendorAvailable?: boolean;
123
+ };
74
124
  } | undefined;
75
125
  /**
76
126
  * Fired when a tool handler hands a widget to the user mid-loop and parks awaiting it
@@ -1 +1 @@
1
- {"version":3,"file":"ai-activity-channel.d.ts","sourceRoot":"","sources":["../../../src/channel/ai-activity-channel.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAEpE;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,qBAAqB;IACpC,2FAA2F;IAC3F,YAAY,EAAE;QAAE,SAAS,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IACtC,iFAAiF;IACjF,WAAW,EAAE,SAAS,CAAC;IACvB,mJAAmJ;IACnJ,aAAa,EAAE,SAAS,CAAC;IACzB,wJAAwJ;IACxJ,YAAY,EAAE,SAAS,CAAC;IACxB;;;;;;;;;;;;;;;;;;OAkBG;IACH,iBAAiB,EAAE,SAAS,CAAC;IAC7B;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,eAAe,EAAE;QAAE,aAAa,CAAC,EAAE,iBAAiB,CAAA;KAAE,GAAG,SAAS,CAAC;IACnE;;;;;;;;;;;OAWG;IACH,uBAAuB,EAAE,SAAS,CAAC;IACnC;;;;;OAKG;IACH,sBAAsB,EAAE,SAAS,CAAC;CACnC"}
1
+ {"version":3,"file":"ai-activity-channel.d.ts","sourceRoot":"","sources":["../../../src/channel/ai-activity-channel.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAEpF;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,qBAAqB;IACpC,2FAA2F;IAC3F,YAAY,EAAE;QAAE,SAAS,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IACtC,iFAAiF;IACjF,WAAW,EAAE,SAAS,CAAC;IACvB,mJAAmJ;IACnJ,aAAa,EAAE,SAAS,CAAC;IACzB,wJAAwJ;IACxJ,YAAY,EAAE,SAAS,CAAC;IACxB;;;;;;;;;;;;;;;;;;OAkBG;IACH,iBAAiB,EAAE,SAAS,CAAC;IAC7B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAsCG;IACH,eAAe,EACX;QACE,aAAa,CAAC,EAAE,iBAAiB,CAAC;QAClC,MAAM,CAAC,EAAE,cAAc,CAAC;QACxB;;;;;;;;;WASG;QACH,MAAM,CAAC,EAAE;YACP,SAAS,CAAC,EAAE,MAAM,CAAC;YACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;YAClB,WAAW,EAAE,MAAM,CAAC;YACpB;;;;;;;;;;eAUG;YACH,MAAM,CAAC,EAAE,cAAc,CAAC;YACxB;;;;;;eAMG;YACH,oBAAoB,CAAC,EAAE,OAAO,CAAC;SAChC,CAAC;KACH,GACD,SAAS,CAAC;IACd;;;;;;;;;;;OAWG;IACH,uBAAuB,EAAE,SAAS,CAAC;IACnC;;;;;OAKG;IACH,sBAAsB,EAAE,SAAS,CAAC;CACnC"}