@genesislcap/ai-assistant 15.40.0 → 15.42.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 (73) hide show
  1. package/dist/ai-assistant.api.json +409 -9
  2. package/dist/ai-assistant.d.ts +196 -6
  3. package/dist/chat-driver.cjs +682 -140
  4. package/dist/chat-driver.cjs.map +3 -3
  5. package/dist/chat-driver.mjs +675 -140
  6. package/dist/chat-driver.mjs.map +3 -3
  7. package/dist/custom-elements.json +1007 -436
  8. package/dist/dts/chat-driver-node.d.ts +2 -2
  9. package/dist/dts/chat-driver-node.d.ts.map +1 -1
  10. package/dist/dts/components/ai-driver/ai-driver.d.ts +4 -0
  11. package/dist/dts/components/ai-driver/ai-driver.d.ts.map +1 -1
  12. package/dist/dts/components/chat-driver/chat-driver.d.ts +121 -4
  13. package/dist/dts/components/chat-driver/chat-driver.d.ts.map +1 -1
  14. package/dist/dts/components/chat-driver/interaction-controller.d.ts.map +1 -1
  15. package/dist/dts/components/chat-driver/turn-failures.d.ts +7 -1
  16. package/dist/dts/components/chat-driver/turn-failures.d.ts.map +1 -1
  17. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts +3 -1
  18. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts.map +1 -1
  19. package/dist/dts/genesis/index.d.ts +2 -1
  20. package/dist/dts/genesis/index.d.ts.map +1 -1
  21. package/dist/dts/genesis/register-genesis-assistant.d.ts +21 -0
  22. package/dist/dts/genesis/register-genesis-assistant.d.ts.map +1 -1
  23. package/dist/dts/genesis/review-model.d.ts +40 -0
  24. package/dist/dts/genesis/review-model.d.ts.map +1 -1
  25. package/dist/dts/genesis/review-payload.d.ts +47 -0
  26. package/dist/dts/genesis/review-payload.d.ts.map +1 -0
  27. package/dist/dts/genesis/write-review/write-review.d.ts +75 -11
  28. package/dist/dts/genesis/write-review/write-review.d.ts.map +1 -1
  29. package/dist/dts/genesis/write-review/write-review.styles.d.ts.map +1 -1
  30. package/dist/dts/genesis/write-review/write-review.template.d.ts.map +1 -1
  31. package/dist/dts/genesis/write-tools.d.ts +49 -0
  32. package/dist/dts/genesis/write-tools.d.ts.map +1 -1
  33. package/dist/dts/genesis/write-turn.d.ts +114 -0
  34. package/dist/dts/genesis/write-turn.d.ts.map +1 -0
  35. package/dist/dts/index.d.ts +2 -0
  36. package/dist/dts/index.d.ts.map +1 -1
  37. package/dist/dts/main/budget-controller.d.ts +12 -2
  38. package/dist/dts/main/budget-controller.d.ts.map +1 -1
  39. package/dist/dts/main/main.d.ts +33 -6
  40. package/dist/dts/main/main.d.ts.map +1 -1
  41. package/dist/dts/react.d.ts +2 -1
  42. package/dist/dts/state/ai-assistant-slice.d.ts +15 -0
  43. package/dist/dts/state/ai-assistant-slice.d.ts.map +1 -1
  44. package/dist/dts/state/session-store.d.ts +1 -0
  45. package/dist/dts/state/session-store.d.ts.map +1 -1
  46. package/dist/dts/suggestions/generate-suggestions.d.ts.map +1 -1
  47. package/dist/dts/utils/history-transform.d.ts.map +1 -1
  48. package/dist/esm/chat-driver-node.js +5 -1
  49. package/dist/esm/components/chat-driver/chat-driver.js +431 -92
  50. package/dist/esm/components/chat-driver/interaction-controller.js +25 -2
  51. package/dist/esm/components/chat-driver/turn-failures.js +9 -2
  52. package/dist/esm/components/orchestrating-driver/orchestrating-driver.js +30 -4
  53. package/dist/esm/genesis/register-genesis-assistant.js +38 -2
  54. package/dist/esm/genesis/review-model.js +47 -1
  55. package/dist/esm/genesis/review-payload.js +18 -0
  56. package/dist/esm/genesis/write-review/write-review.js +225 -40
  57. package/dist/esm/genesis/write-review/write-review.styles.js +18 -0
  58. package/dist/esm/genesis/write-review/write-review.template.js +46 -22
  59. package/dist/esm/genesis/write-tools.js +321 -49
  60. package/dist/esm/genesis/write-turn.js +110 -0
  61. package/dist/esm/main/budget-controller.js +39 -5
  62. package/dist/esm/main/main.js +45 -23
  63. package/dist/esm/state/ai-assistant-slice.js +11 -1
  64. package/dist/esm/state/debug-event-log.js +1 -1
  65. package/dist/esm/suggestions/generate-suggestions.js +4 -1
  66. package/dist/esm/utils/history-transform.js +7 -1
  67. package/dist/react.cjs +14 -2
  68. package/dist/react.mjs +14 -2
  69. package/docs/genesis.md +120 -3
  70. package/docs/migration-GENC-1464.md +12 -2
  71. package/docs/sub_agent.md +21 -4
  72. package/package.json +18 -18
  73. package/scripts/smoke-chat-driver-node.mjs +15 -0
