@genesislcap/ai-assistant 15.46.5 → 15.47.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.
- package/dist/custom-elements.json +426 -214
- package/dist/dts/genesis/config.d.ts +30 -6
- package/dist/dts/genesis/config.d.ts.map +1 -1
- package/dist/dts/genesis/consumes.d.ts.map +1 -1
- package/dist/dts/genesis/event-fields.d.ts.map +1 -1
- package/dist/dts/genesis/filter-fields.d.ts +31 -0
- package/dist/dts/genesis/filter-fields.d.ts.map +1 -1
- package/dist/dts/genesis/index.d.ts +3 -1
- package/dist/dts/genesis/index.d.ts.map +1 -1
- package/dist/dts/genesis/reference-check.d.ts +83 -0
- package/dist/dts/genesis/reference-check.d.ts.map +1 -0
- package/dist/dts/genesis/reference-existence.d.ts +110 -0
- package/dist/dts/genesis/reference-existence.d.ts.map +1 -0
- package/dist/dts/genesis/resource-tools.d.ts +4 -4
- package/dist/dts/genesis/resource-tools.d.ts.map +1 -1
- package/dist/dts/genesis/review-model.d.ts +2 -2
- package/dist/dts/genesis/review-model.d.ts.map +1 -1
- package/dist/dts/genesis/row-source.d.ts +32 -0
- package/dist/dts/genesis/row-source.d.ts.map +1 -1
- package/dist/dts/genesis/server-text.d.ts +29 -0
- package/dist/dts/genesis/server-text.d.ts.map +1 -1
- package/dist/dts/genesis/types.d.ts +32 -5
- package/dist/dts/genesis/types.d.ts.map +1 -1
- package/dist/dts/genesis/write-payload.d.ts +14 -1
- package/dist/dts/genesis/write-payload.d.ts.map +1 -1
- package/dist/dts/genesis/write-plan.d.ts +8 -2
- package/dist/dts/genesis/write-plan.d.ts.map +1 -1
- package/dist/dts/genesis/write-tools.d.ts +5 -3
- package/dist/dts/genesis/write-tools.d.ts.map +1 -1
- package/dist/dts/genesis/write-turn.d.ts +4 -1
- package/dist/dts/genesis/write-turn.d.ts.map +1 -1
- package/dist/esm/genesis/config.js +152 -20
- package/dist/esm/genesis/consumes.js +2 -1
- package/dist/esm/genesis/event-fields.js +5 -8
- package/dist/esm/genesis/filter-fields.js +159 -78
- package/dist/esm/genesis/index.js +1 -0
- package/dist/esm/genesis/reference-check.js +132 -0
- package/dist/esm/genesis/reference-existence.js +283 -0
- package/dist/esm/genesis/resource-tools.js +135 -18
- package/dist/esm/genesis/review-model.js +3 -1
- package/dist/esm/genesis/row-source.js +107 -16
- package/dist/esm/genesis/server-text.js +52 -0
- package/dist/esm/genesis/write-payload.js +32 -4
- package/dist/esm/genesis/write-plan.js +3 -2
- package/dist/esm/genesis/write-tools.js +248 -44
- package/dist/genesis-consumes.cjs +3 -2
- package/dist/genesis-consumes.cjs.map +2 -2
- package/dist/genesis-consumes.mjs +3 -2
- package/dist/genesis-consumes.mjs.map +2 -2
- package/docs/genesis.md +131 -21
- package/package.json +17 -17
- package/scripts/smoke-genesis-consumes-node.mjs +2 -2
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { __awaiter } from "tslib";
|
|
2
|
+
import { fieldKindOf } from './criteria';
|
|
3
|
+
import { tableOf } from './reference-check';
|
|
4
|
+
import { normaliseValue, sameValue } from './value-compare';
|
|
5
|
+
import { isBlankText, quoted } from './write-payload';
|
|
6
|
+
// Whether the references a write proposes name rows that exist (GENC-1611, contracts C-17.7 and
|
|
7
|
+
// C-17.9 to C-17.11). The values come from the frozen payload, never the model's arguments, and a
|
|
8
|
+
// row a read returns is used for existence only: none of it leaves this module.
|
|
9
|
+
/** The most distinct values one call may check. */
|
|
10
|
+
export const MAX_REFERENCE_CHECKS = 50;
|
|
11
|
+
/** Reads in flight at once. */
|
|
12
|
+
const POOL_SIZE = 4;
|
|
13
|
+
/** One deadline for all the reads before a review, not one per read. */
|
|
14
|
+
const PHASE_TIMEOUT_MS = 30000;
|
|
15
|
+
/**
|
|
16
|
+
* What the model is told about each field whose reference is checked (contracts C-17.16), by
|
|
17
|
+
* field. Only a checkable group has a sentence: one that cannot be checked is not offered at all.
|
|
18
|
+
*
|
|
19
|
+
* @internal
|
|
20
|
+
*/
|
|
21
|
+
export function checkedSentences(checkable) {
|
|
22
|
+
const sentences = new Map();
|
|
23
|
+
for (const { reference } of checkable) {
|
|
24
|
+
for (const { field, targetField } of reference.fields) {
|
|
25
|
+
const others = reference.fields.filter((member) => member.field !== field);
|
|
26
|
+
sentences.set(field, `${others.length ? `With ${others.map((member) => member.field).join(', ')}, must` : 'Must'} ` +
|
|
27
|
+
`equal the ${targetField} of one ${tableOf(reference.resource)} row returned by ` +
|
|
28
|
+
`${reference.resource}; checked before the review.`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return sentences;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The tool description's line for the references it checks, cap included, or nothing when it
|
|
35
|
+
* checks none.
|
|
36
|
+
*
|
|
37
|
+
* @internal
|
|
38
|
+
*/
|
|
39
|
+
export function checkedLine(checkable) {
|
|
40
|
+
if (!checkable.length)
|
|
41
|
+
return undefined;
|
|
42
|
+
const groups = checkable.map(({ reference }) => `${reference.fields.map(({ field }) => field).join(' and ')} against ${reference.resource}`);
|
|
43
|
+
return (`Checked before the review: ${groups.join(', ')}. A value that matches no row is refused. ` +
|
|
44
|
+
`At most ${MAX_REFERENCE_CHECKS} distinct reference values per call.`);
|
|
45
|
+
}
|
|
46
|
+
const isUnset = (value) => value === undefined || value === null || (typeof value === 'string' && isBlankText(value));
|
|
47
|
+
const typeOf = (fields, name) => { var _a; return (_a = fields.find((field) => field.name === name)) === null || _a === void 0 ? void 0 : _a.type; };
|
|
48
|
+
/**
|
|
49
|
+
* The text a target field is searched for with, or nothing when a number has no plain form. A
|
|
50
|
+
* number goes as its canonical digits: sent as written, `0012` would be read as an octal literal.
|
|
51
|
+
*/
|
|
52
|
+
function searchValue(value, targetType, ownType) {
|
|
53
|
+
if (fieldKindOf(targetType) !== 'number')
|
|
54
|
+
return String(value);
|
|
55
|
+
const digits = normaliseValue(value, ownType !== null && ownType !== void 0 ? ownType : targetType);
|
|
56
|
+
return /^[-+]?\d+(\.\d+)?$/.test(digits) ? digits : undefined;
|
|
57
|
+
}
|
|
58
|
+
const fieldsOf = (gate) => gate.reference.fields.map(({ field }) => field).join(', ');
|
|
59
|
+
const couldNotCheck = (gate, reason) => `${fieldsOf(gate)} could not be checked against ${gate.reference.resource} (${reason}), so ` +
|
|
60
|
+
'this row was not offered for writing.';
|
|
61
|
+
/**
|
|
62
|
+
* The groups one row has to check, and why it is refused before any read. On a modify only a
|
|
63
|
+
* group with a member the write changes: a row that already holds a dangling reference stays
|
|
64
|
+
* editable while the model leaves it alone.
|
|
65
|
+
*
|
|
66
|
+
* @internal
|
|
67
|
+
*/
|
|
68
|
+
export function asksOf(row, op, fields, checkable) {
|
|
69
|
+
var _a;
|
|
70
|
+
const asks = [];
|
|
71
|
+
const problems = [];
|
|
72
|
+
const details = (_a = row.details) !== null && _a !== void 0 ? _a : {};
|
|
73
|
+
for (const gate of checkable) {
|
|
74
|
+
const members = gate.reference.fields;
|
|
75
|
+
const changed = members.some(({ field }) => { var _a; return !sameValue(details[field], (_a = row.preImage) === null || _a === void 0 ? void 0 : _a[field], typeOf(fields, field)); });
|
|
76
|
+
if (op === 'modify' && !changed)
|
|
77
|
+
continue;
|
|
78
|
+
const empty = members.filter(({ field }) => isUnset(details[field])).map(({ field }) => field);
|
|
79
|
+
// No reference at all, which only an optional group can be: nothing to check.
|
|
80
|
+
if (empty.length === members.length)
|
|
81
|
+
continue;
|
|
82
|
+
if (empty.length) {
|
|
83
|
+
problems.push(`A reference to ${tableOf(gate.reference.resource)} needs all of ${fieldsOf(gate)}; ` +
|
|
84
|
+
`${empty.join(', ')} ${empty.length > 1 ? 'are' : 'is'} empty.`);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const values = members.map(({ field, targetField }) => {
|
|
88
|
+
var _a, _b;
|
|
89
|
+
return [
|
|
90
|
+
targetField,
|
|
91
|
+
searchValue(details[field], (_b = (_a = gate.targetFields.get(targetField)) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : '', typeOf(fields, field)),
|
|
92
|
+
];
|
|
93
|
+
});
|
|
94
|
+
if (values.some(([, value]) => value === undefined)) {
|
|
95
|
+
problems.push(couldNotCheck(gate, 'its value is not a plain number'));
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
asks.push({
|
|
99
|
+
gate,
|
|
100
|
+
sent: members.map(({ field }) => [field, details[field]]),
|
|
101
|
+
values: Object.fromEntries(values),
|
|
102
|
+
lookup: `${gate.reference.resource} ${JSON.stringify(values)}`,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
return { asks, problems };
|
|
106
|
+
}
|
|
107
|
+
/** Why a read failed, in words that never carry the value: on a modify it may be another user's. */
|
|
108
|
+
function failedReason(ask, answer) {
|
|
109
|
+
if (answer.cause !== 'unsearchable')
|
|
110
|
+
return answer.reason;
|
|
111
|
+
const which = ask.gate.reference.fields.length > 1 ? `one of ${fieldsOf(ask.gate)}` : fieldsOf(ask.gate);
|
|
112
|
+
return `${which} has a value that cannot be searched for on ${ask.gate.reference.resource}`;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Why a row is refused for what a read said about one of its groups, or nothing when the row it
|
|
116
|
+
* names exists.
|
|
117
|
+
*
|
|
118
|
+
* @internal
|
|
119
|
+
*/
|
|
120
|
+
export function problemOf(ask, answer) {
|
|
121
|
+
const { resource } = ask.gate.reference;
|
|
122
|
+
if (!answer)
|
|
123
|
+
return couldNotCheck(ask.gate, `${resource} took too long to answer`);
|
|
124
|
+
if (answer.status === 'exists')
|
|
125
|
+
return undefined;
|
|
126
|
+
const members = ask.gate.reference.fields;
|
|
127
|
+
if (answer.status === 'failed')
|
|
128
|
+
return couldNotCheck(ask.gate, failedReason(ask, answer));
|
|
129
|
+
const table = tableOf(resource);
|
|
130
|
+
if (members.length === 1) {
|
|
131
|
+
const [[field, value]] = ask.sent;
|
|
132
|
+
return (`${field} '${quoted(value)}' matches no ${table} row you can see. Read ${resource} and ` +
|
|
133
|
+
`copy its ${members[0].targetField} exactly. Rows proposed in this same batch do not ` +
|
|
134
|
+
'count yet.');
|
|
135
|
+
}
|
|
136
|
+
return (`${ask.sent.map(([field, value]) => `${field} '${quoted(value)}'`).join(', ')} match no ` +
|
|
137
|
+
`single ${table} row you can see. Read ${resource} and copy ` +
|
|
138
|
+
`${members.map(({ targetField }) => targetField).join(', ')} from one row.`);
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Reads each lookup once, at most {@link POOL_SIZE} at a time, until the phase's deadline or a
|
|
142
|
+
* Stop, whichever is first. A read still out then is abandoned, and a lookup with no answer was
|
|
143
|
+
* not checked.
|
|
144
|
+
*/
|
|
145
|
+
function readAll(lookups, deadlineMs, signal) {
|
|
146
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
147
|
+
const answers = new Map();
|
|
148
|
+
const pending = [...lookups];
|
|
149
|
+
let over = false;
|
|
150
|
+
let timer;
|
|
151
|
+
let stop = () => undefined;
|
|
152
|
+
const ended = new Promise((resolve) => {
|
|
153
|
+
stop = () => {
|
|
154
|
+
over = true;
|
|
155
|
+
resolve(undefined);
|
|
156
|
+
};
|
|
157
|
+
timer = setTimeout(stop, deadlineMs);
|
|
158
|
+
signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', stop, { once: true });
|
|
159
|
+
});
|
|
160
|
+
const worker = () => __awaiter(this, void 0, void 0, function* () {
|
|
161
|
+
const open = () => !over && !(signal === null || signal === void 0 ? void 0 : signal.aborted);
|
|
162
|
+
while (open() && pending.length) {
|
|
163
|
+
const [lookup, ask] = pending.shift();
|
|
164
|
+
// oxlint-disable-next-line no-await-in-loop -- the pool is what bounds the reads in flight
|
|
165
|
+
const answer = yield Promise.race([
|
|
166
|
+
ask.gate.source.exists(ask.values).catch(() => ({
|
|
167
|
+
status: 'failed',
|
|
168
|
+
reason: `checking ${ask.gate.reference.resource} failed`,
|
|
169
|
+
})),
|
|
170
|
+
ended,
|
|
171
|
+
]);
|
|
172
|
+
if (answer)
|
|
173
|
+
answers.set(lookup, answer);
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
try {
|
|
177
|
+
yield Promise.all(Array.from({ length: Math.min(POOL_SIZE, pending.length) }, worker));
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
clearTimeout(timer);
|
|
181
|
+
signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', stop);
|
|
182
|
+
}
|
|
183
|
+
return answers;
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Checks before the review that every reference the batch sets names a row the user can see.
|
|
188
|
+
*
|
|
189
|
+
* @remarks
|
|
190
|
+
* A Stop wins over everything this adds: it is checked before any of it, and again once the
|
|
191
|
+
* reads are back, so a stopped call is never answered as refused, disconnected or unchanged.
|
|
192
|
+
*
|
|
193
|
+
* @internal
|
|
194
|
+
*/
|
|
195
|
+
export function checkReferences(rows, options) {
|
|
196
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
197
|
+
var _a, _b, _c, _d;
|
|
198
|
+
if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted)
|
|
199
|
+
return { status: 'stopped' };
|
|
200
|
+
const problems = new Map();
|
|
201
|
+
const asked = new Map();
|
|
202
|
+
const lookups = new Map();
|
|
203
|
+
// A row already refused carries no payload, so it asks nothing: it is not read for.
|
|
204
|
+
for (const row of rows) {
|
|
205
|
+
const found = asksOf(row, options.op, options.fields, options.checkable);
|
|
206
|
+
if (found.problems.length)
|
|
207
|
+
problems.set(row.index, found.problems);
|
|
208
|
+
asked.set(row.index, found.asks);
|
|
209
|
+
for (const ask of found.asks)
|
|
210
|
+
if (!lookups.has(ask.lookup))
|
|
211
|
+
lookups.set(ask.lookup, ask);
|
|
212
|
+
}
|
|
213
|
+
// Refused whole, never checked in part: a batch half checked reads as a batch checked.
|
|
214
|
+
if (lookups.size > MAX_REFERENCE_CHECKS) {
|
|
215
|
+
return {
|
|
216
|
+
status: 'refused',
|
|
217
|
+
reason: `This batch needs ${lookups.size} reference checks and ${MAX_REFERENCE_CHECKS} is the ` +
|
|
218
|
+
'most one review may run. Send fewer rows.',
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
const answers = lookups.size
|
|
222
|
+
? yield readAll(lookups, (_b = options.deadlineMs) !== null && _b !== void 0 ? _b : PHASE_TIMEOUT_MS, options.signal)
|
|
223
|
+
: new Map();
|
|
224
|
+
if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted)
|
|
225
|
+
return { status: 'stopped' };
|
|
226
|
+
// Read from `connect` rather than matched in a reason: a lost connection fails the whole call.
|
|
227
|
+
const failed = [...lookups.keys()].some((lookup) => {
|
|
228
|
+
var _a;
|
|
229
|
+
const status = (_a = answers.get(lookup)) === null || _a === void 0 ? void 0 : _a.status;
|
|
230
|
+
return status !== 'exists' && status !== 'missing';
|
|
231
|
+
});
|
|
232
|
+
if (failed && !options.connect.isConnected)
|
|
233
|
+
return { status: 'not_connected' };
|
|
234
|
+
for (const [index, asks] of asked) {
|
|
235
|
+
for (const ask of asks) {
|
|
236
|
+
const problem = problemOf(ask, answers.get(ask.lookup));
|
|
237
|
+
if (problem)
|
|
238
|
+
problems.set(index, [...((_d = problems.get(index)) !== null && _d !== void 0 ? _d : []), problem]);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return { status: 'checked', problems };
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Reads a row's references again just before it is written (contracts C-17.12), beside its own
|
|
246
|
+
* staleness read. Not memoised across rows, and nothing read before the review is reused: the
|
|
247
|
+
* review can stay open for minutes.
|
|
248
|
+
*
|
|
249
|
+
* @internal
|
|
250
|
+
*/
|
|
251
|
+
export function referencesNow(asks) {
|
|
252
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
253
|
+
const answers = yield Promise.all(asks.map((ask) => ask.gate.source.exists(ask.values).catch(() => ({
|
|
254
|
+
status: 'failed',
|
|
255
|
+
reason: `checking ${ask.gate.reference.resource} failed`,
|
|
256
|
+
}))));
|
|
257
|
+
const gone = asks.find((_, i) => answers[i].status === 'missing');
|
|
258
|
+
if (gone) {
|
|
259
|
+
const { resource, fields } = gone.gate.reference;
|
|
260
|
+
const table = tableOf(resource);
|
|
261
|
+
const named = gone.sent.map(([field, value]) => `${field} '${quoted(value)}'`).join(', ');
|
|
262
|
+
return {
|
|
263
|
+
status: 'gone',
|
|
264
|
+
message: `${named} no longer ${fields.length > 1 ? `match a single ${table} row` : `matches a ${table} row`} ` +
|
|
265
|
+
`you can see, so nothing was written for it. Read ${resource} again before proposing it ` +
|
|
266
|
+
'a second time.',
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
const failed = asks.findIndex((_, i) => answers[i].status === 'failed');
|
|
270
|
+
if (failed === -1)
|
|
271
|
+
return { status: 'there' };
|
|
272
|
+
return {
|
|
273
|
+
status: 'unreadable',
|
|
274
|
+
reason: failedReason(asks[failed], answers[failed]),
|
|
275
|
+
};
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
/** The rows with what the check found added to their problems. */
|
|
279
|
+
export const withReferenceProblems = (rows, problems) => rows.map((row) => {
|
|
280
|
+
var _a;
|
|
281
|
+
const found = problems.get(row.index);
|
|
282
|
+
return found ? Object.assign(Object.assign({}, row), { problems: [...((_a = row.problems) !== null && _a !== void 0 ? _a : []), ...found] }) : row;
|
|
283
|
+
});
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { __awaiter } from "tslib";
|
|
2
|
-
import { getConnect } from '@genesislcap/foundation-comms';
|
|
1
|
+
import { __awaiter, __rest } from "tslib";
|
|
2
|
+
import { dataServerResultFilter, getConnect, } from '@genesislcap/foundation-comms';
|
|
3
3
|
import { logger } from '../utils/logger';
|
|
4
4
|
import { withTimeout } from '../utils/with-timeout';
|
|
5
|
-
import { capIsReadable, DEFAULT_MAX_ROWS, MAX_ROWS_CEILING, toolNameOf } from './config';
|
|
5
|
+
import { capIsReadable, DEFAULT_MAX_ROWS, firstPerToolName, MAX_ROWS_CEILING, toolNameOf, } from './config';
|
|
6
6
|
import { composeCriteria } from './criteria';
|
|
7
|
-
import { loadFilterFields } from './filter-fields';
|
|
7
|
+
import { loadFilterFields, loadQueryFields } from './filter-fields';
|
|
8
8
|
import { serialisable } from './serialisable';
|
|
9
|
-
import { plainFailure, plainServerText } from './server-text';
|
|
9
|
+
import { plainFailure, plainServerText, refusalOf } from './server-text';
|
|
10
10
|
/**
|
|
11
11
|
* The provenance stamped on everything a tool returns from the app (ADR P9). Rows are written by
|
|
12
12
|
* the app's other users, so the model must treat their text as data, never as instructions; the
|
|
@@ -81,7 +81,8 @@ function readDefinition(resource, cap, fields) {
|
|
|
81
81
|
return {
|
|
82
82
|
name: toolNameOf(resource.name),
|
|
83
83
|
description: `${resource.context}\n\n` +
|
|
84
|
-
`Reads ${resource.
|
|
84
|
+
`Reads ${resource.kind === 'query' ? `the ${resource.name} query` : resource.name} from ` +
|
|
85
|
+
`the app. Read-only. Returns at most ${cap} rows per call and ` +
|
|
85
86
|
'says truncated when more rows match; ' +
|
|
86
87
|
(filterable.length
|
|
87
88
|
? 'then narrow the read with filters. '
|
|
@@ -103,8 +104,8 @@ function readDefinition(resource, cap, fields) {
|
|
|
103
104
|
* DETAILS rather than `OFFSET`. The reason it stays out of v1 is that criteria filtering plus
|
|
104
105
|
* the row cap and the truncation note cover the need, and paging adds a second way to be wrong.
|
|
105
106
|
*/
|
|
106
|
-
function truncationNote(maxRows, cap, canFilter) {
|
|
107
|
-
return (
|
|
107
|
+
function truncationNote(maxRows, cap, canFilter, lead = 'More rows match than were returned, so these are not the full set. ') {
|
|
108
|
+
return (lead +
|
|
108
109
|
(canFilter ? 'Narrow the read with filters to find specific rows. ' : '') +
|
|
109
110
|
(maxRows < cap ? `max_rows can go up to ${cap}.` : '')).trim();
|
|
110
111
|
}
|
|
@@ -112,7 +113,7 @@ function truncationNote(maxRows, cap, canFilter) {
|
|
|
112
113
|
* Builds the assistant's tools from an app's resources.
|
|
113
114
|
*
|
|
114
115
|
* @remarks
|
|
115
|
-
* Each request resource becomes a read tool: filters from the resource's own schema, a row cap
|
|
116
|
+
* Each request or query resource becomes a read tool: filters from the resource's own schema, a row cap
|
|
116
117
|
* (ADR P10: 50 by default, never more than the resource's `maxRows` whatever the model asks),
|
|
117
118
|
* no paging (see `truncationNote`), and every result stamped as untrusted app data (P9). Event resources are not turned
|
|
118
119
|
* into tools yet; the write path, with its review table, comes separately.
|
|
@@ -130,8 +131,10 @@ export function createGenesisResourceTools(resources, options = {}) {
|
|
|
130
131
|
// A `maxRows` that is there but is not a number declares SOME cap, and none can be read from
|
|
131
132
|
// it. Falling back to the default read up to five times what was declared — `'10'` became 50,
|
|
132
133
|
// where it once meant 10 — so the resource gets no tool instead, as the validator leaves it out.
|
|
133
|
-
|
|
134
|
-
|
|
134
|
+
//
|
|
135
|
+
// A request and a query are read the same way from the model's side, so they share one set of
|
|
136
|
+
// tool names.
|
|
137
|
+
const reads = firstPerToolName(resources.filter((r) => r.kind === 'request' || r.kind === 'query'))
|
|
135
138
|
.filter((r) => {
|
|
136
139
|
if (capIsReadable(r))
|
|
137
140
|
return true;
|
|
@@ -161,13 +164,15 @@ export function createGenesisResourceTools(resources, options = {}) {
|
|
|
161
164
|
const toolDefinitions = () => {
|
|
162
165
|
inFlight !== null && inFlight !== void 0 ? inFlight : (inFlight = (() => __awaiter(this, void 0, void 0, function* () {
|
|
163
166
|
const connect = resolveConnect();
|
|
164
|
-
yield Promise.all(
|
|
167
|
+
yield Promise.all(reads
|
|
165
168
|
.filter((r) => !settled.has(r.name))
|
|
166
169
|
.map((r) => __awaiter(this, void 0, void 0, function* () {
|
|
167
|
-
var _a;
|
|
170
|
+
var _a, _b;
|
|
168
171
|
if (!connect)
|
|
169
172
|
return;
|
|
170
|
-
const meta =
|
|
173
|
+
const meta = r.kind === 'query'
|
|
174
|
+
? yield loadQueryFields(connect, r.name, (_a = options.timeouts) === null || _a === void 0 ? void 0 : _a.metadataMs)
|
|
175
|
+
: yield loadFilterFields(connect, r.name, (_b = options.timeouts) === null || _b === void 0 ? void 0 : _b.metadataMs);
|
|
171
176
|
if (meta.status === 'ok') {
|
|
172
177
|
filterFields.set(r.name, meta.fields);
|
|
173
178
|
// Three different things, three different logs. "Nothing to filter on" is a
|
|
@@ -182,7 +187,8 @@ export function createGenesisResourceTools(resources, options = {}) {
|
|
|
182
187
|
else {
|
|
183
188
|
logger.warn(`Genesis assistant: ${r.name} came back describing no fields at all, so its ` +
|
|
184
189
|
'read tool takes no filters. Check that the resource is deployed and that ' +
|
|
185
|
-
|
|
190
|
+
'its metadata is published as ' +
|
|
191
|
+
`${r.kind === 'query' ? r.name : r.name.replace(/^REQ_/, '')}.`);
|
|
186
192
|
}
|
|
187
193
|
}
|
|
188
194
|
settled.set(r.name, readDefinition(r, capOf(r), meta.fields));
|
|
@@ -193,14 +199,15 @@ export function createGenesisResourceTools(resources, options = {}) {
|
|
|
193
199
|
settled.set(r.name, readDefinition(r, capOf(r), new Map()));
|
|
194
200
|
}
|
|
195
201
|
})));
|
|
196
|
-
return
|
|
202
|
+
return reads.map((r) => { var _a; return (_a = settled.get(r.name)) !== null && _a !== void 0 ? _a : readDefinition(r, capOf(r), new Map()); });
|
|
197
203
|
}))().finally(() => {
|
|
198
204
|
inFlight = undefined;
|
|
199
205
|
}));
|
|
200
206
|
return inFlight;
|
|
201
207
|
};
|
|
202
208
|
const toolHandlers = {};
|
|
203
|
-
for (const resource of
|
|
209
|
+
for (const resource of reads) {
|
|
210
|
+
const read = resource.kind === 'query' ? readQueryRows : readRows;
|
|
204
211
|
toolHandlers[toolNameOf(resource.name)] = (args) => __awaiter(this, void 0, void 0, function* () {
|
|
205
212
|
var _a;
|
|
206
213
|
// The allow-list a filter is validated against must not depend on toolDefinitions()
|
|
@@ -209,7 +216,7 @@ export function createGenesisResourceTools(resources, options = {}) {
|
|
|
209
216
|
// metadata the definitions use, so the two can never disagree.
|
|
210
217
|
if (!filterFields.has(resource.name))
|
|
211
218
|
yield toolDefinitions();
|
|
212
|
-
return
|
|
219
|
+
return read(resource, capOf(resource), args, resolveConnect(), filterFields.get(resource.name), (_a = options.timeouts) === null || _a === void 0 ? void 0 : _a.readMs);
|
|
213
220
|
});
|
|
214
221
|
}
|
|
215
222
|
return { toolDefinitions, toolHandlers };
|
|
@@ -302,3 +309,113 @@ function readRows(resource_1, cap_1, args_1, connect_1, filterFields_1) {
|
|
|
302
309
|
truncated }, (truncated ? { note: truncationNote(maxRows, cap, !!(filterFields === null || filterFields === void 0 ? void 0 : filterFields.size)) } : {}));
|
|
303
310
|
});
|
|
304
311
|
}
|
|
312
|
+
/** Why a query read timed out, without inviting a retry: each one opens another server subscription. */
|
|
313
|
+
const QUERY_TIMEOUT = 'The app did not answer this read in time. Nothing was returned.';
|
|
314
|
+
/**
|
|
315
|
+
* Reads a dataserver query once: one DATA_LOGON, whose first update is the answer. The socket logs
|
|
316
|
+
* off by itself on that update, so nothing is left subscribed unless the read times out (a known
|
|
317
|
+
* limit: the bridge cannot log off a snapshot it never heard back from).
|
|
318
|
+
*
|
|
319
|
+
* @remarks
|
|
320
|
+
* Every step fails closed, because an empty result is an answer the model will act on:
|
|
321
|
+
* - A reply is read only in a shape the platform is known to send. Anything else is
|
|
322
|
+
* `unexpected_shape`, never zero rows.
|
|
323
|
+
* - Every row must be an INSERT: the first image of a query is. A MODIFY or DELETE would be
|
|
324
|
+
* dropped by taking the inserts alone.
|
|
325
|
+
* - `MORE_ROWS` is the only truncation signal. `ROWS_COUNT` counts an index range and ignores the
|
|
326
|
+
* criteria and the user's rights, so it is never read. A reply that does not say reads as
|
|
327
|
+
* possibly truncated.
|
|
328
|
+
* - Rows are cut to `max_rows` here too: the preview's dev server ignores `MAX_ROWS`.
|
|
329
|
+
*/
|
|
330
|
+
function readQueryRows(resource_1, cap_1, args_1, connect_1, filterFields_1) {
|
|
331
|
+
return __awaiter(this, arguments, void 0, function* (resource, cap, args, connect, filterFields, timeoutMs = READ_TIMEOUT_MS) {
|
|
332
|
+
const fail = (error, message) => ({
|
|
333
|
+
source: GENESIS_DATA_SOURCE,
|
|
334
|
+
untrusted: true,
|
|
335
|
+
resource: resource.name,
|
|
336
|
+
error,
|
|
337
|
+
message,
|
|
338
|
+
});
|
|
339
|
+
if (!(connect === null || connect === void 0 ? void 0 : connect.isConnected)) {
|
|
340
|
+
return fail('not_connected', 'The app is not connected to its server right now.');
|
|
341
|
+
}
|
|
342
|
+
const asked = typeof args.max_rows === 'number' && Number.isFinite(args.max_rows);
|
|
343
|
+
const requested = asked ? Math.floor(args.max_rows) : DEFAULT_MAX_ROWS;
|
|
344
|
+
const maxRows = Math.min(Math.max(requested, 1), cap);
|
|
345
|
+
const composed = composeCriteria(args.filters, filterFields !== null && filterFields !== void 0 ? filterFields : new Map());
|
|
346
|
+
if (composed.status === 'rejected') {
|
|
347
|
+
return fail('invalid_filter', `That filter was not applied: ${composed.reason}`);
|
|
348
|
+
}
|
|
349
|
+
const filtered = !!composed.criteria;
|
|
350
|
+
const refused = (errors) => {
|
|
351
|
+
const { text, codes } = refusalOf(errors);
|
|
352
|
+
if (codes)
|
|
353
|
+
logger.warn(`Genesis assistant: ${resource.name} refused a read (${codes}).`);
|
|
354
|
+
return fail('rejected', readableRefusal(text, resource.name, filtered));
|
|
355
|
+
};
|
|
356
|
+
let reply;
|
|
357
|
+
try {
|
|
358
|
+
// MAX_ROWS always: the server's own default is 250. Nothing else a dataserver takes is sent.
|
|
359
|
+
reply = yield withTimeout(connect.snapshot(resource.name, Object.assign({ MAX_ROWS: maxRows }, (composed.criteria ? { CRITERIA_MATCH: composed.criteria } : {}))), timeoutMs);
|
|
360
|
+
}
|
|
361
|
+
catch (error) {
|
|
362
|
+
// The socket rejects a LOGON_NACK or MSG_NACK with the message it received. That is the app
|
|
363
|
+
// refusing the read, in its own words; anything else is the read failing.
|
|
364
|
+
const received = error === null || error === void 0 ? void 0 : error.receivedMessage;
|
|
365
|
+
if (received && typeof received === 'object') {
|
|
366
|
+
return refused(Array.isArray(received.ERROR) ? received.ERROR : []);
|
|
367
|
+
}
|
|
368
|
+
return fail('request_failed', plainFailure(error, `${resource.name} read failed`, {
|
|
369
|
+
timeout: QUERY_TIMEOUT,
|
|
370
|
+
failed: 'The read failed',
|
|
371
|
+
}));
|
|
372
|
+
}
|
|
373
|
+
const unexpected = () => {
|
|
374
|
+
logger.error(`Genesis assistant: ${resource.name} answered a read in a shape this assistant does not ` +
|
|
375
|
+
'handle.', { MESSAGE_TYPE: reply === null || reply === void 0 ? void 0 : reply.MESSAGE_TYPE, keys: reply ? Object.keys(reply) : [] });
|
|
376
|
+
return fail('unexpected_shape', 'The app sent a shape this read does not handle.');
|
|
377
|
+
};
|
|
378
|
+
// Over HTTP a refusal resolves rather than rejects.
|
|
379
|
+
if (!reply || typeof reply !== 'object')
|
|
380
|
+
return unexpected();
|
|
381
|
+
if (Array.isArray(reply.ERROR) && reply.ERROR.length)
|
|
382
|
+
return refused(reply.ERROR);
|
|
383
|
+
const type = reply.MESSAGE_TYPE;
|
|
384
|
+
if (type !== 'QUERY_UPDATE' && type !== 'QUERY_HTTP_UPDATE')
|
|
385
|
+
return unexpected();
|
|
386
|
+
let serverRows;
|
|
387
|
+
if (reply.ROW === undefined) {
|
|
388
|
+
// An empty result has no ROW at all. Only a reply that says MORE_ROWS is one.
|
|
389
|
+
if (typeof reply.MORE_ROWS !== 'boolean')
|
|
390
|
+
return unexpected();
|
|
391
|
+
serverRows = [];
|
|
392
|
+
}
|
|
393
|
+
else if (Array.isArray(reply.ROW)) {
|
|
394
|
+
serverRows = reply.ROW;
|
|
395
|
+
}
|
|
396
|
+
else {
|
|
397
|
+
return unexpected();
|
|
398
|
+
}
|
|
399
|
+
const firstImage = serverRows.every((row) => { var _a; return ((_a = row === null || row === void 0 ? void 0 : row.DETAILS) === null || _a === void 0 ? void 0 : _a.OPERATION) === 'INSERT'; });
|
|
400
|
+
if (!firstImage)
|
|
401
|
+
return unexpected();
|
|
402
|
+
// The filter copies DETAILS.ROW_REF onto each row. That is the dataserver's own reference, not a
|
|
403
|
+
// column of the app's, so it comes off again: a model told to copy ids from rows it has read
|
|
404
|
+
// must not find one there that no request row has.
|
|
405
|
+
const all = dataServerResultFilter({ ROW: serverRows }).inserts.map((_a) => {
|
|
406
|
+
var { ROW_REF: _rowRef } = _a, columns = __rest(_a, ["ROW_REF"]);
|
|
407
|
+
return serialisable(columns);
|
|
408
|
+
});
|
|
409
|
+
const rows = all.slice(0, maxRows);
|
|
410
|
+
const said = typeof reply.MORE_ROWS === 'boolean';
|
|
411
|
+
const truncated = reply.MORE_ROWS !== false || all.length > maxRows;
|
|
412
|
+
return Object.assign({ source: GENESIS_DATA_SOURCE, untrusted: true, resource: resource.name, rows,
|
|
413
|
+
truncated }, (truncated
|
|
414
|
+
? {
|
|
415
|
+
note: truncationNote(maxRows, cap, !!(filterFields === null || filterFields === void 0 ? void 0 : filterFields.size), said
|
|
416
|
+
? undefined
|
|
417
|
+
: 'The app did not say whether more rows exist, so these may not be the full set. '),
|
|
418
|
+
}
|
|
419
|
+
: {}));
|
|
420
|
+
});
|
|
421
|
+
}
|
|
@@ -195,7 +195,7 @@ export function buildReviewModel(options) {
|
|
|
195
195
|
});
|
|
196
196
|
const built = rows.map((row) => {
|
|
197
197
|
var _a, _b, _c;
|
|
198
|
-
// A REFUSED row will not be written, so it has no change to show — and a refused modify
|
|
198
|
+
// A REFUSED row will not be written, so it has no change to show — and a refused modify can come
|
|
199
199
|
// with its pre-image and an EMPTY payload, which marked every non-empty field as changed and
|
|
200
200
|
// rendered the row as a full wipe: each old value struck through over an empty new one. The
|
|
201
201
|
// screen whose job is to show what will happen showed the most alarming outcome, for a row
|
|
@@ -397,6 +397,8 @@ export function rowFate(fate) {
|
|
|
397
397
|
return 'not written (stopped)';
|
|
398
398
|
case 'changed_since_review':
|
|
399
399
|
return 'not written (changed since the review)';
|
|
400
|
+
case 'reference_gone':
|
|
401
|
+
return 'not written (a record it refers to is gone)';
|
|
400
402
|
case 'gone':
|
|
401
403
|
return 'not written (row changed or no longer exists)';
|
|
402
404
|
case 'invalid_payload':
|