@happyvertical/smrt-template-sveltekit 0.61.6 → 0.62.1
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/agents/m5-browser-gate.md +4 -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 +47 -44
- 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/server.js
CHANGED
|
@@ -9,7 +9,7 @@ import { createOwnerLinkHandler, createSessionLayoutLoad, createSmrtSvelteKitRun
|
|
|
9
9
|
import { buildManifestToolCatalog, describeAssistantTool, invokeManifestTool, manifestToolToAITool, requiresOwnerApproval, } from '@happyvertical/smrt-chat';
|
|
10
10
|
import { readAssistantTurnStream } from '@happyvertical/smrt-chat/assistant-turn';
|
|
11
11
|
import { createAgentCliTurnDriver, createInferenceAssistantAdapters, } from '@happyvertical/smrt-chat/engines';
|
|
12
|
-
import { configuredAssistantAI, mountAssistantRoutes, resolveAssistantPrincipalFromLocals, } from '@happyvertical/smrt-chat/sveltekit';
|
|
12
|
+
import { configuredAssistantAI, mountAssistantRoutes, resolveAssistantPrincipalFromLocals, resolveChatAssistantTier, } from '@happyvertical/smrt-chat/sveltekit';
|
|
13
13
|
import { ObjectRegistry, toSnakeCase, withEmbeddedWriteTransaction, } from '@happyvertical/smrt-core';
|
|
14
14
|
import { createActivationCoordinator, } from '@happyvertical/smrt-core/activation';
|
|
15
15
|
import { cookbookModelCatalog, createAppModelEditor, createSqliteAppModelHistory, } from '@happyvertical/smrt-core/app-models';
|
|
@@ -19,19 +19,34 @@ import { resolveApiMethodExposure } from '@happyvertical/smrt-core/generators/cu
|
|
|
19
19
|
import { MCPGenerator, } from '@happyvertical/smrt-core/generators/mcp';
|
|
20
20
|
import { APIGenerator } from '@happyvertical/smrt-core/generators/rest';
|
|
21
21
|
import { createCookbookRuntimeExposure, filterRuntimeCookbookSnapshot, filterRuntimeExposure, isRuntimeModelEnabled, setRuntimeExposureGate, } from '@happyvertical/smrt-core/runtime-exposure';
|
|
22
|
-
import { createAgentCliService, createChatGPTPlanConnection,
|
|
22
|
+
import { createAgentCliService, createChatGPTPlanConnection, createInferenceSettingsController, createInferenceSettingsHost, engineTierModel, INFERENCE_PERMISSION_DEFINITIONS, inferencePreferenceKind, locateCli, nextEngineModel, resolveEngineEffort, tokenCredentials, } from '@happyvertical/smrt-inference/server';
|
|
23
23
|
import { TaskRunner } from '@happyvertical/smrt-jobs';
|
|
24
|
-
import { createPrebuiltComponentsPreference, createPreferenceStore,
|
|
24
|
+
import { createAssistantSettingsPreference, createPrebuiltComponentsPreference, createPreferenceStore, getPreferencePrincipal, registerPreferenceKind, } from '@happyvertical/smrt-preferences';
|
|
25
25
|
import { mountConnectAiRoutes } from '@happyvertical/smrt-svelte/connect-ai/server';
|
|
26
26
|
import { buildCookbookShell, catalogFromManifests, readInstalledManifests, } from '@happyvertical/smrt-svelte/cookbook/server';
|
|
27
27
|
import { applyShellLayout } from '@happyvertical/smrt-svelte/workspace/layout';
|
|
28
28
|
import { withTenant } from '@happyvertical/smrt-tenancy';
|
|
29
29
|
import { PermissionResolver, RolePermissionCollection, registerPermissionDefinitions, UserCollection, } from '@happyvertical/smrt-users';
|
|
30
30
|
import { error, redirect } from '@sveltejs/kit';
|
|
31
|
-
import { createCookbookDesignRuns, isCookbookDesignFinalCheck, presentCookbookDesignProgress, } from './design-runs.js';
|
|
32
31
|
import { createCookbookOnboarding } from './onboarding.js';
|
|
33
32
|
import { createPluginMode, PLUGIN_CLIENTS, PLUGIN_PERMISSION, } from './plugin-mode.js';
|
|
34
33
|
import { createCookbookHostState } from './state.js';
|
|
34
|
+
import { COOKBOOK_CHANGE_WORKFLOW, createCookbookWorkflowRuns, isCookbookApplyStep, readInput as readWorkflowInput, WORKFLOW_RUN_BUDGET, } from './workflow-runs.js';
|
|
35
|
+
/**
|
|
36
|
+
* The assistant turn's limits (#5005): its budget (stored on the turn's AI
|
|
37
|
+
* run, enforced by core and the loop) and the per-call output cap and kept
|
|
38
|
+
* tool result size, which stay loop options.
|
|
39
|
+
*/
|
|
40
|
+
const ASSISTANT_TURN_LIMITS = Object.freeze({
|
|
41
|
+
budget: Object.freeze({
|
|
42
|
+
maxSteps: 24,
|
|
43
|
+
maxTokens: 160_000,
|
|
44
|
+
maxDurationMs: 600_000,
|
|
45
|
+
callTimeoutMs: 180_000,
|
|
46
|
+
}),
|
|
47
|
+
maxTokens: 16_384,
|
|
48
|
+
toolResultChars: 40_000,
|
|
49
|
+
});
|
|
35
50
|
const describePublicAssistantTool = (name, _args, outcome) => describeAssistantTool(outcome ? name : 'change', undefined, outcome ? { ok: outcome.ok, observation: undefined } : undefined, { recordLabels: 'generic' });
|
|
36
51
|
// Only the core editor's bounded human command captions may become public.
|
|
37
52
|
// Labels containing implementation syntax fall back without altering the ledger.
|
|
@@ -151,10 +166,36 @@ export function createCookbookHost(options) {
|
|
|
151
166
|
let connection;
|
|
152
167
|
let current;
|
|
153
168
|
let starting;
|
|
154
|
-
|
|
169
|
+
/**
|
|
170
|
+
* The workflow step a detached assistant turn runs (#4994). Its turn is a
|
|
171
|
+
* child run of the workflow run (chat's internal turn `step`), so its
|
|
172
|
+
* calls count in the workflow's totals and budget; the turn's own budget
|
|
173
|
+
* holds its tool-loop steps and call timeout.
|
|
174
|
+
*/
|
|
175
|
+
const workflowSteps = new WeakMap();
|
|
176
|
+
const workflowBudget = {
|
|
177
|
+
...WORKFLOW_RUN_BUDGET,
|
|
178
|
+
...options.workflowBudget,
|
|
179
|
+
};
|
|
180
|
+
/** A workflow step turn's run budget, else the assistant turn's. */
|
|
181
|
+
const turnBudget = (context) => {
|
|
182
|
+
const step = workflowSteps.get(context.event.request);
|
|
183
|
+
return step
|
|
184
|
+
? {
|
|
185
|
+
maxSteps: step.limits.maxSteps,
|
|
186
|
+
callTimeoutMs: step.limits.callTimeoutMs,
|
|
187
|
+
}
|
|
188
|
+
: ASSISTANT_TURN_LIMITS.budget;
|
|
189
|
+
};
|
|
190
|
+
/** The turn's wall time: a workflow step's own, else the assistant budget's. */
|
|
191
|
+
const turnMaxMs = (context) => workflowSteps.get(context.event.request)?.limits.maxTurnMs ??
|
|
192
|
+
ASSISTANT_TURN_LIMITS.budget.maxDurationMs;
|
|
193
|
+
const toolResultChars = (context) => workflowSteps.has(context.event.request)
|
|
194
|
+
? workflowBudget.toolResultChars
|
|
195
|
+
: ASSISTANT_TURN_LIMITS.toolResultChars;
|
|
155
196
|
let origin;
|
|
156
197
|
let taskRunner;
|
|
157
|
-
let
|
|
198
|
+
let disposeWorkflowRuns;
|
|
158
199
|
const turns = new Map();
|
|
159
200
|
const digest = (token) => createHash('sha256').update(token).digest('hex');
|
|
160
201
|
const wireName = (slug) => toSnakeCase(slug).replace(/[^a-z0-9_]/g, '_');
|
|
@@ -196,44 +237,45 @@ export function createCookbookHost(options) {
|
|
|
196
237
|
store: createPreferenceStore({ db }),
|
|
197
238
|
isOwner: (p) => isOwner(p.tenantId, p.userId),
|
|
198
239
|
});
|
|
199
|
-
const
|
|
240
|
+
const assistantSettings = createAssistantSettingsPreference({
|
|
200
241
|
store: createPreferenceStore({ db }),
|
|
201
242
|
isOwner: (p) => isOwner(p.tenantId, p.userId),
|
|
202
243
|
});
|
|
203
|
-
|
|
204
|
-
|
|
244
|
+
/** A saved run, or null when it is not this owner's cookbook change run. */
|
|
245
|
+
async function savedWorkflowRun(ownerId, tenantId, runId) {
|
|
246
|
+
try {
|
|
247
|
+
const saved = await workflowRuns.forOwner(ownerId, tenantId).get(runId);
|
|
248
|
+
return saved.definitionKey === COOKBOOK_CHANGE_WORKFLOW ? saved : null;
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
async function restoredWorkflowContext(record) {
|
|
255
|
+
const action = record.context.workflowAction;
|
|
205
256
|
if (!action)
|
|
206
257
|
return {};
|
|
207
258
|
if (action.application !== (options.application ?? options.packageName) ||
|
|
208
259
|
typeof action.runId !== 'string' ||
|
|
209
260
|
typeof action.actionId !== 'string' ||
|
|
210
261
|
!/^(0|[1-9]\d*)$/.test(action.actionId))
|
|
211
|
-
throw new Error('Invalid saved
|
|
262
|
+
throw new Error('Invalid saved workflow action');
|
|
212
263
|
const user = await (await UserCollection.create({ db })).get({
|
|
213
264
|
id: record.requestedBy,
|
|
214
265
|
});
|
|
215
266
|
const principal = record.context.principal;
|
|
216
|
-
const saved = await
|
|
217
|
-
db,
|
|
218
|
-
ownerId: record.requestedBy,
|
|
219
|
-
tenantId: record.tenantId,
|
|
220
|
-
enqueue: async () => {
|
|
221
|
-
throw new Error('Read only');
|
|
222
|
-
},
|
|
223
|
-
}).load(action.runId, record.requestedBy);
|
|
267
|
+
const saved = await savedWorkflowRun(record.requestedBy, record.tenantId, action.runId);
|
|
224
268
|
if (!saved ||
|
|
225
|
-
!/^cookbook-design\/v[345]\//.test(saved.definition) ||
|
|
226
269
|
!user?.profileId ||
|
|
227
270
|
principal?.profileId !== user.profileId ||
|
|
228
|
-
saved.input.threadId !==
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
await
|
|
232
|
-
await designRuns
|
|
271
|
+
readWorkflowInput(saved.input).threadId !== record.context.threadId)
|
|
272
|
+
throw new Error('Saved workflow principal changed');
|
|
273
|
+
await authorizeWorkflowThread(record.requestedBy, record.tenantId, record.context.threadId);
|
|
274
|
+
await workflowRuns
|
|
233
275
|
.forOwner(record.requestedBy, record.tenantId)
|
|
234
276
|
.validateAction(action.runId, action.actionId, record.tool, record.args);
|
|
235
277
|
return {
|
|
236
|
-
|
|
278
|
+
workflowAction: {
|
|
237
279
|
application: action.application,
|
|
238
280
|
runId: action.runId,
|
|
239
281
|
actionId: action.actionId,
|
|
@@ -242,7 +284,7 @@ export function createCookbookHost(options) {
|
|
|
242
284
|
profileId: user.profileId,
|
|
243
285
|
};
|
|
244
286
|
}
|
|
245
|
-
async function
|
|
287
|
+
async function authorizeWorkflowThread(ownerId, tenantId, threadId) {
|
|
246
288
|
if (!tenantId)
|
|
247
289
|
throw new Error('Tenant required');
|
|
248
290
|
await runtime.runAsPrincipal({ id: ownerId, tenantId, kind: 'human' }, async (bound) => {
|
|
@@ -265,37 +307,28 @@ export function createCookbookHost(options) {
|
|
|
265
307
|
},
|
|
266
308
|
});
|
|
267
309
|
if (!response.ok)
|
|
268
|
-
throw new Error('
|
|
310
|
+
throw new Error('Workflow thread unavailable');
|
|
269
311
|
});
|
|
270
312
|
}
|
|
271
313
|
const continuations = new OwnerApprovalContinuations(authority, {
|
|
272
314
|
cookbook: async (record) => {
|
|
273
|
-
const action = record.context.
|
|
315
|
+
const action = record.context.workflowAction;
|
|
274
316
|
if (typeof action?.runId === 'string') {
|
|
275
|
-
const saved = await
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
tenantId: record.tenantId,
|
|
279
|
-
enqueue: async () => {
|
|
280
|
-
throw new Error('Read only');
|
|
281
|
-
},
|
|
282
|
-
}).load(action.runId, record.requestedBy);
|
|
283
|
-
// Native authority records the owner's decision normally. An
|
|
284
|
-
// executor-owned hold remains approved/unconsumed while Stop pauses
|
|
317
|
+
const saved = await savedWorkflowRun(record.requestedBy, record.tenantId, action.runId);
|
|
318
|
+
// Native authority records the owner's decision normally. A
|
|
319
|
+
// workflow-owned hold remains approved/unconsumed while Stop pauses
|
|
285
320
|
// effects; explicit Resume performs the same stable action.
|
|
286
|
-
if (saved?.status === 'stopped' &&
|
|
287
|
-
/^cookbook-design\/v[345]\//.test(saved.definition) &&
|
|
288
|
-
isCookbookDesignFinalCheck(saved))
|
|
321
|
+
if (saved?.status === 'stopped' && isCookbookApplyStep(saved))
|
|
289
322
|
return {
|
|
290
323
|
status: 'deferred',
|
|
291
|
-
summary: 'This
|
|
324
|
+
summary: 'This work is paused. Resume it to apply the approved change.',
|
|
292
325
|
};
|
|
293
326
|
}
|
|
294
327
|
return executeSaved(record, async () => service.invoke(record.tool, { ...record.args, approvalId: record.id }, {
|
|
295
328
|
surface: 'mcp',
|
|
296
329
|
tenantId: record.tenantId,
|
|
297
330
|
userId: record.requestedBy,
|
|
298
|
-
...(await
|
|
331
|
+
...(await restoredWorkflowContext(record)),
|
|
299
332
|
}));
|
|
300
333
|
},
|
|
301
334
|
model: async (record) => executeSaved(record, async (run) => {
|
|
@@ -355,20 +388,14 @@ export function createCookbookHost(options) {
|
|
|
355
388
|
},
|
|
356
389
|
approvals: continuations.adapter('cookbook'),
|
|
357
390
|
previewBeforeApply: async (context) => {
|
|
358
|
-
if (context.
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
throw new Error('Read only');
|
|
365
|
-
},
|
|
366
|
-
}).load(context.designAction.runId, context.userId);
|
|
367
|
-
return (saved?.input
|
|
368
|
-
?.profile?.previewBeforeApply !== false);
|
|
391
|
+
if (context.workflowAction && context.userId && context.tenantId) {
|
|
392
|
+
// The run's pinned setting, captured when it started.
|
|
393
|
+
const saved = await savedWorkflowRun(context.userId, context.tenantId, context.workflowAction.runId);
|
|
394
|
+
return saved
|
|
395
|
+
? readWorkflowInput(saved.input).execution.previewBeforeApply
|
|
396
|
+
: true;
|
|
369
397
|
}
|
|
370
|
-
return ((await
|
|
371
|
-
false);
|
|
398
|
+
return ((await assistantSettings.read()).settings.previewBeforeApply !== false);
|
|
372
399
|
},
|
|
373
400
|
isAppEmpty: async (context) => {
|
|
374
401
|
if (!context.initialSetup || !context.tenantId)
|
|
@@ -468,7 +495,7 @@ export function createCookbookHost(options) {
|
|
|
468
495
|
},
|
|
469
496
|
})
|
|
470
497
|
: undefined;
|
|
471
|
-
const
|
|
498
|
+
const describeWorkflowApp = async (ownerId, tenantId, optional = false) => {
|
|
472
499
|
if (!tenantId)
|
|
473
500
|
throw new Error('Tenant required');
|
|
474
501
|
return runtime.runAsPrincipal({ id: ownerId, tenantId, kind: 'human' }, async () => {
|
|
@@ -484,16 +511,12 @@ export function createCookbookHost(options) {
|
|
|
484
511
|
return service.invoke('app.describe', {}, { surface: 'mcp', tenantId, userId: ownerId });
|
|
485
512
|
});
|
|
486
513
|
};
|
|
487
|
-
|
|
514
|
+
// Registered before the task runner starts (it throws afterwards).
|
|
515
|
+
const workflowRuns = createCookbookWorkflowRuns({
|
|
488
516
|
db,
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
const result = await describeDesignApp(ownerId, tenantId);
|
|
493
|
-
if (!result || !Number.isSafeInteger(result.revision))
|
|
494
|
-
throw new Error('Application revision unavailable');
|
|
495
|
-
return result.revision;
|
|
496
|
-
},
|
|
517
|
+
...(options.workflowBudget ? { budget: options.workflowBudget } : {}),
|
|
518
|
+
authorizeThread: authorizeWorkflowThread,
|
|
519
|
+
describeApp: (ownerId, tenantId) => describeWorkflowApp(ownerId, tenantId, true),
|
|
497
520
|
authorize: async (ownerId, tenantId) => {
|
|
498
521
|
if (!(await isOwner(tenantId, ownerId)))
|
|
499
522
|
throw new Error('Owner required');
|
|
@@ -503,17 +526,17 @@ export function createCookbookHost(options) {
|
|
|
503
526
|
throw new Error('Tenant required');
|
|
504
527
|
return runtime.runAsPrincipal({ id: ownerId, tenantId, kind: 'human' }, async () => {
|
|
505
528
|
await prepare(tenantId, false);
|
|
506
|
-
return (await service.list({ surface: 'mcp', userId: ownerId, tenantId })).filter((tool) => service.
|
|
529
|
+
return (await service.list({ surface: 'mcp', userId: ownerId, tenantId })).filter((tool) => service.supportsWorkflowAction(tool.name));
|
|
507
530
|
});
|
|
508
531
|
},
|
|
509
532
|
executeOperation: async ({ ownerId, tenantId, threadId, runId, actionId, permissions, operation, signal, }) => {
|
|
510
533
|
if (!tenantId ||
|
|
511
534
|
!options.packageName ||
|
|
512
|
-
!service.
|
|
513
|
-
throw new Error('Durable
|
|
535
|
+
!service.supportsWorkflowAction(operation.tool))
|
|
536
|
+
throw new Error('Durable workflow operation unavailable');
|
|
514
537
|
return runtime.runAsPrincipal({ id: ownerId, tenantId, kind: 'human', scopes: [...permissions] }, async (bound) => {
|
|
515
538
|
await prepare(tenantId, false);
|
|
516
|
-
await
|
|
539
|
+
await authorizeWorkflowThread(ownerId, tenantId, threadId);
|
|
517
540
|
const user = await (await UserCollection.create({ db })).get({
|
|
518
541
|
id: ownerId,
|
|
519
542
|
});
|
|
@@ -533,7 +556,7 @@ export function createCookbookHost(options) {
|
|
|
533
556
|
run.assertToolAllowed(operation.tool);
|
|
534
557
|
const at = operation.tool.lastIndexOf('.');
|
|
535
558
|
await run.assertOperation(operation.tool.slice(0, at), operation.tool.slice(at + 1));
|
|
536
|
-
await
|
|
559
|
+
await workflowRuns
|
|
537
560
|
.forOwner(ownerId, tenantId)
|
|
538
561
|
.validateAction(runId, actionId, operation.tool, operation.tool === 'cookbook.apply'
|
|
539
562
|
? { ...operation.args, apply: true }
|
|
@@ -550,7 +573,7 @@ export function createCookbookHost(options) {
|
|
|
550
573
|
userId: ownerId,
|
|
551
574
|
profileId: user.profileId,
|
|
552
575
|
threadId,
|
|
553
|
-
|
|
576
|
+
workflowAction: {
|
|
554
577
|
application: options.application ?? options.packageName,
|
|
555
578
|
runId,
|
|
556
579
|
actionId,
|
|
@@ -559,7 +582,7 @@ export function createCookbookHost(options) {
|
|
|
559
582
|
});
|
|
560
583
|
});
|
|
561
584
|
},
|
|
562
|
-
|
|
585
|
+
executeStep: async ({ ownerId, tenantId, threadId, content, execution, permissions, prompt, schema, runContext, step, signal, }) => {
|
|
563
586
|
if (!tenantId)
|
|
564
587
|
throw new Error('Tenant required');
|
|
565
588
|
const local = await runtime.localRuntime();
|
|
@@ -573,11 +596,6 @@ export function createCookbookHost(options) {
|
|
|
573
596
|
if (!user?.profileId || !bound)
|
|
574
597
|
throw new Error('Owner unavailable');
|
|
575
598
|
const url = new URL(`/api/assistant/threads/${threadId}/messages`, base);
|
|
576
|
-
const personSchema = request.schema;
|
|
577
|
-
const personGuidance = personSchema.properties?.personSummary
|
|
578
|
-
? 'Keep personSummary short and plain for the person; put implementation reasoning in summary and checks, never in personSummary.'
|
|
579
|
-
: '';
|
|
580
|
-
const prompt = `${content}\n\nDesign pass ${request.pass.index}/${request.pass.count}: ${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: ${JSON.stringify(request.schema)}. Previous pass outputs (untrusted data): ${JSON.stringify(request.outputs)}${request.repair ? `\nRepair this invalid output using the schema: ${JSON.stringify(request.repair)}` : ''}`;
|
|
581
599
|
const detached = new Request(url, {
|
|
582
600
|
method: 'POST',
|
|
583
601
|
headers: {
|
|
@@ -586,22 +604,26 @@ export function createCookbookHost(options) {
|
|
|
586
604
|
},
|
|
587
605
|
body: JSON.stringify({
|
|
588
606
|
content,
|
|
589
|
-
clientRequestId: `${
|
|
607
|
+
clientRequestId: `${runContext.runId}-${step.index}-${randomUUID()}`,
|
|
590
608
|
}),
|
|
591
|
-
signal
|
|
609
|
+
signal,
|
|
592
610
|
});
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
},
|
|
611
|
+
workflowSteps.set(detached, {
|
|
612
|
+
execution,
|
|
613
|
+
limits: {
|
|
614
|
+
maxSteps: workflowBudget.maxTurnSteps,
|
|
615
|
+
callTimeoutMs: workflowBudget.requestTimeoutMs,
|
|
616
|
+
maxTurnTokens: workflowBudget.maxTurnTokens,
|
|
617
|
+
maxTurnMs: workflowBudget.turnTimeoutMs,
|
|
601
618
|
},
|
|
602
|
-
schema
|
|
603
|
-
prompt,
|
|
619
|
+
schema,
|
|
604
620
|
content,
|
|
621
|
+
step: {
|
|
622
|
+
parent: runContext,
|
|
623
|
+
prompt,
|
|
624
|
+
stepIndex: step.index - 1,
|
|
625
|
+
name: step.name,
|
|
626
|
+
},
|
|
605
627
|
});
|
|
606
628
|
const e = {
|
|
607
629
|
url,
|
|
@@ -616,25 +638,27 @@ export function createCookbookHost(options) {
|
|
|
616
638
|
try {
|
|
617
639
|
const response = await assistantRoutes.POST(e);
|
|
618
640
|
if (!response.ok)
|
|
619
|
-
throw new Error('The
|
|
641
|
+
throw new Error('The workflow step could not start');
|
|
620
642
|
const outcome = await readAssistantTurnStream(response, () => { });
|
|
621
643
|
const reply = outcome.done?.message;
|
|
622
|
-
if (!reply
|
|
623
|
-
throw new Error('
|
|
624
|
-
|
|
625
|
-
return { output, metadata: reply.metadata.workRun };
|
|
644
|
+
if (!reply)
|
|
645
|
+
throw new Error('The workflow step did not reply');
|
|
646
|
+
return reply.metadata?.workflowOutput ?? reply.content ?? '';
|
|
626
647
|
}
|
|
627
648
|
finally {
|
|
628
|
-
|
|
649
|
+
workflowSteps.delete(detached);
|
|
629
650
|
}
|
|
630
651
|
});
|
|
631
652
|
},
|
|
632
653
|
});
|
|
633
|
-
|
|
654
|
+
disposeWorkflowRuns = workflowRuns.dispose;
|
|
655
|
+
// Claim fencing: a workflow step's every save and reservation proves the
|
|
656
|
+
// worker still holds its job (smrt-workflows).
|
|
634
657
|
taskRunner = new TaskRunner({
|
|
635
658
|
concurrency: 1,
|
|
636
659
|
queues: ['default'],
|
|
637
660
|
retention: false,
|
|
661
|
+
claimFencing: true,
|
|
638
662
|
});
|
|
639
663
|
await taskRunner.initialize(db);
|
|
640
664
|
await taskRunner.start();
|
|
@@ -645,8 +669,8 @@ export function createCookbookHost(options) {
|
|
|
645
669
|
authority,
|
|
646
670
|
continuations,
|
|
647
671
|
preferences,
|
|
648
|
-
|
|
649
|
-
|
|
672
|
+
assistantSettings,
|
|
673
|
+
workflowRuns,
|
|
650
674
|
service,
|
|
651
675
|
gate,
|
|
652
676
|
};
|
|
@@ -669,7 +693,7 @@ export function createCookbookHost(options) {
|
|
|
669
693
|
}
|
|
670
694
|
finally {
|
|
671
695
|
stopped = true;
|
|
672
|
-
|
|
696
|
+
disposeWorkflowRuns?.();
|
|
673
697
|
}
|
|
674
698
|
})());
|
|
675
699
|
const onShutdown = () => {
|
|
@@ -743,12 +767,11 @@ export function createCookbookHost(options) {
|
|
|
743
767
|
continue;
|
|
744
768
|
try {
|
|
745
769
|
const outcome = await host.continuations.resume(owner, record.id);
|
|
746
|
-
const action = outcome.context.
|
|
747
|
-
if (
|
|
748
|
-
|
|
749
|
-
await host.designRuns
|
|
770
|
+
const action = outcome.context.workflowAction;
|
|
771
|
+
if (typeof action?.runId === 'string')
|
|
772
|
+
await host.workflowRuns
|
|
750
773
|
.forOwner(outcome.requestedBy, outcome.tenantId)
|
|
751
|
-
.
|
|
774
|
+
.settleHold(action.runId, outcome);
|
|
752
775
|
}
|
|
753
776
|
catch (error) {
|
|
754
777
|
// A concurrent claimant or a recorded refusal is already visible to the requester.
|
|
@@ -923,7 +946,7 @@ export function createCookbookHost(options) {
|
|
|
923
946
|
userId: context.principal.userId,
|
|
924
947
|
}))
|
|
925
948
|
.filter((tool) => !context.event ||
|
|
926
|
-
!
|
|
949
|
+
!workflowSteps.has(context.event.request) ||
|
|
927
950
|
tool.annotations?.readOnlyHint === true)
|
|
928
951
|
.map((tool) => ({
|
|
929
952
|
...tool,
|
|
@@ -990,85 +1013,85 @@ export function createCookbookHost(options) {
|
|
|
990
1013
|
context.event.locals.permissions);
|
|
991
1014
|
return [
|
|
992
1015
|
...tools
|
|
993
|
-
.filter((t) => !
|
|
1016
|
+
.filter((t) => !workflowSteps.has(context.event.request) || t.action === 'read')
|
|
994
1017
|
.map((t) => t.slug),
|
|
995
1018
|
...(await extra(context)).map((t) => t.slug),
|
|
996
1019
|
];
|
|
997
1020
|
};
|
|
998
1021
|
// Exactly the execution memo generation. Never key a fallback by its resolved model.
|
|
999
|
-
async function
|
|
1022
|
+
async function modelConnectionKey(tenantId, ownerId) {
|
|
1000
1023
|
const host = await ready();
|
|
1001
|
-
return `${(await cli.cliStatus('claude-code')).version ?? 'unknown'}:${await host.state.engineGeneration(tenantId, ownerId)}
|
|
1024
|
+
return `${(await cli.cliStatus('claude-code')).version ?? 'unknown'}:${await host.state.engineGeneration(tenantId, ownerId)}`;
|
|
1002
1025
|
}
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
:
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1026
|
+
/**
|
|
1027
|
+
* The model of a turn on `engine` at `tier` (#5005): an API key binds the
|
|
1028
|
+
* tier through core; Claude Code, Codex and a ChatGPT plan take their
|
|
1029
|
+
* default tier binding (inference `engineTierModel`). The effort is the
|
|
1030
|
+
* tier binding's, else the engine's default.
|
|
1031
|
+
*/
|
|
1032
|
+
async function engineSelection(engine, tier) {
|
|
1033
|
+
const model = engine === 'api'
|
|
1034
|
+
? undefined
|
|
1035
|
+
: engineTierModel({
|
|
1036
|
+
engine,
|
|
1037
|
+
tier,
|
|
1038
|
+
...(engine === 'chatgpt'
|
|
1039
|
+
? { catalog: await (await chatgpt()).models() }
|
|
1040
|
+
: {}),
|
|
1041
|
+
});
|
|
1042
|
+
if (engine !== 'api' && !model)
|
|
1043
|
+
throw new Error('The connected engine has no available model.');
|
|
1044
|
+
const effort = resolveEngineEffort({ tier });
|
|
1045
|
+
return {
|
|
1022
1046
|
engine,
|
|
1023
|
-
|
|
1024
|
-
...(
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1047
|
+
tier,
|
|
1048
|
+
...(model ? { model } : {}),
|
|
1049
|
+
...(effort ? { effort } : {}),
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
/** A workflow step keeps its run's pinned execution; any other turn asks for the assistant's tier. */
|
|
1053
|
+
async function resolveSelection(context) {
|
|
1054
|
+
const pinned = workflowSteps.get(context.event.request);
|
|
1055
|
+
if (pinned) {
|
|
1056
|
+
const { previewBeforeApply: _preview, ...selection } = pinned.execution;
|
|
1057
|
+
return selection;
|
|
1058
|
+
}
|
|
1059
|
+
const engine = (await (await ready()).state.engine(context.principal.tenantId, context.principal.userId)) ??
|
|
1060
|
+
'api';
|
|
1061
|
+
return engineSelection(engine, await resolveChatAssistantTier({
|
|
1062
|
+
db: await runtime.database(),
|
|
1063
|
+
tenantId: context.principal.tenantId,
|
|
1064
|
+
}));
|
|
1065
|
+
}
|
|
1066
|
+
/** A new workflow run's execution: the owner's engine at the assistant's tier. */
|
|
1067
|
+
async function workflowExecution(context) {
|
|
1068
|
+
const host = await ready();
|
|
1069
|
+
return {
|
|
1070
|
+
...(await resolveSelection(context)),
|
|
1071
|
+
previewBeforeApply: (await host.assistantSettings.read()).settings.previewBeforeApply !==
|
|
1072
|
+
false,
|
|
1073
|
+
};
|
|
1028
1074
|
}
|
|
1029
|
-
|
|
1075
|
+
/** The onboarding flow's requests go straight to a workflow run. */
|
|
1076
|
+
async function onboardingActive(context) {
|
|
1077
|
+
const host = await ready();
|
|
1078
|
+
const onboarding = host.onboarding
|
|
1079
|
+
? await host.onboarding.load(context.event)
|
|
1080
|
+
: null;
|
|
1081
|
+
return !!onboarding && (!onboarding.completed || onboarding.rerunning);
|
|
1082
|
+
}
|
|
1083
|
+
/** The owner's assistant settings, edited in the inference settings panel. */
|
|
1084
|
+
const assistantSettings = {
|
|
1030
1085
|
async read(event) {
|
|
1031
1086
|
const principal = resolveAssistantPrincipalFromLocals(event.locals);
|
|
1032
1087
|
if (!principal)
|
|
1033
1088
|
error(401, 'Sign in required');
|
|
1034
|
-
const saved = await (await ready()).
|
|
1035
|
-
const context = { event, principal };
|
|
1036
|
-
const engine = (await (await ready()).state.engine(principal.tenantId, principal.userId)) ?? 'api';
|
|
1037
|
-
const resolved = await Promise.all(['design', 'assist', 'background'].map(async (name) => {
|
|
1038
|
-
try {
|
|
1039
|
-
const profile = await resolveProfile(context, name);
|
|
1040
|
-
const projected = profile.engine === 'claude-code' &&
|
|
1041
|
-
profile.model &&
|
|
1042
|
-
['fable', 'opus'].includes(profile.model)
|
|
1043
|
-
? await projectWorkModelSelection({
|
|
1044
|
-
profile,
|
|
1045
|
-
ownerId: principal.userId,
|
|
1046
|
-
connectionKey: await workModelConnectionKey(principal.tenantId, principal.userId),
|
|
1047
|
-
store: (await ready()).state.fallbackStore(principal.tenantId),
|
|
1048
|
-
})
|
|
1049
|
-
: profile;
|
|
1050
|
-
return { ...projected, unavailable: false };
|
|
1051
|
-
}
|
|
1052
|
-
catch {
|
|
1053
|
-
const defaults = recommendedWorkProfile(name);
|
|
1054
|
-
const setting = saved.settings[name];
|
|
1055
|
-
return {
|
|
1056
|
-
...defaults,
|
|
1057
|
-
...setting,
|
|
1058
|
-
name,
|
|
1059
|
-
engine: setting?.engine ?? engine,
|
|
1060
|
-
tier: name === 'background' ? 'cheap' : 'best',
|
|
1061
|
-
budgets: { ...defaults.budgets, ...setting?.budgets },
|
|
1062
|
-
unavailable: true,
|
|
1063
|
-
};
|
|
1064
|
-
}
|
|
1065
|
-
}));
|
|
1089
|
+
const saved = await (await ready()).assistantSettings.read();
|
|
1066
1090
|
return {
|
|
1067
|
-
|
|
1068
|
-
|
|
1091
|
+
settings: saved.settings,
|
|
1092
|
+
revision: saved.revision,
|
|
1069
1093
|
editable: typeof event.locals.sessionId === 'string' &&
|
|
1070
1094
|
(await isOwner(principal.tenantId, principal.userId)),
|
|
1071
|
-
chatgptSignedIn: (await (await chatgpt()).status()).signedIn,
|
|
1072
1095
|
};
|
|
1073
1096
|
},
|
|
1074
1097
|
async write(event, payload) {
|
|
@@ -1082,7 +1105,7 @@ export function createCookbookHost(options) {
|
|
|
1082
1105
|
!(payload.revision === null || typeof payload.revision === 'string'))
|
|
1083
1106
|
error(400, 'Invalid settings');
|
|
1084
1107
|
try {
|
|
1085
|
-
return await (await ready()).
|
|
1108
|
+
return await (await ready()).assistantSettings.write(payload.settings, payload.revision, { confirmUnprotectedCli: payload.confirmUnprotectedCli === true });
|
|
1086
1109
|
}
|
|
1087
1110
|
catch (cause) {
|
|
1088
1111
|
if (cause instanceof Error && cause.name === 'PreferenceAccessError')
|
|
@@ -1098,7 +1121,7 @@ export function createCookbookHost(options) {
|
|
|
1098
1121
|
error(403, 'Owner required');
|
|
1099
1122
|
if (!(revision === null || typeof revision === 'string'))
|
|
1100
1123
|
error(400, 'Invalid revision');
|
|
1101
|
-
return (await ready()).
|
|
1124
|
+
return (await ready()).assistantSettings.reset(revision);
|
|
1102
1125
|
},
|
|
1103
1126
|
};
|
|
1104
1127
|
const adapters = createInferenceAssistantAdapters({
|
|
@@ -1107,8 +1130,8 @@ export function createCookbookHost(options) {
|
|
|
1107
1130
|
.then((v) => v ?? undefined),
|
|
1108
1131
|
status: async (c) => ({
|
|
1109
1132
|
cliStatus: async (tool) => cli.cliStatus(tool, {
|
|
1110
|
-
protection: (await (await ready()).
|
|
1111
|
-
|
|
1133
|
+
protection: (await (await ready()).assistantSettings.read()).settings
|
|
1134
|
+
.protectLocalCli !== false,
|
|
1112
1135
|
}),
|
|
1113
1136
|
chatgpt: { status: async () => (await chatgpt()).status() },
|
|
1114
1137
|
apiStatus: () => apiStatus(c),
|
|
@@ -1118,7 +1141,7 @@ export function createCookbookHost(options) {
|
|
|
1118
1141
|
connection: await chatgpt(),
|
|
1119
1142
|
fallback: {
|
|
1120
1143
|
ownerId: context.principal.userId,
|
|
1121
|
-
connectionKey: `chatgpt:${JSON.stringify(await (await chatgpt()).models())}:${await (await ready()).state.engineGeneration(context.principal.tenantId, context.principal.userId)}
|
|
1144
|
+
connectionKey: `chatgpt:${JSON.stringify(await (await chatgpt()).models())}:${await (await ready()).state.engineGeneration(context.principal.tenantId, context.principal.userId)}`,
|
|
1122
1145
|
store: (await ready()).state.fallbackStore(context.principal.tenantId),
|
|
1123
1146
|
},
|
|
1124
1147
|
toolNamespace: { name: 'smrt_app', description: 'Work with this app' },
|
|
@@ -1152,33 +1175,34 @@ export function createCookbookHost(options) {
|
|
|
1152
1175
|
label: 'Assistant turn',
|
|
1153
1176
|
});
|
|
1154
1177
|
return {
|
|
1155
|
-
protection: (await host.
|
|
1156
|
-
|
|
1178
|
+
protection: (await host.assistantSettings.read()).settings.protectLocalCli !==
|
|
1179
|
+
false,
|
|
1157
1180
|
mcpUrl: new URL('/mcp', context.event.url).href,
|
|
1158
|
-
...(
|
|
1181
|
+
...(workflowSteps.get(context.event.request)
|
|
1159
1182
|
? {
|
|
1160
|
-
outputSchema:
|
|
1183
|
+
outputSchema: workflowSteps.get(context.event.request)
|
|
1161
1184
|
.schema,
|
|
1162
1185
|
}
|
|
1163
1186
|
: {}),
|
|
1164
|
-
...(turn.
|
|
1165
|
-
(
|
|
1166
|
-
['fable', 'opus'].includes(turn.workProfile.model)) ||
|
|
1167
|
-
(tool === 'codex' &&
|
|
1168
|
-
nextWorkModel(rankOpenAIWorkModels(Object.keys(OPENAI_WORK_MODEL_RANKS).map((id) => ({ id }))), turn.workProfile.model)))
|
|
1187
|
+
...(turn.selection?.model &&
|
|
1188
|
+
nextEngineModel({ engine: tool, model: turn.selection.model })
|
|
1169
1189
|
? {
|
|
1170
1190
|
fallback: {
|
|
1171
1191
|
ownerId: context.principal.userId,
|
|
1172
|
-
connectionKey: await
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1192
|
+
connectionKey: await modelConnectionKey(context.principal.tenantId, context.principal.userId),
|
|
1193
|
+
// One step down the engine's tier binding order.
|
|
1194
|
+
nextModel: nextEngineModel({
|
|
1195
|
+
engine: tool,
|
|
1196
|
+
model: turn.selection.model,
|
|
1197
|
+
}),
|
|
1178
1198
|
store: host.state.fallbackStore(context.principal.tenantId),
|
|
1179
1199
|
},
|
|
1180
1200
|
}
|
|
1181
1201
|
: {}),
|
|
1202
|
+
limits: {
|
|
1203
|
+
turnTimeoutMs: turnBudget(context).callTimeoutMs,
|
|
1204
|
+
toolResultChars: toolResultChars(context),
|
|
1205
|
+
},
|
|
1182
1206
|
canonicalToolName: (name) => names.get(name),
|
|
1183
1207
|
describeTool: (name, args, outcome) => {
|
|
1184
1208
|
const model = models.find((entry) => entry.slug === name);
|
|
@@ -1307,34 +1331,45 @@ export function createCookbookHost(options) {
|
|
|
1307
1331
|
: null;
|
|
1308
1332
|
},
|
|
1309
1333
|
...adapters,
|
|
1310
|
-
|
|
1334
|
+
resolveSelection,
|
|
1335
|
+
assistantSettings: async () => (await (await ready()).assistantSettings.read()).settings,
|
|
1336
|
+
turnBudget: (context) => turnBudget(context),
|
|
1337
|
+
maxTurnTokens: (context) => workflowSteps.get(context.event.request)?.limits.maxTurnTokens,
|
|
1338
|
+
maxTurnMs: (context) => workflowSteps.get(context.event.request)?.limits.maxTurnMs,
|
|
1339
|
+
toolResultChars: (context) => toolResultChars(context),
|
|
1340
|
+
maxTokens: (context) => workflowSteps.has(context.event.request)
|
|
1341
|
+
? workflowBudget.maxTokens
|
|
1342
|
+
: ASSISTANT_TURN_LIMITS.maxTokens,
|
|
1343
|
+
// A workflow step's turn runs as a child run of the workflow run, under
|
|
1344
|
+
// the step's registered prompt.
|
|
1311
1345
|
internalTurn: (context) => {
|
|
1312
|
-
const
|
|
1313
|
-
return
|
|
1346
|
+
const step = workflowSteps.get(context.event.request);
|
|
1347
|
+
return step ? { userMessage: step.content, step: step.step } : undefined;
|
|
1314
1348
|
},
|
|
1315
|
-
|
|
1316
|
-
|
|
1349
|
+
// Onboarding asks for a change straight away: a workflow run, before any
|
|
1350
|
+
// model call. A workflow step itself never defers.
|
|
1351
|
+
deferWorkflowTurn: async (context) => !workflowSteps.has(context.event.request) &&
|
|
1352
|
+
(await onboardingActive(context)),
|
|
1353
|
+
onWorkflowEscalation: async (context, input) => {
|
|
1317
1354
|
const original = input.userMessage ??
|
|
1318
1355
|
[...(input.history ?? [])]
|
|
1319
1356
|
.reverse()
|
|
1320
1357
|
.find((message) => message.role === 'user')?.content;
|
|
1321
1358
|
if (!input.thread?.id || typeof original !== 'string' || !original.trim())
|
|
1322
|
-
throw new Error('
|
|
1359
|
+
throw new Error('Workflow runs require a saved thread and user request');
|
|
1323
1360
|
const host = await ready();
|
|
1324
|
-
const
|
|
1325
|
-
const fixedPasses = Object.hasOwn((await host.workProfiles.read()).settings.design?.budgets ?? {}, 'passes');
|
|
1326
|
-
const state = await host.designRuns
|
|
1361
|
+
const state = await host.workflowRuns
|
|
1327
1362
|
.forOwner(context.principal.userId, context.principal.tenantId)
|
|
1328
1363
|
.start({
|
|
1329
1364
|
threadId: String(input.thread.id),
|
|
1330
1365
|
content: original,
|
|
1331
|
-
|
|
1332
|
-
|
|
1366
|
+
execution: await workflowExecution(context),
|
|
1367
|
+
fixedSteps: Object.hasOwn(options.workflowBudget ?? {}, 'steps'),
|
|
1333
1368
|
permissions: [...(context.principal.permissions ?? [])],
|
|
1334
1369
|
});
|
|
1335
1370
|
return { runId: state.id, message: 'Thinking this through' };
|
|
1336
1371
|
},
|
|
1337
|
-
|
|
1372
|
+
workflowTools: COOKBOOK_TOOL_NAMES.filter((name) => /^(recipes\.(enable|disable|configure)|cookbook\.apply|app\.(add|remove|rename|hide))/.test(name)),
|
|
1338
1373
|
allowedTools: allowed,
|
|
1339
1374
|
tools: (context) => manifest(context.principal.tenantId, context.principal.userId, context.principal.permissions ??
|
|
1340
1375
|
context.event.locals.permissions),
|
|
@@ -1342,8 +1377,8 @@ export function createCookbookHost(options) {
|
|
|
1342
1377
|
approvalContinuations: async () => (await ready()).continuations,
|
|
1343
1378
|
// These tools hold in their own canonical service; never create a second chat hold.
|
|
1344
1379
|
approvalPolicy: async () => ({
|
|
1345
|
-
allowRemovalsInChat: (await (await ready()).
|
|
1346
|
-
|
|
1380
|
+
allowRemovalsInChat: (await (await ready()).assistantSettings.read()).settings
|
|
1381
|
+
.requireRemovalApproval === false,
|
|
1347
1382
|
tools: Object.fromEntries(COOKBOOK_TOOL_NAMES.map((name) => [name, false])),
|
|
1348
1383
|
}),
|
|
1349
1384
|
...options.assistant,
|
|
@@ -1426,11 +1461,11 @@ export function createCookbookHost(options) {
|
|
|
1426
1461
|
? await base(context)
|
|
1427
1462
|
: (base ??
|
|
1428
1463
|
"Help the owner work with their business records and installed recipes. Use only the provided tools and their inline inputs. Claim an operation only when it is offered for that list. When deletion is absent, explain the available update or custom actions from that list's tool schemas instead; never invent a delete operation or require the person to manage internal identity records.");
|
|
1429
|
-
|
|
1430
|
-
return
|
|
1464
|
+
// A workflow step's registered prompt follows this text (chat adds it).
|
|
1465
|
+
return prompt;
|
|
1431
1466
|
},
|
|
1432
1467
|
formatAssistantReply: (content, context) => {
|
|
1433
|
-
if (!
|
|
1468
|
+
if (!workflowSteps.has(context.event.request))
|
|
1434
1469
|
return { content };
|
|
1435
1470
|
let output;
|
|
1436
1471
|
try {
|
|
@@ -1441,45 +1476,28 @@ export function createCookbookHost(options) {
|
|
|
1441
1476
|
}
|
|
1442
1477
|
return {
|
|
1443
1478
|
content: 'I’m checking the requested changes.',
|
|
1444
|
-
metadata: {
|
|
1479
|
+
metadata: { workflowOutput: output },
|
|
1445
1480
|
};
|
|
1446
1481
|
},
|
|
1447
1482
|
});
|
|
1448
|
-
const designProgress = (state) => state
|
|
1449
|
-
? presentCookbookDesignProgress({
|
|
1450
|
-
runId: state.id,
|
|
1451
|
-
pass: {
|
|
1452
|
-
index: Math.min(state.passIndex + 1, Number(state.definition.split('/').at(-1))),
|
|
1453
|
-
count: Number(state.definition.split('/').at(-1)),
|
|
1454
|
-
name: state.passIndex === 0
|
|
1455
|
-
? 'Understand the request'
|
|
1456
|
-
: state.passIndex === 1
|
|
1457
|
-
? 'Propose the design'
|
|
1458
|
-
: 'Check and revise the design',
|
|
1459
|
-
},
|
|
1460
|
-
status: state.status,
|
|
1461
|
-
...(state.note ? { note: state.note } : {}),
|
|
1462
|
-
}, state)
|
|
1463
|
-
: null;
|
|
1464
1483
|
const assistantHandler = async (event) => {
|
|
1465
1484
|
const path = event.params?.path ?? '';
|
|
1466
|
-
if (!path.startsWith('
|
|
1485
|
+
if (!path.startsWith('runs')) {
|
|
1467
1486
|
const response = await assistantRoutes.handle(event);
|
|
1468
1487
|
const decision = /^approvals\/([^/]+)\/decide$/.exec(path);
|
|
1469
1488
|
const actor = resolveAssistantPrincipalFromLocals(event.locals);
|
|
1470
1489
|
if (response.ok && decision && event.request.method === 'POST' && actor) {
|
|
1471
1490
|
const host = await ready();
|
|
1472
1491
|
const record = await host.authority.get(actor.tenantId, decision[1]);
|
|
1473
|
-
const action = record?.context.
|
|
1474
|
-
if (record &&
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
//
|
|
1478
|
-
// check; a status read can retry admission after a transient conflict.
|
|
1492
|
+
const action = record?.context.workflowAction;
|
|
1493
|
+
if (record && typeof action?.runId === 'string') {
|
|
1494
|
+
// The native decision is already durable. Carry it into the run
|
|
1495
|
+
// (an approval re-runs the step's check, which replays the held
|
|
1496
|
+
// action once); a status read retries after a transient conflict.
|
|
1479
1497
|
try {
|
|
1480
|
-
await host.
|
|
1498
|
+
await host.workflowRuns
|
|
1481
1499
|
.forOwner(record.requestedBy, record.tenantId)
|
|
1482
|
-
.
|
|
1500
|
+
.settleHold(action.runId, record);
|
|
1483
1501
|
}
|
|
1484
1502
|
catch {
|
|
1485
1503
|
/* durable hold/outcome remains available */
|
|
@@ -1491,20 +1509,17 @@ export function createCookbookHost(options) {
|
|
|
1491
1509
|
const p = resolveAssistantPrincipalFromLocals(event.locals);
|
|
1492
1510
|
if (!p || !(await isOwner(p.tenantId, p.userId)))
|
|
1493
1511
|
return json({ code: 'not_allowed' }, 403);
|
|
1494
|
-
const runs = (await ready()).
|
|
1512
|
+
const runs = (await ready()).workflowRuns.forOwner(p.userId, p.tenantId);
|
|
1495
1513
|
try {
|
|
1496
|
-
if (path === '
|
|
1514
|
+
if (path === 'runs' && event.request.method === 'GET') {
|
|
1497
1515
|
const threadId = event.url.searchParams.get('threadId');
|
|
1498
1516
|
let state = threadId ? await runs.latest(threadId) : null;
|
|
1499
|
-
const pending = state
|
|
1500
|
-
|
|
1501
|
-
if (state?.status === 'waiting-approval' &&
|
|
1502
|
-
typeof pending === 'string') {
|
|
1517
|
+
const pending = state && readWorkflowInput(state.input).pendingApprovalId;
|
|
1518
|
+
if (state?.status === 'waiting-approval' && pending) {
|
|
1503
1519
|
const record = await (await ready()).authority.get(p.tenantId, pending);
|
|
1504
|
-
if (record?.requestedBy === p.userId
|
|
1505
|
-
['succeeded', 'denied', 'failed', 'expired'].includes(record.status)) {
|
|
1520
|
+
if (record?.requestedBy === p.userId) {
|
|
1506
1521
|
try {
|
|
1507
|
-
state = await runs.
|
|
1522
|
+
state = await runs.settleHold(state.id, record);
|
|
1508
1523
|
}
|
|
1509
1524
|
catch {
|
|
1510
1525
|
/* retry on next status read */
|
|
@@ -1512,14 +1527,14 @@ export function createCookbookHost(options) {
|
|
|
1512
1527
|
}
|
|
1513
1528
|
}
|
|
1514
1529
|
return json({
|
|
1515
|
-
run:
|
|
1530
|
+
run: state ? await runs.present(state) : null,
|
|
1516
1531
|
});
|
|
1517
1532
|
}
|
|
1518
|
-
if (path === '
|
|
1533
|
+
if (path === 'runs' && event.request.method === 'POST') {
|
|
1519
1534
|
if (event.request.headers.get('origin') !== event.url.origin)
|
|
1520
1535
|
return json({ code: 'invalid_origin' }, 403);
|
|
1521
1536
|
if (!/^application\/json\b/i.test(event.request.headers.get('content-type') ?? ''))
|
|
1522
|
-
return json({ code: '
|
|
1537
|
+
return json({ code: 'invalid_workflow_request' }, 415);
|
|
1523
1538
|
// Chat's bounded JSON reader is private; keep this route's small bound
|
|
1524
1539
|
// at its own request boundary rather than buffering an unbounded body.
|
|
1525
1540
|
const maxBytes = 128 * 1024;
|
|
@@ -1548,7 +1563,7 @@ export function createCookbookHost(options) {
|
|
|
1548
1563
|
body = parsed;
|
|
1549
1564
|
}
|
|
1550
1565
|
catch {
|
|
1551
|
-
return json({ code: '
|
|
1566
|
+
return json({ code: 'invalid_workflow_request' }, 400);
|
|
1552
1567
|
}
|
|
1553
1568
|
if (!body ||
|
|
1554
1569
|
typeof body !== 'object' ||
|
|
@@ -1560,7 +1575,7 @@ export function createCookbookHost(options) {
|
|
|
1560
1575
|
typeof body.content !== 'string' ||
|
|
1561
1576
|
!body.content.trim() ||
|
|
1562
1577
|
body.content.length > 32_000)
|
|
1563
|
-
return json({ code: '
|
|
1578
|
+
return json({ code: 'invalid_workflow_request' }, 400);
|
|
1564
1579
|
// Reuse chat's own session/thread ownership boundary before admission.
|
|
1565
1580
|
const thread = await assistantRoutes.GET({
|
|
1566
1581
|
...event,
|
|
@@ -1575,43 +1590,40 @@ export function createCookbookHost(options) {
|
|
|
1575
1590
|
});
|
|
1576
1591
|
if (!thread.ok)
|
|
1577
1592
|
return thread;
|
|
1578
|
-
const profile = await resolveProfile({ event, principal: p }, 'design');
|
|
1579
1593
|
const state = await runs.start({
|
|
1580
1594
|
threadId: body.threadId,
|
|
1581
1595
|
content: body.content,
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1596
|
+
execution: await workflowExecution({
|
|
1597
|
+
event,
|
|
1598
|
+
principal: p,
|
|
1599
|
+
}),
|
|
1600
|
+
fixedSteps: Object.hasOwn(options.workflowBudget ?? {}, 'steps'),
|
|
1585
1601
|
permissions: [
|
|
1586
1602
|
...(p.permissions ??
|
|
1587
1603
|
event.locals.permissions ??
|
|
1588
1604
|
[]),
|
|
1589
1605
|
],
|
|
1590
1606
|
});
|
|
1591
|
-
return json({ run:
|
|
1607
|
+
return json({ run: await runs.present(state) }, 202);
|
|
1592
1608
|
}
|
|
1593
|
-
const match = /^
|
|
1609
|
+
const match = /^runs\/([^/]+)\/(stop|resume)$/.exec(path);
|
|
1594
1610
|
if (!match || event.request.method !== 'POST')
|
|
1595
1611
|
return json({ code: 'not_found' }, 404);
|
|
1596
1612
|
if (event.request.headers.get('origin') !== event.url.origin)
|
|
1597
1613
|
return json({ code: 'invalid_origin' }, 403);
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
...saved.settings.design?.budgets,
|
|
1602
|
-
};
|
|
1603
|
-
// Explicit Resume adopts the owner's current aggregate allowances, without
|
|
1604
|
-
// resetting usage or changing the run's pinned engine, model or passes.
|
|
1614
|
+
// Explicit Resume adopts the workflow definition's allowances, without
|
|
1615
|
+
// resetting usage or changing the run's pinned engine, model or steps;
|
|
1616
|
+
// a run whose worker died is recovered instead.
|
|
1605
1617
|
const state = match[2] === 'stop'
|
|
1606
1618
|
? await runs.stop(match[1])
|
|
1607
1619
|
: await runs.resume(match[1], {
|
|
1608
|
-
maxTokens:
|
|
1609
|
-
maxDurationMs:
|
|
1620
|
+
maxTokens: workflowBudget.maxRunTokens,
|
|
1621
|
+
maxDurationMs: workflowBudget.runTimeoutMs,
|
|
1610
1622
|
});
|
|
1611
|
-
return json({ run:
|
|
1623
|
+
return json({ run: await runs.present(state) });
|
|
1612
1624
|
}
|
|
1613
1625
|
catch {
|
|
1614
|
-
return json({ code: '
|
|
1626
|
+
return json({ code: 'workflow_run_unavailable' }, 409);
|
|
1615
1627
|
}
|
|
1616
1628
|
};
|
|
1617
1629
|
const assistant = { ...assistantRoutes, handle: assistantHandler };
|
|
@@ -1830,8 +1842,8 @@ export function createCookbookHost(options) {
|
|
|
1830
1842
|
...cli,
|
|
1831
1843
|
cliStatus: async (tool, statusOptions) => runtime.runAsPrincipal({ id: principal.userId, tenantId: principal.tenantId }, async () => cli.cliStatus(tool, {
|
|
1832
1844
|
...statusOptions,
|
|
1833
|
-
protection: (await host.
|
|
1834
|
-
|
|
1845
|
+
protection: (await host.assistantSettings.read()).settings
|
|
1846
|
+
.protectLocalCli !== false,
|
|
1835
1847
|
})),
|
|
1836
1848
|
},
|
|
1837
1849
|
chatgpt: await chatgpt(),
|
|
@@ -1851,7 +1863,7 @@ export function createCookbookHost(options) {
|
|
|
1851
1863
|
connectAi,
|
|
1852
1864
|
pluginMode: pluginMode.handle,
|
|
1853
1865
|
inferenceSettings,
|
|
1854
|
-
|
|
1866
|
+
assistantSettings,
|
|
1855
1867
|
async history(event) {
|
|
1856
1868
|
if (event.request.method !== 'GET')
|
|
1857
1869
|
return json({ code: 'method_not_allowed' }, 405);
|
|
@@ -2149,9 +2161,9 @@ export function createCookbookHost(options) {
|
|
|
2149
2161
|
? 'read'
|
|
2150
2162
|
: 'write',
|
|
2151
2163
|
...(spec.annotations &&
|
|
2152
|
-
'
|
|
2153
|
-
spec.annotations.
|
|
2154
|
-
? { metadata: {
|
|
2164
|
+
'runTypes' in spec.annotations &&
|
|
2165
|
+
Array.isArray(spec.annotations.runTypes)
|
|
2166
|
+
? { metadata: { runTypes: [...spec.annotations.runTypes] } }
|
|
2155
2167
|
: {}),
|
|
2156
2168
|
idempotent: spec.annotations?.idempotentHint === true,
|
|
2157
2169
|
openWorld: spec.annotations?.openWorldHint === true,
|
|
@@ -2166,24 +2178,24 @@ export function createCookbookHost(options) {
|
|
|
2166
2178
|
throw new Error('Principal changed');
|
|
2167
2179
|
binding?.turn.beforeToolExecution(spec.slug);
|
|
2168
2180
|
if (binding) {
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
(binding.
|
|
2172
|
-
|
|
2173
|
-
throw new Error('This
|
|
2174
|
-
if (
|
|
2181
|
+
if (binding.toolCalls >=
|
|
2182
|
+
turnBudget(binding.context).maxSteps ||
|
|
2183
|
+
Date.now() - binding.startedAt >=
|
|
2184
|
+
turnMaxMs(binding.context))
|
|
2185
|
+
throw new Error('This step has reached its tool or time limit');
|
|
2186
|
+
if (workflowSteps.has(binding.context.event.request) &&
|
|
2175
2187
|
spec.annotations?.readOnlyHint !== true)
|
|
2176
|
-
throw new Error('
|
|
2188
|
+
throw new Error('Workflow steps can only read and propose');
|
|
2177
2189
|
binding.toolCalls += 1;
|
|
2178
2190
|
}
|
|
2179
2191
|
const tool = spec.model;
|
|
2180
2192
|
if (tool && !isManifestToolEnabled(tool, caller.tenantId))
|
|
2181
2193
|
throw new Error('Tool disabled');
|
|
2182
2194
|
const approvalPolicy = binding?.turn.thread &&
|
|
2183
|
-
!
|
|
2195
|
+
!workflowSteps.has(binding.context.event.request)
|
|
2184
2196
|
? {
|
|
2185
|
-
allowRemovalsInChat: (await host.
|
|
2186
|
-
|
|
2197
|
+
allowRemovalsInChat: (await host.assistantSettings.read()).settings
|
|
2198
|
+
.requireRemovalApproval === false,
|
|
2187
2199
|
}
|
|
2188
2200
|
: undefined;
|
|
2189
2201
|
if (tool &&
|
|
@@ -2344,9 +2356,16 @@ export function createCookbookHost(options) {
|
|
|
2344
2356
|
},
|
|
2345
2357
|
dispose() {
|
|
2346
2358
|
process.removeListener('sveltekit:shutdown', onShutdown);
|
|
2347
|
-
// Release this
|
|
2348
|
-
//
|
|
2349
|
-
|
|
2359
|
+
// Release this host's workflow definition now so a replacement host can
|
|
2360
|
+
// register its own. While the task runner still runs, the handler stays
|
|
2361
|
+
// registered (smrt-jobs refuses the change) and the shared shutdown
|
|
2362
|
+
// releases it after the runner stopped.
|
|
2363
|
+
try {
|
|
2364
|
+
disposeWorkflowRuns?.();
|
|
2365
|
+
}
|
|
2366
|
+
catch {
|
|
2367
|
+
/* released by shutdown once the runner stopped */
|
|
2368
|
+
}
|
|
2350
2369
|
void shutdown().catch(() => { });
|
|
2351
2370
|
current?.gate.dispose?.();
|
|
2352
2371
|
setRuntimeExposureGate(undefined);
|