@genesislcap/ai-assistant 15.48.0 → 15.50.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 (63) hide show
  1. package/dist/ai-assistant.api.json +65 -0
  2. package/dist/ai-assistant.d.ts +35 -16
  3. package/dist/custom-elements.json +118 -2
  4. package/dist/dts/genesis/config.d.ts +31 -0
  5. package/dist/dts/genesis/config.d.ts.map +1 -1
  6. package/dist/dts/genesis/consumes.d.ts.map +1 -1
  7. package/dist/dts/genesis/index.d.ts +2 -2
  8. package/dist/dts/genesis/index.d.ts.map +1 -1
  9. package/dist/dts/genesis/reference-check.d.ts +4 -3
  10. package/dist/dts/genesis/reference-check.d.ts.map +1 -1
  11. package/dist/dts/genesis/reference-existence.d.ts +3 -3
  12. package/dist/dts/genesis/reference-existence.d.ts.map +1 -1
  13. package/dist/dts/genesis/review-model.d.ts +59 -4
  14. package/dist/dts/genesis/review-model.d.ts.map +1 -1
  15. package/dist/dts/genesis/types.d.ts +43 -0
  16. package/dist/dts/genesis/types.d.ts.map +1 -1
  17. package/dist/dts/genesis/write-commit.d.ts +2 -2
  18. package/dist/dts/genesis/write-commit.d.ts.map +1 -1
  19. package/dist/dts/genesis/write-op.d.ts +34 -0
  20. package/dist/dts/genesis/write-op.d.ts.map +1 -0
  21. package/dist/dts/genesis/write-outcome.d.ts +2 -2
  22. package/dist/dts/genesis/write-outcome.d.ts.map +1 -1
  23. package/dist/dts/genesis/write-payload.d.ts +3 -3
  24. package/dist/dts/genesis/write-payload.d.ts.map +1 -1
  25. package/dist/dts/genesis/write-plan.d.ts +18 -7
  26. package/dist/dts/genesis/write-plan.d.ts.map +1 -1
  27. package/dist/dts/genesis/write-review/write-review.d.ts +6 -0
  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 +2 -2
  32. package/dist/dts/genesis/write-tools.d.ts.map +1 -1
  33. package/dist/dts/genesis/write-turn.d.ts +5 -3
  34. package/dist/dts/genesis/write-turn.d.ts.map +1 -1
  35. package/dist/dts/main/main.d.ts +16 -0
  36. package/dist/dts/main/main.d.ts.map +1 -1
  37. package/dist/dts/main/main.styles.d.ts.map +1 -1
  38. package/dist/dts/main/main.template.d.ts +7 -4
  39. package/dist/dts/main/main.template.d.ts.map +1 -1
  40. package/dist/esm/genesis/config.js +204 -5
  41. package/dist/esm/genesis/consumes.js +5 -0
  42. package/dist/esm/genesis/index.js +1 -1
  43. package/dist/esm/genesis/review-model.js +62 -10
  44. package/dist/esm/genesis/write-op.js +18 -0
  45. package/dist/esm/genesis/write-outcome.js +13 -6
  46. package/dist/esm/genesis/write-payload.js +22 -10
  47. package/dist/esm/genesis/write-plan.js +121 -12
  48. package/dist/esm/genesis/write-review/write-review.js +20 -1
  49. package/dist/esm/genesis/write-review/write-review.styles.js +14 -0
  50. package/dist/esm/genesis/write-review/write-review.template.js +25 -7
  51. package/dist/esm/genesis/write-tools.js +304 -74
  52. package/dist/esm/genesis/write-turn.js +9 -5
  53. package/dist/esm/main/main.js +21 -0
  54. package/dist/esm/main/main.styles.js +25 -0
  55. package/dist/esm/main/main.template.js +76 -34
  56. package/dist/genesis-consumes.cjs +6 -1
  57. package/dist/genesis-consumes.cjs.map +2 -2
  58. package/dist/genesis-consumes.mjs +6 -1
  59. package/dist/genesis-consumes.mjs.map +2 -2
  60. package/docs/genesis.md +171 -45
  61. package/docs/styling.md +130 -0
  62. package/package.json +17 -17
  63. package/scripts/smoke-genesis-consumes-node.mjs +14 -1
@@ -1 +1 @@
1
- {"version":3,"file":"main.styles.d.ts","sourceRoot":"","sources":["../../../src/main/main.styles.ts"],"names":[],"mappings":"AAwtCA,eAAO,MAAM,MAAM,iDAQlB,CAAC"}
1
+ {"version":3,"file":"main.styles.d.ts","sourceRoot":"","sources":["../../../src/main/main.styles.ts"],"names":[],"mappings":"AAivCA,eAAO,MAAM,MAAM,iDAQlB,CAAC"}
@@ -18,20 +18,23 @@ import type { ChatMessage } from '@genesislcap/foundation-ai';
18
18
  import { ViewTemplate } from '@genesislcap/web-core';
19
19
  import type { FoundationAiAssistant } from './main';
