@genesislcap/ai-assistant 15.82.0 → 15.84.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 (101) hide show
  1. package/dist/ai-assistant.api.json +2811 -233
  2. package/dist/ai-assistant.d.ts +835 -93
  3. package/dist/chat-driver.cjs +452 -99
  4. package/dist/chat-driver.cjs.map +4 -4
  5. package/dist/chat-driver.mjs +452 -99
  6. package/dist/chat-driver.mjs.map +4 -4
  7. package/dist/custom-elements.json +1903 -907
  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/ai-driver/ai-driver.d.ts +25 -6
  27. package/dist/dts/components/ai-driver/ai-driver.d.ts.map +1 -1
  28. package/dist/dts/components/ai-driver/base-driver-decorator.d.ts +2 -0
  29. package/dist/dts/components/ai-driver/base-driver-decorator.d.ts.map +1 -1
  30. package/dist/dts/components/chat-driver/chat-driver.d.ts +14 -2
  31. package/dist/dts/components/chat-driver/chat-driver.d.ts.map +1 -1
  32. package/dist/dts/components/chat-driver/interaction-controller.d.ts +61 -17
  33. package/dist/dts/components/chat-driver/interaction-controller.d.ts.map +1 -1
  34. package/dist/dts/config/config.d.ts +31 -6
  35. package/dist/dts/config/config.d.ts.map +1 -1
  36. package/dist/dts/config/define-stateful-agent.d.ts +5 -1
  37. package/dist/dts/config/define-stateful-agent.d.ts.map +1 -1
  38. package/dist/dts/genesis/write-outcome.d.ts.map +1 -1
  39. package/dist/dts/index.d.ts +4 -2
  40. package/dist/dts/index.d.ts.map +1 -1
  41. package/dist/dts/main/main.d.ts +11 -0
  42. package/dist/dts/main/main.d.ts.map +1 -1
  43. package/dist/dts/main/main.template.d.ts.map +1 -1
  44. package/dist/dts/notifications/agent-notifications.d.ts +6 -2
  45. package/dist/dts/notifications/agent-notifications.d.ts.map +1 -1
  46. package/dist/dts/notifications/agent-notifier.d.ts +26 -4
  47. package/dist/dts/notifications/agent-notifier.d.ts.map +1 -1
  48. package/dist/dts/state/decision-surface.d.ts +22 -4
  49. package/dist/dts/state/decision-surface.d.ts.map +1 -1
  50. package/dist/dts/state/interaction-context.d.ts +23 -4
  51. package/dist/dts/state/interaction-context.d.ts.map +1 -1
  52. package/dist/dts/state/interaction-registry.d.ts +55 -6
  53. package/dist/dts/state/interaction-registry.d.ts.map +1 -1
  54. package/dist/dts/state/live-interactions.d.ts +28 -0
  55. package/dist/dts/state/live-interactions.d.ts.map +1 -0
  56. package/dist/dts/state/persistence/session-persister.d.ts.map +1 -1
  57. package/dist/dts/state/persistence/session-snapshot.d.ts +16 -5
  58. package/dist/dts/state/persistence/session-snapshot.d.ts.map +1 -1
  59. package/dist/dts/state/test-interaction-context.d.ts +93 -0
  60. package/dist/dts/state/test-interaction-context.d.ts.map +1 -0
  61. package/dist/dts/types/ai-chat-widget.d.ts +7 -6
  62. package/dist/dts/types/ai-chat-widget.d.ts.map +1 -1
  63. package/dist/dts/types/interaction-context.d.ts +128 -17
  64. package/dist/dts/types/interaction-context.d.ts.map +1 -1
  65. package/dist/dts/types/interaction-interceptor.d.ts +48 -6
  66. package/dist/dts/types/interaction-interceptor.d.ts.map +1 -1
  67. package/dist/dts/types/interaction-surface.d.ts +145 -23
  68. package/dist/dts/types/interaction-surface.d.ts.map +1 -1
  69. package/dist/esm/autopilot/autopilot-driver.js +313 -60
  70. package/dist/esm/autopilot/autopilot-session.js +219 -40
  71. package/dist/esm/autopilot/autopilot-tools.js +11 -7
  72. package/dist/esm/autopilot/decision-message.js +105 -26
  73. package/dist/esm/autopilot/hand-back/hand-back.controller.js +2 -1
  74. package/dist/esm/autopilot/index.js +1 -0
  75. package/dist/esm/autopilot/widget-tools.js +39 -0
  76. package/dist/esm/components/ai-driver/base-driver-decorator.js +17 -0
  77. package/dist/esm/components/chat-driver/chat-driver.js +18 -2
  78. package/dist/esm/components/chat-driver/interaction-controller.js +232 -71
  79. package/dist/esm/components/settings-modal/settings-modal.template.js +2 -2
  80. package/dist/esm/config/define-stateful-agent.js +22 -1
  81. package/dist/esm/genesis/write-outcome.js +8 -4
  82. package/dist/esm/index.js +2 -0
  83. package/dist/esm/main/main.js +39 -3
  84. package/dist/esm/main/main.template.js +4 -1
  85. package/dist/esm/notifications/agent-notifications.js +11 -1
  86. package/dist/esm/notifications/agent-notifier.js +41 -7
  87. package/dist/esm/state/debug-event-log.js +5 -5
  88. package/dist/esm/state/decision-surface.js +137 -54
  89. package/dist/esm/state/interaction-context.js +41 -8
  90. package/dist/esm/state/interaction-registry.js +11 -0
  91. package/dist/esm/state/live-interactions.js +36 -0
  92. package/dist/esm/state/persistence/session-persister.js +44 -17
  93. package/dist/esm/state/persistence/session-snapshot.js +2 -2
  94. package/dist/esm/state/test-interaction-context.js +99 -0
  95. package/docs/notifications.md +55 -5
  96. package/docs/styling.md +33 -0
  97. package/package.json +19 -19
  98. package/sandbox/README.md +3 -2
  99. package/sandbox/autopilot.ts +26 -6
  100. package/sandbox/sandbox.ts +2 -0
  101. /package/dist/{tsdoc-metadata.json → dts/tsdoc-metadata.json} +0 -0
