@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
@@ -20,6 +20,30 @@ const DEFAULT_DECISION_FRAMING = "Decided on the user's behalf";
20
20
  * mean it was never the autopilot's to answer.
21
21
  */
22
22
  const HANDED_TO_PERSON = new Set(['policy', 'userOnly', 'no-controller']);
23
+ /**
24
+ * How long a widget the autopilot leaves with the person must go on waiting on them before that is
25
+ * reported as a hand-back (GENC-1660). Its message is appended after the interceptors are asked, and
26
+ * rendered on the next animation frame, so a widget that settles itself as it mounts does so a frame
27
+ * or more after the decline (11 ms in the session that found this): one task (`setTimeout(0)`) runs
28
+ * before that frame, so it is not enough. A quarter of a second covers several frames on a busy
29
+ * page, and is no delay for a notification. A hidden tab runs no frames at all, so there only
30
+ * registering such a widget `resolvesItself` keeps it from reporting (see `asksThePerson`). The
31
+ * same wait lets a widget that starts asking call `setWorking(false)` and `requestAttention` in
32
+ * either order: its message is read once both have landed.
33
+ *
34
+ * @internal
35
+ */
36
+ export const HAND_BACK_GRACE_MS = 250;
37
+ /**
38
+ * Whether `opened` asks the person something, while they hold it (GENC-1660): not when its
39
+ * controller says it is working (`ctx.setWorking(true)`), nor, when its controller has said neither,
40
+ * when it is registered `resolvesItself` — work running, which settles by itself. A controller that
41
+ * says it is asking (`ctx.setWorking(false)`) is, whatever its registration says.
42
+ */
43
+ const asksThePerson = (opened) => {
44
+ var _a, _b;
45
+ return !((_a = opened.ctx.working) !== null && _a !== void 0 ? _a : ((_b = getInteractionRegistration(opened.componentName)) === null || _b === void 0 ? void 0 : _b.resolvesItself) === true);
46
+ };
23
47
  /**
24
48
  * Nothing is happening, and not because the person paused it or has its hand-back: in its flow,
25
49
  * or after its flow ended. Whether that is a stop depends on what came before; see `watchForStop`.
@@ -54,6 +78,7 @@ const DEFAULT_COPY = {
54
78
  running: 'Working on your behalf',
55
79
  paused: 'Paused',
56
80
  selfPaused: "Waiting for your answer: I'll carry on after this",
81
+ waitingForUser: 'Waiting for your answer',
57
82
  handBackLead: 'I need your input on this one:',
58
83
  toggleLabel: 'Autopilot',
59
84
  description: "Answers the assistant's questions on your behalf, so the work keeps going.",
@@ -115,6 +140,8 @@ export class AutopilotDriver extends BaseDriverDecorator {
115
140
  * waited out. See `watchForStop`.
116
141
  */
117
142
  this.ranSinceStop = false;
143
+ /** Stops each wait for a widget left with the person to ask them; see `reportHandBackWhenAsking`. */
144
+ this.handBackWaits = new Set();
118
145
  this.agents = options.agents;
119
146
  this.providerRegistry = options.providerRegistry;
120
147
  this.sessionKey = (_a = options.sessionKey) !== null && _a !== void 0 ? _a : '';
@@ -166,9 +193,13 @@ export class AutopilotDriver extends BaseDriverDecorator {
166
193
  this.onDetach(() => {
167
194
  this.disarmWatchdog();
168
195
  clearTimeout(this.stopCheck);
196
+ for (const stop of this.handBackWaits)
197
+ stop();
169
198
  inner.removeEventListener('flow-owner-changed', onFlowOwnerChanged);
170
199
  inner.removeEventListener('history-updated', onHistoryUpdated);
171
200
  this.releaseHeld();
201
+ this.open = undefined;
202
+ this.declinedWhilePaused = undefined;
172
203
  this.endSessions();
173
204
  });
174
205
  }