@@ -5,21 +5,112 @@ import { opFromName, toolNameOf } from './config';
5
5
  import { fieldKindOf as criteriaKindOf } from './criteria';
6
6
  import { loadEventFields } from './event-fields';
7
7
  import { GENESIS_DATA_SOURCE } from './resource-tools';
8
- import { buildReviewModel, selectedRows } from './review-model';
8
+ import { buildReviewModel, reviewDecisionOf, selectedRows, } from './review-model';
9
+ import { MAX_FEEDBACK_CHARS } from './review-payload';
9
10
  import { createRequestRowSource } from './row-source';
10
11
  import { genesisTypeName } from './type-name';
11
12
  import { commitRows } from './write-commit';
12
13
  import { isCarryOnly, isWholeNumberType, PLATFORM_MAINTAINED, sendableFields, } from './write-payload';
13
14
  import { MAX_WRITE_ROWS, planWrite, stillCurrent, } from './write-plan';
14
15
  import { GENESIS_WRITE_REVIEW } from './write-review/write-review';
16
+ import { createWriteTurns, MAX_CHANGE_ROUNDS, proposalOf, sameProposal, } from './write-turn';
17
+ /**
18
+ * A fresh feedback key: 128 random bits, as hex. See {@link GenesisWriteToolsOptions.feedbackKey}.
19
+ *
20
+ * @internal
21
+ */
22
+ export const mintFeedbackKey = () => Array.from(crypto.getRandomValues(new Uint8Array(FEEDBACK_KEY_BYTES)), (byte) => byte.toString(HEX).padStart(2, '0')).join('');
23
+ /** 128 bits: nothing that could be guessed, and short enough to name in a prompt. */
24
+ const FEEDBACK_KEY_BYTES = 16;
25
+ const HEX = 16;
15
26
  /**
16
27
  * How long a review may stay open. Only one interaction can be in flight at a time, so a review
17
28
  * that never resolves would wedge the assistant for the session; the widget closes read-only and
18
29
  * the handler reports that nothing was written.
19
30
  */
20
31
  const REVIEW_TIMEOUT_MS = 600000;
32
+ /** What a proposal identical to the one the user just asked to change is told. */
33
+ const UNCHANGED_PROPOSAL = 'This is the proposal the user just asked you to change, unchanged. Apply their feedback ' +
34
+ 'first. Nothing was shown or written.';
35
+ /** What a write says when the user stopped the turn before its review was shown. */
36
+ const STOPPED_BEFORE_REVIEW = 'The user stopped this turn. Nothing was shown or written.';
37
+ /** What a write says when the user stopped the turn while its review was open. */
38
+ const STOPPED_AFTER_REVIEW = 'The user stopped this turn. Nothing was written.';
39
+ /** What an approved row says when the user stopped the turn before it was sent. */
40
+ const STOPPED_ROW = 'Not written: the user stopped the turn.';
21
41
  /** The `REASON` the event carries. Composed here, never by the model: it is an audit record. */
22
42
  const APPROVAL_REASON = 'Approved by the user in the assistant write review';