@@ -2,6 +2,7 @@ import { __awaiter } from "tslib";
2
2
  import { recordMetaEvent } from '../../state/debug-event-log';
3
3
  import { createInteractionContext, } from '../../state/interaction-context';
4
4
  import { getInteractionRegistration } from '../../state/interaction-registry';
5
+ import { trackInteractionContext } from '../../state/live-interactions';
5
6
  import { bindStepRecorder } from '../../state/run-steps';
6
7
  import { logger } from '../../utils/logger';
7
8
  /** The framing of a {@link DelegatedDecision} whose claimant declares none. */
@@ -64,6 +65,42 @@ function doneOnUsersBehalf(interaction, answeredBy) {
64
65
  }
65
66
  return {};
66
67
  }
68
+ /**
69
+ * The result as the requester receives it (GENC-1660): an object result carries `answeredBy`, the
70
+ * value stamped on the message, set by the platform alone — a widget's own is replaced, or removed
71
+ * when nobody answered. Copied, so the result stored on the message stays what the widget resolved
72
+ * with. Anything other than a plain object is passed through untouched.
73
+ */
74
+ function stampAnsweredBy(result, answeredBy) {
75
+ if (result === null || typeof result !== 'object' || Array.isArray(result))
76
+ return result;
77
+ const copy = Object.assign({}, result);
78
+ if (answeredBy)
79
+ copy.answeredBy = answeredBy;
80
+ else
81
+ delete copy.answeredBy;
82
+ return copy;
83
+ }
84
+ /**
85
+ * Who answered (GENC-1660), by the route the answer took, not by who held it: the claimant only
86
+ * when it settled through its hold, the person otherwise — so a click on a widget a claimant holds
87
+ * is still the person's answer. A timeout or a stop is nobody's, and so is a widget that settles by
88
+ * itself (`resolvesItself`), and so is one outcome its controller said settled itself
89
+ * (`ctx.resolve(result, { resolvedItself: true })`, for a widget that at other times asks): it asked
90
+ * nothing, so crediting the person would tell the agent and the autopilot they decided something
91
+ * they were never asked. A person's interrupt (a Skip) reaches here the same way as the widget
92
+ * finishing, so the two cannot be told apart; such a widget says which in its own result.
93
+ */
94
+ function whoAnswered(interaction, result, how) {
95
+ var _a;
96
+ const unanswered = (result === null || result === void 0 ? void 0 : result.status) === 'timeout';
97
+ const resolvedItself = !unanswered &&
98
+ !interaction.settledBy &&
99
+ (!!interaction.resolvesItself || (how === null || how === void 0 ? void 0 : how.resolvedItself) === true);
100
+ if (unanswered || resolvedItself)
101
+ return { resolvedItself };
102
+ return { answeredBy: (_a = interaction.settledBy) !== null && _a !== void 0 ? _a : 'user', resolvedItself };
103
+ }
67
104
  /** What an interaction closed by its `signal` resolves with: unanswered, like a timeout. */
