@genesislcap/ai-assistant 15.37.0 → 15.38.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/custom-elements.json +638 -0
  2. package/dist/dts/genesis/calendar.d.ts +25 -0
  3. package/dist/dts/genesis/calendar.d.ts.map +1 -0
  4. package/dist/dts/genesis/config.d.ts +16 -0
  5. package/dist/dts/genesis/config.d.ts.map +1 -1
  6. package/dist/dts/genesis/criteria.d.ts +24 -2
  7. package/dist/dts/genesis/criteria.d.ts.map +1 -1
  8. package/dist/dts/genesis/event-fields.d.ts +84 -0
  9. package/dist/dts/genesis/event-fields.d.ts.map +1 -0
  10. package/dist/dts/genesis/filter-fields.d.ts +69 -5
  11. package/dist/dts/genesis/filter-fields.d.ts.map +1 -1
  12. package/dist/dts/genesis/index.d.ts +3 -0
  13. package/dist/dts/genesis/index.d.ts.map +1 -1
  14. package/dist/dts/genesis/register-genesis-assistant.d.ts +13 -0
  15. package/dist/dts/genesis/register-genesis-assistant.d.ts.map +1 -1
  16. package/dist/dts/genesis/resource-tools.d.ts.map +1 -1
  17. package/dist/dts/genesis/review-model.d.ts +202 -0
  18. package/dist/dts/genesis/review-model.d.ts.map +1 -0
  19. package/dist/dts/genesis/row-source.d.ts +102 -0
  20. package/dist/dts/genesis/row-source.d.ts.map +1 -0
  21. package/dist/dts/genesis/serialisable.d.ts +25 -0
  22. package/dist/dts/genesis/serialisable.d.ts.map +1 -0
  23. package/dist/dts/genesis/server-text.d.ts +63 -0
  24. package/dist/dts/genesis/server-text.d.ts.map +1 -0
  25. package/dist/dts/genesis/type-name.d.ts +18 -0
  26. package/dist/dts/genesis/type-name.d.ts.map +1 -0
  27. package/dist/dts/genesis/types.d.ts +7 -0
  28. package/dist/dts/genesis/types.d.ts.map +1 -1
  29. package/dist/dts/genesis/value-compare.d.ts +19 -0
  30. package/dist/dts/genesis/value-compare.d.ts.map +1 -0
  31. package/dist/dts/genesis/write-commit.d.ts +53 -0
  32. package/dist/dts/genesis/write-commit.d.ts.map +1 -0
  33. package/dist/dts/genesis/write-outcome.d.ts +133 -0
  34. package/dist/dts/genesis/write-outcome.d.ts.map +1 -0
  35. package/dist/dts/genesis/write-payload.d.ts +129 -0
  36. package/dist/dts/genesis/write-payload.d.ts.map +1 -0
  37. package/dist/dts/genesis/write-plan.d.ts +109 -0
  38. package/dist/dts/genesis/write-plan.d.ts.map +1 -0
  39. package/dist/dts/genesis/write-review/write-review.d.ts +127 -0
  40. package/dist/dts/genesis/write-review/write-review.d.ts.map +1 -0
  41. package/dist/dts/genesis/write-review/write-review.styles.d.ts +2 -0
  42. package/dist/dts/genesis/write-review/write-review.styles.d.ts.map +1 -0
  43. package/dist/dts/genesis/write-review/write-review.template.d.ts +4 -0
  44. package/dist/dts/genesis/write-review/write-review.template.d.ts.map +1 -0
  45. package/dist/dts/genesis/write-tools.d.ts +99 -0
  46. package/dist/dts/genesis/write-tools.d.ts.map +1 -0
  47. package/dist/dts/react.d.ts +10 -0
  48. package/dist/esm/genesis/calendar.js +38 -0
  49. package/dist/esm/genesis/config.js +36 -1
  50. package/dist/esm/genesis/criteria.js +59 -55
  51. package/dist/esm/genesis/event-fields.js +158 -0
  52. package/dist/esm/genesis/filter-fields.js +111 -20
  53. package/dist/esm/genesis/index.js +2 -0
  54. package/dist/esm/genesis/register-genesis-assistant.js +76 -4
  55. package/dist/esm/genesis/resource-tools.js +21 -103
  56. package/dist/esm/genesis/review-model.js +248 -0
  57. package/dist/esm/genesis/row-source.js +127 -0
  58. package/dist/esm/genesis/serialisable.js +38 -0
  59. package/dist/esm/genesis/server-text.js +186 -0
  60. package/dist/esm/genesis/type-name.js +20 -0
  61. package/dist/esm/genesis/value-compare.js +87 -0
  62. package/dist/esm/genesis/write-commit.js +78 -0
  63. package/dist/esm/genesis/write-outcome.js +299 -0
  64. package/dist/esm/genesis/write-payload.js +632 -0
  65. package/dist/esm/genesis/write-plan.js +275 -0
  66. package/dist/esm/genesis/write-review/write-review.js +252 -0
  67. package/dist/esm/genesis/write-review/write-review.styles.js +214 -0
  68. package/dist/esm/genesis/write-review/write-review.template.js +182 -0
  69. package/dist/esm/genesis/write-tools.js +660 -0
  70. package/dist/react.cjs +7 -0
  71. package/dist/react.mjs +6 -0
  72. package/docs/genesis.md +152 -10
  73. package/package.json +18 -18