20
20
  /**
21
- * Part names for one avatar element: the bare name, a role-level name, and — on the assistant
22
- * side, whose rows vary — the message type.
21
+ * The three names one element is exposed under: the bare name, a role-level name, and — on the
22
+ * assistant side, whose rows vary — the message type. `rolePartsFor('avatar', 'ai-thinking')` is
23
+ * `avatar avatar-assistant avatar-ai-thinking`.
23
24
  *
24
25
  * The role-level name is the one an app usually wants. `messageType` splits the assistant across
25
26
  * `ai`, `ai-thinking`, `ai-function` and `interaction`, so without it "style the assistant's
26
- * avatar, not the user's" takes four selectors and silently misses any type added later.
27
+ * rows, not the user's" takes four selectors and silently misses any type added later.
27
28
  * `::part()` names cannot be chained, so each has to be a name of its own rather than a
28
29
  * combination. The user side needs no extra name — its role and its type are both `user`.
29
30
  *
31
+ * Shared by the avatar and the message row so the two cannot drift.
32
+ *
30
33
  * Exported for the unit test that pins the vocabulary; not part of the element API.
31
34
  *
32
35
  * @internal
33
36
  */
34
- export declare const avatarPartsFor: (base: string, type: string) => string;
37
+ export declare const rolePartsFor: (base: string, type: string) => string;
35
38
  /**
36
39
  * The timestamp shown beside the sender name (GENC-1257).
37
40
  *
@@ -1 +1 @@
1
- {"version":3,"file":"main.template.d.ts","sourceRoot":"","sources":["../../../src/main/main.template.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAEV,WAAW,EAGZ,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAuC,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAU1F,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,QAAQ,CAAC;AAkDpD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,cAAc,GAAI,MAAM,MAAM,EAAE,MAAM,MAAM,KAAG,MAC4B,CAAC;AAsGzF;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,wBAAwB,kDAWpC,CAAC;AAoJF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,oBAAoB,GAAI,GAAG,qBAAqB,KAAG,MAYlD,CAAC;AAEf;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,kDAUtC,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,mBAAmB,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,mBAAmB,GAAI,GAAG,qBAAqB,KAAG,MAAM,GAAG,IACpB,CAAC;AAyJrD,eAAO,MAAM,6BAA6B,GACxC,oBAAoB,MAAM,KACzB,YAAY,CAAC,qBAAqB,CAqrBpC,CAAC"}
1
+ {"version":3,"file":"main.template.d.ts","sourceRoot":"","sources":["../../../src/main/main.template.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAEV,WAAW,EAGZ,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAgD,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAUnG,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,QAAQ,CAAC;AAkDpD;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,YAAY,GAAI,MAAM,MAAM,EAAE,MAAM,MAAM,KAAG,MAC8B,CAAC;AA0HzF;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,wBAAwB,kDAWpC,CAAC;AAoJF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,oBAAoB,GAAI,GAAG,qBAAqB,KAAG,MAYlD,CAAC;AAEf;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,kDAUtC,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,mBAAmB,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,mBAAmB,GAAI,GAAG,qBAAqB,KAAG,MAAM,GAAG,IACpB,CAAC;AAyJrD,eAAO,MAAM,6BAA6B,GACxC,oBAAoB,MAAM,KACzB,YAAY,CAAC,qBAAqB,CA0sBpC,CAAC"}
@@ -1,6 +1,7 @@
1
1
  import { AI_TIER_IDS, AI_TIER_VENDORS } from '@genesislcap/foundation-ai';
2
2
  import { logger } from '../utils/logger';
3
3
  import { GENESIS_EVENT_OPS, } from './types';
4
+ import { PLATFORM_MAINTAINED } from './write-payload';
4
5
  /** The default read cap, and the ceiling the config may raise it to. */
5
6
  export const DEFAULT_MAX_ROWS = 50;
6
7
  export const MAX_ROWS_CEILING = 1000;
@@ -167,6 +168,165 @@ export function referencesProblems(resource, op = resource === null || resource
167
168
  });
168
169
  return problems;
169
170
  }