68
105
  const STOPPED = {
69
106
  status: 'timeout',
@@ -94,55 +131,118 @@ export class InteractionController {
94
131
  * the root's are ever consulted: a sub-agent's request is opened by the root.
95
132
  */
96
133
  this.interceptors = [];
134
+ /**
135
+ * Checkpoints a reload cut, oldest first, each waiting for a request of its own widget type that
136
+ * `sameWork` agrees is the same work. Held apart from `live`, so neither the work a resumed flow
137
+ * does first nor a request `sameWork` refuses can lose one: a flow may open other long widgets
138
+ * before the one a checkpoint belongs to asks for it. Each leaves when it is taken over, and all
139
+ * of them when the flow ends.
140
+ */
141
+ this.cut = [];
97
142
  }
98
- /** See `ChatDriver.getInteractionCheckpoint`. */
143
+ /**
144
+ * See `ChatDriver.getInteractionCheckpoints`: every checkpoint to save with the session — those a
145
+ * reload cut that nothing has taken yet, oldest first, then the live interaction's. A reload cuts
146
+ * them all, so all of them are restored as cut.
147
+ */
148
+ getCheckpoints() {
149
+ const live = this.live;
150
+ return [
151
+ ...this.cut.map(({ componentName, value }) => ({ componentName, value })),
152
+ ...(live ? [{ componentName: live.componentName, value: live.value }] : []),
153
+ ];
154
+ }
155
+ /**
156
+ * See `ChatDriver.getInteractionCheckpoint` (deprecated): one checkpoint, the live interaction's,
157
+ * else the newest a reload cut.
158
+ */
99
159
  getCheckpoint() {
100
- const cp = this.checkpoint;
101
- return cp ? { componentName: cp.componentName, value: cp.value } : undefined;
160
+ const all = this.getCheckpoints();
161
+ return all[all.length - 1];
102
162
  }
103
- /** See `ChatDriver.restoreInteractionCheckpoint`. Restored means cut: its interaction is gone. */
163
+ /**
164
+ * See `ChatDriver.restoreInteractionCheckpoints`. Restored means cut: their interactions are gone.
165
+ * Replaces whatever was held.
166
+ */
167
+ restoreCheckpoints(saved) {
168
+ this.live = undefined;
169
+ this.cut = (saved !== null && saved !== void 0 ? saved : []).map(({ componentName, value }) => ({ componentName, value }));
170
+ }
171
+ /** See `ChatDriver.restoreInteractionCheckpoint` (deprecated): one, or none. */
104
172
  restoreCheckpoint(saved) {
105
- this.checkpoint = saved
106
- ? { componentName: saved.componentName, value: saved.value, cut: true }
107
- : undefined;
173
+ this.restoreCheckpoints(saved ? [saved] : []);
108
174
  }
109
- /** Drop the checkpoint, used or not, when its flow ends. */
175
+ /** Drop every checkpoint, used or not, cut or live, when its flow ends. */
110
176
  clearCheckpoint(why) {
111
- const cp = this.checkpoint;
112
- if (!cp)
113
- return;
114
- this.checkpoint = undefined;
115
- recordMetaEvent(this.deps.sessionKey, 'interaction.checkpoint', Object.assign({ action: 'cleared', component: cp.componentName, why }, (cp.interactionId ? { interactionId: cp.interactionId } : {})));
177
+ const live = this.live;
178
+ const cut = this.cut;
179
+ this.live = undefined;
180
+ this.cut = [];
181
+ for (const cp of cut) {
182
+ recordMetaEvent(this.deps.sessionKey, 'interaction.checkpoint', {
183
+ action: 'cleared',
184
+ component: cp.componentName,
185
+ why,
186
+ cut: true,
187
+ });
188
+ }
189
+ if (live) {
190
+ recordMetaEvent(this.deps.sessionKey, 'interaction.checkpoint', {
191
+ action: 'cleared',
192
+ component: live.componentName,
193
+ why,
194
+ interactionId: live.interactionId,
195
+ });
196
+ }
116
197
  }
117
198
  /**
118
- * Hand a cut checkpoint to a new request of the same widget type, if its registration's
119
- * `sameWork` agrees. Only the first such request is asked: a refused checkpoint is dropped, and
120
- * the work starts fresh as it would have without one.
199
+ * Offer the checkpoints a reload cut to a new request of their widget type, newest first, and
200
+ * hand it the first its registration's `sameWork` agrees is the same work (any, without one). A
201
+ * checkpoint `sameWork` refuses stays where it is, for a later request of the same type: a flow
202
+ * may ask for other work of that type first. Each refusal is recorded, with the identity kept.
121
203
  */
122
204
  takeOverCheckpoint(componentName, data, interactionId) {
123
205
  var _a;
124
- const cut = this.checkpoint;
125
- if (!(cut === null || cut === void 0 ? void 0 : cut.cut) || cut.componentName !== componentName)
126
- return undefined;
127
- this.checkpoint = undefined;
128
206
  const sameWork = (_a = getInteractionRegistration(componentName)) === null || _a === void 0 ? void 0 : _a.sameWork;
129
- let agrees = true;
130
- if (sameWork) {
131
- try {
132
- agrees = sameWork(cut.value, data);
207
+ for (let i = this.cut.length - 1; i >= 0; i -= 1) {
208
+ const cut = this.cut[i];
209
+ if (cut.componentName !== componentName)
210
+ continue;
211
+ let agrees = true;
212
+ if (sameWork) {
213
+ try {
214
+ agrees = sameWork(cut.value, data);
215
+ }
216
+ catch (e) {
217
+ logger.warn(`InteractionController: "${componentName}" sameWork threw; not taking it over:`, e);
218
+ agrees = false;
219
+ }
133
220
  }
134
- catch (e) {
135
- logger.warn(`InteractionController: "${componentName}" sameWork threw; starting fresh:`, e);
136
- agrees = false;
221
+ if (!agrees) {
222
+ recordMetaEvent(this.deps.sessionKey, 'interaction.checkpoint', {
223
+ action: 'refused',
224
+ component: componentName,
225
+ interactionId,
226
+ saved: cut.value,
227
+ kept: true,
228
+ });
229
+ continue;
137
230
  }
231
+ this.cut.splice(i, 1);
232
+ recordMetaEvent(this.deps.sessionKey, 'interaction.checkpoint', {
233
+ action: 'resumed',
234
+ component: componentName,
235
+ interactionId,
236
+ });
237
+ this.live = { componentName, value: cut.value, interactionId };
238
+ return cut.value;
138
239
  }
139
- recordMetaEvent(this.deps.sessionKey, 'interaction.checkpoint', Object.assign({ action: agrees ? 'resumed' : 'refused', component: componentName, interactionId }, (agrees ? {} : { saved: cut.value })));
140
- if (!agrees)
141
- return undefined;
142
- this.checkpoint = { componentName, value: cut.value, interactionId };
143
- return cut.value;
240
+ return undefined;
144
241
  }
145
- /** A controller's `ctx.saveCheckpoint`: kept as JSON, the form it is persisted in. */
242
+ /**
243
+ * A controller's `ctx.saveCheckpoint`: kept as JSON, the form it is persisted in. Replaces the
244
+ * live interaction's only; the checkpoints a reload cut are left waiting for their own widgets.
245
+ */
146
246
  saveCheckpoint(interactionId, componentName, value) {
147
247
  var _a;
148
248
  if (!this.pending.has(interactionId))
@@ -155,7 +255,7 @@ export class InteractionController {
155
255
  logger.warn(`InteractionController: a "${componentName}" checkpoint is not storable as JSON:`, e);
156
256
  return;
157
257
  }
158
- this.checkpoint = { componentName, value: copy, interactionId };
258
+ this.live = { componentName, value: copy, interactionId };
159
259
  // A finished step changes no message, so autosave would not see it: ask for a save.
160
260
  this.deps.emit(new CustomEvent('checkpoint-saved', { detail: { interactionId } }));
161
261
  }
@@ -182,11 +282,32 @@ export class InteractionController {
182
282
  *
183
283
  * Runs before the interaction's message is appended, so the widget's first render already knows
184
284
  * its holder and nothing appears only to disappear.
285
+ *
286
+ * **A late claim.** An interceptor that declined may still claim it later, through its hold's
287
+ * `claim`, once the asking is over and while nobody else has (see {@link InteractionHold.claim}).
185
288
  */
186
289
  offer(handle, opened) {
187
290
  let claimant;
291
+ let asking = true;
292
+ const claimLate = (interceptor) => {
293
+ // A claim at open is made by returning 'claim', and there is one claim per interaction, ever.
294
+ if (asking || claimant || opened.userOnly)
295
+ return false;
296
+ const pending = this.pending.get(opened.interactionId);
297
+ if (!pending || !handle.setHeldBy(interceptor.id))
298
+ return false;
299
+ claimant = interceptor;
300
+ pending.claimant = interceptor;
301
+ recordMetaEvent(this.deps.sessionKey, 'interaction.held', {
302
+ interactionId: opened.interactionId,
303
+ heldBy: interceptor.id,
304
+ claimant: interceptor.id,
305
+ late: true,
306
+ });
307
+ return true;
308
+ };
188
309
  for (const interceptor of [...this.interceptors].reverse()) {
189
- const hold = this.holdFor(handle, interceptor, () => claimant === interceptor);
310
+ const hold = this.holdFor(handle, interceptor, () => claimant === interceptor, () => claimLate(interceptor));
190
311
  let answer;
191
312
  try {
192
313
  answer = interceptor.onInteractionOpened(Object.assign(Object.assign({}, opened), { ctx: handle.context, hold }));
@@ -211,11 +332,41 @@ export class InteractionController {
211
332
  if (pending)
212
333
  pending.claimant = interceptor;
213
334
  }
335
+ asking = false;
214
336
  return handle.context.heldBy;
215
337
  }
216
- /** The {@link InteractionHold} for one interceptor: it applies only while that one is the claimant. */
217
- holdFor(handle, interceptor, isClaimant) {
338
+ /**
339
+ * Publish `agent-attention-ended` each time the interaction stops waiting on the person — a
340
+ * claimant takes it, or it settles — so a notification still showing for it is closed
341
+ * (GENC-1660). Wired once who holds it is decided, so a claim made as it opens is not one.
342
+ */
343
+ reportAttentionEnds(ctx) {
344
+ const ended = () => this.deps.activityBus.publish('agent-attention-ended', {
345
+ sessionKey: this.deps.sessionKey,
346
+ interactionId: ctx.interactionId,
347
+ });
348
+ let heldBy = ctx.heldBy;
349
+ const unsubscribe = ctx.subscribe(() => {
350
+ if (ctx.heldBy === heldBy)
351
+ return;
352
+ heldBy = ctx.heldBy;
353
+ if (heldBy !== 'user')
354
+ ended();
355
+ });
356
+ ctx.onDispose(() => {
357
+ unsubscribe();
358
+ ended();
359
+ });
360
+ }
361
+ /**
362
+ * The {@link InteractionHold} for one interceptor: it applies only while that one is the claimant,
363
+ * which `claim` can make it after the asking, if nobody else is.
364
+ */
365
+ holdFor(handle, interceptor, isClaimant, claim) {
218
366
  return {
367
+ claim,
368
+ attentionMessage: () => handle.attentionMessage,
369
+ takeAttention: (onRequest) => handle.takeAttention(onRequest),
219
370
  set: (holder) => {
220
371
  var _a;
221
372
  if (!isClaimant())
@@ -394,11 +545,12 @@ export class InteractionController {
394
545
  const timeoutMs = options === null || options === void 0 ? void 0 : options.timeoutMs;
395
546
  const presentation = options === null || options === void 0 ? void 0 : options.presentation;
396
547
  return new Promise((resolve, reject) => {
397
- this.pending.set(interactionId, {
398
- resolve,
548
+ var _a;
549
+ this.pending.set(interactionId, Object.assign(Object.assign({ resolve,
399
550
  reject,
400
- onSettled,
401
- overrideId: chatInputDuringExecution ? interactionId : undefined,
551
+ onSettled, overrideId: chatInputDuringExecution ? interactionId : undefined }, (((_a = getInteractionRegistration(componentName)) === null || _a === void 0 ? void 0 : _a.resolvesItself) === true && {
552
+ resolvesItself: true,
553
+ })), {
402
554
  // Resolve the interaction with a timeout result if the user does not
403
555
  // respond in time. `resolve` runs the same teardown a normal resolution
404
556
  // does (marks the widget read-only, reverts any input override) and
@@ -410,8 +562,7 @@ export class InteractionController {
410
562
  message: `Interaction timed out after ${timeoutMs}ms.`,
411
563
  });
412
564
  }, timeoutMs)
413
- : undefined,
414
- });
565
+ : undefined }));
415
566
  // Create the live context (GENC-1390) BEFORE the widget can mount, so the
416
567
  // wrapper finds it when it builds the pending `interaction` descriptor, and
417
568
  // offer it to the interceptors (GENC-1660) before it is appended, so the
@@ -421,12 +572,15 @@ export class InteractionController {
421
572
  // which `resolve` holds back until there is a message to patch.
422
573
  const handle = createInteractionContext(interactionId, {
423
574
  sessionKey: this.deps.sessionKey,
424
- resolve: (result) => this.resolve(interactionId, result),
575
+ resolve: (result, how) => this.resolve(interactionId, result, how),
425
576
  checkpoint: this.takeOverCheckpoint(componentName, data, interactionId),
426
577
  saveCheckpoint: (value) => this.saveCheckpoint(interactionId, componentName, value),
427
578
  requestAttention: (message) => this.deps.activityBus.publish('agent-attention', Object.assign({ sessionKey: this.deps.sessionKey, kind: 'widget-needs-input', interactionId }, (message ? { message } : {}))),
428
579
  });
429
580
  this.contexts.set(interactionId, handle);
581
+ // Findable by id (`getInteractionContext`) for UI the chat does not render, such as a side
582
+ // panel, until it is disposed.
583
+ handle.context.onDispose(trackInteractionContext(handle.context));
430
584
  bindStepRecorder(handle.context, (step, outcome) => recordMetaEvent(this.deps.sessionKey, 'interaction.step', {
431
585
  interactionId,
432
586
  component: componentName,
@@ -461,6 +615,8 @@ export class InteractionController {
461
615
  // Who holds it is decided: a `requestAttention` the controller made while being built can
462
616
  // now report, or be dropped if a claimant holds it (GENC-1676).
463
617
  handle.markOffered();
618
+ // From here a notification may be shown for it, so say when that goes stale (GENC-1660).
619
+ this.reportAttentionEnds(handle.context);
464
620
  recordMetaEvent(this.deps.sessionKey, 'interaction.requested', Object.assign({ interactionId, component: componentName, agent: this.deps.activeAgentName(), ownerPath,
465
621
  heldBy }, ((options === null || options === void 0 ? void 0 : options.userOnly) ? { userOnly: true } : {})));
466
622
  // Signal the park boundary on the activity bus so turn-aware UI can tell
@@ -486,7 +642,7 @@ export class InteractionController {
486
642
  if (opened) {
487
643
  opened.appended = true;
488
644
  if (opened.early)
489
- this.resolve(interactionId, opened.early.result);
645
+ this.resolve(interactionId, opened.early.result, opened.early.options);
490
646
  }
491
647
  // Closed by the caller's signal the way a timeout closes it: read-only, unanswered, and
492
648
  // through the same teardown. Wired after the widget is in history, so a signal that has
@@ -509,10 +665,11 @@ export class InteractionController {
509
665
  }
510
666
  /**
511
667
  * See `ChatDriver.resolveInteraction`. Warns and returns when the id is unknown — a widget can
512
- * report twice, and the second report has nothing left to settle.
668
+ * report twice, and the second report has nothing left to settle. `how` is what a controller's
669
+ * `ctx.resolve` said about the settle (`resolvedItself`); every other route passes none.
513
670
  */
514
- resolve(interactionId, result) {
515
- var _a, _b, _c, _d, _e, _f, _g;
671
+ resolve(interactionId, result, how) {
672
+ var _a, _b, _c, _d, _e, _f;
516
673
  const interaction = this.pending.get(interactionId);
517
674
  if (!interaction) {
518
675
  logger.warn(`Interaction with ID ${interactionId} not found.`);
@@ -522,7 +679,7 @@ export class InteractionController {
522
679
  // message, and the append that follows would leave a widget pending forever, so hold it until
523
680
  // the message is there. First answer wins, as it would have.
524
681
  if (!interaction.appended) {
525
- (_a = interaction.early) !== null && _a !== void 0 ? _a : (interaction.early = { result });
682
+ (_a = interaction.early) !== null && _a !== void 0 ? _a : (interaction.early = { result, options: how });
526
683
  return;
527
684
  }
528
685
  // Clear the timeout so a user resolution doesn't later fire a stale
@@ -540,11 +697,7 @@ export class InteractionController {
540
697
  const costUsd = typeof (result === null || result === void 0 ? void 0 : result.costUsd) === 'number' && Number.isFinite(result.costUsd) && result.costUsd > 0
541
698
  ? result.costUsd
542
699
  : undefined;
543
- // Who answered (GENC-1660), by the route the answer took, not by who held it: the claimant
544
- // only when it settled through its hold, the person otherwise — so a click on a widget a
545
- // claimant holds is still the person's answer. A timeout or a stop is nobody's.
546
- const unanswered = (result === null || result === void 0 ? void 0 : result.status) === 'timeout';
547
- const answeredBy = unanswered ? undefined : ((_c = interaction.settledBy) !== null && _c !== void 0 ? _c : 'user');
700
+ const { answeredBy, resolvedItself } = whoAnswered(interaction, result, how);
548
701
  // Settled under a claimant's `hold.invoke` run, credited to it: that run's note goes first, so
549
702
  // it precedes the outcome, and the run learns that it was the one that finished it.
550
703
  const run = answeredBy && answeredBy !== 'user' ? interaction.running : undefined;
@@ -553,11 +706,11 @@ export class InteractionController {
553
706
  if (run.note)
554
707
  this.appendNote(run.note);
555
708
  }
556
- const edits = ((_d = interaction.edits) === null || _d === void 0 ? void 0 : _d.length) ? interaction.edits : undefined;
709
+ const edits = ((_c = interaction.edits) === null || _c === void 0 ? void 0 : _c.length) ? interaction.edits : undefined;
557
710
  const { decision, edited } = doneOnUsersBehalf(interaction, answeredBy);
558
711
  const patched = this.deps.patchInteractionMessage(interactionId, (message) => {
559
712
  var _a;
560
- return (Object.assign(Object.assign(Object.assign({}, message), { interaction: Object.assign(Object.assign(Object.assign(Object.assign({}, message.interaction), { resolved: result }), (answeredBy ? { answeredBy } : {})), (edits ? { edits } : {})) }), (costUsd != null ? { externalCostUsd: ((_a = message.externalCostUsd) !== null && _a !== void 0 ? _a : 0) + costUsd } : {})));
713
+ return (Object.assign(Object.assign(Object.assign({}, message), { interaction: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, message.interaction), { resolved: result }), (answeredBy ? { answeredBy } : {})), (resolvedItself ? { resolvedItself } : {})), (edits ? { edits } : {})) }), (costUsd != null ? { externalCostUsd: ((_a = message.externalCostUsd) !== null && _a !== void 0 ? _a : 0) + costUsd } : {})));
561
714
  });
562
715
  if (patched)
563
716
  this.deps.notifyHistoryUpdated();
@@ -569,30 +722,37 @@ export class InteractionController {
569
722
  // Appended before `interaction.resolve` so it precedes the tool result and
570
723
  // any follow-up turn the resumed handler produces.
571
724
  //
572
- // When a claimant answered (GENC-1660), the echo is not something the user said: it is kept
573
- // as a delegated, display-only assistant message, so it renders on the assistant's side and
574
- // never as a user bubble the user did not write.
725
+ // Never as the person's words when a claimant settled it (GENC-1660): they never said them. So
726
+ // a widget can set `userMessage` on every path, a claimant's included, without branching on who
727
+ // is answering. A claimant's run with a note shows only the note, appended above: it already
728
+ // told the person what was chosen and why. Without a note the echo is kept, as a delegated,
729
+ // display-only assistant message, so the person always sees what was chosen for them; a widget
730
+ // whose resolved card leaves the answer to the echo (`planning-question`) would otherwise show
731
+ // no answer at all.
575
732
  if (typeof (result === null || result === void 0 ? void 0 : result.userMessage) === 'string' && result.userMessage.trim()) {
576
- this.deps.appendToHistory(answeredBy && answeredBy !== 'user'
577
- ? {
733
+ if (!answeredBy || answeredBy === 'user') {
734
+ this.deps.appendToHistory({ role: 'synthetic-user', content: result.userMessage });
735
+ }
736
+ else if (!(run === null || run === void 0 ? void 0 : run.note)) {
737
+ this.deps.appendToHistory({
578
738
  role: 'assistant',
579
739
  content: result.userMessage,
580
740
  delegate: answeredBy,
581
741
  excludeFromProvider: true,
582
- }
583
- : { role: 'synthetic-user', content: result.userMessage });
742
+ });
743
+ }
584
744
  }
585
745
  if (interaction.overrideId) {
586
746
  this.deps.emit(new CustomEvent('interaction-stop', { detail: { interactionId } }));
587
747
  }
588
- recordMetaEvent(this.deps.sessionKey, 'interaction.resolved', Object.assign(Object.assign({ interactionId }, (answeredBy ? { answeredBy } : {})), (edits ? { edits: edits.length } : {})));
748
+ recordMetaEvent(this.deps.sessionKey, 'interaction.resolved', Object.assign(Object.assign(Object.assign({ interactionId }, (answeredBy ? { answeredBy } : {})), (resolvedItself ? { resolvedItself } : {})), (edits ? { edits: edits.length } : {})));
589
749
  // The park is ending and the loop is about to resume computing — paired
590
750
  // with `interaction-requested`. Fires for every resolution path (user
591
751
  // completion, timeout, cancellation), since all route through here.
592
752
  this.deps.activityBus.publish('interaction-resolved', undefined);
593
753
  // Before the promise settles, so the record is in place when the handler carries on.
594
754
  try {
595
- (_e = interaction.onSettled) === null || _e === void 0 ? void 0 : _e.call(interaction, Object.assign({ answeredBy, decision }, (edited ? { edited } : {})));
755
+ (_d = interaction.onSettled) === null || _d === void 0 ? void 0 : _d.call(interaction, Object.assign(Object.assign(Object.assign({ answeredBy }, (resolvedItself ? { resolvedItself } : {})), { decision }), (edited ? { edited } : {})));
596
756
  }
597
757
  catch (e) {
598
758
  logger.warn('InteractionController: onSettled threw:', e);
@@ -601,16 +761,17 @@ export class InteractionController {
601
761
  // never passes through the host's `interaction-completed` handler, which is where it started
602
762
  // its loading indicator.
603
763
  this.deps.emit(new CustomEvent('interaction-settled', {
604
- detail: Object.assign({ interactionId }, (answeredBy ? { answeredBy } : {})),
764
+ detail: Object.assign(Object.assign({ interactionId }, (answeredBy ? { answeredBy } : {})), (resolvedItself ? { resolvedItself } : {})),
605
765
  }));
606
- interaction.resolve(result);
766
+ interaction.resolve(stampAnsweredBy(result, answeredBy));
607
767
  this.pending.delete(interactionId);
608
- // Settled, so its work is finished with: nothing is left to resume.
609
- if (((_f = this.checkpoint) === null || _f === void 0 ? void 0 : _f.interactionId) === interactionId)
610
- this.checkpoint = undefined;
768
+ // Settled, so its work is finished with: nothing is left to resume. Cut checkpoints still
769
+ // waiting for their own widgets are not this one's, and stay.
770
+ if (((_e = this.live) === null || _e === void 0 ? void 0 : _e.interactionId) === interactionId)
771
+ this.live = undefined;
611
772
  // Tear down the live context on RESOLVE (not on element unmount) — this closes
612
773
  // any sockets/timers the widget parked on it via `onDispose`. (GENC-1390)
613
- (_g = this.contexts.get(interactionId)) === null || _g === void 0 ? void 0 : _g.dispose();
774
+ (_f = this.contexts.get(interactionId)) === null || _f === void 0 ? void 0 : _f.dispose();
614
775
  this.contexts.delete(interactionId);
615
776
  }
616
777
  /**
@@ -339,8 +339,8 @@ const chatBotSettingsTemplate = (switchTag, buttonTag, segmentedControlTag, segm
339
339
  }))}
340
340
  ${settingsToggleRow('Show timestamps', 'Show when each message was sent, next to the sender name. Screen readers announce the full date in either visible mode.', 'toggle-timestamps', timestampModePickerTemplate(segmentedControlTag, segmentedItemTag))}
341
341
  ${when((x) => x.notificationSettingVisible, settingsToggleRow('Notify me when the assistant needs me', (x) => x.notificationAutopilotOffered
342
- ? 'A browser notification while this tab is in the background. Autopilot notifies only when the autopilot hands back to you or stops.'
343
- : 'A browser notification while this tab is in the background.', 'toggle-notifications', notificationLevelPickerTemplate(segmentedControlTag, segmentedItemTag), 'row', (x) => x.notificationPermissionHint))}
342
+ ? 'A browser notification while this tab is in the background. Autopilot notifies only when the autopilot hands back to you or stops. Always also notifies when the assistant is waiting for your reply.'
343
+ : 'A browser notification while this tab is in the background, when the assistant is waiting for your reply.', 'toggle-notifications', notificationLevelPickerTemplate(segmentedControlTag, segmentedItemTag), 'row', (x) => x.notificationPermissionHint))}
344
344
  ${when((x) => x.persistenceToggleable, chatBotToggleRow('Remember chat', 'Save this conversation so it can be restored after a page refresh. Turning this off deletes the saved copy.', switchTag, 'toggle-remember-chat', (x) => x.persistenceActive, (x, c) => {
345
345
  x.setPersistenceEnabled(readSwitchChecked(c.event));
346
346
  }))}
@@ -1,4 +1,5 @@
1
1
  import { __awaiter, __rest } from "tslib";
2
+ import { AUTOPILOT_TOOL_DEFINITIONS } from '../autopilot/autopilot-tools';
2
3
  import { TOOL_FOLD_SYMBOL } from '../utils/tool-fold';
3
4
  /**
4
5
  * Walk a state object and snapshot any machine-shaped values found on it.
@@ -310,14 +311,34 @@ export function defineStatefulAgent(opts) {
310
311
  * …,
311
312
  * autopilot: defineAutopilot<BootstrapState>({
312
313
  * availableWhen: ({ state }) => briefApproved(state.machine),
313
- * widgetPolicy: { 'planning-question': 'allowed' },
314
+ * widgetPolicy: { 'planning-question': 'allowed', 'sample-data-review': 'allowed' },
315
+ * widgetTools: [SAMPLE_DATA_TOOLS],
314
316
  * systemPrompt: ({ state }) => `${AUTOPILOT_BASE}\n<brief>${frozenBrief(state)}</brief>`,
315
317
  * }),
316
318
  * });
317
319
  * ```
318
320
  *
321
+ * Throws if two of its tools share a name — its widget tools, its own `tools` and the platform's
322
+ * fixed three — since one would silently shadow the other.
323
+ *
319
324
  * @beta
320
325
  */
321
326
  export function defineAutopilot(config) {
327
+ var _a, _b, _c;
328
+ const seen = new Set(AUTOPILOT_TOOL_DEFINITIONS.map((d) => d.name));
329
+ for (const d of (_b = (_a = config.tools) === null || _a === void 0 ? void 0 : _a.definitions) !== null && _b !== void 0 ? _b : []) {
330
+ if (seen.has(d.name)) {
331
+ throw new Error(`defineAutopilot: the tool "${d.name}" is named twice.`);
332
+ }
333
+ seen.add(d.name);
334
+ }
335
+ for (const set of (_c = config.widgetTools) !== null && _c !== void 0 ? _c : []) {
336
+ for (const name of Object.keys(set.tools)) {
337
+ if (seen.has(name)) {
338
+ throw new Error(`defineAutopilot: the widget tool "${name}" (for "${set.componentName}") is named twice.`);
339
+ }
340
+ seen.add(name);
341
+ }
342
+ }
322
343
  return config;
323
344
  }
@@ -8,7 +8,13 @@ import { readsRow } from './write-op';
8
8
  * service", "STATUS_CODE": "404 Not Found"}`.
9
9
  */
10
10
  const NOT_MAPPED = 404;
11
- const isNotMapped = (error) => { var _a; return error.CODE === NOT_MAPPED || String((_a = error.STATUS_CODE) !== null && _a !== void 0 ? _a : '').startsWith(String(NOT_MAPPED)); };
11
+ const isNotMapped = (error) => {
12
+ var _a;
13
+ return String(error.CODE) === String(NOT_MAPPED) ||
14
+ String((_a = error.STATUS_CODE) !== null && _a !== void 0 ? _a : '').startsWith(String(NOT_MAPPED));
15
+ };
16
+ // The router's own statuses: numbers on the wire, digit strings once comms has normalised them.
17
+ const isStatusCode = (code) => /^\d+$/.test(String(code !== null && code !== void 0 ? code : ''));
12
18
  /**
13
19
  * A server error's own words, when they can be shown.
14
20
  *
@@ -232,9 +238,7 @@ export function mapWriteReply(reply, { mode, op }) {
232
238
  if (errors.some(isNotMapped)) {
233
239
  return Object.assign(Object.assign({ status: 'unavailable' }, withFields), { message: `Not available: ${joined(errors)}` });
234
240
  }
235
- const numeric = [
236
- ...new Set(errors.map((error) => error.CODE).filter((code) => typeof code === 'number')),
237
- ];
241
+ const numeric = [...new Set(errors.map((error) => error.CODE).filter(isStatusCode))];
238
242
  return Object.assign(Object.assign({}, writeOutcomeUnknown(`The app answered ${namedType !== null && namedType !== void 0 ? namedType : 'with a failure'}${numeric.length ? ` with code ${numeric.join(', ')}` : ''}, which does not say whether this was written, so whether this was written is unknown.`)), (warnings ? { warnings } : {}));
239
243
  }
240
244
  // Everything from here is an EVENT_NACK: the HANDLER's own answer. It is read as "not written"
package/dist/esm/index.js CHANGED
@@ -22,6 +22,8 @@ export * from './provider/assistant-app-settings';
22
22
  export * from './utils/tool-fold';
23
23
  export { DEFAULT_DELEGATE_FRAMING, isDelegated, } from './utils/delegated-message';
24
24
  export { assistantSettingsSectionTitleStyles } from './styles/settings-section';
25
+ export { getInteractionContext } from './state/live-interactions';
26
+ export { createTestInteractionContext, } from './state/test-interaction-context';
25
27
  export { runSteps } from './state/run-steps';
26
28
  export { getInteractionRegistration, registerInteraction, } from './state/interaction-registry';
27
29
  // MARKDOWN_EXPORTPARTS travels with the component: a host rendering `<ai-chat-markdown>` in its
@@ -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
  };
@@ -2316,10 +2324,11 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
2316
2324
  };
2317
2325
  // An interaction answered by any route — including a controller's `ctx.resolve`, which never
2318
2326
  // reaches `handleInteractionCompleted` — means the turn is about to compute again (GENC-1660).
2319
- // 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.
2320
2329
  const onInteractionSettled = (e) => {
2321
- var _a;
2322
- 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))
2323
2332
  this.startLoadingTimer();
2324
2333
  };
2325
2334
  const onProviderChanged = (e) => {
@@ -4846,6 +4855,8 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
4846
4855
  if (prevState && prevState !== 'idle') {
4847
4856
  this.logMeta('state.changed', { from: prevState, to: 'idle' });
4848
4857
  }
4858
+ // Before a deferred session switch below re-keys the element: the turn was this session's.
4859
+ this.reportTurnEnded(prevState, capturedSessionRef);
4849
4860
  this.syncShowHalo();
4850
4861
  this.fetchSuggestions();
4851
4862
  // setState was dispatched directly via the captured ref (not via the
@@ -4856,6 +4867,31 @@ let FoundationAiAssistant = FoundationAiAssistant_1 = class FoundationAiAssistan
4856
4867
  this.applyDeferredSessionSwitch();
4857
4868
  this.applyDeferredAgentsSwap();
4858
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
+ }
4859
4895
  onChatHeaderMouseDown(e) {
4860
4896
  if (this.popoutMode === 'collapse')
4861
4897
  return;