@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
@@ -2,11 +2,12 @@ import { __awaiter } from "tslib";
2
2
  import { NOOP_ACTIVITY_BUS } from '../channel/ai-activity-bus';
3
3
  import { ChatDriver } from '../components/chat-driver/chat-driver';
4
4
  import { clearSession, getMetaEvents, recordMetaEvent } from '../state/debug-event-log';
5
+ import { checkArgs, exampleArgs, unavailableReason } from '../state/decision-surface';
5
6
  import { buildTimelineEntries } from '../state/persistence/build-timeline-entries';
6
7
  import { logger } from '../utils/logger';
7
8
  import { sumUsage } from '../utils/sum-usage';
8
9
  import { AUTOPILOT_TOOL_DEFINITIONS, HAND_BACK, WIDGET_ACT, WIDGET_READ } from './autopilot-tools';
9
- import { renderActions, renderDecision, renderQuestion, visibleTranscript, } from './decision-message';
10
+ import { anyActionable, capRead, renderActions, renderDecision, renderQuestion, visibleTranscript, } from './decision-message';
10
11
  /** Model calls a decision may take before it is handed back, unless the config says otherwise. */
11
12
  const DEFAULT_MAX_ITERATIONS_PER_DECISION = 6;
12
13
  /** The autopilot's own history, in characters, past which it is rebuilt short (§4.7, N3). */
@@ -82,12 +83,43 @@ function readFrom(history, seen) {
82
83
  }
83
84
  return undefined;
84
85
  }
86
+ /**
87
+ * `widget_act`'s `fields`, parsed leniently: an object is taken as it is (a model may send one
88
+ * despite the schema's string), and a Markdown code fence around the JSON is stripped.
89
+ */
90
+ export function parseFields(fields) {
91
+ if (typeof fields === 'object')
92
+ return { ok: true, value: fields };
93
+ if (typeof fields !== 'string')
94
+ return { ok: false };
95
+ const fenced = /^\s*```[a-zA-Z]*\s*\n?([\s\S]*?)\n?\s*```\s*$/.exec(fields);
96
+ try {
97
+ return { ok: true, value: JSON.parse(fenced ? fenced[1] : fields) };
98
+ }
99
+ catch (_a) {
100
+ return { ok: false };
101
+ }
102
+ }
103
+ /**
104
+ * How to send `fields` for `action`, as a correctly escaped example: the whole `widget_act` call,
105
+ * with `fields` a JSON object inside a string, built from the action's schema where it has one.
106
+ */
107
+ export function fieldsExample(action, schema) {
108
+ if (!schema)
109
+ return 'Send fields as a JSON object, as text.';
110
+ const call = JSON.stringify({ action, fields: JSON.stringify(exampleArgs(schema)) });
111
+ return `Send them as a JSON object inside a string, e.g. widget_act(${call}).`;
112
+ }
85
113
  /** Resolve a static-or-function config field against the working agent's live state. */
86
114
  const resolveWith = (input, ctx, state) => __awaiter(void 0, void 0, void 0, function* () {
87
115
  return typeof input === 'function'
88
116
  ? input(Object.assign(Object.assign({}, ctx), { state }))
89
117
  : input;
90
118
  });
119
+ /** Whether the decision in progress is past its step's refinement limit: refining is withdrawn. */
120
+ const refiningWithheld = (current) => { var _a, _b; return ((_b = (_a = current.refinementsLeft) === null || _a === void 0 ? void 0 : _a.call(current)) !== null && _b !== void 0 ? _b : Number.POSITIVE_INFINITY) <= 0; };
121
+ /** The refinements left to show, or `undefined` when the step has no limit. */
122
+ const refinementsToShow = (current) => { var _a; return (_a = current.refinementsLeft) === null || _a === void 0 ? void 0 : _a.call(current); };
91
123
  /**
92
124
  * One autopilot for one flow (GENC-1660): its own `ChatDriver`, its own history, and the last
93
125
  * message of what the person has seen that it was told about. Each decision is one short turn on
@@ -108,6 +140,8 @@ export class AutopilotSession {
108
140
  this.queue = Promise.resolve();
109
141
  /** Its own messages a size-bounded rebuild dropped, kept for the debug log. */
110
142
  this.archived = [];
