@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
@@ -6,23 +6,45 @@ const normalise = (option) => {
6
6
  var _a;
7
7
  return typeof option === 'string'
8
8
  ? { id: option, label: option }
9
- : { id: (_a = option.id) !== null && _a !== void 0 ? _a : option.label, label: option.label, enabledWhen: option.enabledWhen };
9
+ : { id: (_a = option.id) !== null && _a !== void 0 ? _a : option.label, label: option.label, unavailable: option.unavailable };
10
10
  };
11
- const isEnabled = (option) => {
12
- var _a, _b;
11
+ /** What an unavailable thing says when its guard gives no reason (an empty one, or a throw). */
12
+ export const GENERIC_UNAVAILABLE = 'not available in this state';
13
+ /**
14
+ * Why something cannot be used right now, from its `unavailable` guard, or `undefined` when it can
15
+ * (GENC-1660). One rule for options, actions and widget tools: absent means available; an empty
16
+ * reason, or a guard that throws, counts as unavailable with a generic reason, since a guard that
17
+ * cannot say why cannot vouch for its button either.
18
+ */
19
+ export function unavailableReason(guard, ...args) {
20
+ if (!guard)
21
+ return undefined;
13
22
  try {
14
- return (_b = (_a = option.enabledWhen) === null || _a === void 0 ? void 0 : _a.call(option)) !== null && _b !== void 0 ? _b : true;
23
+ const reason = guard(...args);
24
+ if (reason === undefined)
25
+ return undefined;
26
+ // Without a closing full stop, so a message that ends the sentence itself never shows two.
27
+ return reason.trim().replace(/\.+$/, '') || GENERIC_UNAVAILABLE;
15
28
  }
16
- catch (_c) {
17
- // A guard that throws cannot vouch for its button.
18
- return false;
29
+ catch (_a) {
30
+ return GENERIC_UNAVAILABLE;
19
31
  }
20
- };
32
+ }
33
+ const reasonFor = (option) => unavailableReason(option.unavailable);
34
+ const isEnabled = (option) => reasonFor(option) === undefined;
35
+ /** Each view's description, by name: what the model is told a surface's views hold. */
36
+ const describeViews = (views) => Object.fromEntries(Object.entries(views).map(([name, v]) => [name, v.description]));
37
+ /**
38
+ * Read one named view. Own views only: a name from the model such as `constructor` must not reach
39
+ * the record's prototype. A view it does not have reads as nothing; the autopilot refuses one before
40
+ * it gets here.
41
+ */
42
+ const readView = (views, view) => Object.prototype.hasOwnProperty.call(views, view) ? views[view].read() : undefined;
21
43
  /**
22
44
  * Build the surface for a short-form decision (GENC-1660). Its actions are its options (by id),
23
- * plus `select` for a multi-select and `reply` for a written answer; all of them finish. Every
24
- * read — facts, actions, enabled-ness — is taken fresh, so the surface always describes the
25
- * widget as it is now.
45
+ * plus `select` for a multi-select and `reply` for a written answer; all of them finish. Its views,
46
+ * if it has any, are read by name. Every read — facts, views, actions, enabled-ness — is taken
47
+ * fresh, so the surface always describes the widget as it is now.
26
48
  *
27
49
  * Throws if an option's id collides with another or with a platform-owned name, which is a bug in
28
50
  * the widget rather than something to recover from.
@@ -42,12 +64,10 @@ export function buildDecisionSurface(spec) {
42
64
  const actions = () => {
43
65
  const enabled = options.filter(isEnabled);
44
66
  return [
45
- ...options.map((o) => ({
46
- name: o.id,
47
- label: o.label,
48
- finishes: true,
49
- enabled: isEnabled(o),
50
- })),
67
+ ...options.map((o) => {
68
+ const unavailable = reasonFor(o);
69
+ return Object.assign({ name: o.id, label: o.label, finishes: true, enabled: unavailable === undefined }, (unavailable !== undefined ? { unavailable } : {}));
70
+ }),
51
71
  ...(spec.multi
52
72
  ? [
53
73
  {
@@ -58,18 +78,27 @@ export function buildDecisionSurface(spec) {
58
78
  },
59
79
  ]
60
80
  : []),
61
- ...(spec.freeText
62
- ? [{ name: REPLY_ACTION, finishes: true, enabled: true, args: 'text' }]
63
- : []),
81
+ ...(spec.freeText ? [replyAction()] : []),
64
82
  ];
65
83
  };
84
+ const replyReason = () => unavailableReason(spec.freeTextUnavailable);
85
+ const replyAction = () => {
86
+ const unavailable = replyReason();
87
+ return Object.assign(Object.assign({ name: REPLY_ACTION, finishes: true, enabled: unavailable === undefined }, (unavailable !== undefined ? { unavailable } : {})), { args: 'text', refines: true });
88
+ };
66
89
  const answer = (a) => () => spec.choose(a);
67
- return {
68
- prompt: spec.prompt,
69
- facts: () => { var _a, _b; return (_b = (_a = spec.facts) === null || _a === void 0 ? void 0 : _a.call(spec)) !== null && _b !== void 0 ? _b : {}; },
70
- actions,
71
- isReady: () => actions().some((a) => a.finishes && a.enabled),
72
- prepare(name, args) {
90
+ const facts = () => { var _a, _b; return (_b = (_a = spec.facts) === null || _a === void 0 ? void 0 : _a.call(spec)) !== null && _b !== void 0 ? _b : {}; };
91
+ // Views, where it has any, read as a full-form surface's do: by name, the default being what a
92
+ // read without one returned before views existed (the facts). An empty record is no views, so a
93
+ // decision without them keeps the surface it always had, `read` absent.
94
+ const views = spec.views && Object.keys(spec.views).length ? spec.views : undefined;
95
+ const readable = views
96
+ ? {
97
+ views: describeViews(views),
98
+ read: (view) => (view === undefined ? facts() : readView(views, view)),
99
+ }
100
+ : {};
101
+ return Object.assign(Object.assign({ prompt: spec.prompt, facts }, readable), { actions, isReady: () => actions().some((a) => a.finishes && a.enabled), prepare(name, args) {
73
102
  if (spec.multi && name === SELECT_ACTION) {
74
103
  const picked = args === null || args === void 0 ? void 0 : args.options;
75
104
  if (!Array.isArray(picked) || picked.length === 0) {
@@ -87,7 +116,7 @@ export function buildDecisionSurface(spec) {
87
116
  if (disabled.length) {
88
117
  return {
89
118
  error: 'disabled',
90
- message: `Not available right now: ${disabled.map((o) => o.label).join(', ')}.`,
119
+ message: `Not available right now: ${disabled.map((o) => `${o.label} (${reasonFor(o)})`).join(', ')}.`,
91
120
  };
92
121
  }
93
122
  const picks = chosen;
@@ -98,6 +127,10 @@ export function buildDecisionSurface(spec) {
98
127
  };
99
128
  }
100
129
  if (spec.freeText && name === REPLY_ACTION) {
130
+ const why = replyReason();
131
+ if (why !== undefined) {
132
+ return { error: 'disabled', message: `"reply" is not available right now: ${why}.` };
133
+ }
101
134
  const text = args === null || args === void 0 ? void 0 : args.text;
102
135
  if (typeof text !== 'string' || !text.trim()) {
103
136
  return { error: 'invalid-args', message: '`reply` takes { text: string }, not empty.' };
@@ -108,16 +141,19 @@ export function buildDecisionSurface(spec) {
108
141
  if (!option) {
109
142
  return { error: 'unknown-action', message: `No action "${name}" here.` };
110
143
  }
111
- if (!isEnabled(option)) {
112
- return { error: 'disabled', message: `"${option.label}" is not available right now.` };
144
+ const why = reasonFor(option);
145
+ if (why !== undefined) {
146
+ return {
147
+ error: 'disabled',
148
+ message: `"${option.label}" is not available right now: ${why}.`,
149
+ };
113
150
  }
114
151
  return {
115
152
  choice: option.label,
116
153
  finishes: true,
117
154
  run: answer({ kind: 'option', option: option.id }),
118
155
  };
119
- },
120
- };
156
+ } });
121
157
  }
122
158
  /** How long a choice's text may run in a `decidedOnUsersBehalf` record, in characters. */
123
159
  const CHOICE_CHARS = 300;
@@ -161,30 +197,62 @@ export function checkArgs(args, schema) {
161
197
  .map(([key, prop]) => `${key} should be ${String(prop === null || prop === void 0 ? void 0 : prop.type)}`);
162
198
  return wrong.length ? `${wrong.join('; ')}.` : undefined;
163
199
  }
200
+ /**
201
+ * An example of arguments that fit `schema`, for a refusal to show the model: each property with a
202
+ * placeholder of its declared type, required ones first. Shallow, like {@link checkArgs}.
203
+ */
204
+ export function exampleArgs(schema) {
205
+ var _a, _b;
206
+ const properties = ((_a = schema.properties) !== null && _a !== void 0 ? _a : {});
207
+ const required = new Set((_b = schema.required) !== null && _b !== void 0 ? _b : []);
208
+ const placeholder = (type) => {
209
+ switch (type) {
210
+ case 'string':
211
+ return '…';
212
+ case 'number':
213
+ case 'integer':
214
+ return 0;
215
+ case 'boolean':
216
+ return false;
217
+ case 'array':
218
+ return [];
219
+ case 'object':
220
+ return {};
221
+ default:
222
+ return null;
223
+ }
224
+ };
225
+ const names = Object.keys(properties).sort((a, b) => Number(required.has(b)) - Number(required.has(a)));
226
+ return Object.fromEntries(names.map((name) => { var _a; return [name, placeholder((_a = properties[name]) === null || _a === void 0 ? void 0 : _a.type)]; }));
227
+ }
164
228
  /**
165
229
  * Build the surface for a full-form spec (GENC-1660 §4.2): named actions, some editing and some
166
- * finishing, each guarded and schema-checked; a description; views to read. Every read is fresh.
230
+ * finishing, each guarded and checked (a text action's text, a form's fields against its schema); a
231
+ * description; described views to read, one of them the preview. Every read is fresh.
232
+ *
233
+ * Throws if an action declares both `text` and `argsSchema`, or the preview is not one of the
234
+ * views: a bug in the widget rather than something to recover from.
167
235
  */
168
236
  export function buildFullSurface(spec) {
169
- const guard = (enabledWhen) => {
170
- var _a;
171
- try {
172
- return (_a = enabledWhen === null || enabledWhen === void 0 ? void 0 : enabledWhen()) !== null && _a !== void 0 ? _a : true;
173
- }
174
- catch (_b) {
175
- return false;
237
+ for (const [name, action] of Object.entries(spec.actions)) {
238
+ if (action.text && action.argsSchema) {
239
+ throw new Error(`exposeSurface: action "${name}" takes \`text\` or \`argsSchema\`, not both.`);
176
240
  }
177
- };
178
- const actions = () => Object.entries(spec.actions).map(([name, a]) => (Object.assign({ name, finishes: !!a.finishes, enabled: guard(a.enabledWhen), description: a.description }, (a.argsSchema ? { args: 'fields', argsSchema: a.argsSchema } : {}))));
179
- return {
180
- prompt: spec.prompt,
181
- facts: () => ({}),
182
- describe: () => spec.describe(),
183
- views: spec.views,
184
- read: (view) => spec.read(view),
185
- actions,
186
- isReady: () => actions().some((a) => a.enabled),
187
- prepare(name, args) {
241
+ }
242
+ const views = spec.views && Object.keys(spec.views).length ? spec.views : undefined;
243
+ if (spec.preview !== undefined &&
244
+ !(views && Object.prototype.hasOwnProperty.call(views, spec.preview))) {
245
+ throw new Error(`exposeSurface: the preview "${spec.preview}" is not one of its views.`);
246
+ }
247
+ const actions = () => Object.entries(spec.actions).map(([name, a]) => {
248
+ const unavailable = unavailableReason(a.unavailable);
249
+ return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ name, finishes: !!a.finishes, enabled: unavailable === undefined }, (unavailable !== undefined ? { unavailable } : {})), { description: a.description }), (a.text ? { args: 'text' } : {})), (a.argsSchema ? { args: 'fields', argsSchema: a.argsSchema } : {})), (a.refines ? { refines: true } : {}));
250
+ });
251
+ return Object.assign(Object.assign({ prompt: spec.prompt, facts: () => ({}), describe: () => spec.describe() }, (views
252
+ ? Object.assign(Object.assign({ views: describeViews(views) }, (spec.preview !== undefined ? { preview: spec.preview } : {})), { read: (view) => {
253
+ const name = view !== null && view !== void 0 ? view : spec.preview;
254
+ return name === undefined ? undefined : readView(views, name);
255
+ } }) : {})), { actions, isReady: () => actions().some((a) => a.enabled), prepare(name, args) {
188
256
  // Own actions only: a name from the model such as `constructor` or `toString` must not reach
189
257
  // the object's prototype.
190
258
  const action = Object.prototype.hasOwnProperty.call(spec.actions, name)
@@ -192,8 +260,24 @@ export function buildFullSurface(spec) {
192
260
  : undefined;
193
261
  if (!action)
194
262
  return { error: 'unknown-action', message: `No action "${name}" here.` };
195
- if (!guard(action.enabledWhen)) {
196
- return { error: 'disabled', message: `"${name}" is not available right now.` };
263
+ const why = unavailableReason(action.unavailable);
264
+ if (why !== undefined) {
265
+ return { error: 'disabled', message: `"${name}" is not available right now: ${why}.` };
266
+ }
267
+ if (action.text) {
268
+ const text = args === null || args === void 0 ? void 0 : args.text;
269
+ if (typeof text !== 'string' || !text.trim()) {
270
+ return {
271
+ error: 'invalid-args',
272
+ message: `"${name}" takes its argument as \`text\`, not empty.`,
273
+ };
274
+ }
275
+ const trimmed = text.trim();
276
+ return {
277
+ choice: `${name}: ${trimmed}`.slice(0, CHOICE_CHARS),
278
+ finishes: !!action.finishes,
279
+ run: () => action.run(trimmed),
280
+ };
197
281
  }
198
282
  const problem = checkArgs(args !== null && args !== void 0 ? args : {}, action.argsSchema);
199
283
  if (problem)
@@ -204,6 +288,5 @@ export function buildFullSurface(spec) {
204
288
  finishes: !!action.finishes,
205
289
  run: () => action.run(args !== null && args !== void 0 ? args : {}),
206
290
  };
207
- },
208
- };
291
+ } });
209
292
  }
