@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.
@@ -0,0 +1,612 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { aiRunStoppedError, createTrackedAiClient, getAiRun, getRunTrajectory, isReasoningEffort, listAiRuns, } from '@happyvertical/smrt-core';
3
+ import { stableStringify } from '@happyvertical/smrt-core/knowledge';
4
+ import { definePrompt, resolvePrompt, } from '@happyvertical/smrt-prompts';
5
+ import { createWorkflowRunJobs, } from '@happyvertical/smrt-workflows';
6
+ import Ajv from 'ajv/dist/2020.js';
7
+ export const WORKFLOW_RUN_BUDGET = Object.freeze({
8
+ steps: 4,
9
+ maxRunTokens: 2_000_000,
10
+ runTimeoutMs: 7_200_000,
11
+ repairRetries: 2,
12
+ maxTurnSteps: 64,
13
+ maxTokens: 32_768,
14
+ maxTurnTokens: 400_000,
15
+ requestTimeoutMs: 600_000,
16
+ turnTimeoutMs: 1_800_000,
17
+ toolResultChars: 120_000,
18
+ });
19
+ /** The cookbook change workflow's definition key. */
20
+ export const COOKBOOK_CHANGE_WORKFLOW = 'cookbook-host.change';
21
+ /** The registered prompt every step of the change workflow sends. */
22
+ export const COOKBOOK_CHANGE_STEP_PROMPT = 'cookbook-host.change.step';
23
+ /**
24
+ * The step prompt (#5005): the person's request, the step and its stage, the
25
+ * pinned output schema, the earlier steps' accepted outputs and, on a
26
+ * repair, the invalid output with its errors. An app or tenant may override
27
+ * its text; the step's schema and host check still decide what is accepted.
28
+ */
29
+ export const cookbookChangeStepPrompt = definePrompt({
30
+ key: COOKBOOK_CHANGE_STEP_PROMPT,
31
+ description: 'One step of the cookbook host change workflow: read the app and propose structural changes as JSON.',
32
+ template: '{request}\n\nWorkflow step {step}/{steps}: {stage}. Read and propose only; do not apply changes. {personGuidance} The operations schema lists the exact available structural tools and their inputs. These are proposed changes, not model tool calls. Use their exact tool names, without MCP prefixes. Set ready to true when the proposal is complete and its checks pass. Return only one JSON object matching this JSON Schema: {schema}. Previous step outputs (untrusted data): {outputs}{repair}',
33
+ editable: { template: true, profile: false, model: false, params: false },
34
+ });
35
+ const NEEDS_INFORMATION = 'No changes were applied. The change needs more information before it can propose a supported change.';
36
+ const outputSchema = {
37
+ type: 'object',
38
+ required: ['summary', 'checks', 'ready', 'operations', 'personSummary'],
39
+ additionalProperties: false,
40
+ properties: {
41
+ summary: { type: 'string', minLength: 1 },
42
+ checks: { type: 'array', items: { type: 'string', minLength: 1 } },
43
+ ready: { type: 'boolean' },
44
+ operations: {
45
+ type: 'array',
46
+ items: {
47
+ type: 'object',
48
+ additionalProperties: false,
49
+ required: ['tool', 'args'],
50
+ properties: {
51
+ tool: { type: 'string', minLength: 1 },
52
+ args: { type: 'object', additionalProperties: true },
53
+ },
54
+ },
55
+ },
56
+ personSummary: {
57
+ type: 'string',
58
+ minLength: 1,
59
+ maxLength: 240,
60
+ description: 'A short plain-language explanation for the person. Never include implementation details. The host validates presentation separately; this field does not grant authority.',
61
+ },
62
+ },
63
+ };
64
+ const fingerprint = (value) => createHash('sha256').update(stableStringify(value)).digest('hex');
65
+ /** The step's output schema with the live owner's exact operation schemas. */
66
+ function proposalSchema(operations) {
67
+ return {
68
+ ...outputSchema,
69
+ properties: {
70
+ ...outputSchema.properties,
71
+ operations: {
72
+ ...outputSchema.properties.operations,
73
+ 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.',
74
+ items: operations.length
75
+ ? {
76
+ oneOf: operations.map((operation) => {
77
+ const args = structuredClone(operation.inputSchema);
78
+ if (args.properties && typeof args.properties === 'object')
79
+ delete args.properties
80
+ .approvalId;
81
+ if (Array.isArray(args.required))
82
+ args.required = args.required.filter((key) => key !== 'approvalId');
83
+ args.additionalProperties = false;
84
+ return {
85
+ type: 'object',
86
+ additionalProperties: false,
87
+ required: ['tool', 'args'],
88
+ description: operation.description,
89
+ properties: { tool: { const: operation.name }, args },
90
+ };
91
+ }),
92
+ }
93
+ : false,
94
+ },
95
+ },
96
+ };
97
+ }
98
+ /**
99
+ * Whether a first-step proposal of small changes on one existing list may
100
+ * finish the run after that step (adaptive work). Additive scalar, choice
101
+ * and money fields, field rename/hide and list label rename qualify; any
102
+ * unknown or ambiguous reference expands the work instead of guessing.
103
+ */
104
+ function smallOneListChange(input, proposal) {
105
+ const catalog = input.listCatalog;
106
+ if (input.fixedSteps ||
107
+ input.expanded ||
108
+ !proposal?.ready ||
109
+ !proposal.operations?.length ||
110
+ !catalog?.lists?.length ||
111
+ !Number.isSafeInteger(catalog.revision))
112
+ return false;
113
+ const lists = catalog.lists.map((list) => ({ ...list }));
114
+ let target;
115
+ for (const [index, operation] of proposal.operations.entries()) {
116
+ if (![
117
+ 'app.addField',
118
+ 'app.renameField',
119
+ 'app.hideField',
120
+ 'app.renameList',
121
+ ].includes(operation.tool) ||
122
+ (operation.tool === 'app.addField' &&
123
+ ![
124
+ 'text',
125
+ 'long text',
126
+ 'number',
127
+ 'date',
128
+ 'date-time',
129
+ 'yes/no',
130
+ 'choice',
131
+ 'money',
132
+ ].includes(String(operation.args.kind))) ||
133
+ operation.args.expectedRevision !== catalog.revision + index)
134
+ return false;
135
+ const exact = lists.filter((list) => list.id === operation.args.list || list.label === operation.args.list);
136
+ const matches = exact.length
137
+ ? exact
138
+ : lists.filter((list) => list.synonyms.includes(String(operation.args.list)));
139
+ if (matches.length !== 1 ||
140
+ (target !== undefined && target !== matches[0].id))
141
+ return false;
142
+ target = matches[0].id;
143
+ if (operation.tool === 'app.renameList') {
144
+ if (typeof operation.args.label !== 'string' ||
145
+ lists.some((list) => list.id !== target && list.label === operation.args.label))
146
+ return false;
147
+ matches[0].label = operation.args.label;
148
+ }
149
+ }
150
+ return true;
151
+ }
152
+ /**
153
+ * Whether the run's current step is the one whose accepted proposal is
154
+ * applied: the last step, or an adaptive first step.
155
+ */
156
+ export function isCookbookApplyStep(state) {
157
+ if (state.phase !== 'check')
158
+ return false;
159
+ if (state.step.index === state.step.count)
160
+ return true;
161
+ return (state.step.index === 1 &&
162
+ smallOneListChange(readInput(state.input), state.pending));
163
+ }
164
+ function readExecution(value) {
165
+ if (!value || typeof value !== 'object')
166
+ return undefined;
167
+ const record = value;
168
+ if (typeof record.engine !== 'string' ||
169
+ !['api', 'chatgpt', 'claude-code', 'codex'].includes(record.engine) ||
170
+ (record.model !== undefined && typeof record.model !== 'string') ||
171
+ (record.effort !== undefined && !isReasoningEffort(record.effort)))
172
+ return undefined;
173
+ return {
174
+ engine: record.engine,
175
+ tier: typeof record.tier === 'string' &&
176
+ ['cheap', 'good', 'great', 'best'].includes(record.tier)
177
+ ? record.tier
178
+ : 'best',
179
+ ...(typeof record.model === 'string' ? { model: record.model } : {}),
180
+ ...(isReasoningEffort(record.effort) ? { effort: record.effort } : {}),
181
+ previewBeforeApply: record.previewBeforeApply !== false,
182
+ };
183
+ }
184
+ /** The validated run input. */
185
+ export function readInput(input) {
186
+ if (!input || typeof input !== 'object')
187
+ throw new Error('Invalid workflow input');
188
+ const value = input;
189
+ const execution = readExecution(value.execution);
190
+ if (typeof value.threadId !== 'string' ||
191
+ !value.threadId ||
192
+ typeof value.content !== 'string' ||
193
+ !value.content.trim() ||
194
+ !execution ||
195
+ !Array.isArray(value.permissions) ||
196
+ !value.permissions.every((permission) => typeof permission === 'string') ||
197
+ !value.schema ||
198
+ typeof value.schema !== 'object' ||
199
+ typeof value.schemaPin !== 'string')
200
+ throw new Error('Invalid workflow input');
201
+ return { ...value, execution };
202
+ }
203
+ const NOTES = {
204
+ running: 'I’m working through your request.',
205
+ checking: 'I’m checking the proposed changes.',
206
+ 'waiting-approval': 'Your changes are ready for your review.',
207
+ stopped: 'This work is paused.',
208
+ failed: 'I couldn’t finish this request. Please try again.',
209
+ done: 'This work is complete.',
210
+ };
211
+ /**
212
+ * Public progress is host-owned: model prose, checkpoint notes and error
213
+ * text stay private. Adaptive work shows one planned step until it expands.
214
+ */
215
+ export function presentCookbookWorkflowRun(state, needsInformation = false) {
216
+ const input = readInput(state.input);
217
+ const adaptive = !input.fixedSteps && !input.expanded;
218
+ const status = state.status === 'cancelled'
219
+ ? 'stopped'
220
+ : state.status === 'running' && state.phase === 'check'
221
+ ? 'checking'
222
+ : state.status;
223
+ return {
224
+ runId: state.id,
225
+ status,
226
+ step: {
227
+ index: state.step.index,
228
+ count: adaptive ? Math.max(1, state.step.index) : state.step.count,
229
+ name: state.step.index === 1
230
+ ? 'Planning your changes'
231
+ : 'Checking the proposed changes',
232
+ },
233
+ note: status === 'failed' && needsInformation
234
+ ? 'No changes were made. I need a little more information.'
235
+ : NOTES[status],
236
+ };
237
+ }
238
+ /**
239
+ * The cookbook change workflow on smrt-workflows (#4994, #5005): one
240
+ * `workflow` run per request, its steps run as named handler jobs with claim
241
+ * fencing, each step an assistant turn (a child run) over the registered
242
+ * step prompt, its output checked against the pinned schema and by the host
243
+ * check, which applies the accepted proposal through the core cookbook
244
+ * service and holds for the owner where the service requires it. Create it
245
+ * once per database at startup, BEFORE the host's task runner starts
246
+ * (creating it later throws); dispose it after the runner stops.
247
+ */
248
+ export function createCookbookWorkflowRuns(options) {
249
+ const budget = {
250
+ ...WORKFLOW_RUN_BUDGET,
251
+ ...options.budget,
252
+ };
253
+ if (!Number.isSafeInteger(budget.steps) ||
254
+ budget.steps < 1 ||
255
+ budget.steps > 64)
256
+ throw new Error('Workflow steps must be between 1 and 64');
257
+ const count = budget.steps;
258
+ const ajv = new Ajv({ strict: true, allErrors: true });
259
+ const validators = new Map();
260
+ const validatorFor = (input) => {
261
+ let validate = validators.get(input.schemaPin);
262
+ if (!validate) {
263
+ validate = ajv.compile(input.schema);
264
+ validators.set(input.schemaPin, validate);
265
+ }
266
+ return validate;
267
+ };
268
+ const liveSchema = async (ownerId, tenantId) => proposalSchema((await options.listOperations?.(ownerId, tenantId)) ?? []);
269
+ const assertSchemaPin = async (ownerId, tenantId, input) => {
270
+ if (fingerprint(await liveSchema(ownerId, tenantId)) !== input.schemaPin)
271
+ throw new Error('The change schema changed; start a new workflow run');
272
+ };
273
+ const stepOf = (index) => ({
274
+ name: index === 0 ? 'Propose the change' : 'Check and revise the change',
275
+ promptKey: COOKBOOK_CHANGE_STEP_PROMPT,
276
+ schema: outputSchema,
277
+ async execute(context) {
278
+ const run = await getAiRun(options.db, context.runId);
279
+ if (!run?.ownerId)
280
+ throw new Error('Workflow run not found');
281
+ const ownerId = run.ownerId;
282
+ const tenantId = run.tenantId ?? null;
283
+ await options.authorize(ownerId, tenantId);
284
+ const input = readInput(context.input);
285
+ await assertSchemaPin(ownerId, tenantId, input);
286
+ const prompt = await resolvePrompt(COOKBOOK_CHANGE_STEP_PROMPT, {
287
+ db: options.db,
288
+ tenantId,
289
+ variables: {
290
+ request: input.content,
291
+ step: String(context.step.index),
292
+ steps: String(context.step.count),
293
+ stage: index === 0 ? 'propose' : 'revise',
294
+ personGuidance: 'Keep personSummary short and plain for the person; put implementation reasoning in summary and checks, never in personSummary.',
295
+ schema: JSON.stringify(input.schema),
296
+ outputs: JSON.stringify(context.outputs),
297
+ repair: context.repair
298
+ ? `\nRepair this invalid output using the schema: ${JSON.stringify(context.repair)}`
299
+ : '',
300
+ },
301
+ });
302
+ try {
303
+ return await options.executeStep({
304
+ ownerId,
305
+ tenantId,
306
+ threadId: input.threadId,
307
+ content: input.content,
308
+ stage: index === 0 ? 'propose' : 'revise',
309
+ execution: input.execution,
310
+ permissions: input.permissions,
311
+ prompt,
312
+ schema: input.schema,
313
+ runContext: context.runContext,
314
+ step: context.step,
315
+ signal: context.signal,
316
+ });
317
+ }
318
+ catch (error) {
319
+ // The step's turn stopped because the workflow run stopped (a limit,
320
+ // a stop, a cancel): that is the run's stop, never a failed step.
321
+ const current = await getAiRun(options.db, context.runId);
322
+ if (current && current.status !== 'running')
323
+ throw aiRunStoppedError(current);
324
+ throw error;
325
+ }
326
+ },
327
+ check: (output, context) => check(index, output, context),
328
+ });
329
+ async function check(index, output, context) {
330
+ const run = await getAiRun(options.db, context.runId);
331
+ if (!run?.ownerId)
332
+ throw new Error('Workflow run not found');
333
+ const ownerId = run.ownerId;
334
+ const tenantId = run.tenantId ?? null;
335
+ const input = readInput(context.input);
336
+ // Mechanical validation is repeated after a crash before advancing.
337
+ if (!validatorFor(input)(output))
338
+ throw new Error('Stored workflow output failed validation');
339
+ await assertSchemaPin(ownerId, tenantId, input);
340
+ const plan = output;
341
+ const maximum = index === count - 1;
342
+ const previousCheck = (extra = {}) => ({
343
+ step: index + 1,
344
+ ready: plan.ready,
345
+ checked: true,
346
+ ...extra,
347
+ });
348
+ if (maximum && !plan.ready)
349
+ return { failure: NEEDS_INFORMATION };
350
+ const apply = maximum || (index === 0 && smallOneListChange(input, plan));
351
+ if (!apply || !plan.ready || !plan.operations.length)
352
+ return {
353
+ input: { ...input, expanded: true, previousCheck: previousCheck() },
354
+ };
355
+ if (!options.executeOperation)
356
+ throw new Error('Durable workflow application is unavailable');
357
+ await options.authorize(ownerId, tenantId);
358
+ await options.authorizeThread?.(ownerId, tenantId, input.threadId);
359
+ const results = [];
360
+ for (const [action, operation] of plan.operations.entries()) {
361
+ context.signal.throwIfAborted();
362
+ if (!input.permissions.includes(operation.tool))
363
+ throw new Error('Workflow operation is outside its original permission ceiling');
364
+ const result = await options.executeOperation({
365
+ ownerId,
366
+ tenantId,
367
+ threadId: input.threadId,
368
+ runId: context.runId,
369
+ actionId: String(action),
370
+ permissions: input.permissions,
371
+ operation: operation,
372
+ signal: context.signal,
373
+ });
374
+ if (result.status === 'approval_required') {
375
+ if (typeof result.approvalId !== 'string')
376
+ throw new Error('Workflow approval is unavailable');
377
+ // One hold per gated action: the step passes only once every
378
+ // action of the proposal applied (smrt-workflows counts the holds).
379
+ return {
380
+ waitingApproval: true,
381
+ holdRef: `approval:${result.approvalId}`,
382
+ note: result.summary,
383
+ input: {
384
+ ...input,
385
+ pendingApprovalId: result.approvalId,
386
+ previousCheck: previousCheck(),
387
+ results,
388
+ },
389
+ };
390
+ }
391
+ if (result.status !== 'ok') {
392
+ // These statuses are core planning questions before any hold or
393
+ // effect. Never replan after a receipt, an approval, or an
394
+ // uncertain throw.
395
+ if (!maximum &&
396
+ results.length === 0 &&
397
+ context.approvals === 0 &&
398
+ !input.pendingApprovalId &&
399
+ ['collision', 'clarification_required'].includes(result.status))
400
+ return {
401
+ input: {
402
+ ...input,
403
+ expanded: true,
404
+ previousCheck: previousCheck({ status: result.status }),
405
+ },
406
+ };
407
+ throw new Error(result.summary);
408
+ }
409
+ results.push(result);
410
+ }
411
+ const { pendingApprovalId: _settled, ...rest } = input;
412
+ return {
413
+ complete: true,
414
+ input: { ...rest, previousCheck: previousCheck(), results },
415
+ };
416
+ }
417
+ const definition = {
418
+ key: COOKBOOK_CHANGE_WORKFLOW,
419
+ // The step count is part of the definition: a run resumes only under
420
+ // the count that started it.
421
+ version: `1/steps-${count}`,
422
+ steps: Array.from({ length: count }, (_, index) => stepOf(index)),
423
+ };
424
+ const jobs = createWorkflowRunJobs({
425
+ db: options.db,
426
+ definition,
427
+ queue: 'default',
428
+ authorize: async (owner) => options.authorize(owner.ownerId, owner.tenantId),
429
+ resumeBudget: async (_owner, _state, proposed) => ({
430
+ ...proposed,
431
+ maxTokens: Math.min(proposed.maxTokens ?? budget.maxRunTokens, budget.maxRunTokens),
432
+ maxDurationMs: Math.min(proposed.maxDurationMs ?? budget.runTimeoutMs, budget.runTimeoutMs),
433
+ }),
434
+ configure: (owner, input) => {
435
+ // Every step validates against the schema pinned when the run started
436
+ // (the live owner's operation schemas then), also after a restart.
437
+ const validate = validatorFor(readInput(input));
438
+ return {
439
+ ai: createTrackedAiClient({
440
+ db: options.db,
441
+ tenantId: owner.tenantId,
442
+ }),
443
+ validate: (_schema, output) => validate(output)
444
+ ? []
445
+ : (validate.errors ?? []).map((error) => `${error.instancePath || '/'} ${error.message}`),
446
+ };
447
+ },
448
+ });
449
+ return {
450
+ budget,
451
+ definition,
452
+ /** Forget the definition; stop the task runner first. */
453
+ dispose: () => jobs.dispose(),
454
+ forOwner(ownerId, tenantId) {
455
+ const runs = jobs.forOwner(ownerId, tenantId);
456
+ const needsInformation = async (state) => {
457
+ if (state.status !== 'failed' || state.stopReason !== 'check_failed')
458
+ return false;
459
+ const checks = ((await getRunTrajectory(options.db, state.id))?.entries ?? [])
460
+ .map((entry) => entry.event)
461
+ .filter((event) => event?.type === 'check');
462
+ const last = checks.at(-1)?.payload;
463
+ return last?.failure === NEEDS_INFORMATION;
464
+ };
465
+ const present = async (state) => presentCookbookWorkflowRun(state, await needsInformation(state));
466
+ return {
467
+ present,
468
+ async start(input) {
469
+ await options.authorize(ownerId, tenantId);
470
+ const description = input.fixedSteps !== true
471
+ ? await options.describeApp?.(ownerId, tenantId)
472
+ : undefined;
473
+ const lists = Array.isArray(description?.lists) && description.lists.length <= 512
474
+ ? description.lists.flatMap((value) => {
475
+ if (!value || typeof value !== 'object')
476
+ return [];
477
+ const list = value;
478
+ return typeof list.id === 'string' &&
479
+ list.id.length <= 512 &&
480
+ typeof list.label === 'string' &&
481
+ list.label.length <= 120 &&
482
+ Array.isArray(list.synonyms) &&
483
+ list.synonyms.length <= 32 &&
484
+ list.synonyms.every((alias) => typeof alias === 'string' && alias.length <= 120)
485
+ ? [
486
+ {
487
+ id: list.id,
488
+ label: list.label,
489
+ synonyms: [...list.synonyms],
490
+ },
491
+ ]
492
+ : [];
493
+ })
494
+ : [];
495
+ // Never truncate away an ambiguous target: an incomplete bounded
496
+ // snapshot disables the adaptive finish for this run.
497
+ const listCatalog = description?.status === 'ok' &&
498
+ Number.isSafeInteger(description.revision) &&
499
+ Array.isArray(description.lists) &&
500
+ lists.length === description.lists.length
501
+ ? { revision: description.revision, lists }
502
+ : undefined;
503
+ const schema = await liveSchema(ownerId, tenantId);
504
+ const runInput = {
505
+ threadId: input.threadId,
506
+ content: input.content,
507
+ execution: input.execution,
508
+ permissions: [...(input.permissions ?? [])],
509
+ fixedSteps: input.fixedSteps === true,
510
+ ...(listCatalog ? { listCatalog } : {}),
511
+ schema,
512
+ schemaPin: fingerprint(schema),
513
+ };
514
+ readInput(runInput);
515
+ return runs.start({
516
+ key: randomUUID(),
517
+ input: runInput,
518
+ tags: { threadId: input.threadId },
519
+ budget: {
520
+ maxSteps: count,
521
+ maxTokens: budget.maxRunTokens,
522
+ maxDurationMs: budget.runTimeoutMs,
523
+ maxCallTokens: budget.maxTurnTokens,
524
+ callTimeoutMs: budget.turnTimeoutMs,
525
+ repairRetries: budget.repairRetries,
526
+ },
527
+ });
528
+ },
529
+ /** The newest run of a thread (of this owner's newest 100). */
530
+ async latest(threadId) {
531
+ await options.authorize(ownerId, tenantId);
532
+ const listed = await listAiRuns(options.db, {
533
+ type: 'workflow',
534
+ definitionKey: COOKBOOK_CHANGE_WORKFLOW,
535
+ tenantId,
536
+ limit: 100,
537
+ });
538
+ // Newest first; the owner and thread are on the run row itself.
539
+ for (const listedRun of listed) {
540
+ const run = await getAiRun(options.db, listedRun.id);
541
+ if (run?.ownerId === ownerId && run.tags.threadId === threadId)
542
+ return runs.get(run.id);
543
+ }
544
+ return null;
545
+ },
546
+ get: (id) => runs.get(id),
547
+ /**
548
+ * Check a saved action against the run's accepted proposal before
549
+ * the core service executes or replays it.
550
+ */
551
+ async validateAction(id, actionId, tool, args) {
552
+ const state = await runs.get(id);
553
+ const input = readInput(state.input);
554
+ const output = state.pending;
555
+ if (!isCookbookApplyStep(state) ||
556
+ !['waiting-approval', 'running', 'stopped'].includes(state.status) ||
557
+ !validatorFor(input)(output) ||
558
+ !output?.ready ||
559
+ !/^(0|[1-9]\d*)$/.test(actionId))
560
+ throw new Error('Saved workflow action changed');
561
+ await assertSchemaPin(ownerId, tenantId, input);
562
+ const operation = output.operations[Number(actionId)];
563
+ const desired = operation?.tool === 'cookbook.apply'
564
+ ? { ...operation.args, apply: true }
565
+ : operation?.args;
566
+ if (!operation ||
567
+ operation.tool !== tool ||
568
+ !input.permissions.includes(tool) ||
569
+ fingerprint(desired) !== fingerprint(args))
570
+ throw new Error('Saved workflow arguments changed');
571
+ await options.authorizeThread?.(ownerId, tenantId, input.threadId);
572
+ },
573
+ stop: (id) => runs.stop(id),
574
+ /**
575
+ * Resume a stopped run (raising its limits within the app's), or
576
+ * recover a run whose worker died.
577
+ */
578
+ async resume(id, raise) {
579
+ const state = await runs.get(id);
580
+ return state.status === 'running'
581
+ ? runs.resume(id)
582
+ : runs.resume(id, raise);
583
+ },
584
+ /**
585
+ * Carry an owner decision on the run's pending native hold into the
586
+ * run: approved (or approved and deferred while stopped) re-runs the
587
+ * check, which replays the held action once; denied, failed or
588
+ * expired fails the step. Harmless to repeat.
589
+ */
590
+ async settleHold(id, record) {
591
+ const state = await runs.get(id);
592
+ const pending = readInput(state.input).pendingApprovalId;
593
+ if (!record ||
594
+ record.id !== pending ||
595
+ !['waiting-approval', 'stopped'].includes(state.status))
596
+ return state;
597
+ const approved = ['approved', 'executing', 'succeeded'].includes(record.status);
598
+ const refused = ['denied', 'failed', 'expired'].includes(record.status);
599
+ if (!approved && !refused)
600
+ return state;
601
+ try {
602
+ return await runs.decide(id, { approved });
603
+ }
604
+ catch {
605
+ // Already decided (a repeated read): the run carries it.
606
+ return runs.get(id);
607
+ }
608
+ },
609
+ };
610
+ },
611
+ };
612
+ }
@@ -5,10 +5,10 @@ description: "Minimal SvelteKit project template with s-m-r-t framework integrat
5
5
  status: "stable"