@@ -2,9 +2,11 @@ import { __awaiter } from "tslib";
2
2
  import { getConnect } from '@genesislcap/foundation-comms';
3
3
  import { logger } from '../utils/logger';
4
4
  import { withTimeout } from '../utils/with-timeout';
5
- import { DEFAULT_MAX_ROWS, toolNameOf } from './config';
5
+ import { DEFAULT_MAX_ROWS, MAX_ROWS_CEILING, toolNameOf } from './config';
6
6
  import { composeCriteria } from './criteria';
7
7
  import { loadFilterFields } from './filter-fields';
8
+ import { serialisable } from './serialisable';
9
+ import { plainFailure, plainServerText } from './server-text';
8
10
  /**
9
11
  * The provenance stamped on everything a tool returns from the app (ADR P9). Rows are written by
10
12
  * the app's other users, so the model must treat their text as data, never as instructions; the
@@ -88,35 +90,6 @@ function readDefinition(resource, cap, fields) {
88
90
  parameters: { type: 'object', properties, additionalProperties: false },
89
91
  };
90
92
  }
91
- /**
92
- * Rows as they can be serialised.
93
- *
94
- * @remarks
95
- * Comms' own deserializer turns any integer outside the safe range into a `BigInt`
96
- * (`foundation-utils` `customNumberParser`), so a Genesis LONG or BIGINT column arrives as one.
97
- * The chat driver calls `JSON.stringify` on whatever a tool returns, and that throws on a
98
- * BigInt — one such column anywhere in a row killed the turn with
99
- * "TypeError: Do not know how to serialize a BigInt".
100
- *
101
- * A value that fits a JS number exactly becomes one; anything larger becomes its decimal
102
- * string, because the alternative is telling the model a number that is quietly wrong. Nested
103
- * values are walked: the BigInt can sit inside an object or an array in the row.
104
- */
105
- function serialisable(value) {
106
- if (typeof value === 'bigint') {
107
- const asNumber = Number(value);
108
- return Number.isSafeInteger(asNumber) ? asNumber : value.toString();
109
- }
110
- if (Array.isArray(value))
111
- return value.map(serialisable);
112
- if (value && typeof value === 'object') {
113
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [
114
- key,
115
- serialisable(item),
116
- ]));
117
- }
118
- return value;
119
- }
120
93
  /**
121
94
  * Why a truncated read has no next page.
122
95
  *
@@ -150,7 +123,18 @@ export function createGenesisResourceTools(resources, options = {}) {
150
123
  const requests = resources
151
124
  .filter((r) => r.kind === 'request')
152
125
  .sort((a, b) => a.name.localeCompare(b.name));
153
- const capOf = (r) => { var _a; return (_a = r.maxRows) !== null && _a !== void 0 ? _a : DEFAULT_MAX_ROWS; };
126
+ // Held to the ceiling HERE as well as in the config validator, for the reason `decideOp` is
127
+ // re-checked at the point of use: this factory is exported, and a host calling it directly
128
+ // never passes through the validator. The cap is what stops one read pulling tens of thousands
129
+ // of rows into the conversation and out to the model vendor (ADR P10), so it cannot be a rule
130
+ // that only one entry point obeys. Anything that is not a usable whole number falls back to
131
+ // the default; anything outside the range is clamped into it.
132
+ const capOf = (r) => {
133
+ const asked = r.maxRows;
134
+ if (typeof asked !== 'number' || !Number.isFinite(asked))
135
+ return DEFAULT_MAX_ROWS;
136
+ return Math.min(Math.max(Math.floor(asked), 1), MAX_ROWS_CEILING);
137
+ };
154
138
  const resolveConnect = () => {
155
139
  var _a;
156
140
  try {
@@ -222,62 +206,6 @@ export function createGenesisResourceTools(resources, options = {}) {
222
206
  }
223
207
  return { toolDefinitions, toolHandlers };
224
208
  }
225
- /**
226
- * One short plain sentence — the shape an app's own refusal takes, and the shape a stack trace,
227
- * a SQL error or a Java class name does not.
228
- *
229
- * @remarks
230
- * Deliberately an ALLOW-list on shape. The first version matched the server's text for things it
231
- * recognised (`Groovy`, `Script\d+`), which made it a deny-list: anything unfamiliar went
232
- * straight through to the model and onto the user's screen, and there is no reason to think the
233
- * four patterns seen so far are the only ones a platform can produce. Reviewer catch on #2543 —
234
- * his diagnosis exactly, with a different fix, because suppressing every refusal on a filtered
235
- * read throws away the half worth keeping (see {@link readableRefusal}).
236
- *
237
- * The character set does much of the work: no colon, so `ORA-00904:` and
238
- * `global.genesis.Foo$Bar:` are out; no braces, semicolons, angle brackets or backticks; nothing
239
- * below a space, so a multi-line trace cannot pass. Underscores are allowed, because
240
- * "TRADE_ID is required" is an app message worth keeping — which is what leaves real work for
241
- * the three shape tests below rather than making them decoration.
242
- *
243
- * It is fail-closed by construction, and it will occasionally sanitise a legitimate message that
244
- * happens to read like code. That costs the model a phrase; the other direction costs a
245
- * disclosure.
246
- */
247
- const PLAIN_SENTENCE_LIMIT = 160;
248
- const PLAIN_SENTENCE = /^[A-Za-z0-9_ ,.'"!?%/()-]+$/;
249
- /** `Expr.foo(`, `doThing(` — a call, whatever it is called. */
250
- const CALL_SHAPE = /[A-Za-z0-9_]\(/;
251
- /** A dotted identifier: `Script166.groovy`, `global.genesis`. Not `1.5`, which starts a digit. */
252
- const DOTTED_NAME = /[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_]/;
253
- /** `ORA-00904`, `SQL-1234`: an error code carries no punctuation to catch it by. */
254
- const ERROR_CODE = /\b[A-Za-z]{2,}-\d+\b/;
255
- /** {@link withTimeout}'s own rejection: this bridge's message, not the app's. */
256
- const TIMED_OUT = /^withTimeout:/;
257
- /**
258
- * Whatever a rejection turns out to be, as a sentence.
259
- *
260
- * @remarks
261
- * Comms rejects with a plain object rather than an `Error` on the socket path, so `String(error)`
262
- * handed the model `The read failed: [object Object]` — which tells it nothing and, worse, reads
263
- * like the bridge having no idea what happened. An `Error` still answers with its message.
264
- */
265
- function describeFailure(error) {
266
- var _a;
267
- if (error instanceof Error)
268
- return error.message;
269
- const named = (_a = error) !== null && _a !== void 0 ? _a : {};
270
- for (const candidate of [named.message, named.TEXT, named.ERROR]) {
271
- if (typeof candidate === 'string' && candidate.length)
272
- return candidate;
273
- }
274
- return 'the app gave no reason';
275
- }
276
- const readsLikeProse = (text) => text.length <= PLAIN_SENTENCE_LIMIT &&
277
- PLAIN_SENTENCE.test(text) &&
278
- !CALL_SHAPE.test(text) &&
279
- !DOTTED_NAME.test(text) &&
280
- !ERROR_CODE.test(text);
281
209
  /**
282
210
  * What the model is told when the server refuses a read.
283
211
  *
@@ -300,12 +228,9 @@ const readsLikeProse = (text) => text.length <= PLAIN_SENTENCE_LIMIT &&
300
228
  * one whoever is debugging the bridge needs to see.
301
229
  */
302
230
  function readableRefusal(text, resourceName, filtered) {
303
- if (text && readsLikeProse(text))
304
- return text;
305
- logger.error(`Genesis assistant: ${resourceName} refused a read: ${text || '(the reply named no reason)'}`);
306
- return filtered
231
+ return plainServerText(text, `${resourceName} refused a read`, filtered
307
232
  ? 'That filter was not accepted by the app. Try different fields or fewer conditions.'
308
- : 'The app refused the read.';
233
+ : 'The app refused the read.');
309
234
  }
310
235
  function readRows(resource_1, cap_1, args_1, connect_1, filterFields_1) {
311
236
  return __awaiter(this, arguments, void 0, function* (resource, cap, args, connect, filterFields, timeoutMs = READ_TIMEOUT_MS) {
@@ -343,17 +268,10 @@ function readRows(resource_1, cap_1, args_1, connect_1, filterFields_1) {
343
268
  }), timeoutMs);
344
269
  }
345
270
  catch (error) {
346
- const detail = describeFailure(error);
347
- logger.error(`Genesis assistant: ${resource.name} read failed: ${detail}`);
348
- // Our own timeout, said in words rather than passed through the sanitiser: it is not server
349
- // text, and "the read took too long" is something the model can actually do something about.
350
- if (TIMED_OUT.test(detail)) {
351
- return fail('request_failed', 'The read took too long and was abandoned. Try again, or narrow it with filters.');
352
- }
353
- // Everything else goes through the same shape test the server's own refusals take: a
354
- // rejected Message can carry the server's text, and a transport failure is no reason to
355
- // stop caring where that text ends up.
356
- return fail('request_failed', readsLikeProse(detail) ? `The read failed: ${detail}` : 'The read failed.');
271
+ return fail('request_failed', plainFailure(error, `${resource.name} read failed`, {
272
+ timeout: 'The read took too long and was abandoned. Try again, or narrow it with filters.',
273
+ failed: 'The read failed',
274
+ }));
357
275
  }
358
276
  const errors = reply === null || reply === void 0 ? void 0 : reply.ERROR;
359
277
  if (Array.isArray(errors) && errors.length) {
@@ -0,0 +1,248 @@
1
+ import { formatTimestamp } from '@genesislcap/foundation-utils';
2
+ import { genesisTypeName } from './type-name';
3
+ import { sameValue } from './value-compare';
4
+ import { PLATFORM_MAINTAINED } from './write-payload';
5
+ /**
6
+ * A column's heading when the metadata gives it no title: the field name in words, each
7
+ * capitalised — `COUNTERPARTY_ID` is "Counterparty Id".
8
+ *
9
+ * @remarks
10
+ * Taken to be the platform's own default, which is an INFERENCE: the live 8.15 captures hold
11
+ * three titles and all three follow it (`COMMISSION` "Commission", `COUNTERPARTY_ID`
12
+ * "Counterparty Id", `CREATED_AT` "Created At"). A dictionary that titles a field some other way
13
+ * is not seen here, which is harmless: this is only ever used where no title was declared.
14
+ * A delete's review needs it most. Its columns come from the read resource, whose reply carries
15
+ * no titles at all, and a `.ById` delete event declares only its key — so the same record read
16
+ * as `COUNTERPARTY_ID` in a delete and "Counterparty Id" in a modify. A declared title always
17
+ * wins over this.
18
+ */
19
+ const defaultTitle = (name) => name
20
+ .split('_')
21
+ .filter(Boolean)
22
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
23
+ .join(' ');
24
+ /**
25
+ * Past this many characters a value wraps; at or under it, it stays on one line.
26
+ *
27
+ * @remarks
28
+ * Wrapping every cell broke SHORT values mid-token in a squeezed table: `+ 101.2345` became
29
+ * `101.` over `2345`, and the first line could pass for the whole value, which is approving what
30
+ * you did not see again. A short value is kept whole on one line and the table scrolls; only a
31
+ * value long enough to push the change out of view wraps, where being on several lines is plain.
32
+ */
33
+ export const LONG_VALUE = 24;
34
+ /**
35
+ * How much of a value is spoken in a row's accessible name.
36
+ *
37
+ * @remarks
38
+ * Long enough to identify a record, short enough that one cell cannot become the announcement.
39
+ * The double quote is stripped for the same reason the refusal echo strips the single one: it
40
+ * is the delimiter, and text that closes it reads as ours.
41
+ */
42
+ const MAX_SPOKEN = 48;
43
+ const spokenValue = (display) => {
44
+ const text = display.replace(/"/g, '');
45
+ return text.length > MAX_SPOKEN ? `${text.slice(0, MAX_SPOKEN)}…` : text;
46
+ };
47
+ /**
48
+ * For a NANO_TIMESTAMP only: the window in which reading it as epoch millis is believable. Outside
49
+ * it, the unit is the likelier thing to be wrong.
50
+ */
51
+ const FIRST_PLAUSIBLE_YEAR = 1971;
52
+ /** The years a four-digit formatter can write whole; outside them a date is shown as its millis. */
53
+ const FIRST_WRITABLE_YEAR = 0;
54
+ const LAST_WRITABLE_YEAR = 9999;
55
+ const LAST_PLAUSIBLE_YEAR = 2999;
56
+ /**
57
+ * A value as a person should read it.
58
+ *
59
+ * @remarks
60
+ * Driven by the field's DECLARED type, never by its name: `CREATED_AT` is a DATETIME and ends
61
+ * in neither "DATE" nor "TIME", so a name heuristic would show a user
62
+ * `CREATED_AT 1790001000000` and call it a review. Display only — a formatted date must never
63
+ * re-enter the payload, or the identity property is undone from the presentation side.
64
+ *
65
+ * Formatting is `foundation-utils`' own `formatTimestamp` rather than a local slice of an ISO
66
+ * string: it is the same rendering the rest of the platform's UI gives a DATE and a DATETIME, so
67
+ * a trade's date reads here the way it reads in a grid. It also shows SECONDS, which a local
68
+ * version cut to the minute — and seconds matter on this screen. Genesis does not truncate them
69
+ * (a capture shows `13:27:05` stored as sent), so two timestamps that differ only in seconds
70
+ * used to render identically to an approver and rely on the changed-mark alone to tell them
71
+ * apart.
72
+ *
73
+ * @internal
74
+ */
75
+ export function displayValue(value, type) {
76
+ var _a;
77
+ if (value === undefined || value === null)
78
+ return '';
79
+ const genesisType = genesisTypeName(type);
80
+ const isDate = genesisType === 'DATE' || genesisType === 'LOCALDATE';
81
+ const isDateTime = genesisType === 'DATETIME' ||
82
+ genesisType === 'LOCALDATETIME' ||
83
+ genesisType === 'TIMESTAMP' ||
84
+ genesisType === 'NANO_TIMESTAMP';
85
+ // Only a NUMBER is ever a date here. A digit STRING never is, and a path that tried to read one
86
+ // could not format anything real: the row normaliser (`serialisable`) stamps an integer as
87
+ // text only when it is beyond 2^53, which is past the last instant a JavaScript Date can hold
88
+ // (8.64e15 ms), so every such value became an invalid date and fell through to raw anyway —
89
+ // while a test with a 13-digit string the normaliser never produces said it worked.
90
+ //
91
+ // So a NANO_TIMESTAMP in NANOSECONDS — beyond 2^53 for any instant after April 1970, and so
92
+ // always text — is shown RAW, by design, until its unit is captured from a live app. Raw is
93
+ // honest. A guess at the unit would dress 19 digits up as a date that may be wrong.
94
+ const epoch = typeof value === 'number' ? value : undefined;
95
+ if ((isDate || isDateTime) && epoch !== undefined) {
96
+ const year = new Date(epoch).getUTCFullYear();
97
+ // A plausibility window, but ONLY where the unit is in doubt. Reading a NANO_TIMESTAMP as
98
+ // milliseconds can produce the year 58000 — no NaN, no complaint, and a date nobody can read
99
+ // — and whether its unit is nanoseconds is unverified, so outside the window it is shown raw.
100
+ //
101
+ // A DATE or DATETIME is epoch millis, known, and the window is wrong for it: it showed
102
+ // `9999-12-31`, the usual open-ended maturity in finance data, and any date before 1971 as
103
+ // raw millis. What bounds it instead is what the formatter can write: a four-digit year.
104
+ // Outside 0–9999 its fixed-width pattern drops the day or the seconds, so a date the user is
105
+ // approving would be shown incomplete. Raw millis are ugly, but they are the whole value.
106
+ const plausible = genesisType === 'NANO_TIMESTAMP'
107
+ ? year >= FIRST_PLAUSIBLE_YEAR && year <= LAST_PLAUSIBLE_YEAR
108
+ : year >= FIRST_WRITABLE_YEAR && year <= LAST_WRITABLE_YEAR;
109
+ if (plausible) {
110
+ // The formatter reads 0 as "no timestamp" (`!timestamp`) and returns null, so the epoch
111
+ // itself was shown as a bare `0` — reachable from a model sending '1970-01-01'. Said here in
112
+ // the formatter's own UTC pattern, rather than changing a public formatter whose other
113
+ // callers may rely on 0 rendering blank. `=== 0` covers -0.
114
+ if (epoch === 0)
115
+ return isDateTime ? '1970-01-01 00:00:00' : '1970-01-01';
116
+ // `withTime` false drops the time a date-only field never carried.
117
+ return (_a = formatTimestamp(epoch, isDateTime)) !== null && _a !== void 0 ? _a : String(value);
118
+ }
119
+ }
120
+ return String(value);
121
+ }
122
+ /**
123
+ * Builds what the table renders.
124
+ *
125
+ * @remarks
126
+ * `details` is carried by reference into each row, so the object shown is the object committed.
127
+ * The display strings are derived FROM it and never flow back: a formatted date re-entering the
128
+ * payload would undo the identity property from the presentation side.
129
+ *
130
+ * @internal
131
+ */
132
+ export function buildReviewModel(options) {
133
+ var _a;
134
+ const { resource, op, fields = [], rows } = options;
135
+ const byName = new Map(fields.map((field) => [field.name, field]));
136
+ // Declared order first, then anything a row carries that the metadata did not describe, in the
137
+ // order it is first seen. One column list, so every row's cells line up under it.
138
+ const columnNames = fields.map((field) => field.name);
139
+ for (const row of rows) {
140
+ // What is RENDERED, which for a delete is the whole row rather than the key it sends. The
141
+ // platform's own columns are left out: a modify's review hides them because they never
142
+ // travel, and a delete showing RECORD_ID and TIMESTAMP would be the same table telling the
143
+ // user two different stories about what a column means.
144
+ for (const field of Object.keys((_a = row.display) !== null && _a !== void 0 ? _a : row.details)) {
145
+ if (!columnNames.includes(field) && !PLATFORM_MAINTAINED.has(field))
146
+ columnNames.push(field);
147
+ }
148
+ }
149
+ const columns = columnNames.map((field) => {
150
+ var _a, _b;
151
+ return ({
152
+ field,
153
+ label: (_b = (_a = byName.get(field)) === null || _a === void 0 ? void 0 : _a.title) !== null && _b !== void 0 ? _b : defaultTitle(field),
154
+ });
155
+ });
156
+ const built = rows.map((row) => {
157
+ var _a, _b, _c;
158
+ // A REFUSED row will not be written, so it has no change to show — and a refused modify comes
159
+ // with its pre-image and an EMPTY payload, which marked every non-empty field as changed and
160
+ // rendered the row as a full wipe: each old value struck through over an empty new one. The
161
+ // screen whose job is to show what will happen showed the most alarming outcome, for a row
162
+ // that will not happen at all, often beside a refusal reading "this modify changes nothing".
163
+ // So a refused row shows the row as it stands, and nothing on it is marked as changing.
164
+ const refused = !!((_a = row.problems) === null || _a === void 0 ? void 0 : _a.length);
165
+ const compared = refused ? undefined : row.preImage;
166
+ const shown = (_b = row.display) !== null && _b !== void 0 ? _b : (refused && row.preImage ? row.preImage : row.details);
167
+ // Only meaningful where the two differ; on a modify or an insert everything shown is sent.
168
+ const marksIdentifying = !!row.display;
169
+ const cells = columnNames.map((field) => {
170
+ var _a, _b;
171
+ const declared = byName.get(field);
172
+ const previous = compared ? compared[field] : undefined;
173
+ const display = displayValue(shown[field], declared === null || declared === void 0 ? void 0 : declared.type);
174
+ const previousDisplay = compared ? displayValue(previous, declared === null || declared === void 0 ? void 0 : declared.type) : undefined;
175
+ 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 } : {})), {
176
+ // Compared on the VALUES, with both sides normalised — never on the display text.
177
+ // Display is deliberately lossy (a timestamp is rendered to the minute), so a change of
178
+ // seconds would render identically on both sides and go unmarked, which is the review
179
+ // failing at its one job. A raw comparison would be wrong the other way, marking every
180
+ // row changed, so the normaliser is what makes both correct.
181
+ 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 });
182
+ });
183
+ // The identifying cells where the row has them — a delete marks its key, and a modify or an
184
+ // insert has none, so those fall back to the first cell that carries a value.
185
+ const naming = cells.filter((cell) => cell.identifying && cell.display);
186
+ // Bounded and delimited, because this is ROW TEXT — written by another user of the app —
187
+ // spliced into a sentence of ours and then read aloud. Unbounded it lets one value run over
188
+ // the whole announcement; undelimited there is nothing between their words and ours.
189
+ const spoken = (naming.length ? naming : cells.filter((cell) => cell.display).slice(0, 1))
190
+ .map((cell) => `${cell.label} "${spokenValue(cell.display)}"`)
191
+ .join(', ');
192
+ 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 } : {}));
193
+ });
194
+ return {
195
+ resource,
196
+ op,
197
+ columns,
198
+ rows: built,
199
+ selectable: built.filter((row) => { var _a; return !((_a = row.problems) === null || _a === void 0 ? void 0 : _a.length); }).map((row) => row.index),
200
+ };
201
+ }
202
+ /**
203
+ * The selection a freshly opened review starts with: none.
204
+ *
205
+ * @remarks
206
+ * Called by the component rather than duplicated there. A tested helper nothing uses is an
207
+ * orphaned guarantee — the next person to change the component's default would not fail its
208
+ * test.
209
+ *
210
+ * @internal
211
+ */
212
+ export const initialSelection = () => [];
213
+ /**
214
+ * The selection a still-open review resumes with when it is mounted again: what the user had
215
+ * ticked, as far as the model still offers it.
216
+ *
217
+ * @remarks
218
+ * A pending review is a fresh element on every remount — a reparent in the layout, a dock, a
219
+ * transcript re-render — so a selection held only on the element was dropped, and a user on a
220
+ * twenty-row review redid it with nothing to say why. What is parked survives on the
221
+ * interaction's context; what comes back through here is filtered to the selectable rows, in
222
+ * table order, so a refused row or anything that is not an index can never be restored into a
223
+ * selection. Anything that is not a list is nothing parked, and a fresh review starts empty.
224
+ *
225
+ * @internal
226
+ */
227
+ export const restoredSelection = (model, parked) => {
228
+ var _a;
229
+ return Array.isArray(parked)
230
+ ? ((_a = model === null || model === void 0 ? void 0 : model.selectable) !== null && _a !== void 0 ? _a : []).filter((index) => parked.includes(index))
231
+ : initialSelection();
232
+ };
233
+ /**
234
+ * Whether Write may fire. False on an empty selection, so the button is disabled and the empty
235
+ * state cannot commit anything.
236
+ *
237
+ * @internal
238
+ */
239
+ export const canWrite = (selection) => selection.length > 0;
240
+ /**
241
+ * The rows a Write commits: the ones selected, in the order shown, each carrying the very
242
+ * object the table rendered.
243
+ *
244
+ * @internal
245
+ */
246
+ export const selectedRows = (model, selection) => model.rows
247
+ .filter((row) => { var _a; return selection.has(row.index) && !((_a = row.problems) === null || _a === void 0 ? void 0 : _a.length); })
248
+ .map((row) => ({ index: row.index, details: row.details }));
@@ -0,0 +1,127 @@
1
+ import { __awaiter } from "tslib";
2
+ import { withTimeout } from '../utils/with-timeout';
3
+ import { composeCriteria } from './criteria';
4
+ import { loadFilterFields } from './filter-fields';
5
+ import { serialisable } from './serialisable';
6
+ import { plainFailure, plainServerText } from './server-text';
7
+ /** Two rows are enough to know a key is not one, and one row more than a key should match. */
8
+ const KEY_MAX_ROWS = 2;
9
+ /** A read that never settles would hang the turn; see the read tools' own timeout. */
10
+ const READ_TIMEOUT_MS = 30000;
11
+ /**
12
+ * Reads single rows from a request resource, by an exact match on the key fields.
13
+ *
14
+ * @remarks
15
+ * The criteria is composed by {@link composeCriteria} against the resource's own filter fields,
16
+ * so the expression, the escaping and the types are the ones the read tools already use — the
17
+ * key travels as a value, never as text spliced into an expression, and a field the resource
18
+ * does not publish is refused here rather than by the server.
19
+ *
20
+ * @internal
21
+ */
22
+ export function createRequestRowSource({ connect, resource, timeouts, }) {
23
+ let metadata;
24
+ const loadFields = () => {
25
+ metadata !== null && metadata !== void 0 ? metadata : (metadata = loadFilterFields(connect, resource, timeouts === null || timeouts === void 0 ? void 0 : timeouts.metadataMs)
26
+ .then((loaded) => loaded.status === 'ok'
27
+ ? { fields: loaded.fields, described: loaded.described }
28
+ : `${resource} could not be read (${loaded.reason})`)
29
+ .then((loaded) => {
30
+ if (typeof loaded === 'string')
31
+ metadata = undefined;
32
+ return loaded;
33
+ }));
34
+ return metadata;
35
+ };
36
+ return {
37
+ resource,
38
+ describes() {
39
+ return __awaiter(this, void 0, void 0, function* () {
40
+ const metadata = yield loadFields();
41
+ return typeof metadata === 'string' ? undefined : metadata.described;
42
+ });
43
+ },
44
+ filterableBy() {
45
+ return __awaiter(this, void 0, void 0, function* () {
46
+ const metadata = yield loadFields();
47
+ return typeof metadata === 'string' ? undefined : metadata.fields;
48
+ });
49
+ },
50
+ read(key) {
51
+ return __awaiter(this, void 0, void 0, function* () {
52
+ var _a;
53
+ const entries = Object.entries(key);
54
+ if (!(connect === null || connect === void 0 ? void 0 : connect.isConnected)) {
55
+ return { status: 'failed', reason: 'the app is not connected to its server' };
56
+ }
57
+ const metadata = yield loadFields();
58
+ // Composed by us, but it embeds whatever the metadata request rejected with, so it takes
59
+ // the same allow-list rather than being trusted for having our words around it.
60
+ if (typeof metadata === 'string') {
61
+ return {
62
+ status: 'failed',
63
+ reason: plainServerText(metadata, `${resource} could not be described`, `${resource} could not be read`),
64
+ };
65
+ }
66
+ const composed = composeCriteria(entries.map(([field, value]) => ({ field, op: 'equals', value: String(value) })), metadata.fields);
67
+ if (composed.status === 'rejected') {
68
+ return {
69
+ status: 'failed',
70
+ reason: `${resource} cannot be searched by ${entries
71
+ .map(([field]) => field)
72
+ .join(', ')}: ${composed.reason}`,
73
+ };
74
+ }
75
+ // The invariant this whole module rests on: a read with no criteria returns the FIRST ROW
76
+ // OF THE TABLE, and every caller here treats one row as "the row this write is about". An
77
+ // empty key composes to exactly that, so a modify with nothing to match on would be built
78
+ // — and approved — against whichever row the server happened to send. Refused instead.
79
+ if (!composed.criteria) {
80
+ return { status: 'failed', reason: 'there is no key to find the row by' };
81
+ }
82
+ let reply;
83
+ try {
84
+ reply = yield withTimeout(connect.request(resource, {
85
+ REQUEST: {},
86
+ DETAILS: { MAX_ROWS: KEY_MAX_ROWS, CRITERIA_MATCH: composed.criteria },
87
+ }), (_a = timeouts === null || timeouts === void 0 ? void 0 : timeouts.readMs) !== null && _a !== void 0 ? _a : READ_TIMEOUT_MS);
88
+ }
89
+ catch (error) {
90
+ // The same treatment the read path gives a rejection: a request server that throws
91
+ // mid-read can carry a SQL code, a class name or an internal host in its message, and
92
+ // this reason lands in a red row of the review table as well as in the tool result.
93
+ return {
94
+ status: 'failed',
95
+ reason: plainFailure(error, `${resource} row read failed`, {
96
+ timeout: `${resource} took too long to answer, so the row could not be read`,
97
+ failed: `reading ${resource} failed`,
98
+ }),
99
+ };
100
+ }
101
+ const errors = reply === null || reply === void 0 ? void 0 : reply.ERROR;
102
+ if (Array.isArray(errors) && errors.length) {
103
+ // The server's own text, not the Groovy compiler's: a criteria this module composed
104
+ // cannot fail to compile, so what reaches here is the app refusing the read.
105
+ const text = errors
106
+ .map((e) => e === null || e === void 0 ? void 0 : e.TEXT)
107
+ .filter(Boolean)
108
+ .join('; ');
109
+ // Through the same allow-list the read path uses: this text reaches a model vendor and
110
+ // the user's screen, and a write is no reason for it to travel further than a read.
111
+ return {
112
+ status: 'failed',
113
+ reason: plainServerText(text, `${resource} refused a row read`, `${resource} refused the read`),
114
+ };
115
+ }
116
+ const rows = Array.isArray(reply === null || reply === void 0 ? void 0 : reply.REPLY) ? reply.REPLY : [];
117
+ if (!rows.length)
118
+ return { status: 'missing' };
119
+ if (rows.length > 1)
120
+ return { status: 'ambiguous' };
121
+ // Normalised on the way in: this row is merged into a payload, rendered in the review and
122
+ // carried into the driver's history, where a BigInt from a LONG column cannot be stored.
123
+ return { status: 'ok', row: serialisable(rows[0]) };
124
+ });
125
+ },
126
+ };
127
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Row values as they can be serialised.
3
+ *
4
+ * @remarks
5
+ * Comms' own deserializer turns any integer outside the safe range into a `BigInt`
6
+ * (`foundation-utils` `customNumberParser`), so a Genesis LONG or BIGINT column arrives as one.
7
+ * A BigInt cannot be `JSON.stringify`'d, and both paths that carry a row hit that:
8
+ *
9
+ * - a READ tool's result, which the chat driver stringifies — one such column anywhere in a row
10
+ * killed the turn with "TypeError: Do not know how to serialize a BigInt";
11
+ * - a WRITE's pre-image, which travels into the review interaction's `data` and from there into
12
+ * the driver's history, where it is persisted.
13
+ *
14
+ * A value that fits a JS number exactly becomes one; anything larger becomes its decimal string,
15
+ * because the alternative is telling the model — or showing a user — a number that is quietly
16
+ * wrong. Nested values are walked: the BigInt can sit inside an object or an array in the row.
17
+ *
18
+ * `foundation-utils`' own serializer is not the fix here: it solves stringifying (and is the
19
+ * right fix for the driver, separately), but routing rows through it and back would lose the
20
+ * very precision this preserves.
21
+ *
22
+ * @internal
23
+ */
24
+ export function serialisable(value) {
25
+ if (typeof value === 'bigint') {
26
+ const asNumber = Number(value);
27
+ return Number.isSafeInteger(asNumber) ? asNumber : value.toString();
28
+ }
29
+ if (Array.isArray(value))
30
+ return value.map(serialisable);
31
+ if (value && typeof value === 'object') {
32
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [
33
+ key,
34
+ serialisable(item),
35
+ ]));
36
+ }
37
+ return value;
38
+ }