143
+ /** The widget tools, by component name; filled once, by `widgetTools`. */
144
+ this.toolsByWidget = new Map();
111
145
  const { config } = deps.binding;
112
146
  sessionCount += 1;
113
147
  this.ownKey = `${deps.sessionKey}::autopilot::${deps.agentName}::${sessionCount}`;
@@ -136,15 +170,19 @@ export class AutopilotSession {
136
170
  const surface = opened.ctx.surface;
137
171
  if (!surface || opened.ctx.heldBy !== this.deps.claimant)
138
172
  return { kind: 'aborted' };
173
+ // Sent even when nothing on it can be done — a gate whose controller says it is asking, with
174
+ // every action unavailable: the decision lists them with their reasons and says the only way
175
+ // out is to hand it back, which stays open then even after "decide it yourself".
139
176
  const decision = renderDecision({
140
177
  interactionId: opened.interactionId,
141
178
  componentName: opened.componentName,
142
179
  data: opened.data,
143
180
  surface,
144
181
  decideYourself: !options.allowHandBack,
145
- withholdReply: !options.allowReply,
182
+ withholdRefining: refiningWithheld(options),
183
+ refinementsLeft: refinementsToShow(options),
146
184
  });
147
- return this.runTurn(Object.assign(Object.assign({}, options), { opened, numbering: decision.numbering }), decision.text, opened.interactionId);
185
+ return this.runTurn(Object.assign(Object.assign({}, options), { opened, numbering: decision.numbering }), decision.text, opened.interactionId, decision.actionable ? {} : { nothingEnabled: true });
148
186
  }));
149
187
  }
150
188
  /**
@@ -159,7 +197,7 @@ export class AutopilotSession {
159
197
  return this.enqueue(() => __awaiter(this, void 0, void 0, function* () {
160
198
  if (options.stillWanted && !options.stillWanted())
161
199
  return { kind: 'aborted' };
162
- return this.runTurn({ allowHandBack: options.allowHandBack, allowReply: true, question, numbering: [] }, renderQuestion(question, { decideYourself: !options.allowHandBack }));
200
+ return this.runTurn({ allowHandBack: options.allowHandBack, question, numbering: [] }, renderQuestion(question, { decideYourself: !options.allowHandBack }));
163
201
  }));
164
202
  }
165
203
  /**
@@ -223,8 +261,8 @@ export class AutopilotSession {
223
261
  * calls. Books what it cost to `interactionId`; for a written question, which has none, returns
224
262
  * it on the outcome for the driver to book on its reply.
225
263
  */
