@genesislcap/ai-assistant 15.81.0 → 15.83.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 (110) hide show
  1. package/dist/ai-assistant.api.json +2800 -116
  2. package/dist/ai-assistant.d.ts +887 -109
  3. package/dist/chat-driver.cjs +468 -107
  4. package/dist/chat-driver.cjs.map +4 -4
  5. package/dist/chat-driver.mjs +468 -107
  6. package/dist/chat-driver.mjs.map +4 -4
  7. package/dist/custom-elements.json +1108 -61
  8. package/dist/dts/autopilot/autopilot-driver.d.ts +117 -11
  9. package/dist/dts/autopilot/autopilot-driver.d.ts.map +1 -1
  10. package/dist/dts/autopilot/autopilot-session.d.ts +55 -7
  11. package/dist/dts/autopilot/autopilot-session.d.ts.map +1 -1
  12. package/dist/dts/autopilot/autopilot-tools.d.ts +3 -2
  13. package/dist/dts/autopilot/autopilot-tools.d.ts.map +1 -1
  14. package/dist/dts/autopilot/decision-message.d.ts +35 -3
  15. package/dist/dts/autopilot/decision-message.d.ts.map +1 -1
  16. package/dist/dts/autopilot/hand-back/hand-back.controller.d.ts +2 -2
  17. package/dist/dts/autopilot/hand-back/hand-back.controller.d.ts.map +1 -1
  18. package/dist/dts/autopilot/hand-back/hand-back.d.ts +2 -2
  19. package/dist/dts/autopilot/hand-back/hand-back.d.ts.map +1 -1
  20. package/dist/dts/autopilot/index.d.ts +1 -0
  21. package/dist/dts/autopilot/index.d.ts.map +1 -1
  22. package/dist/dts/autopilot/widget-tools.d.ts +95 -0
  23. package/dist/dts/autopilot/widget-tools.d.ts.map +1 -0
  24. package/dist/dts/channel/ai-activity-channel.d.ts +10 -0
  25. package/dist/dts/channel/ai-activity-channel.d.ts.map +1 -1
  26. package/dist/dts/components/agent-session/agent-session.d.ts +2 -1
  27. package/dist/dts/components/agent-session/agent-session.d.ts.map +1 -1
  28. package/dist/dts/components/ai-driver/ai-driver.d.ts +25 -6
  29. package/dist/dts/components/ai-driver/ai-driver.d.ts.map +1 -1
  30. package/dist/dts/components/ai-driver/base-driver-decorator.d.ts +2 -0
  31. package/dist/dts/components/ai-driver/base-driver-decorator.d.ts.map +1 -1
  32. package/dist/dts/components/chat-driver/chat-driver.d.ts +14 -2
  33. package/dist/dts/components/chat-driver/chat-driver.d.ts.map +1 -1
  34. package/dist/dts/components/chat-driver/interaction-controller.d.ts +61 -17
  35. package/dist/dts/components/chat-driver/interaction-controller.d.ts.map +1 -1
  36. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts +6 -0
  37. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts.map +1 -1
  38. package/dist/dts/config/config.d.ts +31 -6
  39. package/dist/dts/config/config.d.ts.map +1 -1
  40. package/dist/dts/config/define-stateful-agent.d.ts +5 -1
  41. package/dist/dts/config/define-stateful-agent.d.ts.map +1 -1
  42. package/dist/dts/index.d.ts +4 -2
  43. package/dist/dts/index.d.ts.map +1 -1
  44. package/dist/dts/main/main.d.ts +33 -16
  45. package/dist/dts/main/main.d.ts.map +1 -1
  46. package/dist/dts/main/main.template.d.ts.map +1 -1
  47. package/dist/dts/main/main.types.d.ts +15 -0
  48. package/dist/dts/main/main.types.d.ts.map +1 -1
  49. package/dist/dts/notifications/agent-notifications.d.ts +6 -2
  50. package/dist/dts/notifications/agent-notifications.d.ts.map +1 -1
  51. package/dist/dts/notifications/agent-notifier.d.ts +26 -4
  52. package/dist/dts/notifications/agent-notifier.d.ts.map +1 -1
  53. package/dist/dts/state/decision-surface.d.ts +22 -4
  54. package/dist/dts/state/decision-surface.d.ts.map +1 -1
  55. package/dist/dts/state/interaction-context.d.ts +23 -4
  56. package/dist/dts/state/interaction-context.d.ts.map +1 -1
  57. package/dist/dts/state/interaction-registry.d.ts +55 -6
  58. package/dist/dts/state/interaction-registry.d.ts.map +1 -1
  59. package/dist/dts/state/live-interactions.d.ts +28 -0
  60. package/dist/dts/state/live-interactions.d.ts.map +1 -0
  61. package/dist/dts/state/persistence/session-persister.d.ts +6 -0
  62. package/dist/dts/state/persistence/session-persister.d.ts.map +1 -1
  63. package/dist/dts/state/persistence/session-snapshot.d.ts +16 -5
  64. package/dist/dts/state/persistence/session-snapshot.d.ts.map +1 -1
  65. package/dist/dts/state/test-interaction-context.d.ts +93 -0
  66. package/dist/dts/state/test-interaction-context.d.ts.map +1 -0
  67. package/dist/dts/types/ai-chat-widget.d.ts +7 -6
  68. package/dist/dts/types/ai-chat-widget.d.ts.map +1 -1
  69. package/dist/dts/types/interaction-context.d.ts +128 -17
  70. package/dist/dts/types/interaction-context.d.ts.map +1 -1
  71. package/dist/dts/types/interaction-interceptor.d.ts +48 -6
  72. package/dist/dts/types/interaction-interceptor.d.ts.map +1 -1
  73. package/dist/dts/types/interaction-surface.d.ts +145 -23
  74. package/dist/dts/types/interaction-surface.d.ts.map +1 -1
  75. package/dist/dts/utils/delegated-message.d.ts +7 -0
  76. package/dist/dts/utils/delegated-message.d.ts.map +1 -1
  77. package/dist/esm/autopilot/autopilot-driver.js +313 -60
  78. package/dist/esm/autopilot/autopilot-session.js +219 -40
  79. package/dist/esm/autopilot/autopilot-tools.js +11 -7
  80. package/dist/esm/autopilot/decision-message.js +105 -26
  81. package/dist/esm/autopilot/hand-back/hand-back.controller.js +2 -1
  82. package/dist/esm/autopilot/index.js +1 -0
  83. package/dist/esm/autopilot/widget-tools.js +39 -0
  84. package/dist/esm/components/agent-session/agent-session.js +3 -2
  85. package/dist/esm/components/ai-driver/base-driver-decorator.js +17 -0
  86. package/dist/esm/components/chat-driver/chat-driver.js +18 -2
  87. package/dist/esm/components/chat-driver/interaction-controller.js +232 -71
  88. package/dist/esm/components/orchestrating-driver/orchestrating-driver.js +14 -6
  89. package/dist/esm/components/settings-modal/settings-modal.template.js +2 -2
  90. package/dist/esm/config/define-stateful-agent.js +22 -1
  91. package/dist/esm/index.js +2 -0
  92. package/dist/esm/main/main.js +88 -35
  93. package/dist/esm/main/main.template.js +4 -1
  94. package/dist/esm/notifications/agent-notifications.js +11 -1
  95. package/dist/esm/notifications/agent-notifier.js +41 -7
  96. package/dist/esm/state/debug-event-log.js +6 -6
  97. package/dist/esm/state/decision-surface.js +137 -54
  98. package/dist/esm/state/interaction-context.js +41 -8
  99. package/dist/esm/state/interaction-registry.js +11 -0
  100. package/dist/esm/state/live-interactions.js +36 -0
  101. package/dist/esm/state/persistence/session-persister.js +55 -18
  102. package/dist/esm/state/persistence/session-snapshot.js +2 -2
  103. package/dist/esm/state/test-interaction-context.js +99 -0
  104. package/docs/notifications.md +55 -5
  105. package/docs/styling.md +33 -0
  106. package/package.json +19 -19
  107. package/sandbox/README.md +3 -2
  108. package/sandbox/autopilot.ts +26 -6
  109. package/sandbox/sandbox.ts +2 -0
  110. /package/dist/{tsdoc-metadata.json → dts/tsdoc-metadata.json} +0 -0