171
+ /** Table and field names as the generator writes them. */
172
+ const ROW_NAME = /^[A-Z0-9_]+$/;
173
+ /** What only a custom event's row action may carry. `entity` is not one of them: see its doc. */
174
+ const ROW_ONLY_FIELDS = ['shape', 'inputs', 'effects'];
175
+ /** The ops besides a row action whose row a declared `key` may name: a modify and a delete. */
176
+ const KEY_OPS = ['modify', 'delete'];
177
+ /**
178
+ * What is wrong with a declared key: at least one field, each a field name, none twice, and none
179
+ * the platform maintains. The same rule for a row action, a modify and a delete. Collects the
180
+ * fields it accepted into `accepted`, when given.
181
+ */
182
+ function keyProblems(key, accepted = new Set()) {
183
+ if (!Array.isArray(key) || !key.length)
184
+ return ['key must name at least one field'];
185
+ const problems = [];
186
+ for (const field of key) {
187
+ if (typeof field !== 'string' || !ROW_NAME.test(field)) {
188
+ problems.push(`key holds ${shown(field)}, not a field name`);
189
+ }
190
+ else if (accepted.has(field)) {
191
+ problems.push(`key names ${field} twice`);
192
+ }
193
+ else if (PLATFORM_MAINTAINED.has(field)) {
194
+ problems.push(`key names ${field}, which the platform maintains`);
195
+ }
196
+ else {
197
+ accepted.add(field);
198
+ }
199
+ }
200
+ return problems;
201
+ }
202
+ const INPUT_KEYS = ['field', 'required'];
203
+ const EFFECT_KEYS = ['op', 'table'];
204
+ const EFFECT_OPS = ['modify', 'insert'];
205
+ const shown = (value) => typeof value === 'string' ? `'${value}'` : value === null ? 'null' : typeof value;
206
+ /**
207
+ * Why a request a row action needs is not readable, from what the caller knows about it: in the
208
+ * config with no read tool, in the config but left out, or a query. Failing all three it is missing.
209
+ * The validator and the write tools say it the same way, through this.
210
+ *
211
+ * @internal
212
+ */
213
+ export const notReadableReason = ({ unreadable = new Set(), leftOut = new Set(), queries = new Set(), }) => (name) => {
214
+ if (unreadable.has(name))
215
+ return `${name} has no read tool, as its maxRows is not a number`;
216
+ if (leftOut.has(name))
217
+ return `${name} is in the AI config but was left out`;
218
+ if (queries.has(name)) {
219
+ return `${name} is a query in the AI config, and a query is never a row source`;
220
+ }
221
+ return `the AI config has no request resource ${name}`;
222
+ };
223
+ /**
224
+ * What is wrong with a resource's row-action fields (contracts C-18.7.2), if anything.
225
+ *
226
+ * @remarks
227
+ * One rule, three callers: the validator, and the write tools when a tool is defined and when it
228
+ * is called, because the write tools are exported and a direct call never reaches the validator.
229
+ *
230
+ * A custom event with no `shape` has no problem here: the write tools refuse it, as they refuse
231
+ * every custom event that is not a row action. A later change of meaning has to arrive as a new
232
+ * `shape` value, never as a new key on an old one, so a key this version has no place for is a
233
+ * problem rather than something to skip.
234
+ *
235
+ * @param requestNames - The request resources whose rows can be read. A row action reads its rows
236
+ * through `REQ_<entity>`, and without one there is no row to review.
237
+ * @param whyNotReadable - Why a request is not among `requestNames`, when the caller knows: it was
238
+ * left out, has no read tool, or is a query. Without it, the request is said to be missing.
239
+ * @beta
240
+ */
241
+ export function rowActionProblem(resource, requestNames, whyNotReadable = notReadableReason({})) {
242
+ const fields = (resource !== null && resource !== void 0 ? resource : {});
243
+ if (fields.op !== 'custom') {
244
+ const carried = ROW_ONLY_FIELDS.filter((field) => fields[field] !== undefined);
245
+ const problems = carried.length
246
+ ? [
247
+ `${carried.join(', ')} ${carried.length > 1 ? 'apply' : 'applies'} to a custom event's ` +
248
+ 'row action only',
249
+ ]
250
+ : [];
251
+ // A modify or a delete may name its row by the table's key (contracts C-19); held to a row
252
+ // action's key rule. Anywhere else a key names nothing.
253
+ if (fields.key !== undefined) {
254
+ problems.push(...(KEY_OPS.includes(fields.op)
255
+ ? keyProblems(fields.key)
256
+ : ["key applies to a custom event's row action, a modify or a delete only"]));
257
+ }
258
+ return problems.length ? problems.join('; ') : undefined;
259
+ }
260
+ const { shape, entity, key, inputs, effects } = fields;
261
+ if (shape === undefined)
262
+ return undefined;
263
+ if (shape !== 'row') {
264
+ return `shape ${shown(shape)} is not one this version of the assistant runs (row)`;
265
+ }
266
+ const problems = [];
267
+ const table = typeof entity === 'string' && ROW_NAME.test(entity) ? entity : undefined;
268
+ if (!table)
269
+ problems.push(`entity must be a table name (got ${shown(entity)})`);
270
+ const keyFields = new Set();
271
+ problems.push(...keyProblems(key, keyFields));
272
+ if (!Array.isArray(inputs)) {
273
+ problems.push('inputs must be a list');
274
+ }
275
+ else {
276
+ inputs.forEach((input, i) => {
277
+ const at = `inputs[${i}]`;
278
+ if (!isObject(input)) {
279
+ problems.push(`${at} must be an object`);
280
+ return;
281
+ }
282
+ const stray = Object.keys(input).filter((name) => !INPUT_KEYS.includes(name));
283
+ if (stray.length)
284
+ problems.push(`${at} has keys it does not read (${stray.join(', ')})`);
285
+ if (typeof input.field !== 'string' || !ROW_NAME.test(input.field)) {
286
+ problems.push(`${at}.field must be a field name`);
287
+ }
288
+ else if (keyFields.has(input.field)) {
289
+ problems.push(`${input.field} is both a key and an input`);
290
+ }
291
+ if (input.required !== true)
292
+ problems.push(`${at}.required must be true`);
293
+ });
294
+ }
295
+ if (!Array.isArray(effects) || !effects.length) {
296
+ problems.push('effects must list at least one write');
297
+ }
298
+ else {
299
+ let modifies = 0;
300
+ effects.forEach((effect, i) => {
301
+ const at = `effects[${i}]`;
302
+ if (!isObject(effect)) {
303
+ problems.push(`${at} must be an object`);
304
+ return;
305
+ }
306
+ const stray = Object.keys(effect).filter((name) => !EFFECT_KEYS.includes(name));
307
+ if (stray.length)
308
+ problems.push(`${at} has keys it does not read (${stray.join(', ')})`);
309
+ if (!EFFECT_OPS.includes(effect.op))
310
+ problems.push(`${at}.op must be modify or insert`);
311
+ if (typeof effect.table !== 'string' || !ROW_NAME.test(effect.table)) {
312
+ problems.push(`${at}.table must be a table name`);
313
+ }
314
+ if (effect.op === 'modify') {
315
+ modifies += 1;
316
+ if (table && effect.table !== table) {
317
+ problems.push(`${at} modifies ${shown(effect.table)}, not its own table ${table}`);
318
+ }
319
+ }
320
+ });
321
+ if (modifies !== 1) {
322
+ problems.push(`effects must hold exactly one modify of its own table, not ${modifies}`);
323
+ }
324
+ }
325
+ if (table && !requestNames.has(`REQ_${table}`)) {
326
+ problems.push(`its rows are not readable: ${whyNotReadable(`REQ_${table}`)}`);
327
+ }
328
+ return problems.length ? problems.join('; ') : undefined;
329
+ }
170
330
  /**
171
331
  * Checks a generated AI config before anything is registered, and says what can be kept.
172
332
  *
@@ -188,7 +348,7 @@ export function referencesProblems(resource, op = resource === null || resource
188
348
  * @beta
189
349
  */
