@happyvertical/smrt-template-sveltekit 0.60.18 → 0.61.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.
Files changed (80) hide show
  1. package/AGENTS.md +68 -51
  2. package/README.md +25 -10
  3. package/agents/cookbook-design-runs.md +164 -0
  4. package/agents/cookbook-host.md +724 -0
  5. package/agents/onboarding.md +116 -0
  6. package/agents/plugin-mode.md +152 -0
  7. package/cookbook-template/.pnpmfile.cjs +5 -0
  8. package/cookbook-template/src/hooks.server.ts +3 -0
  9. package/cookbook-template/src/lib/server/cookbook.ts +21 -0
  10. package/cookbook-template/src/lib/server/smrt.ts +11 -0
  11. package/cookbook-template/src/routes/+layout.server.ts +24 -0
  12. package/cookbook-template/src/routes/+layout.svelte +47 -0
  13. package/cookbook-template/src/routes/+page.server.ts +15 -0
  14. package/cookbook-template/src/routes/+page.svelte +12 -0
  15. package/cookbook-template/src/routes/api/_runtime/owner-link/+server.ts +2 -0
  16. package/cookbook-template/src/routes/api/assistant/[...path]/+server.ts +2 -0
  17. package/cookbook-template/src/routes/api/connect-ai/+server.ts +2 -0
  18. package/cookbook-template/src/routes/api/cookbook/prebuilt/+server.ts +3 -0
  19. package/cookbook-template/src/routes/api/cookbook/preferences/+server.ts +45 -0
  20. package/cookbook-template/src/routes/api/onboarding/+server.ts +3 -0
  21. package/cookbook-template/src/routes/m/[pkg]/[model]/[[key]]/+page.server.ts +1 -0
  22. package/cookbook-template/src/routes/m/[pkg]/[model]/[[key]]/+page.svelte +7 -0
  23. package/cookbook-template/src/routes/mcp/+server.ts +2 -0
  24. package/cookbook-template/src/routes/onboarding/+page.server.ts +13 -0
  25. package/cookbook-template/src/routes/onboarding/+page.svelte +28 -0
  26. package/cookbook-template/src/routes/s/[slug]/+page.server.ts +10 -0
  27. package/cookbook-template/src/routes/s/[slug]/+page.svelte +6 -0
  28. package/cookbook-template/src/routes/settings/+page.server.ts +22 -0
  29. package/cookbook-template/src/routes/settings/+page.svelte +49 -0
  30. package/cookbook-template/src/routes/settings/inference/+page.server.ts +6 -0
  31. package/cookbook-template/src/routes/settings/inference/+page.svelte +14 -0
  32. package/cookbook-template/vite.config.ts +4 -0
  33. package/dist/host/client.d.ts +8 -0
  34. package/dist/host/client.js +66 -0
  35. package/dist/host/design-runs.d.ts +72 -0
  36. package/dist/host/design-runs.js +763 -0
  37. package/dist/host/generate.d.ts +49 -0
  38. package/dist/host/generate.js +266 -0
  39. package/dist/host/onboarding.d.ts +26 -0
  40. package/dist/host/onboarding.js +247 -0
  41. package/dist/host/plugin-mode.d.ts +55 -0
  42. package/dist/host/plugin-mode.js +184 -0
  43. package/dist/host/preferences.d.ts +40 -0
  44. package/dist/host/preferences.js +163 -0
  45. package/dist/host/server.d.ts +283 -0
  46. package/dist/host/server.js +2400 -0
  47. package/dist/host/settings.d.ts +57 -0
  48. package/dist/host/settings.js +130 -0
  49. package/dist/host/state.d.ts +26 -0
  50. package/dist/host/state.js +149 -0
  51. package/dist/host/sveltekit-client.d.ts +22 -0
  52. package/dist/host/sveltekit-client.js +53 -0
  53. package/dist/smrt-knowledge.okf.md +105 -0
  54. package/examples/notes/src/routes/notes/+page.svelte +145 -0
  55. package/host/CookbookModelPage.svelte +78 -0
  56. package/host/InferenceSettingsPage.svelte +103 -0
  57. package/mcp-apps-template/package.dependencies.json +2 -2
  58. package/package.json +102 -24
  59. package/template/README.md +24 -11
  60. package/template/package.json +17 -12
  61. package/template/smrt.config.ts +4 -0
  62. package/template/src/hooks.server.ts +5 -0
  63. package/template/src/lib/objects/index.ts +7 -3
  64. package/template/src/lib/server/settings-registry.ts +29 -0
  65. package/template/src/lib/server/settings.ts +91 -0
  66. package/template/src/lib/server/smrt.ts +1 -0
  67. package/template/src/lib/settings-client.ts +1 -0
  68. package/template/src/lib/sign-out.ts +1 -19
  69. package/template/src/params/settingsSection.ts +4 -0
  70. package/template/src/routes/+layout.svelte +1 -2
  71. package/template/src/routes/+page.svelte +20 -128
  72. package/template/src/routes/settings/+page.svelte +16 -3
  73. package/template/src/routes/settings/[section=settingsSection]/+page.svelte +19 -0
  74. package/template/src/routes/settings/inference/+page.server.ts +3 -0
  75. package/template/src/routes/settings/inference/+page.svelte +6 -0
  76. package/template/src/routes/settings/prompts/+page.server.ts +50 -0
  77. package/template/src/routes/settings/prompts/+page.svelte +28 -0
  78. package/template.config.js +17 -12
  79. /package/{template → examples/notes}/src/lib/objects/Note.ts +0 -0
  80. /package/{template/src/routes → examples/notes/src/routes/notes}/+page.server.ts +0 -0