@@ -185,7 +216,33 @@ export class AutopilotDriver extends BaseDriverDecorator {
185
216
  const mode = this.onFor === owner ? this.mode : 'paused';
186
217
  const copy = this.copyFor(owner);
187
218
  const selfPaused = ((_a = this.pauseState) === null || _a === void 0 ? void 0 : _a.scope) === 'this-interaction';
188
- return Object.assign(Object.assign({ mode }, (this.pauseState ? { pause: this.pauseState } : {})), { status: selfPaused ? copy.selfPaused : mode === 'running' ? copy.running : copy.paused, needsUser: selfPaused || !!this.turnHandBack, working });
219
+ let status = copy.paused;
220
+ if (selfPaused)
221
+ status = copy.selfPaused;
222
+ else if (mode === 'running')
223
+ status = this.waitingOnUser() ? copy.waitingForUser : copy.running;
224
+ return Object.assign(Object.assign({ mode }, (this.pauseState ? { pause: this.pauseState } : {})), { status,
225
+ // Only the autopilot's own hand-backs: the badge says it stopped and needs the person, which
226
+ // a question it was never going to answer is not. `waitingOnUser` changes the status alone.
227
+ needsUser: selfPaused || !!this.turnHandBack, working });
228
+ }
229
+ /**
230
+ * Whether the working agent is parked on a question the person holds, with the autopilot deciding
231
+ * nothing: one it never took — its policy keeps it for the person, it is `userOnly` (the turn-level
232
+ * hand-back among them), it has no controller, or it opened while paused and no Resume has taken
233
+ * it since (a restored mode takes nothing) — or one another interceptor took and then gave to the
234
+ * person. One the autopilot handed back reads `selfPaused`, and one a pause handed over reads
235
+ * `paused`; `state` settles both before asking this.
236
+ *
237
+ * Never one that asks them nothing (see `asksThePerson`): the person holds it, but it is work
238
+ * running, which settles by itself, so "waiting for your answer" would be untrue. A hand-back is
239
+ * reported by the same rule (see `reportHandBackWhenAsking`).
240
+ */
241
+ waitingOnUser() {
242
+ const open = this.open;
243
+ if (!open || open.ctx.heldBy !== 'user' || this.answersInFlight > 0)
244
+ return false;
245
+ return asksThePerson(open);
189
246
  }