190
350
  export function validateGenesisAiConfig(config) {
191
- var _a;
351
+ var _a, _b;
192
352
  if (!config || typeof config !== 'object') {
193
353
  return {
194
354
  problems: ['the AI config is missing or not an object'],
@@ -240,13 +400,35 @@ export function validateGenesisAiConfig(config) {
240
400
  if (typeof name === 'string')
241
401
  copies.set(name, ((_a = copies.get(name)) !== null && _a !== void 0 ? _a : 0) + 1);
242
402
  }
403
+ // The requests that will be kept, known before any row action is judged against them, so where
404
+ // a row action sits in the list cannot decide whether its rows are readable. Only a request: a
405
+ // query named REQ_<T> is never a row source. A request's own judgement never needs this set.
406
+ const requestNames = new Set();
407
+ // And why any other one is not: so a row action is told its REQ_ was left out, or is a query,
408
+ // rather than that the config has none.
409
+ const leftOut = new Set();
410
+ const queries = new Set();
411
+ for (const resource of c.resources) {
412
+ const name = resource === null || resource === void 0 ? void 0 : resource.name;
413
+ if (typeof name !== 'string')
414
+ continue;
415
+ if ((resource === null || resource === void 0 ? void 0 : resource.kind) === 'query')
416
+ queries.add(name);
417
+ if ((resource === null || resource === void 0 ? void 0 : resource.kind) !== 'request')
418
+ continue;
419
+ if (resourceProblems(resource, (_b = copies.get(name)) !== null && _b !== void 0 ? _b : 0, new Set()).length)
420
+ leftOut.add(name);
421
+ else
422
+ requestNames.add(name);
423
+ }
424
+ const whyNotReadable = notReadableReason({ leftOut, queries });
243
425
  const resources = [];
244
426
  const dropped = [];
245
427
  const warnings = [];
246
428
  c.resources.forEach((resource, i) => {
247
429
  var _a;
248
430
  const name = typeof (resource === null || resource === void 0 ? void 0 : resource.name) === 'string' ? resource.name : undefined;
249
- const wrong = resourceProblems(resource, (_a = copies.get(name !== null && name !== void 0 ? name : '')) !== null && _a !== void 0 ? _a : 0);
431
+ const wrong = resourceProblems(resource, (_a = copies.get(name !== null && name !== void 0 ? name : '')) !== null && _a !== void 0 ? _a : 0, requestNames, whyNotReadable);
250
432
  if (wrong.length) {
251
433
  dropped.push({ at: `resources[${i}]`, name, problems: wrong });
252
434
  return;
@@ -342,17 +524,31 @@ export function customCodeOf(resource) {
342
524
  * which is when GENESIS_AI_CONSUMES has to name it.
343
525
  */
344
526
  function keptCopy(resource, customCode) {
345
- return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ name: resource.name, kind: resource.kind }, (resource.op !== undefined ? { op: resource.op } : {})), { context: resource.context }), (resource.maxRows !== undefined ? { maxRows: resource.maxRows } : {})), (customCode ? { customCode } : {})), (resource.references !== undefined
527
+ var _a, _b, _c;
528
+ return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ name: resource.name, kind: resource.kind }, (resource.op !== undefined ? { op: resource.op } : {})), { context: resource.context }), (resource.maxRows !== undefined ? { maxRows: resource.maxRows } : {})), (customCode ? { customCode } : {})), (resource.references !== undefined
346
529
  ? {
347
530
  references: resource.references.map(({ resource: target, fields }) => ({
348
531
  resource: target,
349
532
  fields: fields.map(({ field, targetField }) => ({ field, targetField })),
350
533
  })),
351
534
  }
535
+ : {})), ((resource.op === 'modify' || resource.op === 'delete') && resource.key !== undefined
536
+ ? { key: [...resource.key] }
537
+ : {})), (resource.op === 'custom' && resource.shape === 'row'
538
+ ? {
539
+ shape: resource.shape,
540
+ entity: resource.entity,
541
+ key: [...((_a = resource.key) !== null && _a !== void 0 ? _a : [])],
542
+ inputs: ((_b = resource.inputs) !== null && _b !== void 0 ? _b : []).map(({ field, required }) => ({ field, required })),
543
+ effects: ((_c = resource.effects) !== null && _c !== void 0 ? _c : []).map(({ op, table }) => ({ op, table })),
544
+ }
352
545
  : {}));
353
546
  }
354
- /** What is wrong with one resource, if anything. `copies` is how many entries share its name. */
355
- function resourceProblems(resource, copies) {
547
+ /**
548
+ * What is wrong with one resource, if anything. `copies` is how many entries share its name, and
549
+ * `requestNames` the requests that will be kept, which a row action reads its rows through.
550
+ */
551
+ function resourceProblems(resource, copies, requestNames, whyNotReadable) {
356
552
  // A kind this version does not know is judged on nothing else: its name need not look like
357
553
  // anything here, and it is left out either way.
358
554
  const kind = resource === null || resource === void 0 ? void 0 : resource.kind;
@@ -405,5 +601,8 @@ function resourceProblems(resource, copies) {
405
601
  }
406
602
  }
407
603
  problems.push(...referencesProblems(resource));
604
+ const rowAction = rowActionProblem(resource, requestNames, whyNotReadable);
605
+ if (rowAction)
606
+ problems.push(rowAction);
408
607
  return problems;
409
608
  }