@@ -867,6 +867,13 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
867
867
  (_a = this._unwireNotifications) === null || _a === void 0 ? void 0 : _a.call(this);
868
868
  this.notificationPermission = agentNotificationPermission();
869
869
  const unsubAttention = agenticActivityBus.subscribe('agent-attention', (d) => this.onAgentAttention(d));
870
+ // A notification for an interaction that no longer waits on the person is stale (GENC-1660).
871
+ const unsubAttentionEnded = agenticActivityBus.subscribe('agent-attention-ended', (d) => {
872
+ const sessionKey = this.getStateKey();
873
+ if (sessionKey !== undefined && belongsToSession(d.sessionKey, sessionKey)) {
874
+ agentNotifier.close(d.interactionId);
875
+ }
876
+ });
870
877
  const unwatchPermission = watchAgentNotificationPermission((permission) => {
871
878
  this.notificationPermission = permission;
872
879
  });
@@ -881,6 +888,7 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
881
888
  });
882
889
  this._unwireNotifications = () => {
883
890
  unsubAttention();
891
+ unsubAttentionEnded();
884
892
  unwatchPermission();
885
893
  removeHost();
886
894
  };
@@ -1323,7 +1331,8 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
1323
1331
  /**
1324
1332
  * Name of the agent the user has pinned via the agent picker. `null` means
1325
1333
  * orchestration: the assistant routes each message. Persisted on the session store, so it survives
1326
- * pop-in/pop-out but resets on page refresh.
1334
+ * pop-in/pop-out. A page refresh resets it unless session persistence is on, which saves it with
1335
+ * the session and restores it.
1327
1336
  *
1328
1337
  * Only changes on explicit user action (picker click or host's `setAgent`).
1329
1338
  * The orchestrator's auto-pin on stateful activation writes
@@ -1335,7 +1344,7 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
1335
1344
  return (_b = (_a = this._sessionRef) === null || _a === void 0 ? void 0 : _a.store.aiAssistant.pinnedAgentName) !== null && _b !== void 0 ? _b : null;
1336
1345
  }
1337
1346
  set pinnedAgentName(value) {
1338
- var _a, _b, _c, _d;
1347
+ var _a, _b, _c, _d, _e;
1339
1348
  const previous = (_b = (_a = this._sessionRef) === null || _a === void 0 ? void 0 : _a.store.aiAssistant.pinnedAgentName) !== null && _b !== void 0 ? _b : null;
1340
1349
  (_c = this._sessionRef) === null || _c === void 0 ? void 0 : _c.actions.aiAssistant.setPinnedAgentName(value);
1341
1350
  (_d = this.driver) === null || _d === void 0 ? void 0 : _d.setPinnedAgent(value);
@@ -1343,6 +1352,9 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
1343
1352
  // fetch when the user pins/unpins so the prompts match the new agent.
1344
1353
  if (previous !== value) {
1345
1354
  this.logMeta(value ? 'agent.pinned' : 'agent.unpinned', { agent: value !== null && value !== void 0 ? value : previous });
1355
+ // The pin is part of the saved session, but nothing else saves when only the pin changes.
1356
+ // Without this, the last save of a turn keeps a pin that was changed after it.
1357
+ (_e = this.persister()) === null || _e === void 0 ? void 0 : _e.scheduleSave();
1346
1358
  this.suggestionsState = { status: 'idle' };
1347
1359
  this.fetchSuggestions();
1348
1360
  }
@@ -2312,10 +2324,11 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
2312
2324
  };
2313
2325
  // An interaction answered by any route — including a controller's `ctx.resolve`, which never
2314
2326
  // reaches `handleInteractionCompleted` — means the turn is about to compute again (GENC-1660).
2315
- // Not on a timeout or a stop, which carry no `answeredBy`: the turn may be ending.
2327
+ // Not on a timeout or a stop, which carry no `answeredBy`: the turn may be ending. A widget
2328
+ // that settled by itself carries none either, as nobody answered it, but its turn goes on.
2316
2329
  const onInteractionSettled = (e) => {
2317
- var _a;
2318
- if ((_a = e.detail) === null || _a === void 0 ? void 0 : _a.answeredBy)
2330
+ const detail = e.detail;
2331
+ if ((detail === null || detail === void 0 ? void 0 : detail.answeredBy) || (detail === null || detail === void 0 ? void 0 : detail.resolvedItself))
2319
2332
  this.startLoadingTimer();
2320
2333
  };
2321
2334
  const onProviderChanged = (e) => {
@@ -4634,29 +4647,29 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
4634
4647
  this.send();
4635
4648
  }
4636
4649
  /**
4637
- * Programmatically submit a message. Equivalent to the user typing into the
4638
- * built-in composer and pressing send, but callable from external code — most
4639
- * commonly a custom input rendered inside `slot="splash"` when paired with
4640
- * `chatConfig.ui.hideComposer`.
4650
+ * Programmatically submit a message. Sends it the way the built-in composer's
4651
+ * Send does, but from external code — a custom input rendered inside
4652
+ * `slot="splash"` when paired with `chatConfig.ui.hideComposer`, or a host
4653
+ * sending on the user's behalf.
4641
4654
  *
4642
- * The input fully describes the turn: `text` and `files` REPLACE any current
4643
- * composer state (they are not appended to it). Files are validated against
4655
+ * The input fully describes the turn: `text` and `files` are sent as given,
4656
+ * and the composer is never read or cleared, so whatever the user has typed or
4657
+ * attached there stays where it is. Files are validated against
4644
4658
  * `chatConfig.ui.acceptedFiles` using the same pipeline as the composer's
4645
- * attach button.
4659
+ * attach button. `options` routes the message — see {@link SubmitMessageOptions}.
4646
4660
  *
4647
- * Atomic on validation: if any file fails validation, no attachments are
4648
- * committed and no send is dispatched. Failure messages are returned in
4649
- * `errors` AND appended to the `attachmentErrors` observable so the built-in
4650
- * chip UI still surfaces them when visible.
4661
+ * Atomic on validation: if any file fails validation, no send is dispatched,
4662
+ * and the failure messages are returned in `errors`. They are not shown as
4663
+ * composer chips: the files are the caller's, not the user's.
4651
4664
  *
4652
- * Resolves once the underlying send has been kicked off — it does NOT await
4653
- * the assistant's response.
4665
+ * Resolves when the send settles: it awaits the driver's `sendMessage`, which
4666
+ * for the built-in drivers is the whole turn, the assistant's response included.
4654
4667
  *
4655
4668
  * @beta
4656
4669
  */
