@happyvertical/smrt-template-sveltekit 0.61.6 → 0.62.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/AGENTS.md +1 -1
- package/agents/cookbook-host.md +93 -85
- package/agents/cookbook-workflow-runs.md +102 -0
- package/cookbook-template/src/routes/settings/inference/+page.server.ts +1 -1
- package/dist/host/client.js +1 -1
- package/dist/host/server.d.ts +16 -46
- package/dist/host/server.js +301 -282
- package/dist/host/settings.d.ts +4 -22
- package/dist/host/settings.js +12 -9
- package/dist/host/workflow-runs.d.ts +201 -0
- package/dist/host/workflow-runs.js +612 -0
- package/dist/smrt-knowledge.okf.md +7 -2
- package/host/InferenceSettingsPage.svelte +9 -8
- package/mcp-apps-template/package.dependencies.json +2 -2
- package/package.json +46 -43
- package/template/package.json +17 -17
- package/template.config.js +17 -17
- package/agents/cookbook-design-runs.md +0 -164
- package/dist/host/design-runs.d.ts +0 -72
- package/dist/host/design-runs.js +0 -763
package/dist/host/design-runs.js
DELETED
|
@@ -1,763 +0,0 @@
|
|
|
1
|
-
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
-
import { stableStringify } from '@happyvertical/smrt-core/knowledge';
|
|
3
|
-
import { createDesignRunDriver, createDesignRunStore, installDesignRunExecutor, } from '@happyvertical/smrt-inference/server';
|
|
4
|
-
import { isRunnerExecutionContext, JobHandle, SmrtJobCollection, SmrtJobEventCollection, } from '@happyvertical/smrt-jobs';
|
|
5
|
-
import Ajv from 'ajv/dist/2020.js';
|
|
6
|
-
const outputSchema = {
|
|
7
|
-
type: 'object',
|
|
8
|
-
required: ['summary', 'checks', 'ready', 'operations'],
|
|
9
|
-
additionalProperties: false,
|
|
10
|
-
properties: {
|
|
11
|
-
summary: { type: 'string', minLength: 1 },
|
|
12
|
-
checks: { type: 'array', items: { type: 'string', minLength: 1 } },
|
|
13
|
-
ready: { type: 'boolean' },
|
|
14
|
-
operations: {
|
|
15
|
-
type: 'array',
|
|
16
|
-
items: {
|
|
17
|
-
type: 'object',
|
|
18
|
-
additionalProperties: false,
|
|
19
|
-
required: ['tool', 'args'],
|
|
20
|
-
properties: {
|
|
21
|
-
tool: { type: 'string', minLength: 1 },
|
|
22
|
-
args: { type: 'object', additionalProperties: true },
|
|
23
|
-
},
|
|
24
|
-
},
|
|
25
|
-
},
|
|
26
|
-
},
|
|
27
|
-
};
|
|
28
|
-
const definitionPrefix = 'cookbook-design/v5/';
|
|
29
|
-
const legacyDurablePrefix = 'cookbook-design/v3/';
|
|
30
|
-
const applicableDefinitions = /^cookbook-design\/v[345]\//;
|
|
31
|
-
// d3b879bef0: core app.addField inputSchema after the v2 adapter excludes
|
|
32
|
-
// approvalId. Derived with core's exported stableStringify, never a copied schema.
|
|
33
|
-
const v2AddFieldSchemaPin = '0a56ace412f0b4756eb29fb16575da602fb97316fe644ac5ea217278756be9b4';
|
|
34
|
-
const fingerprint = (value) => createHash('sha256').update(stableStringify(value)).digest('hex');
|
|
35
|
-
/** The actual checked proposal, including a v5 first-pass proposal, owns Apply. */
|
|
36
|
-
export function isCookbookDesignFinalCheck(state) {
|
|
37
|
-
if (!applicableDefinitions.test(state.definition) || state.phase !== 'check')
|
|
38
|
-
return false;
|
|
39
|
-
if (state.passIndex === Number(state.definition.split('/').at(-1)) - 1)
|
|
40
|
-
return true;
|
|
41
|
-
const input = state.input;
|
|
42
|
-
if (!state.definition.startsWith(definitionPrefix) ||
|
|
43
|
-
state.passIndex !== 0 ||
|
|
44
|
-
input.fixedPasses === true ||
|
|
45
|
-
input.expanded === true)
|
|
46
|
-
return false;
|
|
47
|
-
const proposal = state.outputs[state.passIndex];
|
|
48
|
-
const catalog = input.listCatalog;
|
|
49
|
-
if (!proposal?.ready ||
|
|
50
|
-
!proposal.operations?.length ||
|
|
51
|
-
!catalog?.lists?.length ||
|
|
52
|
-
!Number.isSafeInteger(catalog.revision))
|
|
53
|
-
return false;
|
|
54
|
-
const lists = catalog.lists.map((list) => ({ ...list }));
|
|
55
|
-
let target;
|
|
56
|
-
for (const [index, operation] of proposal.operations.entries()) {
|
|
57
|
-
if (![
|
|
58
|
-
'app.addField',
|
|
59
|
-
'app.renameField',
|
|
60
|
-
'app.hideField',
|
|
61
|
-
'app.renameList',
|
|
62
|
-
].includes(operation.tool) ||
|
|
63
|
-
(operation.tool === 'app.addField' &&
|
|
64
|
-
![
|
|
65
|
-
'text',
|
|
66
|
-
'long text',
|
|
67
|
-
'number',
|
|
68
|
-
'date',
|
|
69
|
-
'date-time',
|
|
70
|
-
'yes/no',
|
|
71
|
-
'choice',
|
|
72
|
-
'money',
|
|
73
|
-
].includes(String(operation.args.kind))) ||
|
|
74
|
-
operation.args.expectedRevision !== Number(catalog.revision) + index)
|
|
75
|
-
return false;
|
|
76
|
-
// Exact descriptor matches are a conservative subset of core's resolution.
|
|
77
|
-
// Unknown spelling/normalization expands the work rather than guessing identity.
|
|
78
|
-
const exact = lists.filter((list) => list.id === operation.args.list || list.label === operation.args.list);
|
|
79
|
-
const matches = exact.length
|
|
80
|
-
? exact
|
|
81
|
-
: lists.filter((list) => list.synonyms.includes(String(operation.args.list)));
|
|
82
|
-
if (matches.length !== 1 ||
|
|
83
|
-
(target !== undefined && target !== matches[0].id))
|
|
84
|
-
return false;
|
|
85
|
-
target = matches[0].id;
|
|
86
|
-
if (operation.tool === 'app.renameList') {
|
|
87
|
-
if (typeof operation.args.label !== 'string' ||
|
|
88
|
-
lists.some((list) => list.id !== target && list.label === operation.args.label))
|
|
89
|
-
return false;
|
|
90
|
-
matches[0].label = operation.args.label;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
return true;
|
|
94
|
-
}
|
|
95
|
-
/** Public progress is host-owned; model prose and raw checkpoint notes stay private. */
|
|
96
|
-
export function presentCookbookDesignProgress(event, state) {
|
|
97
|
-
const notes = {
|
|
98
|
-
running: 'I’m working through your request.',
|
|
99
|
-
checking: 'I’m checking the proposed changes.',
|
|
100
|
-
'waiting-approval': 'Your changes are ready for your review.',
|
|
101
|
-
stopped: 'This work is paused.',
|
|
102
|
-
failed: 'I couldn’t finish this request. Please try again.',
|
|
103
|
-
done: 'This work is complete.',
|
|
104
|
-
};
|
|
105
|
-
const adaptive = state?.definition.startsWith(definitionPrefix) &&
|
|
106
|
-
state.input
|
|
107
|
-
.fixedPasses !== true &&
|
|
108
|
-
state.input.expanded !== true;
|
|
109
|
-
return {
|
|
110
|
-
runId: event.runId,
|
|
111
|
-
status: event.status,
|
|
112
|
-
pass: {
|
|
113
|
-
index: event.pass.index,
|
|
114
|
-
count: adaptive
|
|
115
|
-
? Math.max(1, state?.outputs.length ?? 0)
|
|
116
|
-
: event.pass.count,
|
|
117
|
-
name: event.pass.index === 1
|
|
118
|
-
? state?.definition.startsWith(definitionPrefix)
|
|
119
|
-
? 'Planning your changes'
|
|
120
|
-
: 'Checking your request'
|
|
121
|
-
: event.pass.index === 2
|
|
122
|
-
? 'Planning your changes'
|
|
123
|
-
: 'Checking the proposed changes',
|
|
124
|
-
},
|
|
125
|
-
note: event.status === 'failed' &&
|
|
126
|
-
event.note ===
|
|
127
|
-
'No changes were applied. The design needs more information before it can propose a supported change.'
|
|
128
|
-
? 'No changes were made. I need a little more information.'
|
|
129
|
-
: notes[event.status],
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
/**
|
|
133
|
-
* Concrete cookbook workflow on inference checkpoints and the existing jobs queue.
|
|
134
|
-
* Construct once per database before starting its TaskRunner. Browser requests only
|
|
135
|
-
* admit jobs; model calls occur exclusively through the registered job target.
|
|
136
|
-
*/
|
|
137
|
-
export function createCookbookDesignRuns(options) {
|
|
138
|
-
const ajv = new Ajv({ strict: true, allErrors: true });
|
|
139
|
-
const jobs = SmrtJobCollection.create({ db: options.db });
|
|
140
|
-
const controllers = new Map();
|
|
141
|
-
async function enqueue(tx, state, tenantId) {
|
|
142
|
-
await (await jobs).enqueueJob({
|
|
143
|
-
objectType: '@happyvertical/smrt-inference:DesignRunRecord',
|
|
144
|
-
objectId: state.id,
|
|
145
|
-
method: 'execute',
|
|
146
|
-
args: {},
|
|
147
|
-
tenantId,
|
|
148
|
-
dedupeKey: state.id,
|
|
149
|
-
queue: 'default',
|
|
150
|
-
maxAttempts: 1,
|
|
151
|
-
timeout: state.budget.maxDurationMs,
|
|
152
|
-
timeoutBehavior: 'warn',
|
|
153
|
-
}, { transaction: tx });
|
|
154
|
-
}
|
|
155
|
-
async function driver(ownerId, tenantId, count, claim, definition = `${definitionPrefix}${count}`) {
|
|
156
|
-
if (!Number.isSafeInteger(count) || count < 1 || count > 64)
|
|
157
|
-
throw new Error('Design passes must be between 1 and 64');
|
|
158
|
-
// v1 outputs retain their original contract. New runs advertise the actual
|
|
159
|
-
// owning schemas without granting the model any mutation tools.
|
|
160
|
-
const structured = !definition.startsWith('cookbook-design/v1/');
|
|
161
|
-
const operations = structured
|
|
162
|
-
? ((await options.listOperations?.(ownerId, tenantId)) ?? [])
|
|
163
|
-
: [];
|
|
164
|
-
const versionedOutputSchema = /^cookbook-design\/v[45]\//.test(definition)
|
|
165
|
-
? {
|
|
166
|
-
...outputSchema,
|
|
167
|
-
required: [...outputSchema.required, 'personSummary'],
|
|
168
|
-
properties: {
|
|
169
|
-
...outputSchema.properties,
|
|
170
|
-
personSummary: {
|
|
171
|
-
type: 'string',
|
|
172
|
-
minLength: 1,
|
|
173
|
-
maxLength: 240,
|
|
174
|
-
description: 'A short plain-language explanation for the person. Never include implementation details. The host validates presentation separately; this field does not grant authority.',
|
|
175
|
-
},
|
|
176
|
-
},
|
|
177
|
-
}
|
|
178
|
-
: outputSchema;
|
|
179
|
-
const schema = structured
|
|
180
|
-
? {
|
|
181
|
-
...versionedOutputSchema,
|
|
182
|
-
properties: {
|
|
183
|
-
...versionedOutputSchema.properties,
|
|
184
|
-
operations: {
|
|
185
|
-
...outputSchema.properties.operations,
|
|
186
|
-
description: 'Proposed changes only. Use the exact tool names and arguments below; never MCP wire names or invented tools. Set ready to true when the proposal is complete and its checks pass.',
|
|
187
|
-
items: operations.length
|
|
188
|
-
? {
|
|
189
|
-
oneOf: operations.map((operation) => {
|
|
190
|
-
const args = structuredClone(operation.inputSchema);
|
|
191
|
-
if (args.properties &&
|
|
192
|
-
typeof args.properties === 'object')
|
|
193
|
-
delete args.properties
|
|
194
|
-
.approvalId;
|
|
195
|
-
if (Array.isArray(args.required))
|
|
196
|
-
args.required = args.required.filter((key) => key !== 'approvalId');
|
|
197
|
-
args.additionalProperties = false;
|
|
198
|
-
return {
|
|
199
|
-
type: 'object',
|
|
200
|
-
additionalProperties: false,
|
|
201
|
-
required: ['tool', 'args'],
|
|
202
|
-
description: operation.description,
|
|
203
|
-
properties: { tool: { const: operation.name }, args },
|
|
204
|
-
};
|
|
205
|
-
}),
|
|
206
|
-
}
|
|
207
|
-
: false,
|
|
208
|
-
},
|
|
209
|
-
},
|
|
210
|
-
}
|
|
211
|
-
: outputSchema;
|
|
212
|
-
const validateOutput = ajv.compile(schema);
|
|
213
|
-
const store = createDesignRunStore({
|
|
214
|
-
db: options.db,
|
|
215
|
-
ownerId,
|
|
216
|
-
tenantId,
|
|
217
|
-
...(claim
|
|
218
|
-
? {
|
|
219
|
-
async authorizeWrite(tx, state) {
|
|
220
|
-
const current = await tx.query("UPDATE _smrt_jobs SET updated_at = updated_at WHERE id = ? AND worker_id = ? AND attempts = ? AND object_id = ? AND status = 'running' RETURNING id", claim.jobId, claim.workerId, claim.attempt, state.id);
|
|
221
|
-
return current.rows.length === 1;
|
|
222
|
-
},
|
|
223
|
-
async authorizeRelease(tx, state) {
|
|
224
|
-
const current = await tx.query("UPDATE _smrt_jobs SET updated_at = updated_at WHERE id = ? AND worker_id = ? AND attempts = ? AND object_id = ? AND status IN ('running', 'cancelled', 'completed', 'failed') RETURNING id", claim.jobId, claim.workerId, claim.attempt, state.id);
|
|
225
|
-
return current.rows.length === 1;
|
|
226
|
-
},
|
|
227
|
-
}
|
|
228
|
-
: {}),
|
|
229
|
-
async enqueue(tx, state) {
|
|
230
|
-
await enqueue(tx, state, tenantId);
|
|
231
|
-
},
|
|
232
|
-
});
|
|
233
|
-
const workflow = createDesignRunDriver({
|
|
234
|
-
store,
|
|
235
|
-
definition,
|
|
236
|
-
passes: Array.from({ length: count }, (_, index) => ({
|
|
237
|
-
name: definition.startsWith(definitionPrefix)
|
|
238
|
-
? index === 0
|
|
239
|
-
? 'Propose the design'
|
|
240
|
-
: 'Check and revise the design'
|
|
241
|
-
: index === 0
|
|
242
|
-
? 'Understand the request'
|
|
243
|
-
: index === 1
|
|
244
|
-
? 'Propose the design'
|
|
245
|
-
: 'Check and revise the design',
|
|
246
|
-
schema,
|
|
247
|
-
async check(output, state, { signal }) {
|
|
248
|
-
// Mechanical validation is repeated after a crash before advancing.
|
|
249
|
-
if (!validateOutput(output))
|
|
250
|
-
throw new Error('Stored design output failed validation');
|
|
251
|
-
const plan = output;
|
|
252
|
-
const maximum = index === count - 1;
|
|
253
|
-
const final = isCookbookDesignFinalCheck(state);
|
|
254
|
-
const input = readInput(state.input);
|
|
255
|
-
if (applicableDefinitions.test(definition) &&
|
|
256
|
-
state.input.schemaPin !==
|
|
257
|
-
fingerprint(schema))
|
|
258
|
-
throw new Error('The design schema changed; start a new design run');
|
|
259
|
-
const preview = input.profile.previewBeforeApply;
|
|
260
|
-
if (maximum && applicableDefinitions.test(definition) && !plan.ready)
|
|
261
|
-
return {
|
|
262
|
-
failure: 'No changes were applied. The design needs more information before it can propose a supported change.',
|
|
263
|
-
input: {
|
|
264
|
-
...state.input,
|
|
265
|
-
previousCheck: { pass: index + 1, ready: false, checked: true },
|
|
266
|
-
},
|
|
267
|
-
};
|
|
268
|
-
if (final &&
|
|
269
|
-
applicableDefinitions.test(definition) &&
|
|
270
|
-
plan.ready &&
|
|
271
|
-
plan.operations.length) {
|
|
272
|
-
if (!options.executeOperation)
|
|
273
|
-
throw new Error('Durable design application is unavailable');
|
|
274
|
-
await options.authorize(ownerId, tenantId);
|
|
275
|
-
await options.authorizeThread?.(ownerId, tenantId, input.threadId);
|
|
276
|
-
const pin = state.input.applyPin;
|
|
277
|
-
if (pin && pin !== fingerprint({ input, output, schema }))
|
|
278
|
-
throw new Error('The approved design proposal or schema changed');
|
|
279
|
-
const results = [];
|
|
280
|
-
for (const [action, operation] of plan.operations.entries()) {
|
|
281
|
-
signal.throwIfAborted();
|
|
282
|
-
if (!input.permissions.includes(operation.tool))
|
|
283
|
-
throw new Error('Design operation is outside its original permission ceiling');
|
|
284
|
-
const result = await options.executeOperation({
|
|
285
|
-
ownerId,
|
|
286
|
-
tenantId,
|
|
287
|
-
threadId: input.threadId,
|
|
288
|
-
runId: state.id,
|
|
289
|
-
actionId: String(action),
|
|
290
|
-
permissions: input.permissions,
|
|
291
|
-
operation,
|
|
292
|
-
signal,
|
|
293
|
-
});
|
|
294
|
-
if (result.status === 'approval_required') {
|
|
295
|
-
if (typeof result.approvalId !== 'string')
|
|
296
|
-
throw new Error('Design approval is unavailable');
|
|
297
|
-
return {
|
|
298
|
-
waitingApproval: true,
|
|
299
|
-
note: result.summary,
|
|
300
|
-
input: {
|
|
301
|
-
...state.input,
|
|
302
|
-
pendingApprovalId: result.approvalId,
|
|
303
|
-
previousCheck: {
|
|
304
|
-
pass: index + 1,
|
|
305
|
-
ready: true,
|
|
306
|
-
checked: true,
|
|
307
|
-
},
|
|
308
|
-
results,
|
|
309
|
-
},
|
|
310
|
-
};
|
|
311
|
-
}
|
|
312
|
-
if (result.status !== 'ok') {
|
|
313
|
-
// These statuses are core planning questions before any hold/effect.
|
|
314
|
-
// Never replan after a receipt, an approval, or an uncertain throw.
|
|
315
|
-
if (!maximum &&
|
|
316
|
-
results.length === 0 &&
|
|
317
|
-
!state.input.pendingApprovalId &&
|
|
318
|
-
['collision', 'clarification_required'].includes(result.status))
|
|
319
|
-
return {
|
|
320
|
-
input: {
|
|
321
|
-
...state.input,
|
|
322
|
-
expanded: true,
|
|
323
|
-
previousCheck: {
|
|
324
|
-
pass: index + 1,
|
|
325
|
-
ready: false,
|
|
326
|
-
checked: true,
|
|
327
|
-
status: result.status,
|
|
328
|
-
},
|
|
329
|
-
},
|
|
330
|
-
};
|
|
331
|
-
throw new Error(result.summary);
|
|
332
|
-
}
|
|
333
|
-
results.push(result);
|
|
334
|
-
}
|
|
335
|
-
return {
|
|
336
|
-
...(definition.startsWith(definitionPrefix)
|
|
337
|
-
? { complete: true }
|
|
338
|
-
: {}),
|
|
339
|
-
input: {
|
|
340
|
-
...state.input,
|
|
341
|
-
pendingApprovalId: undefined,
|
|
342
|
-
previousCheck: { pass: index + 1, ready: true, checked: true },
|
|
343
|
-
results,
|
|
344
|
-
},
|
|
345
|
-
};
|
|
346
|
-
}
|
|
347
|
-
return {
|
|
348
|
-
...(maximum && (plan.operations.length > 0 || !plan.ready)
|
|
349
|
-
? {
|
|
350
|
-
waitingApproval: true,
|
|
351
|
-
note: !plan.ready
|
|
352
|
-
? 'The design needs your review before changes can be applied.'
|
|
353
|
-
: preview
|
|
354
|
-
? 'Your design is ready to review. Apply its proposed changes through the existing app controls.'
|
|
355
|
-
: 'Your design is ready. Automatic application is blocked because cookbook tools do not yet support safe durable replay. Review and apply the proposed changes through the app controls.',
|
|
356
|
-
}
|
|
357
|
-
: {}),
|
|
358
|
-
input: {
|
|
359
|
-
...state.input,
|
|
360
|
-
...(definition.startsWith(definitionPrefix)
|
|
361
|
-
? { expanded: true }
|
|
362
|
-
: {}),
|
|
363
|
-
previousCheck: {
|
|
364
|
-
pass: index + 1,
|
|
365
|
-
ready: output.ready,
|
|
366
|
-
checked: true,
|
|
367
|
-
},
|
|
368
|
-
},
|
|
369
|
-
};
|
|
370
|
-
},
|
|
371
|
-
})),
|
|
372
|
-
validate(_schema, output) {
|
|
373
|
-
return validateOutput(output)
|
|
374
|
-
? []
|
|
375
|
-
: (validateOutput.errors ?? []).map((error) => `${error.instancePath || '/'} ${error.message}`);
|
|
376
|
-
},
|
|
377
|
-
async executePass(request) {
|
|
378
|
-
await options.authorize(ownerId, tenantId);
|
|
379
|
-
if (applicableDefinitions.test(definition) &&
|
|
380
|
-
request.input.schemaPin !==
|
|
381
|
-
fingerprint(schema))
|
|
382
|
-
throw new Error('The design schema changed; start a new design run');
|
|
383
|
-
const input = readInput(request.input);
|
|
384
|
-
return options.executePass({
|
|
385
|
-
ownerId,
|
|
386
|
-
tenantId,
|
|
387
|
-
threadId: input.threadId,
|
|
388
|
-
content: input.content,
|
|
389
|
-
profile: input.profile,
|
|
390
|
-
permissions: input.permissions,
|
|
391
|
-
stage: definition.startsWith(definitionPrefix)
|
|
392
|
-
? request.pass.index === 1
|
|
393
|
-
? 'propose'
|
|
394
|
-
: 'revise'
|
|
395
|
-
: request.pass.index === 1
|
|
396
|
-
? 'profile'
|
|
397
|
-
: request.pass.index === 2
|
|
398
|
-
? 'propose'
|
|
399
|
-
: 'revise',
|
|
400
|
-
request,
|
|
401
|
-
});
|
|
402
|
-
},
|
|
403
|
-
async readResource(owner, id, cursor, maxChars) {
|
|
404
|
-
await options.authorize(owner, tenantId);
|
|
405
|
-
if (!options.readResource)
|
|
406
|
-
throw new Error('Design resource not found');
|
|
407
|
-
return options.readResource(owner, tenantId, id, cursor, maxChars);
|
|
408
|
-
},
|
|
409
|
-
...(claim
|
|
410
|
-
? {
|
|
411
|
-
async ownsExecution() {
|
|
412
|
-
const current = await options.db.query("SELECT id FROM _smrt_jobs WHERE id = ? AND worker_id = ? AND attempts = ? AND status = 'running'", claim.jobId, claim.workerId, claim.attempt);
|
|
413
|
-
return current.rows.length === 1;
|
|
414
|
-
},
|
|
415
|
-
}
|
|
416
|
-
: {}),
|
|
417
|
-
onProgress: async (event) => {
|
|
418
|
-
if (options.onProgress)
|
|
419
|
-
await options.onProgress(presentCookbookDesignProgress(event, (await store.load(event.runId, ownerId)) ?? undefined));
|
|
420
|
-
},
|
|
421
|
-
});
|
|
422
|
-
return { ...workflow, validateProposal: validateOutput, schema };
|
|
423
|
-
}
|
|
424
|
-
function passCount(definition) {
|
|
425
|
-
const match = /^cookbook-design\/v[12345]\/(\d+)$/.exec(definition);
|
|
426
|
-
if (!match)
|
|
427
|
-
throw new Error('Design run definition changed');
|
|
428
|
-
return Number(match[1]);
|
|
429
|
-
}
|
|
430
|
-
const dispose = installDesignRunExecutor(options.db, async (record, _args, context) => {
|
|
431
|
-
if (!isRunnerExecutionContext(context))
|
|
432
|
-
throw new Error('Design execution requires TaskRunner ownership');
|
|
433
|
-
const ownerId = record.ownerId;
|
|
434
|
-
const tenantId = record.tenantId;
|
|
435
|
-
if ((context.job.tenantId ?? null) !== tenantId)
|
|
436
|
-
throw new Error('Design run not found');
|
|
437
|
-
await options.authorize(ownerId, tenantId);
|
|
438
|
-
const claim = await options.db.query("SELECT worker_id FROM _smrt_jobs WHERE id = ? AND object_id = ? AND status = 'running'", context.job.jobId, record.id);
|
|
439
|
-
const workerId = claim.rows[0]?.worker_id;
|
|
440
|
-
if (typeof workerId !== 'string')
|
|
441
|
-
throw new Error('Design job lost ownership');
|
|
442
|
-
const state = JSON.parse(record.payload);
|
|
443
|
-
if (state.ownerId !== ownerId || state.id !== record.id)
|
|
444
|
-
throw new Error('Design run not found');
|
|
445
|
-
const controller = new AbortController();
|
|
446
|
-
const abort = () => controller.abort(context.signal.reason);
|
|
447
|
-
if (context.signal.aborted)
|
|
448
|
-
abort();
|
|
449
|
-
context.signal.addEventListener('abort', abort, { once: true });
|
|
450
|
-
controllers.set(state.id, controller);
|
|
451
|
-
try {
|
|
452
|
-
return await (await driver(ownerId, tenantId, passCount(state.definition), {
|
|
453
|
-
jobId: context.job.jobId,
|
|
454
|
-
workerId,
|
|
455
|
-
attempt: context.job.attempt,
|
|
456
|
-
}, state.definition)).run(state.id, ownerId, controller.signal);
|
|
457
|
-
}
|
|
458
|
-
finally {
|
|
459
|
-
controllers.delete(state.id);
|
|
460
|
-
context.signal.removeEventListener('abort', abort);
|
|
461
|
-
}
|
|
462
|
-
});
|
|
463
|
-
return {
|
|
464
|
-
dispose,
|
|
465
|
-
forOwner(ownerId, tenantId) {
|
|
466
|
-
async function existing(id) {
|
|
467
|
-
await options.authorize(ownerId, tenantId);
|
|
468
|
-
// The scoped store enforces owner and tenant before revealing a definition.
|
|
469
|
-
const store = createDesignRunStore({
|
|
470
|
-
db: options.db,
|
|
471
|
-
ownerId,
|
|
472
|
-
tenantId,
|
|
473
|
-
enqueue: async () => {
|
|
474
|
-
throw new Error('Read-only design store');
|
|
475
|
-
},
|
|
476
|
-
});
|
|
477
|
-
const state = await store.load(id, ownerId);
|
|
478
|
-
if (!state)
|
|
479
|
-
throw new Error('Design run not found');
|
|
480
|
-
return driver(ownerId, tenantId, passCount(state.definition), undefined, state.definition);
|
|
481
|
-
}
|
|
482
|
-
return {
|
|
483
|
-
async start(input) {
|
|
484
|
-
await options.authorize(ownerId, tenantId);
|
|
485
|
-
readInput(input);
|
|
486
|
-
if (input.profile.name !== 'design')
|
|
487
|
-
throw new Error('Design runs require the design profile');
|
|
488
|
-
const budget = input.profile.budgets;
|
|
489
|
-
const description = input.fixedPasses !== true
|
|
490
|
-
? await options.describeApp?.(ownerId, tenantId)
|
|
491
|
-
: undefined;
|
|
492
|
-
const lists = Array.isArray(description?.lists) && description.lists.length <= 512
|
|
493
|
-
? description.lists.flatMap((value) => {
|
|
494
|
-
if (!value || typeof value !== 'object')
|
|
495
|
-
return [];
|
|
496
|
-
const list = value;
|
|
497
|
-
return typeof list.id === 'string' &&
|
|
498
|
-
list.id.length <= 512 &&
|
|
499
|
-
typeof list.label === 'string' &&
|
|
500
|
-
list.label.length <= 120 &&
|
|
501
|
-
Array.isArray(list.synonyms) &&
|
|
502
|
-
list.synonyms.length <= 32 &&
|
|
503
|
-
list.synonyms.every((alias) => typeof alias === 'string' && alias.length <= 120)
|
|
504
|
-
? [
|
|
505
|
-
{
|
|
506
|
-
id: list.id,
|
|
507
|
-
label: list.label,
|
|
508
|
-
synonyms: [...list.synonyms],
|
|
509
|
-
},
|
|
510
|
-
]
|
|
511
|
-
: [];
|
|
512
|
-
})
|
|
513
|
-
: [];
|
|
514
|
-
// Never truncate away an ambiguous target. An incomplete bounded
|
|
515
|
-
// descriptor snapshot disables the shortcut for this entire run.
|
|
516
|
-
const listCatalog = description?.status === 'ok' &&
|
|
517
|
-
Number.isSafeInteger(description.revision) &&
|
|
518
|
-
Array.isArray(description.lists) &&
|
|
519
|
-
lists.length === description.lists.length
|
|
520
|
-
? { revision: description.revision, lists }
|
|
521
|
-
: undefined;
|
|
522
|
-
const run = await driver(ownerId, tenantId, budget.passes);
|
|
523
|
-
return run.start({
|
|
524
|
-
id: randomUUID(),
|
|
525
|
-
ownerId,
|
|
526
|
-
resourceIds: input.resourceIds ?? [],
|
|
527
|
-
input: {
|
|
528
|
-
threadId: input.threadId,
|
|
529
|
-
content: input.content,
|
|
530
|
-
profile: input.profile,
|
|
531
|
-
permissions: [...(input.permissions ?? [])],
|
|
532
|
-
fixedPasses: input.fixedPasses === true,
|
|
533
|
-
...(listCatalog ? { listCatalog } : {}),
|
|
534
|
-
schemaPin: fingerprint(run.schema),
|
|
535
|
-
},
|
|
536
|
-
budget: {
|
|
537
|
-
maxTokens: budget.maxRunTokens,
|
|
538
|
-
maxDurationMs: budget.runTimeoutMs,
|
|
539
|
-
maxCallTokens: budget.maxTurnTokens,
|
|
540
|
-
callTimeoutMs: budget.turnTimeoutMs,
|
|
541
|
-
repairRetries: budget.repairRetries,
|
|
542
|
-
toolResultChars: budget.toolResultChars,
|
|
543
|
-
},
|
|
544
|
-
});
|
|
545
|
-
},
|
|
546
|
-
async latest(threadId) {
|
|
547
|
-
await options.authorize(ownerId, tenantId);
|
|
548
|
-
const scope = tenantId === null ? 'tenant_id IS NULL' : 'tenant_id = ?';
|
|
549
|
-
const rows = await options.db.query(`SELECT payload FROM _smrt_inference_design_runs WHERE owner_id = ? AND ${scope} ORDER BY updated_at DESC LIMIT 100`, ...(tenantId === null ? [ownerId] : [ownerId, tenantId]));
|
|
550
|
-
for (const row of rows.rows) {
|
|
551
|
-
const state = JSON.parse(String(row.payload));
|
|
552
|
-
if (readInput(state.input).threadId === threadId)
|
|
553
|
-
return state;
|
|
554
|
-
}
|
|
555
|
-
return null;
|
|
556
|
-
},
|
|
557
|
-
async status(id) {
|
|
558
|
-
return (await existing(id)).status(id, ownerId);
|
|
559
|
-
},
|
|
560
|
-
async validateAction(id, actionId, tool, args) {
|
|
561
|
-
const run = await existing(id);
|
|
562
|
-
const state = await run.status(id, ownerId);
|
|
563
|
-
const output = state.outputs[state.passIndex];
|
|
564
|
-
const input = readInput(state.input);
|
|
565
|
-
if (!applicableDefinitions.test(state.definition) ||
|
|
566
|
-
!isCookbookDesignFinalCheck(state) ||
|
|
567
|
-
!['waiting-approval', 'running', 'checking'].includes(state.status) ||
|
|
568
|
-
!run.validateProposal(output) ||
|
|
569
|
-
state.input.schemaPin !==
|
|
570
|
-
fingerprint(run.schema) ||
|
|
571
|
-
!output.ready ||
|
|
572
|
-
!/^(0|[1-9]\d*)$/.test(actionId))
|
|
573
|
-
throw new Error('Saved design action changed');
|
|
574
|
-
const operation = output.operations[Number(actionId)];
|
|
575
|
-
const desired = operation?.tool === 'cookbook.apply'
|
|
576
|
-
? { ...operation.args, apply: true }
|
|
577
|
-
: operation?.args;
|
|
578
|
-
if (!operation ||
|
|
579
|
-
operation.tool !== tool ||
|
|
580
|
-
!input.permissions.includes(tool) ||
|
|
581
|
-
fingerprint(desired) !== fingerprint(args))
|
|
582
|
-
throw new Error('Saved design arguments changed');
|
|
583
|
-
const pin = state.input.applyPin;
|
|
584
|
-
if (pin && pin !== fingerprint({ input, output, schema: run.schema }))
|
|
585
|
-
throw new Error('Saved design proposal changed');
|
|
586
|
-
await options.authorizeThread?.(ownerId, tenantId, input.threadId);
|
|
587
|
-
},
|
|
588
|
-
async stop(id) {
|
|
589
|
-
const run = await existing(id);
|
|
590
|
-
const state = await run.status(id, ownerId);
|
|
591
|
-
if (state.passIndex >= passCount(state.definition))
|
|
592
|
-
return state;
|
|
593
|
-
const result = await run.stop(id, ownerId);
|
|
594
|
-
controllers.get(id)?.abort(new Error('Design run stopped'));
|
|
595
|
-
return result;
|
|
596
|
-
},
|
|
597
|
-
async resume(id, budget) {
|
|
598
|
-
let run = await existing(id);
|
|
599
|
-
let state = await run.status(id, ownerId);
|
|
600
|
-
const input = readInput(state.input);
|
|
601
|
-
if (state.definition.startsWith('cookbook-design/v2/') &&
|
|
602
|
-
state.status === 'waiting-approval') {
|
|
603
|
-
const count = passCount(state.definition);
|
|
604
|
-
const final = state.outputs[count - 1];
|
|
605
|
-
const upgraded = await driver(ownerId, tenantId, count, undefined, `${legacyDurablePrefix}${count}`);
|
|
606
|
-
const variants = upgraded.schema.properties.operations.items;
|
|
607
|
-
const fieldSchema = variants.oneOf?.find((variant) => variant.properties.tool.const === 'app.addField')?.properties.args;
|
|
608
|
-
if (state.phase !== 'model' ||
|
|
609
|
-
state.passIndex !== count ||
|
|
610
|
-
state.outputs.length !== count ||
|
|
611
|
-
state.leaseRevision !== undefined ||
|
|
612
|
-
state.leaseUntil !== undefined ||
|
|
613
|
-
!upgraded.validateProposal(final) ||
|
|
614
|
-
fingerprint(fieldSchema) !== v2AddFieldSchemaPin ||
|
|
615
|
-
!final.ready ||
|
|
616
|
-
!final.operations.length ||
|
|
617
|
-
!options.authorizeThread ||
|
|
618
|
-
!final.operations.every((operation) => input.permissions.includes(operation.tool)) ||
|
|
619
|
-
!final.operations.every((operation) => operation.tool === 'app.addField'))
|
|
620
|
-
throw new Error('The design proposal is not compatible with durable application');
|
|
621
|
-
await options.authorizeThread(ownerId, tenantId, input.threadId);
|
|
622
|
-
if (!options.currentRevision)
|
|
623
|
-
throw new Error('Live design revision is unavailable');
|
|
624
|
-
const revision = await options.currentRevision(ownerId, tenantId);
|
|
625
|
-
if (!final.operations.every((operation, index) => operation.args.expectedRevision === revision + index))
|
|
626
|
-
throw new Error('The application revision changed; start a new design run');
|
|
627
|
-
// The same current owning schema must still be offered after auth.
|
|
628
|
-
if (fingerprint(upgraded.schema) !==
|
|
629
|
-
fingerprint((await driver(ownerId, tenantId, count, undefined, `${legacyDurablePrefix}${count}`)).schema))
|
|
630
|
-
throw new Error('The design schema changed');
|
|
631
|
-
const next = {
|
|
632
|
-
...state,
|
|
633
|
-
revision: state.revision + 1,
|
|
634
|
-
definition: `${legacyDurablePrefix}${count}`,
|
|
635
|
-
phase: 'check',
|
|
636
|
-
passIndex: count - 1,
|
|
637
|
-
input: {
|
|
638
|
-
...state.input,
|
|
639
|
-
schemaPin: fingerprint(upgraded.schema),
|
|
640
|
-
applyPin: fingerprint({
|
|
641
|
-
input,
|
|
642
|
-
output: final,
|
|
643
|
-
schema: upgraded.schema,
|
|
644
|
-
}),
|
|
645
|
-
},
|
|
646
|
-
};
|
|
647
|
-
if (!options.db.transaction)
|
|
648
|
-
throw new Error('Design runs require transaction support');
|
|
649
|
-
const scope = tenantId === null ? 'tenant_id IS NULL' : 'tenant_id = ?';
|
|
650
|
-
const migrated = await options.db.transaction(async (tx) => tx.query(`UPDATE _smrt_inference_design_runs SET revision = ?, payload = ?, updated_at = ? WHERE id = ? AND owner_id = ? AND ${scope} AND revision = ? AND payload = ? AND NOT EXISTS (SELECT 1 FROM _smrt_jobs WHERE object_id = ? AND object_type = ? AND status IN ('pending', 'running')) RETURNING id`, next.revision, JSON.stringify(next), new Date().toISOString(), id, ownerId, ...(tenantId === null ? [] : [tenantId]), state.revision, JSON.stringify(state), id, '@happyvertical/smrt-inference:DesignRunRecord'));
|
|
651
|
-
if (migrated.rows.length !== 1)
|
|
652
|
-
throw new Error('Design run changed; reload its current status');
|
|
653
|
-
state = next;
|
|
654
|
-
run = upgraded;
|
|
655
|
-
}
|
|
656
|
-
if (state.passIndex >= passCount(state.definition) &&
|
|
657
|
-
state.status !== 'done')
|
|
658
|
-
throw new Error('Review the proposed design and apply it through the existing app controls.');
|
|
659
|
-
const active = await options.db.query("SELECT id FROM _smrt_jobs WHERE object_id = ? AND object_type = ? AND status = 'running'", id, '@happyvertical/smrt-inference:DesignRunRecord');
|
|
660
|
-
if (active.rows.length)
|
|
661
|
-
throw new Error('The current design pass is stopping. Resume when it has stopped.');
|
|
662
|
-
if (applicableDefinitions.test(state.definition) &&
|
|
663
|
-
isCookbookDesignFinalCheck(state) &&
|
|
664
|
-
['running', 'checking'].includes(state.status)) {
|
|
665
|
-
const output = state.outputs[state.passIndex];
|
|
666
|
-
if (!run.validateProposal(output) ||
|
|
667
|
-
!output.ready ||
|
|
668
|
-
!options.authorizeThread)
|
|
669
|
-
throw new Error('Design recovery requires a valid final proposal');
|
|
670
|
-
await options.authorizeThread(ownerId, tenantId, input.threadId);
|
|
671
|
-
const collection = await jobs;
|
|
672
|
-
const candidates = await collection.list({
|
|
673
|
-
where: {
|
|
674
|
-
objectId: id,
|
|
675
|
-
objectType: '@happyvertical/smrt-inference:DesignRunRecord',
|
|
676
|
-
status: 'failed',
|
|
677
|
-
},
|
|
678
|
-
orderBy: 'updated_at DESC',
|
|
679
|
-
limit: 1,
|
|
680
|
-
});
|
|
681
|
-
const prior = candidates[0];
|
|
682
|
-
const events = await SmrtJobEventCollection.create({
|
|
683
|
-
db: options.db,
|
|
684
|
-
});
|
|
685
|
-
const outcomes = await events.listTerminalOutcomes({
|
|
686
|
-
tenantId,
|
|
687
|
-
objectTypes: ['@happyvertical/smrt-inference:DesignRunRecord'],
|
|
688
|
-
limit: 1000,
|
|
689
|
-
});
|
|
690
|
-
if (!prior?.id ||
|
|
691
|
-
!outcomes.outcomes.some((event) => event.jobId === prior.id &&
|
|
692
|
-
event.attempts === prior.attempts &&
|
|
693
|
-
event.failureKind === 'stale-recovery'))
|
|
694
|
-
throw new Error('The previous worker has not been recovered by TaskRunner');
|
|
695
|
-
if (!options.db.transaction)
|
|
696
|
-
throw new Error('Design runs require transaction support');
|
|
697
|
-
const next = {
|
|
698
|
-
...state,
|
|
699
|
-
status: 'running',
|
|
700
|
-
revision: state.revision + 1,
|
|
701
|
-
};
|
|
702
|
-
await options.db.transaction(async (tx) => {
|
|
703
|
-
const recovered = await tx.query("UPDATE _smrt_jobs SET updated_at = updated_at WHERE id = ? AND status = 'failed' AND attempts = ? RETURNING id", prior.id, prior.attempts);
|
|
704
|
-
if (recovered.rows.length !== 1)
|
|
705
|
-
throw new Error('The recovered job changed');
|
|
706
|
-
const scope = tenantId === null ? 'tenant_id IS NULL' : 'tenant_id = ?';
|
|
707
|
-
const saved = await tx.query(`UPDATE _smrt_inference_design_runs SET revision = ?, payload = ?, updated_at = ? WHERE id = ? AND owner_id = ? AND ${scope} AND revision = ? AND payload = ? AND NOT EXISTS (SELECT 1 FROM _smrt_jobs WHERE object_id = ? AND object_type = ? AND status IN ('pending', 'running')) RETURNING id`, next.revision, JSON.stringify(next), new Date().toISOString(), id, ownerId, ...(tenantId === null ? [] : [tenantId]), state.revision, JSON.stringify(state), id, '@happyvertical/smrt-inference:DesignRunRecord');
|
|
708
|
-
if (saved.rows.length !== 1)
|
|
709
|
-
throw new Error('Design run changed; reload its current status');
|
|
710
|
-
await enqueue(tx, next, tenantId);
|
|
711
|
-
});
|
|
712
|
-
return next;
|
|
713
|
-
}
|
|
714
|
-
return run.resume(id, ownerId, budget);
|
|
715
|
-
},
|
|
716
|
-
async resumeAfterApproval(id) {
|
|
717
|
-
await options.authorize(ownerId, tenantId);
|
|
718
|
-
const active = await options.db.query("SELECT id FROM _smrt_jobs WHERE object_id = ? AND object_type = ? AND status = 'running'", id, '@happyvertical/smrt-inference:DesignRunRecord');
|
|
719
|
-
for (const row of active.rows)
|
|
720
|
-
await new JobHandle(String(row.id), await jobs).wait({
|
|
721
|
-
timeout: 30_000,
|
|
722
|
-
pollInterval: 25,
|
|
723
|
-
});
|
|
724
|
-
const run = await existing(id);
|
|
725
|
-
const state = await run.status(id, ownerId);
|
|
726
|
-
if (state.status !== 'waiting-approval' ||
|
|
727
|
-
!applicableDefinitions.test(state.definition))
|
|
728
|
-
return state;
|
|
729
|
-
return run.resume(id, ownerId);
|
|
730
|
-
},
|
|
731
|
-
};
|
|
732
|
-
},
|
|
733
|
-
};
|
|
734
|
-
}
|
|
735
|
-
function readInput(input) {
|
|
736
|
-
if (!input || typeof input !== 'object')
|
|
737
|
-
throw new Error('Invalid design input');
|
|
738
|
-
const value = input;
|
|
739
|
-
if (typeof value.threadId !== 'string' ||
|
|
740
|
-
!value.threadId ||
|
|
741
|
-
typeof value.content !== 'string' ||
|
|
742
|
-
!value.content.trim() ||
|
|
743
|
-
!value.profile ||
|
|
744
|
-
typeof value.profile !== 'object' ||
|
|
745
|
-
value.profile.name !== 'design' ||
|
|
746
|
-
(value.permissions !== undefined &&
|
|
747
|
-
(!Array.isArray(value.permissions) ||
|
|
748
|
-
!value.permissions.every((permission) => typeof permission === 'string'))))
|
|
749
|
-
throw new Error('Invalid design input');
|
|
750
|
-
return {
|
|
751
|
-
threadId: value.threadId,
|
|
752
|
-
content: value.content,
|
|
753
|
-
profile: value.profile,
|
|
754
|
-
permissions: value.permissions ?? [],
|
|
755
|
-
...(typeof value.fixedPasses === 'boolean'
|
|
756
|
-
? { fixedPasses: value.fixedPasses }
|
|
757
|
-
: {}),
|
|
758
|
-
...(value.listCatalog !== undefined
|
|
759
|
-
? { listCatalog: value.listCatalog }
|
|
760
|
-
: {}),
|
|
761
|
-
...(value.expanded === true ? { expanded: true } : {}),
|
|
762
|
-
};
|
|
763
|
-
}
|