@@ -32,6 +32,11 @@ export const GENESIS_AI_CONSUMES = Object.freeze({
32
32
  'maxRows',
33
33
  'customCode',
34
34
  'references',
35
+ 'shape',
36
+ 'entity',
37
+ 'key',
38
+ 'inputs',
39
+ 'effects',
35
40
  ]),
36
41
  vendors: Object.freeze(['anthropic', 'gemini']),
37
42
  tiers: Object.freeze(['low', 'high', 'reasoning']),
@@ -11,7 +11,7 @@
11
11
  * @beta
12
12
  */
13
13
  export { GENESIS_AGENT_NAME, registerGenesisAssistant } from './register-genesis-assistant';
14
- export { customCodeOf } from './config';
14
+ export { customCodeOf, rowActionProblem } from './config';
15
15
  export { GENESIS_AI_CONSUMES } from './consumes';
16
16
  export { validateGenesisAiConfig } from './config';
17
17
  export { createGenesisResourceTools, GENESIS_DATA_SOURCE } from './resource-tools';
@@ -31,6 +31,33 @@ const defaultTitle = (name) => name
31
31
  * value long enough to push the change out of view wraps, where being on several lines is plain.
32
32
  */
33
33
  export const LONG_VALUE = 24;
34
+ /**
35
+ * The header of a row action's review. It names the handler and its table, and never the op: the
36
+ * write is the handler's, not a modify, and `row-action` is the bridge's own word.
37
+ *
38
+ * @internal
39
+ */
40
+ export const rowActionHeading = (rowAction, rows) => `Run ${rowAction.handler} on ${rows} ${rowAction.entity} row(s). Nothing is written until you ` +
41
+ 'choose rows and select Write.';
42
+ /**
43
+ * The lines under a row action's header: what its code wrote, that the row is shown as it is, and
44
+ * that the app may do more in response (contracts C-18.7.7 as C-18.R amends it).
45
+ *
46
+ * @remarks
47
+ * Dated to generation, because an exported app's code can change after it. The effects are what
48
+ * the code does, in its order, not a summary, and the last line is there because consolidators and
49
+ * the app's own logic can react to these writes, which no review here can see.
50
+ *
51
+ * @internal
52
+ */
53
+ export const rowActionLines = (rowAction) => [
54
+ "When this app was generated, the handler's code wrote: " +
55
+ `${rowAction.effects.map(({ op, table }) => `${op} ${table}`).join(', ')}.`,
56
+ "The row is shown as it is now; the handler's code decides what changes.",
57
+ 'Other parts of the app can update more records in response to this.',
58
+ ];
59
+ /** A run's inputs as its payload carries them. */
60
+ const inputsOf = (details, inputs) => Object.fromEntries(inputs.filter((field) => field in details).map((field) => [field, details[field]]));
34
61
  /** `A`, `A and B`, `A, B and C`. */
35
62
  const joined = (items) => items.length > 1 ? `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}` : items[0];
