@genesislcap/ai-assistant 15.42.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 (37) hide show
  1. package/dist/custom-elements.json +49 -1
  2. package/dist/dts/genesis/config.d.ts +51 -6
  3. package/dist/dts/genesis/config.d.ts.map +1 -1
  4. package/dist/dts/genesis/consumes.d.ts +42 -0
  5. package/dist/dts/genesis/consumes.d.ts.map +1 -0
  6. package/dist/dts/genesis/criteria.d.ts.map +1 -1
  7. package/dist/dts/genesis/event-fields.d.ts +4 -1
  8. package/dist/dts/genesis/event-fields.d.ts.map +1 -1
  9. package/dist/dts/genesis/index.d.ts +2 -1
  10. package/dist/dts/genesis/index.d.ts.map +1 -1
  11. package/dist/dts/genesis/register-genesis-assistant.d.ts +29 -4
  12. package/dist/dts/genesis/register-genesis-assistant.d.ts.map +1 -1
  13. package/dist/dts/genesis/resource-tools.d.ts.map +1 -1
  14. package/dist/dts/genesis/review-model.d.ts.map +1 -1
  15. package/dist/dts/genesis/types.d.ts +37 -5
  16. package/dist/dts/genesis/types.d.ts.map +1 -1
  17. package/dist/dts/genesis/write-payload.d.ts.map +1 -1
  18. package/dist/dts/genesis/write-tools.d.ts +26 -5
  19. package/dist/dts/genesis/write-tools.d.ts.map +1 -1
  20. package/dist/esm/genesis/config.js +105 -50
  21. package/dist/esm/genesis/consumes.js +30 -0
  22. package/dist/esm/genesis/criteria.js +28 -0
  23. package/dist/esm/genesis/event-fields.js +20 -3
  24. package/dist/esm/genesis/index.js +1 -0
  25. package/dist/esm/genesis/register-genesis-assistant.js +146 -63
  26. package/dist/esm/genesis/resource-tools.js +20 -12
  27. package/dist/esm/genesis/review-model.js +16 -3
  28. package/dist/esm/genesis/write-payload.js +47 -4
  29. package/dist/esm/genesis/write-tools.js +199 -45
  30. package/dist/genesis-consumes.cjs +35 -0
  31. package/dist/genesis-consumes.cjs.map +7 -0
  32. package/dist/genesis-consumes.mjs +11 -0
  33. package/dist/genesis-consumes.mjs.map +7 -0
  34. package/docs/genesis.md +156 -28
  35. package/package.json +29 -19
  36. package/scripts/build-genesis-consumes-node.mjs +50 -0
  37. package/scripts/smoke-genesis-consumes-node.mjs +70 -0
@@ -3,6 +3,23 @@ import { GENESIS_EVENT_OPS, } from './types';
3
3
  /** The default read cap, and the ceiling the config may raise it to. */
4
4
  export const DEFAULT_MAX_ROWS = 50;
5
5
  export const MAX_ROWS_CEILING = 1000;
6
+ /**
7
+ * Whether a request's `maxRows` can be read as a cap: absent, so the default applies, or a finite
8
+ * number, which is clamped into range.
9
+ *
10
+ * @remarks
11
+ * Anything else declares SOME cap, and none can be read from it, so the request gets no read tool.
12
+ * Having none, it is no row source for a write either: a modify reading through it would answer
13
+ * "no row matches that key" about a table the model cannot read. One test for both factories, so
14
+ * they cannot disagree about which requests the assistant reads. The validator is stricter (a
15
+ * whole number from 1 to 1000) and leaves such a request out before either factory sees it.
16
+ *
17
+ * @internal
18
+ */
19
+ export const capIsReadable = (resource) => {
20
+ const asked = resource.maxRows;
21
+ return asked === undefined || (typeof asked === 'number' && Number.isFinite(asked));
22
+ };
6
23
  /** Tool names are the lowercased resource name; vendors reject names over 64 characters. */
7
24
  const MAX_TOOL_NAME_LENGTH = 64;
8
25
  const RESOURCE_NAME = /^(REQ|EVENT)_[A-Z0-9_]+$/;
@@ -31,20 +48,30 @@ export const opFromName = (resourceName) => {
31
48
  const suffix = (_a = /_(INSERT|MODIFY|DELETE)$/.exec(resourceName)) === null || _a === void 0 ? void 0 : _a[1];
32
49
  return suffix ? suffix.toLowerCase() : undefined;
33
50
  };