43
+ /** A string that ends in the first half of a surrogate pair: half an emoji, say. */
44
+ const ENDS_IN_HIGH_SURROGATE = /[\uD800-\uDBFF]$/;
45
+ /**
46
+ * The feedback text as it travels: trimmed already, cut if it runs over, and saying so.
47
+ *
48
+ * @remarks
49
+ * The review's text area already stops at the same number; this holds for a host that answers the
50
+ * review some other way. Counted in UTF-16 units, as `maxlength` counts them. A cut between the two
51
+ * halves of a surrogate pair would leave half a character — not text, and sent on as a lone
52
+ * `\ud83d` escape — so it moves back one unit to keep the whole character out.
53
+ */
54
+ const boundedFeedback = (text) => {
55
+ if (text.length <= MAX_FEEDBACK_CHARS)
56
+ return text;
57
+ const cut = text.slice(0, MAX_FEEDBACK_CHARS);
58
+ return `${ENDS_IN_HIGH_SURROGATE.test(cut) ? cut.slice(0, -1) : cut}… (cut)`;
59
+ };
60
+ /** What the result says about an answer that wrote nothing: one summary, one line per row. */
61
+ const DECLINED = {
62
+ denied: {
63
+ summary: 'The user denied this write. Nothing was written.',
64
+ row: 'The user denied this write, so nothing was written for it.',
65
+ },
66
+ changes_requested: {
67
+ summary: 'The user asked for changes. Nothing was written.',
68
+ row: 'The user asked for changes, so nothing was written for it.',
69
+ },
70
+ timed_out: {
71
+ summary: 'The review closed before it was answered. Nothing was written.',
72
+ row: 'The review closed before it was answered, so nothing was written for it.',
73
+ },
74
+ };
75
+ /**
76
+ * What the model should do after an answer that wrote nothing: fixed sentences, chosen here and
77
+ * never taken from data, because the rest of the result is data the model is told not to follow.
78
+ */
79
+ const nextAfter = (read, changeRequests, lock) => {
80
+ switch (read.decision) {
81
+ case 'changes_requested':
82
+ if (changeRequests > MAX_CHANGE_ROUNDS) {
83
+ return ('That was the last round of changes this turn. This tool will refuse another ' +
84
+ 'proposal; ask the user in chat how to proceed.');
85
+ }
86
+ return [
87
+ 'Propose this write again through this tool, changed as userFeedback asks and in nothing ' +
88
+ 'else. It opens a fresh review, and nothing is written until the user approves it. If ' +
89
+ 'the request is unclear, ask the user in chat instead.',
90
+ `You may revise it ${MAX_CHANGE_ROUNDS - changeRequests + 1} more time(s) in this turn.`,
91
+ // Said plainly because a ticked row reads like a chosen one: it is not, and a model that
92
+ // took it as approval would drop the rows the user did not tick from the next proposal,
93
+ // or write them without the review.
94
+ ...(read.rowsTicked.length
95
+ ? [
96
+ 'userFeedback.rowsTicked lists the rows the user had ticked when asking. It does ' +
97
+ 'NOT approve them, and nothing was written. Propose every row you still intend ' +
98
+ 'to write again; each needs approval in the fresh review.',
99
+ ]
100
+ : []),
101
+ ].join(' ');
102
+ case 'timed_out':
103
+ return 'Do not propose it again unless the user asks.';
104
+ default:
105
+ // A denial locks the table (see locksOf), and the model is told which tools that stops.
106
+ return (lock === null || lock === void 0 ? void 0 : lock.table)
107
+ ? `Do not propose this write, or any other write to ${lock.table}, again unless the ` +
108
+ `user asks for it. For the rest of this turn, ${joined(lock.tools)} will refuse a ` +
109
+ 'proposal.'
110
+ : 'Do not propose this write again unless the user asks for it. This tool will refuse it ' +
111
+ 'for the rest of this turn.';
112
+ }
113
+ };
23
114
  const DATE_LIKE = /^(DATE|DATETIME|LOCALDATE|LOCALDATETIME|TIMESTAMP)$/;
24
115
  /**
25
116
  * Fields a model may SET: what the op can send, minus the key it is not allowed to choose, and
@@ -200,12 +291,59 @@ const readResourceFor = (eventName) => {
200
291
  const match = /^EVENT_(.+)_(?:INSERT|MODIFY|DELETE)$/.exec(eventName);
201
292
  return match ? `REQ_${match[1]}` : undefined;
202
293
  };
294
+ /** `A`, `A and B`, `A, B and C`. */
295
+ const joined = (items) => items.length > 1 ? `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}` : items[0];
296
+ /**
297
+ * What a denial through each event locks, and which write tools share it.
298
+ *
299
+ * @remarks
300
+ * A table: the one the event's name gives (`TRADE` for `EVENT_TRADE_MODIFY`), or, for a modify or
301
+ * delete whose name gives none, the one its row source resolves to (its rowSources entry, `REQ_`
302
+ * stripped) — the table it reads its row from, and so the one it writes. A write tool with
303
+ * neither locks only itself, as every denial locked before. Keyed on the name alone, an
304
+ * `EVENT_TRADE_CANCEL` declared a delete over `REQ_TRADE` stayed free while the model was told
305
+ * every write tool for TRADE would refuse.
306
+ *
307
+ * The other tables a coded handler writes (`customCode.alsoWrites`) never are a key: they are a
308
+ * disclosure, dated to generation, and a lock on them would hold tables the user never saw in the
309
+ * review. Table and event keys cannot meet, so an event cannot pass for a table.
310
+ *
311
+ * `tools` are the events that can get a write tool by the config, sharing the key, in config
312
+ * order: the denial's `next` names them, so it promises exactly what the lock refuses.
313
+ */
314
+ const locksOf = (resources, sourceNameOf) => {
315
+ const keyOf = (resource) => {
316
+ var _a;
317
+ const decided = decideOp(resource);
318
+ const readsRows = decided.op === 'modify' || decided.op === 'delete';
319
+ const source = (_a = readResourceFor(resource.name)) !== null && _a !== void 0 ? _a : (readsRows ? sourceNameOf(resource, decided.op) : undefined);
320
+ // Only a `REQ_` name gives a table: a request a host named anything else (`ALL_TRADES`) is no
321
+ // table this can name, so the event locks only itself rather than a table that is a guess.
322
+ const table = (source === null || source === void 0 ? void 0 : source.startsWith('REQ_')) ? source.slice('REQ_'.length) : undefined;
323
+ return table ? { key: `table:${table}`, table } : { key: `event:${resource.name}` };
324
+ };
325
+ const canWrite = (resource) => {
326
+ const decided = decideOp(resource);
327
+ if (decided.refused)
328
+ return false;
329
+ return decided.op === 'insert' || !!sourceNameOf(resource, decided.op);
330
+ };
331
+ const events = resources.filter((resource) => resource.kind === 'event');
332
+ return (resource) => {
333
+ const lock = keyOf(resource);
334
+ const tools = events
335
+ .filter((event) => canWrite(event) && keyOf(event).key === lock.key)
336
+ .map((event) => event.name);
337
+ return Object.assign(Object.assign({}, lock), { tools });
338
+ };
339
+ };
203
340
  /**
204
341
  * Builds the assistant's write tools from an app's event resources.
205
342
  *
206
343
  * @beta
207
344
  */