36
63
  /**
@@ -172,11 +199,17 @@ export function displayValue(value, type) {
172
199
  export function buildReviewModel(options) {
173
200
  var _a;
174
201
  const { resource, op, fields = [], rows, customCode } = options;
202
+ const run = op === 'row-action' ? options.rowAction : undefined;
203
+ // A run without its facts would be drawn as a modify, its changes marked, when what changes is
204
+ // the handler's to decide. So every row of it is refused instead: nothing can be written.
205
+ const unexplained = op === 'row-action' && !run;
175
206
  const byName = new Map(fields.map((field) => [field.name, field]));
176
207
  // Declared order first, then anything a row carries that the metadata did not describe, in the
177
208
  // order it is first seen. One column list, so every row's cells line up under it.
178
209
  const columnNames = fields.map((field) => field.name);
179
- for (const row of rows) {
210
+ // A run's columns are its event's fields and no others: what is shown is what is checked before
211
+ // the write, and a column of the row it never sends would be shown and never checked.
212
+ for (const row of run ? [] : rows) {
180
213
  // What is RENDERED, which for a delete is the whole row rather than the key it sends. The
181
214
  // platform's own columns are left out: a modify's review hides them because they never
182
215
  // travel, and a delete showing RECORD_ID and TIMESTAMP would be the same table telling the
@@ -194,16 +227,24 @@ export function buildReviewModel(options) {
194
227
  });
195
228
  });
196
229
  const built = rows.map((row) => {
197
- var _a, _b, _c;
230
+ var _a, _b;
198
231
  // A REFUSED row will not be written, so it has no change to show — and a refused modify can come
199
232
  // with its pre-image and an EMPTY payload, which marked every non-empty field as changed and
200
233
  // rendered the row as a full wipe: each old value struck through over an empty new one. The
201
234
  // screen whose job is to show what will happen showed the most alarming outcome, for a row
202
235
  // that will not happen at all, often beside a refusal reading "this modify changes nothing".
203
236
  // So a refused row shows the row as it stands, and nothing on it is marked as changing.
204
- const refused = !!((_a = row.problems) === null || _a === void 0 ? void 0 : _a.length);
205
- const compared = refused ? undefined : row.preImage;
206
- const shown = (_b = row.display) !== null && _b !== void 0 ? _b : (refused && row.preImage ? row.preImage : row.details);
237
+ const problems = unexplained
238
+ ? [...((_a = row.problems) !== null && _a !== void 0 ? _a : []), 'this run cannot be shown without its handler and table']
239
+ : row.problems;
240
+ const refused = !!(problems === null || problems === void 0 ? void 0 : problems.length);
241
+ // A run is no change from the row, so nothing is compared: the row is shown as it is, with each
242
+ // input as the handler is given it. A refused run shows the row as read and no input, so a
243
+ // value under the input mark is always one the handler would be given. One refused for its
244
+ // inputs was never read, and shows only its problem.
245
+ const compared = refused || run ? undefined : row.preImage;
246
+ const shown = run
247
+ ? Object.assign(Object.assign({}, row.preImage), (refused ? {} : inputsOf(row.details, run.inputs))) : ((_b = row.display) !== null && _b !== void 0 ? _b : (refused && row.preImage ? row.preImage : row.details));
207
248
  // Only meaningful where the two differ; on a modify or an insert everything shown is sent.
208
249
  const marksIdentifying = !!row.display;
209
250
  const cells = columnNames.map((field) => {
@@ -212,13 +253,16 @@ export function buildReviewModel(options) {
212
253
  const previous = compared ? compared[field] : undefined;
213
254
  const display = displayValue(shown[field], declared === null || declared === void 0 ? void 0 : declared.type);
214
255
  const previousDisplay = compared ? displayValue(previous, declared === null || declared === void 0 ? void 0 : declared.type) : undefined;
215
- return Object.assign(Object.assign({ field, label: (_a = declared === null || declared === void 0 ? void 0 : declared.title) !== null && _a !== void 0 ? _a : defaultTitle(field), display }, (compared ? { previousDisplay } : {})), {
256
+ return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ field, label: (_a = declared === null || declared === void 0 ? void 0 : declared.title) !== null && _a !== void 0 ? _a : defaultTitle(field), display }, (compared ? { previousDisplay } : {})), {
216
257
  // Compared on the VALUES, with both sides normalised — never on the display text.
217
258
  // Display is deliberately lossy (a timestamp is rendered to the minute), so a change of
218
259
  // seconds would render identically on both sides and go unmarked, which is the review
219
260
  // failing at its one job. A raw comparison would be wrong the other way, marking every
220
261
  // row changed, so the normaliser is what makes both correct.
221
- changed: !!compared && !sameValue(previous, shown[field], declared === null || declared === void 0 ? void 0 : declared.type), identifying: marksIdentifying && field in row.details, long: display.length > LONG_VALUE || ((_b = previousDisplay === null || previousDisplay === void 0 ? void 0 : previousDisplay.length) !== null && _b !== void 0 ? _b : 0) > LONG_VALUE });
262
+ changed: !!compared && !sameValue(previous, shown[field], declared === null || declared === void 0 ? void 0 : declared.type),
263
+ // A run names its row by its key, explicitly: its details are the whole row, so the
264
+ // delete's rule would mark every cell.
265
+ identifying: run ? run.key.includes(field) : marksIdentifying && field in row.details }), (run && run.key.includes(field) ? { identifies: 'the row the handler runs on' } : {})), (run && !refused && run.inputs.includes(field) ? { input: true } : {})), { long: display.length > LONG_VALUE || ((_b = previousDisplay === null || previousDisplay === void 0 ? void 0 : previousDisplay.length) !== null && _b !== void 0 ? _b : 0) > LONG_VALUE });
222
266
  });
223
267
  // The identifying cells where the row has them — a delete marks its key, and a modify or an
224
268
  // insert has none, so those fall back to the first cell that carries a value.
@@ -229,11 +273,19 @@ export function buildReviewModel(options) {
229
273
  const spoken = (naming.length ? naming : cells.filter((cell) => cell.display).slice(0, 1))
230
274
  .map((cell) => `${cell.label} "${spokenValue(cell.display)}"`)
231
275
  .join(', ');
232
- return Object.assign({ index: row.index, details: row.details, cells, label: spoken || `row ${row.index + 1}` }, (((_c = row.problems) === null || _c === void 0 ? void 0 : _c.length) ? { problems: row.problems } : {}));
276
+ return Object.assign({ index: row.index, details: row.details, cells, label: spoken || `row ${row.index + 1}` }, ((problems === null || problems === void 0 ? void 0 : problems.length) ? { problems } : {}));
233
277
  });
234
- return Object.assign({ resource,
278
+ return Object.assign(Object.assign({ resource,
235
279
  op,
236
- columns, rows: built, selectable: built.filter((row) => { var _a; return !((_a = row.problems) === null || _a === void 0 ? void 0 : _a.length); }).map((row) => row.index) }, (customCode
280
+ columns, rows: built, selectable: built.filter((row) => { var _a; return !((_a = row.problems) === null || _a === void 0 ? void 0 : _a.length); }).map((row) => row.index) }, (run
281
+ ? {
282
+ rowAction: {
283
+ handler: run.handler,
284
+ entity: run.entity,
285
+ effects: run.effects.map(({ op: write, table }) => ({ op: write, table })),
286
+ },
287
+ }
288
+ : {})), (customCode
237
289
  ? {
238
290
  customCode: {
239
291
  alsoWrites: [...customCode.alsoWrites],
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Whether a write reads its row before the review, and again before it commits.
3
+ *
4
+ * @remarks
5
+ * Every place that asks this asks it here. A row action reads its row like a modify, and a site
6
+ * left asking "modify or delete" would treat one like an insert: no row read, no merge, no
7
+ * staleness check before the commit.
8
+ *
9
+ * @internal
10
+ */
11
+ export const readsRow = (op) => op === 'modify' || op === 'delete' || op === 'row-action';
12
+ /**
13
+ * How a model-facing sentence names one write: "a modify", "a delete", or, for a row action, "a run
14
+ * of this handler". The op's own name is never put in front of the model: `row-action` is ours.
15
+ *
16
+ * @internal
17
+ */
18
+ export const aWrite = (op) => op === 'row-action' ? 'a run of this handler' : `a ${op}`;
@@ -1,6 +1,7 @@
1
1
  import { logger } from '../utils/logger';