51
+ /** The kinds of resource the validator accepts. Kept apart from GENESIS_AI_CONSUMES on purpose. */
52
+ const KNOWN_KINDS = ['request', 'event'];
34
53
  /**
35
- * Checks a generated AI config before anything is registered, returning every problem found.
54
+ * Checks a generated AI config before anything is registered, and says what can be kept.
36
55
  *
37
56
  * @remarks
38
57
  * The config is machine-generated and schema-checked upstream, so a violation here is a bug in
39
- * that pipeline, not something to work around. The caller turns problems into a blocked
40
- * assistant with the reason on screen — scoped to the assistant, never an exception that could
41
- * take the app down at start-up — rather than running with part of the config quietly missing.
58
+ * that pipeline, not something to work around — nothing in a resource that breaks a rule is used.
59
+ * But the refusal is scoped to what is wrong. A problem with the config as a whole (it is not
60
+ * switched on, names an unknown vendor or tier, has a `resources` that is not a list) blocks the
61
+ * assistant. No `resources` at all is accepted, with a warning at registration. A
62
+ * problem with one resource leaves that resource out and keeps the rest: one malformed entry used
63
+ * to switch off every tool, reads included, and a config written by a newer generator — a kind this
64
+ * version does not know — would have switched off the whole assistant in every app that met it.
65
+ *
66
+ * Leaving out a kind it does not know is survival, not support: the resource does nothing here.
42
67
  *
43
68
  * @internal
44
69
  */