@@ -0,0 +1,2400 @@
1
+ /** Documented local SvelteKit composition over the existing runtime and cookbook APIs. */
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { executeAsPrincipal, } from '@happyvertical/smrt-agents';
6
+ import { mountMcpAppRoute } from '@happyvertical/smrt-app-mcp/sveltekit';
7
+ import { createSqliteOwnerApprovalStore, isApprovalOwner, OwnerApprovalAuthority, OwnerApprovalContinuations, readOriginFile, } from '@happyvertical/smrt-app-runtime';
8
+ import { createOwnerLinkHandler, createSessionLayoutLoad, createSmrtSvelteKitRuntime, } from '@happyvertical/smrt-app-runtime/sveltekit';
9
+ import { buildManifestToolCatalog, describeAssistantTool, invokeManifestTool, manifestToolToAITool, requiresOwnerApproval, } from '@happyvertical/smrt-chat';
10
+ import { readAssistantTurnStream } from '@happyvertical/smrt-chat/assistant-turn';
11
+ import { createAgentCliTurnDriver, createInferenceAssistantAdapters, } from '@happyvertical/smrt-chat/engines';
12
+ import { configuredAssistantAI, mountAssistantRoutes, resolveAssistantPrincipalFromLocals, } from '@happyvertical/smrt-chat/sveltekit';
13
+ import { ObjectRegistry, toSnakeCase, withEmbeddedWriteTransaction, } from '@happyvertical/smrt-core';
14
+ import { createActivationCoordinator, } from '@happyvertical/smrt-core/activation';
15
+ import { cookbookModelCatalog, createAppModelEditor, createSqliteAppModelHistory, } from '@happyvertical/smrt-core/app-models';
16
+ import { validateCookbook } from '@happyvertical/smrt-core/cookbook';
17
+ import { BUNDLED_COOKBOOK_TEMPLATES, COOKBOOK_TOOL_NAMES, CookbookToolError, createCookbookToolService, setCookbookToolService, } from '@happyvertical/smrt-core/cookbook/tools';
18
+ import { resolveApiMethodExposure } from '@happyvertical/smrt-core/generators/custom-action';
19
+ import { MCPGenerator, } from '@happyvertical/smrt-core/generators/mcp';
20
+ import { APIGenerator } from '@happyvertical/smrt-core/generators/rest';
21
+ import { createCookbookRuntimeExposure, filterRuntimeCookbookSnapshot, filterRuntimeExposure, isRuntimeModelEnabled, setRuntimeExposureGate, } from '@happyvertical/smrt-core/runtime-exposure';
22
+ import { createAgentCliService, createChatGPTPlanConnection, createDesignRunStore, createInferenceSettingsController, createInferenceSettingsHost, INFERENCE_PERMISSION_DEFINITIONS, inferencePreferenceKind, locateCli, nextWorkModel, OPENAI_WORK_MODEL_RANKS, projectWorkModelSelection, rankOpenAIWorkModels, recommendedWorkProfile, resolveWorkProfile, tokenCredentials, } from '@happyvertical/smrt-inference/server';
23
+ import { TaskRunner } from '@happyvertical/smrt-jobs';
24
+ import { createPrebuiltComponentsPreference, createPreferenceStore, createWorkProfilesPreference, getPreferencePrincipal, registerPreferenceKind, } from '@happyvertical/smrt-preferences';
25
+ import { mountConnectAiRoutes } from '@happyvertical/smrt-svelte/connect-ai/server';
26
+ import { buildCookbookShell, catalogFromManifests, readInstalledManifests, } from '@happyvertical/smrt-svelte/cookbook/server';
27
+ import { applyShellLayout } from '@happyvertical/smrt-svelte/workspace/layout';
28
+ import { withTenant } from '@happyvertical/smrt-tenancy';
29
+ import { PermissionResolver, RolePermissionCollection, registerPermissionDefinitions, UserCollection, } from '@happyvertical/smrt-users';
30
+ import { error, redirect } from '@sveltejs/kit';
31
+ import { createCookbookDesignRuns, isCookbookDesignFinalCheck, presentCookbookDesignProgress, } from './design-runs.js';
32
+ import { createCookbookOnboarding } from './onboarding.js';
33
+ import { createPluginMode, PLUGIN_CLIENTS, PLUGIN_PERMISSION, } from './plugin-mode.js';
34
+ import { createCookbookHostState } from './state.js';
35
+ const describePublicAssistantTool = (name, _args, outcome) => describeAssistantTool(outcome ? name : 'change', undefined, outcome ? { ok: outcome.ok, observation: undefined } : undefined, { recordLabels: 'generic' });
36
+ // Only the core editor's bounded human command captions may become public.
37
+ // Labels containing implementation syntax fall back without altering the ledger.
38
+ const personChangeSummary = (value, prospective = false) => {
39
+ if (typeof value !== 'string' ||
40
+ value.length > 180 ||
41
+ !/^(Added|Renamed|Removed|Hid|Showed|Undid|Use|Used|Configured|Enabled|Disabled) [\p{L}\p{N} ’'(),-]+\.?$/u.test(value) ||
42
+ /[a-z][A-Z]/.test(value) ||
43
+ /\b(?:revision|cookbook|smrt|profile|tenant|identity|schema|namespace|class|package)\b/i.test(value))
44
+ return undefined;
45
+ if (!prospective)
46
+ return value.replace(/^Use /, 'Used ');
47
+ const verbs = {
48
+ added: 'Add',
49
+ renamed: 'Rename',
50
+ removed: 'Remove',
51
+ hid: 'Hide',
52
+ showed: 'Show',
53
+ use: 'Use',
54
+ used: 'Use',
55
+ configured: 'Configure',
56
+ enabled: 'Enable',
57
+ disabled: 'Disable',
58
+ };
59
+ return value
60
+ .replace(/^(Added|Renamed|Removed|Hid|Showed|Use|Used|Configured|Enabled|Disabled) /, (verb) => `${verbs[verb.trim().toLowerCase()]} `)
61
+ .replace(/ and kept its data(\.?)$/, ' and keep its data$1');
62
+ };
63
+ async function readHostApp(options) {
64
+ const root = options.root ?? process.cwd();
65
+ return (options.app ??
66
+ (await (async () => {
67
+ const manifests = await readInstalledManifests(root);
68
+ const catalog = catalogFromManifests(manifests, true);
69
+ const checked = validateCookbook(JSON.parse(await readFile(join(root, 'smrt.cookbook.json'), 'utf8')), { recipes: catalog.recipes.map((r) => r.id) });
70
+ if (!checked.ok)
71
+ throw new Error(checked.errors.join('; '));
72
+ // The catalog keeps search/help while dropping full model declarations.
73
+ return {
74
+ cookbook: checked.cookbook,
75
+ catalog: {
76
+ ...catalog,
77
+ recipes: catalog.recipes.map((r) => ({
78
+ ...r,
79
+ requires: r.requires ?? [],
80
+ })),
81
+ },
82
+ };
83
+ })()));
84
+ }
85
+ /** Normal local runtime, with fixed-graph SQLite activation before owner bootstrap. */
86
+ export function createCookbookApplication(options) {
87
+ let activation;
88
+ const runtime = createSmrtSvelteKitRuntime({
89
+ ...options.runtimeOptions,
90
+ createSchema: false,
91
+ prepareDatabase: async (db, context) => {
92
+ if (context.profile !== 'local')
93
+ throw new Error('Cookbook host requires the local SQLite runtime');
94
+ const app = await readHostApp(options);
95
+ const state = await createCookbookHostState(db, app.catalog, app.cookbook);
96
+ const graph = options.lazyActivation;
97
+ activation = createActivationCoordinator({
98
+ scope: graph.scope,
99
+ packageName: options.packageName,
100
+ db,
101
+ manifest: graph.manifest,
102
+ loaders: graph.loaders,
103
+ alwaysOn: graph.alwaysOn ??
104
+ Object.keys(graph.manifest.models).filter((id) => /^@happyvertical\/smrt-(users|profiles|tenancy|chat|approvals|preferences|inference|secrets|jobs):/.test(id)),
105
+ readEnabled: () => state.enabledModelUnion(async (tenantId) => (await (await createSqliteAppModelHistory({
106
+ db,
107
+ tenantId,
108
+ application: options.application ?? options.packageName,
109
+ })).read()).at(-1)?.after),
110
+ });
111
+ setRuntimeExposureGate({ isEnabled: () => false });
112
+ await activation.boot();
113
+ },
114
+ });
115
+ return createCookbookHost({
116
+ ...options,
117
+ runtime,
118
+ activation: () => activation,
119
+ });
120
+ }
121
+ /** One local owner host per process. Construct before runtime.init seeds permissions. */
122
+ export function createCookbookHost(options) {
123
+ const { runtime } = options;
124
+ registerPreferenceKind(inferencePreferenceKind, { replace: true });
125
+ registerPermissionDefinitions([
126
+ ...INFERENCE_PERMISSION_DEFINITIONS,
127
+ {
128
+ slug: 'app.approvals',
129
+ category: 'app',
130
+ name: 'Read your tool approval outcomes',
131
+ description: 'Read the existing owner continuation outcome under the original tool scope',
132
+ },
133
+ {
134
+ slug: PLUGIN_PERMISSION,
135
+ category: 'app',
136
+ name: 'Use the app with your own AI',
137
+ description: 'Delegate the current enabled app tool surface to a local AI client; destructive calls still require owner approval',
138
+ },
139
+ ]);
140
+ const inference = createInferenceSettingsHost({
141
+ database: () => runtime.database(),
142
+ masterKeyProvider: () => runtime.secretMasterKey(),
143
+ overrides: () => runtime.classOptions('InferenceOverride'),
144
+ });
145
+ inference.install();
146
+ const inferenceSettings = createInferenceSettingsController({
147
+ host: inference,
148
+ preferenceStore: async () => createPreferenceStore({ db: await runtime.database() }),
149
+ });
150
+ const cli = options.cli ?? createAgentCliService();
151
+ let connection;
152
+ let current;
153
+ let starting;
154
+ const designRequests = new WeakMap();
155
+ let origin;
156
+ let taskRunner;
157
+ let disposeDesignRuns;
158
+ const turns = new Map();
159
+ const digest = (token) => createHash('sha256').update(token).digest('hex');
160
+ const wireName = (slug) => toSnakeCase(slug).replace(/[^a-z0-9_]/g, '_');
161
+ const isManifestToolEnabled = (tool, tenantId) => isRuntimeModelEnabled(ObjectRegistry.getExposureModel(tool.qualifiedName ?? tool.className), { surface: 'assistant', tenantId });
162
+ const json = (value, status = 200) => Response.json(value, { status, headers: { 'cache-control': 'no-store' } });
163
+ const isOwner = async (tenantId, id) => !!tenantId &&
164
+ !!id &&
165
+ isApprovalOwner(await runtime.database(), { tenantId, id });
166
+ async function initialize() {
167
+ await runtime.init();
168
+ if ((await runtime.resolvedRuntime()).profile !== 'local')
169
+ throw new Error('Cookbook host currently requires the local SQLite runtime');
170
+ const db = await runtime.database();
171
+ const loaded = await readHostApp(options);
172
+ // Fork only the writable envelope; compiled catalog records are immutable
173
+ // and shared with activation. Model editing replaces its models array.
174
+ const app = { ...loaded, catalog: { ...loaded.catalog } };
175
+ if (options.onboarding)
176
+ app.catalog = {
177
+ ...app.catalog,
178
+ cookbooks: [
179
+ {
180
+ id: 'fresh',
181
+ name: 'Fresh',
182
+ document: {
183
+ $schema: 'https://s-m-r-t.dev/schemas/cookbook/v1.json',
184
+ version: 1,
185
+ recipes: [],
186
+ features: [],
187
+ policies: [],
188
+ },
189
+ },
190
+ ...(app.catalog.cookbooks ?? BUNDLED_COOKBOOK_TEMPLATES),
191
+ ],
192
+ };
193
+ const state = await createCookbookHostState(db, app.catalog, app.cookbook);
194
+ const authority = new OwnerApprovalAuthority(await createSqliteOwnerApprovalStore(db), (actor) => isApprovalOwner(db, actor));
195
+ const preferences = createPrebuiltComponentsPreference({
196
+ store: createPreferenceStore({ db }),
197
+ isOwner: (p) => isOwner(p.tenantId, p.userId),
198
+ });
199
+ const workProfiles = createWorkProfilesPreference({
200
+ store: createPreferenceStore({ db }),
201
+ isOwner: (p) => isOwner(p.tenantId, p.userId),
202
+ });
203
+ async function restoredDesignContext(record) {
204
+ const action = record.context.designAction;
205
+ if (!action)
206
+ return {};
207
+ if (action.application !== (options.application ?? options.packageName) ||
208
+ typeof action.runId !== 'string' ||
209
+ typeof action.actionId !== 'string' ||
210
+ !/^(0|[1-9]\d*)$/.test(action.actionId))
211
+ throw new Error('Invalid saved design action');
212
+ const user = await (await UserCollection.create({ db })).get({
213
+ id: record.requestedBy,
214
+ });
215
+ const principal = record.context.principal;
216
+ const saved = await createDesignRunStore({
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);
224
+ if (!saved ||
225
+ !/^cookbook-design\/v[345]\//.test(saved.definition) ||
226
+ !user?.profileId ||
227
+ principal?.profileId !== user.profileId ||
228
+ saved.input.threadId !==
229
+ record.context.threadId)
230
+ throw new Error('Saved design principal changed');
231
+ await authorizeDesignThread(record.requestedBy, record.tenantId, record.context.threadId);
232
+ await designRuns
233
+ .forOwner(record.requestedBy, record.tenantId)
234
+ .validateAction(action.runId, action.actionId, record.tool, record.args);
235
+ return {
236
+ designAction: {
237
+ application: action.application,
238
+ runId: action.runId,
239
+ actionId: action.actionId,
240
+ },
241
+ threadId: record.context.threadId,
242
+ profileId: user.profileId,
243
+ };
244
+ }
245
+ async function authorizeDesignThread(ownerId, tenantId, threadId) {
246
+ if (!tenantId)
247
+ throw new Error('Tenant required');
248
+ await runtime.runAsPrincipal({ id: ownerId, tenantId, kind: 'human' }, async (bound) => {
249
+ const user = await (await UserCollection.create({ db })).get({
250
+ id: ownerId,
251
+ });
252
+ if (!user?.profileId || !bound)
253
+ throw new Error('Owner unavailable');
254
+ const url = new URL(`/api/assistant/threads/${encodeURIComponent(threadId)}/messages`, origin ?? 'http://127.0.0.1');
255
+ const response = await assistantRoutes.GET({
256
+ url,
257
+ request: new Request(url),
258
+ params: {
259
+ path: `threads/${encodeURIComponent(threadId)}/messages`,
260
+ },
261
+ locals: {
262
+ user: { id: ownerId, profileId: user.profileId },
263
+ tenantId,
264
+ permissions: [...(bound.scopes ?? [])],
265
+ },
266
+ });
267
+ if (!response.ok)
268
+ throw new Error('Design thread unavailable');
269
+ });
270
+ }
271
+ const continuations = new OwnerApprovalContinuations(authority, {
272
+ cookbook: async (record) => {
273
+ const action = record.context.designAction;
274
+ if (typeof action?.runId === 'string') {
275
+ const saved = await createDesignRunStore({
276
+ db,
277
+ ownerId: record.requestedBy,
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
285
+ // effects; explicit Resume performs the same stable action.
286
+ if (saved?.status === 'stopped' &&
287
+ /^cookbook-design\/v[345]\//.test(saved.definition) &&
288
+ isCookbookDesignFinalCheck(saved))
289
+ return {
290
+ status: 'deferred',
291
+ summary: 'This design is paused. Resume it to apply the approved change.',
292
+ };
293
+ }
294
+ return executeSaved(record, async () => service.invoke(record.tool, { ...record.args, approvalId: record.id }, {
295
+ surface: 'mcp',
296
+ tenantId: record.tenantId,
297
+ userId: record.requestedBy,
298
+ ...(await restoredDesignContext(record)),
299
+ }));
300
+ },
301
+ model: async (record) => executeSaved(record, async (run) => {
302
+ const offered = record.context.pluginMode === true || record.context.threadId
303
+ ? (await manifest(record.tenantId, record.requestedBy, [
304
+ ...run.permissions,
305
+ ])).find((t) => t.slug === record.tool)
306
+ : (await mcpModels({
307
+ id: record.requestedBy,
308
+ tenantId: record.tenantId,
309
+ scopes: [...run.permissions],
310
+ })).find((t) => t.tool.slug === record.tool)?.tool;
311
+ if (!offered)
312
+ throw new Error('Approved tool is no longer offered');
313
+ return invokeManifestTool(run, offered, record.args, {
314
+ db: run.context.database ?? runtime.databaseConfig(),
315
+ });
316
+ }),
317
+ });
318
+ const executeSaved = async (record, execute) => {
319
+ const principal = record.continuation.principal;
320
+ await prepare(principal.tenantId, false);
321
+ return executeAsPrincipal({
322
+ principal: {
323
+ runAsUserId: principal.id,
324
+ tenantId: principal.tenantId,
325
+ allowedTools: principal.allowedTools,
326
+ },
327
+ db: runtime.databaseConfig(),
328
+ permissions: [
329
+ ...(await (await PermissionResolver.create({
330
+ db: await runtime.database(),
331
+ })).resolvePermissions(principal.id, principal.tenantId)).permissions,
332
+ ].filter((permission) => principal.permissions.includes(permission)),
333
+ }, async (run) => {
334
+ run.assertToolAllowed(record.tool);
335
+ const at = record.tool.lastIndexOf('.');
336
+ await run.assertOperation(record.tool.slice(0, at), record.tool.slice(at + 1));
337
+ return execute(run);
338
+ });
339
+ };
340
+ const livePermissions = async (c) => c.tenantId && c.userId
341
+ ? (await (await PermissionResolver.create({ db })).resolvePermissions(c.userId, c.tenantId)).permissions
342
+ : new Set();
343
+ const service = createCookbookToolService({
344
+ ...(options.activation ? { activation: options.activation() } : {}),
345
+ ...{
346
+ modelEditorFor: (c) => c.tenantId ? editors.get(c.tenantId) : undefined,
347
+ },
348
+ catalog: app.catalog,
349
+ engineFor: state.engineFor,
350
+ isOwner: (c) => isOwner(c.tenantId, c.userId),
351
+ can: async (c, slug) => (await livePermissions(c)).has(slug),
352
+ canAll: async (c, slugs) => {
353
+ const held = await livePermissions(c);
354
+ return new Set(slugs.filter((slug) => held.has(slug)));
355
+ },
356
+ approvals: continuations.adapter('cookbook'),
357
+ previewBeforeApply: async (context) => {
358
+ if (context.designAction && context.userId && context.tenantId) {
359
+ const saved = await createDesignRunStore({
360
+ db,
361
+ ownerId: context.userId,
362
+ tenantId: context.tenantId,
363
+ enqueue: async () => {
364
+ throw new Error('Read only');
365
+ },
366
+ }).load(context.designAction.runId, context.userId);
367
+ return (saved?.input
368
+ ?.profile?.previewBeforeApply !== false);
369
+ }
370
+ return ((await workProfiles.read()).settings.design?.previewBeforeApply !==
371
+ false);
372
+ },
373
+ isAppEmpty: async (context) => {
374
+ if (!context.initialSetup || !context.tenantId)
375
+ return false;
376
+ const engine = state.engineFor(context);
377
+ if (!engine)
378
+ return false;
379
+ const shell = buildCookbookShell({
380
+ cookbook: engine.cookbook(),
381
+ catalog: app.catalog,
382
+ });
383
+ return withTenant({ tenantId: context.tenantId, userId: context.userId ?? undefined }, async () => {
384
+ for (const id of new Set([...shell.entries.values()].map((entry) => entry.model.id))) {
385
+ const table = ObjectRegistry.getTableName(id);
386
+ if (!table)
387
+ return false;
388
+ if (!(await db.tableExists(table)))
389
+ continue;
390
+ const collection = await ObjectRegistry.getCollection(id, {
391
+ ...runtime.classOptions(id),
392
+ db,
393
+ });
394
+ if (await collection.count())
395
+ return false;
396
+ }
397
+ return true;
398
+ });
399
+ },
400
+ commit: state.commit,
401
+ audit: state.audit,
402
+ });
403
+ const cookbookGate = createCookbookRuntimeExposure({
404
+ catalog: app.catalog,
405
+ engineFor: state.engineFor,
406
+ predicate: (model, c) => {
407
+ if (preferences.isEnabled(c.tenantId))
408
+ return true;
409
+ const document = state.engineFor(c)?.cookbook();
410
+ return (!!document?.models &&
411
+ Object.keys(document.models.lists).some((name) => model.qualifiedName === `${document.models.packageName}:${name}`));
412
+ },
413
+ });
414
+ const gate = {
415
+ ...(options.activation
416
+ ? options.activation().gate(cookbookGate)
417
+ : cookbookGate),
418
+ dispose: () => cookbookGate.dispose(),
419
+ };
420
+ setCookbookToolService(service);
421
+ setRuntimeExposureGate(gate);
422
+ const onboarding = options.onboarding
423
+ ? await createCookbookOnboarding({
424
+ db,
425
+ catalog: app.catalog,
426
+ authorize: async (event) => {
427
+ const p = resolveAssistantPrincipalFromLocals(event.locals);
428
+ return p && (await isOwner(p.tenantId, p.userId))
429
+ ? {
430
+ ...p,
431
+ permissions: [
432
+ ...(event.locals.permissions ?? []),
433
+ ],
434
+ }
435
+ : null;
436
+ },
437
+ invoke: async (actor, name, args, initialSetup = false) => {
438
+ const permissions = [
439
+ ...(await (await PermissionResolver.create({ db })).resolvePermissions(actor.userId, actor.tenantId)).permissions,
440
+ ];
441
+ if (!actor.permissions?.includes(name))
442
+ throw new CookbookToolError('forbidden', 'This operation is not in the session permission snapshot.');
443
+ const ceiling = permissions.filter((permission) => actor.permissions.includes(permission));
444
+ return continuations.capture({
445
+ id: actor.userId,
446
+ tenantId: actor.tenantId,
447
+ permissions: ceiling,
448
+ allowedTools: [name],
449
+ }, () => service.invoke(name, args, {
450
+ ...actor,
451
+ surface: 'mcp',
452
+ initialSetup,
453
+ }));
454
+ },
455
+ approval: async (actor, id) => {
456
+ const record = await authority.get(actor.tenantId, id);
457
+ if (!record || record.requestedBy !== actor.userId)
458
+ return null;
459
+ return {
460
+ id: record.id,
461
+ tool: record.tool,
462
+ callId: record.callId,
463
+ summary: record.summary,
464
+ status: record.status,
465
+ decidedBy: record.decidedBy,
466
+ decidedAt: record.decidedAt,
467
+ };
468
+ },
469
+ })
470
+ : undefined;
471
+ const describeDesignApp = async (ownerId, tenantId, optional = false) => {
472
+ if (!tenantId)
473
+ throw new Error('Tenant required');
474
+ return runtime.runAsPrincipal({ id: ownerId, tenantId, kind: 'human' }, async () => {
475
+ await prepare(tenantId, false);
476
+ const context = {
477
+ surface: 'mcp',
478
+ tenantId,
479
+ userId: ownerId,
480
+ };
481
+ if (optional &&
482
+ !(await service.list(context)).some((tool) => tool.name === 'app.describe'))
483
+ return undefined;
484
+ return service.invoke('app.describe', {}, { surface: 'mcp', tenantId, userId: ownerId });
485
+ });
486
+ };
487
+ const designRuns = createCookbookDesignRuns({
488
+ db,
489
+ authorizeThread: authorizeDesignThread,
490
+ describeApp: (ownerId, tenantId) => describeDesignApp(ownerId, tenantId, true),
491
+ currentRevision: async (ownerId, tenantId) => {
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
+ },
497
+ authorize: async (ownerId, tenantId) => {
498
+ if (!(await isOwner(tenantId, ownerId)))
499
+ throw new Error('Owner required');
500
+ },
501
+ listOperations: async (ownerId, tenantId) => {
502
+ if (!tenantId)
503
+ throw new Error('Tenant required');
504
+ return runtime.runAsPrincipal({ id: ownerId, tenantId, kind: 'human' }, async () => {
505
+ await prepare(tenantId, false);
506
+ return (await service.list({ surface: 'mcp', userId: ownerId, tenantId })).filter((tool) => service.supportsDesignAction(tool.name));
507
+ });
508
+ },
509
+ executeOperation: async ({ ownerId, tenantId, threadId, runId, actionId, permissions, operation, signal, }) => {
510
+ if (!tenantId ||
511
+ !options.packageName ||
512
+ !service.supportsDesignAction(operation.tool))
513
+ throw new Error('Durable design operation unavailable');
514
+ return runtime.runAsPrincipal({ id: ownerId, tenantId, kind: 'human', scopes: [...permissions] }, async (bound) => {
515
+ await prepare(tenantId, false);
516
+ await authorizeDesignThread(ownerId, tenantId, threadId);
517
+ const user = await (await UserCollection.create({ db })).get({
518
+ id: ownerId,
519
+ });
520
+ if (!user?.profileId || !bound)
521
+ throw new Error('Owner unavailable');
522
+ signal.throwIfAborted();
523
+ const ceiling = [...(bound.scopes ?? [])].filter((permission) => permissions.includes(permission));
524
+ return executeAsPrincipal({
525
+ principal: {
526
+ runAsUserId: ownerId,
527
+ tenantId,
528
+ allowedTools: [operation.tool],
529
+ },
530
+ db: runtime.databaseConfig(),
531
+ permissions: ceiling,
532
+ }, async (run) => {
533
+ run.assertToolAllowed(operation.tool);
534
+ const at = operation.tool.lastIndexOf('.');
535
+ await run.assertOperation(operation.tool.slice(0, at), operation.tool.slice(at + 1));
536
+ await designRuns
537
+ .forOwner(ownerId, tenantId)
538
+ .validateAction(runId, actionId, operation.tool, operation.tool === 'cookbook.apply'
539
+ ? { ...operation.args, apply: true }
540
+ : operation.args);
541
+ signal.throwIfAborted();
542
+ return continuations.capture({
543
+ id: ownerId,
544
+ tenantId,
545
+ permissions: ceiling,
546
+ allowedTools: [operation.tool],
547
+ }, () => service.invoke(operation.tool, operation.args, {
548
+ surface: 'assistant',
549
+ tenantId,
550
+ userId: ownerId,
551
+ profileId: user.profileId,
552
+ threadId,
553
+ designAction: {
554
+ application: options.application ?? options.packageName,
555
+ runId,
556
+ actionId,
557
+ },
558
+ }));
559
+ });
560
+ });
561
+ },
562
+ executePass: async ({ ownerId, tenantId, threadId, content, profile, permissions, request, stage, }) => {
563
+ if (!tenantId)
564
+ throw new Error('Tenant required');
565
+ const local = await runtime.localRuntime();
566
+ const base = origin ?? (await readOriginFile(local.paths.root))?.origin;
567
+ if (!base)
568
+ throw new Error('The local app origin is unavailable');
569
+ return runtime.runAsPrincipal({ id: ownerId, tenantId, kind: 'human' }, async (bound) => {
570
+ const user = await (await UserCollection.create({ db })).get({
571
+ id: ownerId,
572
+ });
573
+ if (!user?.profileId || !bound)
574
+ throw new Error('Owner unavailable');
575
+ 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
+ const detached = new Request(url, {
582
+ method: 'POST',
583
+ headers: {
584
+ origin: url.origin,
585
+ 'content-type': 'application/json',
586
+ },
587
+ body: JSON.stringify({
588
+ content,
589
+ clientRequestId: `${request.runId}-${request.pass.index}-${randomUUID()}`,
590
+ }),
591
+ signal: request.signal,
592
+ });
593
+ designRequests.set(detached, {
594
+ profile: {
595
+ ...profile,
596
+ budgets: {
597
+ ...profile.budgets,
598
+ maxTurnTokens: Math.min(profile.budgets.maxTurnTokens, request.maxTokens),
599
+ turnTimeoutMs: Math.min(profile.budgets.turnTimeoutMs, request.timeoutMs),
600
+ },
601
+ },
602
+ schema: request.schema,
603
+ prompt,
604
+ content,
605
+ });
606
+ const e = {
607
+ url,
608
+ request: detached,
609
+ params: { path: `threads/${threadId}/messages` },
610
+ locals: {
611
+ user: { id: ownerId, profileId: user.profileId },
612
+ tenantId,
613
+ permissions: [...(bound.scopes ?? [])].filter((slug) => permissions.includes(slug)),
614
+ },
615
+ };
616
+ try {
617
+ const response = await assistantRoutes.POST(e);
618
+ if (!response.ok)
619
+ throw new Error('The design pass could not start');
620
+ const outcome = await readAssistantTurnStream(response, () => { });
621
+ const reply = outcome.done?.message;
622
+ if (!reply?.metadata?.workRun)
623
+ throw new Error('Design execution metadata is unavailable');
624
+ const output = reply.metadata.designOutput ?? reply.content ?? '';
625
+ return { output, metadata: reply.metadata.workRun };
626
+ }
627
+ finally {
628
+ designRequests.delete(detached);
629
+ }
630
+ });
631
+ },
632
+ });
633
+ disposeDesignRuns = designRuns.dispose;
634
+ taskRunner = new TaskRunner({
635
+ concurrency: 1,
636
+ queues: ['default'],
637
+ retention: false,
638
+ });
639
+ await taskRunner.initialize(db);
640
+ await taskRunner.start();
641
+ return {
642
+ ...app,
643
+ onboarding,
644
+ state,
645
+ authority,
646
+ continuations,
647
+ preferences,
648
+ workProfiles,
649
+ designRuns,
650
+ service,
651
+ gate,
652
+ };
653
+ }
654
+ let shutdownPromise;
655
+ let stopped = false;
656
+ const shutdown = () => (shutdownPromise ??= (async () => {
657
+ // Adapter-node emits its lifecycle event after HTTP connections close.
658
+ // Initialization may still be finishing; stop that same runner after it
659
+ // starts rather than leaving newly-created polling/liveness handles alive.
660
+ try {
661
+ await starting;
662
+ }
663
+ catch {
664
+ // Initialization's caller owns that failure. Teardown must still stop
665
+ // partially-started resources without reporting the same error twice.
666
+ }
667
+ try {
668
+ await taskRunner?.stop();
669
+ }
670
+ finally {
671
+ stopped = true;
672
+ disposeDesignRuns?.();
673
+ }
674
+ })());
675
+ const onShutdown = () => {
676
+ void shutdown().catch(() => {
677
+ process.exitCode = 1;
678
+ // biome-ignore lint/suspicious/noConsole: fixed lifecycle failure, no request or credential data
679
+ console.error('Cookbook host shutdown failed');
680
+ });
681
+ };
682
+ process.once('sveltekit:shutdown', onShutdown);
683
+ const ready = () => {
684
+ if (stopped || (!starting && shutdownPromise))
685
+ return Promise.reject(new Error('Cookbook host is shutting down'));
686
+ starting ??= initialize().then((value) => (current = value));
687
+ return starting;
688
+ };
689
+ const publishedDefinitions = new Map();
690
+ const editors = new Map();
691
+ const editorStarts = new Map();
692
+ const prepare = async (tenantId, recover = true) => {
693
+ const host = await ready();
694
+ await host.state.refresh(tenantId);
695
+ await host.preferences.read();
696
+ if (options.packageName && !editors.has(tenantId)) {
697
+ let opening = editorStarts.get(tenantId);
698
+ if (!opening) {
699
+ opening = (async () => {
700
+ const engine = host.state.engineFor({ tenantId });
701
+ if (!engine)
702
+ throw new Error('Cookbook unavailable');
703
+ const editor = await createAppModelEditor({
704
+ db: await runtime.database(),
705
+ application: options.application ?? options.packageName,
706
+ tenantId,
707
+ packageName: options.packageName,
708
+ cookbook: engine.cookbook(),
709
+ catalog: host.catalog,
710
+ authorize: (c) => isOwner(c.tenantId, c.actor),
711
+ publish: async (snapshot) => {
712
+ // Reuse the users upgrade rail; only newly catalogued slugs get owner grants.
713
+ // One transaction prevents a crash between permission creation and its role grant.
714
+ await withEmbeddedWriteTransaction(await runtime.database(), true, async (tx) => {
715
+ await (await RolePermissionCollection.create({ db: tx })).seedNewCatalogPermissions();
716
+ });
717
+ host.catalog.models = cookbookModelCatalog(host.catalog, snapshot.cookbook.models).models;
718
+ await host.state.publishModels(tenantId, snapshot.cookbook, snapshot.revision);
719
+ publishedDefinitions.set(tenantId, snapshot.webDefinitions.filter((definition) => definition.customFields.length > 0 ||
720
+ (definition.objectRef.startsWith(`${snapshot.cookbook.models?.packageName}:`) &&
721
+ Object.hasOwn(snapshot.cookbook.models?.lists ?? {}, definition.objectRef.split(':').at(-1) ?? ''))));
722
+ },
723
+ });
724
+ editors.set(tenantId, editor);
725
+ })();
726
+ editorStarts.set(tenantId, opening);
727
+ }
728
+ try {
729
+ await opening;
730
+ }
731
+ finally {
732
+ editorStarts.delete(tenantId);
733
+ }
734
+ }
735
+ if (recover) {
736
+ const actor = getPreferencePrincipal();
737
+ if (actor?.tenantId === tenantId &&
738
+ actor.userId &&
739
+ (await isOwner(tenantId, actor.userId))) {
740
+ const owner = { id: actor.userId, tenantId };
741
+ for (const record of await host.authority.list(owner, false)) {
742
+ if (record.status !== 'approved' || !record.continuation)
743
+ continue;
744
+ try {
745
+ const outcome = await host.continuations.resume(owner, record.id);
746
+ const action = outcome.context.designAction;
747
+ if (outcome.status === 'succeeded' &&
748
+ typeof action?.runId === 'string')
749
+ await host.designRuns
750
+ .forOwner(outcome.requestedBy, outcome.tenantId)
751
+ .resumeAfterApproval(action.runId);
752
+ }
753
+ catch (error) {
754
+ // A concurrent claimant or a recorded refusal is already visible to the requester.
755
+ if ((await host.authority.get(tenantId, record.id))?.status ===
756
+ 'approved')
757
+ throw error;
758
+ }
759
+ }
760
+ }
761
+ }
762
+ return host;
763
+ };
764
+ const chatgpt = async () => {
765
+ if (options.chatgpt)
766
+ return options.chatgpt;
767
+ connection ??= createChatGPTPlanConnection({
768
+ appName: options.title ?? 'SMRT app',
769
+ credentialsPath: join((await runtime.localRuntime()).paths.root, 'chatgpt-credentials.json'),
770
+ });
771
+ return connection;
772
+ };
773
+ const apiStatus = async (context) => {
774
+ if (options.assistant?.ai)
775
+ return { configured: true };
776
+ try {
777
+ await configuredAssistantAI(context);
778
+ return { configured: true };
779
+ }
780
+ catch {
781
+ return { configured: false };
782
+ }
783
+ };
784
+ const manifest = async (tenantId, userId, scopes) => {
785
+ const host = await ready();
786
+ const document = host.state.engineFor({ tenantId })?.cookbook();
787
+ if (!document)
788
+ return [];
789
+ const shell = buildCookbookShell({
790
+ cookbook: document,
791
+ catalog: host.catalog,
792
+ });
793
+ const engine = userId ? await host.state.engine(tenantId, userId) : null;
794
+ const mcpSlugs = engine === 'claude-code' || engine === 'codex'
795
+ ? new Set((await mcpModels({
796
+ id: userId,
797
+ tenantId,
798
+ scopes: scopes ? [...scopes] : undefined,
799
+ }, true)).map((t) => t.tool.slug))
800
+ : undefined;
801
+ const names = new Set();
802
+ return buildManifestToolCatalog({ all: true }).flatMap((tool) => {
803
+ if (!isManifestToolEnabled(tool, tenantId) ||
804
+ (scopes && !scopes.includes(tool.slug)) ||
805
+ (mcpSlugs && !mcpSlugs.has(tool.slug)))
806
+ return [];
807
+ const key = tool.qualifiedName ?? tool.className;
808
+ // Custom methods follow the owning API declaration, using its canonical
809
+ // exposure resolver. The CLI profile already passed the MCP resolver.
810
+ if (!mcpSlugs &&
811
+ !['read', 'create', 'update', 'delete'].includes(tool.action)) {
812
+ const method = ObjectRegistry.resolveRuntimeMethod(key, tool.action).method;
813
+ if (!method ||
814
+ !resolveApiMethodExposure({
815
+ actionName: tool.action,
816
+ method,
817
+ apiConfig: ObjectRegistry.getConfig(key).api,
818
+ }).exposed)
819
+ return [];
820
+ }
821
+ const entry = modelPlacement(shell, key)?.entry;
822
+ if (!entry)
823
+ return [];
824
+ const functionName = wireName(`${entry.label}_${tool.action}`).slice(0, 64);
825
+ if (names.has(functionName))
826
+ throw new Error('Conflicting app list tool names');
827
+ names.add(functionName);
828
+ return [
829
+ {
830
+ ...tool,
831
+ functionName,
832
+ ...(tool.action === 'delete'
833
+ ? {
834
+ annotations: {
835
+ ...tool.annotations,
836
+ recordDeletion: true,
837
+ },
838
+ }
839
+ : {}),
840
+ description: `${tool.action} records in the app list ${JSON.stringify(entry.label)}.`,
841
+ },
842
+ ];
843
+ });
844
+ };
845
+ // Shared business vocabulary for both native and generated-MCP previews.
846
+ const modelPlacement = (shell, modelId) => {
847
+ const identity = ObjectRegistry.getClass(modelId)?.qualifiedName;
848
+ if (!identity)
849
+ return undefined;
850
+ const entry = [...(shell?.entries.values() ?? [])].find((candidate) => ObjectRegistry.getClass(candidate.model.id)?.qualifiedName === identity);
851
+ if (!entry)
852
+ return undefined;
853
+ return {
854
+ entry,
855
+ noun: shell?.layout?.items?.[entry.id]?.singularLabel ??
856
+ (shell?.layout?.items?.[entry.id]?.label
857
+ ? entry.label
858
+ : (entry.noun ?? entry.label)),
859
+ };
860
+ };
861
+ const mcpModels = async (principal, placedOnly = false) => {
862
+ const host = await ready();
863
+ const document = host.state
864
+ .engineFor({ tenantId: principal.tenantId })
865
+ ?.cookbook();
866
+ const shell = document
867
+ ? buildCookbookShell({ cookbook: document, catalog: host.catalog })
868
+ : undefined;
869
+ const generator = new MCPGenerator({
870
+ classNames: host.catalog.models.map((model) => model.id),
871
+ qualifyCollidingNames: true,
872
+ snakeCaseNames: true,
873
+ }, {
874
+ db: runtime.databaseConfig(),
875
+ tenantId: principal.tenantId,
876
+ user: { id: principal.id },
877
+ permissions: principal.scopes,
878
+ });
879
+ const manifestTools = buildManifestToolCatalog({ all: true }).filter((tool) => isManifestToolEnabled(tool, principal.tenantId));
880
+ const tools = await generator.generateTools();
881
+ return tools.flatMap((descriptor) => {
882
+ if (COOKBOOK_TOOL_NAMES.includes(descriptor.name))
883
+ return [];
884
+ const identity = generator.getToolIdentity(descriptor);
885
+ const placement = modelPlacement(shell, identity.qualifiedName ?? identity.objectName);
886
+ const entry = placement?.entry;
887
+ if (placedOnly && !entry)
888
+ return [];
889
+ if (placedOnly && entry)
890
+ descriptor.description += ` App list label (data): ${JSON.stringify(entry.label)}.`;
891
+ const action = ['list', 'get'].includes(identity.action)
892
+ ? 'read'
893
+ : identity.action;
894
+ const tool = manifestTools.find((t) => t.action === action &&
895
+ ObjectRegistry.getClass(t.qualifiedName ?? t.className)
896
+ ?.qualifiedName ===
897
+ ObjectRegistry.getClass(identity.qualifiedName ?? identity.objectName)?.qualifiedName);
898
+ return tool && principal.scopes?.includes(tool.slug)
899
+ ? [
900
+ {
901
+ descriptor,
902
+ tool: entry && tool.action === 'delete'
903
+ ? {
904
+ ...tool,
905
+ annotations: {
906
+ ...tool.annotations,
907
+ recordDeletion: true,
908
+ },
909
+ }
910
+ : tool,
911
+ generator,
912
+ noun: placement?.noun,
913
+ },
914
+ ]
915
+ : [];
916
+ });
917
+ };
918
+ const extra = async (context) => {
919
+ const host = await ready();
920
+ const tools = (await host.service.assistantTools({
921
+ surface: 'assistant',
922
+ tenantId: context.principal.tenantId,
923
+ userId: context.principal.userId,
924
+ }))
925
+ .filter((tool) => !context.event ||
926
+ !designRequests.has(context.event.request) ||
927
+ tool.annotations?.readOnlyHint === true)
928
+ .map((tool) => ({
929
+ ...tool,
930
+ aiTool: {
931
+ ...tool.aiTool,
932
+ function: { ...tool.aiTool.function, name: wireName(tool.slug) },
933
+ },
934
+ execute: (input) => host.continuations.capture({
935
+ id: context.principal.userId,
936
+ tenantId: context.principal.tenantId,
937
+ permissions: [...input.run.permissions],
938
+ allowedTools: [...input.run.allowedTools],
939
+ }, () => tool.execute(input)),
940
+ }));
941
+ if (context.principal.permissions?.includes('app.approvals') &&
942
+ (await host.authority.list({
943
+ id: context.principal.userId,
944
+ tenantId: context.principal.tenantId,
945
+ }, false)).some((record) => record.requestedBy === context.principal.userId)) {
946
+ tools.push({
947
+ slug: 'app.approvals',
948
+ aiTool: {
949
+ type: 'function',
950
+ function: {
951
+ name: 'owner_approval_outcome',
952
+ description: 'Read your pending owner approval or its recorded outcome.',
953
+ parameters: {
954
+ type: 'object',
955
+ properties: { id: { type: 'string' } },
956
+ required: ['id'],
957
+ additionalProperties: false,
958
+ },
959
+ },
960
+ },
961
+ execute: async ({ run, args }) => {
962
+ run.assertToolAllowed('app.approvals');
963
+ await run.assertOperation('app', 'approvals');
964
+ return approvalOutcome({
965
+ id: run.context.userId,
966
+ tenantId: run.context.tenantId,
967
+ scopes: [...run.permissions],
968
+ }, String(args.id));
969
+ },
970
+ });
971
+ }
972
+ return tools;
973
+ };
974
+ const approvalOutcome = async (caller, id) => {
975
+ if (!caller.id || !caller.tenantId)
976
+ throw new Error('Authentication required');
977
+ const record = await (await ready()).continuations.outcome({ id: caller.id, tenantId: caller.tenantId }, id);
978
+ if (!caller.scopes?.includes(record.tool))
979
+ throw new Error('Approval outcome scope required');
980
+ return {
981
+ id: record.id,
982
+ status: record.status,
983
+ summary: record.summary,
984
+ result: record.result ?? null,
985
+ };
986
+ };
987
+ const allowed = async (context) => {
988
+ const host = await ready();
989
+ const tools = await manifest(context.principal.tenantId, context.principal.userId, context.principal.permissions ??
990
+ context.event.locals.permissions);
991
+ return [
992
+ ...tools
993
+ .filter((t) => !designRequests.has(context.event.request) || t.action === 'read')
994
+ .map((t) => t.slug),
995
+ ...(await extra(context)).map((t) => t.slug),
996
+ ];
997
+ };
998
+ // Exactly the execution memo generation. Never key a fallback by its resolved model.
999
+ async function workModelConnectionKey(tenantId, ownerId) {
1000
+ const host = await ready();
1001
+ return `${(await cli.cliStatus('claude-code')).version ?? 'unknown'}:${await host.state.engineGeneration(tenantId, ownerId)}:${(await host.workProfiles.read()).revision ?? 'recommended'}`;
1002
+ }
1003
+ async function resolveProfile(context, profile) {
1004
+ const host = await ready();
1005
+ const pinned = designRequests.get(context.event.request);
1006
+ if (pinned)
1007
+ return pinned.profile;
1008
+ const saved = await host.workProfiles.read();
1009
+ if (!profile) {
1010
+ const onboarding = host.onboarding
1011
+ ? await host.onboarding.load(context.event)
1012
+ : null;
1013
+ profile =
1014
+ onboarding && (!onboarding.completed || onboarding.rerunning)
1015
+ ? 'design'
1016
+ : 'assist';
1017
+ }
1018
+ const engine = (await host.state.engine(context.principal.tenantId, context.principal.userId)) ?? 'api';
1019
+ const selected = saved.settings[profile]?.engine ?? engine;
1020
+ return resolveWorkProfile({
1021
+ profile,
1022
+ engine,
1023
+ settings: saved.settings[profile],
1024
+ ...(selected === 'chatgpt'
1025
+ ? { catalog: await (await chatgpt()).models() }
1026
+ : {}),
1027
+ });
1028
+ }
1029
+ const workProfiles = {
1030
+ async read(event) {
1031
+ const principal = resolveAssistantPrincipalFromLocals(event.locals);
1032
+ if (!principal)
1033
+ error(401, 'Sign in required');
1034
+ const saved = await (await ready()).workProfiles.read();
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
+ }));
1066
+ return {
1067
+ ...saved,
1068
+ resolved,
1069
+ editable: typeof event.locals.sessionId === 'string' &&
1070
+ (await isOwner(principal.tenantId, principal.userId)),
1071
+ chatgptSignedIn: (await (await chatgpt()).status()).signedIn,
1072
+ };
1073
+ },
1074
+ async write(event, payload) {
1075
+ const principal = resolveAssistantPrincipalFromLocals(event.locals);
1076
+ if (!principal ||
1077
+ typeof event.locals.sessionId !== 'string' ||
1078
+ !(await isOwner(principal.tenantId, principal.userId)))
1079
+ error(403, 'Owner session required');
1080
+ if (!payload ||
1081
+ typeof payload !== 'object' ||
1082
+ !(payload.revision === null || typeof payload.revision === 'string'))
1083
+ error(400, 'Invalid settings');
1084
+ try {
1085
+ return await (await ready()).workProfiles.write(payload.settings, payload.revision, { confirmUnprotectedCli: payload.confirmUnprotectedCli === true });
1086
+ }
1087
+ catch (cause) {
1088
+ if (cause instanceof Error && cause.name === 'PreferenceAccessError')
1089
+ error(403, 'Owner confirmation required to change assistant safety');
1090
+ throw cause;
1091
+ }
1092
+ },
1093
+ async reset(event, revision) {
1094
+ const principal = resolveAssistantPrincipalFromLocals(event.locals);
1095
+ if (!principal ||
1096
+ typeof event.locals.sessionId !== 'string' ||
1097
+ !(await isOwner(principal.tenantId, principal.userId)))
1098
+ error(403, 'Owner required');
1099
+ if (!(revision === null || typeof revision === 'string'))
1100
+ error(400, 'Invalid revision');
1101
+ return (await ready()).workProfiles.reset(revision);
1102
+ },
1103
+ };
1104
+ const adapters = createInferenceAssistantAdapters({
1105
+ binding: async (c) => (await ready()).state
1106
+ .engine(c.principal.tenantId, c.principal.userId)
1107
+ .then((v) => v ?? undefined),
1108
+ status: async (c) => ({
1109
+ cliStatus: async (tool) => cli.cliStatus(tool, {
1110
+ protection: (await (await ready()).workProfiles.read()).settings.safety
1111
+ ?.protectLocalCli !== false,
1112
+ }),
1113
+ chatgpt: { status: async () => (await chatgpt()).status() },
1114
+ apiStatus: () => apiStatus(c),
1115
+ actions: { api: { label: 'Connect AI', href: '/settings/inference' } },
1116
+ }),
1117
+ chatgpt: async (context) => ({
1118
+ connection: await chatgpt(),
1119
+ fallback: {
1120
+ ownerId: context.principal.userId,
1121
+ connectionKey: `chatgpt:${JSON.stringify(await (await chatgpt()).models())}:${await (await ready()).state.engineGeneration(context.principal.tenantId, context.principal.userId)}:${(await (await ready()).workProfiles.read()).revision ?? 'recommended'}`,
1122
+ store: (await ready()).state.fallbackStore(context.principal.tenantId),
1123
+ },
1124
+ toolNamespace: { name: 'smrt_app', description: 'Work with this app' },
1125
+ settingsHref: '/settings',
1126
+ }),
1127
+ ...(options.assistant?.ai ? { api: options.assistant.ai } : {}),
1128
+ cli: (tool, context) => createAgentCliTurnDriver({
1129
+ tool,
1130
+ bind: async (turn) => {
1131
+ const host = await ready();
1132
+ if (!(await isOwner(context.principal.tenantId, context.principal.userId)))
1133
+ throw new Error('Owner required');
1134
+ const local = await runtime.localRuntime();
1135
+ const holder = `assistant-${randomUUID()}`;
1136
+ const listeners = new Set();
1137
+ let tokenHash;
1138
+ const models = await manifest(context.principal.tenantId, context.principal.userId, [...(turn.permissions ?? [])]);
1139
+ const names = new Map([
1140
+ ...models
1141
+ .filter((t) => turn.tools.some((v) => v.slug === t.slug))
1142
+ .map((t) => [t.functionName, t.slug]),
1143
+ ...turn.extraTools.map((t) => [t.aiTool.function.name, t.slug]),
1144
+ ]);
1145
+ const credentials = tokenCredentials(async () => local.mcpTokens, {
1146
+ holder,
1147
+ scopes: [
1148
+ // Mint only tools actually offered by this MCP bridge, not the
1149
+ // larger API permission catalog (which can exceed the token bound).
1150
+ ...new Set(names.values()),
1151
+ ].filter((s) => !turn.permissions || turn.permissions.includes(s)),
1152
+ label: 'Assistant turn',
1153
+ });
1154
+ return {
1155
+ protection: (await host.workProfiles.read()).settings.safety
1156
+ ?.protectLocalCli !== false,
1157
+ mcpUrl: new URL('/mcp', context.event.url).href,
1158
+ ...(designRequests.get(context.event.request)
1159
+ ? {
1160
+ outputSchema: designRequests.get(context.event.request)
1161
+ .schema,
1162
+ }
1163
+ : {}),
1164
+ ...(turn.workProfile?.model &&
1165
+ ((tool === 'claude-code' &&
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)))
1169
+ ? {
1170
+ fallback: {
1171
+ ownerId: context.principal.userId,
1172
+ connectionKey: await workModelConnectionKey(context.principal.tenantId, context.principal.userId),
1173
+ nextModel: tool === 'claude-code'
1174
+ ? turn.workProfile.model === 'fable'
1175
+ ? 'opus'
1176
+ : 'sonnet'
1177
+ : nextWorkModel(rankOpenAIWorkModels(Object.keys(OPENAI_WORK_MODEL_RANKS).map((id) => ({ id }))), turn.workProfile.model),
1178
+ store: host.state.fallbackStore(context.principal.tenantId),
1179
+ },
1180
+ }
1181
+ : {}),
1182
+ canonicalToolName: (name) => names.get(name),
1183
+ describeTool: (name, args, outcome) => {
1184
+ const model = models.find((entry) => entry.slug === name);
1185
+ return describePublicAssistantTool(model?.functionName
1186
+ ? `${model.functionName.slice(0, -(wireName(model.action).length + 1))}.${model.action}`
1187
+ : name, args, outcome);
1188
+ },
1189
+ allowTool: (name) => names.has(name),
1190
+ approvals: {
1191
+ subscribe: (listener) => {
1192
+ listeners.add(listener);
1193
+ let disposed = false;
1194
+ let polling = false;
1195
+ const poll = async () => {
1196
+ if (disposed || polling)
1197
+ return;
1198
+ polling = true;
1199
+ try {
1200
+ const records = await host.authority.list({
1201
+ id: context.principal.userId,
1202
+ tenantId: context.principal.tenantId,
1203
+ }, false);
1204
+ for (const record of records)
1205
+ if (!disposed &&
1206
+ record.requestedBy === context.principal.userId &&
1207
+ record.context.cliTurnId === holder &&
1208
+ record.context.threadId === turn.thread?.id &&
1209
+ record.status !== 'pending')
1210
+ listener({
1211
+ id: record.id,
1212
+ status: record.status === 'succeeded'
1213
+ ? 'approved'
1214
+ : record.status === 'expired'
1215
+ ? 'timeout'
1216
+ : record.status === 'executing'
1217
+ ? 'pending'
1218
+ : record.status,
1219
+ });
1220
+ }
1221
+ catch {
1222
+ /* get() fails closed when the observer cannot read. */
1223
+ }
1224
+ finally {
1225
+ polling = false;
1226
+ }
1227
+ };
1228
+ const timer = setInterval(() => {
1229
+ void poll();
1230
+ }, 100);
1231
+ return () => {
1232
+ disposed = true;
1233
+ listeners.delete(listener);
1234
+ clearInterval(timer);
1235
+ };
1236
+ },
1237
+ get: async (id) => {
1238
+ const record = await host.authority.get(context.principal.tenantId, id);
1239
+ return record &&
1240
+ record.requestedBy === context.principal.userId &&
1241
+ record.context.cliTurnId === holder &&
1242
+ record.context.threadId === turn.thread?.id
1243
+ ? {
1244
+ id,
1245
+ status: record.status === 'succeeded'
1246
+ ? 'approved'
1247
+ : record.status === 'executing'
1248
+ ? 'pending'
1249
+ : record.status === 'expired'
1250
+ ? 'timeout'
1251
+ : record.status,
1252
+ summary: record.summary,
1253
+ preview: null,
1254
+ }
1255
+ : null;
1256
+ },
1257
+ },
1258
+ deps: {
1259
+ locate: (selected) => locateCli(selected, cli.agentCliDeps()),
1260
+ stateDir: async () => local.paths.root,
1261
+ baseEnv: cli.agentCliDeps().env,
1262
+ credentials: {
1263
+ mint: async (pass) => {
1264
+ const token = await credentials.mint(pass);
1265
+ const verified = await runtime.verifyLocalMcpToken(token);
1266
+ if (verified?.id !== context.principal.userId ||
1267
+ verified.tenantId !== context.principal.tenantId) {
1268
+ await credentials.revoke();
1269
+ throw new Error('The local credential does not match this turn');
1270
+ }
1271
+ tokenHash = digest(token);
1272
+ turns.set(tokenHash, {
1273
+ context,
1274
+ turn,
1275
+ id: holder,
1276
+ toolCalls: 0,
1277
+ startedAt: Date.now(),
1278
+ approvalRequired: (id) => {
1279
+ for (const listener of listeners)
1280
+ listener({ id, status: 'pending' });
1281
+ },
1282
+ });
1283
+ return token;
1284
+ },
1285
+ revoke: async () => {
1286
+ if (tokenHash)
1287
+ turns.delete(tokenHash);
1288
+ await credentials.revoke();
1289
+ },
1290
+ },
1291
+ },
1292
+ };
1293
+ },
1294
+ }),
1295
+ });
1296
+ const assistantRoutes = mountAssistantRoutes({
1297
+ runtime,
1298
+ resolvePrincipal: (event) => {
1299
+ const principal = resolveAssistantPrincipalFromLocals(event.locals);
1300
+ return principal
1301
+ ? {
1302
+ ...principal,
1303
+ permissions: [
1304
+ ...(event.locals.permissions ?? []),
1305
+ ],
1306
+ }
1307
+ : null;
1308
+ },
1309
+ ...adapters,
1310
+ resolveWorkProfile: resolveProfile,
1311
+ internalTurn: (context) => {
1312
+ const design = designRequests.get(context.event.request);
1313
+ return design ? { userMessage: design.content } : undefined;
1314
+ },
1315
+ deferDesignTurn: (context) => !designRequests.has(context.event.request),
1316
+ onDesignEscalation: async (context, input) => {
1317
+ const original = input.userMessage ??
1318
+ [...(input.history ?? [])]
1319
+ .reverse()
1320
+ .find((message) => message.role === 'user')?.content;
1321
+ if (!input.thread?.id || typeof original !== 'string' || !original.trim())
1322
+ throw new Error('Design runs require a saved thread and user request');
1323
+ const host = await ready();
1324
+ const profile = await resolveProfile(context, 'design');
1325
+ const fixedPasses = Object.hasOwn((await host.workProfiles.read()).settings.design?.budgets ?? {}, 'passes');
1326
+ const state = await host.designRuns
1327
+ .forOwner(context.principal.userId, context.principal.tenantId)
1328
+ .start({
1329
+ threadId: String(input.thread.id),
1330
+ content: original,
1331
+ profile,
1332
+ fixedPasses,
1333
+ permissions: [...(context.principal.permissions ?? [])],
1334
+ });
1335
+ return { runId: state.id, message: 'Thinking this through' };
1336
+ },
1337
+ designTools: COOKBOOK_TOOL_NAMES.filter((name) => /^(recipes\.(enable|disable|configure)|cookbook\.apply|app\.(add|remove|rename|hide))/.test(name)),
1338
+ allowedTools: allowed,
1339
+ tools: (context) => manifest(context.principal.tenantId, context.principal.userId, context.principal.permissions ??
1340
+ context.event.locals.permissions),
1341
+ extraTools: extra,
1342
+ approvalContinuations: async () => (await ready()).continuations,
1343
+ // These tools hold in their own canonical service; never create a second chat hold.
1344
+ approvalPolicy: async () => ({
1345
+ allowRemovalsInChat: (await (await ready()).workProfiles.read()).settings.safety
1346
+ ?.requireRemovalApproval === false,
1347
+ tools: Object.fromEntries(COOKBOOK_TOOL_NAMES.map((name) => [name, false])),
1348
+ }),
1349
+ ...options.assistant,
1350
+ toolPresentation: 'generic',
1351
+ presentApproval: async (record) => {
1352
+ const binding = record.continuation?.principal;
1353
+ const client = Object.values(PLUGIN_CLIENTS).find((label) => label === binding?.clientName);
1354
+ if (COOKBOOK_TOOL_NAMES.includes(record.tool)) {
1355
+ let caption = client && record.summary.startsWith(`${client}: `)
1356
+ ? record.summary.slice(client.length + 2)
1357
+ : record.summary;
1358
+ if (record.tool === 'cookbook.apply') {
1359
+ const template = ((await ready()).catalog.cookbooks ?? BUNDLED_COOKBOOK_TEMPLATES).find((entry) => entry.id === record.args.id);
1360
+ caption = template ? `Use ${template.name}.` : caption;
1361
+ }
1362
+ else if (['recipes.enable', 'recipes.disable', 'recipes.configure'].includes(record.tool)) {
1363
+ const recipe = (await ready()).catalog.recipes.find((entry) => entry.id === record.args.id);
1364
+ if (recipe)
1365
+ caption = `${record.tool === 'recipes.enable' ? 'Enabled' : record.tool === 'recipes.disable' ? 'Disabled' : 'Configured'} ${recipe.label}.`;
1366
+ }
1367
+ const summary = record.tool === 'app.undo'
1368
+ ? record.status === 'succeeded'
1369
+ ? 'Reversed the last structure change'
1370
+ : 'Reverse the last structure change'
1371
+ : personChangeSummary(caption, record.status !== 'succeeded');
1372
+ return summary
1373
+ ? { summary: client ? `${client}: ${summary}` : summary }
1374
+ : undefined;
1375
+ }
1376
+ if (record.continuation?.executor !== 'model' || !binding)
1377
+ return undefined;
1378
+ if (!binding.allowedTools.includes(record.tool))
1379
+ return undefined;
1380
+ // Match the continuation executor's catalog. Plugin/thread tools use the
1381
+ // app manifest; an API-native action need not also be a generated MCP tool.
1382
+ const native = record.context.pluginMode === true || record.context.threadId;
1383
+ const generated = native
1384
+ ? undefined
1385
+ : (await mcpModels({
1386
+ id: record.requestedBy,
1387
+ tenantId: record.tenantId,
1388
+ scopes: binding.permissions,
1389
+ }, true)).find((entry) => entry.tool.slug === record.tool);
1390
+ const tool = native
1391
+ ? (await manifest(record.tenantId, record.requestedBy, binding.permissions)).find((entry) => entry.slug === record.tool)
1392
+ : generated?.tool;
1393
+ let noun = generated?.noun;
1394
+ if (native && tool) {
1395
+ const host = await ready();
1396
+ const document = host.state
1397
+ .engineFor({ tenantId: record.tenantId })
1398
+ ?.cookbook();
1399
+ const shell = document
1400
+ ? buildCookbookShell({ cookbook: document, catalog: host.catalog })
1401
+ : undefined;
1402
+ noun = modelPlacement(shell, tool.qualifiedName ?? tool.className)?.noun;
1403
+ }
1404
+ const action = tool?.action;
1405
+ if (!noun ||
1406
+ !['delete', 'create', 'update'].includes(action ?? '') ||
1407
+ !personChangeSummary(`Added ${noun}.`))
1408
+ return undefined;
1409
+ const verb = record.status === 'succeeded'
1410
+ ? action === 'delete'
1411
+ ? 'Deleted'
1412
+ : action === 'create'
1413
+ ? 'Added'
1414
+ : 'Updated'
1415
+ : action === 'delete'
1416
+ ? 'Delete'
1417
+ : action === 'create'
1418
+ ? 'Add'
1419
+ : 'Update';
1420
+ return { summary: `${client ? `${client}: ` : ''}${verb} ${noun}` };
1421
+ },
1422
+ describeTool: describePublicAssistantTool,
1423
+ systemPrompt: async (context) => {
1424
+ const base = options.assistant?.systemPrompt;
1425
+ const prompt = typeof base === 'function'
1426
+ ? await base(context)
1427
+ : (base ??
1428
+ "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
+ const design = designRequests.get(context.event.request);
1430
+ return design ? `${prompt}\n\n${design.prompt}` : prompt;
1431
+ },
1432
+ formatAssistantReply: (content, context) => {
1433
+ if (!designRequests.has(context.event.request))
1434
+ return { content };
1435
+ let output;
1436
+ try {
1437
+ output = JSON.parse(content);
1438
+ }
1439
+ catch {
1440
+ output = content;
1441
+ }
1442
+ return {
1443
+ content: 'I’m checking the requested changes.',
1444
+ metadata: { designOutput: output },
1445
+ };
1446
+ },
1447
+ });
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
+ const assistantHandler = async (event) => {
1465
+ const path = event.params?.path ?? '';
1466
+ if (!path.startsWith('design-runs')) {
1467
+ const response = await assistantRoutes.handle(event);
1468
+ const decision = /^approvals\/([^/]+)\/decide$/.exec(path);
1469
+ const actor = resolveAssistantPrincipalFromLocals(event.locals);
1470
+ if (response.ok && decision && event.request.method === 'POST' && actor) {
1471
+ const host = await ready();
1472
+ const record = await host.authority.get(actor.tenantId, decision[1]);
1473
+ const action = record?.context.designAction;
1474
+ if (record &&
1475
+ typeof action?.runId === 'string' &&
1476
+ ['succeeded', 'denied', 'failed', 'expired'].includes(record.status)) {
1477
+ // Native decision is already durable. Queue only its deterministic
1478
+ // check; a status read can retry admission after a transient conflict.
1479
+ try {
1480
+ await host.designRuns
1481
+ .forOwner(record.requestedBy, record.tenantId)
1482
+ .resumeAfterApproval(action.runId);
1483
+ }
1484
+ catch {
1485
+ /* durable hold/outcome remains available */
1486
+ }
1487
+ }
1488
+ }
1489
+ return response;
1490
+ }
1491
+ const p = resolveAssistantPrincipalFromLocals(event.locals);
1492
+ if (!p || !(await isOwner(p.tenantId, p.userId)))
1493
+ return json({ code: 'not_allowed' }, 403);
1494
+ const runs = (await ready()).designRuns.forOwner(p.userId, p.tenantId);
1495
+ try {
1496
+ if (path === 'design-runs' && event.request.method === 'GET') {
1497
+ const threadId = event.url.searchParams.get('threadId');
1498
+ let state = threadId ? await runs.latest(threadId) : null;
1499
+ const pending = state?.input &&
1500
+ state.input.pendingApprovalId;
1501
+ if (state?.status === 'waiting-approval' &&
1502
+ typeof pending === 'string') {
1503
+ const record = await (await ready()).authority.get(p.tenantId, pending);
1504
+ if (record?.requestedBy === p.userId &&
1505
+ ['succeeded', 'denied', 'failed', 'expired'].includes(record.status)) {
1506
+ try {
1507
+ state = await runs.resumeAfterApproval(state.id);
1508
+ }
1509
+ catch {
1510
+ /* retry on next status read */
1511
+ }
1512
+ }
1513
+ }
1514
+ return json({
1515
+ run: designProgress(state),
1516
+ });
1517
+ }
1518
+ if (path === 'design-runs' && event.request.method === 'POST') {
1519
+ if (event.request.headers.get('origin') !== event.url.origin)
1520
+ return json({ code: 'invalid_origin' }, 403);
1521
+ if (!/^application\/json\b/i.test(event.request.headers.get('content-type') ?? ''))
1522
+ return json({ code: 'invalid_design_request' }, 415);
1523
+ // Chat's bounded JSON reader is private; keep this route's small bound
1524
+ // at its own request boundary rather than buffering an unbounded body.
1525
+ const maxBytes = 128 * 1024;
1526
+ if (Number(event.request.headers.get('content-length')) > maxBytes)
1527
+ return json({ code: 'payload_too_large' }, 413);
1528
+ const reader = event.request.body?.getReader();
1529
+ const decoder = new TextDecoder();
1530
+ let size = 0;
1531
+ let text = '';
1532
+ if (reader)
1533
+ for (;;) {
1534
+ const { value, done } = await reader.read();
1535
+ if (done)
1536
+ break;
1537
+ size += value.byteLength;
1538
+ if (size > maxBytes) {
1539
+ await reader.cancel();
1540
+ return json({ code: 'payload_too_large' }, 413);
1541
+ }
1542
+ text += decoder.decode(value, { stream: true });
1543
+ }
1544
+ let body = null;
1545
+ try {
1546
+ const parsed = JSON.parse(text + decoder.decode());
1547
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
1548
+ body = parsed;
1549
+ }
1550
+ catch {
1551
+ return json({ code: 'invalid_design_request' }, 400);
1552
+ }
1553
+ if (!body ||
1554
+ typeof body !== 'object' ||
1555
+ Array.isArray(body) ||
1556
+ Object.keys(body).some((key) => key !== 'threadId' && key !== 'content') ||
1557
+ typeof body.threadId !== 'string' ||
1558
+ !body.threadId ||
1559
+ body.threadId.length > 200 ||
1560
+ typeof body.content !== 'string' ||
1561
+ !body.content.trim() ||
1562
+ body.content.length > 32_000)
1563
+ return json({ code: 'invalid_design_request' }, 400);
1564
+ // Reuse chat's own session/thread ownership boundary before admission.
1565
+ const thread = await assistantRoutes.GET({
1566
+ ...event,
1567
+ request: new Request(event.request.url, {
1568
+ method: 'GET',
1569
+ headers: event.request.headers,
1570
+ }),
1571
+ params: {
1572
+ ...event.params,
1573
+ path: `threads/${encodeURIComponent(body.threadId)}/messages`,
1574
+ },
1575
+ });
1576
+ if (!thread.ok)
1577
+ return thread;
1578
+ const profile = await resolveProfile({ event, principal: p }, 'design');
1579
+ const state = await runs.start({
1580
+ threadId: body.threadId,
1581
+ content: body.content,
1582
+ profile,
1583
+ fixedPasses: Object.hasOwn((await (await ready()).workProfiles.read()).settings.design
1584
+ ?.budgets ?? {}, 'passes'),
1585
+ permissions: [
1586
+ ...(p.permissions ??
1587
+ event.locals.permissions ??
1588
+ []),
1589
+ ],
1590
+ });
1591
+ return json({ run: designProgress(state) }, 202);
1592
+ }
1593
+ const match = /^design-runs\/([^/]+)\/(stop|resume)$/.exec(path);
1594
+ if (!match || event.request.method !== 'POST')
1595
+ return json({ code: 'not_found' }, 404);
1596
+ if (event.request.headers.get('origin') !== event.url.origin)
1597
+ return json({ code: 'invalid_origin' }, 403);
1598
+ const saved = await (await ready()).workProfiles.read();
1599
+ const budgets = {
1600
+ ...recommendedWorkProfile('design').budgets,
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.
1605
+ const state = match[2] === 'stop'
1606
+ ? await runs.stop(match[1])
1607
+ : await runs.resume(match[1], {
1608
+ maxTokens: budgets.maxRunTokens,
1609
+ maxDurationMs: budgets.runTimeoutMs,
1610
+ });
1611
+ return json({ run: designProgress(state) });
1612
+ }
1613
+ catch {
1614
+ return json({ code: 'design_run_unavailable' }, 409);
1615
+ }
1616
+ };
1617
+ const assistant = { ...assistantRoutes, handle: assistantHandler };
1618
+ assistant.GET = assistantHandler;
1619
+ assistant.POST = assistantHandler;
1620
+ const handle = (input) => {
1621
+ // Serve the browser's conventional icon request through the shipped icon.
1622
+ if (input.event.url.pathname === '/favicon.ico')
1623
+ return Promise.resolve(new Response(null, {
1624
+ status: 308,
1625
+ headers: {
1626
+ location: '/favicon.svg',
1627
+ 'cache-control': 'public, max-age=86400',
1628
+ },
1629
+ }));
1630
+ return runtime.handle({
1631
+ ...input,
1632
+ resolve: async (event, resolveOptions) => {
1633
+ origin = event.url.origin;
1634
+ const locals = event.locals;
1635
+ if (locals.tenantId) {
1636
+ await prepare(locals.tenantId);
1637
+ const definition = publishedDefinitions
1638
+ .get(locals.tenantId)
1639
+ ?.find((d) => event.url.pathname === `/api/${d.name}` ||
1640
+ event.url.pathname.startsWith(`/api/${d.name}/`));
1641
+ if (definition && locals.user?.id)
1642
+ return new APIGenerator({
1643
+ basePath: '/api',
1644
+ authMiddleware: () => async (request) => request,
1645
+ }, {
1646
+ tenantId: locals.tenantId,
1647
+ user: { id: locals.user.id },
1648
+ permissions: locals.permissions,
1649
+ db: runtime.databaseConfig(),
1650
+ }).generateHandler()(event.request);
1651
+ }
1652
+ return input.resolve(event, resolveOptions);
1653
+ },
1654
+ });
1655
+ };
1656
+ const session = createSessionLayoutLoad();
1657
+ const assistantToolCatalog = async (actor) => runtime.runAsPrincipal(actor, async (bound) => {
1658
+ const host = await prepare(actor.tenantId);
1659
+ const scopes = [...(bound?.scopes ?? [])];
1660
+ const context = {
1661
+ principal: {
1662
+ userId: actor.id,
1663
+ tenantId: actor.tenantId,
1664
+ permissions: scopes,
1665
+ },
1666
+ };
1667
+ const shell = buildCookbookShell({
1668
+ cookbook: host.state.engineFor(actor).cookbook(),
1669
+ catalog: host.catalog,
1670
+ });
1671
+ const nativeDefinitions = new Map((await host.service.list({
1672
+ surface: 'assistant',
1673
+ tenantId: actor.tenantId,
1674
+ userId: actor.id,
1675
+ })).map((tool) => [tool.name, tool.annotations]));
1676
+ return [
1677
+ ...(await manifest(actor.tenantId, actor.id, scopes)).map((tool) => ({
1678
+ definition: manifestToolToAITool(tool, actor.tenantId).function,
1679
+ source: 'model',
1680
+ annotations: {
1681
+ readOnlyHint: tool.action === 'read',
1682
+ destructiveHint: requiresOwnerApproval(tool, {}),
1683
+ idempotentHint: tool.action === 'read',
1684
+ openWorldHint: false,
1685
+ },
1686
+ model: tool.qualifiedName ?? tool.className,
1687
+ operation: tool.action,
1688
+ recipe: [...shell.entries.values()].find((entry) => ObjectRegistry.getClass(entry.model.id)?.qualifiedName ===
1689
+ ObjectRegistry.getClass(tool.qualifiedName ?? tool.className)
1690
+ ?.qualifiedName)?.recipeId ?? undefined,
1691
+ })),
1692
+ ...(await extra(context))
1693
+ .filter((tool) => scopes.includes(tool.slug))
1694
+ .map((tool) => ({
1695
+ definition: tool.aiTool.function,
1696
+ annotations: nativeDefinitions.get(tool.slug),
1697
+ source: tool.slug === 'app.approvals'
1698
+ ? 'lifecycle'
1699
+ : tool.slug.startsWith('app.')
1700
+ ? 'app'
1701
+ : 'recipe',
1702
+ })),
1703
+ ];
1704
+ });
1705
+ const pluginMode = createPluginMode({
1706
+ runtime,
1707
+ sourceRoot: options.root ?? process.cwd(),
1708
+ name: options.application ?? 'smrt-app',
1709
+ state: async () => (await ready()).state,
1710
+ tools: assistantToolCatalog,
1711
+ authorize: async (event) => {
1712
+ const p = resolveAssistantPrincipalFromLocals(event.locals);
1713
+ if (!p)
1714
+ return null;
1715
+ const local = await runtime.localRuntime();
1716
+ const id = event.cookies.get(runtime.sessionCookie.name);
1717
+ const restored = id ? await local.restoreSession(id) : null;
1718
+ if (!restored ||
1719
+ restored.user.id !== p.userId ||
1720
+ restored.tenantId !== p.tenantId ||
1721
+ restored.parent ||
1722
+ restored.permissionCeiling !== null ||
1723
+ !['local-bootstrap', 'password', 'passkey'].includes(restored.authMethod ?? ''))
1724
+ return null;
1725
+ if (!(await local.mcpTokens?.isOwnerSession?.({
1726
+ userId: p.userId,
1727
+ tenantId: p.tenantId,
1728
+ })))
1729
+ return null;
1730
+ return { id: p.userId, tenantId: p.tenantId };
1731
+ },
1732
+ });
1733
+ async function load(event) {
1734
+ const data = await session(event);
1735
+ const host = await ready();
1736
+ const tenantId = event.locals.tenantId;
1737
+ const engine = tenantId ? host.state.engineFor({ tenantId }) : undefined;
1738
+ const snapshot = engine?.snapshot();
1739
+ const visible = snapshot
1740
+ ? filterRuntimeCookbookSnapshot(snapshot, host.catalog, { tenantId })
1741
+ : undefined;
1742
+ const p = resolveAssistantPrincipalFromLocals(event.locals);
1743
+ const onboarding = p && host.onboarding ? await host.onboarding.load(event) : null;
1744
+ const allowedSlugs = p
1745
+ ? new Set(await allowed({ event, principal: p }))
1746
+ : new Set();
1747
+ const offered = p
1748
+ ? (await manifest(p.tenantId, p.userId, [...allowedSlugs])).filter((t) => allowedSlugs.has(t.slug))
1749
+ : [];
1750
+ const extras = p
1751
+ ? await host.service.list({
1752
+ surface: 'assistant',
1753
+ tenantId: p.tenantId,
1754
+ userId: p.userId,
1755
+ })
1756
+ : [];
1757
+ const connectStatus = p ? await connectAi.GET(event) : null;
1758
+ const connected = connectStatus?.ok
1759
+ ? (await connectStatus.json()).configured === true
1760
+ : false;
1761
+ const introductionShell = engine && visible
1762
+ ? buildCookbookShell({
1763
+ cookbook: {
1764
+ ...engine.cookbook(),
1765
+ recipes: visible.recipes.map((recipe) => recipe.id),
1766
+ features: visible.features,
1767
+ },
1768
+ catalog: host.catalog,
1769
+ })
1770
+ : null;
1771
+ const navigation = introductionShell
1772
+ ? applyShellLayout([], introductionShell.navGroups, undefined, introductionShell.layout)
1773
+ : null;
1774
+ return {
1775
+ assistantToolCatalog: p && tenantId && (await isOwner(tenantId, p.userId))
1776
+ ? await assistantToolCatalog({ id: p.userId, tenantId })
1777
+ : [],
1778
+ ...data,
1779
+ embed: p ? await host.state.embed(p.tenantId, p.userId) : false,
1780
+ onboarding,
1781
+ assistantIntroduction: p
1782
+ ? {
1783
+ lists: navigation
1784
+ ? [
1785
+ ...navigation.nav,
1786
+ ...navigation.groups.flatMap((group) => group.items.slice(0, 1)),
1787
+ ...navigation.groups.flatMap((group) => group.items.slice(1)),
1788
+ ].map((item) => item.label)
1789
+ : [],
1790
+ actions: [
1791
+ ...new Set(offered
1792
+ .map((t) => t.action)
1793
+ .filter((a) => ['read', 'create', 'update', 'delete'].includes(a) &&
1794
+ offered.every((tool) => offered.some((candidate) => candidate.collection === tool.collection &&
1795
+ candidate.action === a)))),
1796
+ ...(extras.some((t) => t.name === 'app.addList')
1797
+ ? ['customize']
1798
+ : []),
1799
+ ],
1800
+ configured: connected,
1801
+ }
1802
+ : undefined,
1803
+ dynamicDefinitions: tenantId
1804
+ ? (publishedDefinitions.get(tenantId) ?? [])
1805
+ : [],
1806
+ enabledModels: filterRuntimeExposure(host.catalog.models, (m) => ObjectRegistry.getExposureModel(m.id), { surface: 'screen', tenantId }).map((m) => ObjectRegistry.getClass(m.id)?.qualifiedName ?? m.id),
1807
+ cookbookApp: {
1808
+ cookbook: {
1809
+ ...(engine?.cookbook() ?? host.cookbook),
1810
+ recipes: visible?.recipes.map((r) => r.id) ?? [],
1811
+ features: visible?.features ?? [],
1812
+ },
1813
+ catalog: host.catalog,
1814
+ warnings: [],
1815
+ },
1816
+ };
1817
+ }
1818
+ const connectAi = mountConnectAiRoutes({
1819
+ authorize: async (event) => {
1820
+ const principal = resolveAssistantPrincipalFromLocals(event.locals);
1821
+ if (!principal ||
1822
+ !(await isOwner(principal.tenantId, principal.userId)) ||
1823
+ !event.locals.permissions?.includes('inference.customize'))
1824
+ return null;
1825
+ const host = await ready();
1826
+ return {
1827
+ engine: () => host.state.engine(principal.tenantId, principal.userId),
1828
+ select: (engine) => host.state.select(principal.tenantId, principal.userId, engine),
1829
+ cli: {
1830
+ ...cli,
1831
+ cliStatus: async (tool, statusOptions) => runtime.runAsPrincipal({ id: principal.userId, tenantId: principal.tenantId }, async () => cli.cliStatus(tool, {
1832
+ ...statusOptions,
1833
+ protection: (await host.workProfiles.read()).settings.safety
1834
+ ?.protectLocalCli !== false,
1835
+ })),
1836
+ },
1837
+ chatgpt: await chatgpt(),
1838
+ apiStatus: () => apiStatus({ event, principal }),
1839
+ };
1840
+ },
1841
+ });
1842
+ return {
1843
+ runtime,
1844
+ handle,
1845
+ init: async () => {
1846
+ await ready();
1847
+ },
1848
+ shutdown,
1849
+ load,
1850
+ assistant,
1851
+ connectAi,
1852
+ pluginMode: pluginMode.handle,
1853
+ inferenceSettings,
1854
+ workProfiles,
1855
+ async history(event) {
1856
+ if (event.request.method !== 'GET')
1857
+ return json({ code: 'method_not_allowed' }, 405);
1858
+ const principal = resolveAssistantPrincipalFromLocals(event.locals);
1859
+ if (!principal || !(await isOwner(principal.tenantId, principal.userId)))
1860
+ return json({ code: 'not_allowed' }, 403);
1861
+ const snapshot = principal.permissions ??
1862
+ event.locals.permissions ??
1863
+ [];
1864
+ if (!snapshot.includes('app.history'))
1865
+ return json({ code: 'not_allowed' }, 403);
1866
+ try {
1867
+ return await runtime.runAsPrincipal({
1868
+ id: principal.userId,
1869
+ tenantId: principal.tenantId,
1870
+ kind: 'human',
1871
+ scopes: [...snapshot],
1872
+ }, async () => {
1873
+ const host = await prepare(principal.tenantId, false);
1874
+ const result = await host.service.invoke('app.history', {}, {
1875
+ surface: 'mcp',
1876
+ tenantId: principal.tenantId,
1877
+ userId: principal.userId,
1878
+ });
1879
+ if (result.status !== 'ok' || !Array.isArray(result.changes))
1880
+ throw new Error('History unavailable');
1881
+ const entries = result.changes
1882
+ .flatMap((value) => {
1883
+ if (!value || typeof value !== 'object')
1884
+ return [];
1885
+ const row = value;
1886
+ if (!Number.isSafeInteger(row.revision))
1887
+ return [];
1888
+ return [
1889
+ {
1890
+ id: String(row.revision),
1891
+ action: row.change?.type ===
1892
+ 'undo'
1893
+ ? 'Reversed the last structure change'
1894
+ : (personChangeSummary(row.summary) ??
1895
+ 'Changed your app'),
1896
+ resourceType: 'Your app',
1897
+ resourceId: 'Changes',
1898
+ ...(row.actor === principal.userId
1899
+ ? { actorLabel: 'You' }
1900
+ : {}),
1901
+ ...(row.status === 'pending'
1902
+ ? { reason: 'Activation pending' }
1903
+ : {}),
1904
+ },
1905
+ ];
1906
+ })
1907
+ .reverse();
1908
+ return json({ revision: result.revision, entries });
1909
+ });
1910
+ }
1911
+ catch {
1912
+ return json({ code: 'history_unavailable' }, 403);
1913
+ }
1914
+ },
1915
+ async onboarding(event) {
1916
+ const mounted = (await ready()).onboarding;
1917
+ return mounted ? mounted.handle(event) : json({ code: 'not_found' }, 404);
1918
+ },
1919
+ async modelEditor(tenantId) {
1920
+ await prepare(tenantId);
1921
+ return editors.get(tenantId);
1922
+ },
1923
+ ownerLink: createOwnerLinkHandler(runtime, { autoClaim: true }),
1924
+ /** Request-scoped: never pass a browser tenant id or retain this across requests. */
1925
+ async cookbookApp(tenantId) {
1926
+ const host = await ready();
1927
+ const engine = host.state.engineFor({ tenantId });
1928
+ if (!engine)
1929
+ throw new Error('Cookbook unavailable');
1930
+ const visible = filterRuntimeCookbookSnapshot(engine.snapshot(), host.catalog, { tenantId });
1931
+ return {
1932
+ cookbook: {
1933
+ ...engine.cookbook(),
1934
+ recipes: visible.recipes.map((r) => r.id),
1935
+ features: visible.features,
1936
+ },
1937
+ catalog: host.catalog,
1938
+ warnings: [],
1939
+ };
1940
+ },
1941
+ async prebuilt(event) {
1942
+ const p = resolveAssistantPrincipalFromLocals(event.locals);
1943
+ if (!p || !(await isOwner(p.tenantId, p.userId)))
1944
+ return json({ code: 'not_allowed' }, 403);
1945
+ const host = await ready();
1946
+ if (event.request.method === 'GET')
1947
+ return json(await host.preferences.read());
1948
+ if (event.request.method !== 'POST')
1949
+ return json({ code: 'method_not_allowed' }, 405);
1950
+ if (event.request.headers.get('origin') !== event.url.origin)
1951
+ return json({ code: 'invalid_origin' }, 403);
1952
+ if (event.request.headers.get('content-type')?.split(';')[0].trim() !==
1953
+ 'application/json')
1954
+ return json({ code: 'invalid_request' }, 415);
1955
+ const reader = event.request.body?.getReader();
1956
+ if (!reader)
1957
+ return json({ code: 'invalid_request' }, 400);
1958
+ let body;
1959
+ try {
1960
+ const chunks = [];
1961
+ let size = 0;
1962
+ for (;;) {
1963
+ const part = await reader.read();
1964
+ if (part.done)
1965
+ break;
1966
+ size += part.value.length;
1967
+ if (size > 4096) {
1968
+ await reader.cancel();
1969
+ return json({ code: 'body_too_large' }, 413);
1970
+ }
1971
+ chunks.push(part.value);
1972
+ }
1973
+ body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
1974
+ }
1975
+ catch {
1976
+ return json({ code: 'invalid_request' }, 400);
1977
+ }
1978
+ finally {
1979
+ reader.releaseLock();
1980
+ }
1981
+ if (!body ||
1982
+ Array.isArray(body) ||
1983
+ typeof body !== 'object' ||
1984
+ Object.keys(body).some((key) => !['enabled', 'revision'].includes(key)) ||
1985
+ typeof body.enabled !== 'boolean' ||
1986
+ !(body.revision === null || typeof body.revision === 'string'))
1987
+ return json({ code: 'invalid_request' }, 400);
1988
+ try {
1989
+ const result = await host.preferences.write(body.enabled, body.revision);
1990
+ return json(result, result.ok ? 200 : 409);
1991
+ }
1992
+ catch (error) {
1993
+ return json({ code: 'not_allowed' }, error.name === 'PreferenceAccessError' ? 403 : 503);
1994
+ }
1995
+ },
1996
+ async mcp(event) {
1997
+ const host = await ready();
1998
+ const bearer = event.request.headers
1999
+ .get('authorization')
2000
+ ?.match(/^Bearer (.+)$/i)?.[1];
2001
+ const locals = event.locals;
2002
+ // This one delegation scope grants only the live app tool surface, not
2003
+ // arbitrary owner permissions. Ordinary operation-scoped tokens stay narrow.
2004
+ let pluginDelegated = false;
2005
+ const verifyPluginToken = async (token) => {
2006
+ const verified = await runtime.verifyLocalMcpToken(token);
2007
+ if (!verified)
2008
+ return null;
2009
+ const local = await runtime.localRuntime();
2010
+ const issued = verified.tokenId
2011
+ ? (await local.mcpTokens?.list())?.find((record) => record.id === verified.tokenId)
2012
+ : undefined;
2013
+ // Opt-in follows the issued ceiling, never a live intersection that
2014
+ // shrank after permission removal. A mixed token must stay narrow.
2015
+ if (!issued)
2016
+ return verified.scopes.length === 1 &&
2017
+ verified.scopes[0] === PLUGIN_PERMISSION
2018
+ ? null
2019
+ : verified;
2020
+ if (issued.status !== 'active')
2021
+ return null;
2022
+ if (issued.scopes.length !== 1 ||
2023
+ issued.scopes[0] !== PLUGIN_PERMISSION)
2024
+ return verified;
2025
+ if (!verified.scopes.includes(PLUGIN_PERMISSION))
2026
+ return null;
2027
+ pluginDelegated = true;
2028
+ if (!(await local.mcpTokens?.isOwnerSession?.({
2029
+ userId: verified.id,
2030
+ tenantId: verified.tenantId,
2031
+ })))
2032
+ return null;
2033
+ return runtime.runAsPrincipal(verified, async () => {
2034
+ await prepare(verified.tenantId);
2035
+ const held = (await (await PermissionResolver.create({ db: await runtime.database() })).resolvePermissions(verified.id, verified.tenantId)).permissions;
2036
+ const offered = new Set([
2037
+ ...(await manifest(verified.tenantId, verified.id, [...held])).map((tool) => tool.slug),
2038
+ ...(await extra({
2039
+ principal: {
2040
+ userId: verified.id,
2041
+ tenantId: verified.tenantId,
2042
+ permissions: [...held],
2043
+ },
2044
+ })).map((tool) => tool.slug),
2045
+ ]);
2046
+ return {
2047
+ ...verified,
2048
+ ...(verified.clientName ? { clientName: verified.clientName } : {}),
2049
+ scopes: [...held].filter((scope) => offered.has(scope)),
2050
+ };
2051
+ });
2052
+ };
2053
+ const verified = bearer ? await verifyPluginToken(bearer) : null;
2054
+ const clientName = verified?.clientName;
2055
+ const principal = verified
2056
+ ? { ...verified, scopes: [...verified.scopes] }
2057
+ : !bearer && locals.user?.id && locals.tenantId
2058
+ ? {
2059
+ id: locals.user.id,
2060
+ tenantId: locals.tenantId,
2061
+ kind: 'human',
2062
+ scopes: locals.permissions,
2063
+ }
2064
+ : null;
2065
+ const binding = bearer ? turns.get(digest(bearer)) : undefined;
2066
+ if (binding?.turn.signal.aborted)
2067
+ return json({ code: 'turn_ended' }, 401);
2068
+ let workflows = [];
2069
+ if (principal?.id && principal.tenantId)
2070
+ await runtime.runAsPrincipal({ ...principal, id: principal.id }, async (bound) => {
2071
+ await prepare(principal.tenantId);
2072
+ const scope = new Set(bound?.scopes ?? []);
2073
+ const modelTools = (pluginDelegated || binding
2074
+ ? []
2075
+ : await mcpModels({ ...principal, scopes: [...scope] }, !!binding)).filter((t) => !binding ||
2076
+ binding.turn.tools.some((v) => v.slug === t.tool.slug));
2077
+ const recipeTools = await host.service.list({
2078
+ surface: pluginDelegated || binding ? 'assistant' : 'mcp',
2079
+ tenantId: principal.tenantId,
2080
+ userId: principal.id,
2081
+ });
2082
+ const specs = [
2083
+ ...(pluginDelegated || binding
2084
+ ? (await manifest(principal.tenantId, principal.id, [
2085
+ ...scope,
2086
+ ]))
2087
+ .filter((tool) => scope.has(tool.slug))
2088
+ .map((tool) => ({
2089
+ name: tool.functionName,
2090
+ slug: tool.slug,
2091
+ ai: manifestToolToAITool(tool, principal.tenantId),
2092
+ model: tool,
2093
+ generator: undefined,
2094
+ annotations: {
2095
+ readOnlyHint: tool.action === 'read',
2096
+ destructiveHint: requiresOwnerApproval(tool, {}),
2097
+ idempotentHint: tool.action === 'read',
2098
+ openWorldHint: false,
2099
+ },
2100
+ }))
2101
+ : []),
2102
+ ...modelTools.map(({ tool, descriptor, generator }) => ({
2103
+ name: descriptor.name,
2104
+ slug: tool.slug,
2105
+ ai: {
2106
+ function: {
2107
+ description: descriptor.description,
2108
+ parameters: descriptor.inputSchema,
2109
+ },
2110
+ },
2111
+ model: tool,
2112
+ generator,
2113
+ annotations: descriptor.annotations,
2114
+ })),
2115
+ ...recipeTools
2116
+ .filter((t) => scope.has(t.name) &&
2117
+ (!binding ||
2118
+ binding.turn.extraTools.some((v) => v.slug === t.name)))
2119
+ .map((tool) => ({
2120
+ name: wireName(tool.name),
2121
+ slug: tool.name,
2122
+ ai: {
2123
+ function: {
2124
+ description: tool.description,
2125
+ parameters: tool.inputSchema,
2126
+ },
2127
+ },
2128
+ model: undefined,
2129
+ generator: undefined,
2130
+ annotations: tool.annotations,
2131
+ })),
2132
+ ];
2133
+ const names = new Set();
2134
+ workflows = specs.map((spec) => {
2135
+ const name = spec.name;
2136
+ if (names.has(name))
2137
+ throw new Error('Conflicting MCP tool aliases');
2138
+ names.add(name);
2139
+ const destructive = spec.annotations?.destructiveHint === true ||
2140
+ (!!spec.model && requiresOwnerApproval(spec.model, {}));
2141
+ return {
2142
+ name,
2143
+ description: spec.ai.function.description ?? spec.slug,
2144
+ inputSchema: spec.ai.function.parameters ?? { type: 'object' },
2145
+ outputSchema: { type: 'object', additionalProperties: true },
2146
+ effect: destructive
2147
+ ? 'destructive'
2148
+ : spec.annotations?.readOnlyHint === true
2149
+ ? 'read'
2150
+ : 'write',
2151
+ ...(spec.annotations &&
2152
+ 'workProfile' in spec.annotations &&
2153
+ spec.annotations.workProfile === 'design'
2154
+ ? { metadata: { workProfile: spec.annotations.workProfile } }
2155
+ : {}),
2156
+ idempotent: spec.annotations?.idempotentHint === true,
2157
+ openWorld: spec.annotations?.openWorldHint === true,
2158
+ mapError: (error) => error instanceof CookbookToolError
2159
+ ? { code: error.code, message: error.publicMessage }
2160
+ : undefined,
2161
+ execute: async ({ arguments: args, principal: caller }) => {
2162
+ if (!caller?.id ||
2163
+ !caller.tenantId ||
2164
+ caller.id !== principal.id ||
2165
+ caller.tenantId !== principal.tenantId)
2166
+ throw new Error('Principal changed');
2167
+ binding?.turn.beforeToolExecution(spec.slug);
2168
+ if (binding) {
2169
+ const budget = binding.turn.workProfile?.budgets;
2170
+ if (budget &&
2171
+ (binding.toolCalls >= budget.maxSteps ||
2172
+ Date.now() - binding.startedAt >= budget.turnTimeoutMs))
2173
+ throw new Error('This pass has reached its tool or time limit');
2174
+ if (designRequests.has(binding.context.event.request) &&
2175
+ spec.annotations?.readOnlyHint !== true)
2176
+ throw new Error('Design passes can only read and propose');
2177
+ binding.toolCalls += 1;
2178
+ }
2179
+ const tool = spec.model;
2180
+ if (tool && !isManifestToolEnabled(tool, caller.tenantId))
2181
+ throw new Error('Tool disabled');
2182
+ const approvalPolicy = binding?.turn.thread &&
2183
+ !designRequests.has(binding.context.event.request)
2184
+ ? {
2185
+ allowRemovalsInChat: (await host.workProfiles.read()).settings.safety
2186
+ ?.requireRemovalApproval === false,
2187
+ }
2188
+ : undefined;
2189
+ if (tool &&
2190
+ (requiresOwnerApproval(tool, args, approvalPolicy, spec.annotations?.destructiveHint === true) ||
2191
+ // A preference may tighten an active request, but cannot
2192
+ // waive the authoring gate bound when that turn started.
2193
+ (!!binding?.turn.thread &&
2194
+ binding.turn.requiresApproval(spec.slug, args)))) {
2195
+ const input = {
2196
+ tenantId: caller.tenantId,
2197
+ requestedBy: caller.id,
2198
+ tool: spec.slug,
2199
+ callId: randomUUID(),
2200
+ args,
2201
+ summary: describeAssistantTool(tool.functionName
2202
+ ? `${tool.functionName.slice(0, -(wireName(tool.action).length + 1))}.${tool.action}`
2203
+ : spec.slug, args),
2204
+ context: binding?.turn.thread
2205
+ ? {
2206
+ principal: binding.context.principal,
2207
+ cliTurnId: binding.id,
2208
+ threadId: binding.turn.thread.id,
2209
+ agentSessionId: binding.turn.thread.agentSessionId,
2210
+ originMessageId: binding.turn.originMessageId,
2211
+ allowedTools: binding.turn.principal.allowedTools ?? [],
2212
+ permissionCeiling: binding.turn.permissions ?? [
2213
+ ...scope,
2214
+ ],
2215
+ driver: 'external',
2216
+ }
2217
+ : pluginDelegated
2218
+ ? { pluginMode: true }
2219
+ : {},
2220
+ };
2221
+ const hold = await host.continuations.capture({
2222
+ id: caller.id,
2223
+ tenantId: caller.tenantId,
2224
+ permissions: [...(caller.scopes ?? [])],
2225
+ allowedTools: [spec.slug],
2226
+ ...(clientName ? { clientName } : {}),
2227
+ }, () => host.continuations
2228
+ .adapter('model', 'continuation')
2229
+ .request(input));
2230
+ const result = {
2231
+ status: 'approval_required',
2232
+ message: `Waiting for the owner's approval in ${options.title ?? 'this app'}.`,
2233
+ approvalId: hold.id,
2234
+ summary: hold.summary,
2235
+ ...(!binding
2236
+ ? { outcomeTool: 'owner_approval_outcome' }
2237
+ : {}),
2238
+ };
2239
+ // Publish the canonical persisted hold before the fast MCP
2240
+ // response can outrun the background status poll.
2241
+ binding?.approvalRequired(hold.id);
2242
+ return {
2243
+ content: [{ type: 'text', text: JSON.stringify(result) }],
2244
+ structuredContent: result,
2245
+ };
2246
+ }
2247
+ if (tool)
2248
+ return executeAsPrincipal({
2249
+ principal: {
2250
+ runAsUserId: caller.id,
2251
+ tenantId: caller.tenantId,
2252
+ allowedTools: [spec.slug],
2253
+ },
2254
+ db: runtime.databaseConfig(),
2255
+ permissions: caller.scopes,
2256
+ }, async (run) => {
2257
+ run.assertToolAllowed(spec.slug);
2258
+ await run.assertOperation(tool.collection, tool.action);
2259
+ if (spec.generator)
2260
+ return spec.generator.handleToolCall({
2261
+ method: 'tools/call',
2262
+ params: { name, arguments: args },
2263
+ });
2264
+ const value = await invokeManifestTool(run, tool, args, {
2265
+ db: run.context.database ?? runtime.databaseConfig(),
2266
+ });
2267
+ const result = value &&
2268
+ typeof value === 'object' &&
2269
+ !Array.isArray(value)
2270
+ ? value
2271
+ : { result: value };
2272
+ return {
2273
+ content: [
2274
+ {
2275
+ type: 'text',
2276
+ text: JSON.stringify(result),
2277
+ },
2278
+ ],
2279
+ structuredContent: result,
2280
+ };
2281
+ });
2282
+ const result = await host.continuations.capture({
2283
+ id: caller.id,
2284
+ tenantId: caller.tenantId,
2285
+ permissions: [...(caller.scopes ?? [])],
2286
+ allowedTools: [spec.slug],
2287
+ ...(clientName ? { clientName } : {}),
2288
+ }, () => host.service.invoke(spec.slug, args, {
2289
+ surface: binding?.turn.thread ? 'assistant' : 'mcp',
2290
+ tenantId: caller.tenantId,
2291
+ userId: caller.id,
2292
+ }));
2293
+ const presented = result.status === 'approval_required'
2294
+ ? {
2295
+ ...result,
2296
+ message: `Waiting for the owner's approval in ${options.title ?? 'this app'}.`,
2297
+ outcomeTool: 'owner_approval_outcome',
2298
+ }
2299
+ : result;
2300
+ return {
2301
+ content: [
2302
+ { type: 'text', text: JSON.stringify(presented) },
2303
+ ],
2304
+ structuredContent: presented,
2305
+ };
2306
+ },
2307
+ };
2308
+ });
2309
+ if ((!pluginDelegated || scope.has('app.approvals')) &&
2310
+ (!binding ||
2311
+ binding.turn.extraTools.some((tool) => tool.slug === 'app.approvals')) &&
2312
+ (await host.authority.list({ id: principal.id, tenantId: principal.tenantId }, false)).some((r) => r.requestedBy === principal.id))
2313
+ workflows.push({
2314
+ name: 'owner_approval_outcome',
2315
+ description: 'Read your pending owner approval or its recorded outcome.',
2316
+ inputSchema: {
2317
+ type: 'object',
2318
+ properties: { id: { type: 'string' } },
2319
+ required: ['id'],
2320
+ additionalProperties: false,
2321
+ },
2322
+ outputSchema: { type: 'object', additionalProperties: true },
2323
+ effect: 'read',
2324
+ idempotent: true,
2325
+ openWorld: false,
2326
+ execute: async ({ arguments: args, principal: caller }) => {
2327
+ if (!caller?.id || !caller.tenantId)
2328
+ throw new Error('Authentication required');
2329
+ const result = await approvalOutcome(caller, String(args.id));
2330
+ return {
2331
+ content: [{ type: 'text', text: JSON.stringify(result) }],
2332
+ structuredContent: result,
2333
+ };
2334
+ },
2335
+ });
2336
+ });
2337
+ return mountMcpAppRoute({
2338
+ runtime: { ...runtime, verifyLocalMcpToken: verifyPluginToken },
2339
+ models: [],
2340
+ requiredScopes: [],
2341
+ workflowTools: workflows,
2342
+ toolListCache: { ttlMs: 0, cacheScope: 'private' },
2343
+ })({ ...event, locals: { ...event.locals } });
2344
+ },
2345
+ dispose() {
2346
+ process.removeListener('sveltekit:shutdown', onShutdown);
2347
+ // Release this database's design-run executor now so a replacement host
2348
+ // can install its own; the task runner stops through the shared shutdown.
2349
+ disposeDesignRuns?.();
2350
+ void shutdown().catch(() => { });
2351
+ current?.gate.dispose?.();
2352
+ setRuntimeExposureGate(undefined);
2353
+ setCookbookToolService(undefined);
2354
+ turns.clear();
2355
+ },
2356
+ };
2357
+ }
2358
+ /** Mount the ordinary cookbook model page with the live session gate. */
2359
+ export async function loadCookbookModelPage({ params, parent, locals, url, }) {
2360
+ const session = locals;
2361
+ if (!session.user)
2362
+ redirect(303, '/setup');
2363
+ const { cookbookApp } = (await parent());
2364
+ if (!cookbookApp)
2365
+ error(404, 'This app has no cookbook.');
2366
+ const shell = buildCookbookShell({
2367
+ cookbook: cookbookApp.cookbook,
2368
+ catalog: cookbookApp.catalog,
2369
+ });
2370
+ const id = `item:${params.pkg}:${params.model}${params.key ? `:${params.key}` : ''}`;
2371
+ const entry = shell.entries.get(id);
2372
+ if (!entry)
2373
+ error(404, 'This page is not in your app.');
2374
+ if (!isRuntimeModelEnabled(ObjectRegistry.getExposureModel(entry.model.id), {
2375
+ surface: 'screen',
2376
+ tenantId: session.tenantId,
2377
+ }))
2378
+ error(404, 'This page is not enabled.');
2379
+ return {
2380
+ recordId: url?.searchParams.get('record') ?? null,
2381
+ referenceHrefs: Object.fromEntries([...shell.entries.values()]
2382
+ .filter((candidate) => !candidate.filter)
2383
+ .map((candidate) => [
2384
+ ObjectRegistry.getClass(candidate.model.id)?.qualifiedName ??
2385
+ candidate.model.id,
2386
+ candidate.href.replace(/(.)\/$/, '$1'),
2387
+ ])),
2388
+ entry: {
2389
+ id: entry.id,
2390
+ label: entry.label,
2391
+ description: entry.description,
2392
+ noun: entry.noun ?? null,
2393
+ filter: entry.filter ?? null,
2394
+ model: ObjectRegistry.getClass(entry.model.id)?.qualifiedName ??
2395
+ entry.model.id,
2396
+ className: entry.model.name,
2397
+ },
2398
+ permissions: session.permissions,
2399
+ };
2400
+ }