@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.
- package/AGENTS.md +68 -51
- package/README.md +25 -10
- package/agents/cookbook-design-runs.md +164 -0
- package/agents/cookbook-host.md +724 -0
- package/agents/onboarding.md +116 -0
- package/agents/plugin-mode.md +152 -0
- package/cookbook-template/.pnpmfile.cjs +5 -0
- package/cookbook-template/src/hooks.server.ts +3 -0
- package/cookbook-template/src/lib/server/cookbook.ts +21 -0
- package/cookbook-template/src/lib/server/smrt.ts +11 -0
- package/cookbook-template/src/routes/+layout.server.ts +24 -0
- package/cookbook-template/src/routes/+layout.svelte +47 -0
- package/cookbook-template/src/routes/+page.server.ts +15 -0
- package/cookbook-template/src/routes/+page.svelte +12 -0
- package/cookbook-template/src/routes/api/_runtime/owner-link/+server.ts +2 -0
- package/cookbook-template/src/routes/api/assistant/[...path]/+server.ts +2 -0
- package/cookbook-template/src/routes/api/connect-ai/+server.ts +2 -0
- package/cookbook-template/src/routes/api/cookbook/prebuilt/+server.ts +3 -0
- package/cookbook-template/src/routes/api/cookbook/preferences/+server.ts +45 -0
- package/cookbook-template/src/routes/api/onboarding/+server.ts +3 -0
- package/cookbook-template/src/routes/m/[pkg]/[model]/[[key]]/+page.server.ts +1 -0
- package/cookbook-template/src/routes/m/[pkg]/[model]/[[key]]/+page.svelte +7 -0
- package/cookbook-template/src/routes/mcp/+server.ts +2 -0
- package/cookbook-template/src/routes/onboarding/+page.server.ts +13 -0
- package/cookbook-template/src/routes/onboarding/+page.svelte +28 -0
- package/cookbook-template/src/routes/s/[slug]/+page.server.ts +10 -0
- package/cookbook-template/src/routes/s/[slug]/+page.svelte +6 -0
- package/cookbook-template/src/routes/settings/+page.server.ts +22 -0
- package/cookbook-template/src/routes/settings/+page.svelte +49 -0
- package/cookbook-template/src/routes/settings/inference/+page.server.ts +6 -0
- package/cookbook-template/src/routes/settings/inference/+page.svelte +14 -0
- package/cookbook-template/vite.config.ts +4 -0
- package/dist/host/client.d.ts +8 -0
- package/dist/host/client.js +66 -0
- package/dist/host/design-runs.d.ts +72 -0
- package/dist/host/design-runs.js +763 -0
- package/dist/host/generate.d.ts +49 -0
- package/dist/host/generate.js +266 -0
- package/dist/host/onboarding.d.ts +26 -0
- package/dist/host/onboarding.js +247 -0
- package/dist/host/plugin-mode.d.ts +55 -0
- package/dist/host/plugin-mode.js +184 -0
- package/dist/host/preferences.d.ts +40 -0
- package/dist/host/preferences.js +163 -0
- package/dist/host/server.d.ts +283 -0
- package/dist/host/server.js +2400 -0
- package/dist/host/settings.d.ts +57 -0
- package/dist/host/settings.js +130 -0
- package/dist/host/state.d.ts +26 -0
- package/dist/host/state.js +149 -0
- package/dist/host/sveltekit-client.d.ts +22 -0
- package/dist/host/sveltekit-client.js +53 -0
- package/dist/smrt-knowledge.okf.md +105 -0
- package/examples/notes/src/routes/notes/+page.svelte +145 -0
- package/host/CookbookModelPage.svelte +78 -0
- package/host/InferenceSettingsPage.svelte +103 -0
- package/mcp-apps-template/package.dependencies.json +2 -2
- package/package.json +102 -24
- package/template/README.md +24 -11
- package/template/package.json +17 -12
- package/template/smrt.config.ts +4 -0
- package/template/src/hooks.server.ts +5 -0
- package/template/src/lib/objects/index.ts +7 -3
- package/template/src/lib/server/settings-registry.ts +29 -0
- package/template/src/lib/server/settings.ts +91 -0
- package/template/src/lib/server/smrt.ts +1 -0
- package/template/src/lib/settings-client.ts +1 -0
- package/template/src/lib/sign-out.ts +1 -19
- package/template/src/params/settingsSection.ts +4 -0
- package/template/src/routes/+layout.svelte +1 -2
- package/template/src/routes/+page.svelte +20 -128
- package/template/src/routes/settings/+page.svelte +16 -3
- package/template/src/routes/settings/[section=settingsSection]/+page.svelte +19 -0
- package/template/src/routes/settings/inference/+page.server.ts +3 -0
- package/template/src/routes/settings/inference/+page.svelte +6 -0
- package/template/src/routes/settings/prompts/+page.server.ts +50 -0
- package/template/src/routes/settings/prompts/+page.svelte +28 -0
- package/template.config.js +17 -12
- /package/{template → examples/notes}/src/lib/objects/Note.ts +0 -0
- /package/{template/src/routes → examples/notes/src/routes/notes}/+page.server.ts +0 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** Generate empty same-name subclasses once; never overwrite the person's extensions. */
|
|
2
|
+
export declare function generateCookbookSubclasses(options?: {
|
|
3
|
+
root?: string;
|
|
4
|
+
objectsDir?: string;
|
|
5
|
+
}): Promise<{
|
|
6
|
+
written: string[];
|
|
7
|
+
existing: string[];
|
|
8
|
+
}>;
|
|
9
|
+
/** Prepare one verified installed-provider superset for both Vite generators. */
|
|
10
|
+
export declare function prepareCookbookHost(options?: {
|
|
11
|
+
root?: string;
|
|
12
|
+
objectsDir?: string;
|
|
13
|
+
collectionAliases?: Readonly<Record<string, string>>;
|
|
14
|
+
}): Promise<{
|
|
15
|
+
subclasses: {
|
|
16
|
+
written: string[];
|
|
17
|
+
existing: string[];
|
|
18
|
+
};
|
|
19
|
+
providers: string[];
|
|
20
|
+
expose: string[];
|
|
21
|
+
generationSnapshot: {
|
|
22
|
+
path: string;
|
|
23
|
+
sha256: string;
|
|
24
|
+
provenance: string;
|
|
25
|
+
sourceRoot: string;
|
|
26
|
+
};
|
|
27
|
+
app: {
|
|
28
|
+
cookbook: import("@happyvertical/smrt-types").Cookbook;
|
|
29
|
+
catalog: {
|
|
30
|
+
recipes: {
|
|
31
|
+
requires: string[];
|
|
32
|
+
nav: import("@happyvertical/smrt-types").RecipeNavEntry[];
|
|
33
|
+
label: string;
|
|
34
|
+
id: string;
|
|
35
|
+
models: string[];
|
|
36
|
+
group?: import("@happyvertical/smrt-types").RecipeGroup | undefined;
|
|
37
|
+
section?: import("@happyvertical/smrt-types").RecipeSection | undefined;
|
|
38
|
+
surfaces?: import("@happyvertical/smrt-types").RecipeSurface[] | undefined;
|
|
39
|
+
requiresAny?: string[][] | undefined;
|
|
40
|
+
}[];
|
|
41
|
+
models: readonly import("@happyvertical/smrt-svelte/cookbook").CookbookModelInfo[];
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
warnings: string[];
|
|
45
|
+
}>;
|
|
46
|
+
/** Vite entry for a complete lazy cookbook host, with no app-owned snapshot script. */
|
|
47
|
+
export declare function cookbookHostVite(options?: Parameters<typeof prepareCookbookHost>[0]): Promise<Array<{
|
|
48
|
+
name: string;
|
|
49
|
+
}>>;
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/** Source customization points for a normal cookbook app, generated from installed manifests. */
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { mkdir, readFile, realpath, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
6
|
+
import { pathToFileURL } from 'node:url';
|
|
7
|
+
import { validateCookbook } from '@happyvertical/smrt-core/cookbook';
|
|
8
|
+
import { catalogFromManifests, readInstalledManifests, } from '@happyvertical/smrt-svelte/cookbook/server';
|
|
9
|
+
/** Generate empty same-name subclasses once; never overwrite the person's extensions. */
|
|
10
|
+
export async function generateCookbookSubclasses(options = {}) {
|
|
11
|
+
const root = await realpath(resolve(options.root ?? process.cwd()));
|
|
12
|
+
const pkg = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
|
|
13
|
+
if (!/^@[^/]+\/[^/]+$/.test(pkg.name ?? ''))
|
|
14
|
+
throw new Error('App subclasses need a scoped package name');
|
|
15
|
+
const directory = resolve(root, options.objectsDir ?? 'src/lib/objects');
|
|
16
|
+
const path = relative(root, directory);
|
|
17
|
+
if (path.startsWith('..') || isAbsolute(path))
|
|
18
|
+
throw new Error('objectsDir must be inside the app');
|
|
19
|
+
const manifests = await readInstalledManifests(root);
|
|
20
|
+
const catalog = catalogFromManifests(manifests);
|
|
21
|
+
const checked = validateCookbook(JSON.parse(await readFile(join(root, 'smrt.cookbook.json'), 'utf8')), { recipes: catalog.recipes.map((r) => r.id) });
|
|
22
|
+
if (!checked.ok)
|
|
23
|
+
throw new Error(checked.errors.join('; '));
|
|
24
|
+
const wanted = new Set(checked.cookbook.features ?? []);
|
|
25
|
+
for (const recipe of catalog.recipes)
|
|
26
|
+
if (checked.cookbook.recipes.includes(recipe.id)) {
|
|
27
|
+
for (const model of recipe.models)
|
|
28
|
+
wanted.add(model);
|
|
29
|
+
for (const nav of recipe.nav)
|
|
30
|
+
wanted.add(nav.model);
|
|
31
|
+
}
|
|
32
|
+
const names = new Map();
|
|
33
|
+
const sources = [...wanted]
|
|
34
|
+
.filter((id) => !id.startsWith(`${pkg.name}:`))
|
|
35
|
+
.sort()
|
|
36
|
+
.map((id) => {
|
|
37
|
+
const model = catalog.models.find((m) => m.id === id);
|
|
38
|
+
if (!model)
|
|
39
|
+
throw new Error(`Installed model is missing: ${id}`);
|
|
40
|
+
const previous = names.get(model.name);
|
|
41
|
+
if (previous && previous !== id)
|
|
42
|
+
throw new Error(`App identity collision: ${previous} and ${id} both need ${pkg.name}:${model.name}`);
|
|
43
|
+
names.set(model.name, id);
|
|
44
|
+
const manifest = manifests.find((m) => Object.values(m.objects ?? {}).some((raw) => raw.qualifiedName === id));
|
|
45
|
+
const raw = Object.values(manifest?.objects ?? {}).find((raw) => raw.qualifiedName === id);
|
|
46
|
+
const importPath = raw?.importPath ?? manifest?.packageName;
|
|
47
|
+
const exportName = raw?.exportName ?? model.name;
|
|
48
|
+
if (!importPath ||
|
|
49
|
+
!/^@[\w-]+\/[\w-]+(?:\/[\w.-]+)*$/.test(importPath) ||
|
|
50
|
+
importPath.split('/').includes('..') ||
|
|
51
|
+
!/^[\w-]+$/.test(model.packageId) ||
|
|
52
|
+
!/^[A-Za-z_$][\w$]*$/.test(exportName) ||
|
|
53
|
+
!/^[A-Za-z_$][\w$]*$/.test(model.name))
|
|
54
|
+
throw new Error(`Model has no safe public import: ${id}`);
|
|
55
|
+
return {
|
|
56
|
+
file: join(directory, model.packageId, `${model.name}.ts`),
|
|
57
|
+
source: `import { ${exportName} as ${model.name}Base } from '${importPath}';\nimport { smrt } from '@happyvertical/smrt-core';\n\n@smrt({})\nexport class ${model.name} extends ${model.name}Base {}\n`,
|
|
58
|
+
};
|
|
59
|
+
});
|
|
60
|
+
const written = [];
|
|
61
|
+
const existing = [];
|
|
62
|
+
for (const { file, source } of sources) {
|
|
63
|
+
let ancestor = resolve(file, '..');
|
|
64
|
+
for (;;) {
|
|
65
|
+
try {
|
|
66
|
+
const at = relative(root, await realpath(ancestor));
|
|
67
|
+
if (at.startsWith('..') || isAbsolute(at))
|
|
68
|
+
throw new Error('objectsDir must resolve inside the app');
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (error.code !== 'ENOENT')
|
|
73
|
+
throw error;
|
|
74
|
+
ancestor = resolve(ancestor, '..');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
await mkdir(resolve(file, '..'), { recursive: true });
|
|
78
|
+
try {
|
|
79
|
+
await writeFile(file, source, { flag: 'wx' });
|
|
80
|
+
written.push(relative(root, file));
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (error.code !== 'EEXIST')
|
|
84
|
+
throw error;
|
|
85
|
+
existing.push(relative(root, file));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return { written, existing };
|
|
89
|
+
}
|
|
90
|
+
/** Prepare one verified installed-provider superset for both Vite generators. */
|
|
91
|
+
export async function prepareCookbookHost(options = {}) {
|
|
92
|
+
const root = await realpath(resolve(options.root ?? process.cwd()));
|
|
93
|
+
const objectsDir = options.objectsDir ?? 'src/lib/objects';
|
|
94
|
+
const subclasses = await generateCookbookSubclasses({ root, objectsDir });
|
|
95
|
+
const manifests = (await readInstalledManifests(root)).filter((manifest) => manifest.packageName !== '@happyvertical/smrt-core');
|
|
96
|
+
const providers = manifests.map((manifest) => manifest.packageName).sort();
|
|
97
|
+
const catalog = catalogFromManifests(manifests, true);
|
|
98
|
+
const cookbook = JSON.parse(await readFile(join(root, 'smrt.cookbook.json'), 'utf8'));
|
|
99
|
+
const expose = [
|
|
100
|
+
...new Set([
|
|
101
|
+
...catalog.recipes.flatMap((recipe) => [
|
|
102
|
+
...recipe.models,
|
|
103
|
+
...recipe.nav.map((entry) => entry.model),
|
|
104
|
+
]),
|
|
105
|
+
...(cookbook.features ?? []),
|
|
106
|
+
]),
|
|
107
|
+
].sort();
|
|
108
|
+
const require = createRequire(join(root, 'package.json'));
|
|
109
|
+
const { build } = await import(pathToFileURL(require.resolve('vite')).href);
|
|
110
|
+
const { smrtPlugin, serializeSmrtGenerationSnapshot, sha256SmrtGenerationSnapshot, } = await import('@happyvertical/smrt-core/vite-plugin');
|
|
111
|
+
const { smrtConsumer, separateHostedStiCollections, aliasHostedCollections, findInstalledPackageJson, } = await import('@happyvertical/smrt-core/consumer-plugin');
|
|
112
|
+
await mkdir(join(root, '.smrt'), { recursive: true });
|
|
113
|
+
const entry = join(root, '.smrt/exposure-entry.js');
|
|
114
|
+
await writeFile(entry, 'export {};\n');
|
|
115
|
+
await build({
|
|
116
|
+
root,
|
|
117
|
+
configFile: false,
|
|
118
|
+
logLevel: 'error',
|
|
119
|
+
plugins: [
|
|
120
|
+
smrtPlugin({
|
|
121
|
+
projectRoot: root,
|
|
122
|
+
include: [`${objectsDir}/**/*.ts`],
|
|
123
|
+
generateTypes: false,
|
|
124
|
+
svelteKit: { enabled: false, lazyActivation: true },
|
|
125
|
+
}),
|
|
126
|
+
smrtConsumer({
|
|
127
|
+
projectRoot: root,
|
|
128
|
+
packages: providers,
|
|
129
|
+
generateTypes: false,
|
|
130
|
+
svelteKit: false,
|
|
131
|
+
lazyActivation: true,
|
|
132
|
+
}),
|
|
133
|
+
],
|
|
134
|
+
build: { write: false, rollupOptions: { input: entry } },
|
|
135
|
+
});
|
|
136
|
+
const manifest = aliasHostedCollections(separateHostedStiCollections(JSON.parse(await readFile(join(root, '.smrt/manifest.json'), 'utf8')), expose, (key, definition) => definition.qualifiedName ?? key), options.collectionAliases ?? {}, expose);
|
|
137
|
+
// Linked provider sources may live outside the host. Snapshot paths are
|
|
138
|
+
// portable under their common ancestor and verified by core on every use.
|
|
139
|
+
let sourceRoot = root;
|
|
140
|
+
const providerSourceRoots = new Map();
|
|
141
|
+
for (const definition of Object.values(manifest.objects)) {
|
|
142
|
+
if (!definition.filePath || !isAbsolute(definition.filePath))
|
|
143
|
+
continue;
|
|
144
|
+
// A published manifest can name an existing publisher checkout. Only
|
|
145
|
+
// source belonging to this installed provider (including workspace links)
|
|
146
|
+
// may widen the snapshot root or contribute a source digest.
|
|
147
|
+
if (definition.packageName &&
|
|
148
|
+
definition.packageName !== manifest.packageName) {
|
|
149
|
+
if (!providerSourceRoots.has(definition.packageName)) {
|
|
150
|
+
const metadata = findInstalledPackageJson(definition.packageName, root);
|
|
151
|
+
providerSourceRoots.set(definition.packageName, metadata ? dirname(metadata) : undefined);
|
|
152
|
+
}
|
|
153
|
+
const packageRoot = providerSourceRoots.get(definition.packageName);
|
|
154
|
+
const path = packageRoot
|
|
155
|
+
? relative(packageRoot, definition.filePath)
|
|
156
|
+
: '..';
|
|
157
|
+
if (!packageRoot ||
|
|
158
|
+
path === '..' ||
|
|
159
|
+
path.startsWith(`..${sep}`) ||
|
|
160
|
+
isAbsolute(path) ||
|
|
161
|
+
!existsSync(definition.filePath)) {
|
|
162
|
+
delete definition.filePath;
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
while (relative(sourceRoot, definition.filePath).startsWith('..'))
|
|
167
|
+
sourceRoot = dirname(sourceRoot);
|
|
168
|
+
}
|
|
169
|
+
const provenance = 'smrt-cookbook-host-v1';
|
|
170
|
+
const contents = serializeSmrtGenerationSnapshot(manifest, provenance, {
|
|
171
|
+
sourceRoot,
|
|
172
|
+
});
|
|
173
|
+
const sha256 = sha256SmrtGenerationSnapshot(contents);
|
|
174
|
+
const snapshotPath = `.smrt/host-snapshots/${sha256.slice(7)}.json`;
|
|
175
|
+
const generationSnapshot = {
|
|
176
|
+
path: snapshotPath,
|
|
177
|
+
sha256,
|
|
178
|
+
provenance,
|
|
179
|
+
sourceRoot,
|
|
180
|
+
};
|
|
181
|
+
await mkdir(join(root, '.smrt/host-snapshots'), { recursive: true });
|
|
182
|
+
try {
|
|
183
|
+
await writeFile(join(root, snapshotPath), contents, { flag: 'wx' });
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
if (error.code !== 'EEXIST')
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
await writeFile(join(root, '.smrt/host-options.json'), `${JSON.stringify({
|
|
190
|
+
packages: providers,
|
|
191
|
+
expose,
|
|
192
|
+
generationSnapshot,
|
|
193
|
+
}, null, 2)}\n`);
|
|
194
|
+
const checked = validateCookbook(cookbook, {
|
|
195
|
+
recipes: catalog.recipes.map((r) => r.id),
|
|
196
|
+
});
|
|
197
|
+
if (!checked.ok)
|
|
198
|
+
throw new Error(checked.errors.join('; '));
|
|
199
|
+
const app = {
|
|
200
|
+
cookbook: checked.cookbook,
|
|
201
|
+
catalog: {
|
|
202
|
+
...catalog,
|
|
203
|
+
recipes: catalog.recipes.map((r) => ({
|
|
204
|
+
...r,
|
|
205
|
+
requires: r.requires ?? [],
|
|
206
|
+
})),
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
// Use the preset's existing generated-declaration directory, never app-owned types.
|
|
210
|
+
const typesDir = join(root, 'src/lib/types/smrt-generated');
|
|
211
|
+
await mkdir(typesDir, { recursive: true });
|
|
212
|
+
await writeFile(join(typesDir, 'cookbook-host.d.ts'), `// Generated by cookbookHostVite; do not edit.\ndeclare module 'virtual:smrt-cookbook-app' {\n export const app: NonNullable<import('@happyvertical/smrt-template-sveltekit/host/server').CookbookHostOptions['app']>;\n export const initialApp: import('@happyvertical/smrt-svelte/cookbook/server').CookbookAppData;\n}\n`);
|
|
213
|
+
return {
|
|
214
|
+
subclasses,
|
|
215
|
+
providers,
|
|
216
|
+
expose,
|
|
217
|
+
generationSnapshot,
|
|
218
|
+
app,
|
|
219
|
+
warnings: checked.warnings,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
/** Vite entry for a complete lazy cookbook host, with no app-owned snapshot script. */
|
|
223
|
+
export async function cookbookHostVite(options = {}) {
|
|
224
|
+
const prepared = await prepareCookbookHost(options);
|
|
225
|
+
const { smrt } = await import('@happyvertical/smrt-core/vite');
|
|
226
|
+
const plugins = await smrt({
|
|
227
|
+
projectRoot: options.root,
|
|
228
|
+
objectsDir: options.objectsDir,
|
|
229
|
+
packages: prepared.providers,
|
|
230
|
+
expose: prepared.expose,
|
|
231
|
+
generationSnapshot: prepared.generationSnapshot,
|
|
232
|
+
lazyActivation: true,
|
|
233
|
+
});
|
|
234
|
+
// Keep the existing portable public shape across consumers' Vite versions;
|
|
235
|
+
// validate the actual hooks against this build's Vite internally.
|
|
236
|
+
const catalogPlugin = {
|
|
237
|
+
name: 'smrt-cookbook-catalog',
|
|
238
|
+
// This Node-only server seam resolves its own SDK dependency. Bundling a
|
|
239
|
+
// linked workspace copy can hoist the SDK back into the host's boot chunk.
|
|
240
|
+
config() {
|
|
241
|
+
return {
|
|
242
|
+
ssr: {
|
|
243
|
+
external: [
|
|
244
|
+
'@happyvertical/smrt-app-mcp',
|
|
245
|
+
'@happyvertical/smrt-app-cli',
|
|
246
|
+
],
|
|
247
|
+
},
|
|
248
|
+
};
|
|
249
|
+
},
|
|
250
|
+
resolveId(id) {
|
|
251
|
+
return id === 'virtual:smrt-cookbook-app'
|
|
252
|
+
? '\0virtual:smrt-cookbook-app'
|
|
253
|
+
: null;
|
|
254
|
+
},
|
|
255
|
+
load(id) {
|
|
256
|
+
return id === '\0virtual:smrt-cookbook-app'
|
|
257
|
+
? `import { narrowCatalog } from '@happyvertical/smrt-svelte/cookbook/server';
|
|
258
|
+
export const app = JSON.parse(${JSON.stringify(JSON.stringify(prepared.app))}, (_key, value) => value && typeof value === "object" ? Object.freeze(value) : value);
|
|
259
|
+
const selected = narrowCatalog(app.catalog, { recipes: app.cookbook.recipes, features: app.cookbook.features ?? [] });
|
|
260
|
+
export const initialApp = Object.freeze({ cookbook: app.cookbook, catalog: Object.freeze({ recipes: Object.freeze(selected.recipes), models: Object.freeze(selected.models) }), warnings: Object.freeze(${JSON.stringify(prepared.warnings)}) });
|
|
261
|
+
`
|
|
262
|
+
: null;
|
|
263
|
+
},
|
|
264
|
+
};
|
|
265
|
+
return [...plugins, catalogPlugin];
|
|
266
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { AssistantApprovalView } from '@happyvertical/smrt-chat/assistant-turn';
|
|
2
|
+
import { type EngineCatalog } from '@happyvertical/smrt-core/cookbook/engine';
|
|
3
|
+
import type { CookbookToolName, CookbookToolResult } from '@happyvertical/smrt-core/cookbook/tools';
|
|
4
|
+
import type { OnboardingState } from '@happyvertical/smrt-svelte/onboarding';
|
|
5
|
+
import type { DatabaseInterface } from '@happyvertical/sql';
|
|
6
|
+
import type { RequestEvent } from '@sveltejs/kit';
|
|
7
|
+
type Actor = {
|
|
8
|
+
userId: string;
|
|
9
|
+
tenantId: string;
|
|
10
|
+
permissions?: readonly string[];
|
|
11
|
+
};
|
|
12
|
+
export declare function createCookbookOnboarding(options: {
|
|
13
|
+
db: DatabaseInterface;
|
|
14
|
+
catalog: EngineCatalog;
|
|
15
|
+
authorize(event: {
|
|
16
|
+
locals: unknown;
|
|
17
|
+
}): Promise<Actor | null>;
|
|
18
|
+
invoke(actor: Actor, name: CookbookToolName, args: Record<string, unknown>, initialSetup?: boolean): Promise<CookbookToolResult>;
|
|
19
|
+
approval(actor: Actor, id: string): Promise<AssistantApprovalView | null>;
|
|
20
|
+
}): Promise<{
|
|
21
|
+
handle: (event: RequestEvent) => Promise<Response>;
|
|
22
|
+
load(event: {
|
|
23
|
+
locals: unknown;
|
|
24
|
+
}): Promise<OnboardingState | null>;
|
|
25
|
+
}>;
|
|
26
|
+
export {};
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/** Resumable local-owner composition. The cookbook service remains the mutation authority. */
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { createCookbookEngine, } from '@happyvertical/smrt-core/cookbook/engine';
|
|
4
|
+
const TABLE = '_smrt_cookbook_onboarding';
|
|
5
|
+
const initial = {
|
|
6
|
+
step: 'welcome',
|
|
7
|
+
completed: false,
|
|
8
|
+
rerunning: false,
|
|
9
|
+
selected: null,
|
|
10
|
+
approvalId: null,
|
|
11
|
+
};
|
|
12
|
+
const hash = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
13
|
+
export async function createCookbookOnboarding(options) {
|
|
14
|
+
const { db } = options;
|
|
15
|
+
await db.query(`CREATE TABLE IF NOT EXISTS ${TABLE} (tenant_id TEXT NOT NULL, user_id TEXT NOT NULL, revision TEXT NOT NULL, state TEXT NOT NULL, PRIMARY KEY (tenant_id, user_id))`);
|
|
16
|
+
async function read(actor) {
|
|
17
|
+
await db.query(`INSERT INTO ${TABLE} (tenant_id, user_id, revision, state) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING`, actor.tenantId, actor.userId, randomUUID(), JSON.stringify({ ...initial, preview: null }));
|
|
18
|
+
const row = (await db.query(`SELECT revision, state FROM ${TABLE} WHERE tenant_id = ? AND user_id = ?`, actor.tenantId, actor.userId)).rows[0];
|
|
19
|
+
if (!row)
|
|
20
|
+
throw new Error('Onboarding unavailable');
|
|
21
|
+
return { ...JSON.parse(String(row.state)), revision: String(row.revision) };
|
|
22
|
+
}
|
|
23
|
+
async function save(actor, before, after) {
|
|
24
|
+
const revision = randomUUID();
|
|
25
|
+
const result = await db.query(`UPDATE ${TABLE} SET revision = ?, state = ? WHERE tenant_id = ? AND user_id = ? AND revision = ? RETURNING revision`, revision, JSON.stringify(after), actor.tenantId, actor.userId, before.revision);
|
|
26
|
+
if (result.rows.length !== 1)
|
|
27
|
+
throw new Error('Onboarding changed');
|
|
28
|
+
return { ...after, revision };
|
|
29
|
+
}
|
|
30
|
+
const lists = (document) => createCookbookEngine({ catalog: options.catalog, cookbook: document })
|
|
31
|
+
.snapshot()
|
|
32
|
+
.sections.filter((s) => !s.hidden)
|
|
33
|
+
.flatMap((s) => s.items.filter((i) => !i.hidden).map((i) => i.label));
|
|
34
|
+
async function project(actor, saved) {
|
|
35
|
+
const approval = saved.approvalId
|
|
36
|
+
? await options.approval(actor, saved.approvalId)
|
|
37
|
+
: null;
|
|
38
|
+
if (approval?.status === 'succeeded' && saved.step !== 'done') {
|
|
39
|
+
saved = await save(actor, saved, {
|
|
40
|
+
...saved,
|
|
41
|
+
completed: true,
|
|
42
|
+
rerunning: false,
|
|
43
|
+
step: 'done',
|
|
44
|
+
preview: null,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
let templates = [];
|
|
48
|
+
if (saved.step === 'template') {
|
|
49
|
+
try {
|
|
50
|
+
templates = (await options.invoke(actor, 'cookbook.listTemplates', {}))
|
|
51
|
+
.templates;
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (!error ||
|
|
55
|
+
typeof error !== 'object' ||
|
|
56
|
+
!('code' in error) ||
|
|
57
|
+
error.code !== 'forbidden')
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
step: saved.step,
|
|
63
|
+
completed: saved.completed,
|
|
64
|
+
rerunning: saved.rerunning,
|
|
65
|
+
selected: saved.selected,
|
|
66
|
+
approvalId: saved.approvalId,
|
|
67
|
+
revision: saved.revision,
|
|
68
|
+
preview: saved.preview,
|
|
69
|
+
approval,
|
|
70
|
+
templates,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const json = (data, status = 200) => Response.json(data, { status, headers: { 'cache-control': 'no-store' } });
|
|
74
|
+
async function handle(event) {
|
|
75
|
+
const actor = await options.authorize(event);
|
|
76
|
+
if (!actor)
|
|
77
|
+
return json({ code: 'not_allowed' }, 403);
|
|
78
|
+
if (!['GET', 'POST'].includes(event.request.method))
|
|
79
|
+
return json({ code: 'method_not_allowed' }, 405);
|
|
80
|
+
try {
|
|
81
|
+
if (event.request.method === 'GET')
|
|
82
|
+
return json(await project(actor, await read(actor)));
|
|
83
|
+
if (event.request.headers.get('origin') !== event.url.origin)
|
|
84
|
+
return json({ code: 'invalid_origin' }, 403);
|
|
85
|
+
if (event.request.headers.get('content-type')?.split(';')[0].trim() !==
|
|
86
|
+
'application/json')
|
|
87
|
+
return json({ code: 'invalid_request' }, 415);
|
|
88
|
+
const reader = event.request.body?.getReader();
|
|
89
|
+
if (!reader)
|
|
90
|
+
return json({ code: 'invalid_request' }, 400);
|
|
91
|
+
let raw = '';
|
|
92
|
+
try {
|
|
93
|
+
const decoder = new TextDecoder();
|
|
94
|
+
let size = 0;
|
|
95
|
+
for (;;) {
|
|
96
|
+
const chunk = await reader.read();
|
|
97
|
+
if (chunk.done)
|
|
98
|
+
break;
|
|
99
|
+
size += chunk.value.byteLength;
|
|
100
|
+
if (size > 4096) {
|
|
101
|
+
await reader.cancel();
|
|
102
|
+
return json({ code: 'body_too_large' }, 413);
|
|
103
|
+
}
|
|
104
|
+
raw += decoder.decode(chunk.value, { stream: true });
|
|
105
|
+
}
|
|
106
|
+
raw += decoder.decode();
|
|
107
|
+
}
|
|
108
|
+
finally {
|
|
109
|
+
reader.releaseLock();
|
|
110
|
+
}
|
|
111
|
+
let body;
|
|
112
|
+
try {
|
|
113
|
+
body = JSON.parse(raw);
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return json({ code: 'invalid_request' }, 400);
|
|
117
|
+
}
|
|
118
|
+
if (!body ||
|
|
119
|
+
Array.isArray(body) ||
|
|
120
|
+
typeof body !== 'object' ||
|
|
121
|
+
Object.keys(body).some((k) => !['action', 'revision', 'id'].includes(k)) ||
|
|
122
|
+
typeof body.action !== 'string' ||
|
|
123
|
+
typeof body.revision !== 'string')
|
|
124
|
+
return json({ code: 'invalid_request' }, 400);
|
|
125
|
+
const saved = await read(actor);
|
|
126
|
+
const held = saved.approvalId
|
|
127
|
+
? await options.approval(actor, saved.approvalId)
|
|
128
|
+
: null;
|
|
129
|
+
const unsettled = !!saved.approvalId &&
|
|
130
|
+
(!held || ['pending', 'approved', 'executing'].includes(held.status));
|
|
131
|
+
if (body.revision !== saved.revision)
|
|
132
|
+
return json({ code: 'conflict' }, 409);
|
|
133
|
+
const next = { ...saved };
|
|
134
|
+
switch (body.action) {
|
|
135
|
+
case 'welcome':
|
|
136
|
+
if (saved.step !== 'welcome' || saved.completed)
|
|
137
|
+
return json({ code: 'invalid_step' }, 409);
|
|
138
|
+
next.step = 'ai';
|
|
139
|
+
break;
|
|
140
|
+
case 'continue':
|
|
141
|
+
case 'skip':
|
|
142
|
+
if (saved.step !== 'ai')
|
|
143
|
+
return json({ code: 'invalid_step' }, 409);
|
|
144
|
+
next.step = 'template';
|
|
145
|
+
break;
|
|
146
|
+
case 'back':
|
|
147
|
+
if (unsettled || !['ai', 'template'].includes(saved.step))
|
|
148
|
+
return json({ code: 'invalid_step' }, 409);
|
|
149
|
+
next.step = saved.step === 'ai' ? 'welcome' : 'ai';
|
|
150
|
+
next.preview = null;
|
|
151
|
+
next.selected = null;
|
|
152
|
+
next.approvalId = null;
|
|
153
|
+
break;
|
|
154
|
+
case 'restart':
|
|
155
|
+
if (!saved.completed || saved.rerunning)
|
|
156
|
+
return json({ code: 'invalid_step' }, 409);
|
|
157
|
+
Object.assign(next, {
|
|
158
|
+
step: 'template',
|
|
159
|
+
rerunning: true,
|
|
160
|
+
selected: null,
|
|
161
|
+
preview: null,
|
|
162
|
+
approvalId: null,
|
|
163
|
+
});
|
|
164
|
+
break;
|
|
165
|
+
case 'cancel':
|
|
166
|
+
if (!saved.rerunning || unsettled)
|
|
167
|
+
return json({ code: 'invalid_step' }, 409);
|
|
168
|
+
Object.assign(next, {
|
|
169
|
+
step: 'done',
|
|
170
|
+
rerunning: false,
|
|
171
|
+
selected: null,
|
|
172
|
+
preview: null,
|
|
173
|
+
approvalId: null,
|
|
174
|
+
});
|
|
175
|
+
break;
|
|
176
|
+
case 'preview': {
|
|
177
|
+
if (saved.step !== 'template' ||
|
|
178
|
+
unsettled ||
|
|
179
|
+
typeof body.id !== 'string')
|
|
180
|
+
return json({ code: 'invalid_step' }, 409);
|
|
181
|
+
const preview = await options.invoke(actor, 'cookbook.apply', {
|
|
182
|
+
id: body.id,
|
|
183
|
+
});
|
|
184
|
+
const diff = preview.diff;
|
|
185
|
+
next.selected = body.id;
|
|
186
|
+
next.approvalId = null;
|
|
187
|
+
next.preview = {
|
|
188
|
+
id: body.id,
|
|
189
|
+
previewToken: String(preview.previewToken),
|
|
190
|
+
revision: Number(preview.revision),
|
|
191
|
+
before: lists(diff.before),
|
|
192
|
+
after: lists(diff.after),
|
|
193
|
+
};
|
|
194
|
+
next.signature = hash(diff);
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
case 'apply': {
|
|
198
|
+
if (saved.step !== 'template' || !saved.preview || saved.approvalId)
|
|
199
|
+
return json({ code: 'invalid_step' }, 409);
|
|
200
|
+
// Refresh process-local preview receipts after a restart, but only for exactly the reviewed diff/revision.
|
|
201
|
+
const preview = await options.invoke(actor, 'cookbook.apply', {
|
|
202
|
+
id: saved.preview.id,
|
|
203
|
+
});
|
|
204
|
+
if (hash(preview.diff) !== saved.signature ||
|
|
205
|
+
preview.revision !== saved.preview.revision)
|
|
206
|
+
return json({ code: 'preview_changed' }, 409);
|
|
207
|
+
const result = await options.invoke(actor, 'cookbook.apply', {
|
|
208
|
+
id: saved.preview.id,
|
|
209
|
+
apply: true,
|
|
210
|
+
expectedRevision: preview.revision,
|
|
211
|
+
previewToken: preview.previewToken,
|
|
212
|
+
}, !saved.completed && !saved.rerunning);
|
|
213
|
+
if (result.status === 'approval_required')
|
|
214
|
+
next.approvalId = String(result.approvalId);
|
|
215
|
+
else if (result.status === 'ok')
|
|
216
|
+
Object.assign(next, {
|
|
217
|
+
step: 'done',
|
|
218
|
+
completed: true,
|
|
219
|
+
rerunning: false,
|
|
220
|
+
preview: null,
|
|
221
|
+
});
|
|
222
|
+
else
|
|
223
|
+
throw new Error('Unexpected application result');
|
|
224
|
+
break;
|
|
225
|
+
}
|
|
226
|
+
default:
|
|
227
|
+
return json({ code: 'invalid_request' }, 400);
|
|
228
|
+
}
|
|
229
|
+
return json(await project(actor, await save(actor, saved, next)));
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
if (error &&
|
|
233
|
+
typeof error === 'object' &&
|
|
234
|
+
'code' in error &&
|
|
235
|
+
error.code === 'forbidden')
|
|
236
|
+
return json({ code: 'not_allowed' }, 403);
|
|
237
|
+
return json({ code: 'onboarding_failed' }, 503);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return {
|
|
241
|
+
handle,
|
|
242
|
+
async load(event) {
|
|
243
|
+
const actor = await options.authorize(event);
|
|
244
|
+
return actor ? project(actor, await read(actor)) : null;
|
|
245
|
+
},
|
|
246
|
+
};
|
|
247
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { PrincipalTool } from '@happyvertical/smrt-agents';
|
|
2
|
+
import type { generateLocalMcpSetup } from '@happyvertical/smrt-app-cli';
|
|
3
|
+
import type { LocalMcpTokenRecord } from '@happyvertical/smrt-app-runtime';
|
|
4
|
+
import type { SmrtSvelteKitRuntime } from '@happyvertical/smrt-app-runtime/sveltekit';
|
|
5
|
+
import type { CookbookToolDefinition } from '@happyvertical/smrt-core/cookbook/tools';
|
|
6
|
+
import type { RequestEvent } from '@sveltejs/kit';
|
|
7
|
+
import type { createCookbookHostState } from './state.js';
|
|
8
|
+
export declare const PLUGIN_PERMISSION = "app.plugin";
|
|
9
|
+
export declare const PLUGIN_CLIENTS: {
|
|
10
|
+
readonly codex: "Codex";
|
|
11
|
+
readonly 'claude-code': "Claude Code";
|
|
12
|
+
readonly 'claude-desktop': "Claude Desktop";
|
|
13
|
+
};
|
|
14
|
+
export type PluginClient = keyof typeof PLUGIN_CLIENTS;
|
|
15
|
+
export type PluginConnection = {
|
|
16
|
+
client: PluginClient;
|
|
17
|
+
name: string;
|
|
18
|
+
status: LocalMcpTokenRecord['status'] | 'not_connected';
|
|
19
|
+
lastSeen: LocalMcpTokenRecord['lastUsedAt'];
|
|
20
|
+
setup: ReturnType<typeof generateLocalMcpSetup> | null;
|
|
21
|
+
};
|
|
22
|
+
export type PluginModeState = {
|
|
23
|
+
embed: boolean;
|
|
24
|
+
connections: PluginConnection[];
|
|
25
|
+
chatgpt: string;
|
|
26
|
+
/** The same live definitions supplied to the in-app assistant. */
|
|
27
|
+
tools?: Array<{
|
|
28
|
+
definition: PrincipalTool['aiTool']['function'];
|
|
29
|
+
annotations?: CookbookToolDefinition['annotations'];
|
|
30
|
+
source: 'model' | 'recipe' | 'app' | 'lifecycle';
|
|
31
|
+
model?: string;
|
|
32
|
+
operation?: string;
|
|
33
|
+
recipe?: string;
|
|
34
|
+
}>;
|
|
35
|
+
};
|
|
36
|
+
export declare function createPluginMode(options: {
|
|
37
|
+
runtime: SmrtSvelteKitRuntime;
|
|
38
|
+
sourceRoot: string;
|
|
39
|
+
name: string;
|
|
40
|
+
state: () => Promise<Awaited<ReturnType<typeof createCookbookHostState>>>;
|
|
41
|
+
tools?: (actor: {
|
|
42
|
+
id: string;
|
|
43
|
+
tenantId: string;
|
|
44
|
+
}) => Promise<PluginModeState['tools']>;
|
|
45
|
+
authorize(event: RequestEvent): Promise<{
|
|
46
|
+
id: string;
|
|
47
|
+
tenantId: string;
|
|
48
|
+
} | null>;
|
|
49
|
+
}): {
|
|
50
|
+
handle: (event: RequestEvent) => Promise<Response>;
|
|
51
|
+
read: (actor: {
|
|
52
|
+
id: string;
|
|
53
|
+
tenantId: string;
|
|
54
|
+
}) => Promise<PluginModeState>;
|
|
55
|
+
};
|