4657
- submitMessage(input) {
4670
+ submitMessage(input, options) {
4658
4671
  return __awaiter(this, void 0, void 0, function* () {
4659
- var _a, _b, _c;
4672
+ var _a, _b, _c, _d;
4660
4673
  if (this.sendBlocked) {
4661
4674
  return { ok: false, errors: [this.sendRefusalReason()] };
4662
4675
  }
@@ -4664,8 +4677,8 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
4664
4677
  if ((_a = input.files) === null || _a === void 0 ? void 0 : _a.length) {
4665
4678
  const { attachments, errors } = yield this.attachmentCtrl.process(input.files);
4666
4679
  // State may have flipped to 'loading' during the async file processing
4667
- // (e.g. a concurrent send via the composer). Re-check before committing
4668
- // any composer state. Beyond this point execution is synchronous up to
4680
+ // (e.g. a concurrent send via the composer). Re-check before sending.
4681
+ // Beyond this point execution is synchronous up to
4669
4682
  // `await this.send()`, and `send()` sets `state='loading'` before its
4670
4683
  // own first await — so no further race window exists.
4671
4684
  // (Cast widens through TS's narrowing of `this.state` from the earlier
@@ -4674,25 +4687,26 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
4674
4687
  return { ok: false, errors: [this.sendRefusalReason()] };
4675
4688
  }
4676
4689
  if (errors.length) {
4677
- this.attachmentErrors = errors;
4678
4690
  return { ok: false, errors };
4679
4691
  }
4680
4692
  nextAttachments = attachments;
4681
4693
  }
4682
- const text = ((_b = input.text) !== null && _b !== void 0 ? _b : '').trim();
4694
+ // After the file read, as the busy re-check is: `agents` may have changed during it.
4695
+ const agent = options === null || options === void 0 ? void 0 : options.agent;
4696
+ if (typeof agent === 'string' && !((_b = this.agents) !== null && _b !== void 0 ? _b : []).some((a) => a.name === agent)) {
4697
+ return { ok: false, errors: [`Unknown agent: ${agent}`] };
4698
+ }
4699
+ const text = ((_c = input.text) !== null && _c !== void 0 ? _c : '').trim();
4683
4700
  if (!text && !nextAttachments.length) {
4684
4701
  return { ok: false, errors: ['Empty message'] };
4685
4702
  }
4686
- this.inputValue = text;
4687
- this.attachments = nextAttachments;
4688
- this.attachmentErrors = [];
4689
4703
  try {
4690
- yield this.send();
4704
+ yield this.send({ text, attachments: nextAttachments }, agent !== undefined ? { agent } : undefined);
4691
4705
  return { ok: true, errors: [] };
4692
4706
  }
4693
4707
  catch (e) {
4694
4708
  logger.error('submitMessage send failed:', e);
4695
- return { ok: false, errors: [(_c = e === null || e === void 0 ? void 0 : e.message) !== null && _c !== void 0 ? _c : 'Send failed'] };
4709
+ return { ok: false, errors: [(_d = e === null || e === void 0 ? void 0 : e.message) !== null && _d !== void 0 ? _d : 'Send failed'] };
4696
4710
  }
4697
4711
  });
4698
4712
  }
@@ -4768,11 +4782,17 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
4768
4782
  }
4769
4783
  });
4770
4784
  }