208
345
  export function createGenesisWriteTools(resources, options = {}) {
346
+ var _a;
209
347
  const events = resources
210
348
  .filter((r) => r.kind === 'event')
211
349
  .sort((a, b) => a.name.localeCompare(b.name));
@@ -220,12 +358,8 @@ export function createGenesisWriteTools(resources, options = {}) {
220
358
  }
221
359
  };
222
360
  const sources = new Map();
223
- /**
224
- * The resource a modify or delete reads through, or nothing — in which case the event gets no
225
- * tool. A modify with no row to read cannot be built: under replace semantics the fields
226
- * nobody named would be written as null.
227
- */
228
- const sourceFor = (resource, op, connect) => {
361
+ /** The name of the request resource a modify or delete reads through, or none. */
362
+ const sourceNameOf = (resource, op) => {
229
363
  var _a;
230
364
  // The DECIDED op, not `resource.op`: a resource whose op comes from its name would
231
365
  // otherwise be told it needs a row source and handed none.
@@ -239,7 +373,17 @@ export function createGenesisWriteTools(resources, options = {}) {
239
373
  // unchecked override would let a config typo widen that silently, and the pre-image it
240
374
  // fetched would land in the driver's persisted history.
241
375
  const name = configured !== null && configured !== void 0 ? configured : derived;
242
- if (!name || !requestNames.has(name))
376
+ return name && requestNames.has(name) ? name : undefined;
377
+ };
378
+ const lockOf = locksOf(resources, sourceNameOf);
379
+ /**
380
+ * The resource a modify or delete reads through, or nothing — in which case the event gets no
381
+ * tool. A modify with no row to read cannot be built: under replace semantics the fields
382
+ * nobody named would be written as null.
383
+ */
384
+ const sourceFor = (resource, op, connect) => {
385
+ const name = sourceNameOf(resource, op);
386
+ if (!name)
243
387
  return undefined;
244
388
  let source = sources.get(resource.name);
245
389
  if (!source) {
@@ -397,6 +541,9 @@ export function createGenesisWriteTools(resources, options = {}) {
397
541
  }));
398
542
  return inFlight;
399
543
  };
544
+ // One record per turn and event, shared by every handler below: see write-turn.ts.
545
+ const turns = createWriteTurns();
546
+ const feedbackKey = (_a = options.feedbackKey) !== null && _a !== void 0 ? _a : mintFeedbackKey();
400
547
  const toolHandlers = {};
401
548
  for (const resource of events) {
402
549
  toolHandlers[toolNameOf(resource.name)] = (args, context) => __awaiter(this, void 0, void 0, function* () {
@@ -406,6 +553,9 @@ export function createGenesisWriteTools(resources, options = {}) {
406
553
  loadFields,
407
554
  coverage,
408
555
  timeouts: options.timeouts,
556
+ turns,
557
+ feedbackKey,
558
+ lockOf,
409
559
  });
410
560
  });
411
561
  }
@@ -464,7 +614,7 @@ const summarise = (rows) => {
464
614
  };
