@genesislcap/ai-assistant 15.40.0 → 15.42.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 (73) hide show
  1. package/dist/ai-assistant.api.json +409 -9
  2. package/dist/ai-assistant.d.ts +196 -6
  3. package/dist/chat-driver.cjs +682 -140
  4. package/dist/chat-driver.cjs.map +3 -3
  5. package/dist/chat-driver.mjs +675 -140
  6. package/dist/chat-driver.mjs.map +3 -3
  7. package/dist/custom-elements.json +1007 -436
  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/ai-driver/ai-driver.d.ts +4 -0
  11. package/dist/dts/components/ai-driver/ai-driver.d.ts.map +1 -1
  12. package/dist/dts/components/chat-driver/chat-driver.d.ts +121 -4
  13. package/dist/dts/components/chat-driver/chat-driver.d.ts.map +1 -1
  14. package/dist/dts/components/chat-driver/interaction-controller.d.ts.map +1 -1
  15. package/dist/dts/components/chat-driver/turn-failures.d.ts +7 -1
  16. package/dist/dts/components/chat-driver/turn-failures.d.ts.map +1 -1
  17. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts +3 -1
  18. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts.map +1 -1
  19. package/dist/dts/genesis/index.d.ts +2 -1
  20. package/dist/dts/genesis/index.d.ts.map +1 -1
  21. package/dist/dts/genesis/register-genesis-assistant.d.ts +21 -0
  22. package/dist/dts/genesis/register-genesis-assistant.d.ts.map +1 -1
  23. package/dist/dts/genesis/review-model.d.ts +40 -0
  24. package/dist/dts/genesis/review-model.d.ts.map +1 -1
  25. package/dist/dts/genesis/review-payload.d.ts +47 -0
  26. package/dist/dts/genesis/review-payload.d.ts.map +1 -0
  27. package/dist/dts/genesis/write-review/write-review.d.ts +75 -11
  28. package/dist/dts/genesis/write-review/write-review.d.ts.map +1 -1
  29. package/dist/dts/genesis/write-review/write-review.styles.d.ts.map +1 -1
  30. package/dist/dts/genesis/write-review/write-review.template.d.ts.map +1 -1
  31. package/dist/dts/genesis/write-tools.d.ts +49 -0
  32. package/dist/dts/genesis/write-tools.d.ts.map +1 -1
  33. package/dist/dts/genesis/write-turn.d.ts +114 -0
  34. package/dist/dts/genesis/write-turn.d.ts.map +1 -0
  35. package/dist/dts/index.d.ts +2 -0
  36. package/dist/dts/index.d.ts.map +1 -1
  37. package/dist/dts/main/budget-controller.d.ts +12 -2
  38. package/dist/dts/main/budget-controller.d.ts.map +1 -1
  39. package/dist/dts/main/main.d.ts +33 -6
  40. package/dist/dts/main/main.d.ts.map +1 -1
  41. package/dist/dts/react.d.ts +2 -1
  42. package/dist/dts/state/ai-assistant-slice.d.ts +15 -0
  43. package/dist/dts/state/ai-assistant-slice.d.ts.map +1 -1
  44. package/dist/dts/state/session-store.d.ts +1 -0
  45. package/dist/dts/state/session-store.d.ts.map +1 -1
  46. package/dist/dts/suggestions/generate-suggestions.d.ts.map +1 -1
  47. package/dist/dts/utils/history-transform.d.ts.map +1 -1
  48. package/dist/esm/chat-driver-node.js +5 -1
  49. package/dist/esm/components/chat-driver/chat-driver.js +431 -92
  50. package/dist/esm/components/chat-driver/interaction-controller.js +25 -2
  51. package/dist/esm/components/chat-driver/turn-failures.js +9 -2
  52. package/dist/esm/components/orchestrating-driver/orchestrating-driver.js +30 -4
  53. package/dist/esm/genesis/register-genesis-assistant.js +38 -2
  54. package/dist/esm/genesis/review-model.js +47 -1
  55. package/dist/esm/genesis/review-payload.js +18 -0
  56. package/dist/esm/genesis/write-review/write-review.js +225 -40
  57. package/dist/esm/genesis/write-review/write-review.styles.js +18 -0
  58. package/dist/esm/genesis/write-review/write-review.template.js +46 -22
  59. package/dist/esm/genesis/write-tools.js +321 -49
  60. package/dist/esm/genesis/write-turn.js +110 -0
  61. package/dist/esm/main/budget-controller.js +39 -5
  62. package/dist/esm/main/main.js +45 -23
  63. package/dist/esm/state/ai-assistant-slice.js +11 -1
  64. package/dist/esm/state/debug-event-log.js +1 -1
  65. package/dist/esm/suggestions/generate-suggestions.js +4 -1
  66. package/dist/esm/utils/history-transform.js +7 -1
  67. package/dist/react.cjs +14 -2
  68. package/dist/react.mjs +14 -2
  69. package/docs/genesis.md +120 -3
  70. package/docs/migration-GENC-1464.md +12 -2
  71. package/docs/sub_agent.md +21 -4
  72. package/package.json +18 -18
  73. package/scripts/smoke-chat-driver-node.mjs +15 -0
@@ -8,6 +8,8 @@ import { logger } from '../utils/logger';
8
8
  * variants because the banner names one vendor or several.
9
9
  */
10
10
  const RAISE_LIMIT_ACTION = 'Contact your administrator to raise it.';
11
+ /** The banner for a block that is not a budget wall, when the host gave no reason (GENC-1611). */
12
+ const UNAVAILABLE_REASON = 'The assistant is unavailable.';
11
13
  const RAISE_LIMITS_ACTION = 'Contact your administrator to raise them.';
