@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
@@ -1,5 +1,5 @@
1
1
  import { __awaiter, __rest } from "tslib";
2
- import { BudgetExhaustedError, ContextOverflowError, ProviderRefusedError, isObservableAIProviderRegistry, MalformedFunctionCallError, ResponseTruncatedError, vendorTypeOfLabel, } from '@genesislcap/foundation-ai';
2
+ import { AIServiceError, BudgetExhaustedError, DEFAULT_AI_SERVICE_ERROR_MESSAGES, ContextOverflowError, ProviderRefusedError, isObservableAIProviderRegistry, isTerminalAIServiceRefusal, MalformedFunctionCallError, ResponseTruncatedError, vendorTypeOfLabel, } from '@genesislcap/foundation-ai';
3
3
  import { NOOP_ACTIVITY_BUS } from '../../channel/ai-activity-bus';
4
4
  import { resolveChatProvider } from '../../config/validate-providers';
5
5
  import { clearSession, getMetaEvents, mergeMetaEvents, recordMetaEvent, recordTurnError, recordTurnRetry, } from '../../state/debug-event-log';
@@ -18,6 +18,29 @@ import { TURN_FAILURE_EXITS, turnDone } from './turn-failures';
18
18
  import { TurnRecorder } from './turn-recorder';
19
19
  /** Re-exported so `from './chat-driver'` keeps resolving these. */
20
20
  export { EMPTY_RESPONSE_NUDGE, MALFORMED_CALL_NUDGE, REQUEST_CONTINUATION_TOOL, } from './chat-driver.constants';