@@ -21,22 +21,33 @@ export function createInteractionContext(interactionId, deps = {}) {
21
21
  let surface;
22
22
  let lastActivityAt = Date.now();
23
23
  let checkpoint = deps.checkpoint;
24
+ let working;
24
25
  // GENC-1676: the widget's first `requestAttention`, held until who holds the interaction is
25
- // decided (`markOffered`), then reported once — or dropped, if a claimant holds it.
26
+ // decided (`markOffered`), then reported once — or not at all, if a claimant holds it. Its message
27
+ // is kept either way, for the claimant's hand-back to report (GENC-1660).
26
28
  let offered = false;
27
29
  let attention;
28
30
  let attentionDone = false;
31
+ // GENC-1660: set while an interceptor reports the request in the driver's place (`takeAttention`).
32
+ let attentionTaker;
29
33
  const reportAttention = () => {
30
34
  var _a;
31
35
  if (!offered || !attention || attentionDone || disposed || settled)
32
36
  return;
33
37
  attentionDone = true;
34
- // A claimant's: its own hand-back reports, if it gives the interaction back.
38
+ // A claimant's: its own hand-back reports, with the message, if it gives the interaction back.
35
39
  if (heldBy !== 'user')
36
40
  return;
37
- (_a = deps.requestAttention) === null || _a === void 0 ? void 0 : _a.call(deps, attention.message);
41
+ (_a = (attentionTaker !== null && attentionTaker !== void 0 ? attentionTaker : deps.requestAttention)) === null || _a === void 0 ? void 0 : _a(attention.message);
38
42
  };
39
- /** Fire every waiting `onSurfaceReady` once the surface has something a claimant could do. */
43
+ /**
44
+ * The surface as the context reports it: readiness follows what the controller said it is doing
45
+ * (`setWorking`) before the surface's own rule. Working: not ready, whatever is enabled. Asking:
46
+ * ready, even with nothing enabled, since what it exposed is the decision to make now. Never said:
47
+ * the surface's own rule, as before.
48
+ */
49
+ const reporting = (built) => (Object.assign(Object.assign({}, built), { isReady: () => working === false || (working !== true && built.isReady()) }));
50
+ /** Fire every waiting `onSurfaceReady` once a decision is due (see `reporting`). */
40
51
  const checkReady = () => {
41
52
  if (disposed || !surface || readyListeners.size === 0 || !surface.isReady())
42
53
  return;
@@ -69,6 +80,16 @@ export function createInteractionContext(interactionId, deps = {}) {
69
80
  get checkpoint() {
70
81
  return checkpoint;
71
82
  },
83
+ get working() {
84
+ return working;
85
+ },
86
+ setWorking(next) {
87
+ if (disposed || next === working)
88
+ return;
89
+ working = next;
90
+ // Status and readiness both read it, so subscribers re-read and a gate that just opened fires.
91
+ context.notify();
92
+ },
72
93
  saveCheckpoint(next) {
73
94
  var _a;
74
95
  if (disposed)
@@ -123,23 +144,23 @@ export function createInteractionContext(interactionId, deps = {}) {
123
144
  }
124
145
  disposers.add(fn);
125
146
  },
126
- resolve(result) {
147
+ resolve(result, options) {
127
148
  var _a;
128
149
  if (settled || disposed)
129
150
  return;
130
151
  settled = true;
131
- (_a = deps.resolve) === null || _a === void 0 ? void 0 : _a.call(deps, result);
152
+ (_a = deps.resolve) === null || _a === void 0 ? void 0 : _a.call(deps, result, options);
132
153
  },
133
154
  exposeDecision(decision) {
134
155
  if (disposed)
135
156
  return;
136
- surface = buildDecisionSurface(decision);
157
+ surface = reporting(buildDecisionSurface(decision));
137
158
  context.notify();
138
159
  },
139
160
  exposeSurface(spec) {
140
161
  if (disposed)
141
162
  return;
142
- surface = buildFullSurface(spec);
163
+ surface = reporting(buildFullSurface(spec));
143
164
  context.notify();
144
165
  },
145
166
  onSurfaceReady(fn) {
@@ -201,6 +222,18 @@ export function createInteractionContext(interactionId, deps = {}) {
201
222
  offered = true;
202
223
  reportAttention();
203
224
  },
225
+ get attentionMessage() {
226
+ return attention === null || attention === void 0 ? void 0 : attention.message;
227
+ },
228
+ takeAttention(onRequest) {
229
+ if (attentionDone || disposed || settled || attentionTaker)
230
+ return undefined;
231
+ attentionTaker = onRequest;
232
+ return () => {
233
+ if (attentionTaker === onRequest)
234
+ attentionTaker = undefined;
235
+ };
236
+ },
204
237
  get surface() {
205
238
  return surface;
206
239
  },
@@ -7,12 +7,23 @@ const registry = new Map();
7
7
  *
8
8
  * Registering is optional and additive: an unregistered widget works exactly as before.
9
9
  *
10
+ * Generic over the controller its factory builds, which types `ctx.controller` for the factory and
11
+ * for anything that reads the context with the same type argument (a view, a widget tool):
12
+ *
13
+ * ```ts
14
+ * registerInteraction<ReviewController>('review', {
15
+ * controller: (data, ctx) => new ReviewController(data as ReviewData, ctx),
16
+ * asText: reviewAsText,
17
+ * });
18
+ * ```
19
+ *
10
20
  * @beta
11
21
  */
12
22
  export function registerInteraction(name, registration) {
13
23
  if (registry.has(name)) {
14
24
  logger.warn(`registerInteraction: "${name}" was already registered; replacing it.`);
15
25
  }
26
+ // Stored untyped: the registry holds every widget's, and its readers do not know the type.
16
27
  registry.set(name, registration);
17
28
  }
18
29
  /**
@@ -0,0 +1,36 @@
1
+ /** Every pending interaction's live context, by id, across the drivers in this window. */
2
+ const live = new Map();
3
+ /**
4
+ * Make a driver-owned context findable by {@link getInteractionContext} until it is disposed. Returns
5
+ * the untrack, which the driver passes to the context's own `onDispose`.
6
+ *
7
+ * @internal
8
+ */
9
+ export function trackInteractionContext(context) {
10
+ live.set(context.interactionId, context);
11
+ return () => {
12
+ if (live.get(context.interactionId) === context)
13
+ live.delete(context.interactionId);
14
+ };
15
+ }
16
+ /**
17
+ * The live context of a pending interaction, by its id (GENC-1660), for UI that the chat does not
18
+ * render and so is never handed one: a layout side panel that shows a widget's detail, say. It can
19
+ * subscribe, read `heldBy` and reach the controller directly, rather than through a channel of its
20
+ * own. `undefined` once the interaction has resolved (its context is disposed then) and for an id
21
+ * that never opened.
22
+ *
23
+ * `TController` types `controller`, as it was registered (`registerInteraction<TController>()`).
24
+ * Unchecked: the caller says what it expects.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * const ctx = getInteractionContext<ReviewController>(interactionId);
29
+ * const unsubscribe = ctx?.subscribe(() => this.render(ctx.controller?.view(), ctx.heldBy));
30
+ * ```
31
+ *
32
+ * @beta
33
+ */
34
+ export function getInteractionContext(interactionId) {
35
+ return live.get(interactionId);
36
+ }
@@ -11,6 +11,33 @@ import { buildResumeNote, createPersistedSession, interruptedPromptFiles, isRest
11
11
  const autopilotOf = (driver) => driver && typeof driver.getPersistedMode === 'function'
12
12
  ? driver
13
13
  : undefined;
14
+ /**
15
+ * The checkpoints to save (GENC-1660 §4.12): every one the driver holds, or, from a third-party
16
+ * driver with only the older single form, its one.
17
+ */
18
+ function checkpointsOf(driver) {
19
+ var _a;
20
+ if (driver === null || driver === void 0 ? void 0 : driver.getInteractionCheckpoints)
21
+ return [...driver.getInteractionCheckpoints()];
22
+ const one = (_a = driver === null || driver === void 0 ? void 0 : driver.getInteractionCheckpoint) === null || _a === void 0 ? void 0 : _a.call(driver);
23
+ return one ? [one] : [];
24
+ }
25
+ /** The checkpoints a snapshot holds: `checkpoints`, or the one an older snapshot wrote. */
26
+ function savedCheckpoints(snapshot) {
27
+ if (snapshot.checkpoints)
28
+ return snapshot.checkpoints;
29
+ return snapshot.checkpoint ? [snapshot.checkpoint] : [];
30
+ }
31
+ /** Hand restored checkpoints back to the driver: none clears what it holds. */
32
+ function restoreCheckpoints(driver, saved) {
33
+ var _a;
34
+ if (driver === null || driver === void 0 ? void 0 : driver.restoreInteractionCheckpoints) {
35
+ driver.restoreInteractionCheckpoints(saved);
36
+ }
37
+ else {
38
+ (_a = driver === null || driver === void 0 ? void 0 : driver.restoreInteractionCheckpoint) === null || _a === void 0 ? void 0 : _a.call(driver, saved[saved.length - 1]);
39
+ }
40
+ }
14
41
  /**
15
42
  * Backstop for a slow/hung persistence provider on startup restore (GENC-1351
16
43
  * §6). Deliberately long: silently losing a restorable session is a far worse
@@ -79,6 +106,12 @@ export class SessionPersister {
79
106
  * the "boundary unmoved" skip below can never swallow the stamp itself (GENC-1511).
80
107
  */
81
108
  this._interruptedStamped = false;
109
+ /**
110
+ * The pin the current episode's frozen write carried, the other half of the "boundary
111
+ * unmoved" skip key. A pin change on its own moves no boundary, but the frozen snapshot
112
+ * still has to carry the new pin, or a reload restores the old one (GENC-1737).
113
+ */
114
+ this._frozenPinnedAgentName = null;
82
115
  /** Consecutive failed saves; reset by any success. GENC-1511. */
83
116
  this._saveFailures = 0;
84
117
  /** Whether this broken episode has already been reported to the host. */
@@ -297,7 +330,7 @@ export class SessionPersister {
297
330
  */
298
331
  persistSession() {
299
332
  return __awaiter(this, void 0, void 0, function* () {
300
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
333
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
301
334
  const { provider, enabled } = this.deps.getPersistence();
302
335
  if (!enabled || !provider)
303
336
  return;
@@ -397,7 +430,10 @@ export class SessionPersister {
397
430
  // it re-arms the moment the boundary moves, and the resumable path below clears it,
398
431
  // so it can never become the one-way "never write again" state it replaces. It also
399
432
  // drops the `provider.load` this branch used to issue on every single autosave.
400
- if (this._persistedMessages === frozen.messages.length && this._interruptedStamped) {
433
+ // The pin is part of the key too: changing it moves no boundary, but is new content.
434
+ if (this._persistedMessages === frozen.messages.length &&
435
+ this._interruptedStamped &&
436
+ this._frozenPinnedAgentName === frozen.pinnedAgentName) {
401
437
  return;
402
438
  }
403
439
  this.logMeta('persistence.suppressed', {
@@ -410,6 +446,7 @@ export class SessionPersister {
410
446
  yield provider.save(key, Object.assign(Object.assign({}, frozen), { interrupted: { message: resumeMessage, prompt: resumePrompt } }));
411
447
  this._persistedMessages = frozen.messages.length;
412
448
  this._interruptedStamped = true;
449
+ this._frozenPinnedAgentName = frozen.pinnedAgentName;
413
450
  this.recordSaveOutcome(true, '', frozen.savedAt);
414
451
  logger.debug('Flow non-resumable — froze snapshot + stamped interrupted marker', { key });
415
452
  }
@@ -458,7 +495,7 @@ export class SessionPersister {
458
495
  agentSnapshots,
459
496
  condensePolicies: this.condensePoliciesToPersist(driver, messages),
460
497
  autopilot: (_h = autopilotOf(driver)) === null || _h === void 0 ? void 0 : _h.getPersistedMode(),
461
- checkpoint: (_j = driver === null || driver === void 0 ? void 0 : driver.getInteractionCheckpoint) === null || _j === void 0 ? void 0 : _j.call(driver),
498
+ checkpoints: checkpointsOf(driver),
462
499
  });
463
500
  // Observability (GENC-1351): record what each autosave captured for stateful
464
501
  // agents — `agents: []` here means no machine snapshot was taken (the bug to
@@ -474,7 +511,7 @@ export class SessionPersister {
474
511
  const captured = {
475
512
  messages: messages.length,
476
513
  agents: Object.keys(agentSnapshots),
477
- active: (_k = liveActive === null || liveActive === void 0 ? void 0 : liveActive.name) !== null && _k !== void 0 ? _k : null,
514
+ active: (_j = liveActive === null || liveActive === void 0 ? void 0 : liveActive.name) !== null && _j !== void 0 ? _j : null,
478
515
  hasSerialize: !!(liveActive === null || liveActive === void 0 ? void 0 : liveActive.serialize),
479
516
  agentSnapshots,
480
517
  };
@@ -493,7 +530,7 @@ export class SessionPersister {
493
530
  // means the body never reached the wire at all, because a provider builds its
494
531
  // request body inside the `fetch` init, so a throw while serialising creates no
495
532
  // request and leaves no server-side trace.
496
- this.recordSaveOutcome(false, (_l = e === null || e === void 0 ? void 0 : e.message) !== null && _l !== void 0 ? _l : String(e));
533
+ this.recordSaveOutcome(false, (_k = e === null || e === void 0 ? void 0 : e.message) !== null && _k !== void 0 ? _k : String(e));
497
534
  // Report straight away rather than waiting for the next attempt: we are on the resumable
498
535
  // path, so a reload is safe NOW, and a one-cycle delay is a second of extra exposure for
499
536
  // no benefit.
@@ -510,8 +547,8 @@ export class SessionPersister {
510
547
  agents: captured.agents,
511
548
  active: captured.active,
512
549
  hasSerialize: captured.hasSerialize,
513
- error: (_m = e === null || e === void 0 ? void 0 : e.name) !== null && _m !== void 0 ? _m : typeof e,
514
- message: (_o = e === null || e === void 0 ? void 0 : e.message) !== null && _o !== void 0 ? _o : String(e),
550
+ error: (_l = e === null || e === void 0 ? void 0 : e.name) !== null && _l !== void 0 ? _l : typeof e,
551
+ message: (_m = e === null || e === void 0 ? void 0 : e.message) !== null && _m !== void 0 ? _m : String(e),
515
552
  });
516
553
  logger.error('Session save failed:', e);
517
554
  }
@@ -530,7 +567,7 @@ export class SessionPersister {
530
567
  */
531
568
  restore() {
532
569
  return __awaiter(this, void 0, void 0, function* () {
533
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
570
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
534
571
  const { provider } = this.deps.getPersistence();
535
572
  if (!provider)
536
573
  return undefined;
@@ -590,11 +627,11 @@ export class SessionPersister {
590
627
  driver === null || driver === void 0 ? void 0 : driver.primeRestoredAgentState(snapshot.agentSnapshots);
591
628
  // The autopilot's mode waits for its flow to re-activate; restoring it starts nothing.
592
629
  (_d = autopilotOf(driver)) === null || _d === void 0 ? void 0 : _d.restorePersistedMode(snapshot.autopilot);
593
- // A long action the reload cut waits for the next request of its widget type (§4.12) — but
594
- // only when its flow is re-activated above. A flow left behind (interrupted, or an owner this
595
- // driver does not know) never ends, so nothing would clear its checkpoint, and the next request
596
- // of that widget type would take over the abandoned run's work.
597
- (_e = driver === null || driver === void 0 ? void 0 : driver.restoreInteractionCheckpoint) === null || _e === void 0 ? void 0 : _e.call(driver, flowOwner ? snapshot.checkpoint : undefined);
630
+ // Long actions the reload cut wait for requests of their widget types (§4.12) — but only when
631
+ // their flow is re-activated above. A flow left behind (interrupted, or an owner this driver
632
+ // does not know) never ends, so nothing would clear its checkpoints, and the next request of
633
+ // such a widget type would take over the abandoned run's work.
634
+ restoreCheckpoints(driver, flowOwner ? savedCheckpoints(snapshot) : []);
598
635
  // Seed the carry-forward cache so the immediate post-restore autosave (fired
599
636
  // by the history change below, before any agent re-activates) preserves the
600
637
  // machine snapshot instead of overwriting it with an empty one (GENC-1351).
@@ -667,14 +704,14 @@ export class SessionPersister {
667
704
  }
668
705
  const messages = [...trimmed, ...trailers];
669
706
  ref.actions.aiAssistant.loadSession(toLoadSessionPayload(Object.assign(Object.assign({}, snapshot), { messages })));
670
- (_f = driver === null || driver === void 0 ? void 0 : driver.loadHistory) === null || _f === void 0 ? void 0 : _f.call(driver, [...messages]);
707
+ (_e = driver === null || driver === void 0 ? void 0 : driver.loadHistory) === null || _e === void 0 ? void 0 : _e.call(driver, [...messages]);
671
708
  // Re-arm the condense policies that had not fired at save time (GENC-1632) — AFTER
672
709
  // `loadHistory`, because the driver keeps only entries whose tool call is in the history it
673
710
  // now holds, which is how an entry for a call `trimToRestorableBoundary` cut away is dropped
674
711
  // rather than resurrected. A snapshot from before the field existed has none, so this is a
675
712
  // no-op and the restore is exactly what it was. Timing against the agent's re-activation is
676
713
  // the driver's problem, not ours: it defers the activation stamp to the next `installAgent`.
677
- const condenseRestore = (_g = driver === null || driver === void 0 ? void 0 : driver.restoreCondensePolicies) === null || _g === void 0 ? void 0 : _g.call(driver, snapshot.condensePolicies);
714
+ const condenseRestore = (_f = driver === null || driver === void 0 ? void 0 : driver.restoreCondensePolicies) === null || _f === void 0 ? void 0 : _f.call(driver, snapshot.condensePolicies);
678
715
  // Observability (GENC-1351, counts refined for GENC-1632 review): record exactly what the
679
716
  // restore primed, so a post-reload debug-log export shows whether a stateful agent's snapshot
680
717
  // actually came back (meta events reset on reload, so this is the only window onto the
@@ -686,7 +723,7 @@ export class SessionPersister {
686
723
  // are left OFF the object (not zeroed) when there is no driver or it predates this method, so
687
724
  // that case can't be misread as "re-armed none" either.
688
725
  this.logMeta('persistence.restored', {
689
- agents: Object.keys((_h = snapshot.agentSnapshots) !== null && _h !== void 0 ? _h : {}),
726
+ agents: Object.keys((_g = snapshot.agentSnapshots) !== null && _g !== void 0 ? _g : {}),
690
727
  condensePolicies: Object.assign({ stored: Array.isArray(snapshot.condensePolicies) ? snapshot.condensePolicies.length : 0 }, condenseRestore),
691
728
  agentSnapshots: snapshot.agentSnapshots,
692
729
  pinnedAgentName: snapshot.pinnedAgentName,
@@ -716,8 +753,8 @@ export class SessionPersister {
716
753
  //
717
754
  // On the driver itself, not a narrowed orchestrator (GENC-1660): both members are on
718
755
  // `AiDriver` and every decorator forwards them, so this reaches the routing whatever wraps it.
719
- driver === null || driver === void 0 ? void 0 : driver.setPinnedAgent((_j = snapshot.pinnedAgentName) !== null && _j !== void 0 ? _j : null);
720
- driver === null || driver === void 0 ? void 0 : driver.setFlowOwner((_k = snapshot.flowOwnerAgentName) !== null && _k !== void 0 ? _k : null);
756
+ driver === null || driver === void 0 ? void 0 : driver.setPinnedAgent((_h = snapshot.pinnedAgentName) !== null && _h !== void 0 ? _h : null);
757
+ driver === null || driver === void 0 ? void 0 : driver.setFlowOwner((_j = snapshot.flowOwnerAgentName) !== null && _j !== void 0 ? _j : null);
721
758
  if (flowOwner) {
722
759
  this.logMeta('persistence.resume-planned', {
723
760
  flowOwner,
@@ -13,8 +13,8 @@ export const PERSISTED_SESSION_VERSION = 1;
13
13
  * @internal
14
14
  */
15
15
  export function createPersistedSession(input) {
16
- var _a, _b;
17
- return Object.assign(Object.assign(Object.assign({ version: PERSISTED_SESSION_VERSION, savedAt: new Date().toISOString(), host: input.host, sessionKey: input.sessionKey, messages: input.messages, activeAgentName: input.activeAgentName, pinnedAgentName: input.pinnedAgentName, flowOwnerAgentName: input.flowOwnerAgentName, sessionCostUsd: input.sessionCostUsd, contextTokens: input.contextTokens, contextLimit: input.contextLimit, activeModel: input.activeModel, activeProviderName: input.activeProviderName, agentSnapshots: (_a = input.agentSnapshots) !== null && _a !== void 0 ? _a : {} }, (((_b = input.condensePolicies) === null || _b === void 0 ? void 0 : _b.length) ? { condensePolicies: input.condensePolicies } : {})), (input.autopilot ? { autopilot: input.autopilot } : {})), (input.checkpoint ? { checkpoint: input.checkpoint } : {}));
16
+ var _a, _b, _c;
17
+ return Object.assign(Object.assign(Object.assign({ version: PERSISTED_SESSION_VERSION, savedAt: new Date().toISOString(), host: input.host, sessionKey: input.sessionKey, messages: input.messages, activeAgentName: input.activeAgentName, pinnedAgentName: input.pinnedAgentName, flowOwnerAgentName: input.flowOwnerAgentName, sessionCostUsd: input.sessionCostUsd, contextTokens: input.contextTokens, contextLimit: input.contextLimit, activeModel: input.activeModel, activeProviderName: input.activeProviderName, agentSnapshots: (_a = input.agentSnapshots) !== null && _a !== void 0 ? _a : {} }, (((_b = input.condensePolicies) === null || _b === void 0 ? void 0 : _b.length) ? { condensePolicies: input.condensePolicies } : {})), (input.autopilot ? { autopilot: input.autopilot } : {})), (((_c = input.checkpoints) === null || _c === void 0 ? void 0 : _c.length) ? { checkpoints: input.checkpoints } : {}));
18
18
  }
19
19
  /**
20
20
  * Resolve the notice text + pre-fill prompt for an interrupted (non-resumable) flow