45
70
  export function validateGenesisAiConfig(config) {
46
- if (!config || typeof config !== 'object')
47
- return ['the AI config is missing or not an object'];
71
+ var _a;
72
+ if (!config || typeof config !== 'object') {
73
+ return { problems: ['the AI config is missing or not an object'], resources: [], dropped: [] };
74
+ }
48
75
  const c = config;
49
76
  const problems = [];
50
77
  if (c.enabled !== true)
@@ -69,53 +96,81 @@ export function validateGenesisAiConfig(config) {
69
96
  // registration logs a warning naming both causes. What that case needs is a signal, not a
70
97
  // block.
71
98
  if (c.resources === undefined)
72
- return problems;
73
- if (!Array.isArray(c.resources))
74
- return [...problems, 'resources must be an array'];
75
- const seen = new Set();
76
- c.resources.forEach((resource, i) => {
77
- const at = `resources[${i}]`;
99
+ return { problems, resources: [], dropped: [] };
100
+ if (!Array.isArray(c.resources)) {
101
+ return { problems: [...problems, 'resources must be an array'], resources: [], dropped: [] };
102
+ }
103
+ // Counted over every entry before any is judged: a duplicate leaves out EVERY copy. Which one
104
+ // the generator meant is unknown, and keeping the first would be a guess at it. Two tools with
105
+ // one name are rejected by the vendor, and the same list feeds the generated MCP script, which
106
+ // refuses a repeated name at load.
107
+ const copies = new Map();
108
+ for (const resource of c.resources) {
78
109
  const name = resource === null || resource === void 0 ? void 0 : resource.name;
79
- if (typeof name !== 'string' || !RESOURCE_NAME.test(name)) {
80
- problems.push(`${at}: name must look like REQ_<NAME> or EVENT_<NAME> (got ${String(name)})`);
81
- return;
82
- }
83
- if (toolNameOf(name).length > MAX_TOOL_NAME_LENGTH) {
84
- problems.push(`${name}: longer than the ${MAX_TOOL_NAME_LENGTH} characters a tool name allows`);
85
- }
86
- // A duplicate is not harmless: two tools with one name are rejected by the vendor, and the
87
- // same list feeds the generated MCP script, which refuses a repeated name at load.
88
- if (seen.has(name))
89
- problems.push(`${name}: appears more than once`);
90
- seen.add(name);
91
- const expectedKind = name.startsWith('REQ_') ? 'request' : 'event';
92
- if (resource.kind !== expectedKind) {
93
- problems.push(`${name}: kind must be '${expectedKind}' (got ${String(resource.kind)})`);
110
+ if (typeof name === 'string')
111
+ copies.set(name, ((_a = copies.get(name)) !== null && _a !== void 0 ? _a : 0) + 1);
112
+ }
113
+ const resources = [];
114
+ const dropped = [];
115
+ c.resources.forEach((resource, i) => {
116
+ var _a;
117
+ const name = typeof (resource === null || resource === void 0 ? void 0 : resource.name) === 'string' ? resource.name : undefined;
118
+ const wrong = resourceProblems(resource, (_a = copies.get(name !== null && name !== void 0 ? name : '')) !== null && _a !== void 0 ? _a : 0);
119
+ if (wrong.length)
120
+ dropped.push({ at: `resources[${i}]`, name, problems: wrong });
121
+ else
122
+ resources.push(resource);
123
+ });
124
+ return { problems, resources, dropped };
125
+ }
126
+ /** What is wrong with one resource, if anything. `copies` is how many entries share its name. */
127
+ function resourceProblems(resource, copies) {
128
+ // A kind this version does not know is judged on nothing else: its name need not look like
129
+ // anything here (a dataserver query's name is free-form), and it is left out either way.
130
+ const kind = resource === null || resource === void 0 ? void 0 : resource.kind;
131
+ if (typeof kind === 'string' && !KNOWN_KINDS.includes(kind)) {
132
+ return [
133
+ `kind '${kind}' is not one this version of the assistant reads (${KNOWN_KINDS.join(' or ')})`,
134
+ ];
135
+ }
136
+ const name = resource === null || resource === void 0 ? void 0 : resource.name;
137
+ if (typeof name !== 'string' || !RESOURCE_NAME.test(name)) {
138
+ return [`name must look like REQ_<NAME> or EVENT_<NAME> (got ${String(name)})`];
139
+ }
140
+ const problems = [];
141
+ if (toolNameOf(name).length > MAX_TOOL_NAME_LENGTH) {
142
+ problems.push(`longer than the ${MAX_TOOL_NAME_LENGTH} characters a tool name allows`);
143
+ }
144
+ if (copies > 1) {
145
+ problems.push(`appears ${copies} times, and which one is meant is unknown`);
146
+ }
147
+ const expectedKind = name.startsWith('REQ_') ? 'request' : 'event';
148
+ if (kind !== expectedKind) {
149
+ problems.push(`kind must be '${expectedKind}' (got ${String(kind)})`);
150
+ }
151
+ if (typeof resource.context !== 'string')
152
+ problems.push('context must be a string');
153
+ if (expectedKind === 'event') {
154
+ if (!GENESIS_EVENT_OPS.includes(resource.op)) {
155
+ problems.push(`op must be one of ${GENESIS_EVENT_OPS.join(', ')}`);
94
156
  }
95
- if (typeof resource.context !== 'string')
96
- problems.push(`${name}: context must be a string`);
97
- if (expectedKind === 'event') {
98
- if (!GENESIS_EVENT_OPS.includes(resource.op)) {
99
- problems.push(`${name}: op must be one of ${GENESIS_EVENT_OPS.join(', ')}`);
100
- }
101
- // The same cross-check `kind` gets, for the same reason: a name and a declaration that
102
- // disagree are a generator bug, and this one is not cosmetic — see opFromName.
103
- const declared = opFromName(name);
104
- if (declared && resource.op !== declared) {
105
- problems.push(`${name}: op must be '${declared}' to match its name (got ${String(resource.op)})`);
106
- }
107
- if (resource.maxRows !== undefined)
108
- problems.push(`${name}: maxRows applies to requests only`);
157
+ // The same cross-check `kind` gets, for the same reason: a name and a declaration that
158
+ // disagree are a generator bug, and this one is not cosmetic — see opFromName.
159
+ const declared = opFromName(name);
160
+ if (declared && resource.op !== declared) {
161
+ problems.push(`op must be '${declared}' to match its name (got ${String(resource.op)})`);
109
162
  }
110
- else {
111
- if (resource.op !== undefined)
112
- problems.push(`${name}: op applies to events only`);
113
- const { maxRows } = resource;
114
- if (maxRows !== undefined &&
115
- !(Number.isInteger(maxRows) && maxRows >= 1 && maxRows <= MAX_ROWS_CEILING)) {
116
- problems.push(`${name}: maxRows must be a whole number from 1 to ${MAX_ROWS_CEILING}`);
117
- }
163
+ if (resource.maxRows !== undefined)
164
+ problems.push('maxRows applies to requests only');
165
+ }
166
+ else {
167
+ if (resource.op !== undefined)
168
+ problems.push('op applies to events only');
169
+ const { maxRows } = resource;
170
+ if (maxRows !== undefined &&
171
+ !(Number.isInteger(maxRows) && maxRows >= 1 && maxRows <= MAX_ROWS_CEILING)) {
172
+ problems.push(`maxRows must be a whole number from 1 to ${MAX_ROWS_CEILING}`);
118
173
  }
119
- });
174
+ }
120
175
  return problems;
121
176
  }
@@ -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.",