226
- runTurn(current, decisionText, interactionId) {
227
- return __awaiter(this, void 0, void 0, function* () {
264
+ runTurn(current_1, decisionText_1, interactionId_1) {
265
+ return __awaiter(this, arguments, void 0, function* (current, decisionText, interactionId, sentDetail = {}) {
228
266
  var _a, _b, _c, _d, _e, _f, _g;
229
267
  // Past its budget, the autopilot's own history is rebuilt: dropped, and replaced by a short-form
230
268
  // digest of everything the person saw. Its first decision in a flow — including the first after a
@@ -266,7 +304,7 @@ export class AutopilotSession {
266
304
  decisionText,
267
305
  ].join('\n');
268
306
  this.current = current;
269
- recordMetaEvent(this.deps.sessionKey, 'autopilot.decision-sent', Object.assign(Object.assign({}, (interactionId ? { interactionId } : { question: true })), { agent: this.deps.agentName, chars: message.length }));
307
+ recordMetaEvent(this.deps.sessionKey, 'autopilot.decision-sent', Object.assign(Object.assign(Object.assign({}, (interactionId ? { interactionId } : { question: true })), { agent: this.deps.agentName, chars: message.length }), sentDetail));
270
308
  const before = this.driver.getRawHistory().length;
271
309
  // The per-decision spend cap, checked as each model call lands: past it, the decision is handed
272
310
  // back rather than finished at any price.
@@ -317,17 +355,39 @@ export class AutopilotSession {
317
355
  return outcome;
318
356
  });
319
357
  }
320
- /** The autopilot as an agent: its config's resolvers bound to the working agent's state. */
358
+ /**
359
+ * The autopilot as an agent: its config's resolvers bound to the working agent's state. Its tools
360
+ * — the fixed three, the config's own, and its widget tools — are fixed here, once, sorted by
361
+ * name, so every decision sends the same list and the cached prefix holds.
362
+ */
321
363
  agentConfig() {
322
364
  var _a, _b, _c;
323
365
  const { binding } = this.deps;
324
366
  const { config } = binding;
367
+ const ownDefinitions = (_b = (_a = config.tools) === null || _a === void 0 ? void 0 : _a.definitions) !== null && _b !== void 0 ? _b : [];
368
+ const widget = this.widgetTools([
369
+ ...AUTOPILOT_TOOL_DEFINITIONS.map((d) => d.name),
370
+ ...ownDefinitions.map((d) => d.name),
371
+ ]);
372
+ // A plain comparison, not `localeCompare`: the order must not depend on the browser's locale.
373
+ const byName = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
374
+ const agentTail = config.tailContext
375
+ ? (ctx) => __awaiter(this, void 0, void 0, function* () { var _a; return (_a = (yield resolveWith(config.tailContext, ctx, binding.state()))) !== null && _a !== void 0 ? _a : ''; })
376
+ : undefined;
325
377
  return {
326
378
  name: `${this.deps.agentName} autopilot`,
327
379
  description: `Answers ${this.deps.agentName}'s questions on the user's behalf.`,
328
380
  systemPrompt: (ctx) => __awaiter(this, void 0, void 0, function* () { var _a; return (_a = (yield resolveWith(config.systemPrompt, ctx, binding.state()))) !== null && _a !== void 0 ? _a : ''; }),
329
- tailContext: config.tailContext
330
- ? (ctx) => __awaiter(this, void 0, void 0, function* () { var _a; return (_a = (yield resolveWith(config.tailContext, ctx, binding.state()))) !== null && _a !== void 0 ? _a : ''; })
381
+ // The platform's line on the widget tools usable now goes in front of the agent's own tail,
382
+ // which follows unchanged. Re-read on every model call and never stored, so it cannot go
383
+ // stale in history the way a line in the decision message would.
384
+ tailContext: widget.definitions.length || agentTail
385
+ ? (ctx) => __awaiter(this, void 0, void 0, function* () {
386
+ var _a;
387
+ return [this.widgetToolsLine(), (_a = (yield (agentTail === null || agentTail === void 0 ? void 0 : agentTail(ctx)))) !== null && _a !== void 0 ? _a : '']
388
+ .filter((part) => part.trim())
389
+ .join('\n\n');
390
+ })
331
391
  : undefined,
332
392
  provider: typeof config.provider === 'function'
333
393
  ? (ctx) => __awaiter(this, void 0, void 0, function* () {
@@ -337,10 +397,102 @@ export class AutopilotSession {
337
397
  : config.provider,
338
398
  // The prefix (tools, system, stored history) is stable by design, so cache all of it.
339
399
  cachePolicy: { scope: 'history' },
340
- toolDefinitions: [...AUTOPILOT_TOOL_DEFINITIONS, ...((_b = (_a = config.tools) === null || _a === void 0 ? void 0 : _a.definitions) !== null && _b !== void 0 ? _b : [])],
341
- toolHandlers: Object.assign(Object.assign({}, (_c = config.tools) === null || _c === void 0 ? void 0 : _c.handlers), this.fixedHandlers()),
400
+ toolDefinitions: [
401
+ ...AUTOPILOT_TOOL_DEFINITIONS,
402
+ ...ownDefinitions,
403
+ ...widget.definitions,
404
+ ].sort(byName),
405
+ toolHandlers: Object.assign(Object.assign(Object.assign({}, (_c = config.tools) === null || _c === void 0 ? void 0 : _c.handlers), widget.handlers), this.fixedHandlers()),
342
406
  };
343
407
  }
408
+ /**
409
+ * The config's widget tools as tools: their definitions and their handlers, each routed to the
410
+ * interaction of its widget type being decided. A name already `taken` (a fixed tool, one of the
411
+ * config's own, or an earlier widget tool) is skipped with a warning: `defineAutopilot` refuses
412
+ * such a config, so only one built by hand gets here.
413
+ */
414
+ widgetTools(taken) {
415
+ var _a, _b;
416
+ const names = new Set(taken);
417
+ const definitions = [];
418
+ const handlers = {};
419
+ for (const set of (_a = this.deps.binding.config.widgetTools) !== null && _a !== void 0 ? _a : []) {
420
+ for (const [name, spec] of Object.entries(set.tools)) {
421
+ if (names.has(name)) {
422
+ logger.warn(`AutopilotSession: the widget tool "${name}" is named twice; skipping it.`);
423
+ continue;
424
+ }
425
+ names.add(name);
426
+ definitions.push(Object.assign(Object.assign({}, spec.definition), { name }));
427
+ handlers[name] = this.widgetToolHandler(set.componentName, name, spec);
428
+ const forWidget = (_b = this.toolsByWidget.get(set.componentName)) !== null && _b !== void 0 ? _b : [];
429
+ this.toolsByWidget.set(set.componentName, [...forWidget, { name, spec }]);
430
+ }
431
+ }
432
+ return { definitions, handlers };
433
+ }
434
+ /**
435
+ * The platform's line in the tail: the widget tools usable now — those of the widget the decision
436
+ * in progress is on, less any that say they are unavailable — and nothing when there are none.
437
+ */
438
+ widgetToolsLine() {
439
+ var _a;
440
+ const opened = (_a = this.current) === null || _a === void 0 ? void 0 : _a.opened;
441
+ const tools = opened ? this.toolsByWidget.get(opened.componentName) : undefined;
442
+ const controller = opened === null || opened === void 0 ? void 0 : opened.ctx.controller;
443
+ if (!(tools === null || tools === void 0 ? void 0 : tools.length) || controller === undefined)
444
+ return '';
445
+ const usable = tools
446
+ .filter(({ spec }) => unavailableReason(spec.unavailable, controller) === undefined)
447
+ .map(({ name }) => name)
448
+ .sort();
449
+ return usable.length ? `Tools for the widget open now: ${usable.join(', ')}.` : '';
450
+ }
451
+ /**
452
+ * One widget tool's handler: routed to the interaction of `componentName` the autopilot is
453
+ * deciding and holds, its controller passed to `run`, its arguments checked first. Refused, with a
454
+ * reason, when no such interaction is in progress. Its result is capped, and leaves the history
455
+ * at the end of the decision, as a `widget_read` does.
456
+ */
457
+ widgetToolHandler(componentName, name, spec) {
458
+ return (args, ctx) => __awaiter(this, void 0, void 0, function* () {
459
+ var _a, _b, _c;
460
+ const opened = (_a = this.current) === null || _a === void 0 ? void 0 : _a.opened;
461
+ if (!opened || opened.componentName !== componentName) {
462
+ const now = opened ? ` The widget open now is "${opened.componentName}".` : '';
463
+ return `Not available: no "${componentName}" widget is open now, so ${name} cannot be used.${now}`;
464
+ }
465
+ if (opened.ctx.heldBy !== this.deps.claimant) {
466
+ return `Not available: the "${componentName}" widget is with the user now.`;
467
+ }
468
+ const controller = opened.ctx.controller;
469
+ if (controller === undefined) {
470
+ return `Not available: the "${componentName}" widget has nothing to read from.`;
471
+ }
472
+ const why = unavailableReason(spec.unavailable, controller);
473
+ if (why !== undefined)
474
+ return `Not available right now: ${name}: ${why}.`;
475
+ const problem = checkArgs(args !== null && args !== void 0 ? args : {}, spec.definition.parameters);
476
+ if (problem)
477
+ return `Not done: ${name}: ${problem}`;
478
+ let output;
479
+ try {
480
+ output = yield spec.run(controller, (args !== null && args !== void 0 ? args : {}));
481
+ }
482
+ catch (e) {
483
+ return `Could not read: ${e instanceof Error ? e.message : String(e)}`;
484
+ }
485
+ const result = capRead(typeof output === 'string' ? output : ((_b = JSON.stringify(output)) !== null && _b !== void 0 ? _b : 'null'));
486
+ // Like a read: it serves the decision it was made for, and is stale once that is made.
487
+ (_c = ctx.condenseWhen) === null || _c === void 0 ? void 0 : _c.call(ctx, {
488
+ on: { kind: 'turnEnd' },
489
+ response: {
490
+ replaceWith: `[An earlier ${name} result, ${result.length} characters, for a decision that has since been made.]`,
491
+ },
492
+ });
493
+ return result;
494
+ });
495
+ }
344
496
  /** `widget_read`, `widget_act` and `hand_back`, acting on the decision in progress. */
345
497
  fixedHandlers() {
346
498
  const relist = () => {
@@ -352,28 +504,44 @@ export class AutopilotSession {
352
504
  const surface = (_a = current === null || current === void 0 ? void 0 : current.opened) === null || _a === void 0 ? void 0 : _a.ctx.surface;
353
505
  if (!current || !surface)
354
506
  return 'There is nothing to decide now.';
355
- const actions = renderActions(surface.actions(), { withholdReply: !current.allowReply });
507
+ const actions = renderActions(surface.actions(), {
508
+ withholdRefining: refiningWithheld(current),
509
+ refinementsLeft: refinementsToShow(current),
510
+ });
356
511
  current.numbering = actions.numbering;
357
512
  return actions.text;
358
513
  };
359
514
  return {
360
515
  [WIDGET_READ]: (args, ctx) => __awaiter(this, void 0, void 0, function* () {
361
- var _a, _b;
516
+ var _a, _b, _c, _d;
362
517
  const current = this.current;
363
518
  if ((current === null || current === void 0 ? void 0 : current.question) !== undefined)
364
519
  return `Question: ${current.question}\n${relist()}`;
365
520
  const surface = (_a = current === null || current === void 0 ? void 0 : current.opened) === null || _a === void 0 ? void 0 : _a.ctx.surface;
366
521
  if (!surface)
367
522
  return 'There is nothing to decide now.';
368
- const view = args === null || args === void 0 ? void 0 : args.view;
369
- // A full-form surface is read by view; a short-form decision has only its facts.
523
+ const asked = args === null || args === void 0 ? void 0 : args.view;
524
+ // A blank view is no view: a model may fill an optional string with "" rather than omit it.
525
+ const view = typeof asked === 'string' && asked.trim() ? asked.trim() : undefined;
526
+ const names = Object.keys((_b = surface.views) !== null && _b !== void 0 ? _b : {});
527
+ // A view the surface does not list is refused, naming those it does, so the model corrects
528
+ // itself rather than taking the default (or nothing) as the view it asked for. A surface
529
+ // that lists no views is read as before.
530
+ if (view !== undefined && names.length && !names.includes(view)) {
531
+ return `No view "${view}" here. Views: ${names.join(', ')}.`;
532
+ }
533
+ // A surface with views is read by view (the default without one: a decision's facts, a
534
+ // full-form surface's preview); a short-form decision without views has only its facts.
370
535
  const state = surface.read ? surface.read(view) : surface.facts();
371
- const result = `${JSON.stringify(state)}\n${relist()}`;
536
+ const shown = state === undefined
537
+ ? `Nothing to read without a view.${names.length ? ` Views: ${names.join(', ')}.` : ''}`
538
+ : capRead((_c = JSON.stringify(state)) !== null && _c !== void 0 ? _c : 'null');
539
+ const result = `${shown}\n${relist()}`;
372
540
  // A read serves the decision it was made for. Once that turn ends it is stale — the widget
373
541
  // has moved on — so it leaves the autopilot's history as a one-line note rather than riding
374
542
  // every later decision at full size. Not a re-read pointer: reading again would read the
375
543
  // next decision, not this one.
376
- (_b = ctx.condenseWhen) === null || _b === void 0 ? void 0 : _b.call(ctx, {
544
+ (_d = ctx.condenseWhen) === null || _d === void 0 ? void 0 : _d.call(ctx, {
377
545
  on: { kind: 'turnEnd' },
378
546
  response: {
379
547
  replaceWith: `[An earlier read${view ? ` of the "${view}" view` : ''}, ${result.length} characters, for a decision that has since been made.]`,
@@ -382,7 +550,7 @@ export class AutopilotSession {
382
550
  return result;
383
551
  }),
384
552
  [WIDGET_ACT]: (args, ctx) => __awaiter(this, void 0, void 0, function* () {
385
- var _a, _b, _c, _d;
553
+ var _a, _b, _c, _d, _e;
386
554
  const current = this.current;
387
555
  if (!current)
388
556
  return 'There is nothing to decide now.';
@@ -401,47 +569,58 @@ export class AutopilotSession {
401
569
  // A number names an option in the list last sent; a name is a platform-owned action.
402
570
  const byNumber = (value) => /^\d+$/.test(value.trim()) ? current.numbering[Number(value.trim()) - 1] : undefined;
403
571
  const name = (_b = byNumber(String(action !== null && action !== void 0 ? action : ''))) !== null && _b !== void 0 ? _b : String(action !== null && action !== void 0 ? action : '').trim();
404
- if (name === 'reply' && !current.allowReply) {
405
- return `Not done: a written answer is not available for this one; choose an option or hand it back.\n${relist()}`;
572
+ const listed = (_c = opened.ctx.surface) === null || _c === void 0 ? void 0 : _c.actions().find((a) => a.name === name);
573
+ // Past the refinement limit, a refining action is withdrawn: not listed, and refused here.
574
+ if ((listed === null || listed === void 0 ? void 0 : listed.refines) && refiningWithheld(current)) {
575
+ const what = name === 'reply' ? 'a written answer' : `"${name}"`;
576
+ return `Not done: ${what} is not available for this one any more; choose another action or hand it back.\n${relist()}`;
406
577
  }
407
- // A full-form action takes its arguments as `fields`, a JSON object sent as text.
408
- let parsedFields;
409
- if (fields !== undefined && fields !== '') {
410
- try {
411
- parsedFields = JSON.parse(fields);
412
- }
413
- catch (_e) {
414
- return `Not done: fields is not valid JSON.\n${relist()}`;
578
+ // An action taking one free-text argument gets `text`, as `reply` does; a form gets its
579
+ // `fields`, parsed leniently; anything else its options and text, as given.
580
+ let invokeArgs;
581
+ if ((listed === null || listed === void 0 ? void 0 : listed.args) === 'text') {
582
+ invokeArgs = { text };
583
+ }
584
+ else if (fields !== undefined && fields !== null && fields !== '') {
585
+ const parsed = parseFields(fields);
586
+ if (!parsed.ok) {
587
+ return `Not done: fields is not valid JSON. ${fieldsExample(name, listed === null || listed === void 0 ? void 0 : listed.argsSchema)}\n${relist()}`;
415
588
  }
589
+ invokeArgs = parsed.value;
590
+ }
591
+ else {
592
+ invokeArgs = Object.assign(Object.assign({}, (options ? { options: options.map((o) => { var _a; return (_a = byNumber(o)) !== null && _a !== void 0 ? _a : o; }) } : {})), (text !== undefined ? { text } : {}));
416
593
  }
417
- const result = yield opened.hold.invoke(name, parsedFields !== undefined
418
- ? parsedFields
419
- : Object.assign(Object.assign({}, (options ? { options: options.map((o) => { var _a; return (_a = byNumber(o)) !== null && _a !== void 0 ? _a : o; }) } : {})), (text !== undefined ? { text } : {})), { note });
594
+ const result = yield opened.hold.invoke(name, invokeArgs, { note });
420
595
  if (!result.ok) {
421
596
  return `Not done: ${result.message}\n${relist()}`;
422
597
  }
423
- if (name === 'reply')
424
- (_c = current.onReply) === null || _c === void 0 ? void 0 : _c.call(current);
598
+ if (listed === null || listed === void 0 ? void 0 : listed.refines)
599
+ (_d = current.onRefine) === null || _d === void 0 ? void 0 : _d.call(current, name);
425
600
  recordMetaEvent(this.deps.sessionKey, 'autopilot.acted', Object.assign({ interactionId: opened.interactionId, action: name, finished: result.finished }, (note ? { note } : {})));
426
601
  if (result.finished) {
427
602
  current.outcome = { kind: 'acted', action: name };
428
- (_d = ctx.completeSubAgent) === null || _d === void 0 ? void 0 : _d.call(ctx, { acted: name });
603
+ (_e = ctx.completeSubAgent) === null || _e === void 0 ? void 0 : _e.call(ctx, { acted: name });
429
604
  return 'Done.';
430
605
  }
431
606
  const changed = result.output !== undefined ? `\nResult: ${JSON.stringify(result.output)}` : '';
432
607
  return `Done, and it is still open.${changed}\n${relist()}`;
433
608
  }),
434
609
  [HAND_BACK]: (args, ctx) => __awaiter(this, void 0, void 0, function* () {
435
- var _a, _b;
610
+ var _a, _b, _c;
436
611
  const current = this.current;
437
612
  if (!current)
438
613
  return 'There is nothing to decide now.';
439
- if (!current.allowHandBack) {
440
- return 'hand_back is not available: the user asked you to decide this one yourself.';
614
+ // "Decide it yourself" withdraws hand_back, but not when nothing can be done: read now, as
615
+ // the widget stands, since an action may have become available since the decision was sent.
616
+ const surface = (_a = current.opened) === null || _a === void 0 ? void 0 : _a.ctx.surface;
617
+ const nothingEnabled = !!surface && !anyActionable(surface.actions(), refiningWithheld(current));
618
+ if (!current.allowHandBack && !nothingEnabled) {
619
+ return `hand_back is not available: the user asked you to decide this one yourself.\n${relist()}`;
441
620
  }
442
- const reason = String((_a = args.reason) !== null && _a !== void 0 ? _a : '').trim();
621
+ const reason = String((_b = args.reason) !== null && _b !== void 0 ? _b : '').trim();
443
622
  current.outcome = { kind: 'handed-back', reason, trigger: 'model' };
444
- (_b = ctx.completeSubAgent) === null || _b === void 0 ? void 0 : _b.call(ctx, { handedBack: reason });
623
+ (_c = ctx.completeSubAgent) === null || _c === void 0 ? void 0 : _c.call(ctx, { handedBack: reason });
445
624
  return 'Handed to the user.';
446
625
  }),
447
626
  };
@@ -7,13 +7,14 @@ export const HAND_BACK = 'hand_back';
7
7
  /**
8
8
  * The autopilot's three fixed tools (GENC-1660 §4.2, §4.6). Fixed for every decision, so the cached
9
9
  * prefix holds: what varies — the widget, its actions, their arguments — travels in the decision
10
- * message, not here. Plain string and string-array fields only, which every provider accepts
11
- * (critique round 2, N5: Gemini rejects a type-array union).
10
+ * message, not here. An autopilot's own tools and its widget tools join them, the whole list sorted
11
+ * by name and fixed for its session. Plain string and string-array fields only, which every
12
+ * provider accepts (critique round 2, N5: Gemini rejects a type-array union).
12
13
  */
13
14
  export const AUTOPILOT_TOOL_DEFINITIONS = [
14
15
  {
15
16
  name: WIDGET_READ,
16
- description: 'Read the current decision as it stands now: its state (one of its views, if it lists views), 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.',
17
+ 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.',
17
18
  parameters: {
18
19
  type: 'object',
19
20
  properties: {
@@ -23,7 +24,7 @@ export const AUTOPILOT_TOOL_DEFINITIONS = [
23
24
  },
24
25
  {
25
26
  name: WIDGET_ACT,
26
- 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, or "reply" with `text` to answer in your own words. ' +
27
+ 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`. ' +
27
28
  'If it settles the decision, your turn ends. ' +
28
29
  '`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.',
29
30
  parameters: {
@@ -39,10 +40,13 @@ export const AUTOPILOT_TOOL_DEFINITIONS = [
39
40
  items: { type: 'string' },
40
41
  description: 'For "select": the options to choose, by number or label.',
41
42
  },
42
- text: { type: 'string', description: 'For "reply": your answer, in the user\'s place.' },
43
+ text: {
44
+ type: 'string',
45
+ description: 'For "reply" (your answer, in the user\'s place) and any action listed as name({text}): its one argument, as plain text.',
46
+ },
43
47
  fields: {
44
48
  type: 'string',
45
- description: 'For a named action that takes arguments: a JSON object, as text, matching the args schema the decision lists for it.',
49
+ description: 'Only for an action listed as name({fields}): a JSON object, as text, matching the fields schema the decision lists for it.',
46
50
  },
47
51
  note: {
48
52
  type: 'string',
@@ -53,7 +57,7 @@ export const AUTOPILOT_TOOL_DEFINITIONS = [
53
57
  },
54
58
  {
55
59
  name: HAND_BACK,
56
- 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. 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:" — say plainly what you need from them. Never mention an autopilot or a second agent.',
60
+ 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:" — say plainly what you need from them. Never mention an autopilot or a second agent.',
57
61
  parameters: {
58
62
  type: 'object',
59
63
  required: ['reason'],