12
14
  /**
13
15
  * Banner copy built from the figures a 402 actually reported, or `undefined`
@@ -331,8 +333,27 @@ export class BudgetController {
331
333
  return this.reachableVendors.every((v) => session.blockedVendors.includes(v));
332
334
  }
333
335
  set blocked(value) {
334
- var _a;
335
- (_a = this.deps.sessionRef()) === null || _a === void 0 ? void 0 : _a.actions.aiAssistant.setBlocked({ blocked: value });
336
+ this.setBlocked(value);
337
+ }
338
+ /**
339
+ * Whether the block is a spend wall (GENC-1611), which is when the composer may say "AI usage limit
340
+ * reached". Per-vendor walls are budget walls by definition; the vendor-agnostic block says so
341
+ * through its cause, which the driver's own latch sets and a host passes to `setBlocked`.
342
+ *
343
+ * A vendor-agnostic block that gave no cause is a host relabelling budget walls only while the
344
+ * walls still cover every vendor the assistant can reach, and that is only known once the vendors
345
+ * are. Worked out on every read, so statuses that load or a wall that lifts change the answer.
346
+ */
347
+ get blockedByBudget() {
348
+ const session = this.slice;
349
+ if (!session || !this.blocked)
350
+ return false;
351
+ if (!session.blocked)
352
+ return true;
353
+ if (session.blockedCause)
354
+ return session.blockedCause === 'budget';
355
+ const reachable = this.reachableVendors;
356
+ return reachable.length > 0 && reachable.every((v) => session.blockedVendors.includes(v));
336
357
  }
337
358
  /**
338
359
  * The distinct vendors the registry can currently reach, from the provider
@@ -583,9 +604,10 @@ export class BudgetController {
583
604
  * is gone" after its own pre-flight cannot be silently overruled by a driver
584
605
  * latch it never saw.
585
606
  */