6
6
  generated:
7
7
  by: "smrt/scripts/generate-knowledge-okf.ts"
8
- at: "2026-11-13T21:20:20Z"
8
+ at: "2026-11-16T07:01:04Z"
9
9
  audience: "internal"
10
10
  evidence_level: "source-inspected"
11
- source_revision: "sha256:718f91ad0fbb7d47d0f98df0aa4899244b5a36532e4fa028a7a443f0b8c00d3a"
11
+ source_revision: "sha256:1570c66c9340bcc8be717863bdc6c17b2d2b283d0a74a3c7d2378b042d212eab"
12
12
  sources:
13
13
  - id: "manifest"
14
14
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/template-sveltekit/package.json"
@@ -20,6 +20,9 @@ sources:
20
20
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/template-sveltekit/agents/cookbook-host.md"
21
21
  title: "@happyvertical/smrt-template-sveltekit packages/template-sveltekit/agents/cookbook-host.md"
22
22
  - id: "agents-3"
23
+ resource: "https://github.com/happyvertical/smrt/blob/main/packages/template-sveltekit/agents/cookbook-workflow-runs.md"
24
+ title: "@happyvertical/smrt-template-sveltekit packages/template-sveltekit/agents/cookbook-workflow-runs.md"
25
+ - id: "agents-4"
23
26
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/template-sveltekit/agents/m5-browser-gate.md"
24
27
  title: "@happyvertical/smrt-template-sveltekit packages/template-sveltekit/agents/m5-browser-gate.md"
25
28
  ---
@@ -37,6 +40,7 @@ sources:
37
40
 
38
41
  - `packages/template-sveltekit/AGENTS.md`
39
42
  - `packages/template-sveltekit/agents/cookbook-host.md`
43
+ - `packages/template-sveltekit/agents/cookbook-workflow-runs.md`
40
44
  - `packages/template-sveltekit/agents/m5-browser-gate.md`
41
45
 
42
46
  ## Framework dependencies
@@ -70,6 +74,7 @@ sources:
70
74
  - [smrt-ui](/components/smrt-ui.md)
71
75
  - [smrt-users](/components/smrt-users.md)
72
76
  - [smrt-web](/components/smrt-web.md)
77
+ - [smrt-workflows](/components/smrt-workflows.md)
73
78
 
74
79
  ## SDK dependencies
75
80