@genesislcap/ai-assistant 15.41.0 → 15.43.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 (41) hide show
  1. package/dist/chat-driver.cjs +115 -6
  2. package/dist/chat-driver.cjs.map +3 -3
  3. package/dist/chat-driver.mjs +115 -6
  4. package/dist/chat-driver.mjs.map +3 -3
  5. package/dist/custom-elements.json +761 -713
  6. package/dist/dts/genesis/config.d.ts +51 -6
  7. package/dist/dts/genesis/config.d.ts.map +1 -1
  8. package/dist/dts/genesis/consumes.d.ts +42 -0
  9. package/dist/dts/genesis/consumes.d.ts.map +1 -0
  10. package/dist/dts/genesis/criteria.d.ts.map +1 -1
  11. package/dist/dts/genesis/event-fields.d.ts +4 -1
  12. package/dist/dts/genesis/event-fields.d.ts.map +1 -1
  13. package/dist/dts/genesis/index.d.ts +2 -1
  14. package/dist/dts/genesis/index.d.ts.map +1 -1
  15. package/dist/dts/genesis/register-genesis-assistant.d.ts +29 -4
  16. package/dist/dts/genesis/register-genesis-assistant.d.ts.map +1 -1
  17. package/dist/dts/genesis/resource-tools.d.ts.map +1 -1
  18. package/dist/dts/genesis/review-model.d.ts.map +1 -1
  19. package/dist/dts/genesis/types.d.ts +37 -5
  20. package/dist/dts/genesis/types.d.ts.map +1 -1
  21. package/dist/dts/genesis/write-payload.d.ts.map +1 -1
  22. package/dist/dts/genesis/write-tools.d.ts +26 -5
  23. package/dist/dts/genesis/write-tools.d.ts.map +1 -1
  24. package/dist/esm/genesis/config.js +105 -50
  25. package/dist/esm/genesis/consumes.js +30 -0
  26. package/dist/esm/genesis/criteria.js +28 -0
  27. package/dist/esm/genesis/event-fields.js +20 -3
  28. package/dist/esm/genesis/index.js +1 -0
  29. package/dist/esm/genesis/register-genesis-assistant.js +146 -63
  30. package/dist/esm/genesis/resource-tools.js +20 -12
  31. package/dist/esm/genesis/review-model.js +16 -3
  32. package/dist/esm/genesis/write-payload.js +47 -4
  33. package/dist/esm/genesis/write-tools.js +199 -45
  34. package/dist/genesis-consumes.cjs +35 -0
  35. package/dist/genesis-consumes.cjs.map +7 -0
  36. package/dist/genesis-consumes.mjs +11 -0
  37. package/dist/genesis-consumes.mjs.map +7 -0
  38. package/docs/genesis.md +156 -28
  39. package/package.json +29 -19
  40. package/scripts/build-genesis-consumes-node.mjs +50 -0
  41. package/scripts/smoke-genesis-consumes-node.mjs +70 -0
@@ -0,0 +1,30 @@
1
+ /**
2
+ * What this version of the assistant reads from a generated AI config: the resource kinds it
3
+ * accepts, the resource fields its validator or a tool reads, and the `vendor` and `tier` values
4
+ * it accepts.
5
+ *
6
+ * @remarks
7
+ * The generator must not emit what the installed assistant does not read, or a new kind is left out
8
+ * and a new field ignored — and an older assistant used to block entirely on a kind it did not know.
9
+ * Nothing in the generator can say which version will run its output. So the app's seed declares
10
+ * what it expects, and the seed's CI checks that declaration against this constant, exported from
11
+ * the version it installs. That makes this the single statement of what an assistant consumes, and
12
+ * it carries no version number because it needs none.
13
+ *
14
+ * A test holds it to the code: its kinds are the ones validation accepts, and its fields are the
15
+ * ones read. A change that teaches the validator a kind, or a tool a field, updates it in the same
16
+ * commit.
17
+ *
18
+ * A resource this version does not read is only left out, but an unknown `vendor` or `tier` still
19
+ * blocks the whole assistant, so those are here too. They are written out rather than imported
20
+ * from foundation-ai, which this entry must not load; a test holds them equal to its
21
+ * `AI_TIER_VENDORS` and `AI_TIER_IDS`, which the validator checks against.
22
+ *
23
+ * @beta
24
+ */
25
+ export const GENESIS_AI_CONSUMES = Object.freeze({
26
+ kinds: Object.freeze(['request', 'event']),
27
+ resourceFields: Object.freeze(['name', 'kind', 'op', 'context', 'maxRows']),
28
+ vendors: Object.freeze(['anthropic', 'gemini']),
29
+ tiers: Object.freeze(['low', 'high', 'reasoning']),
30
+ });
@@ -97,6 +97,22 @@ export function fieldKindOf(type) {
97
97
  return 'string';
98
98
  return undefined;
99
99
  }