465
615
  function runWrite(resource, args, context, deps) {
466
616
  return __awaiter(this, void 0, void 0, function* () {
467
- var _a, _b, _c, _d, _e;
617
+ var _a, _b, _c, _d, _e, _f;
468
618
  const fail = (error, message) => ({
469
619
  source: GENESIS_DATA_SOURCE,
470
620
  untrusted: true,
@@ -479,6 +629,17 @@ function runWrite(resource, args, context, deps) {
479
629
  return fail('rejected', `${resource.name} has no write tool because ${decided.refused}.`);
480
630
  }
481
631
  const op = decided.op;
632
+ // A denial holds for the rest of the turn, in code: the prompt asks the model not to propose it
633
+ // again, and this is what happens if it does. Checked before anything is read or shown.
634
+ const turn = deps.turns.of(context.turnSignal, resource.name);
635
+ const lock = deps.lockOf(resource);
636
+ const denial = () => ({
637
+ by: deps.turns.deniedBy(context.turnSignal, lock.key),
638
+ table: lock.table,
639
+ });
640
+ const refusedThisTurn = turnRefusal(turn, resource.name, denial());
641
+ if (refusedThisTurn)
642
+ return fail('rejected', refusedThisTurn);
482
643
  const { connect } = deps;
483
644
  if (!(connect === null || connect === void 0 ? void 0 : connect.isConnected)) {
484
645
  return fail('not_connected', 'The app is not connected to its server, so nothing was written.');
@@ -507,6 +668,8 @@ function runWrite(resource, args, context, deps) {
507
668
  const plan = yield planWrite(args.rows, { op, fields, source });
508
669
  if (plan.status === 'rejected')
509
670
  return fail('rejected', plan.reason);
671
+ // What the identical check below compares: see write-turn.ts.
672
+ const proposal = proposalOf(op, plan.rows, fields);
510
673
  // Every column the review will RENDER needs a type, and for a delete that is more than the
511
674
  // event declares: it shows the whole row, including columns the event never mentions, and
512
675
  // without a type a date is shown to the approver as raw epoch millis — `1789948800000` is not
@@ -568,9 +731,31 @@ function runWrite(resource, args, context, deps) {
568
731
  message: `Not written: ${(_a = row.problems) === null || _a === void 0 ? void 0 : _a.join('; ')}`,
569
732
  });
570
733
  };
734
+ // Every turn rule again, with nothing awaited between here and the review. The calls one model
735
+ // response makes run together, so while this one was reading its rows another call may have
736
+ // been denied under the same lock (any write tool for this table), or another call to this tool
737
+ // asked about for the last time, or had this very proposal sent back. Checked only at the top,
738
+ // that call's answer came too late to stop this review opening.
739
+ const refusedNow = turnRefusal(turn, resource.name, denial());
740
+ if (refusedNow)
741
+ return fail('rejected', refusedNow);
742
+ // The same proposal the user just asked to change means the feedback was not applied. Showing it
743
+ // again would ask the user the same question; refused instead, and it does not use up a round.
744
+ // Only here, after every await, so it sees the latest answer.
745
+ if (turn.lastAsked && sameProposal(proposal, turn.lastAsked, fields)) {
746
+ return fail('rejected', UNCHANGED_PROPOSAL);
747
+ }
748
+ // A turn the user stopped while this was being prepared shows nothing: a review that opened
749
+ // after the Stop would park the turn on it, and an Approve given then would still commit.
750
+ if ((_a = context.turnSignal) === null || _a === void 0 ? void 0 : _a.aborted)
751
+ return fail('rejected', STOPPED_BEFORE_REVIEW);
571
752
  let review;
572
753
  try {
573
- review = yield context.requestInteraction(GENESIS_WRITE_REVIEW, model, { timeoutMs: (_b = (_a = deps.timeouts) === null || _a === void 0 ? void 0 : _a.reviewMs) !== null && _b !== void 0 ? _b : REVIEW_TIMEOUT_MS });
754
+ review = yield context.requestInteraction(GENESIS_WRITE_REVIEW, model, {
755
+ timeoutMs: (_c = (_b = deps.timeouts) === null || _b === void 0 ? void 0 : _b.reviewMs) !== null && _c !== void 0 ? _c : REVIEW_TIMEOUT_MS,
756
+ // A Stop while the review is open closes it unanswered, as a timeout does.
757
+ signal: context.turnSignal,
758
+ });
574
759
  }
575
760
  catch (error) {
576
761
  // requestInteraction throws when another interaction is already open. A throw out of a tool
@@ -578,28 +763,34 @@ function runWrite(resource, args, context, deps) {
578
763
  logger.error(`Genesis assistant: ${resource.name} could not show its review: ${String(error)}`);
579
764
  return fail('request_failed', 'The review could not be shown, so nothing was written.');
580
765
  }
581
- if ((review === null || review === void 0 ? void 0 : review.status) !== 'approved') {
582
- const why = (review === null || review === void 0 ? void 0 : review.status) === 'timeout'
583
- ? 'The review closed before it was answered'
584
- : `The user did not approve it${(review === null || review === void 0 ? void 0 : review.message) ? `: ${review.message}` : ''}`;
585
- return result(resource.name, false, plan.rows.map((row) => {
586
- var _a, _b;
587
- return ({
588
- index: row.index,
589
- status: ((_a = row.problems) === null || _a === void 0 ? void 0 : _a.length) ? 'invalid_payload' : 'not_selected',
590
- committed: false,
591
- message: ((_b = row.problems) === null || _b === void 0 ? void 0 : _b.length) ? `Not written: ${row.problems.join('; ')}` : why,
592
- });
593
- }), `${why}. Nothing was written.`);
766
+ // Read once, the way the review's own closed summary reads it. Anything it does not recognise
767
+ // writes nothing: a `message` on a denial is not carried — it is the channel the model was told
768
+ // to ignore, and a denial needs no words — and an approval whose payload is not a list approves
769
+ // no rows.
770
+ // Stopped while the review was open, or between its answer and here: nothing is committed,
771
+ // whatever the answer was. An Approve after a Stop is not an Approve of this turn.
772
+ if ((_d = context.turnSignal) === null || _d === void 0 ? void 0 : _d.aborted)
773
+ return fail('rejected', STOPPED_AFTER_REVIEW);
774
+ const read = reviewDecisionOf(review, model);
775
+ // A blank change request reads as a denial too (reviewDecisionOf), so it locks: the safe end. A
776
+ // timeout does not — the user did not answer, which is not the same as saying no.
777
+ if (read.decision === 'denied')
778
+ deps.turns.deny(context.turnSignal, lock.key, resource.name);
779
+ if (read.decision === 'changes_requested')
780
+ turn.changeRequests += 1;
781
+ // Only the proposal just asked about is remembered: any other answer clears it.
782
+ turn.lastAsked = read.decision === 'changes_requested' ? proposal : undefined;
783
+ if (read.decision !== 'approved') {
784
+ return declinedResult(resource.name, plan.rows, read, turn.changeRequests, deps.feedbackKey, lock);
594
785
  }
595
786
  // Indexes, never rows: what the review hands back cannot be a payload, so `selectedRows`
596
787
  // reads the objects the table rendered out of the model itself — and re-applies the rule that
597
788
  // a refused row is never committed, whatever came back.
598
- const chosen = new Set((_c = review.payload) !== null && _c !== void 0 ? _c : []);
789
+ const chosen = new Set(read.rows);
599
790
  const approved = selectedRows(model, chosen);
600
791
  const lines = new Map();
601
792
  for (const row of plan.rows) {
602
- if ((_d = row.problems) === null || _d === void 0 ? void 0 : _d.length)
793
+ if ((_e = row.problems) === null || _e === void 0 ? void 0 : _e.length)
603
794
  lines.set(row.index, refused(row));
604
795
  else if (!chosen.has(row.index)) {
605
796
  lines.set(row.index, {
@@ -610,51 +801,132 @@ function runWrite(resource, args, context, deps) {
610
801
  });
611
802
  }
612
803
  }
613
- // Re-checked and committed ONE ROW AT A TIME, in order.
614
- //
615
- // Checking every row up front and then committing them widened the window with each row's
616
- // position — row 25 would be written against a check taken before rows 1 to 24 had even been
617
- // sent. Interleaving keeps each row's window to a single round trip, which is as close to
618
- // compare-and-set as a platform that offers neither allows.
804
+ yield commitApproved(approved, lines, {
805
+ eventName: resource.name,
806
+ op,
807
+ byIndex,
808
+ source,
809
+ checkedFields,
810
+ connect,
811
+ commitMs: (_f = deps.timeouts) === null || _f === void 0 ? void 0 : _f.commitMs,
812
+ turnSignal: context.turnSignal,
813
+ });
814
+ const rows = plan.rows.map((row) => {
815
+ var _a;
816
+ return (_a = lines.get(row.index)) !== null && _a !== void 0 ? _a : {
817
+ index: row.index,
818
+ status: 'unknown',
819
+ committed: false,
820
+ message: 'No outcome was recorded for this row.',
821
+ };
822
+ });
823
+ return result(resource.name, true, rows, summarise(rows), 'approved');
824
+ });
825
+ }
826
+ /**
827
+ * Re-checks and commits the approved rows ONE AT A TIME, in order, recording each outcome in
828
+ * `lines`.
829
+ *
830
+ * @remarks
831
+ * Checking every row up front and then committing them widened the window with each row's
832
+ * position — row 25 would be written against a check taken before rows 1 to 24 had even been
833
+ * sent. Interleaving keeps each row's window to a single round trip, which is as close to
834
+ * compare-and-set as a platform that offers neither allows.
835
+ *
836
+ * A Stop pressed while earlier rows were being written stops the rest. The approval covered the
837
+ * rows as a batch, but each row is its own write, and the user has taken the turn back: what was
838
+ * committed stays reported as written, and every row not yet sent is not sent. Checked before a
839
+ * row's re-read and again before its commit, because the re-read is a round trip the user can
840
+ * press Stop during.
841
+ */
842
+ function commitApproved(approved, lines, run) {
843
+ return __awaiter(this, void 0, void 0, function* () {
844
+ const stoppedAt = (index) => {
845
+ var _a;
846
+ if (!((_a = run.turnSignal) === null || _a === void 0 ? void 0 : _a.aborted))
847
+ return false;
848
+ lines.set(index, { index, status: 'failed', committed: false, message: STOPPED_ROW });
849
+ return true;
850
+ };
619
851
  for (const row of approved) {
620
- const planned = byIndex.get(row.index);
621
- if (op === 'modify' || op === 'delete') {
852
+ if (stoppedAt(row.index))
853
+ continue;
854
+ const planned = run.byIndex.get(row.index);
855
+ if (run.op === 'modify' || run.op === 'delete') {
622
856
  // A check run early is a check of a row that may since have moved: it has to run against
623
857
  // the row as it is at the moment of writing, which is the whole point of interleaving.
624
858
  // oxlint-disable-next-line no-await-in-loop -- each row is checked as it is written
625
- const outcome = yield stillCurrent(planned, { source, fields: checkedFields });
859
+ const outcome = yield stillCurrent(planned, {
860
+ source: run.source,
861
+ fields: run.checkedFields,
862
+ });
626
863
  if (outcome.status !== 'current') {
627
864
  lines.set(row.index, notCurrent(row.index, outcome));
628
865
  continue;
629
866
  }
867
+ if (stoppedAt(row.index))
868
+ continue;
630
869
  }
631
870
  // oxlint-disable-next-line no-await-in-loop -- writes must not race each other
632
871
  const [outcome] = yield commitRows([row], {
633
- connect,
634
- eventName: resource.name,
635
- op,
872
+ connect: run.connect,
873
+ eventName: run.eventName,
874
+ op: run.op,
636
875
  reason: APPROVAL_REASON,
637
- timeoutMs: (_e = deps.timeouts) === null || _e === void 0 ? void 0 : _e.commitMs,
876
+ timeoutMs: run.commitMs,
638
877
  });
639
878
  lines.set(outcome.index, committedLine(outcome, planned === null || planned === void 0 ? void 0 : planned.notes));
640
879
  }
641
- const rows = plan.rows.map((row) => {
642
- var _a;
643
- return (_a = lines.get(row.index)) !== null && _a !== void 0 ? _a : {
644
- index: row.index,
645
- status: 'unknown',
646
- committed: false,
647
- message: 'No outcome was recorded for this row.',
648
- };
649
- });
650
- return result(resource.name, true, rows, summarise(rows));
651
880
  });
652
881
  }
653
- const result = (resource, approved, rows, summary) => ({
882
+ /**
883
+ * Why a call is refused before anything is read or shown, because of how the user has already
884
+ * answered this event in this turn — or `undefined`. See write-turn.ts.
885
+ */
886
+ const turnRefusal = (turn, resource, denial) => {
887
+ // A denial holds for the rest of the turn, in code: the prompt asks the model not to propose it
888
+ // again, and this is what happens if it does. For every write to its table, naming the event
889
+ // the user actually said no to (see locksOf).
890
+ if (denial.by && denial.table) {
891
+ return (`The user denied a write to ${denial.table} (${denial.by}) earlier in this turn, so no ` +
892
+ `write to ${denial.table} is proposed again until they ask. Nothing was shown or written.`);
893
+ }
894
+ if (denial.by) {
895
+ return (`The user denied ${resource} earlier in this turn, so it is not proposed again until ` +
896
+ 'they ask. Nothing was shown or written.');
897
+ }
898
+ if (turn.changeRequests > MAX_CHANGE_ROUNDS) {
899
+ return (`The user has asked for changes to ${resource} ${turn.changeRequests} times in this ` +
900
+ 'turn. Ask them in chat how to proceed. Nothing was shown or written.');
901
+ }
902
+ return undefined;
903
+ };
904
+ /** The result for a review that wrote nothing: what the user decided, and what to do next. */
905
+ const declinedResult = (resource, rows, read, changeRequests, key, lock) => {
906
+ const declined = DECLINED[read.decision];
907
+ // The bridge's own words first: what the user typed and what to do next, ahead of the rows the
908
+ // prompt tells the model to treat as data. The key is what proves them, so the order is not the
909
+ // safety; it is where a model reading the result meets them first.
910
+ return Object.assign(Object.assign(Object.assign({}, (read.decision === 'changes_requested'
911
+ ? {
912
+ userFeedback: Object.assign({ authoredBy: 'user', key, text: boundedFeedback(read.text) }, (read.rowsTicked.length ? { rowsTicked: read.rowsTicked } : {})),
913
+ }
914
+ : {})), { next: { key, text: nextAfter(read, changeRequests, lock) } }), result(resource, false, rows.map((row) => {
915
+ var _a, _b;
916
+ return ({
917
+ index: row.index,
918
+ status: ((_a = row.problems) === null || _a === void 0 ? void 0 : _a.length) ? 'invalid_payload' : 'not_selected',
919
+ committed: false,
920
+ message: ((_b = row.problems) === null || _b === void 0 ? void 0 : _b.length) ? `Not written: ${row.problems.join('; ')}` : declined.row,
921
+ });
922
+ }), declined.summary, read.decision));
923
+ };
924
+ const result = (resource, approved, rows, summary, decision) => ({
654
925
  source: GENESIS_DATA_SOURCE,
655
926
  untrusted: true,
656
927
  resource,
657
928
  approved,
929
+ decision,
658
930
  rows,
659
931
  summary,
660
932
  });
@@ -0,0 +1,110 @@
1
+ import { logger } from '../utils/logger';
2
+ import { sameValue } from './value-compare';
3
+ /**
4
+ * What a planned write proposes, in the form `sameProposal` compares.
5
+ *
6
+ * @remarks
7
+ * A modify's payload is the whole merged row, so it also carries every column it leaves alone,
8
+ * as read. Compared whole, a column somebody else changed between two reviews made a resent
9
+ * proposal look new. Only the fields that differ from the row as read are kept.
10
+ *
11
+ * @internal
12
+ */
13
+ export function proposalOf(op, rows, fields) {
14
+ const typeOf = new Map(fields.map((field) => [field.name, field.type]));
15
+ return rows.map((row) => {
16
+ var _a, _b, _c, _d, _e;
17
+ const details = (_a = row.details) !== null && _a !== void 0 ? _a : {};
18
+ const preImage = (_b = row.preImage) !== null && _b !== void 0 ? _b : {};
19
+ const change = op === 'modify'
20
+ ? Object.fromEntries(Object.entries(details).filter(([name, value]) => !sameValue(value, preImage[name], typeOf.get(name))))
21
+ : details;
22
+ return { target: (_c = row.key) !== null && _c !== void 0 ? _c : {}, change, problems: (_d = row.problems) !== null && _d !== void 0 ? _d : [], notes: (_e = row.notes) !== null && _e !== void 0 ? _e : [] };
23
+ });
24
+ }
25
+ /**
26
+ * Whether two proposals would put the same thing in front of the user.
27
+ *
28
+ * @remarks
29
+ * Compared on the BUILT payloads, not on the model's arguments: `'900'` and `900` for an INT build
30
+ * the same payload. Each field is compared by `sameValue` on the type the event declares, so
31
+ * `'1.25'` and `'1.250'` are one BIGDECIMAL while `'007'` and `'7'` stay two STRINGs.
32
+ *
33
+ * Rows are matched by what they are, not by where they are: the same rows in another order are the
34
+ * same proposal. A modify matches on the key the model named its row by, so the same row named by
35
+ * a different key reads as a new proposal and is reviewed again. That is the safe side: a proposal
36
+ * wrongly taken as unchanged would tell the model it ignored feedback it applied.
37
+ *
38
+ * @internal
39
+ */
40
+ export function sameProposal(a, b, fields) {
41
+ if (a.length !== b.length)
42
+ return false;
43
+ const typeOf = new Map(fields.map((field) => [field.name, field.type]));
44
+ const sameRecord = (x, y) => [...new Set([...Object.keys(x), ...Object.keys(y)])].every((name) => sameValue(x[name], y[name], typeOf.get(name)));
45
+ const sameList = (x, y) => x.length === y.length && x.every((item, index) => item === y[index]);
46
+ // Each row of `b` answers for one row of `a`, so two copies of a row are not matched by one.
47
+ const unmatched = [...b];
48
+ return a.every((row) => {
49
+ const at = unmatched.findIndex((other) => sameRecord(row.target, other.target) &&
50
+ sameRecord(row.change, other.change) &&
51
+ sameList(row.problems, other.problems) &&
52
+ sameList(row.notes, other.notes));
53
+ if (at < 0)
54
+ return false;
55
+ unmatched.splice(at, 1);
56
+ return true;
57
+ });
58
+ }
59
+ /**
60
+ * How many REVISED proposals a turn allows per event: the first proposal and three revisions, so
61
+ * the user can ask for changes four times. After the fourth request the tool refuses, and the
62
+ * model asks in chat — a loop of "not quite" is a conversation, not another review.
63
+ *
64
+ * @internal
65
+ */
66
+ export const MAX_CHANGE_ROUNDS = 3;
67
+ /** What a host whose tool context has no turn signal is told, once per set of write tools. */
68
+ const NO_SIGNAL_WARNING = 'Genesis assistant: a write tool was called without turnSignal on its handler context, so ' +
69
+ 'its turn rules (a denial, the limit on change requests, the unchanged-proposal check) hold ' +
70
+ 'for the life of these tools, across every chat view, instead of for one user message. Pass ' +
71
+ "the chat driver's turnSignal through.";
72
+ /** @internal */
73
+ export function createWriteTurns() {
74
+ const turns = new WeakMap();
75
+ // One key for every call that arrives without a signal. See above: the safe end.
76
+ const noSignal = {};
77
+ let warned = false;
78
+ const turnOf = (signal) => {
79
+ if (!signal && !warned) {
80
+ warned = true;
81
+ logger.warn(NO_SIGNAL_WARNING);
82
+ }
83
+ const key = signal !== null && signal !== void 0 ? signal : noSignal;
84
+ let turn = turns.get(key);
85
+ if (!turn) {
86
+ turn = { resources: new Map(), denials: new Map() };
87
+ turns.set(key, turn);
88
+ }
89
+ return turn;
90
+ };
91
+ return {
92
+ of(signal, resource) {
93
+ const { resources } = turnOf(signal);
94
+ let state = resources.get(resource);
95
+ if (!state) {
96
+ state = { changeRequests: 0 };
97
+ resources.set(resource, state);
98
+ }
99
+ return state;
100
+ },
101
+ deniedBy(signal, lock) {
102
+ return turnOf(signal).denials.get(lock);
103
+ },
104
+ deny(signal, lock, event) {
105
+ const { denials } = turnOf(signal);
106
+ if (!denials.has(lock))
107
+ denials.set(lock, event);
108
+ },
109
+ };
110
+ }