@genesislcap/ai-assistant 15.82.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 (99) 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 +1038 -42
  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/index.d.ts +4 -2
  39. package/dist/dts/index.d.ts.map +1 -1
  40. package/dist/dts/main/main.d.ts +11 -0
  41. package/dist/dts/main/main.d.ts.map +1 -1
  42. package/dist/dts/main/main.template.d.ts.map +1 -1
  43. package/dist/dts/notifications/agent-notifications.d.ts +6 -2
  44. package/dist/dts/notifications/agent-notifications.d.ts.map +1 -1
  45. package/dist/dts/notifications/agent-notifier.d.ts +26 -4
  46. package/dist/dts/notifications/agent-notifier.d.ts.map +1 -1
  47. package/dist/dts/state/decision-surface.d.ts +22 -4
  48. package/dist/dts/state/decision-surface.d.ts.map +1 -1
  49. package/dist/dts/state/interaction-context.d.ts +23 -4
  50. package/dist/dts/state/interaction-context.d.ts.map +1 -1
  51. package/dist/dts/state/interaction-registry.d.ts +55 -6
  52. package/dist/dts/state/interaction-registry.d.ts.map +1 -1
  53. package/dist/dts/state/live-interactions.d.ts +28 -0
  54. package/dist/dts/state/live-interactions.d.ts.map +1 -0
  55. package/dist/dts/state/persistence/session-persister.d.ts.map +1 -1
  56. package/dist/dts/state/persistence/session-snapshot.d.ts +16 -5
  57. package/dist/dts/state/persistence/session-snapshot.d.ts.map +1 -1
  58. package/dist/dts/state/test-interaction-context.d.ts +93 -0
  59. package/dist/dts/state/test-interaction-context.d.ts.map +1 -0
  60. package/dist/dts/types/ai-chat-widget.d.ts +7 -6
  61. package/dist/dts/types/ai-chat-widget.d.ts.map +1 -1
  62. package/dist/dts/types/interaction-context.d.ts +128 -17
  63. package/dist/dts/types/interaction-context.d.ts.map +1 -1
  64. package/dist/dts/types/interaction-interceptor.d.ts +48 -6
  65. package/dist/dts/types/interaction-interceptor.d.ts.map +1 -1
  66. package/dist/dts/types/interaction-surface.d.ts +145 -23
  67. package/dist/dts/types/interaction-surface.d.ts.map +1 -1
  68. package/dist/esm/autopilot/autopilot-driver.js +313 -60
  69. package/dist/esm/autopilot/autopilot-session.js +219 -40
  70. package/dist/esm/autopilot/autopilot-tools.js +11 -7
  71. package/dist/esm/autopilot/decision-message.js +105 -26
  72. package/dist/esm/autopilot/hand-back/hand-back.controller.js +2 -1
  73. package/dist/esm/autopilot/index.js +1 -0
  74. package/dist/esm/autopilot/widget-tools.js +39 -0
  75. package/dist/esm/components/ai-driver/base-driver-decorator.js +17 -0
  76. package/dist/esm/components/chat-driver/chat-driver.js +18 -2
  77. package/dist/esm/components/chat-driver/interaction-controller.js +232 -71
  78. package/dist/esm/components/settings-modal/settings-modal.template.js +2 -2
  79. package/dist/esm/config/define-stateful-agent.js +22 -1
  80. package/dist/esm/index.js +2 -0
  81. package/dist/esm/main/main.js +39 -3
  82. package/dist/esm/main/main.template.js +4 -1
  83. package/dist/esm/notifications/agent-notifications.js +11 -1
  84. package/dist/esm/notifications/agent-notifier.js +41 -7
  85. package/dist/esm/state/debug-event-log.js +5 -5
  86. package/dist/esm/state/decision-surface.js +137 -54
  87. package/dist/esm/state/interaction-context.js +41 -8
  88. package/dist/esm/state/interaction-registry.js +11 -0
  89. package/dist/esm/state/live-interactions.js +36 -0
  90. package/dist/esm/state/persistence/session-persister.js +44 -17
  91. package/dist/esm/state/persistence/session-snapshot.js +2 -2
  92. package/dist/esm/state/test-interaction-context.js +99 -0
  93. package/docs/notifications.md +55 -5
  94. package/docs/styling.md +33 -0
  95. package/package.json +19 -19
  96. package/sandbox/README.md +3 -2
  97. package/sandbox/autopilot.ts +26 -6
  98. package/sandbox/sandbox.ts +2 -0
  99. /package/dist/{tsdoc-metadata.json → dts/tsdoc-metadata.json} +0 -0