2
2
  import { serialisable } from './serialisable';
3
3
  import { plainFieldName, plainServerText, readsLikeFieldName, readsLikeKeyValue, } from './server-text';
4
+ import { readsRow } from './write-op';
4
5
  /**
5
6
  * Whether a MSG_NACK error says the event is not mapped to a service — the one MSG_NACK that
6
7
  * means nothing ran. Live 8.15: `{"CODE": 404, "TEXT": "Resource EVENT_X is not mapped to a
@@ -238,7 +239,9 @@ export function mapWriteReply(reply, { mode, op }) {
238
239
  }
239
240
  // Everything from here is an EVENT_NACK: the HANDLER's own answer. It is read as "not written"
240
241
  // whatever STATUS_CODE its errors carry, 5xx included — do not "fix" that to `unknown` by
241
- // analogy with the router's MSG_NACK above, but know exactly what it rests on.
242
+ // analogy with the router's MSG_NACK above, but know exactly what it rests on. The code is not
243
+ // a signal here: a handler's own nack() arrives as INTERNAL_ERROR 500, a throw as
244
+ // REQUEST_FAILED 400 (contracts C-18.L, LC-8 and LC-9).
242
245
  //
243
246
  // genesis-server v8.15.14, TransactionalEventHandlerContainer.transactionalEventFlow
244
247
  // (genesis-parent/genesis-pal-eventhandler/.../eventhandler/pal/parse/
@@ -250,17 +253,21 @@ export function mapWriteReply(reply, { mode, op }) {
250
253
  // - onCommit writes rows and then RETURNS nack(): the block completes normally, nothing rolls
251
254
  // back, and those writes COMMIT, under a NACK.
252
255
  // So "an EVENT_NACK means not written" holds for the handlers this path accepts: Create-
253
- // generated CRUD handlers, which write and ack(), or throw and roll back. It does not hold in
254
- // general — a hand-written handler that writes and then returns nack() commits its writes —
255
- // and that is one more reason `custom` events get no write tool.
256
+ // generated CRUD handlers, which write and ack(), or throw and roll back; and a ROW ACTION's
257
+ // handler, which the app generator accepts only when its code never nacks after a write and
258
+ // never writes while validating (contracts C-18.4 G12 and G7), so it too nacks before writing
259
+ // or throws and rolls back (contracts C-18.L, LC-9: a throw after a modify and an insert
260
+ // rolled both back). It does not hold in general — a hand-written handler that writes and
261
+ // then returns nack() commits its writes — and that is why any other custom event gets no
262
+ // write tool.
256
263
  //
257
- // Only a modify or a delete has an existing row to lose. On an insert RECORD_NOT_FOUND is a
264
+ // Only an op that read its row has an existing row to lose. On an insert RECORD_NOT_FOUND is a
258
265
  // reference the handler looked up ("Counterparty 'CP999' does not exist"), and "that row changed
259
266
  // or was removed" was said about a row it was creating, with the app's reason dropped. An insert
260
267
  // falls through to the ordinary classification: the live shape, a TableStandardError, is a
261
268
  // database_error; anything else, the app's refusal. Both are not written, and both carry the
262
269
  // server's own text.
263
- if ((op === 'modify' || op === 'delete') && codes.has('RECORD_NOT_FOUND')) {
270
+ if (readsRow(op) && codes.has('RECORD_NOT_FOUND')) {
264
271
  return Object.assign(Object.assign({ status: 'gone' }, withFields), { message: `That row changed or was removed, so nothing was written: ${joined(errors)}` });
265
272
  }
266
273
  if (codes.has('DUPLICATE_KEY')) {
@@ -2,6 +2,7 @@ import { utcMillisOf } from './calendar';
2
2
  import { cannotBeChanged, notAcceptedHere } from './reference-check';
3
3
  import { genesisTypeName } from './type-name';
4
4
  import { sameValue } from './value-compare';
5
+ import { aWrite, readsRow } from './write-op';
5
6
  /**
6
7
  * Epoch millis, the floor below which a "date" is not one.
7
8
  *
@@ -85,7 +86,7 @@ const timeOfDayOnADay = (field, value) => DAY_TYPES.has(genesisTypeName(field.ty
85
86
  * row's value is the row's too. `fromRow` is false for an echo, so the value is compared with the
86
87
  * row's.
87
88
  */