100
+ /**
101
+ * The kinds of JavaScript value a filter value may be: what a literal can be written from.
102
+ *
103
+ * @remarks
104
+ * `bigint` among them. Comms turns a LONG beyond the safe range into a BigInt, so a host filtering
105
+ * on a value it read through its own Connect holds one, and `String()` of it is its exact digits:
106
+ * the one representation of that LONG that has not been rounded. A model cannot send one, as JSON
107
+ * has none.
108
+ */
109
+ const VALUE_TYPES = new Set(['string', 'number', 'bigint', 'boolean']);
110
+ /** What a value that is not one is, for the refusal: a list, an object, or its own kind. */
111
+ const kindOfValue = (value) => {
112
+ if (Array.isArray(value))
113
+ return 'a list';
114
+ return typeof value === 'object' ? 'an object' : `a ${typeof value}`;
115
+ };
100
116
  /**
101
117
  * Escapes a value for a criteria string literal: backslashes first, then quotes. An unescaped
102
118
  * quote would close the literal early — which is the injection this module exists to prevent —
@@ -298,6 +314,18 @@ function fragmentFor(filter, field) {
298
314
  if (filter.value === undefined || filter.value === null || filter.value === '') {
299
315
  return { status: 'rejected', reason: `the filter on ${field.name} has no value.` };
300
316
  }
317
+ // One value, of a kind a literal can be written from. A list or an object has none: String()
318
+ // made `['NEW', 'OPEN']` into 'NEW,OPEN', a valid criteria that matches nothing, and the read
319
+ // came back empty for the model to report as "there are none". Number, date and enum fields
320
+ // refused it on their own checks; a plain text field did not.
321
+ if (!VALUE_TYPES.has(typeof filter.value)) {
322
+ return {
323
+ status: 'rejected',
324
+ reason: `the filter on ${field.name} has ${kindOfValue(filter.value)} ` +
325
+ 'for its value. A filter takes one value; filters are all matched, so for either of two ' +
326
+ 'values read once for each.',
327
+ };
328
+ }
301
329
  // Before the checks below, every one of which interpolates the value into its reason: a guard
302
330
  // placed after them leaves the amplification it exists to prevent wide open. The reason here
303
331
  // names the LENGTH and never the value, for the same reason.
@@ -27,6 +27,23 @@ const JSON_TYPE_BY_GENESIS_TYPE = {
27
27
  STRING: 'string',
28
28
  ENUM: 'string',
29
29
  };
30
+ /**
31
+ * A field's Genesis type: its `GENESIS_TYPE` when the reply carries one, else its `TYPE`.
32
+ *
33
+ * @remarks
34
+ * `TYPE` follows the Java class the value travels as, not the field's type in the dictionary. A
35
+ * GSF 8.15 app describes a DATE field as `TYPE: 'DATETIME'` (`DESCRIPTION:
36
+ * 'org.joda.time.DateTime'`) and `GENESIS_TYPE: 'DATE'`. Read from `TYPE`, no rule written for a
37
+ * DATE (no time of day, the day-only schema and display) ever applied to a real one. Not
38
+ * declared on `MetadataDetail`, so read defensively, as `TITLE` is.
39
+ *
40
+ * The write side only. `filter-fields` still reads `TYPE`: a DATE composes other criteria than
41
+ * a DATETIME (`Expr.dateIs*`, equality included), and that has not been run against an app.
42
+ */
43
+ const typeOf = (detail) => {
44
+ const genesisType = detail.GENESIS_TYPE;
45
+ return typeof genesisType === 'string' && genesisType.trim() ? genesisType : detail.TYPE;
46
+ };
30
47
  /**
31
48
  * How a field travels, or `undefined` when neither the metadata nor this module can say.
32
49
  *
@@ -41,7 +58,7 @@ const jsonTypeOf = (detail) => {
41
58
  const declared = String((_a = detail.JSON_TYPE) !== null && _a !== void 0 ? _a : '').toLowerCase();
42
59
  if (declared)
43
60
  return declared;
44
- return JSON_TYPE_BY_GENESIS_TYPE[genesisTypeName(detail.TYPE)];
61
+ return JSON_TYPE_BY_GENESIS_TYPE[genesisTypeName(typeOf(detail))];
45
62
  };
46
63
  const titleOf = (detail) => {
47
64
  const title = detail.TITLE;
@@ -56,7 +73,7 @@ export function eventFieldsFrom(metadata) {
56
73
  const named = details.filter((detail) => typeof (detail === null || detail === void 0 ? void 0 : detail.NAME) === 'string' && detail.NAME.length);
57
74
  // Untyped, or typed as something this module cannot say how to send: either way the value
58
75
  // would go out on a guess, so neither is writable.
59
- const writable = (detail) => !!detail.TYPE && !!jsonTypeOf(detail);
76
+ const writable = (detail) => !!typeOf(detail) && !!jsonTypeOf(detail);
60
77
  const untyped = named.filter((detail) => !writable(detail)).map((detail) => detail.NAME);
61
78
  const fields = [];
62
79
  const unreadableValues = [];
@@ -68,7 +85,7 @@ export function eventFieldsFrom(metadata) {
68
85
  }
69
86
  fields.push({
70
87
  name: detail.NAME,
71
- type: String(detail.TYPE),
88
+ type: String(typeOf(detail)),
72
89
  jsonType: jsonTypeOf(detail),
73
90
  // NULLABLE is about the column; OPTIONAL is about the payload, and it is the one that
74
91
  // decides whether the model must supply a value.
@@ -11,6 +11,7 @@
11
11
  * @beta
12
12
  */