190
247
  get copy() {
191
248
  return this.copyFor(this.flowOwner());
@@ -232,25 +289,33 @@ export class AutopilotDriver extends BaseDriverDecorator {
232
289
  const held = this.held;
233
290
  if (held === null || held === void 0 ? void 0 : held.handedOver) {
234
291
  // Pausing handed it over, so take it back; a self-pause the person resumed means "decide it
235
- // yourself", so take it back without the option to hand it back again.
292
+ // yourself", so take it back without the option to hand it back again — unless, when the
293
+ // decision is sent, nothing on it can be done (every action unavailable), when handing it
294
+ // back is the only way out and stays open (see `AutopilotSession.decide`).
236
295
  held.handedOver = undefined;
237
296
  if (held.opened.hold.set('claimant')) {
238
297
  // Watched again, as when it was first claimed: the watchdog stops for good once it hands
239
298
  // an interaction back, and a decision that stalled once may well stall again.
240
299
  this.armWatchdog(held);
241
- this.decide(held, { allowHandBack: !wasSelfPaused });
300
+ // Decided once a decision is due, as when it was first claimed: a widget paused and resumed
301
+ // mid-work is not sent one until its work is done.
302
+ this.decideWhenReady(held, { allowHandBack: !wasSelfPaused });
242
303
  }
243
304
  }
244
- else if (!held && !this.turnHandBack && !this.inner.isBusy()) {
245
- // Resumed with the working agent idle — its turn ended waiting for the person — so carry it
246
- // on, or nothing would happen until they typed: answer the question it ended on, if it ended
247
- // on one nobody answered, or tell it to carry on. Only on a live Resume, never on a restore.
248
- const question = this.lastQuestion();
249
- if (question) {
250
- this.answerInBackground(owner, question);
251
- }
252
- else {
253
- void this.continueFromHistory([{ role: 'user', content: CARRY_ON_PRIMER }]);
305
+ else if (!held && !this.turnHandBack) {
306
+ // Nothing held, so carry the working agent on, or nothing would happen until the person did
307
+ // something. Only on a live Resume, never on a restore. Parked on a widget that opened while
308
+ // paused and is still the person's: take it and decide it, as if it had been claimed when it
309
+ // opened. Otherwise, if the working agent is idle — its turn ended waiting for the person —
310
+ // answer the question it ended on, if it ended on one nobody answered, or tell it to carry on.
311
+ if (!this.takeOpenOnResume(owner) && !this.inner.isBusy()) {
312
+ const question = this.lastQuestion();
313
+ if (question) {
314
+ this.answerInBackground(owner, question);
315
+ }
316
+ else {
317
+ void this.continueFromHistory([{ role: 'user', content: CARRY_ON_PRIMER }]);
318
+ }
254
319
  }
255
320
  }
256
321
  this.notify();
@@ -386,9 +451,16 @@ export class AutopilotDriver extends BaseDriverDecorator {
386
451
  onTurnEnded(result) {
387
452
  return __awaiter(this, void 0, void 0, function* () {
388
453
  const owner = this.flowOwner();
389
- // Nothing to do unless the autopilot is running for a flow that is still going.
390
- if (!owner || this.onFor !== owner || this.mode !== 'running' || this.pauseState)
454
+ // Nothing to do unless the autopilot is running for a flow that is still going, and is still
455
+ // available to it: availability can drop mid-turn, and the UI then shows it as off. Bailing
456
+ // needs no notify of its own — `afterTurn` notifies straight after this returns.
457
+ if (!owner ||
458
+ this.onFor !== owner ||
459
+ this.mode !== 'running' ||
460
+ this.pauseState ||
461
+ !this.isAvailable(owner)) {
391
462
  return;
463
+ }
392
464
  if (this.held || this.turnHandBack || this.inner.isBusy())
393
465
  return;
394
466
  const failure = result.reason === 'done' ? result.failureReason : undefined;
@@ -427,9 +499,9 @@ export class AutopilotDriver extends BaseDriverDecorator {
427
499
  *
428
500
  * Sent only if the question still stands when the answer lands: no pause or resume since it was
429
501
  * asked (Pause stops it, and the question is the person's to answer by typing), the flow still
430
- * running, the working agent idle, and the question still the last thing it said. Otherwise the
431
- * answer goes nowhere — not sent, not counted, not recorded as acted — and its cost is recorded as
432
- * dropped, as it is whenever no reply is sent to carry it.
502
+ * running and the autopilot still available to it, the working agent idle, and the question still
503
+ * the last thing it said. Otherwise the answer goes nowhere — not sent, not counted, not recorded
504
+ * as acted — and its cost is recorded as dropped, as it is whenever no reply is sent to carry it.
433
505
  */
434
506
  answer(owner, question) {
435
507
  return __awaiter(this, void 0, void 0, function* () {
@@ -443,6 +515,7 @@ export class AutopilotDriver extends BaseDriverDecorator {
443
515
  this.onFor === owner &&
444
516
  this.mode === 'running' &&
445
517
  !this.pauseState &&
518
+ this.isAvailable(owner) &&
446
519
  !this.inner.isBusy() &&
447
520
  this.lastQuestion() === question;
448
521
  this.answersInFlight += 1;
@@ -611,57 +684,227 @@ export class AutopilotDriver extends BaseDriverDecorator {
611
684
  // Claiming and deciding
612
685
  // -----------------------------------------------------------------------------------------------
613
686
  onInteractionOpened(opened) {
614
- var _a, _b;
615
- const decline = (reason) => {
616
- this.record('autopilot.declined', {
617
- interactionId: opened.interactionId,
618
- component: opened.componentName,
619
- reason,
620
- });
621
- // The run waits on the person now. Its own turn-level hand-back reports itself.
622
- if (HANDED_TO_PERSON.has(reason) && opened.componentName !== AUTOPILOT_HAND_BACK) {
623
- this.attention('autopilot-handed-back', opened.interactionId);
687
+ this.trackOpen(opened);
688
+ const owner = this.flowOwner();
689
+ if (!owner || this.onFor !== owner || this.mode !== 'running') {
690
+ // Still the autopilot's to take if the person resumes it while this is open (see `resume`).
691
+ this.declinedWhilePaused = opened;
692
+ return this.decline(opened, 'paused');
693
+ }
694
+ const verdict = this.eligibility(opened, owner);
695
+ if ('reason' in verdict)
696
+ return this.decline(opened, verdict.reason);
697
+ // The claim is granted only once this returns, so act on it after.
698
+ this.take(opened, verdict.agentName, { deferred: true });
699
+ return 'claim';
700
+ }
701
+ decline(opened, reason, extra = {}) {
702
+ this.record('autopilot.declined', Object.assign({ interactionId: opened.interactionId, component: opened.componentName, reason }, extra));
703
+ // The run waits on the person now, once the widget does. Its own turn-level hand-back reports
704
+ // itself.
705
+ if (HANDED_TO_PERSON.has(reason) && opened.componentName !== AUTOPILOT_HAND_BACK) {
706
+ this.reportHandBackWhenAsking(opened);
707
+ }
708
+ return undefined;
709
+ }
710
+ /**
711
+ * Report a widget the autopilot declined, and so left with the person, as a hand-back (GENC-1660)
712
+ * — but only once it waits on them: by the rule the status reads (`asksThePerson`), or because the
713
+ * widget asked for their attention. Then only if it still does, and is still theirs, after
714
+ * `HAND_BACK_GRACE_MS`, so one that settles itself as it mounts never reports. One that is working
715
+ * reports when it starts asking, with the message it asked with. One that settles first, or that
716
+ * another interceptor claims first, never reports: that claimant reports its own hand-back.
717
+ *
718
+ * The report is the interaction's one notification. The widget's own request is taken over
719
+ * (`hold.takeAttention`), so it is not reported as well, before or after: it only counts as the
720
+ * widget asking. When its request has already counted — reported while the person held it, before
721
+ * a decline on Resume — the person was told then, so nothing more is reported.
722
+ */
723
+ reportHandBackWhenAsking(opened) {
724
+ const { ctx, hold } = opened;
725
+ let asked = false;
726
+ let waiting = true;
727
+ let reported = false;
728
+ let grace;
729
+ let unsubscribe = () => undefined;
730
+ let release = () => undefined;
731
+ const stop = () => {
732
+ if (!waiting)
733
+ return;
734
+ waiting = false;
735
+ clearTimeout(grace);
736
+ unsubscribe();
737
+ this.handBackWaits.delete(stop);
738
+ // Not reported after all, so a request the widget makes from here is its own again.
739
+ if (!reported)
740
+ release();
741
+ };
742
+ const asks = () => asked || asksThePerson(opened);
743
+ const check = () => {
744
+ if (!waiting)
745
+ return;
746
+ if (ctx.heldBy !== 'user') {
747
+ stop();
748
+ return;
624
749
  }
625
- return undefined;
750
+ if (grace !== undefined || !asks())
751
+ return;
752
+ grace = setTimeout(() => {
753
+ grace = undefined;
754
+ if (!waiting)
755
+ return;
756
+ if (ctx.heldBy !== 'user') {
757
+ stop();
758
+ return;
759
+ }
760
+ // Back to work within the wait: report when it next asks.
761
+ if (!asks())
762
+ return;
763
+ reported = true;
764
+ stop();
765
+ this.attention('autopilot-handed-back', opened.interactionId, hold.attentionMessage());
766
+ }, HAND_BACK_GRACE_MS);
626
767
  };
627
- const owner = this.flowOwner();
628
- if (!owner || this.onFor !== owner || this.mode !== 'running')
629
- return decline('paused');
768
+ const taken = hold.takeAttention(() => {
769
+ asked = true;
770
+ check();
771
+ });
772
+ if (!taken)
773
+ return;
774
+ release = taken;
775
+ unsubscribe = ctx.subscribe(check);
776
+ ctx.onDispose(stop);
777
+ this.handBackWaits.add(stop);
778
+ check();
779
+ }
780
+ /**
781
+ * Whether the autopilot running for `owner` may take `opened`: the agent that answers for it, or
782
+ * why not, as `autopilot.declined` records it. The mode is the caller's to check — the open path
783
+ * asks this only while running, and a live Resume only for what opened while paused — so both ask
784
+ * the same questions in the same order.
785
+ */
786
+ eligibility(opened, owner) {
787
+ var _a, _b;
630
788
  if (opened.ownerPath[0] !== owner)
631
- return decline('other-flow');
789
+ return { reason: 'other-flow' };
632
790
  // The innermost agent on the path that declares an autopilot answers for it: sub-agents
633
791
  // inherit their flow's.
634
792
  const agentName = [...opened.ownerPath].reverse().find((name) => this.bindingFor(name));
635
793
  const binding = agentName ? this.bindingFor(agentName) : undefined;
636
794
  if (!agentName || !binding)
637
- return decline('no-autopilot');
795
+ return { reason: 'no-autopilot' };
638
796
  if (!this.isAvailable(owner))
639
- return decline('unavailable');
797
+ return { reason: 'unavailable' };
640
798
  if (opened.userOnly)
641
- return decline('userOnly');
799
+ return { reason: 'userOnly' };
642
800
  if (((_b = (_a = binding.config.widgetPolicy) === null || _a === void 0 ? void 0 : _a[opened.componentName]) !== null && _b !== void 0 ? _b : 'human-first') !== 'allowed') {
643
- return decline('policy');
801
+ return { reason: 'policy' };
644
802
  }
645
803
  if (opened.ctx.controller === undefined)
646
- return decline('no-controller');
804
+ return { reason: 'no-controller' };
805
+ return { agentName };
806
+ }
807
+ /**
808
+ * Hold an interaction the autopilot claimed, watch it, and decide it once its surface is ready.
809
+ * `deferred` when the claim is granted only after the caller returns (the open path), so the
810
+ * decision waits a microtask for it; a late claim through `hold.claim` is granted already.
811
+ *
812
+ * The decision starts only if the autopilot still holds it then, with no pause or resume in
813
+ * between: a pause hands it over, and the Resume after that decides it itself.
814
+ */
815
+ take(opened, agentName, how) {
647
816
  const held = { opened, agentName };
648
817
  this.held = held;
649
818
  opened.ctx.onDispose(() => this.onSettled(held));
650
- this.record('autopilot.claimed', {
651
- interactionId: opened.interactionId,
652
- component: opened.componentName,
653
- ownerPath: opened.ownerPath,
654
- });
819
+ this.record('autopilot.claimed', Object.assign({ interactionId: opened.interactionId, component: opened.componentName, ownerPath: opened.ownerPath }, (how.onResume ? { onResume: true } : {})));
655
820
  this.armWatchdog(held);
656
- // The claim is granted only once this returns, so act on it after.
821
+ const generation = this.generation;
822
+ const decideWhenReady = () => {
823
+ if (this.generation !== generation)
824
+ return;
825
+ this.decideWhenReady(held, { allowHandBack: true });
826
+ };
827
+ if (how.deferred)
828
+ queueMicrotask(decideWhenReady);
829
+ else
830
+ decideWhenReady();
831
+ }
832
+ /**
833
+ * Decide `held` once a decision is due on it (`onSurfaceReady`): at once if one is, or when its
834
+ * controller next makes one due — exposes a surface, enables an action, or says it is asking.
835
+ * Only if, by then, the autopilot still holds it with no pause or resume in between: a pause hands
836
+ * it over, and the Resume after that decides it itself.
837
+ */
838
+ decideWhenReady(held, options) {
839
+ const generation = this.generation;
840
+ held.opened.ctx.onSurfaceReady(() => {
841
+ if (this.held === held &&
842
+ this.generation === generation &&
843
+ held.opened.ctx.heldBy === AUTOPILOT_CLAIMANT) {
844
+ this.decide(held, options);
845
+ }
846
+ });
847
+ }
848
+ /**
849
+ * On a live Resume: take the open interaction if it was declined only because the autopilot was
850
+ * paused when it opened, and would be claimed if it opened now — the same checks as the open
851
+ * path. Returns whether it took it. A person may have started on it; it is taken as it stands, as
852
+ * Resume takes back one a pause handed over, and the autopilot reads it as it now is.
853
+ */
854
+ takeOpenOnResume(owner) {
855
+ const opened = this.open;
856
+ if (!opened || opened !== this.declinedWhilePaused || opened.ctx.heldBy !== 'user') {
857
+ return false;
858
+ }
859
+ this.declinedWhilePaused = undefined;
860
+ const verdict = this.eligibility(opened, owner);
861
+ if ('reason' in verdict) {
862
+ this.decline(opened, verdict.reason, { onResume: true });
863
+ return false;
864
+ }
865
+ // Refused only when another interceptor claimed it first, whoever holds it now.
866
+ if (!opened.hold.claim()) {
867
+ this.decline(opened, 'claimed-elsewhere', { onResume: true });
868
+ return false;
869
+ }
870
+ this.take(opened, verdict.agentName, { deferred: false, onResume: true });
871
+ return true;
872
+ }
873
+ /**
874
+ * Follow every interaction while it is open, claimed or not, so the status can say when the
875
+ * person is the one being waited on (see `waitingOnUser`), and tell the host each time that
876
+ * changes: when it opens, when it moves between holders, and when it settles.
877
+ */
878
+ trackOpen(opened) {
879
+ this.open = opened;
880
+ const { ctx } = opened;
881
+ // The context notifies on every change to the widget's own state too, so pass on only a change
882
+ // of holder, or of whether its controller says it is working: that is all the status reads.
883
+ let heldBy = ctx.heldBy;
884
+ let working = ctx.working;
885
+ const unsubscribe = ctx.subscribe(() => {
886
+ if (ctx.heldBy === heldBy && ctx.working === working)
887
+ return;
888
+ heldBy = ctx.heldBy;
889
+ working = ctx.working;
890
+ if (this.open === opened)
891
+ this.notify();
892
+ });
893
+ ctx.onDispose(() => {
894
+ unsubscribe();
895
+ if (this.declinedWhilePaused === opened)
896
+ this.declinedWhilePaused = undefined;
897
+ if (this.open !== opened)
898
+ return;
899
+ this.open = undefined;
900
+ this.notify();
901
+ });
902
+ // Once the claim, if any, has landed — interceptors are asked before the holder is settled — so
903
+ // the host reads who holds it as it now is.
657
904
  queueMicrotask(() => {
658
- opened.ctx.onSurfaceReady(() => {
659
- if (this.held === held && opened.ctx.heldBy === AUTOPILOT_CLAIMANT) {
660
- this.decide(held, { allowHandBack: true });
661
- }
662
- });
905
+ if (this.open === opened)
906
+ this.notify();
663
907
  });
664
- return 'claim';
665
908
  }
666
909
  /** Run one decision on the flow's session, and act on how it ended. */
667
910
  decide(held, options) {
@@ -670,7 +913,7 @@ export class AutopilotDriver extends BaseDriverDecorator {
670
913
  return;
671
914
  const key = this.stepKey(held);
672
915
  session
673
- .decide(held.opened, Object.assign(Object.assign({}, options), { allowReply: this.mayRefine(held, key), onReply: () => this.countRefinement(held, key) }))
916
+ .decide(held.opened, Object.assign(Object.assign({}, options), { refinementsLeft: () => this.refinementsLeft(held, key), onRefine: (action) => this.countRefinement(held, key, action) }))
674
917
  .then((outcome) => this.onDecided(held, outcome))
675
918
  .catch((e) => {
676
919
  logger.error('AutopilotDriver: a decision failed:', e);
@@ -695,14 +938,18 @@ export class AutopilotDriver extends BaseDriverDecorator {
695
938
  }
696
939
  return held.opened.componentName;
697
940
  }
698
- /** Whether a written answer is still allowed on this step. The count resets when the step changes. */
699
- mayRefine(held, key) {
941
+ /**
942
+ * How many refining actions (written answers, and full-form actions declared `refines`) are left
943
+ * on this step: none left withdraws them all. Read fresh, so a refinement taken mid-decision (a
944
+ * `refines` action that does not settle) counts at once. The count resets when the step changes.
945
+ */
946
+ refinementsLeft(held, key) {
700
947
  var _a;
701
948
  if (((_a = this.refinements) === null || _a === void 0 ? void 0 : _a.key) !== key)
702
949
  this.refinements = { key, count: 0 };
703
- return this.refinements.count < this.refinementLimit(held);
950
+ return Math.max(0, this.refinementLimit(held) - this.refinements.count);
704
951
  }
705
- countRefinement(held, key) {
952
+ countRefinement(held, key, action) {
706
953
  var _a;
707
954
  if (((_a = this.refinements) === null || _a === void 0 ? void 0 : _a.key) !== key)
708
955
  this.refinements = { key, count: 0 };
@@ -710,12 +957,13 @@ export class AutopilotDriver extends BaseDriverDecorator {
710
957
  const limit = this.refinementLimit(held);
711
958
  this.record('autopilot.refinement', {
712
959
  interactionId: held.opened.interactionId,
960
+ action,
713
961
  stepKey: key,
714
962
  count: this.refinements.count,
715
963
  limitReached: this.refinements.count >= limit,
716
964
  });
717
965
  }
718
- /** Written answers allowed per step: the config's when it is a whole number `>= 0`. */
966
+ /** Refinements allowed per step: the config's when it is a whole number `>= 0`. */
719
967
  refinementLimit(held) {
720
968
  var _a;
721
969
  const limit = (_a = this.bindingFor(held.agentName)) === null || _a === void 0 ? void 0 : _a.config.maxRefinements;
@@ -788,7 +1036,9 @@ export class AutopilotDriver extends BaseDriverDecorator {
788
1036
  trigger,
789
1037
  });
790
1038
  this.notify();
791
- this.attention('autopilot-handed-back', held.opened.interactionId);
1039
+ // The widget's own words, if it asked for the person while the autopilot held it (GENC-1660):
1040
+ // its request was held back then, so this is its one notification.
1041
+ this.attention('autopilot-handed-back', held.opened.interactionId, held.opened.hold.attentionMessage());
792
1042
  }
793
1043
  /**
794
1044
  * On detach: hand a claimed interaction the autopilot still holds to the person, stopping its
@@ -915,9 +1165,12 @@ export class AutopilotDriver extends BaseDriverDecorator {
915
1165
  record(type, detail) {
916
1166
  recordMetaEvent(this.sessionKey, type, detail);
917
1167
  }
918
- /** Report that something needs the person, for the assistant to notify them (GENC-1676). */
919
- attention(kind, interactionId) {
920
- this.activityBus.publish('agent-attention', Object.assign({ sessionKey: this.sessionKey, kind }, (interactionId ? { interactionId } : {})));
1168
+ /**
1169
+ * Report that something needs the person, for the assistant to notify them (GENC-1676), with the
1170
+ * widget's own message when it gave one (GENC-1660).
1171
+ */
1172
+ attention(kind, interactionId, message) {
1173
+ this.activityBus.publish('agent-attention', Object.assign(Object.assign({ sessionKey: this.sessionKey, kind }, (interactionId ? { interactionId } : {})), (message ? { message } : {})));
921
1174
  }
922
1175
  /**
923
1176
  * Report the autopilot stopping work on its own (GENC-1676): after running and working, nothing