4771
- send() {
4785
+ /**
4786
+ * @param message - What to send in place of the composer's contents, which are then neither
4787
+ * read nor cleared (`submitMessage`). Left out, the composer's contents are sent and cleared.
4788
+ * @param routing - Passed on to the driver: how this one message is routed.
4789
+ */
4790
+ send(message, routing) {
4772
4791
  return __awaiter(this, void 0, void 0, function* () {
4773
4792
  var _a;
4774
- const input = this.inputValue.trim();
4775
- if ((!input && !this.attachments.length) || this.sendBlocked)
4793
+ const input = message ? message.text : this.inputValue.trim();
4794
+ const attachments = message ? message.attachments : this.attachments;
4795
+ if ((!input && !attachments.length) || this.sendBlocked)
4776
4796
  return;
4777
4797
  this._pendingSendPrompt = input;
4778
4798
  // Capture the session ref before any await. If a lifecycle event occurs during
@@ -4781,8 +4801,14 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
4781
4801
  // which in turn triggers the _executionCompletionUnsub subscription on whichever
4782
4802
  // element is currently active (e.g. the collapse-mode element after docking).
4783
4803
  const capturedSessionRef = this._sessionRef;
4784
- const pendingAttachments = this.attachmentCtrl.take();
4785
- this.inputValue = '';
4804
+ let pendingAttachments;
4805
+ if (message) {
4806
+ pendingAttachments = attachments.length ? attachments : undefined;
4807
+ }
4808
+ else {
4809
+ pendingAttachments = this.attachmentCtrl.take();
4810
+ this.inputValue = '';
4811
+ }
4786
4812
  this.suggestionsState = { status: 'idle' };
4787
4813
  this._userScrolledAway = false;
4788
4814
  // Close the picker on send — the toggle button is disabled during loading,
@@ -4795,7 +4821,7 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
4795
4821
  this.startLoadingTimer();
4796
4822
  const displayInput = withAttachmentNote(input, pendingAttachments);
4797
4823
  try {
4798
- const result = yield ((_a = this.driver) === null || _a === void 0 ? void 0 : _a.sendMessage(displayInput, pendingAttachments));
4824
+ const result = yield ((_a = this.driver) === null || _a === void 0 ? void 0 : _a.sendMessage(displayInput, pendingAttachments, routing));
4799
4825
  // Latch the backend block the moment the driver reports it, so the composer
4800
4826
  // locks without waiting on the host's next pre-flight. The bus subscription
4801
4827
  // in `connectedCallback` covers most walls; this covers the one it cannot —
@@ -4829,6 +4855,8 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
4829
4855
  if (prevState && prevState !== 'idle') {
4830
4856
  this.logMeta('state.changed', { from: prevState, to: 'idle' });
4831
4857
  }
4858
+ // Before a deferred session switch below re-keys the element: the turn was this session's.
4859
+ this.reportTurnEnded(prevState, capturedSessionRef);
4832
4860
  this.syncShowHalo();
4833
4861
  this.fetchSuggestions();
4834
4862
  // setState was dispatched directly via the captured ref (not via the
@@ -4839,6 +4867,31 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
4839
4867
  this.applyDeferredSessionSwitch();
4840
4868
  this.applyDeferredAgentsSwap();
4841
4869
  }
4870
+ /**
4871
+ * Report a turn that ended with the assistant waiting for the person to type (GENC-1660), for the
4872
+ * Always level: `turn-ended` on the activity bus, like every other notification report.
4873
+ *
4874
+ * Only for a turn that ran to its end, failed ones included: not one the person stopped
4875
+ * (`cancelling`), since they are there. Not while an interaction waits on them, which reports
4876
+ * itself, so the person is never told twice about one moment. And not while an autopilot runs for
4877
+ * the flow: it answers, hands back or reports its own stop. Sub-agents' turns never get here; they
4878
+ * run inside one of the parent's.
4879
+ */
4880
+ reportTurnEnded(prevState, sessionRef) {
4881
+ var _a, _b;
4882
+ if (prevState !== 'loading')
4883
+ return;
4884
+ const sessionKey = this.getStateKey();
4885
+ if (!sessionKey)
4886
+ return;
4887
+ if (((_a = this.autopilotHost) === null || _a === void 0 ? void 0 : _a.state.mode) === 'running')
4888
+ return;
4889
+ const messages = (_b = sessionRef === null || sessionRef === void 0 ? void 0 : sessionRef.store.aiAssistant.messages) !== null && _b !== void 0 ? _b : [];
4890
+ const last = messages[messages.length - 1];
4891
+ if ((last === null || last === void 0 ? void 0 : last.interaction) && !last.interaction.resolved)
4892
+ return;
4893
+ agenticActivityBus.publish('agent-attention', { sessionKey, kind: 'turn-ended' });
4894
+ }
4842
4895
  onChatHeaderMouseDown(e) {
4843
4896
  if (this.popoutMode === 'collapse')
4844
4897
  return;
@@ -628,13 +628,16 @@ ${(tc) => { var _a; return (((_a = tc.foldPath) === null || _a === void 0 ? void
628
628
  // it is filled the way the person's own bubble is while it runs, since it is filling in for them.
629
629
  // A toggle: `aria-pressed` carries its state, so its accessible name is constant (the pill's own
630
630
  // label) and what the click does — Pause / Resume — leads its tooltip instead.
631
+ // While on it carries a second part name, `autopilot-toggle-on`, as the conversation carries
632
+ // `conversation-has-stepper`: `::part()` cannot select a class or an attribute, so without it a
633
+ // host could restyle the pill but not its on state, e.g. to fill it with its own user-bubble token.
631
634
  const autopilotToggleTemplate = html `
632
635
  <${buttonTag}
633
636
  class="${(x) => classNames('composer-pill', 'composer-pill-labelled', 'autopilot-toggle', [
634
637
  'is-on',
635
638
  x.autopilotCanPause,
636
639
  ])}"
637
- part="autopilot-toggle"
640
+ part="${(x) => (x.autopilotCanPause ? 'autopilot-toggle autopilot-toggle-on' : 'autopilot-toggle')}"
638
641
  appearance="stealth"
639
642
  aria-pressed="${(x) => (x.autopilotCanPause ? 'true' : 'false')}"
640
643
  title="${(x) => x.autopilotToggleTitle}"
@@ -44,12 +44,22 @@ export const levelOffered = (level, config) => notificationsOffered(config) && (
44
44
  * @internal
45
45
  */
46
46
  export const effectiveNotificationLevel = (stored, config) => (levelOffered(stored, config) ? stored : 'off');
47
+ /**
48
+ * The lowest level that notifies for each kind. Keyed by the union, so a new kind is a compile
49
+ * error here rather than one every level silently shows or hides.
50
+ */
51
+ const KIND_LEVEL = {
52
+ 'autopilot-handed-back': 'autopilot',
53
+ 'autopilot-stopped': 'autopilot',
54
+ 'widget-needs-input': 'needs-input',
55
+ 'turn-ended': 'needs-input',
56
+ };
47
57
  /**
48
58
  * Whether a level notifies for a kind of event.
49
59
  *
50
60
  * @internal
51
61
  */
52
- export const levelAllows = (level, kind) => level === 'needs-input' || (level === 'autopilot' && kind !== 'widget-needs-input');
62
+ export const levelAllows = (level, kind) => level === 'needs-input' || (level === 'autopilot' && KIND_LEVEL[kind] === 'autopilot');
53
63
  /**
54
64
  * Whether an event's session is `sessionKey` or one of its sub-agents' sessions.
55
65
  *
@@ -2,8 +2,8 @@ import { logger } from '../utils/logger';
2
2
  import { agentNotificationPermission, DEFAULT_AGENT_NOTIFICATION_MESSAGE, levelAllows, } from './agent-notifications';
3
3
  /**
4
4
  * How long a notification with a given tag holds off another with the same tag. Two sources can
5
- * report one moment — the autopilot declining a widget it may not answer, and that widget asking
6
- * for attention — and the second should not alert again. It may still improve the text: see
5
+ * report one moment — the autopilot handing a widget back, and that widget asking for attention
6
+ * just after — and the second should not alert again. It may still improve the text: see
7
7
  * `AgentNotifier.notify`.
8
8
  */
9
9
  const REPEAT_WINDOW_MS = 5000;
@@ -19,19 +19,23 @@ const browserEnv = {
19
19
  notification.close();
20
20
  onClick();
21
21
  };
22
+ return notification;
22
23
  },
23
24
  now: () => Date.now(),
24
25
  };
26
+ /** One interaction's tag, whichever report it came from. */
27
+ const interactionTag = (interactionId) => `ai-assistant:${interactionId}`;
25
28
  /**
26
29
  * The tag a notification carries. The browser replaces a notification that has the same tag, so
27
30
  * windows that share a session never stack copies. Interaction ids are unique, so one interaction
28
31
  * gets one notification whichever session reported it (a sub-agent's or its parent's); everything
29
- * else the autopilot reports shares one per session.
32
+ * else shares one per session — the autopilot's stop, and a turn ending (GENC-1660), which can
33
+ * report the same moment when the turn that ends the flow stops the autopilot.
30
34
  *
31
35
  * @internal
32
36
  */
33
37
  export const agentNotificationTag = (detail) => detail.interactionId
34
- ? `ai-assistant:${detail.interactionId}`
38
+ ? interactionTag(detail.interactionId)
35
39
  : `ai-assistant:${detail.sessionKey}:autopilot`;
36
40
  /**
37
41
  * Decides whether an `agent-attention` event becomes a browser notification, and shows it
@@ -40,8 +44,11 @@ export const agentNotificationTag = (detail) => detail.interactionId
40
44
  * Shows nothing when the level does not cover the event, when permission is not granted, while
41
45
  * the person is looking at the page (the in-page UI covers that), or when the same tag was just
42
46
  * shown — unless the repeat brings a widget's own message the first lacked. That one replaces the
43
- * notification under the same tag, silently: the autopilot reports a widget it declines before
44
- * the widget's own request is reported, and the widget's words are the better ones.
47
+ * notification under the same tag, silently: the autopilot hands a widget back before the
48
+ * widget's own request is reported, and the widget's words are the better ones.
49
+ *
50
+ * A notification about an interaction is closed once that interaction stops waiting on the person
51
+ * (`close`), so a stale one does not linger (GENC-1660).
45
52
  *
46
53
  * @internal
47
54
  */
@@ -50,6 +57,8 @@ export class AgentNotifier {
50
57
  this.env = env;
51
58
  /** Each tag shown within the repeat window: when, and whether it carried a widget's message. */
52
59
  this.shown = new Map();
60
+ /** The notification showing for each interaction's tag, until it is closed. */
61
+ this.open = new Map();
53
62
  }
54
63
  /** Show a notification for `detail` if it should be shown. Returns whether it was. */
55
64
  notify(detail, context) {
@@ -71,8 +80,9 @@ export class AgentNotifier {
71
80
  const replacing = !!previous && !previous.message && !!detail.message;
72
81
  if (previous && !replacing)
73
82
  return false;
83
+ let handle;
74
84
  try {
75
- this.env.show(context.title, Object.assign({ body: detail.message || context.message || DEFAULT_AGENT_NOTIFICATION_MESSAGE, tag }, (replacing ? { silent: true } : {})), context.onClick);
85
+ handle = this.env.show(context.title, Object.assign({ body: detail.message || context.message || DEFAULT_AGENT_NOTIFICATION_MESSAGE, tag }, (replacing ? { silent: true } : {})), context.onClick);
76
86
  }
77
87
  catch (e) {
78
88
  // Some browsers (Chrome on Android) only allow notifications from a service worker, and
@@ -81,6 +91,30 @@ export class AgentNotifier {
81
91
  return false;
82
92
  }
83
93
  this.shown.set(tag, { at: (_a = previous === null || previous === void 0 ? void 0 : previous.at) !== null && _a !== void 0 ? _a : now, message: !!detail.message });
94
+ // Only an interaction's: the session's own (a stop, a turn ending) has nothing to go stale on.
95
+ if (detail.interactionId && handle)
96
+ this.open.set(tag, handle);
97
+ return true;
98
+ }
99
+ /**
100
+ * Close the notification showing for `interactionId`, if one is: the interaction no longer waits
101
+ * on the person, because it settled or a claimant took it (GENC-1660). Its tag is forgotten too,
102
+ * so if the interaction comes back to the person (a claimant hands it back), that notifies anew.
103
+ * Returns whether one was closed.
104
+ */
105
+ close(interactionId) {
106
+ const tag = interactionTag(interactionId);
107
+ this.shown.delete(tag);
108
+ const handle = this.open.get(tag);
109
+ if (!handle)
110
+ return false;
111
+ this.open.delete(tag);
112
+ try {
113
+ handle.close();
114
+ }
115
+ catch (e) {
116
+ logger.warn('AgentNotifier: could not close a notification', e);
117
+ }
84
118
  return true;
85
119
  }
86
120
  }
@@ -78,8 +78,8 @@ export const META_EVENT_IMPORTANCE = {
78
78
  'interaction.outcome-dropped': 'high',
79
79
  // A long action's step starting, finishing, or skipped on resume because it was already done.
80
80
  'interaction.step': 'low',
81
- // A cut checkpoint taken over after a reload, refused (by sameWork, or as malformed), or dropped
82
- // at flow end.
81
+ // A cut checkpoint taken over after a reload, refused (by sameWork, and kept for a later request;
82
+ // or as malformed), or dropped at flow end, as is the live one.
83
83
  'interaction.checkpoint': 'normal',
84
84
  // A claimant handing a pending interaction to the person, or taking it back.
85
85
  'interaction.held': 'normal',
@@ -253,8 +253,8 @@ export const DEBUG_LOG_README = [
253
253
  '`timeline` is the entire session as one array, already sorted chronologically by `timestamp` (ISO 8601). Every entry has a `kind`.',
254
254
  'Timestamps are millisecond-resolution; entries that share the same millisecond are ordered by a fixed kind rank (event, then turn, then message), which is a heuristic and may not reflect exact causal order within that millisecond — e.g. a user message and the turn it triggered, or a final assistant message and its turn.end event, can appear in either order depending on whether they landed in the same millisecond. Read the logical structure of a turn rather than over-interpreting the micro-ordering of co-timestamped entries of different kinds.',
255
255
  "kind:'message' — the conversation. `role` is user/assistant/tool/system-event/synthetic-user; `agentName` says which agent produced it; `toolCalls`/`toolResult`/`interaction` carry tool and widget activity; `inputTokens`/`outputTokens`/`cost` are per-message LLM usage, where `inputTokens` is the WHOLE prompt for that request and `cacheReadTokens`/`cacheWriteTokens` BREAK IT DOWN rather than add to it — uncached input is `inputTokens` minus those two, and adding the cache fields to `inputTokens` counts the prompt twice. The cache fields are absent on providers that report no cache split (Gemini reports reads only, since implicit caching bills no write) and on messages persisted before they existed, so read them as 0 when missing. Each bucket bills at a different rate — cache reads a fraction of uncached input, cache writes a premium, output highest — so a large token count at a small cost means the prompt was mostly cache hits. `externalCostUsd` is any non-LLM cost a widget reported for its own external service calls (folded into the session cost total alongside `cost`). On model-produced assistant messages, `model` is the concrete model id that generated it (e.g. 'gemini-2.5-flash-lite') and `providerName` is the registry slot it resolved under (e.g. a tier name like 'high'/'low', or the default); together they attribute the message — and any tool calls it carries — to an exact model even across a mid-session vendor/tier switch, where one slot name can map to different models before and after the switch. Both are undefined on any entry that is NOT an LLM response: non-assistant roles (user/tool/system-event) and 'synthetic-user' echoes; assistant interaction/widget entries (empty content carrying an `interaction` — a rendered widget, not a model turn); driver-authored assistant fallbacks (the timeout, repeated-malformed-call, and empty-response apology messages); and messages restored from a session persisted before these fields existed. One partial case: on a genuine model turn whose provider exposes no `getStatus` (or reports no model), `providerName` is still set but `model` alone is undefined. A 'synthetic-user' message is a display-only echo of an interaction outcome (e.g. the answer a widget reported): it renders on the user's side of the chat and `agentName` is the agent that created it, but it is never sent to the LLM — so it has no matching 'turn' and the model learns the outcome only from the corresponding tool result. An echo of an answer an interceptor (such as an autopilot) gave is NOT synthetic-user: see the delegated-messages paragraph.",
256
- 'The autopilot (GENC-1660) runs on a driver of its own, and everything it did is harvested into this log: entries with delegate: autopilot and an agentName ending in › Autopilot are its turns (the decision message it was sent is the user message of its turn, so what it was shown is there verbatim; its systemPrompt is its grounding, such as the brief), its tool calls (widget_read, widget_act, hand_back) and their results, and its own events. Its cost is already in the session total: it is booked as externalCostUsd on the interaction each decision answered, or, for a written question it answered, on the user message it sent on the user behalf (delegate: autopilot), so do not add its turns to that total. Spend that reached no message is recorded as autopilot.cost-dropped instead.',
257
- "Delegated messages (GENC-1660): a message with a `delegate` field was written or sent ON THE USER'S BEHALF by a driver decorator, and `delegate` names it (e.g. autopilot). The platform stamps it; nothing else can. It renders as the assistant whatever its role. A delegated `user` message was NOT typed by the user: it is an answer given on their behalf, and the model read it with `delegateFraming` in brackets in front of the content (the stored `content` is the bare text). A delegated `assistant` message is display-only (`excludeFromProvider`): the decorator's narration, or the echo of a widget answer it gave, which takes the place of a synthetic-user echo. To tell what the person decided from what was decided for them, read `interaction.answeredBy` and these fields, never the role alone.",
256
+ 'The autopilot (GENC-1660) runs on a driver of its own, and everything it did is harvested into this log: entries with delegate: autopilot and an agentName ending in › Autopilot are its turns (the decision message it was sent is the user message of its turn, so what it was shown is there verbatim; its systemPrompt is its grounding, such as the brief), its tool calls (widget_read, widget_act, hand_back, any read-only tools of its own, and its widget tools — reads with parameters that a widget type declares, routed to the interaction of that type being decided and refused with a reason when none is, offered on every decision so its tool list never changes; while one is open its tail starts with a line naming them) and their results (a read, view or widget tool, is capped at about 20,000 characters, cut with a note asking for less, and leaves its history at the end of the decision as a one-line note), and its own events. Its cost is already in the session total: it is booked as externalCostUsd on the interaction each decision answered, or, for a written question it answered, on the user message it sent on the user behalf (delegate: autopilot), so do not add its turns to that total. Spend that reached no message is recorded as autopilot.cost-dropped instead.',
257
+ "Delegated messages (GENC-1660): a message with a `delegate` field was written or sent ON THE USER'S BEHALF by a driver decorator, and `delegate` names it (e.g. autopilot). The platform stamps it; nothing else can. It renders as the assistant whatever its role. A delegated `user` message was NOT typed by the user: it is an answer given on their behalf, and the model read it with `delegateFraming` in brackets in front of the content (the stored `content` is the bare text). A delegated `assistant` message is display-only (`excludeFromProvider`): the decorator's narration note, or, when its answer carried no note, the widget's own echo of the answer (its `userMessage`), shown as the assistant and never as the person. A widget answer a decorator gave with a note is not echoed at all: the note already says what was chosen. To tell what the person decided from what was decided for them, read `interaction.answeredBy` and these fields, never the role alone.",
258
258
  "Sub-agent messages appear inline. When a tool delegates to a sub-agent (via `requestSubAgent`), the sub-agent's whole conversation — its own assistant/tool messages, each with their own `content`/`thinking`/`toolCalls`/`toolResult` and per-message `model`/`providerName`/`inputTokens`/`outputTokens`/`cacheReadTokens`/`cacheWriteTokens`/`cost` — is hoisted into the timeline as ordinary kind:'message' entries, interleaved by timestamp right after the tool call that spawned them (so you read the delegation top-to-bottom). A hoisted entry is marked: `subAgentDepth` is its delegation depth (1 for a sub-agent, 2 for a sub-agent's sub-agent, …), `subAgentOf` is the id of the parent tool call that spawned it (correlates it back even when two sub-agents run in one parent turn), `subAgentName` is the sub-agent's own name, and `agentName` is rewritten to a `\"<parent> › <sub-agent>\"` breadcrumb (composing when nested, e.g. `\"UI Builder › Planner › Grounding\"`). The sub-agent's per-LLM-call snapshots also surface as kind:'turn' entries with an N-M `turnIndex`, and subagent.started/completed (or subagent.failed) events bracket the run. Per-message `cost` on hoisted entries is already part of the session total (it is summed from the un-flattened history), so summing the top-level timeline does NOT double-count.",
259
259
  "kind:'turn' — one LLM call. `turnIndex` is a string: a top-level turn is the bare counter ('0', '1', …); a sub-agent's turns are numbered under the parent turn that activated them ('3-1', '3-2', …, and a nested sub-agent contributes '3-2-1', …), and `agentName` names the agent that ran the turn. `systemPrompt` and `toolNames` are what the model saw. A systemPrompt of '<repeated — identical to turn N>' was byte-identical to turn N and de-duplicated; the full prompt is shown whenever it changes (often because a stateful agent advanced), so prompt evolution is visible.",
260
260
  "kind:'turn'.`model`/`providerName`/`provider` — which model ran that call: the concrete model id, the registry slot it resolved under (a tier name like 'high'/'low', or the default), and the vendor. Recorded per CALL, so an agent whose `provider` selector varies by state — a flow that plans on a high tier and executes on a low one — has every step attributed, including calls that produced no message. `model` is the SERVING model where the provider reports one, so a turn answered by a server-side fallback names the model that answered rather than the one requested; it always matches the `model` on the message that call produced. Absent when the provider exposes no `getStatus` and the transport stamped nothing.",
@@ -262,11 +262,11 @@ export const DEBUG_LOG_README = [
262
262
  "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.",
263
263
  "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'.",
264
264
  "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.",
265
- '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; detail.ownerPath names the agents that actually asked, outermost first, the last being the one whose tool requested it, and detail.heldBy says who held it when it opened: user, or the id of the interceptor that claimed it, such as autopilot; on interaction.resolved, detail.answeredBy is who answered — the claimant id when it settled through its own hold, user for any other answer (a click counts as the person even on a widget a claimant held) — absent when it closed unanswered (a timeout or a stop); the same value is stamped on the interaction message as answeredBy, and when it is not user the tool result that interaction returned carries a decidedOnUsersBehalf record, so the model was told the choice was not made by the person; detail.edits, present only when non-zero, counts the editing actions a claimant ran on the widget before it was settled, whoever settled it, and those edits are stamped on the interaction message as edits, each with by, action, choice and args when it had some, in the order they ran, while a decidedOnUsersBehalf record carries their choice texts as edits, and when the person settled it after such edits the tool result carries an editedOnUsersBehalf record instead — the framing and those choice texts — so the model knows the widget was changed on the user behalf before the user answered, and that the user then confirmed it by finishing it), interaction.held (a claimant moved a pending interaction to the person or back to itself — detail.heldBy is the new holder, detail.claimant the interceptor; a widget held by anything but user was not answered by the person), interaction.claim-refused (a claim on a userOnly interaction, which stays with the person — detail.claimant + reason), autopilot.* (the autopilot, a decorator that answers interactions on behalf of the user — autopilot.claimed / autopilot.declined say whether it took each interaction and, for a decline, detail.reason: paused, other-flow, no-autopilot, unavailable, userOnly, policy or no-controller; autopilot.decision-sent is what it was sent (detail.chars); autopilot.acted is what it did (detail.action, detail.note, detail.finished); autopilot.handed-back is a decision it gave to the person (detail.reason and detail.trigger: model, no-decision or error); autopilot.paused / autopilot.resumed are mode changes (detail.scope, detail.trigger, detail.decideYourself when the person resumed during a hand-back; detail.trigger is restored when the mode came back with the session after a reload, applied once its flow re-activated, which starts nothing by itself); autopilot.error is the wrapper itself failing; autopilot.refinement counts a written answer against its step (detail.stepKey, detail.count, detail.limitReached, after which reply is withdrawn for that step); autopilot.handback-presented is the turn-level hand-back, shown when a working turn ended needing the person with no widget to hand over (detail.why: max-iterations, context-exhausted, failure or question; detail.options; detail.choice once answered); autopilot.catch-up is the autopilot being given the whole visible transcript at once (detail.why: first, for its first decision in a flow or after a reload; size, when its own history passed its budget and was rebuilt short — detail.ownChars; or compacted, when a compaction removed the last message it had seen, so it reads the summary and everything since, short; in each, what it had sent on the user behalf is included and labelled as its own, since its own history does not hold it); autopilot.cost-dropped is autopilot spend that no message carries, so it is NOT in the session total (detail.costUsd and detail.why: handed-back, aborted or stale for a written question it answered that no reply was sent for — stale when a pause, a resume, a new turn or the end of its flow came before the answer landed, which then went nowhere — or no-recorder when the driver had no way to book a decision to its interaction); a hand-back trigger can also be budget (the decision passed its spend cap), watchdog (its work went quiet: no ready surface and no heartbeat, or its own decision stalled with no model call landing, which stops that decision) or detached (the autopilot was removed while it held the interaction, which went to the person with no reason shown). To debug one autopilot decision, follow its interactionId: interaction.requested (heldBy), autopilot.claimed, autopilot.decision-sent, autopilot.acted or autopilot.handed-back, interaction.invoked, interaction.resolved (answeredBy), then the next turn of the working agent), interaction.invoked (a claimant ran one of the actions the widget itself exposes, through its hold, the same code the button runs — detail.claimant, detail.action (an option id, select or reply) and detail.finished, whether that settled the interaction, and when it did not, the run is recorded as an edit; the choice and narration it recorded reach the result of the tool that asked as decidedOnUsersBehalf), interaction.step (a long action run as named steps through runSteps, which survive a reload — detail.step and detail.outcome: started, done, skipped when the step was already done before a reload, or resumed when it started before a reload and runs again with what it saved part-way, such as a job id it re-attaches to), interaction.checkpoint (the one checkpoint a conversation keeps for its long action — detail.action: resumed when a reload cut the work and the next request of the same widget type took it over, refused when the registration sameWork said the new request is different work (detail.saved is the identity it kept) or when runSteps found the handed-over checkpoint malformed and started fresh (detail.reason, detail.saved), or cleared when its flow ended with nothing taking it over), 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.',
265
+ '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; detail.ownerPath names the agents that actually asked, outermost first, the last being the one whose tool requested it, and detail.heldBy says who held it when it opened: user, or the id of the interceptor that claimed it, such as autopilot; on interaction.resolved, detail.answeredBy is who answered — the claimant id when it settled through its own hold, user for any other answer (a click counts as the person even on a widget a claimant held) — absent when it closed unanswered (a timeout or a stop), and absent too when it settled by itself other than through the hold of a claimant — a widget registered resolvesItself (one that does its work and settles on its own, asking the person nothing, such as a generation run), or one outcome its controller said settled itself (ctx.resolve with resolvedItself, such as a generation phase that failed outright before its review gate ever asked anything) — which then carries detail.resolvedItself: true instead, as the interaction message does — nobody answered it, and the platform cannot tell it finishing from the person interrupting it (a Skip), so only the result of the widget itself can say which; the same value is stamped on the interaction message as answeredBy and on the result the asking tool handler receives (absent there in the same cases), and when it is not user the tool result that interaction returned carries a decidedOnUsersBehalf record, so the model was told the choice was not made by the person; detail.edits, present only when non-zero, counts the editing actions a claimant ran on the widget before it was settled, whoever settled it, and those edits are stamped on the interaction message as edits, each with by, action, choice and args when it had some, in the order they ran, while a decidedOnUsersBehalf record carries their choice texts as edits, and when the person settled it after such edits the tool result carries an editedOnUsersBehalf record instead — the framing and those choice texts — so the model knows the widget was changed on the user behalf before the user answered, and that the user then confirmed it by finishing it), interaction.held (a claimant moved a pending interaction to the person or back to itself — detail.heldBy is the new holder, detail.claimant the interceptor; detail.late: true is an interceptor that declined it when it opened claiming it afterwards, such as the autopilot resumed while it was open; a widget held by anything but user was not answered by the person), interaction.claim-refused (a claim on a userOnly interaction, which stays with the person — detail.claimant + reason), autopilot.* (the autopilot, a decorator that answers interactions on behalf of the user — autopilot.claimed / autopilot.declined say whether it took each interaction and, for a decline, detail.reason: paused, other-flow, no-autopilot, unavailable, userOnly, policy or no-controller; one declined as paused that is still open when the person resumes the autopilot is looked at again, and the autopilot.claimed or autopilot.declined recorded for it then carries detail.onResume: true (a decline then can also be claimed-elsewhere, another interceptor having claimed it first); a restored mode looks at nothing; autopilot.decision-sent is what it was sent (detail.chars; detail.nothingEnabled: true when every action on the widget was unavailable — a gate whose controller said it was asking, such as a failed build the autopilot may not cancel — so it could only hand it back, which it may then do even after the person asked it to decide it itself; a widget whose controller says it is working (ctx.setWorking) is never sent a decision until it says it is asking, even when an action is enabled or the person resumes the autopilot); autopilot.acted is what it did (detail.action, detail.note, detail.finished); autopilot.handed-back is a decision it gave to the person (detail.reason and detail.trigger: model, no-decision or error); autopilot.paused / autopilot.resumed are mode changes (detail.scope, detail.trigger, detail.decideYourself when the person resumed during a hand-back; detail.trigger is restored when the mode came back with the session after a reload, applied once its flow re-activated, which starts nothing by itself); autopilot.error is the wrapper itself failing; autopilot.refinement counts a refining action against its step — a written answer (reply) or a widget action declared refines, such as a regenerate with instructions, counted together (detail.action, detail.stepKey, detail.count, detail.limitReached, after which every refining action is withdrawn for that step: not listed, and refused; the decision and every relisting of its actions say how many are left at the step, as a line Refinements left at this step: N, wherever the widget has a refining action); autopilot.handback-presented is the turn-level hand-back, shown when a working turn ended needing the person with no widget to hand over (detail.why: max-iterations, context-exhausted, failure or question; detail.options; detail.choice once answered); autopilot.catch-up is the autopilot being given the whole visible transcript at once (detail.why: first, for its first decision in a flow or after a reload; size, when its own history passed its budget and was rebuilt short — detail.ownChars; or compacted, when a compaction removed the last message it had seen, so it reads the summary and everything since, short; in each, what it had sent on the user behalf is included and labelled as its own, since its own history does not hold it); autopilot.cost-dropped is autopilot spend that no message carries, so it is NOT in the session total (detail.costUsd and detail.why: handed-back, aborted or stale for a written question it answered that no reply was sent for — stale when a pause, a resume, a new turn or the end of its flow came before the answer landed, which then went nowhere — or no-recorder when the driver had no way to book a decision to its interaction); a hand-back trigger can also be budget (the decision passed its spend cap), watchdog (its work went quiet: no ready surface and no heartbeat, or its own decision stalled with no model call landing, which stops that decision) or detached (the autopilot was removed while it held the interaction, which went to the person with no reason shown). To debug one autopilot decision, follow its interactionId: interaction.requested (heldBy), autopilot.claimed, autopilot.decision-sent, autopilot.acted or autopilot.handed-back, interaction.invoked, interaction.resolved (answeredBy), then the next turn of the working agent), interaction.invoked (a claimant ran one of the actions the widget itself exposes, through its hold, the same code the button runs — detail.claimant, detail.action (an option id, select or reply) and detail.finished, whether that settled the interaction, and when it did not, the run is recorded as an edit; the choice and narration it recorded reach the result of the tool that asked as decidedOnUsersBehalf), interaction.step (a long action run as named steps through runSteps, which survive a reload — detail.step and detail.outcome: started, done, skipped when the step was already done before a reload, or resumed when it started before a reload and runs again with what it saved part-way, such as a job id it re-attaches to), interaction.checkpoint (the checkpoints a conversation keeps for its long actions: the one in flight, and each one a reload cut, held apart until a request of its own widget type takes it over, so a resumed flow that opens other long widgets first, which save their own, loses nothing — detail.action: resumed when a reload cut the work and a request of the same widget type that the registration sameWork agrees is the same work took it over, refused when sameWork said a new request is different work (detail.saved is the identity it kept; detail.kept: true, since it stays for a later request of that type, and is offered to every one until one agrees) or when runSteps found the handed-over checkpoint malformed and started fresh (detail.reason, detail.saved), or cleared when its flow ended, once per checkpoint, with detail.cut: true for one a reload cut that nothing took over), 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.',
266
266
  '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.',
267
267
  "`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.",
268
268
  '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.',
269
- "kind:'event' type 'routing.decided' — how ONE turn was routed, emitted by the orchestrating driver before the agent runs (and again after every handoff). `decision` is why that agent was chosen: 'classified' (the classifier ran and picked one), 'no-match' (it ran and answered -1 — nothing listed covers the request), 'ballot-exhausted' (every eligible specialist had already handed off this turn, so the ballot was empty and NO call was made — distinct from 'no-match', where one ran and declined), 'pinned' (a user pin or an active stateful flow owned the turn, so no call was made), 'single-candidate'/'no-specialists' (configuration left nothing to decide), 'provider-unavailable' (the registry default exposes no chat()), 'classifier-failed' (every attempt threw — `error` carries the last one). `to` names the agent and `fallback` says whether that agent is the fallback. `candidates` is what was actually ON THE BALLOT, in ballot order, so `index` — the classifier's own answer — indexes it directly; `excluded` names the specialists left off because they already handed off this turn, so the full eligible set is `candidates` ∪ `excluded`. `candidates` is absent on the four decisions that put nothing to a vote — 'pinned', 'single-candidate', 'no-specialists', 'ballot-exhausted'. It IS present on 'provider-unavailable', which is not an exception worth removing: the ballot was built there, it simply never got sent. `attempts` covers the retry ladder. `durationMs` is on EVERY routing.decided, and is the field to read when a decision looks wrong: the four decisions that can reach the fallback are told apart by the clock as much as by their name, because a fallback routing that resolved in tens of milliseconds made no network call at all whatever its `decision` says.",
269
+ "kind:'event' type 'routing.decided' — how ONE turn was routed, emitted by the orchestrating driver before the agent runs (and again after every handoff). `decision` is why that agent was chosen: 'classified' (the classifier ran and picked one), 'no-match' (it ran and answered -1 — nothing listed covers the request), 'ballot-exhausted' (every eligible specialist had already handed off this turn, so the ballot was empty and NO call was made — distinct from 'no-match', where one ran and declined), 'pinned' (a user pin, an agent named for that one message by the send's `agent` option, or an active stateful flow owned the turn, so no call was made), 'single-candidate'/'no-specialists' (configuration left nothing to decide), 'provider-unavailable' (the registry default exposes no chat()), 'classifier-failed' (every attempt threw — `error` carries the last one). `to` names the agent and `fallback` says whether that agent is the fallback. `candidates` is what was actually ON THE BALLOT, in ballot order, so `index` — the classifier's own answer — indexes it directly; `excluded` names the specialists left off because they already handed off this turn, so the full eligible set is `candidates` ∪ `excluded`. `candidates` is absent on the four decisions that put nothing to a vote — 'pinned', 'single-candidate', 'no-specialists', 'ballot-exhausted'. It IS present on 'provider-unavailable', which is not an exception worth removing: the ballot was built there, it simply never got sent. `attempts` covers the retry ladder. `durationMs` is on EVERY routing.decided, and is the field to read when a decision looks wrong: the four decisions that can reach the fallback are told apart by the clock as much as by their name, because a fallback routing that resolved in tens of milliseconds made no network call at all whatever its `decision` says.",
270
270
  "kind:'event' type 'routing.decided'.`usage` — what that classifier call cost, in the same four-bucket + costUsd shape as `sessionUsage`, plus `model`. Absent on the decisions that make no call (see 'pinned' and the configuration ones). THIS SPEND IS NOT IN `sessionUsage`: a classifier call never enters the transcript and `sessionUsage` is derived from the transcript, so classifier cost is missing from the session total by construction, not by accident. Sum these events to close that gap — it is the one component of a session's real spend that the totals cannot see.",
271
271
  'To debug a failure: find the last turn.error or tool.failed, then read upward for the user message, the turn(s), and the agent/provider/state events that led into it. For a turn that went to the wrong agent, read its routing.decided first — `decision` says whether anything was actually asked.',
272
272
  ];