88
- function timeOfDayRefusal(field, { raw, value, fromRow, rowValue, }) {
89
+ function timeOfDayRefusal(field, { raw, value, fromRow, rowValue, op, }) {
89
90
  if (fromRow || !timeOfDayOnADay(field, value))
90
91
  return undefined;
91
92
  const rowMillis = rowValue === undefined ? undefined : toEpochMillis(rowValue);
@@ -94,7 +95,10 @@ function timeOfDayRefusal(field, { raw, value, fromRow, rowValue, }) {
94
95
  // The row itself holds a time here, and an echo of it that is off by a second, or spelt without
95
96
  // its seconds, is not that value. Sent as the bare day it would overwrite the stored time, so
96
97
  // the model is told it can leave the field out instead.
97
- const keep = timeOfDayOnADay(field, rowMillis) ? ", or leave it out to keep the row's value" : '';
98
+ // A run's input cannot be left out: the handler needs it.
99
+ const keep = op !== 'row-action' && timeOfDayOnADay(field, rowMillis)
100
+ ? ", or leave it out to keep the row's value"
101
+ : '';
98
102
  return `${field.name} is a date; send it without a time of day${keep} (got '${quoted(raw)}')`;
99
103
  }
100
104
  /** Genesis types that hold a whole number, whatever JSON type their metadata declares. */
@@ -325,10 +329,11 @@ export const PLATFORM_MAINTAINED = new Set(['RECORD_ID', 'TIMESTAMP']);
325
329
  * field is carried from the row (see `sourceOf`), and a model value that differs is refused by
326
330
  * name: keyed on another field, `changes: { TRADE_ID: 'SOMEONE_ELSE' }` used to go on the wire.
327
331
  *
328
- * A `custom` event stays strict: its semantics are the app's, so there is nothing to reason
329
- * from, and its NACK will say what it wanted.
332
+ * A row action is loosened as a modify is: its handler loads the row by the key it is sent, so
333
+ * the row's own key has to travel. A plain `custom` event stays strict: its semantics are the
334
+ * app's, so there is nothing to reason from, and its NACK will say what it wanted.
330
335
  */
331
- const readOnlyAllowedFor = (op) => op === 'modify' || op === 'delete';
336
+ const readOnlyAllowedFor = (op) => readsRow(op);
332
337
  /**
333
338
  * The fields this op may put on the wire: what the event declares, minus the platform's own
334
339
  * columns, minus anything the op may not send.
@@ -490,6 +495,12 @@ function sourceOf(field, given, changes, rowValue, merge, op) {
490
495
  // "change" whose two sides render identically, or a `' '` that in effect cleared the column
491
496
  // this tool says it cannot clear; on an insert, spaces written into a column the review showed
492
497
  // as empty. With no row value to keep, a blank is simply not set.
498
+ // A run's input is never the row's value: the handler is given what the model sent or nothing,
499
+ // and a blank one is refused. The planner refuses it first; this is the second guard, so the row's
500
+ // current price can never go in as the "new" one (contracts C-18.7.6).
501
+ if (modelSent && isBlankEntry(raw) && op === 'row-action') {
502
+ return { raw, fromRow: false, problem: `input ${field.name} is required` };
503
+ }
493
504
  if (modelSent && isBlankEntry(raw)) {
494
505
  return rowHas ? { raw: rowValue, fromRow: true } : { raw: '', fromRow: false };
495
506
  }
@@ -547,13 +558,14 @@ export function buildEventPayload(fields, row, { op, preImage, unchecked }) {
547
558
  // semantics the unnamed fields would be written as null. Saying so beats the required-field
548
559
  // loop's "SYMBOL needs a value", which blames the model for a value it cannot supply — the
549
560
  // row was never read.
550
- if ((op === 'modify' || op === 'delete') && !preImage) {
561
+ if (readsRow(op) && !preImage) {
551
562
  return {
552
563
  status: 'rejected',
553
- problems: [`a ${op} must be based on a row that was read first`],
564
+ problems: [`${aWrite(op)} must be based on a row that was read first`],
554
565
  };
555
566
  }
556
- // Merged for a MODIFY only.
567
+ // Merged for a MODIFY and a row action only. A row action's handler loads the row and saves it
568
+ // back, so it is sent whole: the row as read, with the inputs applied (contracts C-18.7.6).
557
569
  //
558
570
  // The merge exists because a generated modify replaces the record, so a payload carrying only
559
571
  // the named fields writes null over the rest. A delete has no such semantics: the showcase's
@@ -564,7 +576,7 @@ export function buildEventPayload(fields, row, { op, preImage, unchecked }) {
564
576
  //
565
577
  // An insert never inherits either, even if a caller hands it a pre-image: a new record must
566
578
  // contain what the user saw proposed and nothing else.
567
- const merge = !!preImage && op === 'modify';
579
+ const merge = !!preImage && (op === 'modify' || op === 'row-action');
568
580
  // A delete is its key: `changes` is meaningless on one, and the rest of the record is not
569
581
  // something it sends.
570
582
  // A DELETE is built from the ROW'S OWN key, never from the key the model searched with.
@@ -644,7 +656,7 @@ export function buildEventPayload(fields, row, { op, preImage, unchecked }) {
644
656
  }
645
657
  const converted = valueFor(field, raw);
646
658
  const { value } = converted;
647
- const problem = (_a = converted.problem) !== null && _a !== void 0 ? _a : timeOfDayRefusal(field, { raw, value, fromRow, rowValue });
659
+ const problem = (_a = converted.problem) !== null && _a !== void 0 ? _a : timeOfDayRefusal(field, { raw, value, fromRow, rowValue, op });
648
660
  if (problem) {
649
661
  // Attribute it correctly. A value carried from the pre-image is the SERVER's own — most
650
662
  // often a LONG beyond 2^53 that the read stamped as text and a JSON integer cannot carry