586
- setBlocked(blocked, reason) {
607
+ setBlocked(blocked, reason, cause) {
587
608
  var _a;
588
- (_a = this.deps.sessionRef()) === null || _a === void 0 ? void 0 : _a.actions.aiAssistant.setBlocked({ blocked, reason });
609
+ // No cause is stored as none: blockedByBudget decides on read whether it relabels budget walls.
610
+ (_a = this.deps.sessionRef()) === null || _a === void 0 ? void 0 : _a.actions.aiAssistant.setBlocked({ blocked, reason, cause });
589
611
  }
590
612
  /**
591
613
  * Latch the backend block off a turn outcome. The single decision point for
@@ -689,7 +711,11 @@ export class BudgetController {
689
711
  }
690
712
  if (!vendor || vendor === 'none') {
691
713
  if (!this.blocked) {
692
- ref === null || ref === void 0 ? void 0 : ref.actions.aiAssistant.setBlocked({ blocked: true, reason: formatBlockedReason(budget) });
714
+ ref === null || ref === void 0 ? void 0 : ref.actions.aiAssistant.setBlocked({
715
+ blocked: true,
716
+ reason: formatBlockedReason(budget),
717
+ cause: 'budget',
718
+ });
693
719
  }
694
720
  }
695
721
  else if (!this.isVendorBlocked(vendor) || this.isVendorSwept(vendor)) {
@@ -760,6 +786,11 @@ export class BudgetController {
760
786
  var _a, _b;
761
787
  if (this.blockedReason)
762
788
  return this.blockedReason;
789
+ // A block that is not a budget wall, with no reason from the host, says so neutrally rather than
790
+ // telling the user their budget is spent (GENC-1611).
791
+ const session = this.slice;
792
+ if ((session === null || session === void 0 ? void 0 : session.blocked) && !this.blockedByBudget)
793
+ return UNAVAILABLE_REASON;
763
794
  const walled = this.relevantBlockedVendors;
764
795
  if (walled.length === 0)
765
796
  return DEFAULT_BUDGET_EXHAUSTED_MESSAGE;
@@ -888,6 +919,9 @@ __decorate([
888
919
  __decorate([
889
920
  volatile
890
921
  ], BudgetController.prototype, "blocked", null);
922
+ __decorate([
923
+ volatile
924
+ ], BudgetController.prototype, "blockedByBudget", null);
891
925
  __decorate([
892
926
  volatile
893
927
  ], BudgetController.prototype, "reachableVendors", null);
@@ -134,14 +134,19 @@ const SESSION_PERSISTENCE_SOURCE = 'session';
134
134
  */
135
135
  const DEFAULT_PERSISTENCE_SOURCE = 'host';
136
136
  /**
137
- * Composer placeholder while the assistant is blocked (GENC-1464). Deliberately
137
+ * Composer placeholder while a budget wall blocks the assistant (GENC-1464). Deliberately
138
138
  * fixed and short, and NOT host-overridable — the banner directly above it
139
139
  * carries the detail, and that one IS overridable via `setBlocked(true, reason)`.
140
140
  * The banner's own default copy is `DEFAULT_BUDGET_EXHAUSTED_MESSAGE`, read
141
141
  * straight from `foundation-ai` so the banner and the driver's transcript bubble
142
142
  * cannot drift apart.
143
143
  */
144
- const BLOCKED_PLACEHOLDER = 'AI usage limit reached';
144
+ const BUDGET_BLOCKED_PLACEHOLDER = 'AI usage limit reached';
145
+ /**
146
+ * Composer placeholder for every other block (GENC-1611): no right to use the chat, AI switched
147
+ * off, a host's own reason. Neutral, because it is true of all of them; the banner says which.
148
+ */
149
+ const UNAVAILABLE_PLACEHOLDER = 'Assistant unavailable';
145
150
  /**
146
151
  * How often the transcript's relative timestamps are recomputed (GENC-1257).
147
152
  *
@@ -865,7 +870,10 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
865
870
  * / "New chat", not a pop-in/out. It stays set until the host writes
866
871
  * `false` — because nothing the user can do inside the assistant refills a
867
872
  * budget. Hosts typically set it from their own pre-flight budget check on
868
- * mount, and clear it once a later check shows headroom again.
873
+ * mount, and clear it once a later check shows headroom again. Such a host
874
+ * should use `setBlocked(true, reason, { cause: 'budget' })`: a plain
875
+ * `blocked = true` is taken for a budget wall only while per-vendor budget
876
+ * walls cover every vendor the assistant can reach (GENC-1611).
869
877
  *
870
878
  * The driver also latches it automatically when a turn ends with the
871
879
  * `'budget-exhausted'` failure reason — off the `tool-loop-end` activity bus
@@ -1137,16 +1145,20 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
1137
1145
  * Equivalent to the {@link FoundationAiAssistant.blocked} setter, plus the
1138
1146
  * reason in one atomic write.
1139
1147
  *
1140
- * Blocking writes the **vendor-agnostic** block — what a host with one budget
1141
- * pot means — and does not populate
1148
+ * Blocking writes the **vendor-agnostic** block and does not populate
1142
1149
  * {@link FoundationAiAssistant.blockedVendors}. Unblocking clears the
1143
1150
  * per-vendor walls as well, so a host asserting "the wall is gone" after its
1144
1151
  * own pre-flight cannot be silently overruled by a driver latch it never saw.
1145
1152
  *
1153
+ * `options.cause` says why (GENC-1611). Pass `'budget'` for a spend wall, so the composer reads
1154
+ * "AI usage limit reached"; any other block reads "Assistant unavailable". Omitted, a block keeps
1155
+ * the cause it already has, and a new one reads as a budget wall only while per-vendor budget walls
1156
+ * cover every vendor the assistant can reach.
1157
+ *
1146
1158
  * @beta
1147
1159
  */
1148
- setBlocked(blocked, reason) {
1149
- this.budget.setBlocked(blocked, reason);
1160
+ setBlocked(blocked, reason, options) {
1161
+ this.budget.setBlocked(blocked, reason, options === null || options === void 0 ? void 0 : options.cause);
1150
1162
  }
1151
1163
  /**
1152
1164
  * Copy shown in the blocked banner — the host's override, else copy composed
@@ -1785,6 +1797,7 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
1785
1797
  maxTurnSnapshots: agent.maxTurnSnapshots,
1786
1798
  activityBus: agenticActivityBus,
1787
1799
  budgetExhaustedMessage: this.transcriptBudgetExhaustedMessage,
1800
+ aiServiceErrorMessages: this.aiServiceErrorMessages,
1788
1801
  });
1789
1802
  }
1790
1803
  return new ChatDriver(this.providerRegistry, {
@@ -1794,6 +1807,7 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
1794
1807
  sessionKey: (_c = this.getStateKey()) !== null && _c !== void 0 ? _c : '',
1795
1808
  activityBus: agenticActivityBus,
1796
1809
  budgetExhaustedMessage: this.transcriptBudgetExhaustedMessage,
1810
+ aiServiceErrorMessages: this.aiServiceErrorMessages,
1797
1811
  });
1798
1812
  }
1799
1813
  /**
@@ -2090,7 +2104,10 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
2090
2104
  // disconnectedCallback resets state to 'idle', so we must check real driver state here.
2091
2105
  if ((_c = this.driver) === null || _c === void 0 ? void 0 : _c.isBusy()) {
2092
2106
  this.state = 'loading';
2093
- this.startLoadingTimer();
2107
+ // The rule `handleMessagesUpdate` follows, on a remount too: a turn parked on a widget the
2108
+ // user has not answered is waiting, not working. Started unconditionally, the dots showed
2109
+ // under an open review after a pop-out or a dock move, and stayed until it was answered.
2110
+ this.syncLoadingIndicator();
2094
2111
  // Subscribe once so that when the originating send() completes (possibly on a
2095
2112
  // different element instance that has since disconnected), this element cleans up
2096
2113
  // its own timer, syncs the halo, and triggers the post-response suggestion fetch.
@@ -2466,19 +2483,8 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
2466
2483
  // individual step gets a fresh window before the spinner appears.
2467
2484
  // If the last message is a blocking interaction, stop the timer — the AI is
2468
2485
  // waiting for the user, not computing.
2469
- if (this.busy) {
2470
- const last = this.messages[this.messages.length - 1];
2471
- // Only a *pending* interaction means the assistant is blocked waiting on
2472
- // the user. Once it's resolved — or for any normal step — the assistant is
2473
- // computing again, so the indicator should resume (e.g. while it works out
2474
- // the next planning question after the user answers a widget).
2475
- if ((last === null || last === void 0 ? void 0 : last.interaction) && !last.interaction.resolved) {
2476
- this.stopLoadingTimer();
2477
- }
2478
- else {
2479
- this.startLoadingTimer();
2480
- }
2481
- }
2486
+ if (this.busy)
2487
+ this.syncLoadingIndicator();
2482
2488
  this.syncShowHalo();
2483
2489
  this.syncShowingSplash();
2484
2490
  // Context size, from the estimator rather than from the last raw measurement.
@@ -2601,6 +2607,21 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
2601
2607
  this.clearLoadingTimer();
2602
2608
  this.showLoadingIndicator = false;
2603
2609
  }
2610
+ /**
2611
+ * The loading indicator for a turn that is running: shown, unless the turn is parked on the
2612
+ * user.
2613
+ *
2614
+ * @remarks
2615
+ * Only a *pending* interaction means the assistant is blocked waiting on the user. Once it's
2616
+ * resolved — or for any normal step — the assistant is computing again, so the indicator should
2617
+ * resume (e.g. while it works out the next planning question after the user answers a widget).
2618
+ */
2619
+ syncLoadingIndicator() {
2620
+ if (this.hasActivePendingInteraction)
2621
+ this.stopLoadingTimer();
2622
+ else
2623
+ this.startLoadingTimer();
2624
+ }
2604
2625
  /** Called when the user clicks the popout button. */
2605
2626
  handlePopout() {
2606
2627
  if (this.popoutMode === 'expand') {
@@ -3453,8 +3474,9 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
3453
3474
  get effectivePlaceholder() {
3454
3475
  // The block outranks the agent pin: while blocked the composer is disabled
3455
3476
  // anyway, so naming the pinned agent would only imply a send is possible.
3456
- if (this.blocked)
3457
- return BLOCKED_PLACEHOLDER;
3477
+ if (this.blocked) {
3478
+ return this.budget.blockedByBudget ? BUDGET_BLOCKED_PLACEHOLDER : UNAVAILABLE_PLACEHOLDER;
3479
+ }
3458
3480
  // The full explanation, not a stub. With no banner above it this is the only
3459
3481
  // place the remedy is stated, and the composer it sits in is the control the
3460
3482
  // remedy is about — so the sentence is where the user is already looking.
@@ -33,6 +33,7 @@ export function createDefaultSessionState() {
33
33
  restoring: false,
34
34
  blocked: false,
35
35
  blockedReason: null,
36
+ blockedCause: null,
36
37
  blockedVendors: [],
37
38
  sweptVendors: [],
38
39
  blockedVendorReasons: {},
@@ -155,16 +156,24 @@ export const aiAssistantSlice = createSlice({
155
156
  * `setBlocked(false)` that used to unblock would leave the composer locked.
156
157
  */
157
158
  setBlocked(state, action) {
159
+ var _a;
160
+ const wasBlocked = state.blocked;
158
161
  state.blocked = action.payload.blocked;
159
162
  if (!action.payload.blocked) {
160
163
  state.blockedReason = null;
164
+ state.blockedCause = null;
161
165
  state.blockedVendors = [];
162
166
  state.sweptVendors = [];
163
167
  state.blockedVendorReasons = {};
168
+ return;
164
169
  }
165
- else if (action.payload.reason !== undefined) {
170
+ if (action.payload.reason !== undefined) {
166
171
  state.blockedReason = action.payload.reason;
167
172
  }
173
+ // Like the reason, an omitted cause keeps the one already there, so a host relabelling a
174
+ // budget latch leaves it a budget block. A new block that says nothing stores nothing: whether
175
+ // it reads as a budget wall depends on walls that can change after it is set.
176
+ state.blockedCause = (_a = action.payload.cause) !== null && _a !== void 0 ? _a : (wasBlocked ? state.blockedCause : null);
168
177
  },
169
178
  /**
170
179
  * Write the banner explanation without touching the flag.
@@ -346,6 +355,7 @@ export const aiAssistantSlice = createSlice({
346
355
  providerStatuses: state.providerStatuses,
347
356
  blocked: state.blocked,
348
357
  blockedReason: state.blockedReason,
358
+ blockedCause: state.blockedCause,
349
359
  blockedVendors: state.blockedVendors,
350
360
  sweptVendors: state.sweptVendors,
351
361
  blockedVendorReasons: state.blockedVendorReasons,
@@ -222,7 +222,7 @@ export const DEBUG_LOG_README = [
222
222
  "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.",
223
223
  "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'.",
224
224
  "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.",
225
- '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/provider-refused/context-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, for provider-refused the kind (spend|auth) plus the upstream status and error type — the vendor refusing the ACCOUNT rather than us refusing to spend, so the remedy is a top-up or a key rotation rather than a raised cap, and the kind is the only place that distinction survives because the user-facing copy is deliberately cause-free, for context-exhausted the estimated contextTokens against the guard that stopped the turn plus the iterations reached — the driver ending a runaway tool loop at the edge of the context window rather than issuing a request the provider would reject, so the transcript survives intact and can still be compacted, 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/provider_refused/context_exhausted; budget_exhausted, provider_refused and context_exhausted are all 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), routing.decided (ONE PER ROUTING DECISION — see its own paragraph below), 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.',
225
+ '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/provider-refused/context-exhausted/ai-service-error, 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, for provider-refused the kind (spend|auth) plus the upstream status and error type — the vendor refusing the ACCOUNT rather than us refusing to spend, so the remedy is a top-up or a key rotation rather than a raised cap, and the kind is the only place that distinction survives because the user-facing copy is deliberately cause-free, for context-exhausted the estimated contextTokens against the guard that stopped the turn plus the iterations reached — the driver ending a runaway tool loop at the edge of the context window rather than issuing a request the provider would reject, so the transcript survives intact and can still be compacted, for ai-service-error the code (one of AI_SERVICE_ERROR_CODES, e.g. NO_API_KEY) and the status the AI service answered with — its own text goes to the browser console only, 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/provider_refused/context_exhausted/ai_service_error; budget_exhausted and provider_refused are terminal for the PARENT turn too, and so is ai_service_error when the refusal is about the service rather than the request and came from the vendor the parent calls — the parent stops rather than calling the model again into the same wall; after context_exhausted the parent goes on, but its own next call is likely to stop on the same guard), agent.handoff (routing; from=null is the initial activation), agent.pinned/unpinned (forced routing), routing.decided (ONE PER ROUTING DECISION — see its own paragraph below), 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.',
226
226
  '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.',
227
227
  "`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.",
228
228
  '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.',
@@ -1,4 +1,5 @@
1
1
  import { __awaiter } from "tslib";
2
+ import { reachesProvider } from '../utils/context-tokens';
2
3
  import { logger } from '../utils/logger';
3
4
  /** Turns of transcript given to the model when suggesting follow-ups. */
4
5
  const HISTORY_WINDOW = 8;
@@ -63,10 +64,12 @@ export function buildSuggestionsPrompt(ctx, history, prompt, count, allAgentInfo
63
64
  guidanceBlock +
64
65
  OUTPUT_FORMAT(count));
65
66
  }
67
+ // What the model saw, and nothing the driver wrote: a notice here would be put back to the model.
66
68
  const conversationContext = history
67
69
  .filter((m) => {
68
70
  var _a, _b;
69
- return (m.role === 'user' || m.role === 'assistant') &&
71
+ return reachesProvider(m) &&
72
+ (m.role === 'user' || m.role === 'assistant') &&
70
73
  !((_a = m.toolCalls) === null || _a === void 0 ? void 0 : _a.length) &&
71
74
  !m.thinking &&
72
75
  !!((_b = m.content) === null || _b === void 0 ? void 0 : _b.trim());
@@ -237,7 +237,13 @@ function renderMessageForSummary(m) {
237
237
  * combined summary.
238
238
  */
239
239
  export function buildCompactionSummaryPrompt(toCompact) {
240
- const transcript = toCompact.map(renderMessageForSummary).filter(Boolean).join('\n');
240
+ // A driver notice never reached the model, so it does not reach it through the summary either.
241
+ // Only that flag is filtered: reasoning and narration are folded in on purpose (above).
242
+ const transcript = toCompact
243
+ .filter((m) => !m.excludeFromProvider)
244
+ .map(renderMessageForSummary)
245
+ .filter(Boolean)
246
+ .join('\n');
241
247
  const systemPrompt = 'You compress a conversation transcript into a concise summary that lets an AI ' +
242
248
  'assistant continue the conversation seamlessly. Preserve key facts, decisions, ' +
243
249
  'what the user wants, entity names and IDs, and any unresolved threads. Write ' +
package/dist/react.cjs CHANGED
@@ -146,8 +146,20 @@ const FoundationAiPopoutManager = React.forwardRef(function FoundationAiPopoutMa
146
146
  });
147
147
 
148
148
  const GenesisWriteReview = React.forwardRef(function GenesisWriteReview(props, ref) {
149
- const { children, ...rest } = props;
150
- return React.createElement(customElements.getName(GenesisWriteReviewWC) ?? 'GENESIS_WRITE_REVIEW', { ...rest, ref }, children);
149
+ const { onInteractionCompleted, children, ...rest } = props;
150
+ const _innerRef = React.useRef(null);
151
+ const _onInteractionCompletedRef = React.useRef(onInteractionCompleted);
152
+ _onInteractionCompletedRef.current = onInteractionCompleted;
153
+ React.useLayoutEffect(() => {
154
+ const el = _innerRef.current;
155
+ if (!el) return;
156
+ const _onInteractionCompletedFn = (e) => _onInteractionCompletedRef.current?.(e);
157
+ el.addEventListener('interaction-completed', _onInteractionCompletedFn);
158
+ return () => {
159
+ el.removeEventListener('interaction-completed', _onInteractionCompletedFn);
160
+ };
161
+ }, []);
162
+ return React.createElement(customElements.getName(GenesisWriteReviewWC) ?? 'GENESIS_WRITE_REVIEW', { ...rest, ref: _mergeRefs(_innerRef, ref) }, children);
151
163
  });
152
164
 
153
165
  module.exports = {
package/dist/react.mjs CHANGED
@@ -144,6 +144,18 @@ export const FoundationAiPopoutManager = React.forwardRef(function FoundationAiP
144
144
  });
145
145
 
146
146
  export const GenesisWriteReview = React.forwardRef(function GenesisWriteReview(props, ref) {
147
- const { children, ...rest } = props;
148
- return React.createElement(customElements.getName(GenesisWriteReviewWC) ?? 'GENESIS_WRITE_REVIEW', { ...rest, ref }, children);
147
+ const { onInteractionCompleted, children, ...rest } = props;
148
+ const _innerRef = React.useRef(null);
149
+ const _onInteractionCompletedRef = React.useRef(onInteractionCompleted);
150
+ _onInteractionCompletedRef.current = onInteractionCompleted;
151
+ React.useLayoutEffect(() => {
152
+ const el = _innerRef.current;
153
+ if (!el) return;
154
+ const _onInteractionCompletedFn = (e) => _onInteractionCompletedRef.current?.(e);
155
+ el.addEventListener('interaction-completed', _onInteractionCompletedFn);
156
+ return () => {
157
+ el.removeEventListener('interaction-completed', _onInteractionCompletedFn);
158
+ };
159
+ }, []);
160
+ return React.createElement(customElements.getName(GenesisWriteReviewWC) ?? 'GENESIS_WRITE_REVIEW', { ...rest, ref: _mergeRefs(_innerRef, ref) }, children);
149
161
  });
package/docs/genesis.md CHANGED
@@ -57,8 +57,10 @@ A blocked registration registers no providers.
57
57
 
58
58
  The agent runs on the registry's default provider, which is the configured tier. Its system prompt
59
59
  is the configured prompt, then a fixed rule that tool results are app data and never
60
- instructions, then a fixed rule for reading a write's per-row outcome (never write an `unknown`
61
- row again), then the extensions' prompt.
60
+ instructions, then its one exception (a change request the user typed into a write review, see
61
+ [The user's answer](#the-users-answer)), then a fixed rule for reading a write's per-row outcome
62
+ (never write an `unknown` row again, and never re-propose a denied write, or any other write to
63
+ that table, unless asked), then the extensions' prompt.
62
64
 
63
65
  ---
64
66
 
@@ -183,6 +185,68 @@ row can be changed in that time. Committing the payload built from the row as it
183
185
  write the reviewed values straight over somebody else's change, and the server would ACK it.
184
186
  A row that moved is reported as `changed_since_review` and left alone.
185
187
 
188
+ ### The user's answer
189
+
190
+ The review offers three answers:
191
+
192
+ - **Write N rows** commits the ticked rows, as above. It is disabled until a row is ticked; rows
193
+ start unticked.
194
+ - **Ask for changes** opens a text box, which takes up to 1000 characters and counts down to the
195
+ limit; the tool cuts what reaches the model at the same number. Sending it writes **nothing**,
196
+ whatever is ticked. The
197
+ model receives the text as `userFeedback: { authoredBy: 'user', key, text, rowsTicked? }` at the
198
+ top of the tool's result, with a fixed `next: { key, text }` telling it to propose again through
199
+ the same tool. The
200
+ new proposal gets a fresh review that opens unticked. `rowsTicked` lists the rows that were
201
+ ticked, by the same indexes as the result's `rows`, as context only: it approves nothing. The
202
+ request also shows on the user's side of the chat, as the literal words the model gets: markdown
203
+ in it is shown, not rendered.
204
+ - **Deny** is one click with no reason. The model is told not to propose the write, or any other
205
+ write to that table, again unless the user asks, and which write tools will refuse one.
206
+
207
+ **Stop** ends it too. A write the user stopped before its review opened shows nothing; a review
208
+ open when they stop closes unanswered, like one that timed out; and nothing is committed once the
209
+ turn is stopped, even if an Approve lands first. A Stop pressed while approved rows are being
210
+ written stops the rest: rows already committed are reported as written, and every row not yet
211
+ sent is reported `failed` with "Not written: the user stopped the turn."
212
+
213
+ The text is capped at 1000 characters and never reaches the event's `REASON` or `DETAILS`. The
214
+ system prompt makes `userFeedback` and `next` the one exception to "tool results are data", and
215
+ only when their `key` matches the one it names. A shape proves nothing: an app's own tool can
216
+ return any text, including a perfect copy of a write result. The key is random, minted once per
217
+ `registerGenesisAssistant`, and written only into the prompt and into what the write tools
218
+ return, so nothing that stores or returns data can know it. A session replayed from an earlier
219
+ registration carries an older key, and its feedback then reads as data. An app with no event
220
+ resources has no write tools, and its prompt carries no exception at all.
221
+
222
+ Three rules hold for the rest of the **turn** (the answer to one user message), in code rather
223
+ than in the prompt: a denial per table, the other two per event:
224
+
225
+ - after a **denial**, the write tools for that table refuse a proposal for the rest of the user's
226
+ message, before anything is read or shown. A write tool's table comes from its name
227
+ (`EVENT_<T>_INSERT`, `_MODIFY` or `_DELETE`), or, for a modify or delete without one, from its
228
+ row source; a write tool with neither locks only itself. A row source that is a view locks under
229
+ the view's name. The denial's `next` names the tools it locks;
230
+ - the user may ask for changes on **four** reviews: the first proposal and three revisions. After
231
+ the fourth request the model is told that was the last round, the next call is refused, and it
232
+ asks in chat instead;
233
+ - a proposal **identical** to the one the user just asked to change is refused without a review.
234
+ Proposals are compared on the payloads they would write, field by field by type, so `'900'` and
235
+ `900` for an INT are the same proposal. A modify is compared on what it changes, so a column
236
+ somebody else edited between the two reviews does not make a resend new. Rows are matched by
237
+ the key the model named them by, in any order, and what a row's outcome would say (such as a
238
+ blank kept as the row's value) is part of the proposal.
239
+
240
+ A turn is recognised by the `turnSignal` the chat driver passes each tool call. It spans the whole
241
+ user message: an orchestrated handoff that comes back to the same agent, and a sub-agent the
242
+ message delegates to, get the same one, so neither starts the rules over. A Stop ends it, even one
243
+ pressed between an orchestrated message's turns, and a continuation from history after a Stop
244
+ starts a new one, free of the stopped message's denials and rounds. A host that
245
+ builds its own tool context without one gets a single turn for the life of the tools, shared by
246
+ every chat view, and all three rules with it: a denial holds until the tools are recreated,
247
+ change requests count across every message (so the fourth ends revisions for good), and a resend
248
+ is compared with the last proposal asked about in any message. The first such call logs a warning.
249
+
186
250
  ### A modify needs somewhere to read its rows from
187
251
 
188
252
  A generated CRUD modify **replaces** the record, so a payload carrying only the fields the model
@@ -260,7 +324,9 @@ and the tool list should be a true map of what the assistant can do.
260
324
 
261
325
  ### Reading the result
262
326
 
263
- Each row gets its own outcome; a failure does not stop the rest of the batch. `committed: true`
327
+ The result's `decision` is what the user answered: `approved`, `denied`, `changes_requested` or
328
+ `timed_out`; anything but an approval also carries a `next`. Each row gets its own outcome; a
329
+ failure does not stop the rest of the batch. `committed: true`
264
330
  means the row reached the database. `committed: false` does **not** mean it did not: a row whose
265
331
  status is `unknown` was sent, and no answer settled it: none came, the one that came could not be
266
332
  read, or it was a `MSG_NACK` other than a 404. The server may well have written it. Never retry
@@ -285,6 +351,57 @@ anything, for an app that assembles its own agent.
285
351
 
286
352
  ---
287
353
 
354
+ ## When the chat endpoint refuses
355
+
356
+ The app's chat endpoint (`/gwf/ai-service/<vendor>/chat`) names each refusal in the body's `code`.
357
+ The assistant reads the code, not the status, so a missing key is sent once whether it comes back as
358
+ a `424` or a `503`. It ends the turn and tells the user in words, with a hint for whoever runs the app:
359
+
360
+ | Code | Meaning | Retried? |
361
+ | ------------------------- | ------------------------------------------------------ | --------------------------- |
362
+ | `NO_API_KEY` | No API key is configured for the vendor. | No |
363
+ | `BAD_API_KEY` | The key has characters an API key cannot have. | No |
364
+ | `KEY_UNREADABLE` | An encrypted key could not be decrypted. | No |
365
+ | `MODEL_NOT_ALLOWED` | The request asked for a model the app does not allow. | No |
366
+ | `BAD_REQUEST` | The endpoint refused the shape of the request. | No |
367
+ | `FALLBACKS_NOT_SUPPORTED` | The request named fallback models. | No |
368
+ | `REQUEST_TOO_LARGE` | The request is larger, or nested deeper, than allowed. | No |
369
+ | `VENDOR_UNREACHABLE` | The endpoint could not reach the vendor. | Yes, like any passing fault |
370
+
371
+ The app's router can refuse a request before the endpoint runs: with no session (401), or when the
372
+ user lacks the `AI_CHAT` right the endpoint demands (403). Its reply is the router's own NACK
373
+ (`MESSAGE_TYPE: 'MSG_NACK'`, an `ERROR` list) and carries no `code`. The assistant recognises a 401 or
374
+ 403 with that NACK, or with an empty body, and tells the user their session has ended, or that they
375
+ don't have access and an administrator can give it. These two, `SIGNED_OUT` and `ACCESS_DENIED`, are
376
+ `AI_SERVICE_ACCESS_REFUSALS`, kept apart from the codes an endpoint sends. Any other 401 or 403 (a
377
+ vendor's own, or an HTML page from a proxy in between) keeps its own handling.
378
+
379
+ The router also caps a request's size, and refuses a larger one with a 413 before the endpoint runs. A
380
+ 413 with no `code` and an empty or non-JSON body is read as `REQUEST_TOO_LARGE`, and not sent again.
381
+
382
+ A code not in this list is handled by its status, as before. The sentences are
383
+ `DEFAULT_AI_SERVICE_ERROR_MESSAGES` in `@genesislcap/foundation-ai`, next to `AI_SERVICE_ERROR_CODES`
384
+ and `AIServiceError`. Replace any of them before the element connects:
385
+
386
+ ```ts
387
+ assistant.aiServiceErrorMessages = {
388
+ NO_API_KEY: 'The assistant is not set up yet. Ask the platform team for an API key.',
389
+ };
390
+ ```
391
+
392
+ The endpoint's own text goes to the browser console. It is not shown to the user, sent to the model or
393
+ written to the debug log, which records the code and the status.
394
+
395
+ ### The composer while blocked
396
+
397
+ `setBlocked(true, blockedReason)` puts the reason in the banner above the composer, and the composer
398
+ reads **Assistant unavailable**. With no reason, the banner reads "The assistant is unavailable." rather
399
+ than the budget sentence. **AI usage limit reached** is kept for a spend wall: the assistant's own
400
+ budget latch, per-vendor walls (and a cause-less block laid over them), or
401
+ `setBlocked(true, reason, { cause: 'budget' })`.
402
+
403
+ ---
404
+
288
405
  ## Why a separate entry point
289
406
 
290
407
  The bridge imports `@genesislcap/foundation-comms`. This package declares no `sideEffects`, so
@@ -163,7 +163,7 @@ it stays in sync across pop-in/pop-out — with **two deliberate differences**:
163
163
 
164
164
  While blocked: the composer textarea and send button are disabled, the attach button is
165
165
  disabled, the suggestion chips are hidden, the placeholder swaps to
166
- `AI usage limit reached`, no suggestion requests are issued (each one would be a
166
+ `AI usage limit reached` (for a budget wall only since GENC-1611, see below), no suggestion requests are issued (each one would be a
167
167
  guaranteed `402`), and `send()` / `submitMessage()` refuse. `submitMessage` returns
168
168
  `{ ok: false, errors: [<the blocked reason>] }` rather than the transient
169
169
  `'Assistant is busy'`, so a caller looping on "busy" doesn't spin forever.
@@ -464,6 +464,7 @@ async function applyBudgetGate(assistantEl: FoundationAiAssistant) {
464
464
  withinBudget
465
465
  ? null
466
466
  : `AI usage limit reached ($${spentUsd} of $${budgetUsd}). Contact Genesis to increase it.`,
467
+ { cause: 'budget' },
467
468
  );
468
469
  }
469
470
 
@@ -476,9 +477,18 @@ await applyBudgetGate(assistantEl);
476
477
  Pass no `reason` to use the default copy:
477
478
 
478
479
  ```ts
479
- assistantEl.blocked = true;
480
+ assistantEl.setBlocked(true, undefined, { cause: 'budget' });
480
481
  ```
481
482
 
483
+ > **Since GENC-1611, say that the block is a budget wall.** The composer reads
484
+ > `AI usage limit reached` only for one: the driver's own latch, a per-vendor wall, or a
485
+ > `setBlocked` call with `{ cause: 'budget' }`. Any other block, including `blocked = true`
486
+ > and a `setBlocked` call without a cause, reads `Assistant unavailable`, because most of them
487
+ > are not about money: no right to use the chat, AI switched off for the build. Its banner, when no
488
+ > reason is given, reads `The assistant is unavailable.` rather than the budget sentence. A call
489
+ > without a cause while already blocked by a budget wall keeps it one, whether the driver latched it
490
+ > for one vendor or for all, so relabelling the driver's latch (Option C) needs no change.
491
+
482
492
  Release it once a later check shows headroom (unblocking always clears the reason, so a
483
493
  stale explanation can never outlive the condition):
484
494
 
package/docs/sub_agent.md CHANGED
@@ -133,7 +133,12 @@ When `completeSubAgent` is called, the sub-agent's tool loop exits and `requestS
133
133
  The return type of `requestSubAgent<T>` is:
134
134
 
135
135
  ```ts
136
- Promise<{ ok: true; result: T } | { ok: false; reason: SubAgentFailureReason }>;
136
+ Promise<
137
+ | { ok: true; result: T }
138
+ | { ok: false; reason: Exclude<SubAgentFailureReason, 'ai_service_error'> }
139
+ // Narrowing on this reason gives both fields, always set.
140
+ | { ok: false; reason: 'ai_service_error'; code: AIServiceRefusal; terminal: boolean }
141
+ >;
137
142
 
138
143
  type SubAgentFailureReason =
139
144
  | 'max_iterations'
@@ -143,7 +148,10 @@ type SubAgentFailureReason =
143
148
  | 'timeout'
144
149
  | 'response_truncated'
145
150
  | 'refusal'
146
- | 'budget_exhausted';
151
+ | 'budget_exhausted'
152
+ | 'provider_refused'
153
+ | 'context_exhausted'
154
+ | 'ai_service_error';
147
155
  ```
148
156
 
149
157
  Branch on `ok` in the calling handler — but **the right recovery depends on which
@@ -155,6 +163,9 @@ reason you got**, and the two groups are opposites:
155
163
  | `response_truncated` | **Do not retry as-is** — re-issuing the same request hits the same output-token cap. Retry only with a smaller step, or raise the provider's `maxTokens`. |
156
164
  | `refusal` | **Terminal.** A safety-classifier decline is deterministic; the same request will be declined again. Return a terse error. |
157
165
  | `budget_exhausted` | **Terminal, and already handled for you.** The AI-spend budget is gone and the proxy is refusing every request. Retrying is another `402`, and "ask the user" is asking someone who cannot fix it. Return a terse error and let the turn end — the parent driver ends the turn as soon as this outcome comes back, so your handler will not be called again this turn. |
166
+ | `provider_refused` | **Terminal, and already handled for you.** The vendor refused the account (a revoked key, a suspended organisation). Retrying gets the same refusal. Return a terse error: the parent driver ends the turn before its next model call, as for `budget_exhausted`. |
167
+ | `context_exhausted` | **Terminal.** The sub-agent stopped because going on would overrun the context window. Re-invoking it with the same conversation stops it the same way, and your own next model call is likely to stop on the same guard. Return a terse error; a new conversation, or a smaller task, is the way on. |
168
+ | `ai_service_error` | **Check `terminal`.** The app's AI service refused the sub-agent, and `code` says why (`MODEL_NOT_ALLOWED`, `NO_API_KEY`, …). When `terminal` is true, re-invoking the sub-agent with the same request gets the same refusal: return a terse error and do not re-invoke it. Only `VENDOR_UNREACHABLE` is not terminal, but a refusal from your own vendor that is about the service (for example `VENDOR_UNREACHABLE`) still ends this turn; retry on the user's next message, not in the handler. When the refusal is about the service itself and the sub-agent used your vendor, the parent turn ends on it, as for `budget_exhausted`, unless a completion or a handoff from the same batch goes on past it. The user is shown the sentence for a key, access, model or reachability refusal once per message, so your reply need not repeat it; a refusal about the request itself (`REQUEST_TOO_LARGE`, `BAD_REQUEST`, `FALLBACKS_NOT_SUPPORTED`) is left to you and the console. |
158
169
 
159
170
  ```ts
160
171
  const outcome = await context.requestSubAgent<ExtractedTrades>('trade_file_extractor', {
@@ -164,7 +175,13 @@ const outcome = await context.requestSubAgent<ExtractedTrades>('trade_file_extra
164
175
  if (!outcome.ok) {
165
176
  // Terminal reasons: report and stop. Retrying reproduces them, and for
166
177
  // budget_exhausted the parent turn is ending anyway.
167
- if (outcome.reason === 'budget_exhausted' || outcome.reason === 'refusal') {
178
+ if (
179
+ outcome.reason === 'budget_exhausted' ||
180
+ outcome.reason === 'refusal' ||
181
+ outcome.reason === 'provider_refused' ||
182
+ outcome.reason === 'context_exhausted' ||
183
+ (outcome.reason === 'ai_service_error' && outcome.terminal)
184
+ ) {
168
185
  return { error: `Extraction could not run (${outcome.reason}).` };
169
186
  }
170
187
  // Everything else is worth another attempt or a question to the user.
@@ -213,7 +230,7 @@ The default (`{ name: string }`) leaves the name as `string` — no breaking cha
213
230
 
214
231
  ## History passed to the sub-agent
215
232
 
216
- By default the sub-agent receives a snapshot of the full parent conversation history as context. The in-flight assistant message (the one containing the tool call that triggered the sub-agent) is excluded — it has unresolved tool calls that would confuse the sub-agent.
233
+ By default the sub-agent receives a snapshot of the full parent conversation history as context. The in-flight assistant message (the one containing the tool call that triggered the sub-agent) is excluded — it has unresolved tool calls that would confuse the sub-agent. Anything appended after it during the same batch is cut too: a widget the tool showed, the user's reply to it, a notice. Pass what the sub-agent needs from those through `task` or `context`.
217
234
 
218
235
  Use `historyCap` to limit how much history the sub-agent sees:
219
236