13
13
  export { GENESIS_AGENT_NAME, registerGenesisAssistant } from './register-genesis-assistant';
14
+ export { GENESIS_AI_CONSUMES } from './consumes';
14
15
  export { createGenesisResourceTools, GENESIS_DATA_SOURCE } from './resource-tools';
15
16
  export { createGenesisWriteTools } from './write-tools';
16
17
  export { GENESIS_WRITE_REVIEW, GenesisWriteReview } from './write-review/write-review';
@@ -66,6 +66,48 @@ export const WRITE_OUTCOME_PROMPT = 'A write tool shows the user every row it wo
66
66
  'own outcome: read them. A row whose status is "unknown" was sent and may well have been ' +
67
67
  'written — never write it again, and say plainly that it needs checking. If the user denied a ' +
68
68
  'write, do not propose it, or any other write to that table, again unless they ask.';
69
+ /**
70
+ * What the user reads when AI is switched off for the app, in its build or in its config. A
71
+ * choice, not a fault.
72
+ *
73
+ * @internal
74
+ */
75
+ export const ASSISTANT_OFF_REASON = 'The assistant is switched off for this app.';
76
+ /**
77
+ * What the user reads when the assistant cannot run because of how it is set up.
78
+ *
79
+ * @remarks
80
+ * One sentence for every fault, on purpose. The detail names resources, tools and settings, which
81
+ * mean nothing to the person using the app and are the app's internals besides; it goes to the
82
+ * console and to `blockedDetail`, for whoever maintains the app. It used to be the banner itself:
83
+ * "The AI configuration is invalid: resources[3]: op must be …".
84
+ *
85
+ * @internal
86
+ */
87
+ export const ASSISTANT_FAULT_REASON = "The assistant isn't set up correctly, so it can't be used. An administrator can find the " +
88
+ 'details in the browser console.';
89
+ /**
90
+ * The resources whose tool name no extension tool already has.
91
+ *
92
+ * @remarks
93
+ * An extension is the app's own hand-written code; a generated tool is derived from a config
94
+ * that a regeneration can change under it. When the two share a name the hand-written one is
95
+ * kept and the generated resource is left out, with a warning naming both. This used to block the
96
+ * whole assistant, which was harmless while every generated name began `req_` or `event_`; a
97
+ * generator emitting free-form names makes it reachable on the regeneration of an existing app.
98
+ */
99
+ function withoutClashes(resources, extensionNames, leftOut) {
100
+ return resources.filter((resource) => {
101
+ const tool = toolNameOf(resource.name);
102
+ if (!extensionNames.has(tool))
103
+ return true;
104
+ leftOut.push(`left out ${resource.name}: the app's extension tool ${tool} has the name its tool would ` +
105
+ 'have. The extension is kept; rename it to have both.');
106
+ return false;
107
+ });
108
+ }
109
+ /** A resource the validator left out, named and explained, for the console. */
110
+ const describeDropped = (drop) => `${drop.name ? `${drop.name} (${drop.at})` : drop.at}: ${drop.problems.join(', ')}`;
69
111
  /**
70
112
  * The exported app's own AI proxy: `<PUBLIC_PATH>/gwf/ai-service`.
71
113
  * Unless the build names another base: a build-time `GENX_AI_CHAT_BASE` comes first.
@@ -128,53 +170,85 @@ export function genesisProviderOptions(config, options = {}) {
128
170
  * connects before they are registered keeps the empty fallback for the whole page load.
129
171
  *
130
172
  * It never throws. Anything that stops the assistant working — AI switched off for the build,
131
- * an invalid config, an extension tool reusing a generated tool's name — is logged as an error
132
- * and returned as `blockedReason`, with no agents. The mount code applies it with the element's
133
- * `setBlocked(true, blockedReason)`. The app keeps working: one misnamed chat tool, for instance
134
- * after a regeneration renames a resource onto an extension's tool, must never take it down.
173
+ * an invalid config, an extension tool defined twice or with no handler, an extension handler with
174
+ * no tool definition — comes back as a
175
+ * `blockedReason` for the user and a `blockedDetail` for a developer, with no agents. The mount
176
+ * code applies the reason with the element's `setBlocked(true, blockedReason)`. The app keeps
177
+ * working: a problem with its assistant must never take it down at start-up.
178
+ *
179
+ * A problem with one resource does not block: that resource is left out, and the console says why.
180
+ * Nor does every resource being left out, while the app has extension tools of its own; with none,
181
+ * it blocks, as nothing would be left to reach. Nor does an extension tool with the name a generated tool would have: the extension is
182
+ * kept and the generated resource left out, with a warning naming both.
135
183
  *
136
184
  * @beta
137
185
  */