@@ -4034,8 +4034,8 @@ var META_EVENT_IMPORTANCE = {
4034
4034
  "interaction.outcome-dropped": "high",
4035
4035
  // A long action's step starting, finishing, or skipped on resume because it was already done.
4036
4036
  "interaction.step": "low",
4037
- // A cut checkpoint taken over after a reload, refused (by sameWork, or as malformed), or dropped
4038
- // at flow end.
4037
+ // A cut checkpoint taken over after a reload, refused (by sameWork, and kept for a later request;
4038
+ // or as malformed), or dropped at flow end, as is the live one.
4039
4039
  "interaction.checkpoint": "normal",
4040
4040
  // A claimant handing a pending interaction to the person, or taking it back.
4041
4041
  "interaction.held": "normal",
@@ -5274,14 +5274,22 @@ var FoldController = class {
5274
5274
  // src/state/decision-surface.ts
5275
5275
  var SELECT_ACTION = "select";
5276
5276
  var REPLY_ACTION = "reply";
5277
- var normalise = (option) => typeof option === "string" ? { id: option, label: option } : { id: option.id ?? option.label, label: option.label, enabledWhen: option.enabledWhen };
5278
- var isEnabled = (option) => {
5277
+ var normalise = (option) => typeof option === "string" ? { id: option, label: option } : { id: option.id ?? option.label, label: option.label, unavailable: option.unavailable };
5278
+ var GENERIC_UNAVAILABLE = "not available in this state";
5279
+ function unavailableReason(guard, ...args) {
5280
+ if (!guard) return void 0;
5279
5281
  try {
5280
- return option.enabledWhen?.() ?? true;
5282
+ const reason = guard(...args);
5283
+ if (reason === void 0) return void 0;
5284
+ return reason.trim().replace(/\.+$/, "") || GENERIC_UNAVAILABLE;
5281
5285
  } catch {
5282
- return false;
5286
+ return GENERIC_UNAVAILABLE;
5283
5287
  }
5284
- };
5288
+ }
5289
+ var reasonFor = (option) => unavailableReason(option.unavailable);
5290
+ var isEnabled = (option) => reasonFor(option) === void 0;
5291
+ var describeViews = (views) => Object.fromEntries(Object.entries(views).map(([name, v]) => [name, v.description]));
5292
+ var readView = (views, view) => Object.prototype.hasOwnProperty.call(views, view) ? views[view].read() : void 0;
5285
5293
  function buildDecisionSurface(spec) {
5286
5294
  const options = spec.options.map(normalise);
5287
5295
  const ids = /* @__PURE__ */ new Set();
@@ -5296,12 +5304,16 @@ function buildDecisionSurface(spec) {
5296
5304
  const actions = () => {
5297
5305
  const enabled = options.filter(isEnabled);
5298
5306
  return [
5299
- ...options.map((o) => ({
5300
- name: o.id,
5301
- label: o.label,
5302
- finishes: true,
5303
- enabled: isEnabled(o)
5304
- })),
5307
+ ...options.map((o) => {
5308
+ const unavailable = reasonFor(o);
5309
+ return {
5310
+ name: o.id,
5311
+ label: o.label,
5312
+ finishes: true,
5313
+ enabled: unavailable === void 0,
5314
+ ...unavailable !== void 0 ? { unavailable } : {}
5315
+ };
5316
+ }),
5305
5317
  ...spec.multi ? [
5306
5318
  {
5307
5319
  name: SELECT_ACTION,
@@ -5310,13 +5322,32 @@ function buildDecisionSurface(spec) {
5310
5322
  args: "options"
5311
5323
  }
5312
5324
  ] : [],
5313
- ...spec.freeText ? [{ name: REPLY_ACTION, finishes: true, enabled: true, args: "text" }] : []
5325
+ ...spec.freeText ? [replyAction()] : []
5314
5326
  ];
5315
5327
  };
5328
+ const replyReason = () => unavailableReason(spec.freeTextUnavailable);
5329
+ const replyAction = () => {
5330
+ const unavailable = replyReason();
5331
+ return {
5332
+ name: REPLY_ACTION,
5333
+ finishes: true,
5334
+ enabled: unavailable === void 0,
5335
+ ...unavailable !== void 0 ? { unavailable } : {},
5336
+ args: "text",
5337
+ refines: true
5338
+ };
5339
+ };
5316
5340
  const answer = (a) => () => spec.choose(a);
5341
+ const facts = () => spec.facts?.() ?? {};
5342
+ const views = spec.views && Object.keys(spec.views).length ? spec.views : void 0;
5343
+ const readable = views ? {
5344
+ views: describeViews(views),
5345
+ read: (view) => view === void 0 ? facts() : readView(views, view)
5346
+ } : {};
5317
5347
  return {
5318
5348
  prompt: spec.prompt,
5319
- facts: () => spec.facts?.() ?? {},
5349
+ facts,
5350
+ ...readable,
5320
5351
  actions,
5321
5352
  isReady: () => actions().some((a) => a.finishes && a.enabled),
5322
5353
  prepare(name, args) {
@@ -5337,7 +5368,7 @@ function buildDecisionSurface(spec) {
5337
5368
  if (disabled.length) {
5338
5369
  return {
5339
5370
  error: "disabled",
5340
- message: `Not available right now: ${disabled.map((o) => o.label).join(", ")}.`
5371
+ message: `Not available right now: ${disabled.map((o) => `${o.label} (${reasonFor(o)})`).join(", ")}.`
5341
5372
  };
5342
5373
  }
5343
5374
  const picks = chosen;
@@ -5348,6 +5379,10 @@ function buildDecisionSurface(spec) {
5348
5379
  };
5349
5380
  }
5350
5381
  if (spec.freeText && name === REPLY_ACTION) {
5382
+ const why2 = replyReason();
5383
+ if (why2 !== void 0) {
5384
+ return { error: "disabled", message: `"reply" is not available right now: ${why2}.` };
5385
+ }
5351
5386
  const text = args?.text;
5352
5387
  if (typeof text !== "string" || !text.trim()) {
5353
5388
  return { error: "invalid-args", message: "`reply` takes { text: string }, not empty." };
@@ -5358,8 +5393,12 @@ function buildDecisionSurface(spec) {
5358
5393
  if (!option) {
5359
5394
  return { error: "unknown-action", message: `No action "${name}" here.` };
5360
5395
  }
5361
- if (!isEnabled(option)) {
5362
- return { error: "disabled", message: `"${option.label}" is not available right now.` };
5396
+ const why = reasonFor(option);
5397
+ if (why !== void 0) {
5398
+ return {
5399
+ error: "disabled",
5400
+ message: `"${option.label}" is not available right now: ${why}.`
5401
+ };
5363
5402
  }
5364
5403
  return {
5365
5404
  choice: option.label,
@@ -5399,33 +5438,65 @@ function checkArgs(args, schema) {
5399
5438
  return wrong.length ? `${wrong.join("; ")}.` : void 0;
5400
5439
  }
5401
5440
  function buildFullSurface(spec) {
5402
- const guard = (enabledWhen) => {
5403
- try {
5404
- return enabledWhen?.() ?? true;
5405
- } catch {
5406
- return false;
5441
+ for (const [name, action] of Object.entries(spec.actions)) {
5442
+ if (action.text && action.argsSchema) {
5443
+ throw new Error(
5444
+ `exposeSurface: action "${name}" takes \`text\` or \`argsSchema\`, not both.`
5445
+ );
5407
5446
  }
5408
- };
5409
- const actions = () => Object.entries(spec.actions).map(([name, a]) => ({
5410
- name,
5411
- finishes: !!a.finishes,
5412
- enabled: guard(a.enabledWhen),
5413
- description: a.description,
5414
- ...a.argsSchema ? { args: "fields", argsSchema: a.argsSchema } : {}
5415
- }));
5447
+ }
5448
+ const views = spec.views && Object.keys(spec.views).length ? spec.views : void 0;
5449
+ if (spec.preview !== void 0 && !(views && Object.prototype.hasOwnProperty.call(views, spec.preview))) {
5450
+ throw new Error(`exposeSurface: the preview "${spec.preview}" is not one of its views.`);
5451
+ }
5452
+ const actions = () => Object.entries(spec.actions).map(([name, a]) => {
5453
+ const unavailable = unavailableReason(a.unavailable);
5454
+ return {
5455
+ name,
5456
+ finishes: !!a.finishes,
5457
+ enabled: unavailable === void 0,
5458
+ ...unavailable !== void 0 ? { unavailable } : {},
5459
+ description: a.description,
5460
+ ...a.text ? { args: "text" } : {},
5461
+ ...a.argsSchema ? { args: "fields", argsSchema: a.argsSchema } : {},
5462
+ ...a.refines ? { refines: true } : {}
5463
+ };
5464
+ });
5416
5465
  return {
5417
5466
  prompt: spec.prompt,
5418
5467
  facts: () => ({}),
5419
5468
  describe: () => spec.describe(),
5420
- views: spec.views,
5421
- read: (view) => spec.read(view),
5469
+ ...views ? {
5470
+ views: describeViews(views),
5471
+ ...spec.preview !== void 0 ? { preview: spec.preview } : {},
5472
+ read: (view) => {
5473
+ const name = view ?? spec.preview;
5474
+ return name === void 0 ? void 0 : readView(views, name);
5475
+ }
5476
+ } : {},
5422
5477
  actions,
5423
5478
  isReady: () => actions().some((a) => a.enabled),
5424
5479
  prepare(name, args) {
5425
5480
  const action = Object.prototype.hasOwnProperty.call(spec.actions, name) ? spec.actions[name] : void 0;
5426
5481
  if (!action) return { error: "unknown-action", message: `No action "${name}" here.` };
5427
- if (!guard(action.enabledWhen)) {
5428
- return { error: "disabled", message: `"${name}" is not available right now.` };
5482
+ const why = unavailableReason(action.unavailable);
5483
+ if (why !== void 0) {
5484
+ return { error: "disabled", message: `"${name}" is not available right now: ${why}.` };
5485
+ }
5486
+ if (action.text) {
5487
+ const text = args?.text;
5488
+ if (typeof text !== "string" || !text.trim()) {
5489
+ return {
5490
+ error: "invalid-args",
5491
+ message: `"${name}" takes its argument as \`text\`, not empty.`
5492
+ };
5493
+ }
5494
+ const trimmed = text.trim();
5495
+ return {
5496
+ choice: `${name}: ${trimmed}`.slice(0, CHOICE_CHARS),
5497
+ finishes: !!action.finishes,
5498
+ run: () => action.run(trimmed)
5499
+ };
5429
5500
  }
5430
5501
  const problem = checkArgs(args ?? {}, action.argsSchema);
5431
5502
  if (problem) return { error: "invalid-args", message: `"${name}": ${problem}` };
@@ -5453,15 +5524,21 @@ function createInteractionContext(interactionId, deps = {}) {
5453
5524
  let surface;
5454
5525
  let lastActivityAt = Date.now();
5455
5526
  let checkpoint = deps.checkpoint;
5527
+ let working;
5456
5528
  let offered = false;
5457
5529
  let attention;
5458
5530
  let attentionDone = false;
5531
+ let attentionTaker;
5459
5532
  const reportAttention = () => {
5460
5533
  if (!offered || !attention || attentionDone || disposed || settled) return;
5461
5534
  attentionDone = true;
5462
5535
  if (heldBy !== "user") return;
5463
- deps.requestAttention?.(attention.message);
5536
+ (attentionTaker ?? deps.requestAttention)?.(attention.message);
5464
5537
  };
5538
+ const reporting = (built) => ({
5539
+ ...built,
5540
+ isReady: () => working === false || working !== true && built.isReady()
5541
+ });
5465
5542
  const checkReady = () => {
5466
5543
  if (disposed || !surface || readyListeners.size === 0 || !surface.isReady()) return;
5467
5544
  const waiting = [...readyListeners];
@@ -5492,6 +5569,14 @@ function createInteractionContext(interactionId, deps = {}) {
5492
5569
  get checkpoint() {
5493
5570
  return checkpoint;
5494
5571
  },
5572
+ get working() {
5573
+ return working;
5574
+ },
5575
+ setWorking(next) {
5576
+ if (disposed || next === working) return;
5577
+ working = next;
5578
+ context.notify();
5579
+ },
5495
5580
  saveCheckpoint(next) {
5496
5581
  if (disposed) return;
5497
5582
  checkpoint = next;
@@ -5534,19 +5619,19 @@ function createInteractionContext(interactionId, deps = {}) {
5534
5619
  }
5535
5620
  disposers.add(fn);
5536
5621
  },
5537
- resolve(result) {
5622
+ resolve(result, options) {
5538
5623
  if (settled || disposed) return;
5539
5624
  settled = true;
5540
- deps.resolve?.(result);
5625
+ deps.resolve?.(result, options);
5541
5626
  },
5542
5627
  exposeDecision(decision) {
5543
5628
  if (disposed) return;
5544
- surface = buildDecisionSurface(decision);
5629
+ surface = reporting(buildDecisionSurface(decision));
5545
5630
  context.notify();
5546
5631
  },
5547
5632
  exposeSurface(spec) {
5548
5633
  if (disposed) return;
5549
- surface = buildFullSurface(spec);
5634
+ surface = reporting(buildFullSurface(spec));
5550
5635
  context.notify();
5551
5636
  },
5552
5637
  onSurfaceReady(fn) {
@@ -5600,6 +5685,16 @@ function createInteractionContext(interactionId, deps = {}) {
5600
5685
  offered = true;
5601
5686
  reportAttention();
5602
5687
  },
5688
+ get attentionMessage() {
5689
+ return attention?.message;
5690
+ },
5691
+ takeAttention(onRequest) {
5692
+ if (attentionDone || disposed || settled || attentionTaker) return void 0;
5693
+ attentionTaker = onRequest;
5694
+ return () => {
5695
+ if (attentionTaker === onRequest) attentionTaker = void 0;
5696
+ };
5697
+ },
5603
5698
  get surface() {
5604
5699
  return surface;
5605
5700
  }
@@ -5612,6 +5707,15 @@ function getInteractionRegistration(name) {
5612
5707
  return registry2.get(name);
5613
5708
  }
5614
5709
 
5710
+ // src/state/live-interactions.ts
5711
+ var live = /* @__PURE__ */ new Map();
5712
+ function trackInteractionContext(context) {
5713
+ live.set(context.interactionId, context);
5714
+ return () => {
5715
+ if (live.get(context.interactionId) === context) live.delete(context.interactionId);
5716
+ };
5717
+ }
5718
+
5615
5719
  // src/state/run-steps.ts
5616
5720
  var recorders = /* @__PURE__ */ new WeakMap();
5617
5721
  function bindStepRecorder(ctx, record, refused) {
@@ -5660,6 +5764,19 @@ function doneOnUsersBehalf(interaction, answeredBy) {
5660
5764
  }
5661
5765
  return {};
5662
5766
  }
5767
+ function stampAnsweredBy(result, answeredBy) {
5768
+ if (result === null || typeof result !== "object" || Array.isArray(result)) return result;
5769
+ const copy = { ...result };
5770
+ if (answeredBy) copy.answeredBy = answeredBy;
5771
+ else delete copy.answeredBy;
5772
+ return copy;
5773
+ }
5774
+ function whoAnswered(interaction, result, how) {
5775
+ const unanswered = result?.status === "timeout";
5776
+ const resolvedItself = !unanswered && !interaction.settledBy && (!!interaction.resolvesItself || how?.resolvedItself === true);
5777
+ if (unanswered || resolvedItself) return { resolvedItself };
5778
+ return { answeredBy: interaction.settledBy ?? "user", resolvedItself };
5779
+ }
5663
5780
  var STOPPED = {
5664
5781
  status: "timeout",
5665
5782
  message: "The turn was stopped before this was answered."
@@ -5682,58 +5799,118 @@ var InteractionController = class {
5682
5799
  * the root's are ever consulted: a sub-agent's request is opened by the root.
5683
5800
  */
5684
5801
  this.interceptors = [];
5802
+ /**
5803
+ * Checkpoints a reload cut, oldest first, each waiting for a request of its own widget type that
5804
+ * `sameWork` agrees is the same work. Held apart from `live`, so neither the work a resumed flow
5805
+ * does first nor a request `sameWork` refuses can lose one: a flow may open other long widgets
5806
+ * before the one a checkpoint belongs to asks for it. Each leaves when it is taken over, and all
5807
+ * of them when the flow ends.
5808
+ */
5809
+ this.cut = [];
5685
5810
  }
5686
- /** See `ChatDriver.getInteractionCheckpoint`. */
5811
+ /**
5812
+ * See `ChatDriver.getInteractionCheckpoints`: every checkpoint to save with the session — those a
5813
+ * reload cut that nothing has taken yet, oldest first, then the live interaction's. A reload cuts
5814
+ * them all, so all of them are restored as cut.
5815
+ */
5816
+ getCheckpoints() {
5817
+ const live2 = this.live;
5818
+ return [
5819
+ ...this.cut.map(({ componentName, value }) => ({ componentName, value })),
5820
+ ...live2 ? [{ componentName: live2.componentName, value: live2.value }] : []
5821
+ ];
5822
+ }
5823
+ /**
5824
+ * See `ChatDriver.getInteractionCheckpoint` (deprecated): one checkpoint, the live interaction's,
5825
+ * else the newest a reload cut.
5826
+ */
5687
5827
  getCheckpoint() {
5688
- const cp = this.checkpoint;
5689
- return cp ? { componentName: cp.componentName, value: cp.value } : void 0;
5828
+ const all = this.getCheckpoints();
5829
+ return all[all.length - 1];
5690
5830
  }
5691
- /** See `ChatDriver.restoreInteractionCheckpoint`. Restored means cut: its interaction is gone. */
5831
+ /**
5832
+ * See `ChatDriver.restoreInteractionCheckpoints`. Restored means cut: their interactions are gone.
5833
+ * Replaces whatever was held.
5834
+ */
5835
+ restoreCheckpoints(saved) {
5836
+ this.live = void 0;
5837
+ this.cut = (saved ?? []).map(({ componentName, value }) => ({ componentName, value }));
5838
+ }
5839
+ /** See `ChatDriver.restoreInteractionCheckpoint` (deprecated): one, or none. */
5692
5840
  restoreCheckpoint(saved) {
5693
- this.checkpoint = saved ? { componentName: saved.componentName, value: saved.value, cut: true } : void 0;
5841
+ this.restoreCheckpoints(saved ? [saved] : []);
5694
5842
  }
5695
- /** Drop the checkpoint, used or not, when its flow ends. */
5843
+ /** Drop every checkpoint, used or not, cut or live, when its flow ends. */
5696
5844
  clearCheckpoint(why) {
5697
- const cp = this.checkpoint;
5698
- if (!cp) return;
5699
- this.checkpoint = void 0;
5700
- recordMetaEvent(this.deps.sessionKey, "interaction.checkpoint", {
5701
- action: "cleared",
5702
- component: cp.componentName,
5703
- why,
5704
- ...cp.interactionId ? { interactionId: cp.interactionId } : {}
5705
- });
5845
+ const live2 = this.live;
5846
+ const cut = this.cut;
5847
+ this.live = void 0;
5848
+ this.cut = [];
5849
+ for (const cp of cut) {
5850
+ recordMetaEvent(this.deps.sessionKey, "interaction.checkpoint", {
5851
+ action: "cleared",
5852
+ component: cp.componentName,
5853
+ why,
5854
+ cut: true
5855
+ });
5856
+ }
5857
+ if (live2) {
5858
+ recordMetaEvent(this.deps.sessionKey, "interaction.checkpoint", {
5859
+ action: "cleared",
5860
+ component: live2.componentName,
5861
+ why,
5862
+ interactionId: live2.interactionId
5863
+ });
5864
+ }
5706
5865
  }
5707
5866
  /**
5708
- * Hand a cut checkpoint to a new request of the same widget type, if its registration's
5709
- * `sameWork` agrees. Only the first such request is asked: a refused checkpoint is dropped, and
5710
- * the work starts fresh as it would have without one.
5867
+ * Offer the checkpoints a reload cut to a new request of their widget type, newest first, and
5868
+ * hand it the first its registration's `sameWork` agrees is the same work (any, without one). A
5869
+ * checkpoint `sameWork` refuses stays where it is, for a later request of the same type: a flow
5870
+ * may ask for other work of that type first. Each refusal is recorded, with the identity kept.
5711
5871
  */
5712
5872
  takeOverCheckpoint(componentName, data, interactionId) {
5713
- const cut = this.checkpoint;
5714
- if (!cut?.cut || cut.componentName !== componentName) return void 0;
5715
- this.checkpoint = void 0;
5716
5873
  const sameWork = getInteractionRegistration(componentName)?.sameWork;
5717
- let agrees = true;
5718
- if (sameWork) {
5719
- try {
5720
- agrees = sameWork(cut.value, data);
5721
- } catch (e) {
5722
- logger2.warn(`InteractionController: "${componentName}" sameWork threw; starting fresh:`, e);
5723
- agrees = false;
5874
+ for (let i = this.cut.length - 1; i >= 0; i -= 1) {
5875
+ const cut = this.cut[i];
5876
+ if (cut.componentName !== componentName) continue;
5877
+ let agrees = true;
5878
+ if (sameWork) {
5879
+ try {
5880
+ agrees = sameWork(cut.value, data);
5881
+ } catch (e) {
5882
+ logger2.warn(
5883
+ `InteractionController: "${componentName}" sameWork threw; not taking it over:`,
5884
+ e
5885
+ );
5886
+ agrees = false;
5887
+ }
5724
5888
  }
5889
+ if (!agrees) {
5890
+ recordMetaEvent(this.deps.sessionKey, "interaction.checkpoint", {
5891
+ action: "refused",
5892
+ component: componentName,
5893
+ interactionId,
5894
+ saved: cut.value,
5895
+ kept: true
5896
+ });
5897
+ continue;
5898
+ }
5899
+ this.cut.splice(i, 1);
5900
+ recordMetaEvent(this.deps.sessionKey, "interaction.checkpoint", {
5901
+ action: "resumed",
5902
+ component: componentName,
5903
+ interactionId
5904
+ });
5905
+ this.live = { componentName, value: cut.value, interactionId };
5906
+ return cut.value;
5725
5907
  }
5726
- recordMetaEvent(this.deps.sessionKey, "interaction.checkpoint", {
5727
- action: agrees ? "resumed" : "refused",
5728
- component: componentName,
5729
- interactionId,
5730
- ...agrees ? {} : { saved: cut.value }
5731
- });
5732
- if (!agrees) return void 0;
5733
- this.checkpoint = { componentName, value: cut.value, interactionId };
5734
- return cut.value;
5908
+ return void 0;
5735
5909
  }
5736
- /** A controller's `ctx.saveCheckpoint`: kept as JSON, the form it is persisted in. */
5910
+ /**
5911
+ * A controller's `ctx.saveCheckpoint`: kept as JSON, the form it is persisted in. Replaces the
5912
+ * live interaction's only; the checkpoints a reload cut are left waiting for their own widgets.
5913
+ */
5737
5914
  saveCheckpoint(interactionId, componentName, value) {
5738
5915
  if (!this.pending.has(interactionId)) return;
5739
5916
  let copy;
@@ -5746,7 +5923,7 @@ var InteractionController = class {
5746
5923
  );
5747
5924
  return;
5748
5925
  }
5749
- this.checkpoint = { componentName, value: copy, interactionId };
5926
+ this.live = { componentName, value: copy, interactionId };
5750
5927
  this.deps.emit(new CustomEvent("checkpoint-saved", { detail: { interactionId } }));
5751
5928
  }
5752
5929
  /** See `ChatDriver.addInteractionInterceptor`. Returns a remover. */
@@ -5773,11 +5950,34 @@ var InteractionController = class {
5773
5950
  *
5774
5951
  * Runs before the interaction's message is appended, so the widget's first render already knows
5775
5952
  * its holder and nothing appears only to disappear.
5953
+ *
5954
+ * **A late claim.** An interceptor that declined may still claim it later, through its hold's
5955
+ * `claim`, once the asking is over and while nobody else has (see {@link InteractionHold.claim}).
5776
5956
  */
5777
5957
  offer(handle, opened) {
5778
5958
  let claimant;
5959
+ let asking = true;
5960
+ const claimLate = (interceptor) => {
5961
+ if (asking || claimant || opened.userOnly) return false;
5962
+ const pending = this.pending.get(opened.interactionId);
5963
+ if (!pending || !handle.setHeldBy(interceptor.id)) return false;
5964
+ claimant = interceptor;
5965
+ pending.claimant = interceptor;
5966
+ recordMetaEvent(this.deps.sessionKey, "interaction.held", {
5967
+ interactionId: opened.interactionId,
5968
+ heldBy: interceptor.id,
5969
+ claimant: interceptor.id,
5970
+ late: true
5971
+ });
5972
+ return true;
5973
+ };
5779
5974
  for (const interceptor of [...this.interceptors].reverse()) {
5780
- const hold = this.holdFor(handle, interceptor, () => claimant === interceptor);
5975
+ const hold = this.holdFor(
5976
+ handle,
5977
+ interceptor,
5978
+ () => claimant === interceptor,
5979
+ () => claimLate(interceptor)
5980
+ );
5781
5981
  let answer;
5782
5982
  try {
5783
5983
  answer = interceptor.onInteractionOpened({ ...opened, ctx: handle.context, hold });
@@ -5799,11 +5999,39 @@ var InteractionController = class {
5799
5999
  const pending = this.pending.get(opened.interactionId);
5800
6000
  if (pending) pending.claimant = interceptor;
5801
6001
  }
6002
+ asking = false;
5802
6003
  return handle.context.heldBy;
5803
6004
  }
5804
- /** The {@link InteractionHold} for one interceptor: it applies only while that one is the claimant. */
5805
- holdFor(handle, interceptor, isClaimant) {
6005
+ /**
6006
+ * Publish `agent-attention-ended` each time the interaction stops waiting on the person — a
6007
+ * claimant takes it, or it settles — so a notification still showing for it is closed
6008
+ * (GENC-1660). Wired once who holds it is decided, so a claim made as it opens is not one.
6009
+ */
6010
+ reportAttentionEnds(ctx) {
6011
+ const ended = () => this.deps.activityBus.publish("agent-attention-ended", {
6012
+ sessionKey: this.deps.sessionKey,
6013
+ interactionId: ctx.interactionId
6014
+ });
6015
+ let heldBy = ctx.heldBy;
6016
+ const unsubscribe = ctx.subscribe(() => {
6017
+ if (ctx.heldBy === heldBy) return;
6018
+ heldBy = ctx.heldBy;
6019
+ if (heldBy !== "user") ended();
6020
+ });
6021
+ ctx.onDispose(() => {
6022
+ unsubscribe();
6023
+ ended();
6024
+ });
6025
+ }
6026
+ /**
6027
+ * The {@link InteractionHold} for one interceptor: it applies only while that one is the claimant,
6028
+ * which `claim` can make it after the asking, if nobody else is.
6029
+ */
6030
+ holdFor(handle, interceptor, isClaimant, claim) {
5806
6031
  return {
6032
+ claim,
6033
+ attentionMessage: () => handle.attentionMessage,
6034
+ takeAttention: (onRequest) => handle.takeAttention(onRequest),
5807
6035
  set: (holder) => {
5808
6036
  if (!isClaimant()) return false;
5809
6037
  const next = holder === "user" ? "user" : interceptor.id;
@@ -5947,6 +6175,9 @@ var InteractionController = class {
5947
6175
  reject,
5948
6176
  onSettled,
5949
6177
  overrideId: chatInputDuringExecution ? interactionId : void 0,
6178
+ ...getInteractionRegistration(componentName)?.resolvesItself === true && {
6179
+ resolvesItself: true
6180
+ },
5950
6181
  // Resolve the interaction with a timeout result if the user does not
5951
6182
  // respond in time. `resolve` runs the same teardown a normal resolution
5952
6183
  // does (marks the widget read-only, reverts any input override) and
@@ -5960,7 +6191,7 @@ var InteractionController = class {
5960
6191
  });
5961
6192
  const handle = createInteractionContext(interactionId, {
5962
6193
  sessionKey: this.deps.sessionKey,
5963
- resolve: (result) => this.resolve(interactionId, result),
6194
+ resolve: (result, how) => this.resolve(interactionId, result, how),
5964
6195
  checkpoint: this.takeOverCheckpoint(componentName, data, interactionId),
5965
6196
  saveCheckpoint: (value) => this.saveCheckpoint(interactionId, componentName, value),
5966
6197
  requestAttention: (message) => this.deps.activityBus.publish("agent-attention", {
@@ -5971,6 +6202,7 @@ var InteractionController = class {
5971
6202
  })
5972
6203
  });
5973
6204
  this.contexts.set(interactionId, handle);
6205
+ handle.context.onDispose(trackInteractionContext(handle.context));
5974
6206
  bindStepRecorder(
5975
6207
  handle.context,
5976
6208
  (step, outcome) => recordMetaEvent(this.deps.sessionKey, "interaction.step", {
@@ -6003,6 +6235,7 @@ var InteractionController = class {
6003
6235
  userOnly: options?.userOnly === true
6004
6236
  });
6005
6237
  handle.markOffered();
6238
+ this.reportAttentionEnds(handle.context);
6006
6239
  recordMetaEvent(this.deps.sessionKey, "interaction.requested", {
6007
6240
  interactionId,
6008
6241
  component: componentName,
@@ -6032,7 +6265,7 @@ var InteractionController = class {
6032
6265
  const opened = this.pending.get(interactionId);
6033
6266
  if (opened) {
6034
6267
  opened.appended = true;
6035
- if (opened.early) this.resolve(interactionId, opened.early.result);
6268
+ if (opened.early) this.resolve(interactionId, opened.early.result, opened.early.options);
6036
6269
  }
6037
6270
  const signal = options?.signal;
6038
6271
  if (signal) {
@@ -6051,16 +6284,17 @@ var InteractionController = class {
6051
6284
  }
6052
6285
  /**
6053
6286
  * See `ChatDriver.resolveInteraction`. Warns and returns when the id is unknown — a widget can
6054
- * report twice, and the second report has nothing left to settle.
6287
+ * report twice, and the second report has nothing left to settle. `how` is what a controller's
6288
+ * `ctx.resolve` said about the settle (`resolvedItself`); every other route passes none.
6055
6289
  */
6056
- resolve(interactionId, result) {
6290
+ resolve(interactionId, result, how) {
6057
6291
  const interaction = this.pending.get(interactionId);
6058
6292
  if (!interaction) {
6059
6293
  logger2.warn(`Interaction with ID ${interactionId} not found.`);
6060
6294
  return;
6061
6295
  }
6062
6296
  if (!interaction.appended) {
6063
- interaction.early ??= { result };
6297
+ interaction.early ??= { result, options: how };
6064
6298
  return;
6065
6299
  }
6066
6300
  if (interaction.timeoutHandle) clearTimeout(interaction.timeoutHandle);
@@ -6070,8 +6304,7 @@ var InteractionController = class {
6070
6304
  result?.diagnostics
6071
6305
  );
6072
6306
  const costUsd = typeof result?.costUsd === "number" && Number.isFinite(result.costUsd) && result.costUsd > 0 ? result.costUsd : void 0;
6073
- const unanswered = result?.status === "timeout";
6074
- const answeredBy = unanswered ? void 0 : interaction.settledBy ?? "user";
6307
+ const { answeredBy, resolvedItself } = whoAnswered(interaction, result, how);
6075
6308
  const run = answeredBy && answeredBy !== "user" ? interaction.running : void 0;
6076
6309
  if (run) {
6077
6310
  interaction.settledInRun = run.token;
@@ -6085,20 +6318,23 @@ var InteractionController = class {
6085
6318
  ...message.interaction,
6086
6319
  resolved: result,
6087
6320
  ...answeredBy ? { answeredBy } : {},
6321
+ ...resolvedItself ? { resolvedItself } : {},
6088
6322
  ...edits ? { edits } : {}
6089
6323
  },
6090
6324
  ...costUsd != null ? { externalCostUsd: (message.externalCostUsd ?? 0) + costUsd } : {}
6091
6325
  }));
6092
6326
  if (patched) this.deps.notifyHistoryUpdated();
6093
6327
  if (typeof result?.userMessage === "string" && result.userMessage.trim()) {
6094
- this.deps.appendToHistory(
6095
- answeredBy && answeredBy !== "user" ? {
6328
+ if (!answeredBy || answeredBy === "user") {
6329
+ this.deps.appendToHistory({ role: "synthetic-user", content: result.userMessage });
6330
+ } else if (!run?.note) {
6331
+ this.deps.appendToHistory({
6096
6332
  role: "assistant",
6097
6333
  content: result.userMessage,
6098
6334
  delegate: answeredBy,
6099
6335
  excludeFromProvider: true
6100
- } : { role: "synthetic-user", content: result.userMessage }
6101
- );
6336
+ });
6337
+ }
6102
6338
  }
6103
6339
  if (interaction.overrideId) {
6104
6340
  this.deps.emit(new CustomEvent("interaction-stop", { detail: { interactionId } }));
@@ -6106,22 +6342,32 @@ var InteractionController = class {
6106
6342
  recordMetaEvent(this.deps.sessionKey, "interaction.resolved", {
6107
6343
  interactionId,
6108
6344
  ...answeredBy ? { answeredBy } : {},
6345
+ ...resolvedItself ? { resolvedItself } : {},
6109
6346
  ...edits ? { edits: edits.length } : {}
6110
6347
  });
6111
6348
  this.deps.activityBus.publish("interaction-resolved", void 0);
6112
6349
  try {
6113
- interaction.onSettled?.({ answeredBy, decision, ...edited ? { edited } : {} });
6350
+ interaction.onSettled?.({
6351
+ answeredBy,
6352
+ ...resolvedItself ? { resolvedItself } : {},
6353
+ decision,
6354
+ ...edited ? { edited } : {}
6355
+ });
6114
6356
  } catch (e) {
6115
6357
  logger2.warn("InteractionController: onSettled threw:", e);
6116
6358
  }
6117
6359
  this.deps.emit(
6118
6360
  new CustomEvent("interaction-settled", {
6119
- detail: { interactionId, ...answeredBy ? { answeredBy } : {} }
6361
+ detail: {
6362
+ interactionId,
6363
+ ...answeredBy ? { answeredBy } : {},
6364
+ ...resolvedItself ? { resolvedItself } : {}
6365
+ }
6120
6366
  })
6121
6367
  );
6122
- interaction.resolve(result);
6368
+ interaction.resolve(stampAnsweredBy(result, answeredBy));
6123
6369
  this.pending.delete(interactionId);
6124
- if (this.checkpoint?.interactionId === interactionId) this.checkpoint = void 0;
6370
+ if (this.live?.interactionId === interactionId) this.live = void 0;
6125
6371
  this.contexts.get(interactionId)?.dispose();
6126
6372
  this.contexts.delete(interactionId);
6127
6373
  }
@@ -8049,11 +8295,27 @@ var ChatDriver = class _ChatDriver extends EventTarget {
8049
8295
  getInteractionContext(interactionId) {
8050
8296
  return this.interactions.context(interactionId);
8051
8297
  }
8052
- /** {@inheritDoc AiDriver.getInteractionCheckpoint} */
8298
+ /** {@inheritDoc AiDriver.getInteractionCheckpoints} */
8299
+ getInteractionCheckpoints() {
8300
+ return this.interactions.getCheckpoints();
8301
+ }
8302
+ /** {@inheritDoc AiDriver.restoreInteractionCheckpoints} */
8303
+ restoreInteractionCheckpoints(saved) {
8304
+ this.interactions.restoreCheckpoints(saved);
8305
+ }
8306
+ /**
8307
+ * {@inheritDoc AiDriver.getInteractionCheckpoint}
8308
+ *
8309
+ * @deprecated Use `getInteractionCheckpoints`.
8310
+ */
8053
8311
  getInteractionCheckpoint() {
8054
8312
  return this.interactions.getCheckpoint();
8055
8313
  }
8056
- /** {@inheritDoc AiDriver.restoreInteractionCheckpoint} */
8314
+ /**
8315
+ * {@inheritDoc AiDriver.restoreInteractionCheckpoint}
8316
+ *
8317
+ * @deprecated Use `restoreInteractionCheckpoints`.
8318
+ */
8057
8319
  restoreInteractionCheckpoint(saved) {
8058
8320
  this.interactions.restoreCheckpoint(saved);
8059
8321
  }
@@ -9340,6 +9602,18 @@ var BaseDriverDecorator = class _BaseDriverDecorator extends EventTarget {
9340
9602
  getFlowOwner() {
9341
9603
  return this.inner.getFlowOwner?.() ?? null;
9342
9604
  }
9605
+ getInteractionCheckpoints() {
9606
+ if (this.inner.getInteractionCheckpoints) return this.inner.getInteractionCheckpoints();
9607
+ const one = this.inner.getInteractionCheckpoint?.();
9608
+ return one ? [one] : [];
9609
+ }
9610
+ restoreInteractionCheckpoints(saved) {
9611
+ if (this.inner.restoreInteractionCheckpoints) {
9612
+ this.inner.restoreInteractionCheckpoints(saved);
9613
+ } else {
9614
+ this.inner.restoreInteractionCheckpoint?.(saved[saved.length - 1]);
9615
+ }
9616
+ }
9343
9617
  getInteractionCheckpoint() {
9344
9618
  return this.inner.getInteractionCheckpoint?.();
9345
9619
  }
@@ -10061,6 +10335,68 @@ function defineAgent(config) {
10061
10335
  return config;
10062
10336
  }
10063
10337
 
10338
+ // src/autopilot/autopilot-tools.ts
10339
+ var WIDGET_READ = "widget_read";
10340
+ var WIDGET_ACT = "widget_act";
10341
+ var HAND_BACK = "hand_back";
10342
+ var AUTOPILOT_TOOL_DEFINITIONS = [
10343
+ {
10344
+ name: WIDGET_READ,
10345
+ description: "Read the current decision as it stands now: its state (one of its views, if it lists views; without one, its facts or the view shown as Now), and its actions with their numbers and whether each is available. Use it when the decision message may be out of date, or to read a view it lists.",
10346
+ parameters: {
10347
+ type: "object",
10348
+ properties: {
10349
+ view: { type: "string", description: "One of the views the decision lists, if any." }
10350
+ }
10351
+ }
10352
+ },
10353
+ {
10354
+ name: WIDGET_ACT,
10355
+ description: 'Act on the current decision, as the user would by clicking. `action` is the number of an option from the decision\'s list (e.g. "1"), or a named action from that list: "select" with `options` to choose several, "reply" with `text` to answer in your own words, any action listed as name({text}) with its argument in `text`, and any listed as name({fields}) with `fields`. If it settles the decision, your turn ends. `note` is shown to the user as the assistant speaking, before the outcome: one short sentence in the first person saying what you chose and why, e.g. "Your brief has no external feeds, so I\'ll skip Data Feeds." Never mention an autopilot or a second agent.',
10356
+ parameters: {
10357
+ type: "object",
10358
+ required: ["action"],
10359
+ properties: {
10360
+ action: {
10361
+ type: "string",
10362
+ description: 'An option number from the list, starting at 1, or a named action ("select", "reply").'
10363
+ },
10364
+ options: {
10365
+ type: "array",
10366
+ items: { type: "string" },
10367
+ description: 'For "select": the options to choose, by number or label.'
10368
+ },
10369
+ text: {
10370
+ type: "string",
10371
+ description: `For "reply" (your answer, in the user's place) and any action listed as name({text}): its one argument, as plain text.`
10372
+ },
10373
+ fields: {
10374
+ type: "string",
10375
+ description: "Only for an action listed as name({fields}): a JSON object, as text, matching the fields schema the decision lists for it."
10376
+ },
10377
+ note: {
10378
+ type: "string",
10379
+ description: "Shown to the user as the assistant speaking. One sentence, first person."
10380
+ }
10381
+ }
10382
+ }
10383
+ },
10384
+ {
10385
+ name: HAND_BACK,
10386
+ description: 'Give this one decision to the user, when it rests on something only they can know and neither their brief nor their own answers settle it, or when nothing on it can be done (every action unavailable). Your turn ends and the user sees the question. `reason` is shown to them as the assistant speaking, after "I need your input on this one:" \u2014 say plainly what you need from them. Never mention an autopilot or a second agent.',
10387
+ parameters: {
10388
+ type: "object",
10389
+ required: ["reason"],
10390
+ properties: {
10391
+ reason: {
10392
+ type: "string",
10393
+ description: "What the user needs to decide, and why it is theirs."
10394
+ }
10395
+ }
10396
+ }
10397
+ }
10398
+ ];
10399
+
10064
10400
  // src/config/define-stateful-agent.ts
10065
10401
  function defaultStatefulDebugSnapshot(state) {
10066
10402
  if (!state || typeof state !== "object") return state;
@@ -10260,6 +10596,23 @@ function defineStatefulAgent(opts) {
10260
10596
  };
10261
10597
  }
10262
10598
  function defineAutopilot(config) {
10599
+ const seen = new Set(AUTOPILOT_TOOL_DEFINITIONS.map((d) => d.name));
10600
+ for (const d of config.tools?.definitions ?? []) {
10601
+ if (seen.has(d.name)) {
10602
+ throw new Error(`defineAutopilot: the tool "${d.name}" is named twice.`);
10603
+ }
10604
+ seen.add(d.name);
10605
+ }
10606
+ for (const set of config.widgetTools ?? []) {
10607
+ for (const name of Object.keys(set.tools)) {
10608
+ if (seen.has(name)) {
10609
+ throw new Error(
10610
+ `defineAutopilot: the widget tool "${name}" (for "${set.componentName}") is named twice.`
10611
+ );
10612
+ }
10613
+ seen.add(name);
10614
+ }
10615
+ }
10263
10616
  return config;
10264
10617
  }
10265
10618