21
+ /**
22
+ * Refusals about one request rather than the service: the parent may well succeed, so a sub-agent's
23
+ * is not shown to the user.
24
+ */
25
+ const REQUEST_SCOPED_REFUSALS = new Set([
26
+ 'REQUEST_TOO_LARGE',
27
+ 'BAD_REQUEST',
28
+ 'FALLBACKS_NOT_SUPPORTED',
29
+ ]);
30
+ /**
31
+ * Refusals about the AI service itself rather than the request, so any call to the same vendor gets
32
+ * the same answer: a sub-agent's stops its parent too. MODEL_NOT_ALLOWED is in neither set. The
33
+ * parent may run on another model, so it goes on, but the refusal is about the app's configuration,
34
+ * so the user is shown it.
35
+ */
36
+ const SERVICE_WIDE_REFUSALS = new Set([
37
+ 'NO_API_KEY',
38
+ 'BAD_API_KEY',
39
+ 'KEY_UNREADABLE',
40
+ 'SIGNED_OUT',
41
+ 'ACCESS_DENIED',
42
+ 'VENDOR_UNREACHABLE',
43
+ ]);
21
44
  /**
22
45
  * Lift the reportable facts off a {@link BudgetExhaustedError}, or `undefined`
23
46
  * when it carries none.
@@ -78,6 +101,21 @@ const budgetDetailOf = (e) => {
78
101
  return undefined;
79
102
  return Object.assign(Object.assign({ budgetUsd: e.budgetUsd, spentUsd: e.spentUsd, vendorLabel: e.vendorLabel }, (vendor ? { vendor } : {})), (e.otherVendorAvailable != null ? { otherVendorAvailable: e.otherVendorAvailable } : {}));
80
103
  };
104
+ /**
105
+ * Where the tool calls still waiting for their results start: the last assistant message with a
106
+ * call no later tool result answers. The history's length when every call has its answer.
107
+ */
108
+ function inFlightToolCallsAt(history) {
109
+ var _a;
110
+ for (let i = history.length - 1; i >= 0; i -= 1) {
111
+ const message = history[i];
112
+ if (message.role !== 'assistant' || !((_a = message.toolCalls) === null || _a === void 0 ? void 0 : _a.length))
113
+ continue;
114
+ const answered = new Set(history.slice(i + 1).map((later) => { var _a; return (_a = later.toolResult) === null || _a === void 0 ? void 0 : _a.toolCallId; }));
115
+ return message.toolCalls.some((call) => !answered.has(call.id)) ? i : history.length;
116
+ }
117
+ return history.length;
118
+ }
81
119
  export class ChatDriver extends EventTarget {
82
120
  constructor(providerRegistry, config = {}) {
83
121
  super();
@@ -223,6 +261,17 @@ export class ChatDriver extends EventTarget {
223
261
  this.turnController = new AbortController();
224
262
  /** True when the current turn was stopped via `cancel()` (vs a dispose). Drives the "Stopped." marker. */
225
263
  this.turnCancelled = false;
264
+ /**
265
+ * The scope tool handlers see as `turnSignal`: one USER MESSAGE. Minted by `sendMessage`, so a
266
+ * handoff's `continueFromHistory` — a new `turnController`, but the same message — keeps it,
267
+ * and a sub-agent inherits it (`inheritedTurnSignal`). Aborted by `cancel()` and by a dispose.
268
+ * `continueFromHistory` mints one only when the message it would continue was stopped.
269
+ *
270
+ * Kept apart from `turnController`, which is per REQUEST and restarts on every continuation: a
271
+ * handler that remembers something "for the rest of the turn" (the write tools' deny lock) keyed
272
+ * on that one was reset by every handoff inside a single message.
273
+ */
274
+ this.messageController = new AbortController();
226
275
  /**
227
276
  * Caches validated provider lookups per name within the current agent. Cleared
228
277
  * by `installAgent` so each new agent's static/function-resolved names are
@@ -259,6 +308,20 @@ export class ChatDriver extends EventTarget {
259
308
  * children costing N doomed calls plus a doomed parent one.
260
309
  */
261
310
  this.providerRefusedThisTurn = false;
311
+ /**
312
+ * A sub-agent was refused by the AI service this turn in a way that stops this driver too
313
+ * (GENC-1611): a service-wide code, from the vendor this driver calls. Sub-agent path only, like
314
+ * `providerRefusedThisTurn`; this driver's own refusal returns straight out of the catch.
315
+ */
316
+ this.aiServiceErrorThisTurn = false;
317
+ /** Codes a child's refusal was already shown for during this user message. */
318
+ this.aiServiceNoticesShown = new Set();
319
+ /**
320
+ * Notices waiting for the tool batch to end. Written mid-batch they would sit between the
321
+ * assistant's tool calls and their results, where a later sub-agent's primer would pick up the
322
+ * unanswered calls.
323
+ */
324
+ this.aiServiceNoticesQueued = [];
262
325
  /**
263
326
  * Set the moment a budget wall is observed anywhere in this turn — this
264
327
  * driver's own 402, or a sub-agent's (which surfaces here only as a
@@ -275,7 +338,7 @@ export class ChatDriver extends EventTarget {
275
338
  * Reset per turn alongside `budgetWallDetail`.
276
339
  */
277
340
  this.budgetWallViaSubAgent = false;
278
- const { toolHandlers = {}, toolDefinitions = [], systemPrompt, primerHistory, maxToolIterations = DEFAULT_MAX_TOOL_ITERATIONS, maxFoldOperations = DEFAULT_MAX_FOLD_OPERATIONS, condenseBatchCalls = 1, maxTurnSnapshots = DEFAULT_MAX_TURN_SNAPSHOTS, sessionKey = '', deferAgentRelease = false, activityBus = NOOP_ACTIVITY_BUS, budgetExhaustedMessage, providerRefusedMessage, } = config;
341
+ const { toolHandlers = {}, toolDefinitions = [], systemPrompt, primerHistory, maxToolIterations = DEFAULT_MAX_TOOL_ITERATIONS, maxFoldOperations = DEFAULT_MAX_FOLD_OPERATIONS, condenseBatchCalls = 1, maxTurnSnapshots = DEFAULT_MAX_TURN_SNAPSHOTS, sessionKey = '', deferAgentRelease = false, activityBus = NOOP_ACTIVITY_BUS, budgetExhaustedMessage, providerRefusedMessage, aiServiceErrorMessages, } = config;
279
342
  this.maxToolIterations = maxToolIterations;
280
343
  this.condenseBatchCalls = condenseBatchCalls;
281
344
  this.sessionKey = sessionKey;
@@ -283,6 +346,7 @@ export class ChatDriver extends EventTarget {
283
346
  this.activityBus = activityBus;
284
347
  this.budgetExhaustedMessageOverride = budgetExhaustedMessage;
285
348
  this.providerRefusedMessageOverride = providerRefusedMessage;
349
+ this.aiServiceErrorMessagesOverride = aiServiceErrorMessages;
286
350
  if (typeof toolHandlers === 'function') {
287
351
  this.toolHandlersFactory = toolHandlers;
288
352
  this.toolHandlers = {};
@@ -374,15 +438,49 @@ export class ChatDriver extends EventTarget {
374
438
  /**
375
439
  * Stop the current turn (user "stop" button). Aborts the in-flight provider
376
440
  * request immediately; if a tool is mid-execution it runs to completion and
377
- * the loop bails at the next boundary (tools are atomic). No-op when idle.
378
- * The driver stays usable for the next message.
441
+ * the loop bails at the next boundary (tools are atomic). When idle it only ends
442
+ * the message (see below) and appends nothing. The driver stays usable for the
443
+ * next message.
379
444
  */
380
445
  cancel() {
446
+ // The message is over, running or not: a handler holding `turnSignal` — including one in a
447
+ // sub-agent, which inherits it — sees the stop. Ended even when idle, because an orchestrator
448
+ // stops between this driver's turns too (its re-classify, an agent install): a continuation
449
+ // afterwards would otherwise carry the stopped message's denials and change rounds.
450
+ this.messageController.abort(new DOMException('Cancelled by user', 'AbortError'));
381
451
  if (!this.busy)
382
452
  return;
383
453
  this.turnCancelled = true;
384
454
  this.turnController.abort(new DOMException('Cancelled by user', 'AbortError'));
385
455
  }
456
+ /**
457
+ * Start a fresh per-MESSAGE scope for tool handlers (see `messageController`). Chained to
458
+ * `lifecycleController` so a dispose aborts it; the link lives until the next message, because
459
+ * a handoff continues this one.
460
+ */
461
+ beginMessage() {
462
+ var _a;
463
+ (_a = this.unlinkLifecycleFromMessage) === null || _a === void 0 ? void 0 : _a.call(this);
464
+ this.messageController = new AbortController();
465
+ const lifecycle = this.lifecycleController.signal;
466
+ if (lifecycle.aborted) {
467
+ this.messageController.abort(lifecycle.reason);
468
+ this.unlinkLifecycleFromMessage = undefined;
469
+ return;
470
+ }
471
+ const onDispose = () => this.messageController.abort(lifecycle.reason);
472
+ lifecycle.addEventListener('abort', onDispose, { once: true });
473
+ this.unlinkLifecycleFromMessage = () => lifecycle.removeEventListener('abort', onDispose);
474
+ }
475
+ /**
476
+ * Makes this (sub-agent) driver's handlers see the parent message's `turnSignal` instead of one
477
+ * of their own: a delegation is part of the message that made it.
478
+ *
479
+ * @internal
480
+ */
481
+ inheritTurnSignal(signal) {
482
+ this.inheritedTurnSignal = signal;
483
+ }
386
484
  /**
387
485
  * Start a fresh per-turn abort scope. Chains `lifecycleController` into the
388
486
  * new `turnController` so a dispose mid-turn also aborts the request.
@@ -443,9 +541,9 @@ export class ChatDriver extends EventTarget {
443
541
  endTurnWithFailure(exit, overrides) {
444
542
  var _a;
445
543
  if (this.isSubAgent) {
446
- this.failSubAgent(exit.subReason, overrides === null || overrides === void 0 ? void 0 : overrides.budget, overrides === null || overrides === void 0 ? void 0 : overrides.providerRefused);
544
+ this.failSubAgent(exit.subReason, overrides === null || overrides === void 0 ? void 0 : overrides.budget, overrides === null || overrides === void 0 ? void 0 : overrides.providerRefused, overrides === null || overrides === void 0 ? void 0 : overrides.aiServiceError);
447
545
  }
448
- else {
546
+ else if (!(overrides === null || overrides === void 0 ? void 0 : overrides.silent)) {
449
547
  this.appendDriverNotice((_a = overrides === null || overrides === void 0 ? void 0 : overrides.copy) !== null && _a !== void 0 ? _a : exit.copy);
450
548
  }
451
549
  return turnDone(exit.resultReason, overrides === null || overrides === void 0 ? void 0 : overrides.budget, overrides === null || overrides === void 0 ? void 0 : overrides.providerRefused);
@@ -500,6 +598,19 @@ export class ChatDriver extends EventTarget {
500
598
  : 'your AI usage limit';
501
599
  return `You've reached ${subject}. Switch to another AI provider in Settings to keep going, or contact your administrator to raise it.`;
502
600
  }
601
+ /**
602
+ * Record a message the user sent and then stopped before any turn took it: during an
603
+ * orchestrator's first classify, or its first agent's install. Only an optimistic
604
+ * `history-updated` had shown it, so it vanished on the next update, and from a reload. Appended
605
+ * here with the "Stopped." marker a stopped turn leaves, as `reportBudgetExhausted` appends a
606
+ * message the budget wall kept from its turn.
607
+ *
608
+ * @internal
609
+ */
610
+ reportStoppedBeforeTurn(userMessage) {
611
+ this.appendToHistory(userMessage);
612
+ this.appendToHistory({ role: 'system-event', content: 'Stopped.' });
613
+ }
503
614
  reportBudgetExhausted(e, pendingUserMessage) {
504
615
  var _a, _b;
505
616
  if (pendingUserMessage)
@@ -535,6 +646,203 @@ export class ChatDriver extends EventTarget {
535
646
  var _a;
536
647
  return (_a = this.providerRefusedMessageOverride) !== null && _a !== void 0 ? _a : TURN_FAILURE_EXITS.providerRefused.copy;
537
648
  }
649
+ /**
650
+ * A terminal AI service error hit **outside** the tool loop — `OrchestratingDriver`'s classification
651
+ * phase (GENC-1611). The same log line, debug-log entry, sentence and result as the in-loop branch.
652
+ *
653
+ * @param pendingUserMessage - the user's message when it has NOT been appended yet, for the reason
654
+ * `reportBudgetExhausted` gives.
655
+ */
656
+ reportAIServiceError(e, pendingUserMessage) {
657
+ if (pendingUserMessage) {
658
+ // A new user message that sendMessage never saw: its sentences start from none.
659
+ this.aiServiceNoticesShown.clear();
660
+ this.aiServiceNoticesQueued = [];
661
+ this.appendToHistory(pendingUserMessage);
662
+ }
663
+ return this.endTurnWithAIServiceError(e);
664
+ }
665
+ /**
666
+ * The sentence for an AI service error code (GENC-1611): the host's override, else the default.
667
+ * Never the service's own text, which goes to the console only.
668
+ */
669
+ aiServiceErrorBubble(code) {
670
+ var _a;
671
+ if (!code)
672
+ return TURN_FAILURE_EXITS.aiServiceError.copy;
673
+ const override = (_a = this.aiServiceErrorMessagesOverride) === null || _a === void 0 ? void 0 : _a[code];
674
+ // A blank entry counts as none: an empty sentence would end the turn with nothing to read.
675
+ return (override === null || override === void 0 ? void 0 : override.trim()) ? override : DEFAULT_AI_SERVICE_ERROR_MESSAGES[code];
676
+ }
677
+ /**
678
+ * Shows a sub-agent's AI-service refusal that the turn went on without, once per code in a user
679
+ * message: the user's sentence with the host's overrides, never the service's text. A sub-agent
680
+ * passes it up to the driver the user sees.
681
+ */
682
+ noticeAIServiceRefusal(code) {
683
+ // About the child's own request, which the parent recovered from: the console has it.
684
+ if (REQUEST_SCOPED_REFUSALS.has(code))
685
+ return;
686
+ if (this.hostAIServiceNotice) {
687
+ this.hostAIServiceNotice(code);
688
+ return;
689
+ }
690
+ // A child still running after the turn ended: there is no batch left to write it after.
691
+ if (!this.busy)
692
+ return;
693
+ if (this.aiServiceNoticesShown.has(code) || this.aiServiceNoticesQueued.includes(code))
694
+ return;
695
+ this.aiServiceNoticesQueued.push(code);
696
+ }
697
+ /**
698
+ * Writes the notices queued during a tool batch, once its results are in the history, or before
699
+ * the failure when the batch threw. A code counts as shown only once written.
700
+ */
701
+ flushAIServiceNotices() {
702
+ const codes = this.aiServiceNoticesQueued;
703
+ this.aiServiceNoticesQueued = [];
704
+ for (const code of codes) {
705
+ this.aiServiceNoticesShown.add(code);
706
+ this.appendDriverNotice(this.aiServiceErrorBubble(code));
707
+ }
708
+ }
709
+ /** Ends the turn on an AI service error: logged with the service's text, shown without it. */
710
+ endTurnWithAIServiceError(e) {
711
+ var _a, _b, _c;
712
+ // The service's own text goes to the console only: `e.message` leaves it out.
713
+ logger.error('ChatDriver: the AI service refused the request', e, (_a = e.detail) !== null && _a !== void 0 ? _a : '');
714
+ recordTurnError(this.sessionKey, 'ai-service-error', {
715
+ agent: this.activeAgentName,
716
+ provider: this.lastResolvedProviderName,
717
+ vendor: (_b = vendorTypeOfLabel(e.vendorLabel)) !== null && _b !== void 0 ? _b : this.lastResolvedProvider,
718
+ code: e.code,
719
+ status: e.status,
720
+ isSubAgent: this.isSubAgent,
721
+ });
722
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.aiServiceError, {
723
+ copy: this.aiServiceErrorBubble(e.code),
724
+ aiServiceError: {
725
+ code: e.code,
726
+ vendor: (_c = vendorTypeOfLabel(e.vendorLabel)) !== null && _c !== void 0 ? _c : this.lastResolvedProvider,
727
+ },
728
+ silent: this.aiServiceSentenceShown(e.code),
729
+ });
730
+ }
731
+ /**
732
+ * Whether this user message already showed the sentence for `code`, so a turn-ending failure
733
+ * does not show it twice. Marks it shown otherwise. Only the driver the user sees keeps count.
734
+ */
735
+ aiServiceSentenceShown(code) {
736
+ if (this.isSubAgent || !code)
737
+ return false;
738
+ if (this.aiServiceNoticesShown.has(code))
739
+ return true;
740
+ this.aiServiceNoticesShown.add(code);
741
+ return false;
742
+ }
743
+ /**
744
+ * Whether a sub-agent hit a wall this turn that stops this driver too. A handoff goes on past an
745
+ * AI-service wall: the next agent may use another vendor, and if it uses this one its own call
746
+ * meets the wall and says so.
747
+ */
748
+ subAgentWallThisTurn(handingOff = false) {
749
+ return (this.providerRefusedThisTurn ||
750
+ this.budgetExhaustedThisTurn ||
751
+ (this.aiServiceErrorThisTurn && !handingOff));
752
+ }
753
+ /**
754
+ * Ends the turn when a sub-agent hit a wall this turn that stops this driver too: the provider
755
+ * refusing the account, the AI service (GENC-1611), or the budget. Checked before each model call,
756
+ * and again right after a tool batch, before a handoff or the iteration cap can report the turn as
757
+ * something else.
758
+ */
759
+ endTurnOnSubAgentWall() {
760
+ var _a, _b, _c, _d, _e;
761
+ if (!this.subAgentWallThisTurn())
762
+ return undefined;
763
+ this.subAgentCompletion = undefined;
764
+ // A budget wall observed earlier this turn ends it HERE, before another
765
+ // model call. Reachable only via a sub-agent (this driver's own 402
766
+ // returns straight out of the catch below) — `invokeSubAgent` sets the
767
+ // flag, its `{ ok: false, reason: 'budget_exhausted' }` outcome is
768
+ // appended as a tool result, and without this the loop would call the
769
+ // provider again into the same wall: N batched sub-agent calls otherwise
770
+ // cost N doomed children AND a doomed parent call.
771
+ //
772
+ // Scoped strictly to the budget reason: every other SubAgentFailureReason
773
+ // is something the parent can legitimately recover from, so those still
774
+ // let the loop continue.
775
+ // A provider refusal seen earlier this turn ends it HERE, before another model call. Reachable
776
+ // only via a sub-agent — this driver's own refusal returns straight out of the catch — and
777
+ // without it the loop would call the provider again into the same wall (GENC-1506).
778
+ if (this.providerRefusedThisTurn) {
779
+ logger.error('ChatDriver: ending the turn — a sub-agent hit the provider wall');
780
+ recordTurnError(this.sessionKey, 'provider-refused', {
781
+ agent: this.activeAgentName,
782
+ provider: this.lastResolvedProviderName,
783
+ kind: (_a = this.providerRefusedDetail) === null || _a === void 0 ? void 0 : _a.kind,
784
+ via: 'sub-agent',
785
+ isSubAgent: this.isSubAgent,
786
+ });
787
+ // The detail is forwarded, not just the reason — this driver may itself be an INTERMEDIATE
788
+ // sub-agent, and a refusal that started in a grandchild reaches its own parent only through
789
+ // this call. Dropping it still stopped the top-level turn (the reason travels), but it
790
+ // arrived with no vendor and no kind, which is the whole diagnostic this payload exists to
791
+ // carry across hops. The adjacent budget path forwards `budgetWallDetail` for the same reason.
792
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.providerRefused, {
793
+ copy: this.providerRefusedBubble(),
794
+ providerRefused: this.providerRefusedDetail,
795
+ });
796
+ }
797
+ // The AI service refused a sub-agent (GENC-1611): end the turn here rather than call the same
798
+ // service again. The code is forwarded so a grandparent can still say what is wrong.
799
+ if (this.aiServiceErrorThisTurn) {
800
+ logger.error('ChatDriver: ending the turn — a sub-agent was refused by the AI service');
801
+ recordTurnError(this.sessionKey, 'ai-service-error', {
802
+ agent: this.activeAgentName,
803
+ provider: this.lastResolvedProviderName,
804
+ code: (_b = this.aiServiceWall) === null || _b === void 0 ? void 0 : _b.code,
805
+ via: 'sub-agent',
806
+ isSubAgent: this.isSubAgent,
807
+ });
808
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.aiServiceError, {
809
+ copy: this.aiServiceErrorBubble((_c = this.aiServiceWall) === null || _c === void 0 ? void 0 : _c.code),
810
+ aiServiceError: this.aiServiceWall,
811
+ silent: this.aiServiceSentenceShown((_d = this.aiServiceWall) === null || _d === void 0 ? void 0 : _d.code),
812
+ });
813
+ }
814
+ if (this.budgetExhaustedThisTurn) {
815
+ logger.error('ChatDriver: ending the turn — a sub-agent hit the AI budget wall');
816
+ recordTurnError(this.sessionKey, 'budget-exhausted', {
817
+ agent: this.activeAgentName,
818
+ provider: this.lastResolvedProviderName,
819
+ // The CHILD's vendor when it knew one, and NOTHING otherwise. On this
820
+ // path the wall is definitionally the child's, and on a mixed registry
821
+ // `lastResolvedProvider` is this driver's own vendor — the one known
822
+ // NOT to have refused. An unattributable child wall must degrade to
823
+ // the vendor-agnostic block (which `latchBlockedFrom` handles
824
+ // fail-safe), never to a vendor that is known to be wrong: naming the
825
+ // parent's vendor here walled BOTH — the child's via its own
826
+ // tool-loop-end, the parent's via this event — and derived `blocked`
827
+ // over headroom that still existed.
828
+ vendor: (_e = this.budgetWallDetail) === null || _e === void 0 ? void 0 : _e.vendor,
829
+ via: 'sub-agent',
830
+ isSubAgent: this.isSubAgent,
831
+ });
832
+ // The copy is composed from the DETAIL, not an error object: on this path the
833
+ // wall arrived as a sub-agent's failure payload — `budgetWallDetail`, first
834
+ // attribution wins — and an unattributable child wall (detail undefined)
835
+ // composes the neutral default. The same detail rides the result, so
836
+ // `loopEndDetail` publishes the refusing vendor rather than falling through to
837
+ // `lastResolvedProvider`, and the host's latch walls the vendor that actually
838
+ // ran out.
839
+ return this.endTurnWithFailure(TURN_FAILURE_EXITS.budgetExhausted, {
840
+ copy: this.budgetExhaustedBubble(this.budgetWallDetail),
841
+ budget: this.budgetWallDetail,
842
+ });
843
+ }
844
+ return undefined;
845
+ }
538
846
  /** The typed failure reason on a loop result, or `undefined` for a clean turn / handoff. */
539
847
  static failureReasonOf(result) {
540
848
  return result.reason === 'done' ? result.failureReason : undefined;
@@ -868,12 +1176,12 @@ export class ChatDriver extends EventTarget {
868
1176
  * under a separate session key, so recording here would orphan the event off
869
1177
  * the user-visible debug-log timeline.)
870
1178
  */
871
- failSubAgent(reason, budget, providerRefused) {
1179
+ failSubAgent(reason, budget, providerRefused, aiServiceError) {
872
1180
  if (!this.isSubAgent || this.subAgentFailure)
873
1181
  return;
874
1182
  // Each payload is omitted rather than set to `undefined` so a failure carrying neither has a shape
875
1183
  // unchanged for a structural comparison, matching `turnDone`.
876
- this.subAgentFailure = Object.assign(Object.assign({ reason }, (budget ? { budget } : {})), (providerRefused ? { providerRefused } : {}));
1184
+ this.subAgentFailure = Object.assign(Object.assign(Object.assign({ reason }, (budget ? { budget } : {})), (providerRefused ? { providerRefused } : {})), (aiServiceError ? { aiServiceError } : {}));
877
1185
  }
878
1186
  /**
879
1187
  * Returns true if `releaseAgent` was called during the most recent turn.
@@ -1346,6 +1654,9 @@ export class ChatDriver extends EventTarget {
1346
1654
  return { reason: 'done' };
1347
1655
  this.busy = true;
1348
1656
  this.beginTurn();
1657
+ // A new user message. `continueFromHistory` keeps the scope, unless the message it would
1658
+ // continue was stopped (see `messageController`).
1659
+ this.beginMessage();
1349
1660
  // A new user turn — advances the `turnEnd` clock (continuations after a
1350
1661
  // handoff stay on the same turn; they go through `continueFromHistory`).
1351
1662
  this.turnSeq += 1;
@@ -1357,6 +1668,10 @@ export class ChatDriver extends EventTarget {
1357
1668
  this.budgetWallViaSubAgent = false;
1358
1669
  this.providerRefusedThisTurn = false;
1359
1670
  this.providerRefusedDetail = undefined;
1671
+ this.aiServiceErrorThisTurn = false;
1672
+ this.aiServiceWall = undefined;
1673
+ this.aiServiceNoticesShown.clear();
1674
+ this.aiServiceNoticesQueued = [];
1360
1675
  this.appendToHistory({ role: 'user', content: userInput, attachments });
1361
1676
  this.turnStartedAt = Date.now();
1362
1677
  recordMetaEvent(this.sessionKey, 'turn.start', {
@@ -1379,6 +1694,8 @@ export class ChatDriver extends EventTarget {
1379
1694
  name: e instanceof Error ? e.name : undefined,
1380
1695
  message: e instanceof Error ? e.message : String(e),
1381
1696
  });
1697
+ // A notice the thrown batch queued goes first: nothing else would write it.
1698
+ this.flushAIServiceNotices();
1382
1699
  this.appendDriverNotice('Sorry, something went wrong on my end. Please try again in a moment.');
1383
1700
  result = turnDone('exception');
1384
1701
  return result;
@@ -1423,7 +1740,12 @@ export class ChatDriver extends EventTarget {
1423
1740
  * error growing as the fan-out widens.
1424
1741
  */
1425
1742
  buildHandlerContext(activeToolCallId, traceCapture) {
1426
- return Object.assign(Object.assign({ requestInteraction: (componentName, data, options) => this.requestInteraction(componentName, data, options) }, (this.subAgentsMap.size > 0 && {
1743
+ var _a;
1744
+ return Object.assign(Object.assign({ requestInteraction: (componentName, data, options) => this.requestInteraction(componentName, data, options),
1745
+ // The MESSAGE's scope: one object per `sendMessage`, kept across a handoff's continuation
1746
+ // and handed to a sub-agent, and aborted by `cancel()` as well as a dispose. Not the
1747
+ // per-request `turnController`, which every continuation replaces.
1748
+ turnSignal: (_a = this.inheritedTurnSignal) !== null && _a !== void 0 ? _a : this.messageController.signal }, (this.subAgentsMap.size > 0 && {
1427
1749
  requestSubAgent: (name, options) => this.invokeSubAgent(name, options).then(({ outcome, trace }) => {
1428
1750
  // Append, never assign: see `traceCapture` on `buildHandlerContext`. Order
1429
1751
  // is completion order, which is fine — every message carries its own
@@ -1495,7 +1817,7 @@ export class ChatDriver extends EventTarget {
1495
1817
  */
1496
1818
  invokeSubAgent(name, options) {
1497
1819
  return __awaiter(this, void 0, void 0, function* () {
1498
- var _a, _b, _c, _d, _e, _f;
1820
+ var _a, _b, _c, _d, _e, _f, _g;
1499
1821
  const subConfig = this.subAgentsMap.get(name);
1500
1822
  if (!subConfig) {
1501
1823
  const available = [...this.subAgentsMap.keys()].join(', ') || '(none)';
@@ -1504,11 +1826,9 @@ export class ChatDriver extends EventTarget {
1504
1826
  const { task, historyCap, context, timeoutMs } = options !== null && options !== void 0 ? options : {};
1505
1827
  // Exclude the current in-flight assistant message (the one with tool calls that
1506
1828
  // triggered this invocation) — it has unresolved tool calls that would confuse
1507
- // the sub-agent into thinking it needs to handle tools it doesn't own.
1508
- const lastMsg = this.history[this.history.length - 1];
1509
- const baseHistory = (lastMsg === null || lastMsg === void 0 ? void 0 : lastMsg.role) === 'assistant' && ((_a = lastMsg.toolCalls) === null || _a === void 0 ? void 0 : _a.length)
1510
- ? this.history.slice(0, -1)
1511
- : this.history;
1829
+ // the sub-agent into thinking it needs to handle tools it doesn't own. Found by its
1830
+ // unanswered calls, not by being last: a widget the batch showed can come after it.
1831
+ const baseHistory = this.history.slice(0, inFlightToolCallsAt(this.history));
1512
1832
  const snapshotHistory = historyCap != null ? applyHistoryCap(baseHistory, historyCap) : [...baseHistory];
1513
1833
  const contextMessages = context
1514
1834
  ? [{ role: 'user', content: `[Sub-agent context]: ${JSON.stringify(context)}` }]
@@ -1516,7 +1836,7 @@ export class ChatDriver extends EventTarget {
1516
1836
  const effectivePrimer = [
1517
1837
  ...snapshotHistory,
1518
1838
  ...contextMessages,
1519
- ...((_b = subConfig.primerHistory) !== null && _b !== void 0 ? _b : []),
1839
+ ...((_a = subConfig.primerHistory) !== null && _a !== void 0 ? _a : []),
1520
1840
  ];
1521
1841
  // Unique per-invocation id — reused for the lifecycle event bracket below —
1522
1842
  // and a child session key derived from it. The child files its meta events
@@ -1533,6 +1853,9 @@ export class ChatDriver extends EventTarget {
1533
1853
  // Mark before the first turn so the child forces tool use and reports a
1534
1854
  // typed failure (rather than user-facing text) if it never completes.
1535
1855
  child.markAsSubAgent();
1856
+ // The delegation is part of this message: its handlers see this message's scope, so a stop
1857
+ // reaches them and per-message state (a denied write) holds across the delegation.
1858
+ child.inheritTurnSignal((_b = this.inheritedTurnSignal) !== null && _b !== void 0 ? _b : this.messageController.signal);
1536
1859
  // The guard is policy, and a sub-agent runs the same tool loop against the
1537
1860
  // same window. Without this every child was inert — and the
1538
1861
  // `context_exhausted` sub-agent failure this feature added was unreachable by
@@ -1554,6 +1877,8 @@ export class ChatDriver extends EventTarget {
1554
1877
  // pending map the main UI is wired to. Recurses naturally for nested
1555
1878
  // sub-agents.
1556
1879
  child.setHostInteractionRequester((componentName, data, opts) => this.requestInteraction(componentName, data, opts));
1880
+ // The same route for a refusal the child absorbs, so the user sees it in the root transcript.
1881
+ child.hostAIServiceNotice = (code) => this.noticeAIServiceRefusal(code);
1557
1882
  const forwardTrace = (e) => {
1558
1883
  this.dispatchEvent(new CustomEvent('sub-agent-history-updated', {
1559
1884
  detail: { agentName: subConfig.name, history: e.detail },
@@ -1712,6 +2037,42 @@ export class ChatDriver extends EventTarget {
1712
2037
  this.providerRefusedThisTurn = true;
1713
2038
  (_f = this.providerRefusedDetail) !== null && _f !== void 0 ? _f : (this.providerRefusedDetail = failure === null || failure === void 0 ? void 0 : failure.providerRefused);
1714
2039
  }
2040
+ // The AI SERVICE wall via a child (GENC-1611). It stops this driver too only when this driver's
2041
+ // next call would get the same answer: a refusal about the service rather than the child's own
2042
+ // request, from the vendor this driver calls. Otherwise the handler gets the failure and the
2043
+ // turn goes on, and a refusal that does reach this driver's own call is reported from there.
2044
+ const wall = failure === null || failure === void 0 ? void 0 : failure.aiServiceError;
2045
+ if (reason === 'ai_service_error' &&
2046
+ wall &&
2047
+ SERVICE_WIDE_REFUSALS.has(wall.code) &&
2048
+ wall.vendor !== undefined &&
2049
+ wall.vendor === this.lastResolvedProvider) {
2050
+ this.aiServiceErrorThisTurn = true;
2051
+ (_g = this.aiServiceWall) !== null && _g !== void 0 ? _g : (this.aiServiceWall = wall);
2052
+ }
2053
+ else if (reason === 'ai_service_error' && wall) {
2054
+ // The turn goes on without it, so nothing else would tell the user.
2055
+ this.noticeAIServiceRefusal(wall.code);
2056
+ }
2057
+ // The code tells a handler whether calling this sub-agent again can help: a terminal refusal
2058
+ // comes back the same every time.
2059
+ if (reason === 'ai_service_error') {
2060
+ if (wall) {
2061
+ return {
2062
+ outcome: {
2063
+ ok: false,
2064
+ reason,
2065
+ code: wall.code,
2066
+ terminal: isTerminalAIServiceRefusal(wall.code),
2067
+ },
2068
+ trace,
2069
+ };
2070
+ }
2071
+ // Both producers record the refusal with it, so this is a bug. Reported like the other
2072
+ // failure that says nothing about itself, rather than with a code nobody sent.
2073
+ logger.error(`ChatDriver: sub-agent "${name}" was refused by the AI service with no code`);
2074
+ return { outcome: { ok: false, reason: 'max_iterations' }, trace };
2075
+ }
1715
2076
  return { outcome: { ok: false, reason }, trace };
1716
2077
  });
1717
2078
  }
@@ -1724,6 +2085,11 @@ export class ChatDriver extends EventTarget {
1724
2085
  if (this.busy)
1725
2086
  return { reason: 'done' };
1726
2087
  this.busy = true;
2088
+ // A continuation keeps the message it continues (see `messageController`), unless that
2089
+ // message was stopped. Its scope is then already aborted, and this method is public: a host
2090
+ // continuing after a Stop handed every handler a stopped turn until the next sendMessage.
2091
+ if (this.messageController.signal.aborted)
2092
+ this.beginMessage();
1727
2093
  this.beginTurn();
1728
2094
  this.subAgentCompletion = undefined;
1729
2095
  this.subAgentFailure = undefined;
@@ -1732,6 +2098,8 @@ export class ChatDriver extends EventTarget {
1732
2098
  this.budgetWallViaSubAgent = false;
1733
2099
  this.providerRefusedThisTurn = false;
1734
2100
  this.providerRefusedDetail = undefined;
2101
+ this.aiServiceErrorThisTurn = false;
2102
+ this.aiServiceWall = undefined;
1735
2103
  this.turnStartedAt = Date.now();
1736
2104
  recordMetaEvent(this.sessionKey, 'turn.start', {
1737
2105
  phase: 'continueFromHistory',
@@ -1753,6 +2121,8 @@ export class ChatDriver extends EventTarget {
1753
2121
  name: e instanceof Error ? e.name : undefined,
1754
2122
  message: e instanceof Error ? e.message : String(e),
1755
2123
  });
2124
+ // A notice the thrown batch queued goes first: nothing else would write it.
2125
+ this.flushAIServiceNotices();
1756
2126
  this.appendDriverNotice('Sorry, something went wrong on my end. Please try again in a moment.');
1757
2127
  result = turnDone('exception');
1758
2128
  return result;
@@ -1782,7 +2152,7 @@ export class ChatDriver extends EventTarget {
1782
2152
  // oxlint-disable-next-line complexity, max-lines-per-function
1783
2153
  runToolLoop(userInput, attachments, transientPrimer) {
1784
2154
  return __awaiter(this, void 0, void 0, function* () {
1785
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
2155
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
1786
2156
  if (!this.systemPrompt) {
1787
2157
  logger.warn('ChatDriver: no systemPrompt set. The assistant will have no instructions — provide a systemPrompt via agents config or the foundation-ai-assistant property.');
1788
2158
  }
@@ -1824,71 +2194,12 @@ export class ChatDriver extends EventTarget {
1824
2194
  if (this.turnController.signal.aborted) {
1825
2195
  return this.completeAbortedTurn();
1826
2196
  }
1827
- // A budget wall observed earlier this turn ends it HERE, before another
1828
- // model call. Reachable only via a sub-agent (this driver's own 402
1829
- // returns straight out of the catch below) — `invokeSubAgent` sets the
1830
- // flag, its `{ ok: false, reason: 'budget_exhausted' }` outcome is
1831
- // appended as a tool result, and without this the loop would call the
1832
- // provider again into the same wall: N batched sub-agent calls otherwise
1833
- // cost N doomed children AND a doomed parent call.
1834
- //
1835
- // Scoped strictly to the budget reason: every other SubAgentFailureReason
1836
- // is something the parent can legitimately recover from, so those still
1837
- // let the loop continue.
1838
- // A provider refusal seen earlier this turn ends it HERE, before another model call. Reachable
1839
- // only via a sub-agent — this driver's own refusal returns straight out of the catch — and
1840
- // without it the loop would call the provider again into the same wall (GENC-1506).
1841
- if (this.providerRefusedThisTurn) {
1842
- logger.error('ChatDriver: ending the turn — a sub-agent hit the provider wall');
1843
- recordTurnError(this.sessionKey, 'provider-refused', {
1844
- agent: this.activeAgentName,
1845
- provider: this.lastResolvedProviderName,
1846
- kind: (_a = this.providerRefusedDetail) === null || _a === void 0 ? void 0 : _a.kind,
1847
- via: 'sub-agent',
1848
- isSubAgent: this.isSubAgent,
1849
- });
1850
- // The detail is forwarded, not just the reason — this driver may itself be an INTERMEDIATE
1851
- // sub-agent, and a refusal that started in a grandchild reaches its own parent only through
1852
- // this call. Dropping it still stopped the top-level turn (the reason travels), but it
1853
- // arrived with no vendor and no kind, which is the whole diagnostic this payload exists to
1854
- // carry across hops. The adjacent budget path forwards `budgetWallDetail` for the same reason.
1855
- return this.endTurnWithFailure(TURN_FAILURE_EXITS.providerRefused, {
1856
- copy: this.providerRefusedBubble(),
1857
- providerRefused: this.providerRefusedDetail,
1858
- });
1859
- }
1860
- if (this.budgetExhaustedThisTurn) {
1861
- logger.error('ChatDriver: ending the turn — a sub-agent hit the AI budget wall');
1862
- recordTurnError(this.sessionKey, 'budget-exhausted', {
1863
- agent: this.activeAgentName,
1864
- provider: this.lastResolvedProviderName,
1865
- // The CHILD's vendor when it knew one, and NOTHING otherwise. On this
1866
- // path the wall is definitionally the child's, and on a mixed registry
1867
- // `lastResolvedProvider` is this driver's own vendor — the one known
1868
- // NOT to have refused. An unattributable child wall must degrade to
1869
- // the vendor-agnostic block (which `latchBlockedFrom` handles
1870
- // fail-safe), never to a vendor that is known to be wrong: naming the
1871
- // parent's vendor here walled BOTH — the child's via its own
1872
- // tool-loop-end, the parent's via this event — and derived `blocked`
1873
- // over headroom that still existed.
1874
- vendor: (_b = this.budgetWallDetail) === null || _b === void 0 ? void 0 : _b.vendor,
1875
- via: 'sub-agent',
1876
- isSubAgent: this.isSubAgent,
1877
- });
1878
- // The copy is composed from the DETAIL, not an error object: on this path the
1879
- // wall arrived as a sub-agent's failure payload — `budgetWallDetail`, first
1880
- // attribution wins — and an unattributable child wall (detail undefined)
1881
- // composes the neutral default. The same detail rides the result, so
1882
- // `loopEndDetail` publishes the refusing vendor rather than falling through to
1883
- // `lastResolvedProvider`, and the host's latch walls the vendor that actually
1884
- // ran out.
1885
- return this.endTurnWithFailure(TURN_FAILURE_EXITS.budgetExhausted, {
1886
- copy: this.budgetExhaustedBubble(this.budgetWallDetail),
1887
- budget: this.budgetWallDetail,
1888
- });
1889
- }
2197
+ // A wall a sub-agent hit earlier this turn ends it here, before another model call.
2198
+ const wall = this.endTurnOnSubAgentWall();
2199
+ if (wall)
2200
+ return wall;
1890
2201
  const promptCtx = {
1891
- agentName: (_c = this.activeAgentName) !== null && _c !== void 0 ? _c : '',
2202
+ agentName: (_a = this.activeAgentName) !== null && _a !== void 0 ? _a : '',
1892
2203
  history: this.history,
1893
2204
  turnIndex: iterations - 1,
1894
2205
  signal: this.turnController.signal,
@@ -1961,7 +2272,7 @@ export class ChatDriver extends EventTarget {
1961
2272
  // loses all summarized context. `normalizeForProvider` only touches
1962
2273
  // `compacted-summary`, so it's a safe pass-through for everything else.
1963
2274
  const primer = normalizeForProvider([
1964
- ...((_d = this.primerHistory) !== null && _d !== void 0 ? _d : []),
2275
+ ...((_b = this.primerHistory) !== null && _b !== void 0 ? _b : []),
1965
2276
  ...(transientPrimer !== null && transientPrimer !== void 0 ? transientPrimer : []),
1966
2277
  ]);
1967
2278
  const baseHistory = firstLlmCall ? this.history.slice(0, -1) : this.history;
@@ -2212,7 +2523,7 @@ export class ChatDriver extends EventTarget {
2212
2523
  recordTurnError(this.sessionKey, 'context-exhausted', {
2213
2524
  agent: this.activeAgentName,
2214
2525
  provider: this.lastResolvedProviderName,
2215
- vendor: (_e = vendorTypeOfLabel(e.vendorLabel)) !== null && _e !== void 0 ? _e : this.lastResolvedProvider,
2526
+ vendor: (_c = vendorTypeOfLabel(e.vendorLabel)) !== null && _c !== void 0 ? _c : this.lastResolvedProvider,
2216
2527
  promptTokens: e.promptTokens,
2217
2528
  limitTokens: e.limitTokens,
2218
2529
  via: 'provider',
@@ -2237,7 +2548,7 @@ export class ChatDriver extends EventTarget {
2237
2548
  recordTurnError(this.sessionKey, 'provider-refused', {
2238
2549
  agent: this.activeAgentName,
2239
2550
  provider: this.lastResolvedProviderName,
2240
- vendor: (_f = vendorTypeOfLabel(e.vendorLabel)) !== null && _f !== void 0 ? _f : this.lastResolvedProvider,
2551
+ vendor: (_d = vendorTypeOfLabel(e.vendorLabel)) !== null && _d !== void 0 ? _d : this.lastResolvedProvider,
2241
2552
  kind: e.kind,
2242
2553
  upstreamStatus: e.upstreamStatus,
2243
2554
  upstreamType: e.upstreamType,
@@ -2248,6 +2559,12 @@ export class ChatDriver extends EventTarget {
2248
2559
  providerRefused: detail,
2249
2560
  });
2250
2561
  }
2562
+ // The AI SERVICE wall (GENC-1611): the app's chat endpoint named a configuration error, such as
2563
+ // a missing API key. Sending the request again gets the same answer, so it ends the turn here,
2564
+ // ahead of the transient retry below. VENDOR_UNREACHABLE is not terminal and takes that retry.
2565
+ if (e instanceof AIServiceError && e.terminal) {
2566
+ return this.endTurnWithAIServiceError(e);
2567
+ }
2251
2568
  if (e instanceof BudgetExhaustedError) {
2252
2569
  // Flagged as well as returned: a sub-agent's wall reaches the PARENT
2253
2570
  // only as a tool result, and the parent must not issue another model
@@ -2266,7 +2583,7 @@ export class ChatDriver extends EventTarget {
2266
2583
  recordTurnError(this.sessionKey, 'budget-exhausted', {
2267
2584
  agent: this.activeAgentName,
2268
2585
  provider: this.lastResolvedProviderName,
2269
- vendor: (_h = (_g = vendorTypeOfLabel(e.vendorLabel)) !== null && _g !== void 0 ? _g : vendorTypeOfLabel(e.serverVendor)) !== null && _h !== void 0 ? _h : this.lastResolvedProvider,
2586
+ vendor: (_f = (_e = vendorTypeOfLabel(e.vendorLabel)) !== null && _e !== void 0 ? _e : vendorTypeOfLabel(e.serverVendor)) !== null && _f !== void 0 ? _f : this.lastResolvedProvider,
2270
2587
  budgetUsd: e.budgetUsd,
2271
2588
  spentUsd: e.spentUsd,
2272
2589
  isSubAgent: true,
@@ -2315,6 +2632,9 @@ export class ChatDriver extends EventTarget {
2315
2632
  iterations -= 1;
2316
2633
  continue;
2317
2634
  }
2635
+ // Still unreachable after the retries: say so, rather than "something went wrong on my end".
2636
+ if (e instanceof AIServiceError)
2637
+ return this.endTurnWithAIServiceError(e);
2318
2638
  throw e;
2319
2639
  }
2320
2640
  // Attribute the response to the concrete model + registry slot that
@@ -2355,15 +2675,15 @@ export class ChatDriver extends EventTarget {
2355
2675
  // fallback chain answered on a different model than the one we asked for.
2356
2676
  if (response.model !== undefined)
2357
2677
  turnSnapshot.model = response.model;
2358
- const isThinkingStep = response.content && ((_j = response.toolCalls) === null || _j === void 0 ? void 0 : _j.length);
2359
- const isEmptyResponse = !((_k = response.content) === null || _k === void 0 ? void 0 : _k.trim()) && !((_l = response.toolCalls) === null || _l === void 0 ? void 0 : _l.length);
2678
+ const isThinkingStep = response.content && ((_g = response.toolCalls) === null || _g === void 0 ? void 0 : _g.length);
2679
+ const isEmptyResponse = !((_h = response.content) === null || _h === void 0 ? void 0 : _h.trim()) && !((_j = response.toolCalls) === null || _j === void 0 ? void 0 : _j.length);
2360
2680
  // A pre-output refusal (safety-classifier decline, e.g. Fable 5 `stop_reason: 'refusal'`)
2361
2681
  // comes back with empty content, so it looks like a blank response — but it is deterministic:
2362
2682
  // retrying re-sends the identical request and refuses again, burning up to
2363
2683
  // MAX_EMPTY_RESPONSE_RETRIES turns on the most expensive models for the same outcome, ending
2364
2684
  // in the misleading "blank response" message. Treat it as a terminal, non-retried failure with
2365
2685
  // its own reason and message. (GENC-1461)
2366
- const isRefusal = ((_m = response.responseMeta) === null || _m === void 0 ? void 0 : _m.finishReason) === 'refusal';
2686
+ const isRefusal = ((_k = response.responseMeta) === null || _k === void 0 ? void 0 : _k.finishReason) === 'refusal';
2367
2687
  if (isEmptyResponse) {
2368
2688
  emptyResponseAttempts += 1;
2369
2689
  if (!isRefusal && emptyResponseAttempts < MAX_EMPTY_RESPONSE_RETRIES) {
@@ -2434,7 +2754,7 @@ export class ChatDriver extends EventTarget {
2434
2754
  emptyResponseAttempts = 0;
2435
2755
  malformedAttempts = 0;
2436
2756
  setupTransportAttempts = 0;
2437
- if (!((_o = response.toolCalls) === null || _o === void 0 ? void 0 : _o.length)) {
2757
+ if (!((_l = response.toolCalls) === null || _l === void 0 ? void 0 : _l.length)) {
2438
2758
  break;
2439
2759
  }
2440
2760
  const [toolCalls, systemCalls] = response.toolCalls.reduce((acc, tc) => {
@@ -2664,7 +2984,7 @@ export class ChatDriver extends EventTarget {
2664
2984
  // The response was appended before execution — find it and annotate.
2665
2985
  let tcMsgIdx = -1;
2666
2986
  for (let i = this.history.length - 1; i >= 0; i -= 1) {
2667
- if (this.history[i].role === 'assistant' && ((_p = this.history[i].toolCalls) === null || _p === void 0 ? void 0 : _p.length)) {
2987
+ if (this.history[i].role === 'assistant' && ((_m = this.history[i].toolCalls) === null || _m === void 0 ? void 0 : _m.length)) {
2668
2988
  tcMsgIdx = i;
2669
2989
  break;
2670
2990
  }
@@ -2695,12 +3015,14 @@ export class ChatDriver extends EventTarget {
2695
3015
  this.history[tcMsgIdx] = Object.assign(Object.assign({}, tcMsg), { toolCalls: annotatedCalls });
2696
3016
  this.notifyHistoryUpdated();
2697
3017
  }
3018
+ // After the results, so a notice never sits between the tool calls and their answers.
3019
+ this.flushAIServiceNotices();
2698
3020
  if (hitUnknownToolLimit) {
2699
3021
  logger.error(`ChatDriver: unknown-tool limit (${DEFAULT_MAX_UNKNOWN_TOOL_CALLS}) reached — stopping`);
2700
3022
  const unknownTools = [
2701
3023
  ...new Set([
2702
3024
  ...this.recentUnknownToolNames,
2703
- ...((_q = response.toolCalls) !== null && _q !== void 0 ? _q : [])
3025
+ ...((_o = response.toolCalls) !== null && _o !== void 0 ? _o : [])
2704
3026
  .filter((tc) => unknownToolIds.has(tc.id))
2705
3027
  .map((tc) => tc.name),
2706
3028
  ]),
@@ -2712,7 +3034,7 @@ export class ChatDriver extends EventTarget {
2712
3034
  const staleTools = [
2713
3035
  ...new Set([
2714
3036
  ...this.recentStaleToolNames,
2715
- ...((_r = response.toolCalls) !== null && _r !== void 0 ? _r : [])
3037
+ ...((_p = response.toolCalls) !== null && _p !== void 0 ? _p : [])
2716
3038
  .filter((tc) => staleToolIds.has(tc.id))
2717
3039
  .map((tc) => tc.name),
2718
3040
  ]),
@@ -2729,7 +3051,24 @@ export class ChatDriver extends EventTarget {
2729
3051
  });
2730
3052
  return this.endTurnWithFailure(TURN_FAILURE_EXITS.unknownToolLimit);
2731
3053
  }
3054
+ // A wall a sub-agent hit in this batch wins over the exits below, which would report the turn
3055
+ // as a handoff or the iteration cap, or lose the wall altogether. Three things win over it: a
3056
+ // completion, which needs no further model call; a handoff past an AI-service wall; and a stop
3057
+ // the user pressed while the batch ran, which ends the turn as "Stopped." as it would at the
3058
+ // next model call.
2732
3059
  const firstContinuation = systemCalls[0];
3060
+ if (!this.subAgentCompletion && this.subAgentWallThisTurn(!!firstContinuation)) {
3061
+ if (this.turnController.signal.aborted)
3062
+ return this.completeAbortedTurn();
3063
+ const wallAfterBatch = this.endTurnOnSubAgentWall();
3064
+ if (wallAfterBatch)
3065
+ return wallAfterBatch;
3066
+ }
3067
+ // A completion or a handoff went on past a child's AI-service refusal: say it once.
3068
+ if (this.aiServiceErrorThisTurn && this.aiServiceWall) {
3069
+ this.noticeAIServiceRefusal(this.aiServiceWall.code);
3070
+ this.flushAIServiceNotices();
3071
+ }
2733
3072
  if (firstContinuation) {
2734
3073
  const { summary, remaining_task: remainingTask } = firstContinuation.args;
2735
3074
  return { reason: 'agent-handoff', summary, remainingTask };