138
186
  export function registerGenesisAssistant(options) {
139
- var _a, _b, _c, _d, _e;
140
- const blocked = (reason, fault = true) => {
187
+ var _a, _b, _c, _d;
188
+ /**
189
+ * `off` is a choice (AI switched off in the build or the config), `fault` is anything else.
190
+ * Named at every call rather than defaulted: which sentence the user reads, and whether the
191
+ * console shows an error, is decided here.
192
+ */
193
+ const blocked = (kind, detail) => {
141
194
  // An app built without the AI flag, or with the assistant switched off, is a choice rather
142
195
  // than a fault: logging it at error level would put an error in every page load's console.
143
- if (fault)
144
- logger.error(`Genesis assistant disabled: ${reason}`);
196
+ if (kind === 'fault')
197
+ logger.error(`Genesis assistant disabled: ${detail}`);
145
198
  else
146
- logger.debug(`Genesis assistant disabled: ${reason}`);
147
- return { agents: [], blockedReason: reason };
199
+ logger.debug(`Genesis assistant disabled: ${detail}`);
200
+ return {
201
+ agents: [],
202
+ // One of two fixed sentences, never built from the detail: see ASSISTANT_FAULT_REASON.
203
+ blockedReason: kind === 'fault' ? ASSISTANT_FAULT_REASON : ASSISTANT_OFF_REASON,
204
+ blockedDetail: detail,
205
+ };
148
206
  };
149
207
  if (!options || typeof options !== 'object') {
150
- return blocked('registerGenesisAssistant was called without its options.');
208
+ return blocked('fault', 'registerGenesisAssistant was called without its options.');
151
209
  }
152
210
  if (!isAIFeatureEnabled()) {
153
- return blocked('AI features are switched off for this app. Build it with GENX_ENABLE_AI=true.', false);
211
+ return blocked('off', 'AI features are switched off for this app. Build it with GENX_ENABLE_AI=true.');
154
212
  }
155
213
  const { config } = options;
156
214
  if ((config === null || config === void 0 ? void 0 : config.enabled) === false) {
157
- return blocked("The AI assistant is switched off in this app's configuration.", false);
215
+ return blocked('off', "The AI assistant is switched off in this app's configuration.");
158
216
  }
159
- const problems = validateGenesisAiConfig(config);
160
- if (problems.length)
161
- return blocked(`The AI configuration is invalid: ${problems.join('; ')}.`);
162
- const resources = (_a = config.resources) !== null && _a !== void 0 ? _a : [];
163
- const extensions = (_b = options.extensions) !== null && _b !== void 0 ? _b : {};
164
- const extensionDefinitions = (_c = extensions.toolDefinitions) !== null && _c !== void 0 ? _c : [];
165
- const extensionHandlers = (_d = extensions.toolHandlers) !== null && _d !== void 0 ? _d : {};
217
+ const check = validateGenesisAiConfig(config);
218
+ if (check.problems.length) {
219
+ return blocked('fault', `The AI configuration is invalid: ${check.problems.join('; ')}.`);
220
+ }
221
+ // What was left out, said only once no later check can block: "the rest of the assistant
222
+ // works" is false of an assistant that is blocked after all, and the fault banner sends its
223
+ // reader to the console, where it would be the first thing they read.
224
+ const leftOut = check.dropped.map((drop) => `left out ${describeDropped(drop)}. It gets no tool; the rest of the assistant works.`);
225
+ // What survived validation. Every consumer below reads this, or what survives it in turn —
226
+ // never `config.resources`, where a null entry is still waiting to throw.
227
+ const validated = check.resources;
228
+ // `null` is "no extensions", as a `null` handler map is "no handlers" below. Any other shape
229
+ // that is not an object is the app's own code at fault: read as none, it quietly cost the
230
+ // assistant every hand-written tool with nothing anywhere to say why.
231
+ const given = options.extensions;
232
+ if (given !== undefined &&
233
+ given !== null &&
234
+ (typeof given !== 'object' || Array.isArray(given))) {
235
+ return blocked('fault', 'The app extensions must be an object of toolDefinitions, toolHandlers and systemPrompt.');
236
+ }
237
+ const extensions = (_a = options.extensions) !== null && _a !== void 0 ? _a : {};
238
+ const extensionDefinitions = (_b = extensions.toolDefinitions) !== null && _b !== void 0 ? _b : [];
239
+ const extensionHandlers = (_c = extensions.toolHandlers) !== null && _c !== void 0 ? _c : {};
166
240
  // The app's extensions are hand-written (`client/src/ai/extensions/`) and this package builds
167
241
  // without strictNullChecks, so a wrong shape gets here as easily as a wrong name. Checked
168
242
  // rather than trusted, because throwing would take the app's start-up down with it.
169
243
  if (!Array.isArray(extensionDefinitions)) {
170
- return blocked('The app extension toolDefinitions must be a list of tool definitions.');
244
+ return blocked('fault', 'The app extension toolDefinitions must be a list of tool definitions.');
171
245
  }
172
246
  const malformed = extensionDefinitions.filter((definition) => !definition || typeof definition.name !== 'string' || !definition.name.length);
173
247
  if (malformed.length) {
174
- return blocked(`${malformed.length} app extension tool definition(s) have no name. Every tool needs one.`);
248
+ return blocked('fault', `${malformed.length} app extension tool definition(s) have no name. Every tool needs one.`);
175
249
  }
176
250
  if (extensions.systemPrompt !== undefined && typeof extensions.systemPrompt !== 'string') {
177
- return blocked('The app extension systemPrompt must be a string.');
251
+ return blocked('fault', 'The app extension systemPrompt must be a string.');
178
252
  }
179
253
  // `null` is not tested for here, deliberately: the `?? {}` above has already turned it into
180
254
  // `{}`, so an `=== null` half could never fire — a guard that cannot fail reads as though it
@@ -182,24 +256,12 @@ export function registerGenesisAssistant(options) {
182
256
  // harmless, since nothing is written or disclosed by having none; refusing it would block the
183
257
  // whole assistant over a benign value. What this still refuses is a SHAPE that is not an object.
184
258
  if (typeof extensionHandlers !== 'object') {
185
- return blocked('The app extension toolHandlers must be an object of name to handler.');
259
+ return blocked('fault', 'The app extension toolHandlers must be an object of name to handler.');
186
260
  }
187
- // Reserved for every resource, reads and writes alike, so an extension that would clash with
188
- // a write tool is caught now rather than when writes arrive.
189
- const generatedNames = new Set(resources.map((r) => toolNameOf(r.name)));
190
261
  const definitionNames = extensionDefinitions.map((d) => d.name);
191
- // Handler KEYS as well as definition names: the handler map is spread over the generated
192
- // handlers, so a key with no definition of its own would silently replace a generated tool's
193
- // handler while the model still sees the generated description.
194
- const extensionNames = [...new Set([...definitionNames, ...Object.keys(extensionHandlers)])];
195
- const clashes = extensionNames.filter((name) => generatedNames.has(name));
196
- if (clashes.length) {
197
- return blocked(`App extension tool(s) ${clashes.join(', ')} reuse a name generated from the app's ` +
198
- 'resources. Rename the extension tool.');
199
- }
200
262
  const repeated = definitionNames.filter((name, i) => definitionNames.indexOf(name) !== i);
201
263
  if (repeated.length) {
202
- return blocked(`App extension tool(s) ${[...new Set(repeated)].join(', ')} are defined twice.`);
264
+ return blocked('fault', `App extension tool(s) ${[...new Set(repeated)].join(', ')} are defined twice.`);
203
265
  }
204
266
  // An OWN-property check, not a plain lookup: a tool named `toString` or `constructor` would
205
267
  // otherwise find Object.prototype's and pass as handled. (`Object.hasOwn` needs a newer lib
@@ -207,43 +269,56 @@ export function registerGenesisAssistant(options) {
207
269
  const hasOwnHandler = (name) => Object.prototype.hasOwnProperty.call(extensionHandlers, name);
208
270
  const unhandled = definitionNames.filter((name) => !hasOwnHandler(name) || typeof extensionHandlers[name] !== 'function');
209
271
  if (unhandled.length) {
210
- return blocked(`App extension tool(s) ${unhandled.join(', ')} have no handler.`);
272
+ return blocked('fault', `App extension tool(s) ${unhandled.join(', ')} have no handler.`);
273
+ }
274
+ // The mirror of the check above. The model is never told about a handler with no definition,
275
+ // and the handler map is spread over the generated handlers, so all it can ever do is answer
276
+ // for a tool something else describes: a generated one with its name, while the model still
277
+ // reads the generated description. A clash keeps the extension's TOOL, and a handler alone is
278
+ // not one, so this is a shape problem, and a shape problem blocks (contracts C-15A F-1).
279
+ const undescribed = Object.keys(extensionHandlers).filter((name) => !definitionNames.includes(name));
280
+ if (undescribed.length) {
281
+ return blocked('fault', `App extension handler(s) ${undescribed.join(', ')} have no tool definition.`);
282
+ }
283
+ // Every resource left out is not the empty list an app may choose: the config named tools and
284
+ // none can be built. With no tool of the app's own either, running on would be a chat that
285
+ // reaches nothing and reads, to its user, exactly like a working one — answering from nothing.
286
+ // Judged only now the extensions are known: an app with tools of its own still has a working
287
+ // assistant, as it does with `resources: []`, and a config a newer generator filled with a kind
288
+ // this version does not read must not take those tools down with it.
289
+ if (check.dropped.length && !validated.length && !definitionNames.length) {
290
+ return blocked('fault', `Every resource in the AI configuration was left out: ${check.dropped.map(describeDropped).join('; ')}.`);
211
291
  }
212
- // rowSources is hand-written like the extensions, and it decides which resource a write reads
213
- // its rows through — so a typo there is not cosmetic: it is the difference between "this
214
- // modify has no tool" and someone wondering for an afternoon why it does not. Checked here so
215
- // it says so, rather than going quiet in a console warning.
292
+ // Every handler has a definition by now, so the definitions name every extension tool.
293
+ const resources = withoutClashes(validated, new Set(definitionNames), leftOut);
294
+ // rowSources is hand-written like the extensions, and deprecated: a write reads its rows only
295
+ // through its table's own request resource, which is the default. A shape that is not an object
296
+ // is a fault in the app's own code. Every entry is judged by the write tools, which hold the
297
+ // rule for a direct call too: one naming another source costs its event the write tool (see
298
+ // rowSourceRefusal), and one naming no event they were given is said to have no effect.
216
299
  const rowSources = options.rowSources;
217
- if (rowSources !== undefined) {
218
- if (rowSources === null || typeof rowSources !== 'object' || Array.isArray(rowSources)) {
219
- return blocked('rowSources must be an object of event name to request resource name.');
220
- }
221
- const requests = new Set(resources.filter((r) => r.kind === 'request').map((r) => r.name));
222
- const events = new Set(resources.filter((r) => r.kind === 'event').map((r) => r.name));
223
- const badSources = Object.entries(rowSources).filter(([, read]) => typeof read !== 'string' || !requests.has(read));
224
- if (badSources.length) {
225
- return blocked(`rowSources names ${badSources.map(([, read]) => String(read)).join(', ')}, which ` +
226
- "is not a request resource in this app's AI config. A write reads its rows through a " +
227
- 'resource the assistant can already read.');
228
- }
229
- const unknownEvents = Object.keys(rowSources).filter((event) => !events.has(event));
230
- if (unknownEvents.length) {
231
- return blocked(`rowSources names ${unknownEvents.join(', ')}, which are not event resources.`);
232
- }
300
+ if (rowSources !== undefined &&
301
+ (rowSources === null || typeof rowSources !== 'object' || Array.isArray(rowSources))) {
302
+ return blocked('fault', 'rowSources must be an object of event name to request resource name.');
233
303
  }
234
304
  let switcher;
235
305
  try {
236
- switcher = registerTieredAIProviders((_e = options.container) !== null && _e !== void 0 ? _e : DI.getOrCreateDOMContainer(), genesisProviderOptions(config, options));
306
+ switcher = registerTieredAIProviders((_d = options.container) !== null && _d !== void 0 ? _d : DI.getOrCreateDOMContainer(), genesisProviderOptions(config, options));
237
307
  }
238
308
  catch (error) {
239
- return blocked(`The AI providers could not be registered: ${error.message}`);
309
+ return blocked('fault', `The AI providers could not be registered: ${error.message}`);
240
310
  }
311
+ // The last check that can block is behind us.
312
+ for (const line of leftOut)
313
+ logger.warn(`Genesis assistant: ${line}`);
241
314
  // Accepted (see validateGenesisAiConfig), but announced. An assistant with no generated tools
242
315
  // is a real configuration, and it is indistinguishable from one whose resource list came out
243
316
  // empty by mistake: the chat opens and answers, and can reach no data, with nothing anywhere
244
317
  // to say why. A warning costs the deliberate case one console line and gives the broken one
245
318
  // something to find. Both causes are named, so whoever reads it can tell which one they have.
246
- if (!resources.length) {
319
+ // Over what validation kept, not what the extensions left: a resource an extension replaced is
320
+ // not one the configuration failed to name, and its own warning has said so.
321
+ if (!validated.length && !check.dropped.length) {
247
322
  logger.warn('Genesis assistant: the AI configuration names no resources, so the assistant has no ' +
248
323
  "tools that read or write this app's data. That is expected if its tools all come from " +
249
324
  "the app's own extensions, or it is meant as a chat helper with none. If not, whatever " +
@@ -257,10 +332,18 @@ export function registerGenesisAssistant(options) {
257
332
  connect: options.connect,
258
333
  rowSources,
259
334
  feedbackKey,
335
+ // So a modify whose table's read was left out is not told to add it.
336
+ leftOut: [
337
+ ...check.dropped.map((drop) => drop.name).filter((name) => !!name),
338
+ ...validated.filter((resource) => !resources.includes(resource)).map((r) => r.name),
339
+ ],
260
340
  });
261
341
  // The exception to "tool results are data" only where a write tool can exist to earn it. A
262
- // read-only app has none, so every userFeedback its model could see would be a forgery.
263
- const canWrite = resources.some((resource) => resource.kind === 'event');
342
+ // read-only app has none, so every userFeedback its model could see would be a forgery. Nor
343
+ // does an app whose every event the config itself refuses: a custom op, a rowSources entry
344
+ // naming another source, a modify whose table's read did not survive. What metadata withholds
345
+ // later cannot be known here, and a tool that may still come earns the prompt.
346
+ const canWrite = writes.writableEvents.length > 0;
264
347
  const agent = {
265
348
  name: GENESIS_AGENT_NAME,
266
349
  description: "Answers questions about this app's data and helps with its tasks.",
@@ -2,7 +2,7 @@ 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, MAX_ROWS_CEILING, toolNameOf } from './config';
5
+ import { capIsReadable, DEFAULT_MAX_ROWS, MAX_ROWS_CEILING, toolNameOf } from './config';
6
6
  import { composeCriteria } from './criteria';
7
7
  import { loadFilterFields } from './filter-fields';
8
8
  import { serialisable } from './serialisable';
@@ -120,21 +120,29 @@ function truncationNote(maxRows, cap, canFilter) {
120
120
  * @beta
121
121
  */
122
122
  export function createGenesisResourceTools(resources, options = {}) {
123
- const requests = resources
124
- .filter((r) => r.kind === 'request')
125
- .sort((a, b) => a.name.localeCompare(b.name));
126
123
  // Held to the ceiling HERE as well as in the config validator, for the reason `decideOp` is
127
124
  // re-checked at the point of use: this factory is exported, and a host calling it directly
128
125
  // never passes through the validator. The cap is what stops one read pulling tens of thousands
129
126
  // 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
- };
127
+ // that only one entry point obeys. No `maxRows` is the default; a number outside the range is
128
+ // clamped into it.
129
+ //
130
+ // A `maxRows` that is there but is not a number declares SOME cap, and none can be read from
131
+ // it. Falling back to the default read up to five times what was declared — `'10'` became 50,
132
+ // where it once meant 10 — so the resource gets no tool instead, as the validator leaves it out.
133
+ const requests = resources
134
+ .filter((r) => r.kind === 'request')
135
+ .filter((r) => {
136
+ if (capIsReadable(r))
137
+ return true;
138
+ logger.warn(`Genesis assistant: ${r.name} has no read tool because its maxRows (${String(r.maxRows)}) ` +
139
+ 'is not a number, so the cap it declares cannot be read.');
140
+ return false;
141
+ })
142
+ .sort((a, b) => a.name.localeCompare(b.name));
143
+ const capOf = (r) => r.maxRows === undefined
144
+ ? DEFAULT_MAX_ROWS
145
+ : Math.min(Math.max(Math.floor(r.maxRows), 1), MAX_ROWS_CEILING);
138
146
  const resolveConnect = () => {
139
147
  var _a;
140
148
  try {
@@ -53,6 +53,11 @@ const FIRST_PLAUSIBLE_YEAR = 1971;
53
53
  const FIRST_WRITABLE_YEAR = 0;
54
54
  const LAST_WRITABLE_YEAR = 9999;
55
55
  const LAST_PLAUSIBLE_YEAR = 2999;
56
+ const MS_PER_SECOND = 1000;
57
+ const MS_PER_DAY = 86400000;
58
+ const MILLIS_DIGITS = 3;
59
+ /** `value mod unit`, never negative, so an instant before 1970 is read the same way. */
60
+ const remainder = (value, unit) => ((value % unit) + unit) % unit;
56
61
  /**
57
62
  * A value as a person should read it.
58
63
  *
@@ -73,7 +78,6 @@ const LAST_PLAUSIBLE_YEAR = 2999;
73
78
  * @internal
74
79
  */
75
80
  export function displayValue(value, type) {
76
- var _a;
77
81
  if (value === undefined || value === null)
78
82
  return '';
79
83
  const genesisType = genesisTypeName(type);
@@ -113,8 +117,17 @@ export function displayValue(value, type) {
113
117
  // callers may rely on 0 rendering blank. `=== 0` covers -0.
114
118
  if (epoch === 0)
115
119
  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);
120
+ // What is written is the millis, so the review shows every part of them that is there.
121
+ // A DATE is a day, but the payload builder takes a time with it ('2026-09-21T15:30', or a
122
+ // DATETIME a model echoes), and shown as the day alone the user approved a time they never
123
+ // saw. So a DATE shows its time whenever it is not midnight — and any value its
124
+ // milliseconds whenever they are not zero, which the formatter's seconds pattern drops.
125
+ const withTime = isDateTime || remainder(epoch, MS_PER_DAY) !== 0;
126
+ const shown = formatTimestamp(epoch, withTime);
127
+ if (!shown)
128
+ return String(value);
129
+ const millis = remainder(epoch, MS_PER_SECOND);
130
+ return millis ? `${shown}.${String(millis).padStart(MILLIS_DIGITS, '0')}` : shown;
118
131
  }
119
132
  }
120
133
  return String(value);
@@ -62,6 +62,40 @@ function toEpochMillis(value) {
62
62
  // to write `2026-13-01` as 2027-01-01 and report it `written`. See utcMillisOf.
63
63
  return (_a = utcMillisOf(year, month, day, hour, minute, second)) !== null && _a !== void 0 ? _a : NO_SUCH_DATE;
64
64
  }
65
+ /** Genesis types that hold a day, and no time of day. */
66
+ const DAY_TYPES = new Set(['DATE', 'LOCALDATE']);
67
+ const MS_PER_DAY = 86400000;
68
+ /**
69
+ * Whether a value the payload would send for a DATE or LOCALDATE falls at a time of day: epoch
70
+ * millis that are not a whole number of days. `-0` is not a time of day, so a negative whole day
71
+ * is not either.
72
+ */
73
+ const timeOfDayOnADay = (field, value) => DAY_TYPES.has(genesisTypeName(field.type)) &&
74
+ typeof value === 'number' &&
75
+ value % MS_PER_DAY !== 0;
76
+ /**
77
+ * Why a DATE the model gave is refused for its time of day, or nothing.
78
+ *
79
+ * @remarks
80
+ * The date travels as epoch millis, so the time is written too, and a review showing only the day
81
+ * would hide it. Refused, so the model can resend the day alone. The ROW's own value is kept
82
+ * whatever it holds, and the review shows it in full: the row is what the server stored, and
83
+ * refusing it would make the row unwritable over a field nobody is changing. A model echoing the
84
+ * row's value is the row's too. `fromRow` is false for an echo, so the value is compared with the
85
+ * row's.
86
+ */
87
+ function timeOfDayRefusal(field, { raw, value, fromRow, rowValue, }) {
88
+ if (fromRow || !timeOfDayOnADay(field, value))
89
+ return undefined;
90
+ const rowMillis = rowValue === undefined ? undefined : toEpochMillis(rowValue);
91
+ if (rowMillis === value)
92
+ return undefined;
93
+ // The row itself holds a time here, and an echo of it that is off by a second, or spelt without
94
+ // its seconds, is not that value. Sent as the bare day it would overwrite the stored time, so
95
+ // the model is told it can leave the field out instead.
96
+ const keep = timeOfDayOnADay(field, rowMillis) ? ", or leave it out to keep the row's value" : '';
97
+ return `${field.name} is a date; send it without a time of day${keep} (got '${quoted(raw)}')`;
98
+ }
65
99
  /** Genesis types that hold a whole number, whatever JSON type their metadata declares. */
66
100
  const WHOLE_NUMBER_TYPES = new Set(['INT', 'INTEGER', 'LONG', 'SHORT', 'NANO_TIMESTAMP']);
67
101
  /**
@@ -159,13 +193,18 @@ function valueFor(field, raw) {
159
193
  const millis = toEpochMillis(raw);
160
194
  if (millis === NO_SUCH_DATE) {
161
195
  return {
196
+ // No hour for a DATE: it is offered no time of day (see timeOfDayOnADay).
162
197
  problem: `${label} is not a date that exists (got '${quoted(raw)}'): a month runs 01–12, a day ` +
163
- "to the month's last, an hour 00–23, and a year starts at 0100",
198
+ `to the month's last, ${DAY_TYPES.has(type) ? '' : 'an hour 00–23, '}and a year ` +
199
+ 'starts at 0100',
164
200
  };
165
201
  }
166
202
  if (millis === undefined) {
167
203
  return {
168
- problem: `${label} is a date and must be YYYY-MM-DD, YYYY-MM-DDTHH:MM or epoch millis (got '${quoted(raw)}')`,
204
+ // A DATE is offered no time of day: one given is refused (see timeOfDayOnADay).
205
+ problem: `${label} is a date and must be ` +
206
+ `${DAY_TYPES.has(type) ? 'YYYY-MM-DD' : 'YYYY-MM-DD, YYYY-MM-DDTHH:MM'} or epoch millis ` +
207
+ `(got '${quoted(raw)}')`,
169
208
  };
170
209
  }
171
210
  return { value: millis };
@@ -466,6 +505,7 @@ function sourceOf(field, given, changes, rowValue, merge, op) {
466
505
  return { raw, fromRow: merge && !modelSent };
467
506
  }
468
507
  export function buildEventPayload(fields, row, { op, preImage } = {}) {
508
+ var _a;
469
509
  if (!row || typeof row !== 'object' || Array.isArray(row)) {
470
510
  return {
471
511
  status: 'rejected',
@@ -553,7 +593,8 @@ export function buildEventPayload(fields, row, { op, preImage } = {}) {
553
593
  problems.push(`${name} is set by the server and cannot be written`);
554
594
  continue;
555
595
  }
556
- const source = sourceOf(field, given, changes, merge ? preImage === null || preImage === void 0 ? void 0 : preImage[name] : undefined, merge, op);
596
+ const rowValue = merge ? preImage === null || preImage === void 0 ? void 0 : preImage[name] : undefined;
597
+ const source = sourceOf(field, given, changes, rowValue, merge, op);
557
598
  if (source.problem) {
558
599
  problems.push(source.problem);
559
600
  continue;
@@ -573,7 +614,9 @@ export function buildEventPayload(fields, row, { op, preImage } = {}) {
573
614
  problems.push(unsupplied(field));
574
615
  continue;
575
616
  }
576
- const { value, problem } = valueFor(field, raw);
617
+ const converted = valueFor(field, raw);
618
+ const { value } = converted;
619
+ const problem = (_a = converted.problem) !== null && _a !== void 0 ? _a : timeOfDayRefusal(field, { raw, value, fromRow, rowValue });
577
620
  if (problem) {
578
621
  // Attribute it correctly. A value carried from the pre-image is the SERVER's own — most
579
622
  // often a LONG beyond 2^53 that the read stamped as text and a JSON integer cannot carry