@genesislcap/ai-assistant 15.37.0 → 15.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/custom-elements.json +638 -0
- package/dist/dts/genesis/calendar.d.ts +25 -0
- package/dist/dts/genesis/calendar.d.ts.map +1 -0
- package/dist/dts/genesis/config.d.ts +16 -0
- package/dist/dts/genesis/config.d.ts.map +1 -1
- package/dist/dts/genesis/criteria.d.ts +24 -2
- package/dist/dts/genesis/criteria.d.ts.map +1 -1
- package/dist/dts/genesis/event-fields.d.ts +84 -0
- package/dist/dts/genesis/event-fields.d.ts.map +1 -0
- package/dist/dts/genesis/filter-fields.d.ts +69 -5
- package/dist/dts/genesis/filter-fields.d.ts.map +1 -1
- package/dist/dts/genesis/index.d.ts +3 -0
- package/dist/dts/genesis/index.d.ts.map +1 -1
- package/dist/dts/genesis/register-genesis-assistant.d.ts +13 -0
- package/dist/dts/genesis/register-genesis-assistant.d.ts.map +1 -1
- package/dist/dts/genesis/resource-tools.d.ts.map +1 -1
- package/dist/dts/genesis/review-model.d.ts +202 -0
- package/dist/dts/genesis/review-model.d.ts.map +1 -0
- package/dist/dts/genesis/row-source.d.ts +102 -0
- package/dist/dts/genesis/row-source.d.ts.map +1 -0
- package/dist/dts/genesis/serialisable.d.ts +25 -0
- package/dist/dts/genesis/serialisable.d.ts.map +1 -0
- package/dist/dts/genesis/server-text.d.ts +63 -0
- package/dist/dts/genesis/server-text.d.ts.map +1 -0
- package/dist/dts/genesis/type-name.d.ts +18 -0
- package/dist/dts/genesis/type-name.d.ts.map +1 -0
- package/dist/dts/genesis/types.d.ts +7 -0
- package/dist/dts/genesis/types.d.ts.map +1 -1
- package/dist/dts/genesis/value-compare.d.ts +19 -0
- package/dist/dts/genesis/value-compare.d.ts.map +1 -0
- package/dist/dts/genesis/write-commit.d.ts +53 -0
- package/dist/dts/genesis/write-commit.d.ts.map +1 -0
- package/dist/dts/genesis/write-outcome.d.ts +133 -0
- package/dist/dts/genesis/write-outcome.d.ts.map +1 -0
- package/dist/dts/genesis/write-payload.d.ts +129 -0
- package/dist/dts/genesis/write-payload.d.ts.map +1 -0
- package/dist/dts/genesis/write-plan.d.ts +109 -0
- package/dist/dts/genesis/write-plan.d.ts.map +1 -0
- package/dist/dts/genesis/write-review/write-review.d.ts +127 -0
- package/dist/dts/genesis/write-review/write-review.d.ts.map +1 -0
- package/dist/dts/genesis/write-review/write-review.styles.d.ts +2 -0
- package/dist/dts/genesis/write-review/write-review.styles.d.ts.map +1 -0
- package/dist/dts/genesis/write-review/write-review.template.d.ts +4 -0
- package/dist/dts/genesis/write-review/write-review.template.d.ts.map +1 -0
- package/dist/dts/genesis/write-tools.d.ts +99 -0
- package/dist/dts/genesis/write-tools.d.ts.map +1 -0
- package/dist/dts/react.d.ts +10 -0
- package/dist/esm/genesis/calendar.js +38 -0
- package/dist/esm/genesis/config.js +36 -1
- package/dist/esm/genesis/criteria.js +59 -55
- package/dist/esm/genesis/event-fields.js +158 -0
- package/dist/esm/genesis/filter-fields.js +111 -20
- package/dist/esm/genesis/index.js +2 -0
- package/dist/esm/genesis/register-genesis-assistant.js +76 -4
- package/dist/esm/genesis/resource-tools.js +21 -103
- package/dist/esm/genesis/review-model.js +248 -0
- package/dist/esm/genesis/row-source.js +127 -0
- package/dist/esm/genesis/serialisable.js +38 -0
- package/dist/esm/genesis/server-text.js +186 -0
- package/dist/esm/genesis/type-name.js +20 -0
- package/dist/esm/genesis/value-compare.js +87 -0
- package/dist/esm/genesis/write-commit.js +78 -0
- package/dist/esm/genesis/write-outcome.js +299 -0
- package/dist/esm/genesis/write-payload.js +632 -0
- package/dist/esm/genesis/write-plan.js +275 -0
- package/dist/esm/genesis/write-review/write-review.js +252 -0
- package/dist/esm/genesis/write-review/write-review.styles.js +214 -0
- package/dist/esm/genesis/write-review/write-review.template.js +182 -0
- package/dist/esm/genesis/write-tools.js +660 -0
- package/dist/react.cjs +7 -0
- package/dist/react.mjs +6 -0
- package/docs/genesis.md +152 -10
- package/package.json +18 -18
|
@@ -0,0 +1,660 @@
|
|
|
1
|
+
import { __awaiter } from "tslib";
|
|
2
|
+
import { getConnect } from '@genesislcap/foundation-comms';
|
|
3
|
+
import { logger } from '../utils/logger';
|
|
4
|
+
import { opFromName, toolNameOf } from './config';
|
|
5
|
+
import { fieldKindOf as criteriaKindOf } from './criteria';
|
|
6
|
+
import { loadEventFields } from './event-fields';
|
|
7
|
+
import { GENESIS_DATA_SOURCE } from './resource-tools';
|
|
8
|
+
import { buildReviewModel, selectedRows } from './review-model';
|
|
9
|
+
import { createRequestRowSource } from './row-source';
|
|
10
|
+
import { genesisTypeName } from './type-name';
|
|
11
|
+
import { commitRows } from './write-commit';
|
|
12
|
+
import { isCarryOnly, isWholeNumberType, PLATFORM_MAINTAINED, sendableFields, } from './write-payload';
|
|
13
|
+
import { MAX_WRITE_ROWS, planWrite, stillCurrent, } from './write-plan';
|
|
14
|
+
import { GENESIS_WRITE_REVIEW } from './write-review/write-review';
|
|
15
|
+
/**
|
|
16
|
+
* How long a review may stay open. Only one interaction can be in flight at a time, so a review
|
|
17
|
+
* that never resolves would wedge the assistant for the session; the widget closes read-only and
|
|
18
|
+
* the handler reports that nothing was written.
|
|
19
|
+
*/
|
|
20
|
+
const REVIEW_TIMEOUT_MS = 600000;
|
|
21
|
+
/** The `REASON` the event carries. Composed here, never by the model: it is an audit record. */
|
|
22
|
+
const APPROVAL_REASON = 'Approved by the user in the assistant write review';
|
|
23
|
+
const DATE_LIKE = /^(DATE|DATETIME|LOCALDATE|LOCALDATETIME|TIMESTAMP)$/;
|
|
24
|
+
/**
|
|
25
|
+
* Fields a model may SET: what the op can send, minus the key it is not allowed to choose, and
|
|
26
|
+
* minus a type whose value is only ever carried from the row (see `isCarryOnly`). Offering one
|
|
27
|
+
* would be the schema inviting a value the handler then refuses.
|
|
28
|
+
*/
|
|
29
|
+
const writableFields = (fields, op) => sendableFields(fields, op).filter((field) => !field.readOnly && !isCarryOnly(field));
|
|
30
|
+
/**
|
|
31
|
+
* What an INSERT requires but a model may not set, so no insert of it can ever be built. The
|
|
32
|
+
* event gets no tool: one that refused every call would cost a turn each time and teach the
|
|
33
|
+
* model nothing, and the tool list should be a true map of what the assistant can do.
|
|
34
|
+
*/
|
|
35
|
+
const requiredCarryOnly = (fields) => sendableFields(fields, 'insert')
|
|
36
|
+
.filter((field) => !field.optional && !field.readOnly && isCarryOnly(field))
|
|
37
|
+
.map((field) => field.name);
|
|
38
|
+
/**
|
|
39
|
+
* One field as a tool parameter.
|
|
40
|
+
*
|
|
41
|
+
* @remarks
|
|
42
|
+
* A date is declared as TEXT even though it travels as epoch millis, because the model should
|
|
43
|
+
* write `2026-09-21` and the bridge should be the thing that knows the wire format. A
|
|
44
|
+
* BIGDECIMAL is text for the opposite reason: it must not be rounded on the way, and a JSON
|
|
45
|
+
* number is exactly how that happens.
|
|
46
|
+
*/
|
|
47
|
+
function propertyFor(field) {
|
|
48
|
+
var _a;
|
|
49
|
+
const type = genesisTypeName(field.type);
|
|
50
|
+
if ((_a = field.validValues) === null || _a === void 0 ? void 0 : _a.length) {
|
|
51
|
+
return { type: 'string', enum: [...field.validValues] };
|
|
52
|
+
}
|
|
53
|
+
if (DATE_LIKE.test(type)) {
|
|
54
|
+
return {
|
|
55
|
+
type: 'string',
|
|
56
|
+
description: type === 'DATE' || type === 'LOCALDATE'
|
|
57
|
+
? 'A date, as YYYY-MM-DD.'
|
|
58
|
+
: 'A date and time, as YYYY-MM-DD or YYYY-MM-DDTHH:MM.',
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
// A whole number by its GENESIS type, as the payload builder checks it: a LONG declared as a
|
|
62
|
+
// JSON `number` was offered as any number, fractions included, and then refused by the
|
|
63
|
+
// handler — the schema promising more than the handler takes. Declared as text, it is text,
|
|
64
|
+
// so a value past 2^53 can travel whole.
|
|
65
|
+
if (isWholeNumberType(field.type)) {
|
|
66
|
+
return field.jsonType === 'string'
|
|
67
|
+
? { type: 'string', description: 'A whole number written as text, so nothing is rounded.' }
|
|
68
|
+
: { type: 'integer' };
|
|
69
|
+
}
|
|
70
|
+
switch (field.jsonType) {
|
|
71
|
+
case 'integer':
|
|
72
|
+
return { type: 'integer' };
|
|
73
|
+
case 'number':
|
|
74
|
+
return { type: 'number' };
|
|
75
|
+
case 'boolean':
|
|
76
|
+
return { type: 'boolean' };
|
|
77
|
+
default:
|
|
78
|
+
return type === 'BIGDECIMAL' || type === 'DECIMAL'
|
|
79
|
+
? { type: 'string', description: 'A number written as text, so nothing is rounded.' }
|
|
80
|
+
: { type: 'string' };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const objectOf = (fields, required) => (Object.assign(Object.assign({ type: 'object', properties: Object.fromEntries(fields.map((field) => [field.name, propertyFor(field)])) }, (required.length ? { required: [...required] } : {})), { additionalProperties: false }));
|
|
84
|
+
/** The row shape each op takes: values for an insert, a key (and changes) for the rest. */
|
|
85
|
+
/**
|
|
86
|
+
* The event fields a row can be found by: the ones the row source can match by EQUALITY.
|
|
87
|
+
*
|
|
88
|
+
* @remarks
|
|
89
|
+
* Judged by the ROW SOURCE's filter fields and the type it gives them, because that is what the
|
|
90
|
+
* read composes its criteria against — not by the type the event declares. The event's own
|
|
91
|
+
* fields offered keys the read then refused: one outside a published `CRITERIA_FIELDS`, one the
|
|
92
|
+
* source leaves untyped, an ENUM whose values it cannot read. Equality also rules out a
|
|
93
|
+
* timestamp — criteria.ts refuses it deliberately, the platform's own datetime operators having
|
|
94
|
+
* none — and a type this bridge does not know at all. Each was the schema promising a key the
|
|
95
|
+
* read would refuse, the direction of schema/handler disagreement that costs the model a turn
|
|
96
|
+
* and puts a review in front of the user with every row red.
|
|
97
|
+
*/
|
|
98
|
+
const keyFieldsOf = (fields, keyable) => fields
|
|
99
|
+
.filter((field) => !PLATFORM_MAINTAINED.has(field.name))
|
|
100
|
+
.filter((field) => {
|
|
101
|
+
const matched = keyable.get(field.name);
|
|
102
|
+
const kind = matched && criteriaKindOf(matched.type);
|
|
103
|
+
return kind !== undefined && kind !== 'datetime';
|
|
104
|
+
})
|
|
105
|
+
.map((field) => field.name);
|
|
106
|
+
/**
|
|
107
|
+
* @param keyable - The row source's filter fields. Empty unless given, so a caller that forgets
|
|
108
|
+
* it offers no key at all rather than falling back to the event's own fields.
|
|
109
|
+
*/
|
|
110
|
+
function rowSchema(fields, op, keyable = new Map()) {
|
|
111
|
+
const writable = writableFields(fields, op);
|
|
112
|
+
if (op === 'insert' || op === 'custom') {
|
|
113
|
+
return objectOf(writable, writable.filter((field) => !field.optional).map((field) => field.name));
|
|
114
|
+
}
|
|
115
|
+
const key = {
|
|
116
|
+
type: 'object',
|
|
117
|
+
description: 'Which row to act on: the values that identify exactly one row, such as its id.',
|
|
118
|
+
properties: Object.fromEntries(keyFieldsOf(fields, keyable).map((name) => [name, { type: 'string' }])),
|
|
119
|
+
additionalProperties: false,
|
|
120
|
+
};
|
|
121
|
+
return op === 'delete'
|
|
122
|
+
? { type: 'object', properties: { key }, required: ['key'], additionalProperties: false }
|
|
123
|
+
: {
|
|
124
|
+
type: 'object',
|
|
125
|
+
properties: {
|
|
126
|
+
key,
|
|
127
|
+
changes: Object.assign(Object.assign({}, objectOf(writable, [])), { description: 'Only the fields to change. Everything else keeps the value it has now. An empty ' +
|
|
128
|
+
'string or null also leaves a field as it is: this tool cannot clear a column.' }),
|
|
129
|
+
},
|
|
130
|
+
required: ['key', 'changes'],
|
|
131
|
+
additionalProperties: false,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* `custom` has no entry because a custom event never reaches a definition — see {@link
|
|
136
|
+
* decideOp}. A vague verb here ("Runs") was the only thing standing between the model and a
|
|
137
|
+
* path with none of this module's guarantees.
|
|
138
|
+
*/
|
|
139
|
+
const WHAT_IT_DOES = {
|
|
140
|
+
insert: 'Adds rows to',
|
|
141
|
+
modify: 'Changes rows in',
|
|
142
|
+
delete: 'Removes rows from',
|
|
143
|
+
};
|
|
144
|
+
function writeDefinition(resource, op, fields, keyable) {
|
|
145
|
+
return {
|
|
146
|
+
name: toolNameOf(resource.name),
|
|
147
|
+
description: `${resource.context}\n\n` +
|
|
148
|
+
`${WHAT_IT_DOES[op]} ${resource.name}. Nothing is written until the user has read the ` +
|
|
149
|
+
'rows in a review and approved them, one by one — so propose the whole change and let ' +
|
|
150
|
+
'them decide, rather than asking in chat first. The result says what happened to each ' +
|
|
151
|
+
'row; read it rather than assuming the write succeeded.',
|
|
152
|
+
parameters: {
|
|
153
|
+
type: 'object',
|
|
154
|
+
properties: {
|
|
155
|
+
rows: {
|
|
156
|
+
type: 'array',
|
|
157
|
+
// Declared because the handler enforces them: `planWrite` refuses an empty list and
|
|
158
|
+
// anything over the batch cap, so a schema silent about both let the model find out
|
|
159
|
+
// by being refused.
|
|
160
|
+
minItems: 1,
|
|
161
|
+
maxItems: MAX_WRITE_ROWS,
|
|
162
|
+
items: rowSchema(fields, op, keyable),
|
|
163
|
+
},
|
|
164
|
+
},
|
|
165
|
+
required: ['rows'],
|
|
166
|
+
additionalProperties: false,
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
const decideOp = (resource) => {
|
|
171
|
+
const named = opFromName(resource.name);
|
|
172
|
+
const declared = resource.op;
|
|
173
|
+
if (declared && named && declared !== named) {
|
|
174
|
+
return {
|
|
175
|
+
refused: `it is declared as '${declared}' and its name says '${named}'. A write built on the ` +
|
|
176
|
+
'wrong one replaces the record with every unnamed column empty',
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
// Either order would do: the check above has already refused the case where both exist and
|
|
180
|
+
// disagree, so at this point they agree or only one of them is set. A mutation swapping them
|
|
181
|
+
// stays green for that reason, and a test asserting the order would be asserting nothing.
|
|
182
|
+
const op = declared !== null && declared !== void 0 ? declared : named;
|
|
183
|
+
if (!op) {
|
|
184
|
+
return {
|
|
185
|
+
refused: 'it declares no op and its name does not end in _INSERT, _MODIFY or _DELETE, so there ' +
|
|
186
|
+
'is no way to know what a write through it would do',
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
if (op === 'custom') {
|
|
190
|
+
return {
|
|
191
|
+
refused: 'a custom event gets no write tool yet: every rule this path follows was learned from ' +
|
|
192
|
+
"generated CRUD handlers, and a custom handler is the app's own. If it replaces the " +
|
|
193
|
+
'record, a write would blank the fields nobody named and the review could not show it',
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
return { op };
|
|
197
|
+
};
|
|
198
|
+
/** `EVENT_TRADE_MODIFY` reads its rows from `REQ_TRADE`, when the app exposes one. */
|
|
199
|
+
const readResourceFor = (eventName) => {
|
|
200
|
+
const match = /^EVENT_(.+)_(?:INSERT|MODIFY|DELETE)$/.exec(eventName);
|
|
201
|
+
return match ? `REQ_${match[1]}` : undefined;
|
|
202
|
+
};
|
|
203
|
+
/**
|
|
204
|
+
* Builds the assistant's write tools from an app's event resources.
|
|
205
|
+
*
|
|
206
|
+
* @beta
|
|
207
|
+
*/
|
|
208
|
+
export function createGenesisWriteTools(resources, options = {}) {
|
|
209
|
+
const events = resources
|
|
210
|
+
.filter((r) => r.kind === 'event')
|
|
211
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
212
|
+
const requestNames = new Set(resources.filter((r) => r.kind === 'request').map((r) => r.name));
|
|
213
|
+
const resolveConnect = () => {
|
|
214
|
+
var _a;
|
|
215
|
+
try {
|
|
216
|
+
return (_a = options.connect) !== null && _a !== void 0 ? _a : getConnect();
|
|
217
|
+
}
|
|
218
|
+
catch (_b) {
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
const sources = new Map();
|
|
223
|
+
/**
|
|
224
|
+
* The resource a modify or delete reads through, or nothing — in which case the event gets no
|
|
225
|
+
* tool. A modify with no row to read cannot be built: under replace semantics the fields
|
|
226
|
+
* nobody named would be written as null.
|
|
227
|
+
*/
|
|
228
|
+
const sourceFor = (resource, op, connect) => {
|
|
229
|
+
var _a;
|
|
230
|
+
// The DECIDED op, not `resource.op`: a resource whose op comes from its name would
|
|
231
|
+
// otherwise be told it needs a row source and handed none.
|
|
232
|
+
if (op !== 'modify' && op !== 'delete')
|
|
233
|
+
return undefined;
|
|
234
|
+
const configured = (_a = options.rowSources) === null || _a === void 0 ? void 0 : _a[resource.name];
|
|
235
|
+
const derived = readResourceFor(resource.name);
|
|
236
|
+
// Gated for the OVERRIDE as well as the derived name. A modify reads through a resource the
|
|
237
|
+
// assistant can already read — that is the rule the docs state, and it is what keeps the
|
|
238
|
+
// write path from becoming a read side-channel for columns no read tool may return. An
|
|
239
|
+
// unchecked override would let a config typo widen that silently, and the pre-image it
|
|
240
|
+
// fetched would land in the driver's persisted history.
|
|
241
|
+
const name = configured !== null && configured !== void 0 ? configured : derived;
|
|
242
|
+
if (!name || !requestNames.has(name))
|
|
243
|
+
return undefined;
|
|
244
|
+
let source = sources.get(resource.name);
|
|
245
|
+
if (!source) {
|
|
246
|
+
source = createRequestRowSource({ connect, resource: name, timeouts: options.timeouts });
|
|
247
|
+
sources.set(resource.name, source);
|
|
248
|
+
}
|
|
249
|
+
return source;
|
|
250
|
+
};
|
|
251
|
+
/**
|
|
252
|
+
* Whether a row read through `source` can carry a whole payload for this event.
|
|
253
|
+
*
|
|
254
|
+
* @remarks
|
|
255
|
+
* A generated modify REPLACES the record, so a column the read resource does not return is a
|
|
256
|
+
* column written null — the blanking the pre-image merge exists to prevent, one level up,
|
|
257
|
+
* with the merge correct and its INPUT unchecked. It cannot be caught row by row: a field the
|
|
258
|
+
* pre-image omits and one the row genuinely holds as null look exactly the same.
|
|
259
|
+
*
|
|
260
|
+
* `undefined` means the resource's metadata could not be read, which is a reason to ask again
|
|
261
|
+
* rather than to settle.
|
|
262
|
+
*/
|
|
263
|
+
const coverage = (op, fields, source) => __awaiter(this, void 0, void 0, function* () {
|
|
264
|
+
const described = yield source.describes();
|
|
265
|
+
if (!described)
|
|
266
|
+
return undefined;
|
|
267
|
+
return {
|
|
268
|
+
missing: sendableFields(fields, op)
|
|
269
|
+
.map((field) => field.name)
|
|
270
|
+
.filter((name) => !described.has(name)),
|
|
271
|
+
};
|
|
272
|
+
});
|
|
273
|
+
const settled = new Map();
|
|
274
|
+
/** Events that will never get a tool, so the next turn does not ask about them again. */
|
|
275
|
+
const skipped = new Set();
|
|
276
|
+
const eventFields = new Map();
|
|
277
|
+
let inFlight;
|
|
278
|
+
const loadFields = (resource, connect) => __awaiter(this, void 0, void 0, function* () {
|
|
279
|
+
var _a;
|
|
280
|
+
const known = eventFields.get(resource.name);
|
|
281
|
+
if (known)
|
|
282
|
+
return known;
|
|
283
|
+
const loaded = yield loadEventFields(connect, resource.name, (_a = options.timeouts) === null || _a === void 0 ? void 0 : _a.metadataMs);
|
|
284
|
+
if (loaded.status !== 'ok') {
|
|
285
|
+
// Settled for the session when asking again cannot change the answer: Connect has cached
|
|
286
|
+
// the reply (any reply with a key, an ERROR one included) and would return it again
|
|
287
|
+
// without reaching the server, so a retry only repeats the refusal in the log. A request
|
|
288
|
+
// that failed, or a reply with no keys, is asked again — a resource still priming at
|
|
289
|
+
// start-up can answer properly next time, and settling it would lose the tool for the
|
|
290
|
+
// whole session.
|
|
291
|
+
if (loaded.settled)
|
|
292
|
+
skipped.add(resource.name);
|
|
293
|
+
logger.warn(`Genesis assistant: ${resource.name} has no write tool: ${loaded.reason}.`);
|
|
294
|
+
return undefined;
|
|
295
|
+
}
|
|
296
|
+
eventFields.set(resource.name, loaded.fields);
|
|
297
|
+
return loaded.fields;
|
|
298
|
+
});
|
|
299
|
+
const toolDefinitions = () => {
|
|
300
|
+
inFlight !== null && inFlight !== void 0 ? inFlight : (inFlight = (() => __awaiter(this, void 0, void 0, function* () {
|
|
301
|
+
const connect = resolveConnect();
|
|
302
|
+
if (!connect)
|
|
303
|
+
return [...settled.values()];
|
|
304
|
+
yield Promise.all(events
|
|
305
|
+
.filter((resource) => !settled.has(resource.name) && !skipped.has(resource.name))
|
|
306
|
+
.map((resource) => __awaiter(this, void 0, void 0, function* () {
|
|
307
|
+
var _a;
|
|
308
|
+
// What op this is has to be settled before anything else is decided by it. The
|
|
309
|
+
// config validator checks it too, but only the registration path reaches that.
|
|
310
|
+
const decided = decideOp(resource);
|
|
311
|
+
if (decided.refused) {
|
|
312
|
+
skipped.add(resource.name);
|
|
313
|
+
logger.warn(`Genesis assistant: ${resource.name} has no write tool because ${decided.refused}.`);
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
const source = sourceFor(resource, decided.op, connect);
|
|
317
|
+
const needsRow = decided.op === 'modify' || decided.op === 'delete';
|
|
318
|
+
if (needsRow && !source) {
|
|
319
|
+
// Settled for good: the app exposes no resource to read this event's rows
|
|
320
|
+
// through, which is a property of the config rather than of this moment, so
|
|
321
|
+
// asking again on the next turn would give the same answer.
|
|
322
|
+
skipped.add(resource.name);
|
|
323
|
+
const named = (_a = options.rowSources) === null || _a === void 0 ? void 0 : _a[resource.name];
|
|
324
|
+
logger.warn(`Genesis assistant: ${resource.name} has no write tool because ` +
|
|
325
|
+
(named
|
|
326
|
+
? `rowSources names ${named}, which is not a request resource in this app's ` +
|
|
327
|
+
'AI config. A write reads its rows through a resource the assistant can ' +
|
|
328
|
+
'already read.'
|
|
329
|
+
: 'the app exposes no request resource to read its rows from. Add ' +
|
|
330
|
+
`${readResourceFor(resource.name)} to the AI config, or name one in ` +
|
|
331
|
+
'rowSources.'));
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
const fields = yield loadFields(resource, connect);
|
|
335
|
+
if (!fields)
|
|
336
|
+
return;
|
|
337
|
+
// An insert or a modify with nothing a model may SET could never be built: every
|
|
338
|
+
// call would be refused. Its fields are all key, platform-maintained, or carry-only.
|
|
339
|
+
// No tool, and the console says why. A delete is exempt by design: it sets nothing,
|
|
340
|
+
// it sends the row's key.
|
|
341
|
+
if ((decided.op === 'insert' || decided.op === 'modify') &&
|
|
342
|
+
!writableFields(fields, decided.op).length) {
|
|
343
|
+
skipped.add(resource.name);
|
|
344
|
+
logger.warn(`Genesis assistant: ${resource.name} has no write tool because it has no field ` +
|
|
345
|
+
'a model may set: each one is its key, maintained by the platform, or a ' +
|
|
346
|
+
'NANO_TIMESTAMP this assistant does not set.');
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
const unsettable = decided.op === 'insert' ? requiredCarryOnly(fields) : [];
|
|
350
|
+
if (unsettable.length) {
|
|
351
|
+
skipped.add(resource.name);
|
|
352
|
+
logger.warn(`Genesis assistant: ${resource.name} has no write tool because it requires ` +
|
|
353
|
+
`${unsettable.join(', ')}, which this assistant does not set: the unit of a ` +
|
|
354
|
+
'NANO_TIMESTAMP has not been confirmed.');
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
// Only a MODIFY needs full coverage: it replaces the record, so a column the read
|
|
358
|
+
// cannot see is a column written null. A delete sends its key and nothing else, so
|
|
359
|
+
// demanding the rest would refuse a tool over fields it never puts on the wire.
|
|
360
|
+
if (source && decided.op === 'modify') {
|
|
361
|
+
const covered = yield coverage(decided.op, fields, source);
|
|
362
|
+
if (!covered)
|
|
363
|
+
return;
|
|
364
|
+
if (covered.missing.length) {
|
|
365
|
+
skipped.add(resource.name);
|
|
366
|
+
logger.warn(`Genesis assistant: ${resource.name} has no write tool because ` +
|
|
367
|
+
`${source.resource} does not return ${covered.missing.join(', ')}. A ` +
|
|
368
|
+
'generated modify replaces the record, so a column it cannot read would be ' +
|
|
369
|
+
'written null. Point rowSources at a resource that returns every field.');
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
// A modify AND a delete find their row by a key, so both are offered only the fields
|
|
374
|
+
// the row source can match on — not only the modify, whose coverage block above this
|
|
375
|
+
// would have been the easy place to put it. Metadata that cannot be read is asked
|
|
376
|
+
// again next turn: falling back to the event's own fields is the defect this fixes.
|
|
377
|
+
let keyable;
|
|
378
|
+
if (source && needsRow) {
|
|
379
|
+
keyable = yield source.filterableBy();
|
|
380
|
+
if (!keyable)
|
|
381
|
+
return;
|
|
382
|
+
if (!keyFieldsOf(fields, keyable).length) {
|
|
383
|
+
skipped.add(resource.name);
|
|
384
|
+
logger.warn(`Genesis assistant: ${resource.name} has no write tool because ` +
|
|
385
|
+
`${source.resource} can be searched by none of the fields it declares, so no ` +
|
|
386
|
+
'row could be found to act on.');
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
settled.set(resource.name, writeDefinition(resource, decided.op, fields, keyable));
|
|
391
|
+
})));
|
|
392
|
+
return events
|
|
393
|
+
.map((resource) => settled.get(resource.name))
|
|
394
|
+
.filter((definition) => !!definition);
|
|
395
|
+
}))().finally(() => {
|
|
396
|
+
inFlight = undefined;
|
|
397
|
+
}));
|
|
398
|
+
return inFlight;
|
|
399
|
+
};
|
|
400
|
+
const toolHandlers = {};
|
|
401
|
+
for (const resource of events) {
|
|
402
|
+
toolHandlers[toolNameOf(resource.name)] = (args, context) => __awaiter(this, void 0, void 0, function* () {
|
|
403
|
+
return runWrite(resource, args, context, {
|
|
404
|
+
connect: resolveConnect(),
|
|
405
|
+
sourceFor,
|
|
406
|
+
loadFields,
|
|
407
|
+
coverage,
|
|
408
|
+
timeouts: options.timeouts,
|
|
409
|
+
});
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
return { toolDefinitions, toolHandlers };
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* The line for a row that was sent, with anything the plan must also say about it — a blank the
|
|
416
|
+
* model sent that was kept as the row's value, so the model cannot report a clear that did not
|
|
417
|
+
* happen.
|
|
418
|
+
*/
|
|
419
|
+
function committedLine(outcome, notes = []) {
|
|
420
|
+
var _a, _b;
|
|
421
|
+
return Object.assign(Object.assign(Object.assign({ index: outcome.index, status: outcome.status, committed: outcome.committed, message: [outcome.message, ...notes].join(' ') }, (outcome.generated ? { generated: outcome.generated } : {})), (((_a = outcome.fields) === null || _a === void 0 ? void 0 : _a.length) ? { fields: outcome.fields } : {})), (((_b = outcome.warnings) === null || _b === void 0 ? void 0 : _b.length) ? { warnings: outcome.warnings } : {}));
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* What a row that did not survive its re-read is reported as.
|
|
425
|
+
*
|
|
426
|
+
* @remarks
|
|
427
|
+
* Three different facts, three different statuses. "We could not check" is not "it changed":
|
|
428
|
+
* nothing was sent in either case, but only one of them is somebody else's edit, and a model
|
|
429
|
+
* told the wrong one of the two would draw the wrong conclusion about what to do next.
|
|
430
|
+
*/
|
|
431
|
+
function notCurrent(index, outcome) {
|
|
432
|
+
if (outcome.status === 'gone') {
|
|
433
|
+
return {
|
|
434
|
+
index,
|
|
435
|
+
status: 'gone',
|
|
436
|
+
committed: false,
|
|
437
|
+
message: 'That row no longer exists, so nothing was written for it.',
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
if (outcome.status === 'changed') {
|
|
441
|
+
return {
|
|
442
|
+
index,
|
|
443
|
+
status: 'changed_since_review',
|
|
444
|
+
committed: false,
|
|
445
|
+
message: `Changed since the review (${outcome.fields.join(', ')}), so nothing was written for ` +
|
|
446
|
+
'it. Read it again before proposing the change a second time.',
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
return {
|
|
450
|
+
index,
|
|
451
|
+
status: 'failed',
|
|
452
|
+
committed: false,
|
|
453
|
+
message: `It could not be checked before writing (${outcome.reason}), so nothing was written for it.`,
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
const summarise = (rows) => {
|
|
457
|
+
var _a;
|
|
458
|
+
const counts = new Map();
|
|
459
|
+
for (const row of rows)
|
|
460
|
+
counts.set(row.status, ((_a = counts.get(row.status)) !== null && _a !== void 0 ? _a : 0) + 1);
|
|
461
|
+
// Counted by STATUS and never as "written / not written": `unknown` is neither, and folding it
|
|
462
|
+
// into a not-written count is how a row gets written twice.
|
|
463
|
+
return [...counts.entries()].map(([status, count]) => `${count} ${status}`).join(', ');
|
|
464
|
+
};
|
|
465
|
+
function runWrite(resource, args, context, deps) {
|
|
466
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
467
|
+
var _a, _b, _c, _d, _e;
|
|
468
|
+
const fail = (error, message) => ({
|
|
469
|
+
source: GENESIS_DATA_SOURCE,
|
|
470
|
+
untrusted: true,
|
|
471
|
+
resource: resource.name,
|
|
472
|
+
error,
|
|
473
|
+
message,
|
|
474
|
+
});
|
|
475
|
+
// Settled here as well as when the tool was defined: this factory is exported, so a host can
|
|
476
|
+
// hold the handlers without ever calling toolDefinitions().
|
|
477
|
+
const decided = decideOp(resource);
|
|
478
|
+
if (decided.refused) {
|
|
479
|
+
return fail('rejected', `${resource.name} has no write tool because ${decided.refused}.`);
|
|
480
|
+
}
|
|
481
|
+
const op = decided.op;
|
|
482
|
+
const { connect } = deps;
|
|
483
|
+
if (!(connect === null || connect === void 0 ? void 0 : connect.isConnected)) {
|
|
484
|
+
return fail('not_connected', 'The app is not connected to its server, so nothing was written.');
|
|
485
|
+
}
|
|
486
|
+
const fields = yield deps.loadFields(resource, connect);
|
|
487
|
+
if (!fields) {
|
|
488
|
+
return fail('request_failed', `${resource.name} could not be described, so nothing was sent.`);
|
|
489
|
+
}
|
|
490
|
+
const source = deps.sourceFor(resource, op, connect);
|
|
491
|
+
if ((op === 'modify' || op === 'delete') && !source) {
|
|
492
|
+
return fail('rejected', `${resource.name} has no resource to read its rows from.`);
|
|
493
|
+
}
|
|
494
|
+
if (source && op === 'modify') {
|
|
495
|
+
// Checked here as well as when the tool was defined, because this factory is exported: a
|
|
496
|
+
// host can hold the handlers without ever calling toolDefinitions(), and the guarantee must
|
|
497
|
+
// not depend on which of the two ran first.
|
|
498
|
+
const covered = yield deps.coverage(op, fields, source);
|
|
499
|
+
if (!covered) {
|
|
500
|
+
return fail('request_failed', `${source.resource} could not be described, so nothing was sent.`);
|
|
501
|
+
}
|
|
502
|
+
if (covered.missing.length) {
|
|
503
|
+
return fail('rejected', `${resource.name} cannot be written through ${source.resource}, which does not return ` +
|
|
504
|
+
`${covered.missing.join(', ')}. Writing without those would set them empty.`);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
const plan = yield planWrite(args.rows, { op, fields, source });
|
|
508
|
+
if (plan.status === 'rejected')
|
|
509
|
+
return fail('rejected', plan.reason);
|
|
510
|
+
// Every column the review will RENDER needs a type, and for a delete that is more than the
|
|
511
|
+
// event declares: it shows the whole row, including columns the event never mentions, and
|
|
512
|
+
// without a type a date is shown to the approver as raw epoch millis — `1789948800000` is not
|
|
513
|
+
// a review. The row source described those columns, so it has the answer.
|
|
514
|
+
const shownFields = [...sendableFields(fields, op)];
|
|
515
|
+
if (op === 'delete' && source) {
|
|
516
|
+
const described = yield source.describes();
|
|
517
|
+
for (const [name, type] of described !== null && described !== void 0 ? described : []) {
|
|
518
|
+
// The platform's own columns stay out, as review-model already keeps them out of the
|
|
519
|
+
// columns a row brings: a delete showing RECORD_ID and TIMESTAMP would be the same table
|
|
520
|
+
// telling the user two different stories about what a column means. This loop is how they
|
|
521
|
+
// came back in — the row source describes every column it returns, theirs included.
|
|
522
|
+
if (PLATFORM_MAINTAINED.has(name))
|
|
523
|
+
continue;
|
|
524
|
+
if (!shownFields.some((field) => field.name === name)) {
|
|
525
|
+
shownFields.push({ name, type, jsonType: 'string', optional: true, readOnly: true });
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
const model = buildReviewModel({
|
|
530
|
+
resource: resource.name,
|
|
531
|
+
op,
|
|
532
|
+
// The columns are the fields this op can SEND — the platform's own never travel, so a column
|
|
533
|
+
// for them would show a user a blank for something no write touches — plus, for a delete,
|
|
534
|
+
// the ones it merely shows.
|
|
535
|
+
fields: shownFields,
|
|
536
|
+
rows: plan.rows.map((row) => {
|
|
537
|
+
var _a;
|
|
538
|
+
return (Object.assign(Object.assign({ index: row.index, details: (_a = row.details) !== null && _a !== void 0 ? _a : {} }, (op === 'delete' && row.preImage ? { display: row.preImage } : {})), { preImage: op === 'delete' ? undefined : row.preImage, problems: row.problems }));
|
|
539
|
+
}),
|
|
540
|
+
});
|
|
541
|
+
// What the staleness check compares: every column the review RENDERED, because what the user
|
|
542
|
+
// saw is evidence for what was checked only if the two are the same set. For a modify that is
|
|
543
|
+
// the event's own fields, which are also everything the write can change. A delete SENDS its
|
|
544
|
+
// key alone but SHOWS the whole row, and a check over the key let a row somebody changed while
|
|
545
|
+
// the review was open be removed as approved: the user saw QUANTITY 7, approved removing that
|
|
546
|
+
// row, and the row removed held 900 — reported `written`. Columns the metadata did not type
|
|
547
|
+
// are compared untyped; the platform's own are left out by stillCurrent, as TIMESTAMP moves
|
|
548
|
+
// on every unrelated write.
|
|
549
|
+
const checkedFields = op === 'delete'
|
|
550
|
+
? model.columns.map(({ field }) => {
|
|
551
|
+
var _a;
|
|
552
|
+
return (_a = shownFields.find((shown) => shown.name === field)) !== null && _a !== void 0 ? _a : {
|
|
553
|
+
name: field,
|
|
554
|
+
type: '',
|
|
555
|
+
jsonType: 'string',
|
|
556
|
+
optional: true,
|
|
557
|
+
readOnly: true,
|
|
558
|
+
};
|
|
559
|
+
})
|
|
560
|
+
: fields;
|
|
561
|
+
const byIndex = new Map(plan.rows.map((row) => [row.index, row]));
|
|
562
|
+
const refused = (row) => {
|
|
563
|
+
var _a;
|
|
564
|
+
return ({
|
|
565
|
+
index: row.index,
|
|
566
|
+
status: 'invalid_payload',
|
|
567
|
+
committed: false,
|
|
568
|
+
message: `Not written: ${(_a = row.problems) === null || _a === void 0 ? void 0 : _a.join('; ')}`,
|
|
569
|
+
});
|
|
570
|
+
};
|
|
571
|
+
let review;
|
|
572
|
+
try {
|
|
573
|
+
review = yield context.requestInteraction(GENESIS_WRITE_REVIEW, model, { timeoutMs: (_b = (_a = deps.timeouts) === null || _a === void 0 ? void 0 : _a.reviewMs) !== null && _b !== void 0 ? _b : REVIEW_TIMEOUT_MS });
|
|
574
|
+
}
|
|
575
|
+
catch (error) {
|
|
576
|
+
// requestInteraction throws when another interaction is already open. A throw out of a tool
|
|
577
|
+
// handler invites the model to retry, which for a write means doing it twice.
|
|
578
|
+
logger.error(`Genesis assistant: ${resource.name} could not show its review: ${String(error)}`);
|
|
579
|
+
return fail('request_failed', 'The review could not be shown, so nothing was written.');
|
|
580
|
+
}
|
|
581
|
+
if ((review === null || review === void 0 ? void 0 : review.status) !== 'approved') {
|
|
582
|
+
const why = (review === null || review === void 0 ? void 0 : review.status) === 'timeout'
|
|
583
|
+
? 'The review closed before it was answered'
|
|
584
|
+
: `The user did not approve it${(review === null || review === void 0 ? void 0 : review.message) ? `: ${review.message}` : ''}`;
|
|
585
|
+
return result(resource.name, false, plan.rows.map((row) => {
|
|
586
|
+
var _a, _b;
|
|
587
|
+
return ({
|
|
588
|
+
index: row.index,
|
|
589
|
+
status: ((_a = row.problems) === null || _a === void 0 ? void 0 : _a.length) ? 'invalid_payload' : 'not_selected',
|
|
590
|
+
committed: false,
|
|
591
|
+
message: ((_b = row.problems) === null || _b === void 0 ? void 0 : _b.length) ? `Not written: ${row.problems.join('; ')}` : why,
|
|
592
|
+
});
|
|
593
|
+
}), `${why}. Nothing was written.`);
|
|
594
|
+
}
|
|
595
|
+
// Indexes, never rows: what the review hands back cannot be a payload, so `selectedRows`
|
|
596
|
+
// reads the objects the table rendered out of the model itself — and re-applies the rule that
|
|
597
|
+
// a refused row is never committed, whatever came back.
|
|
598
|
+
const chosen = new Set((_c = review.payload) !== null && _c !== void 0 ? _c : []);
|
|
599
|
+
const approved = selectedRows(model, chosen);
|
|
600
|
+
const lines = new Map();
|
|
601
|
+
for (const row of plan.rows) {
|
|
602
|
+
if ((_d = row.problems) === null || _d === void 0 ? void 0 : _d.length)
|
|
603
|
+
lines.set(row.index, refused(row));
|
|
604
|
+
else if (!chosen.has(row.index)) {
|
|
605
|
+
lines.set(row.index, {
|
|
606
|
+
index: row.index,
|
|
607
|
+
status: 'not_selected',
|
|
608
|
+
committed: false,
|
|
609
|
+
message: 'The user did not select this row, so nothing was written for it.',
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
// Re-checked and committed ONE ROW AT A TIME, in order.
|
|
614
|
+
//
|
|
615
|
+
// Checking every row up front and then committing them widened the window with each row's
|
|
616
|
+
// position — row 25 would be written against a check taken before rows 1 to 24 had even been
|
|
617
|
+
// sent. Interleaving keeps each row's window to a single round trip, which is as close to
|
|
618
|
+
// compare-and-set as a platform that offers neither allows.
|
|
619
|
+
for (const row of approved) {
|
|
620
|
+
const planned = byIndex.get(row.index);
|
|
621
|
+
if (op === 'modify' || op === 'delete') {
|
|
622
|
+
// A check run early is a check of a row that may since have moved: it has to run against
|
|
623
|
+
// the row as it is at the moment of writing, which is the whole point of interleaving.
|
|
624
|
+
// oxlint-disable-next-line no-await-in-loop -- each row is checked as it is written
|
|
625
|
+
const outcome = yield stillCurrent(planned, { source, fields: checkedFields });
|
|
626
|
+
if (outcome.status !== 'current') {
|
|
627
|
+
lines.set(row.index, notCurrent(row.index, outcome));
|
|
628
|
+
continue;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
// oxlint-disable-next-line no-await-in-loop -- writes must not race each other
|
|
632
|
+
const [outcome] = yield commitRows([row], {
|
|
633
|
+
connect,
|
|
634
|
+
eventName: resource.name,
|
|
635
|
+
op,
|
|
636
|
+
reason: APPROVAL_REASON,
|
|
637
|
+
timeoutMs: (_e = deps.timeouts) === null || _e === void 0 ? void 0 : _e.commitMs,
|
|
638
|
+
});
|
|
639
|
+
lines.set(outcome.index, committedLine(outcome, planned === null || planned === void 0 ? void 0 : planned.notes));
|
|
640
|
+
}
|
|
641
|
+
const rows = plan.rows.map((row) => {
|
|
642
|
+
var _a;
|
|
643
|
+
return (_a = lines.get(row.index)) !== null && _a !== void 0 ? _a : {
|
|
644
|
+
index: row.index,
|
|
645
|
+
status: 'unknown',
|
|
646
|
+
committed: false,
|
|
647
|
+
message: 'No outcome was recorded for this row.',
|
|
648
|
+
};
|
|
649
|
+
});
|
|
650
|
+
return result(resource.name, true, rows, summarise(rows));
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
const result = (resource, approved, rows, summary) => ({
|
|
654
|
+
source: GENESIS_DATA_SOURCE,
|
|
655
|
+
untrusted: true,
|
|
656
|
+
resource,
|
|
657
|
+
approved,
|
|
658
|
+
rows,
|
|
659
|
+
summary,
|
|
660
|
+
});
|