@happyvertical/smrt-core 0.51.36 → 0.51.38

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 (60) hide show
  1. package/agents/build-knowledge.md +25 -0
  2. package/agents/generators.md +27 -0
  3. package/dist/consumer-plugin/artifact-publication.d.ts +2 -0
  4. package/dist/consumer-plugin/artifact-publication.d.ts.map +1 -1
  5. package/dist/consumer-plugin/artifact-publication.js +15 -1
  6. package/dist/consumer-plugin/artifact-publication.js.map +1 -1
  7. package/dist/consumer-plugin/index.d.ts.map +1 -1
  8. package/dist/consumer-plugin/index.js +3 -3
  9. package/dist/consumer-plugin/index.js.map +1 -1
  10. package/dist/generators/mcp-runtime-template.d.ts +17 -0
  11. package/dist/generators/mcp-runtime-template.d.ts.map +1 -1
  12. package/dist/generators/mcp-runtime-template.js +27 -19
  13. package/dist/generators/mcp-runtime-template.js.map +1 -1
  14. package/dist/generators/mcp-tool-name.d.ts +17 -0
  15. package/dist/generators/mcp-tool-name.d.ts.map +1 -0
  16. package/dist/generators/mcp-tool-name.js +33 -0
  17. package/dist/generators/mcp-tool-name.js.map +1 -0
  18. package/dist/generators/mcp.d.ts +46 -1
  19. package/dist/generators/mcp.d.ts.map +1 -1
  20. package/dist/generators/mcp.js +105 -53
  21. package/dist/generators/mcp.js.map +1 -1
  22. package/dist/generators/tool-schema.d.ts +6 -0
  23. package/dist/generators/tool-schema.d.ts.map +1 -1
  24. package/dist/generators/tool-schema.js +8 -3
  25. package/dist/generators/tool-schema.js.map +1 -1
  26. package/dist/index.js +3 -1
  27. package/dist/knowledge.d.ts +2 -0
  28. package/dist/knowledge.d.ts.map +1 -1
  29. package/dist/knowledge.js +3 -1
  30. package/dist/knowledge.js.map +1 -1
  31. package/dist/manifest/discover-base-classes.js +2 -2
  32. package/dist/manifest/discover-base-classes.js.map +1 -1
  33. package/dist/manifest/discover-smrt-packages.d.ts.map +1 -1
  34. package/dist/manifest/discover-smrt-packages.js +3 -2
  35. package/dist/manifest/discover-smrt-packages.js.map +1 -1
  36. package/dist/manifest/generator.d.ts +7 -0
  37. package/dist/manifest/generator.d.ts.map +1 -1
  38. package/dist/manifest/generator.js +30 -15
  39. package/dist/manifest/generator.js.map +1 -1
  40. package/dist/manifest/manager.d.ts.map +1 -1
  41. package/dist/manifest/manager.js +6 -2
  42. package/dist/manifest/manager.js.map +1 -1
  43. package/dist/manifest/static-manifest.js +1 -1
  44. package/dist/manifest/static-manifest.js.map +1 -1
  45. package/dist/manifest/store.js +1 -1
  46. package/dist/manifest.json +1 -1
  47. package/dist/node_modules/.pnpm/{brace-expansion@5.0.9 → brace-expansion@5.0.11}/node_modules/brace-expansion/dist/esm/index.js +32 -19
  48. package/dist/node_modules/.pnpm/brace-expansion@5.0.11/node_modules/brace-expansion/dist/esm/index.js.map +1 -0
  49. package/dist/node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/index.js +1 -1
  50. package/dist/scanner/types.d.ts +2 -0
  51. package/dist/scanner/types.d.ts.map +1 -1
  52. package/dist/scanner/types.js.map +1 -1
  53. package/dist/scripts/generate-manifest.js +44 -44
  54. package/dist/scripts/generate-test-manifest.js +49 -2
  55. package/dist/smrt-knowledge.json +7 -7
  56. package/dist/vite-plugin/index.d.ts.map +1 -1
  57. package/dist/vite-plugin/index.js +16 -6
  58. package/dist/vite-plugin/index.js.map +1 -1
  59. package/package.json +4 -4
  60. package/dist/node_modules/.pnpm/brace-expansion@5.0.9/node_modules/brace-expansion/dist/esm/index.js.map +0 -1
@@ -84,6 +84,28 @@ Config precedence for knowledge is defaults → top-level `knowledge` in
84
84
  `smrt.config.ts` → `packages[packageName].knowledge` → plugin option →
85
85
  object-level `@smrt({ knowledge })`.
86
86
 
87
+ Test generation uses that same effective configuration and publishes knowledge
88
+ matching the manifest it generated. Disabling knowledge removes a previous local
89
+ knowledge artifact, so consumers cannot mistake it for current enabled output.
90
+ `new ManifestBuilder(projectRoot)` keeps discovery, package identity, and output
91
+ at that explicit root, including installed providers and external base classes;
92
+ omitting the argument retains the current-working-directory
93
+ behavior. Both manifest writers retain declared package dependencies when merging
94
+ their local and consumed-object projections.
95
+
96
+ Test manifests carry optional `artifactPurpose: 'test'`; dependency discovery
97
+ skips those artifacts, including `.smrt` fallbacks. Unmarked runtime manifests,
98
+ empty published providers, and source-only development providers remain eligible.
99
+ `ManifestBuilder` accepts explicit `outputMode: 'dev' | 'build'`; omitted mode
100
+ retains legacy filename inference. Vitest selects dev mode explicitly, so tests
101
+ never replace a production `dist/manifest.json`. Relative output directories are
102
+ resolved against the builder's project root.
103
+
104
+ Tracked `src/lib/server/smrt-register.ts` belongs to SvelteKit config/type
105
+ generation. Generic library builds consume it but do not cache or restore it
106
+ as an output; otherwise a concurrent config producer's bytes can be replayed
107
+ over a newer registration after dependency eligibility changes.
108
+
87
109
  Object-level `knowledge: false` excludes an object from authored context only;
88
110
  it must not change runtime manifest registration. Use
89
111
  `knowledge: { tags, summary, risks }` for review-sensitive domain objects.
@@ -132,3 +154,6 @@ module, so it must exist during `svelte-kit sync`, before Vite's `buildStart`.
132
154
  Both hosted routes and the legacy `svelteKit: true` mode follow this order.
133
155
  The clean-consumer regression fixture ships real provider declarations and
134
156
  checks the generated imports with `svelte-check`.
157
+ Core's `generate:test` task depends on its own `build`: both publish the local
158
+ `.smrt` manifest/knowledge pair, so Turbo must serialize production before test
159
+ generation instead of caching an interleaved pair.
@@ -239,3 +239,30 @@ Core never imports smrt-dev-mcp; only the generated file does, at consumer
239
239
  runtime. The route carries the auto-generated header so the sweep owns it.
240
240
 
241
241
  Generated SvelteKit write routes (#2977) call `requireRoutePermission(locals, action)` after `requireRouteAuth`: CRUD writes need `<collection>.create|update|delete` and mutating custom actions `<collection>.<method>` in the session permission snapshot on `locals`, else 403 (fail-closed; `api.public: true` stays open, `tenantContext.superAdminBypass` skips). See `packages/users/agents/permissions.md`.
242
+
243
+ ## MCP protocol identifiers (#3219)
244
+
245
+ MCP discovery preserves existing names matching `[A-Za-z0-9_.-]{1,64}`.
246
+ Previously invalid names use their first 31 sanitized ASCII characters, `_`,
247
+ and the first 32 hex characters of SHA-256 over the JSON tuple
248
+ `[original class name, lowercased action name, original raw tool name]`.
249
+ This makes long or punctuation-bearing identifiers deterministic without
250
+ collapsing common prefixes. Discovery reserves compliant names first and fails
251
+ closed on any duplicate raw name or final alias collision instead of advertising
252
+ ambiguous dispatch (including class names differing only by case across packages).
253
+ Consumers must use the advertised name rather than constructing one.
254
+
255
+ The generator retains a separate class/action binding for each descriptor and
256
+ emits that mapping for generated runtimes. Dispatch, task eligibility, tenant
257
+ scoping, ordering, and STI metadata use this binding; protocol aliases are not
258
+ execution identities. The advertised catalog still gates execution. The direct
259
+ runtime-template API accepts `toolTargets`; omitting it retains the legacy
260
+ `object_action` convention for existing direct callers. Supply explicit targets
261
+ for canonicalized names or class names containing underscores. This contract
262
+ does not change CLI, REST, or WebMCP identifiers.
263
+
264
+ `MCPGenerator.getToolIdentity(tool)` exposes the generator-validated original
265
+ class, action, and raw generated name to in-process catalog composers. App MCP
266
+ uses it for class allow-lists, tenant checks, and compatible workflow guards;
267
+ those consumers must not reverse protocol aliases. The alias remains the sole
268
+ wire tool name and is still the key for public patterns and generic tool policy.
@@ -24,4 +24,6 @@ export interface ArtifactFilesystem {
24
24
  * concurrent reader between individual renames can still observe a mixed set.
25
25
  */
26
26
  export declare function publishArtifactFiles(files: ArtifactFile[], filesystem?: ArtifactFilesystem): void;
27
+ /** Atomically replace one artifact without ever removing its reader-visible path. */
28
+ export declare function publishAtomicArtifact(file: ArtifactFile, filesystem?: ArtifactFilesystem): void;
27
29
  //# sourceMappingURL=artifact-publication.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"artifact-publication.d.ts","sourceRoot":"","sources":["../../src/consumer-plugin/artifact-publication.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAE9B,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,kBAAkB;IACjC,UAAU,EAAE,OAAO,EAAE,CAAC,UAAU,CAAC;IACjC,UAAU,EAAE,OAAO,EAAE,CAAC,UAAU,CAAC;IACjC,QAAQ,EAAE,OAAO,EAAE,CAAC,QAAQ,CAAC;IAC7B,UAAU,EAAE,OAAO,EAAE,CAAC,UAAU,CAAC;IACjC,aAAa,EAAE,OAAO,EAAE,CAAC,aAAa,CAAC;IACvC,SAAS,EAAE,OAAO,EAAE,CAAC,SAAS,CAAC;CAChC;AAQD;;;;;;;;;;;GAWG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,YAAY,EAAE,EACrB,UAAU,GAAE,kBAAuB,GAClC,IAAI,CAsFN"}
1
+ {"version":3,"file":"artifact-publication.d.ts","sourceRoot":"","sources":["../../src/consumer-plugin/artifact-publication.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAE9B,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,kBAAkB;IACjC,UAAU,EAAE,OAAO,EAAE,CAAC,UAAU,CAAC;IACjC,UAAU,EAAE,OAAO,EAAE,CAAC,UAAU,CAAC;IACjC,QAAQ,EAAE,OAAO,EAAE,CAAC,QAAQ,CAAC;IAC7B,UAAU,EAAE,OAAO,EAAE,CAAC,UAAU,CAAC;IACjC,aAAa,EAAE,OAAO,EAAE,CAAC,aAAa,CAAC;IACvC,SAAS,EAAE,OAAO,EAAE,CAAC,SAAS,CAAC;CAChC;AAQD;;;;;;;;;;;GAWG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,YAAY,EAAE,EACrB,UAAU,GAAE,kBAAuB,GAClC,IAAI,CAsFN;AAED,qFAAqF;AACrF,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,YAAY,EAClB,UAAU,GAAE,kBAAuB,GAClC,IAAI,CAgBN"}
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import * as fs from "node:fs";
2
3
  //#region src/consumer-plugin/artifact-publication.ts
3
4
  /**
@@ -74,7 +75,20 @@ function publishArtifactFiles(files, filesystem = fs) {
74
75
  }
75
76
  }
76
77
  }
78
+ /** Atomically replace one artifact without ever removing its reader-visible path. */
79
+ function publishAtomicArtifact(file, filesystem = fs) {
80
+ const stagedPath = `${file.path}.smrt-${randomUUID()}.tmp`;
81
+ const stats = filesystem.existsSync(file.path) ? filesystem.statSync(file.path) : void 0;
82
+ if (stats && !stats.isFile()) throw new Error(`Artifact target is not a file: ${file.path}`);
83
+ try {
84
+ filesystem.writeFileSync(stagedPath, file.content, "utf-8");
85
+ if (stats) filesystem.chmodSync(stagedPath, stats.mode & 511);
86
+ filesystem.renameSync(stagedPath, file.path);
87
+ } finally {
88
+ if (filesystem.existsSync(stagedPath)) filesystem.unlinkSync(stagedPath);
89
+ }
90
+ }
77
91
  //#endregion
78
- export { publishArtifactFiles };
92
+ export { publishArtifactFiles, publishAtomicArtifact };
79
93
 
80
94
  //# sourceMappingURL=artifact-publication.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"artifact-publication.js","names":[],"sources":["../../src/consumer-plugin/artifact-publication.ts"],"sourcesContent":["import * as fs from 'node:fs';\n\nexport interface ArtifactFile {\n path: string;\n content: string;\n}\n\nexport interface ArtifactFilesystem {\n existsSync: typeof fs.existsSync;\n renameSync: typeof fs.renameSync;\n statSync: typeof fs.statSync;\n unlinkSync: typeof fs.unlinkSync;\n writeFileSync: typeof fs.writeFileSync;\n chmodSync: typeof fs.chmodSync;\n}\n\ninterface StagedArtifact {\n path: string;\n stagedPath: string;\n backupPath?: string;\n}\n\n/**\n * Stage and publish a related artifact set with synchronous-failure recovery.\n *\n * Every existing target is first renamed to an adjacent backup, preserving its\n * mode, before a staged replacement is renamed into place. If a later rename\n * fails, rollback restores backups using rename only; it never truncates an\n * old target by rewriting it. A rollback failure retains its backup for manual\n * recovery and is included with the original publication failure.\n *\n * There is no portable multi-file filesystem transaction: a process crash or a\n * concurrent reader between individual renames can still observe a mixed set.\n */\nexport function publishArtifactFiles(\n files: ArtifactFile[],\n filesystem: ArtifactFilesystem = fs,\n): void {\n const unique = `${process.pid}-${Date.now()}`;\n const staged: StagedArtifact[] = [];\n const backed: StagedArtifact[] = [];\n const published: StagedArtifact[] = [];\n let retainBackups = false;\n\n try {\n for (const [index, file] of files.entries()) {\n const exists = filesystem.existsSync(file.path);\n const stats = exists ? filesystem.statSync(file.path) : undefined;\n if (stats && !stats.isFile()) {\n throw new Error(`Artifact target is not a file: ${file.path}`);\n }\n const mode = stats ? stats.mode & 0o777 : undefined;\n const stagedFile = {\n path: file.path,\n stagedPath: `${file.path}.smrt-${unique}-${index}.tmp`,\n backupPath: exists\n ? `${file.path}.smrt-${unique}-${index}.bak`\n : undefined,\n };\n // Register before the write: a failed write can still leave a partial\n // temporary file, which the finally cleanup must see.\n staged.push(stagedFile);\n filesystem.writeFileSync(stagedFile.stagedPath, file.content, 'utf-8');\n if (mode !== undefined) filesystem.chmodSync(stagedFile.stagedPath, mode);\n }\n for (const file of staged) {\n if (!file.backupPath) continue;\n filesystem.renameSync(file.path, file.backupPath);\n backed.push(file);\n }\n for (const file of staged) {\n filesystem.renameSync(file.stagedPath, file.path);\n published.push(file);\n }\n } catch (publicationError) {\n const rollbackErrors: unknown[] = [];\n for (const file of backed.reverse()) {\n try {\n if (!file.backupPath) {\n throw new Error(`Missing artifact backup: ${file.path}`);\n }\n // Replacing a published staged file is safe: its authoritative prior\n // contents are held by backupPath until this rename succeeds.\n filesystem.renameSync(file.backupPath, file.path);\n } catch (rollbackError) {\n rollbackErrors.push(rollbackError);\n }\n }\n for (const file of published) {\n if (file.backupPath) continue;\n try {\n if (filesystem.existsSync(file.path)) filesystem.unlinkSync(file.path);\n } catch (rollbackError) {\n rollbackErrors.push(rollbackError);\n }\n }\n if (rollbackErrors.length > 0) {\n retainBackups = true;\n throw new AggregateError(\n [publicationError, ...rollbackErrors],\n 'Artifact publication failed and rollback retained recovery backups',\n );\n }\n throw publicationError;\n } finally {\n for (const file of staged) {\n try {\n if (filesystem.existsSync(file.stagedPath))\n filesystem.unlinkSync(file.stagedPath);\n } catch {\n // A staging file is not an authoritative artifact.\n }\n if (!retainBackups) {\n try {\n if (file.backupPath && filesystem.existsSync(file.backupPath)) {\n filesystem.unlinkSync(file.backupPath);\n }\n } catch {\n // A failed cleanup leaves a recoverable backup behind.\n }\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAkCA,SAAgB,qBACd,OACA,aAAiC,IAC3B;CACN,MAAM,SAAS,GAAG,QAAQ,IAAI,GAAG,KAAK,IAAI;CAC1C,MAAM,SAA2B,CAAC;CAClC,MAAM,SAA2B,CAAC;CAClC,MAAM,YAA8B,CAAC;CACrC,IAAI,gBAAgB;CAEpB,IAAI;EACF,KAAK,MAAM,CAAC,OAAO,SAAS,MAAM,QAAQ,GAAG;GAC3C,MAAM,SAAS,WAAW,WAAW,KAAK,IAAI;GAC9C,MAAM,QAAQ,SAAS,WAAW,SAAS,KAAK,IAAI,IAAI,KAAA;GACxD,IAAI,SAAS,CAAC,MAAM,OAAO,GACzB,MAAM,IAAI,MAAM,kCAAkC,KAAK,MAAM;GAE/D,MAAM,OAAO,QAAQ,MAAM,OAAO,MAAQ,KAAA;GAC1C,MAAM,aAAa;IACjB,MAAM,KAAK;IACX,YAAY,GAAG,KAAK,KAAK,QAAQ,OAAO,GAAG,MAAM;IACjD,YAAY,SACR,GAAG,KAAK,KAAK,QAAQ,OAAO,GAAG,MAAM,QACrC,KAAA;GACN;GAGA,OAAO,KAAK,UAAU;GACtB,WAAW,cAAc,WAAW,YAAY,KAAK,SAAS,OAAO;GACrE,IAAI,SAAS,KAAA,GAAW,WAAW,UAAU,WAAW,YAAY,IAAI;EAC1E;EACA,KAAK,MAAM,QAAQ,QAAQ;GACzB,IAAI,CAAC,KAAK,YAAY;GACtB,WAAW,WAAW,KAAK,MAAM,KAAK,UAAU;GAChD,OAAO,KAAK,IAAI;EAClB;EACA,KAAK,MAAM,QAAQ,QAAQ;GACzB,WAAW,WAAW,KAAK,YAAY,KAAK,IAAI;GAChD,UAAU,KAAK,IAAI;EACrB;CACF,SAAS,kBAAkB;EACzB,MAAM,iBAA4B,CAAC;EACnC,KAAK,MAAM,QAAQ,OAAO,QAAQ,GAChC,IAAI;GACF,IAAI,CAAC,KAAK,YACR,MAAM,IAAI,MAAM,4BAA4B,KAAK,MAAM;GAIzD,WAAW,WAAW,KAAK,YAAY,KAAK,IAAI;EAClD,SAAS,eAAe;GACtB,eAAe,KAAK,aAAa;EACnC;EAEF,KAAK,MAAM,QAAQ,WAAW;GAC5B,IAAI,KAAK,YAAY;GACrB,IAAI;IACF,IAAI,WAAW,WAAW,KAAK,IAAI,GAAG,WAAW,WAAW,KAAK,IAAI;GACvE,SAAS,eAAe;IACtB,eAAe,KAAK,aAAa;GACnC;EACF;EACA,IAAI,eAAe,SAAS,GAAG;GAC7B,gBAAgB;GAChB,MAAM,IAAI,eACR,CAAC,kBAAkB,GAAG,cAAc,GACpC,oEACF;EACF;EACA,MAAM;CACR,UAAU;EACR,KAAK,MAAM,QAAQ,QAAQ;GACzB,IAAI;IACF,IAAI,WAAW,WAAW,KAAK,UAAU,GACvC,WAAW,WAAW,KAAK,UAAU;GACzC,QAAQ,CAER;GACA,IAAI,CAAC,eACH,IAAI;IACF,IAAI,KAAK,cAAc,WAAW,WAAW,KAAK,UAAU,GAC1D,WAAW,WAAW,KAAK,UAAU;GAEzC,QAAQ,CAER;EAEJ;CACF;AACF"}
1
+ {"version":3,"file":"artifact-publication.js","names":[],"sources":["../../src/consumer-plugin/artifact-publication.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport * as fs from 'node:fs';\n\nexport interface ArtifactFile {\n path: string;\n content: string;\n}\n\nexport interface ArtifactFilesystem {\n existsSync: typeof fs.existsSync;\n renameSync: typeof fs.renameSync;\n statSync: typeof fs.statSync;\n unlinkSync: typeof fs.unlinkSync;\n writeFileSync: typeof fs.writeFileSync;\n chmodSync: typeof fs.chmodSync;\n}\n\ninterface StagedArtifact {\n path: string;\n stagedPath: string;\n backupPath?: string;\n}\n\n/**\n * Stage and publish a related artifact set with synchronous-failure recovery.\n *\n * Every existing target is first renamed to an adjacent backup, preserving its\n * mode, before a staged replacement is renamed into place. If a later rename\n * fails, rollback restores backups using rename only; it never truncates an\n * old target by rewriting it. A rollback failure retains its backup for manual\n * recovery and is included with the original publication failure.\n *\n * There is no portable multi-file filesystem transaction: a process crash or a\n * concurrent reader between individual renames can still observe a mixed set.\n */\nexport function publishArtifactFiles(\n files: ArtifactFile[],\n filesystem: ArtifactFilesystem = fs,\n): void {\n const unique = `${process.pid}-${Date.now()}`;\n const staged: StagedArtifact[] = [];\n const backed: StagedArtifact[] = [];\n const published: StagedArtifact[] = [];\n let retainBackups = false;\n\n try {\n for (const [index, file] of files.entries()) {\n const exists = filesystem.existsSync(file.path);\n const stats = exists ? filesystem.statSync(file.path) : undefined;\n if (stats && !stats.isFile()) {\n throw new Error(`Artifact target is not a file: ${file.path}`);\n }\n const mode = stats ? stats.mode & 0o777 : undefined;\n const stagedFile = {\n path: file.path,\n stagedPath: `${file.path}.smrt-${unique}-${index}.tmp`,\n backupPath: exists\n ? `${file.path}.smrt-${unique}-${index}.bak`\n : undefined,\n };\n // Register before the write: a failed write can still leave a partial\n // temporary file, which the finally cleanup must see.\n staged.push(stagedFile);\n filesystem.writeFileSync(stagedFile.stagedPath, file.content, 'utf-8');\n if (mode !== undefined) filesystem.chmodSync(stagedFile.stagedPath, mode);\n }\n for (const file of staged) {\n if (!file.backupPath) continue;\n filesystem.renameSync(file.path, file.backupPath);\n backed.push(file);\n }\n for (const file of staged) {\n filesystem.renameSync(file.stagedPath, file.path);\n published.push(file);\n }\n } catch (publicationError) {\n const rollbackErrors: unknown[] = [];\n for (const file of backed.reverse()) {\n try {\n if (!file.backupPath) {\n throw new Error(`Missing artifact backup: ${file.path}`);\n }\n // Replacing a published staged file is safe: its authoritative prior\n // contents are held by backupPath until this rename succeeds.\n filesystem.renameSync(file.backupPath, file.path);\n } catch (rollbackError) {\n rollbackErrors.push(rollbackError);\n }\n }\n for (const file of published) {\n if (file.backupPath) continue;\n try {\n if (filesystem.existsSync(file.path)) filesystem.unlinkSync(file.path);\n } catch (rollbackError) {\n rollbackErrors.push(rollbackError);\n }\n }\n if (rollbackErrors.length > 0) {\n retainBackups = true;\n throw new AggregateError(\n [publicationError, ...rollbackErrors],\n 'Artifact publication failed and rollback retained recovery backups',\n );\n }\n throw publicationError;\n } finally {\n for (const file of staged) {\n try {\n if (filesystem.existsSync(file.stagedPath))\n filesystem.unlinkSync(file.stagedPath);\n } catch {\n // A staging file is not an authoritative artifact.\n }\n if (!retainBackups) {\n try {\n if (file.backupPath && filesystem.existsSync(file.backupPath)) {\n filesystem.unlinkSync(file.backupPath);\n }\n } catch {\n // A failed cleanup leaves a recoverable backup behind.\n }\n }\n }\n }\n}\n\n/** Atomically replace one artifact without ever removing its reader-visible path. */\nexport function publishAtomicArtifact(\n file: ArtifactFile,\n filesystem: ArtifactFilesystem = fs,\n): void {\n const stagedPath = `${file.path}.smrt-${randomUUID()}.tmp`;\n const exists = filesystem.existsSync(file.path);\n const stats = exists ? filesystem.statSync(file.path) : undefined;\n if (stats && !stats.isFile()) {\n throw new Error(`Artifact target is not a file: ${file.path}`);\n }\n try {\n filesystem.writeFileSync(stagedPath, file.content, 'utf-8');\n if (stats) filesystem.chmodSync(stagedPath, stats.mode & 0o777);\n // POSIX rename replaces the destination atomically: readers see either\n // the old complete file or the new complete file, never no path/bytes.\n filesystem.renameSync(stagedPath, file.path);\n } finally {\n if (filesystem.existsSync(stagedPath)) filesystem.unlinkSync(stagedPath);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAmCA,SAAgB,qBACd,OACA,aAAiC,IAC3B;CACN,MAAM,SAAS,G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AAM,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,EAEL,KAAK,6BAA6B,EACnC,MAAM,2BAA2B,CAAC;AAYnC,OAAO,EAGL,KAAK,gBAAgB,EACtB,MAAM,uCAAuC,CAAC;AAoB/C,OAAO,EACL,kCAAkC,EAClC,KAAK,sCAAsC,EAC3C,KAAK,8BAA8B,EACnC,KAAK,6BAA6B,EAClC,KAAK,0BAA0B,EAC/B,+BAA+B,EAC/B,4BAA4B,GAC7B,MAAM,2BAA2B,CAAC;AAqDnC;;;;GAIG;AACH,MAAM,WAAW,4BACf,SAAQ,OAAO,CACb,IAAI,CACF,gBAAgB,EACd,WAAW,GACX,YAAY,GACZ,gBAAgB,GAChB,aAAa,GACb,cAAc,GACd,aAAa,GACb,gBAAgB,CACnB,CACF;IACD,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;CAC5B;AAED,MAAM,WAAW,mBAAmB;IAClC,4EAA4E;IAC5E,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,uCAAuC;IACvC,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,2CAA2C;IAC3C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,oEAAoE;IACpE,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,6BAA6B,CAAC;IACnD;;;;OAIG;IACH,SAAS,CAAC,EAAE,OAAO,GAAG,4BAA4B,CAAC;IACnD;;;;;OAKG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,oDAAoD;IACpD,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,4BAA4B;IAC5B,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AA2VD;;GAEG;AACH,wBAAgB,YAAY,CAAC,OAAO,GAAE,mBAAwB,GAAG,MAAM,CA2WtE"}
@@ -1,15 +1,15 @@
1
1
  import "../scanner/types.js";
2
+ import { publishArtifactFiles } from "./artifact-publication.js";
2
3
  import { canonicalSvelteKitPath } from "../vite-plugin/sveltekit-path.js";
3
4
  import { clearGeneratedSvelteKitRouteFiles, reconcileSvelteKitRouteGitignore } from "../vite-plugin/sveltekit-generator.js";
4
5
  import { generateWebModule, isCollectionManifestClass, resolveCollectionItemObject } from "../vite-plugin/web-collections.js";
6
+ import { resolveFileKnowledgeConfig } from "../knowledge-config.js";
5
7
  import { buildDomainKnowledgeManifest } from "../knowledge.js";
6
8
  import { manifestExportCandidates } from "../manifest/package-manifest-exports.js";
7
9
  import { loadVerifiedSmrtGenerationSnapshot, serializeSmrtGenerationSnapshot, sha256SmrtGenerationSnapshot } from "../generation-snapshot.js";
8
- import { resolveFileKnowledgeConfig } from "../knowledge-config.js";
9
10
  import { generateClientModule } from "../vite-plugin/generated-client.js";
10
11
  import { activeProducerKnowledgeRoutePaths, activeSvelteKitRouteParticipants, assertNoSvelteKitRouteRootSymlinkConflict, assertSvelteKitRouteCoordinationComplete, contributeSvelteKitRoutes, expectedSvelteKitRouteOwners, markSvelteKitRouteParticipant, producerKnowledgeRoutePaths, revokeSvelteKitRoutes } from "../vite-plugin/sveltekit-route-coordinator.js";
11
12
  import { generateDeclarations } from "../prebuild/index.js";
12
- import { publishArtifactFiles } from "./artifact-publication.js";
13
13
  import * as fs from "node:fs";
14
14
  import * as path from "node:path";
15
15
  //#region src/consumer-plugin/index.ts
@@ -162,7 +162,7 @@ function selectConsumerRouteManifest(manifest, options) {
162
162
  }
163
163
  return {
164
164
  ...manifest,
165
- smrtDependencies: [...new Set(Object.values(manifest.objects).map((objectDef) => objectDef.packageName).filter((packageName) => typeof packageName === "string" && packageName !== manifest.packageName))].sort(),
165
+ smrtDependencies: [.../* @__PURE__ */ new Set([...manifest.smrtDependencies ?? [], ...Object.values(manifest.objects).map((objectDef) => objectDef.packageName).filter((packageName) => typeof packageName === "string" && packageName !== manifest.packageName)])].sort(),
166
166
  objects
167
167
  };
168
168
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/consumer-plugin/index.ts"],"sourcesContent":["/**\n * Vite plugin for consuming SMRT packages\n * Solves virtual module resolution in downstream projects\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { DomainKnowledgeAgentSurface } from '@happyvertical/smrt-types';\nimport type { ConfigEnv, Plugin } from 'vite';\nimport {\n loadVerifiedSmrtGenerationSnapshot,\n type SmrtGenerationSnapshotOptions,\n} from '../generation-snapshot.js';\nimport { buildDomainKnowledgeManifest } from '../knowledge.js';\nimport { resolveFileKnowledgeConfig } from '../knowledge-config.js';\nimport { manifestExportCandidates } from '../manifest/package-manifest-exports.js';\nimport { generateDeclarations } from '../prebuild/index.js';\nimport type {\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types.js';\nimport { MANIFEST_TIMESTAMP } from '../scanner/types.js';\nimport { generateClientModule } from '../vite-plugin/generated-client.js';\nimport type { SmrtPluginApi } from '../vite-plugin/index.js';\nimport {\n clearGeneratedSvelteKitRouteFiles,\n reconcileSvelteKitRouteGitignore,\n type SvelteKitOptions,\n} from '../vite-plugin/sveltekit-generator.js';\nimport { canonicalSvelteKitPath } from '../vite-plugin/sveltekit-path.js';\nimport {\n activeProducerKnowledgeRoutePaths,\n activeSvelteKitRouteParticipants,\n assertNoSvelteKitRouteRootSymlinkConflict,\n assertSvelteKitRouteCoordinationComplete,\n contributeSvelteKitRoutes,\n expectedSvelteKitRouteOwners,\n markSvelteKitRouteParticipant,\n producerKnowledgeRoutePaths,\n revokeSvelteKitRoutes,\n} from '../vite-plugin/sveltekit-route-coordinator.js';\nimport {\n generateWebModule,\n isCollectionManifestClass,\n resolveCollectionItemObject,\n} from '../vite-plugin/web-collections.js';\nimport { publishArtifactFiles } from './artifact-publication.js';\n\nexport {\n loadVerifiedSmrtGenerationSnapshot,\n type SerializeSmrtGenerationSnapshotOptions,\n type SmrtGenerationSnapshotArtifact,\n type SmrtGenerationSnapshotOptions,\n type SmrtGenerationSnapshotView,\n serializeSmrtGenerationSnapshot,\n sha256SmrtGenerationSnapshot,\n} from '../generation-snapshot.js';\n\n/**\n * Loosely-typed view of an object definition as carried by an external\n * package's static manifest. The static manifests are read from JSON at the\n * package boundary, so only the fields this plugin consumes are typed; the\n * index signature preserves any additional fields (e.g. for spreads). This is\n * a structural superset of a manifest `SmartObjectDefinition` plus the\n * consumer-only `hasCollection` marker.\n */\ninterface ConsumerObjectDefinition {\n className?: string;\n packageName?: string;\n packageVersion?: string;\n qualifiedName?: string;\n importPath?: string;\n exportName?: string;\n collectionExportName?: string;\n hasCollection?: boolean;\n collection?: string;\n extends?: string;\n extendsQualified?: string;\n extendsTypeArg?: string;\n [key: string]: unknown;\n}\n\n/**\n * Aggregated manifest assembled by the consumer plugin from one or more\n * external package manifests. Loosely typed because the inputs originate from\n * JSON read at the package boundary.\n */\ninterface ConsumerManifest {\n version: string;\n timestamp: number;\n packageName?: string;\n packageVersion?: string;\n smrtDependencies?: string[];\n objects: Record<string, ConsumerObjectDefinition>;\n}\n\n/**\n * Minimal structural shape of a parsed `package.json` consumed here (name,\n * version, and the export map used to derive import paths). The index\n * signature keeps the remaining fields accessible.\n */\ninterface ConsumerPackageJson {\n name?: string;\n version?: string;\n main?: string;\n exports?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\n/**\n * SvelteKit route-hosting options for dependency models. Unlike `packages`,\n * `objects` is an HTTP exposure boundary: every entry must be an exact,\n * provider-qualified manifest key (for example, `@acme/widgets:Widget`).\n */\nexport interface SmrtConsumerSvelteKitOptions\n extends Partial<\n Pick<\n SvelteKitOptions,\n | 'routesDir'\n | 'configPath'\n | 'configFileName'\n | 'kebabRoutes'\n | 'changesRoute'\n | 'eventsRoute'\n | 'resourcesRoute'\n >\n > {\n objects: readonly string[];\n}\n\nexport interface SmrtConsumerOptions {\n /** SMRT packages to scan (e.g., ['@my-org/products', '@my-org/content']) */\n packages?: string[];\n /** Generate TypeScript declarations */\n generateTypes?: boolean;\n /** Output directory for generated types */\n typesDir?: string;\n /** Project root path (defaults to the current working directory) */\n projectRoot?: string;\n /**\n * Reuse an immutable, verified aggregated manifest instead of discovering\n * packages or writing `.smrt/manifest.json`. Registration and generated\n * types still consume the verified manifest.\n */\n generationSnapshot?: SmrtGenerationSnapshotOptions;\n /**\n * Consumer SvelteKit integration. `true` retains the historical compatibility\n * mode and does not generate dependency routes. Route hosting requires an\n * explicit, provider-qualified object allowlist.\n */\n svelteKit?: boolean | SmrtConsumerSvelteKitOptions;\n /**\n * Apply kebab-case to generated custom-method URL segments. This must match\n * the producer plugin's `svelteKit.kebabRoutes` setting. When explicit\n * consumer SvelteKit hosting is configured, its `kebabRoutes` value takes\n * precedence, including an explicit `false`.\n */\n kebabRoutes?: boolean;\n /** Use static types only (for federation builds) */\n staticTypes?: boolean;\n /** Disable file scanning */\n disableScanning?: boolean;\n}\n\n// Distinct resolved ids per plugin (#1795). smrtPlugin resolves\n// `@happyvertical/smrt-virt-*` to `\\0smrt:*`; if this consumer plugin also\n// resolved its `@smrt/*` specifiers to `\\0smrt:*` the two virtual modules would\n// share a rollup id, and in standalone/federation builds the consumer's\n// fallback `load` would non-deterministically win and shadow smrtPlugin's real\n// module. Namespacing the consumer ids (`\\0smrt-consumer:*`) keeps them\n// separate so each plugin only ever loads its own module.\nconst VIRTUAL_MODULES = {\n '@smrt/routes': 'smrt-consumer:routes',\n '@smrt/client': 'smrt-consumer:client',\n '@smrt/mcp': 'smrt-consumer:mcp',\n '@smrt/types': 'smrt-consumer:types',\n '@smrt/manifest': 'smrt-consumer:manifest',\n '@smrt/web': 'smrt-consumer:web',\n};\n\nconst CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION = 1;\nconst CONSUMER_SVELTEKIT_ROUTES_ARTIFACT = 'consumer-sveltekit-routes.json';\n\ninterface ConsumerSvelteKitRoutesArtifact {\n version: number;\n routesDir: string[];\n}\n\nfunction consumerSvelteKitRoutesArtifactPath(projectRoot: string): string {\n return path.join(projectRoot, '.smrt', CONSUMER_SVELTEKIT_ROUTES_ARTIFACT);\n}\n\n/** Persist only project-relative consumer route roots, never an output file list. */\nfunction canonicalConsumerRouteRoot(\n projectRoot: string,\n routesDir: string,\n): string {\n const root = path.resolve(projectRoot);\n const relative = path.relative(root, path.resolve(root, routesDir));\n if (\n !relative ||\n relative === '..' ||\n relative.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relative)\n ) {\n throw new Error(\n `[smrt:consumer] svelteKit.routesDir must be a project-relative subdirectory (received ${JSON.stringify(routesDir)})`,\n );\n }\n return relative.split(path.sep).join('/');\n}\n\nfunction loadConsumerSvelteKitRouteRoots(projectRoot: string): string[] {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n if (!fs.existsSync(artifactPath)) return [];\n let parsed: ConsumerSvelteKitRoutesArtifact;\n try {\n parsed = JSON.parse(fs.readFileSync(artifactPath, 'utf-8'));\n } catch {\n throw new Error(\n `[smrt:consumer] Cannot read ${CONSUMER_SVELTEKIT_ROUTES_ARTIFACT}; refusing to leave hosted routes unreconciled`,\n );\n }\n if (\n parsed?.version !== CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION ||\n !Array.isArray(parsed.routesDir) ||\n parsed.routesDir.some((routesDir) => typeof routesDir !== 'string')\n ) {\n throw new Error(\n `[smrt:consumer] Invalid ${CONSUMER_SVELTEKIT_ROUTES_ARTIFACT}; refusing to leave hosted routes unreconciled`,\n );\n }\n return [...new Set(parsed.routesDir)].map((routesDir) =>\n canonicalConsumerRouteRoot(projectRoot, routesDir),\n );\n}\n\nfunction publishConsumerSvelteKitRouteRoots(\n projectRoot: string,\n routesDir: string[],\n): void {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n fs.mkdirSync(path.dirname(artifactPath), { recursive: true });\n publishArtifactFiles([\n {\n path: artifactPath,\n content: JSON.stringify(\n {\n version: CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION,\n routesDir: [...new Set(routesDir)].sort(),\n } satisfies ConsumerSvelteKitRoutesArtifact,\n null,\n 2,\n ),\n },\n ]);\n}\n\nfunction removeConsumerSvelteKitRouteRoots(projectRoot: string): void {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n if (fs.existsSync(artifactPath)) fs.unlinkSync(artifactPath);\n}\n\n/**\n * A hosting-to-hosting move can replace one configured root with another in a\n * fresh lifecycle. Validate every durable former root before the new target\n * journals or clears anything, otherwise a rejected move could alter the\n * prior generated surface before reconciliation notices the conflict.\n */\nasync function assertConsumerSvelteKitFormerRouteRootsAreSafe(\n userConfig: unknown,\n projectRoot: string,\n routesDir: readonly string[],\n env?: ConfigEnv,\n): Promise<void> {\n if (routesDir.length === 0) return;\n const activeParticipants = await activeSvelteKitRouteParticipants(\n userConfig,\n projectRoot,\n env,\n );\n const activeRoots = activeParticipants.map(\n (participant) => participant.routesDir,\n );\n for (const priorRoutesDir of routesDir) {\n assertNoSvelteKitRouteRootSymlinkConflict(\n canonicalSvelteKitPath(path.resolve(projectRoot, priorRoutesDir)),\n activeRoots,\n );\n }\n}\n\nasync function reconcileConsumerSvelteKitRouteRoots(\n lifecycle: object,\n userConfig: unknown,\n projectRoot: string,\n routesDir: string[],\n afterReconciled: () => void,\n env?: ConfigEnv,\n): Promise<void> {\n const remaining = new Set(routesDir);\n const reconcileOne = (routesDir: string) => {\n remaining.delete(routesDir);\n if (remaining.size === 0) afterReconciled();\n };\n\n if (remaining.size === 0) {\n afterReconciled();\n return;\n }\n\n for (const routesDir of [...remaining]) {\n const routeRoot = canonicalSvelteKitPath(\n path.resolve(projectRoot, routesDir),\n );\n const activeParticipants = await activeSvelteKitRouteParticipants(\n userConfig,\n projectRoot,\n env,\n );\n // The durable consumer inventory names roots, not individual handlers.\n // Check before every reconciliation branch, including an active parent\n // consumer that would otherwise compact a nested former root without a\n // sweep. A child symlink into a foreign active root makes that ownership\n // ambiguous, so retaining the inventory makes retry safe.\n assertNoSvelteKitRouteRootSymlinkConflict(\n routeRoot,\n activeParticipants.map((participant) => participant.routesDir),\n );\n const containingConsumer = activeParticipants.find(\n (participant) =>\n participant.owner === 'consumer' &&\n (routeRoot === participant.routesDir ||\n routeRoot.startsWith(`${participant.routesDir}${path.sep}`)),\n );\n // A current parent consumer root has already swept and regenerated this\n // former child root. Sweeping it again would remove the newly selected\n // handler before SvelteKit inventories it.\n if (containingConsumer) {\n reconcileOne(routesDir);\n continue;\n }\n const containingProducer = activeParticipants.find(\n (participant) =>\n participant.owner === 'producer' &&\n (routeRoot === participant.routesDir ||\n routeRoot.startsWith(`${participant.routesDir}${path.sep}`)),\n );\n if (containingProducer) {\n await revokeSvelteKitRoutes(\n lifecycle,\n await expectedSvelteKitRouteOwners(\n userConfig,\n containingProducer.projectRoot,\n containingProducer.routesDir,\n env,\n ),\n containingProducer.projectRoot,\n containingProducer.routesDir,\n () => reconcileOne(routesDir),\n );\n continue;\n }\n const owners = await expectedSvelteKitRouteOwners(\n userConfig,\n projectRoot,\n routesDir,\n env,\n );\n if (owners.includes('producer')) {\n await revokeSvelteKitRoutes(\n lifecycle,\n owners,\n projectRoot,\n routesDir,\n () => reconcileOne(routesDir),\n );\n continue;\n }\n clearGeneratedSvelteKitRouteFiles(\n routeRoot,\n producerKnowledgeRoutePaths(lifecycle),\n new Set(\n activeParticipants\n .map((participant) => participant.routesDir)\n .filter((activeRoot) => activeRoot !== routeRoot),\n ),\n );\n reconcileSvelteKitRouteGitignore(projectRoot, routesDir);\n reconcileOne(routesDir);\n }\n}\n\nfunction consumerRouteOptions(\n value: SmrtConsumerOptions['svelteKit'],\n): SmrtConsumerSvelteKitOptions | undefined {\n if (!value || value === true) return undefined;\n if (!Array.isArray(value.objects) || value.objects.length === 0) {\n throw new Error(\n '[smrt:consumer] svelteKit.objects must list at least one provider-qualified object reference',\n );\n }\n for (const objectRef of value.objects) {\n if (typeof objectRef !== 'string' || !objectRef.includes(':')) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects entries must be provider-qualified (received ${JSON.stringify(objectRef)})`,\n );\n }\n }\n return value;\n}\n\nfunction consumerUtilityOption<T extends { enabled?: boolean }>(\n value: T | undefined,\n): T | { enabled: false } {\n return value?.enabled === true ? value : { enabled: false };\n}\n\nfunction consumerObjectRef(\n manifestKey: string,\n objectDef: ConsumerObjectDefinition,\n): string | undefined {\n if (manifestKey.includes(':')) return manifestKey;\n if (objectDef.qualifiedName?.includes(':')) return objectDef.qualifiedName;\n if (objectDef.packageName && objectDef.className) {\n return `${objectDef.packageName}:${objectDef.className}`;\n }\n return undefined;\n}\n\n/**\n * Select exactly the dependency objects that a consumer explicitly hosts.\n * Validation completes before the generator clears its managed files, so an\n * invalid deployment cannot erase a previously generated route surface.\n */\nfunction selectConsumerRouteManifest(\n manifest: ConsumerManifest,\n options: SmrtConsumerSvelteKitOptions,\n): SmartObjectManifest {\n const entriesByRef = new Map<string, [string, ConsumerObjectDefinition]>();\n for (const [manifestKey, objectDef] of Object.entries(manifest.objects)) {\n const objectRef = consumerObjectRef(manifestKey, objectDef);\n if (objectRef) entriesByRef.set(objectRef, [manifestKey, objectDef]);\n }\n\n const selected = new Set<string>();\n const objects: Record<string, ConsumerObjectDefinition> = {};\n for (const objectRef of options.objects) {\n const entry = entriesByRef.get(objectRef);\n if (!entry) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects references unknown dependency object ${JSON.stringify(objectRef)}`,\n );\n }\n if (selected.has(objectRef)) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects contains duplicate object ${JSON.stringify(objectRef)}`,\n );\n }\n selected.add(objectRef);\n const [, objectDef] = entry;\n objects[objectRef] = { ...objectDef, qualifiedName: objectRef };\n }\n\n const sourceManifest = manifest as unknown as SmartObjectManifest;\n // Use the generator's canonical ancestry resolver so a collection subclass\n // inherits the selected item's identity through any number of ancestors.\n for (const [manifestKey, objectDef] of Object.entries(manifest.objects)) {\n const candidate = objectDef as unknown as SmartObjectDefinition;\n if (!isCollectionManifestClass(sourceManifest, candidate)) continue;\n const item = resolveCollectionItemObject(sourceManifest, candidate);\n const itemEntry = item\n ? Object.entries(manifest.objects).find(\n ([, value]) => (value as unknown) === item,\n )\n : undefined;\n const itemRef = itemEntry\n ? consumerObjectRef(itemEntry[0], itemEntry[1])\n : undefined;\n if (!itemRef || !selected.has(itemRef)) continue;\n const collectionRef = consumerObjectRef(manifestKey, objectDef);\n if (collectionRef) {\n objects[collectionRef] = { ...objectDef, qualifiedName: collectionRef };\n }\n }\n\n return {\n ...manifest,\n // The generated route config imports this full registration entry point so\n // SSR retains every consumer provider, while only `objects` reach routing.\n // `smrtDependencies` is optional in verified snapshots, so derive this\n // generator signal from the immutable full manifest rather than treating\n // absent metadata as an empty provider inventory.\n smrtDependencies: [\n ...new Set(\n Object.values(manifest.objects)\n .map((objectDef) => objectDef.packageName)\n .filter(\n (packageName): packageName is string =>\n typeof packageName === 'string' &&\n packageName !== manifest.packageName,\n ),\n ),\n ].sort(),\n objects,\n } as unknown as SmartObjectManifest;\n}\n\n/**\n * Consumer plugin for projects that use SMRT packages\n */\nexport function smrtConsumer(options: SmrtConsumerOptions = {}): Plugin {\n const {\n packages = [],\n generateTypes = true,\n typesDir = 'src/types/smrt-generated',\n projectRoot = process.cwd(),\n generationSnapshot,\n disableScanning = false,\n kebabRoutes = false,\n } = options;\n const consumerSvelteKit = consumerRouteOptions(options.svelteKit);\n // Hosted routes, the generated client, and web tool definitions must expose\n // the same custom-action URLs. Nested consumer SvelteKit hosting owns this\n // policy when present, including an explicit false override.\n const effectiveKebabRoutes = consumerSvelteKit?.kebabRoutes ?? kebabRoutes;\n\n let smrtPackages: string[] = [];\n let typeManifest: ConsumerManifest | null = null;\n let typesGenerated = false;\n let producerApi: SmrtPluginApi | undefined;\n let routeLifecycleConfig: object | undefined;\n\n function loadGenerationSnapshot(): ConsumerManifest {\n if (!generationSnapshot) {\n throw new Error('[smrt:consumer] Generation snapshot is not configured');\n }\n return loadVerifiedSmrtGenerationSnapshot<ConsumerManifest>(\n generationSnapshot,\n projectRoot,\n 'dependencies',\n );\n }\n\n /**\n * Resolve the packages to aggregate, and whether that list was asserted by\n * the consumer's config. An explicit list fails closed when a package\n * yields no manifest; a heuristically discovered one only warns.\n */\n async function resolveConsumerPackages(): Promise<{\n names: string[];\n explicit: boolean;\n }> {\n if (packages.length === 0 && !disableScanning) {\n return {\n names: await discoverSmrtPackages(projectRoot),\n explicit: false,\n };\n }\n return { names: packages, explicit: packages.length > 0 };\n }\n\n async function generateConfigTypes(\n manifest?: ConsumerManifest,\n ): Promise<void> {\n if (!generateTypes || typesGenerated) return;\n\n if (manifest) {\n typeManifest = manifest;\n } else if (generationSnapshot) {\n typeManifest = loadGenerationSnapshot();\n } else {\n const resolved = await resolveConsumerPackages();\n typeManifest = await aggregateTypeManifests(resolved.names, projectRoot, {\n explicit: resolved.explicit,\n });\n }\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n\n const plugin: Plugin = {\n name: 'smrt-consumer',\n\n // SvelteKit inventories routes in its config hook. Run before it so a\n // clean consumer build sees the explicit dependency routes on its first\n // invocation, even when sveltekit() appears first in vite.config.\n enforce: 'pre',\n\n config: {\n order: 'pre',\n async handler(userConfig, env) {\n const routeLifecycle = env ?? userConfig;\n routeLifecycleConfig = routeLifecycle;\n const previousConsumerRouteRoots =\n loadConsumerSvelteKitRouteRoots(projectRoot);\n if (consumerSvelteKit) {\n await assertConsumerSvelteKitFormerRouteRootsAreSafe(\n userConfig,\n projectRoot,\n previousConsumerRouteRoots,\n env,\n );\n const routePackages = await resolveConsumerPackages();\n const routeManifest = generationSnapshot\n ? loadGenerationSnapshot()\n : await aggregateTypeManifests(routePackages.names, projectRoot, {\n explicit: routePackages.explicit,\n });\n const hostedManifest = selectConsumerRouteManifest(\n routeManifest,\n consumerSvelteKit,\n );\n const routesDir = canonicalConsumerRouteRoot(\n projectRoot,\n consumerSvelteKit.routesDir ?? 'src/routes/api',\n );\n const reservedRoutePaths = await activeProducerKnowledgeRoutePaths(\n userConfig,\n projectRoot,\n env,\n );\n const routeOptions = {\n enabled: true,\n routesDir,\n objectsDir: 'src/lib/objects',\n configPath: consumerSvelteKit.configPath ?? 'src/lib/server',\n configFileName: consumerSvelteKit.configFileName ?? 'smrt.ts',\n kebabRoutes: effectiveKebabRoutes,\n // These span a model set rather than one selected object, so new\n // consumer hosting starts fail-closed. Callers can opt in with the\n // generator's established option shapes.\n changesRoute: consumerUtilityOption(consumerSvelteKit.changesRoute),\n eventsRoute: consumerUtilityOption(consumerSvelteKit.eventsRoute),\n resourcesRoute: consumerUtilityOption(\n consumerSvelteKit.resourcesRoute,\n ),\n rejectRouteCollisions: true,\n };\n let ownershipJournaled = false;\n let reconciliationScheduled = false;\n await contributeSvelteKitRoutes(\n routeLifecycle,\n await expectedSvelteKitRouteOwners(\n userConfig,\n projectRoot,\n routeOptions.routesDir,\n env,\n ),\n projectRoot,\n {\n owner: 'consumer',\n routeManifest: hostedManifest,\n semanticManifest: routeManifest as unknown as SmartObjectManifest,\n options: routeOptions,\n reservedRoutePaths,\n beforeCleanup: async () => {\n // Route selection and collision checks have succeeded, but no\n // generated output has changed. SvelteKit type checking still\n // runs after this config hook and needs these declarations.\n await generateConfigTypes(routeManifest);\n // The generated TS registration imports this runtime module.\n // SvelteKit sync must resolve it before Vite buildStart runs.\n await generateRegistrationFile(routeManifest, projectRoot);\n if (ownershipJournaled) return;\n ownershipJournaled = true;\n // Preflight has succeeded but no generated output has changed.\n // Keep both roots until old-root reconciliation commits.\n publishConsumerSvelteKitRouteRoots(projectRoot, [\n ...previousConsumerRouteRoots,\n routesDir,\n ]);\n },\n afterGenerate: async () => {\n if (reconciliationScheduled) return;\n reconciliationScheduled = true;\n const priorRoots = previousConsumerRouteRoots.filter(\n (previousRoot) => previousRoot !== routesDir,\n );\n await reconcileConsumerSvelteKitRouteRoots(\n routeLifecycle,\n userConfig,\n projectRoot,\n priorRoots,\n () =>\n publishConsumerSvelteKitRouteRoots(projectRoot, [\n routesDir,\n ]),\n env,\n );\n },\n },\n );\n } else {\n // Legacy/non-hosting SvelteKit consumers have no route preflight,\n // but still need physical virtual-module declarations before their\n // SvelteKit typecheck reaches Vite's later buildStart lifecycle.\n await generateConfigTypes();\n if (options.svelteKit && typeManifest) {\n await generateRegistrationFile(typeManifest, projectRoot);\n }\n if (previousConsumerRouteRoots.length > 0) {\n await reconcileConsumerSvelteKitRouteRoots(\n routeLifecycle,\n userConfig,\n projectRoot,\n previousConsumerRouteRoots,\n () => removeConsumerSvelteKitRouteRoots(projectRoot),\n env,\n );\n }\n }\n return {\n build: {\n rollupOptions: {\n // Runtime registration evaluates provider entry points so their\n // exact constructors can be registered. Leave optional native\n // provider binaries to Node instead of parsing them as JavaScript.\n external: [/\\.node$/],\n },\n },\n };\n },\n },\n\n configResolved(resolvedConfig) {\n if (consumerSvelteKit && routeLifecycleConfig) {\n assertSvelteKitRouteCoordinationComplete(routeLifecycleConfig);\n }\n producerApi = (resolvedConfig.plugins ?? []).find(\n (plugin) => plugin?.name === 'smrt-auto-service',\n )?.api as SmrtPluginApi | undefined;\n },\n\n async buildStart() {\n console.log('[smrt:consumer] Initializing SMRT consumer plugin');\n\n if (generationSnapshot) {\n typeManifest = loadGenerationSnapshot();\n console.log(\n `[smrt:consumer] Reusing verified generation snapshot (${generationSnapshot.provenance})`,\n );\n await generateRegistrationFile(typeManifest, projectRoot);\n if (generateTypes && !typesGenerated) {\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n return;\n }\n\n // Discover SMRT packages if not explicitly specified\n const resolvedPackages = await resolveConsumerPackages();\n smrtPackages = resolvedPackages.names;\n\n if (smrtPackages.length > 0) {\n console.log(\n `[smrt:consumer] Found SMRT packages: ${smrtPackages.join(', ')}`,\n );\n\n // Aggregate type manifests from discovered packages\n typeManifest = await aggregateTypeManifests(smrtPackages, projectRoot, {\n explicit: resolvedPackages.explicit,\n });\n // Wait before reading .smrt/manifest.json: a producer's parallel\n // buildStart writes its current local manifest after scanning. Reading\n // first could merge an older local manifest with a newer surface.\n const agentSurface = producerApi\n ? await producerApi.resolveKnowledgeAgentSurface()\n : undefined;\n\n // Save aggregated manifest for CLI discovery\n await saveAggregatedManifest(\n typeManifest,\n projectRoot,\n producerApi?.resolveKnowledgeConfig,\n agentSurface,\n );\n\n // Generate registration file for CLI class loading\n await generateRegistrationFile(typeManifest, projectRoot);\n\n // Generate types if requested\n if (generateTypes && !typesGenerated) {\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n } else {\n console.log('[smrt:consumer] No SMRT packages found');\n typeManifest = {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n };\n }\n },\n\n resolveId(id, _importer) {\n // Resolve virtual modules to generated type declarations\n if (id in VIRTUAL_MODULES) {\n // Generated declarations are ambient TypeScript declarations, not\n // executable JavaScript. Vite must always load the consumer runtime\n // module after default type generation writes them.\n if (id !== '@smrt/types') {\n return `\\0${VIRTUAL_MODULES[id as keyof typeof VIRTUAL_MODULES]}`;\n }\n\n const typeFileName = getTypeFileName(id);\n const typePath = path.join(projectRoot, typesDir, typeFileName);\n\n // If types file exists, resolve to it\n if (fs.existsSync(typePath)) {\n return typePath;\n }\n\n // Otherwise use virtual module ID for runtime resolution\n return `\\0${VIRTUAL_MODULES[id as keyof typeof VIRTUAL_MODULES]}`;\n }\n return null;\n },\n\n async load(id) {\n // Handle virtual modules if types aren't available\n const cleanId = id.startsWith('\\0') ? id.slice(1) : id;\n\n if (!typeManifest) {\n typeManifest = generationSnapshot\n ? loadGenerationSnapshot()\n : {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n };\n }\n\n switch (cleanId) {\n case 'smrt-consumer:routes':\n return generateFallbackRoutesModule();\n\n case 'smrt-consumer:client':\n return generateFallbackClientModule(typeManifest, {\n kebabRoutes: effectiveKebabRoutes,\n });\n\n case 'smrt-consumer:mcp':\n return generateFallbackMcpModule();\n\n case 'smrt-consumer:types':\n return generateFallbackTypesModule(typeManifest);\n\n case 'smrt-consumer:manifest':\n return generateFallbackManifestModule(typeManifest);\n\n case 'smrt-consumer:web':\n return generateWebModule(\n typeManifest as unknown as SmartObjectManifest,\n {\n kebabRoutes: effectiveKebabRoutes,\n },\n );\n\n default:\n return null;\n }\n },\n };\n markSvelteKitRouteParticipant(\n plugin,\n 'consumer',\n Boolean(consumerSvelteKit),\n consumerSvelteKit?.routesDir ?? 'src/routes/api',\n undefined,\n () => projectRoot,\n );\n return plugin;\n}\n\n/**\n * Discover SMRT packages from a consumer app's dependencies.\n *\n * Intentional split (#1579): this **consumer-plugin** path is async and\n * resolves SMRT packages from the downstream app's `package.json` dependency\n * names (`@have/`/`smrt` heuristic + `hasSmrtManifest` probe) inside the Vite\n * consumer plugin. It is deliberately separate from the build-time\n * `discoverSmrtPackages()` in `src/manifest/discover-smrt-packages.ts` — a\n * synchronous, lockfile-cached `node_modules` manifest scan used for manifest\n * generation. Different inputs, contexts, and lifecycles, not duplicated logic.\n */\nasync function discoverSmrtPackages(projectRoot: string): Promise<string[]> {\n const packages: string[] = [];\n const nodeModulesPath = path.join(projectRoot, 'node_modules');\n\n if (!fs.existsSync(nodeModulesPath)) {\n return packages;\n }\n\n try {\n // Check package.json for workspace dependencies\n const packageJsonPath = path.join(projectRoot, 'package.json');\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n const allDeps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n ...packageJson.peerDependencies,\n };\n\n // Look for packages that likely contain SMRT objects\n for (const [name, version] of Object.entries(allDeps)) {\n if (\n typeof version === 'string' &&\n (name.includes('smrt') ||\n name.includes('@have/') ||\n (await hasSmrtManifest(nodeModulesPath, name)))\n ) {\n packages.push(name);\n }\n }\n }\n } catch (error) {\n console.warn('[smrt:consumer] Error discovering packages:', error);\n }\n\n return packages;\n}\n\n/**\n * Manifest locations probed for a consumed package, in preference order.\n *\n * The package's own `package.json#exports` map comes first: it is the\n * published contract for where the manifest lives, and a package whose build\n * emits outside this framework's conventional layout (for example\n * `\"./manifest.json\": \"./dist/lib/manifest.json\"`) is otherwise skipped\n * entirely (issue #2923). The conventional paths remain as a fallback for\n * packages that ship a manifest without exporting a subpath for it.\n */\nfunction legacyStaticManifestPath(packageDir: string): string {\n return path.join(packageDir, 'dist', 'manifest', 'static-manifest.js');\n}\n\nfunction packageManifestCandidates(\n packageDir: string,\n packageJson?: ConsumerPackageJson,\n): string[] {\n return [\n ...manifestExportCandidates(packageDir, packageJson),\n legacyStaticManifestPath(packageDir),\n path.join(packageDir, 'dist', 'manifest.json'),\n path.join(packageDir, 'manifest.json'),\n ];\n}\n\n/**\n * Whether a dependency looks like a SMRT package, for the name-heuristic\n * discovery path only.\n *\n * This decides whether a package this framework knows nothing about is pulled\n * into aggregation at all, so mere existence of a manifest-shaped file is not\n * enough: `manifest.json` at a package root or `dist/manifest.json` is a\n * common artifact of unrelated tooling (Vite build manifests, PWA and\n * extension manifests). A false positive would announce a stranger under\n * \"Found SMRT packages\", tell the user to publish a manifest for a package\n * that has nothing to do with SMRT, and — for a JS candidate — evaluate that\n * dependency's module inside the build.\n *\n * A JSON candidate is therefore confirmed by parsing it and requiring\n * `moduleType: 'smrt'`, matching what build-time discovery requires. A JS\n * candidate cannot be identified without importing it, which is the thing\n * being avoided, so only the historical `dist/manifest/static-manifest.js`\n * location counts — exactly the probe this function used before #2923.\n */\nasync function hasSmrtManifest(\n nodeModulesPath: string,\n packageName: string,\n): Promise<boolean> {\n const packagePath = path.join(nodeModulesPath, packageName);\n const legacyStaticManifest = legacyStaticManifestPath(packagePath);\n\n for (const manifestPath of packageManifestCandidates(packagePath)) {\n if (!fs.existsSync(manifestPath)) continue;\n\n if (!manifestPath.endsWith('.json')) {\n if (manifestPath === legacyStaticManifest) return true;\n continue;\n }\n\n try {\n const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')) as {\n moduleType?: string;\n };\n if (manifest?.moduleType === 'smrt') return true;\n } catch {\n // Not a readable SMRT manifest; keep probing the remaining candidates.\n }\n }\n\n return false;\n}\n\n/**\n * Aggregate type manifests from multiple packages.\n *\n * A package that yields no usable manifest is never dropped silently\n * (issue #2923): an explicitly listed package fails the build, and a\n * heuristically discovered one warns by name. Silence here surfaces much\n * later as missing tables, routes, and generated types with nothing in the\n * build log to connect them to the package that was skipped.\n *\n * @param packages - Package names to aggregate.\n * @param projectRoot - Consumer project root containing `node_modules`.\n * @param options - `explicit` marks a caller-supplied `packages` list, whose\n * entries are assertions rather than guesses and therefore fail closed.\n */\nasync function aggregateTypeManifests(\n packages: string[],\n projectRoot: string,\n options: { explicit?: boolean } = {},\n): Promise<ConsumerManifest> {\n const aggregatedManifest: ConsumerManifest = {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n smrtDependencies: [...packages],\n objects: {},\n };\n\n const unresolvedPackages: string[] = [];\n\n for (const packageName of packages) {\n let loadedManifest = false;\n try {\n const packageDir = path.join(projectRoot, 'node_modules', packageName);\n\n // Load package.json for version and export information\n const packageJsonPath = path.join(packageDir, 'package.json');\n let packageJson: ConsumerPackageJson;\n try {\n const packageJsonContent = fs.readFileSync(packageJsonPath, 'utf-8');\n packageJson = JSON.parse(packageJsonContent) as ConsumerPackageJson;\n } catch {\n console.warn(\n `[smrt:consumer] Could not read package.json for ${packageName}`,\n );\n unresolvedPackages.push(packageName);\n continue;\n }\n\n // Try the package's declared manifest export first, then convention.\n const manifestCandidates = packageManifestCandidates(\n packageDir,\n packageJson,\n );\n\n for (const manifestPath of manifestCandidates) {\n if (fs.existsSync(manifestPath)) {\n // Import or read the manifest. A candidate that exists but cannot be\n // read, parsed, or imported must not end the search: the export map\n // is probed before the conventional paths, so letting one stale or\n // malformed exported target throw out of this loop would take away\n // the `dist/manifest.json` fallback a package used to load through.\n let manifest: Partial<ConsumerManifest> | undefined;\n try {\n if (manifestPath.endsWith('.js')) {\n const manifestModule = await import(manifestPath);\n manifest =\n manifestModule.staticManifest || manifestModule.default;\n } else {\n const manifestContent = fs.readFileSync(manifestPath, 'utf-8');\n manifest = JSON.parse(\n manifestContent,\n ) as Partial<ConsumerManifest>;\n }\n } catch (error) {\n console.warn(\n `[smrt:consumer] Could not load manifest candidate ${manifestPath} for ${packageName}; trying the next location:`,\n error,\n );\n continue;\n }\n\n if (manifest?.objects) {\n console.log(\n `[smrt:consumer] Loaded manifest from ${packageName} (${Object.keys(manifest.objects).length} objects)`,\n );\n\n // ENHANCED: Preserve package metadata for each object\n for (const [objectName, objectDef] of Object.entries(\n manifest.objects,\n )) {\n const def = objectDef;\n\n aggregatedManifest.objects[objectName] = {\n ...def,\n // Ensure package metadata is preserved/set\n packageName:\n def.packageName || manifest.packageName || packageName,\n packageVersion:\n def.packageVersion ||\n manifest.packageVersion ||\n packageJson.version,\n // Add fallback import paths if missing\n importPath: def.importPath || determineImportPath(packageJson),\n exportName: def.exportName || def.className || objectName,\n collectionExportName:\n def.collectionExportName ||\n `${def.className || objectName}Collection`,\n };\n }\n\n loadedManifest = true;\n break; // Use first found manifest for this package\n }\n }\n }\n } catch (error) {\n console.warn(\n `[smrt:consumer] Error loading manifest from ${packageName}:`,\n error,\n );\n }\n\n if (!loadedManifest) {\n unresolvedPackages.push(packageName);\n }\n }\n\n if (unresolvedPackages.length > 0) {\n const named = unresolvedPackages.join(', ');\n if (options.explicit) {\n throw new Error(\n `[smrt:consumer] No SMRT manifest could be resolved for ${named}. ` +\n 'Listed packages must publish a manifest through ' +\n 'package.json#exports (\"./manifest.json\") or at dist/manifest.json, ' +\n 'dist/manifest/static-manifest.js, or manifest.json. Build the ' +\n 'package, or remove it from smrtConsumer({ packages }).',\n );\n }\n // Discovery matches on dependency name, so a hit here is a guess: some\n // matched packages (UI/runtime helpers) legitimately have no objects.\n // Name them anyway — a missing manifest is otherwise invisible until the\n // objects turn up absent from routes and schema.\n console.warn(\n `[smrt:consumer] No SMRT manifest could be resolved for ${named}; ` +\n 'contributing 0 objects. If the package provides SMRT objects, ' +\n 'publish its manifest through package.json#exports (\"./manifest.json\").',\n );\n }\n\n return aggregatedManifest;\n}\n\n/**\n * Determine import path from package.json\n */\nfunction determineImportPath(packageJson: ConsumerPackageJson): string {\n const packageName = packageJson.name;\n\n if (!packageName) {\n throw new Error('Package name not found in package.json');\n }\n\n // Strategy 1: Check for specific exports\n if (packageJson.exports) {\n // Check for objects export\n if (packageJson.exports['./objects']) {\n return `${packageName}/objects`;\n }\n\n // Check for main export\n const mainExport = packageJson.exports['.'];\n if (mainExport) {\n // Handle conditional exports\n if (typeof mainExport === 'object' && mainExport !== null) {\n const conditional = mainExport as Record<string, unknown>;\n if (conditional.import) {\n return packageName;\n }\n if (conditional.default) {\n return packageName;\n }\n }\n return packageName;\n }\n }\n\n // Strategy 2: Check main field\n if (packageJson.main) {\n return packageName;\n }\n\n // Strategy 3: Fallback to package name\n return packageName;\n}\n\n/**\n * Save aggregated manifest to .smrt/manifest.json for CLI discovery.\n *\n * Merge-preserving: `smrtPlugin()` writes the project's own scanned objects\n * to the same file (`writeLocalManifest`, issue #963), and both writes happen\n * in parallel `buildStart` hooks — so a plain overwrite here would clobber\n * the local objects whenever this plugin's write lands last (issue #1760\n * review). Local field metadata would then silently vanish from CLI schema\n * commands and from server runtimes that seed `.smrt/manifest.json`, dropping\n * domain columns on write. This function therefore only ADDS/refreshes the\n * external-package entries it owns and preserves everything else already in\n * the file (including the top-level `packageName` the local write sets).\n */\nasync function saveAggregatedManifest(\n manifest: ConsumerManifest,\n projectRoot: string,\n resolveKnowledgeConfig?: SmrtPluginApi['resolveKnowledgeConfig'],\n agentSurface?: DomainKnowledgeAgentSurface,\n): Promise<void> {\n const smrtDir = path.join(projectRoot, '.smrt');\n const manifestPath = path.join(smrtDir, 'manifest.json');\n\n try {\n // Create .smrt directory if it doesn't exist\n if (!fs.existsSync(smrtDir)) {\n fs.mkdirSync(smrtDir, { recursive: true });\n }\n\n // Merge with whatever is on disk: existing entries (typically the local\n // project's objects written by smrtPlugin) are preserved; aggregated\n // external entries win for the qualified names this plugin owns.\n let merged: ConsumerManifest = manifest;\n if (fs.existsSync(manifestPath)) {\n try {\n const existing = JSON.parse(\n fs.readFileSync(manifestPath, 'utf-8'),\n ) as Partial<ConsumerManifest>;\n if (existing && typeof existing.objects === 'object') {\n merged = {\n ...existing,\n ...manifest,\n // The aggregated manifest carries no packageName; keep the local\n // project's (used as the manifest cache key at runtime).\n ...(existing.packageName\n ? { packageName: existing.packageName }\n : {}),\n objects: { ...existing.objects, ...manifest.objects },\n };\n }\n } catch {\n // Unreadable/corrupt existing file — fall back to a plain write.\n }\n }\n\n // smrtPlugin writes the local knowledge artifact before this consumer\n // plugin merges external package entries into the same manifest. Refresh\n // the artifact from the merged manifest so its source hash always names\n // the manifest that CLI discovery and server runtimes actually consume.\n // The consumer deliberately does not load the scanner. Only carry a\n // surface from the current producer scan: a prior artifact can describe\n // declarations that have since changed while retaining the same path.\n // Re-hashing that current path under a stale declaration would make an\n // incorrect agent contract look fresh.\n const knowledgePath = path.join(smrtDir, 'smrt-knowledge.json');\n const packageJsonPath = path.join(projectRoot, 'package.json');\n const packageJson = fs.existsSync(packageJsonPath)\n ? JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n : undefined;\n const knowledgeConfig = resolveKnowledgeConfig\n ? await resolveKnowledgeConfig(merged as unknown as SmartObjectManifest)\n : await resolveFileKnowledgeConfig(\n projectRoot,\n merged.packageName ?? packageJson?.name,\n );\n if (knowledgeConfig.enabled === false) {\n publishArtifactFiles([\n { path: manifestPath, content: JSON.stringify(merged, null, 2) },\n ]);\n return;\n }\n const knowledge = buildDomainKnowledgeManifest({\n manifest: merged as unknown as SmartObjectManifest,\n rootDir: projectRoot,\n packageJson,\n manifestPath,\n config: knowledgeConfig,\n agentSurface,\n });\n // Stage both artifacts before replacing either. Renames are individually\n // atomic; if a synchronous later rename fails, restore every earlier\n // replacement. A process crash between renames cannot be made pair-atomic\n // with ordinary filesystem operations, so the next generation remains the\n // freshness repair path for that distinct failure mode.\n publishArtifactFiles([\n { path: knowledgePath, content: JSON.stringify(knowledge, null, 2) },\n { path: manifestPath, content: JSON.stringify(merged, null, 2) },\n ]);\n\n console.log(\n `[smrt:consumer] Saved aggregated manifest to .smrt/manifest.json (${Object.keys(merged.objects).length} objects)`,\n );\n } catch (error) {\n throw new Error('[smrt:consumer] Failed to save aggregated manifest', {\n cause: error,\n });\n }\n}\n\n/**\n * Generate registration file for CLI class loading\n *\n * Creates .smrt/register.js with static imports and registrations\n * for all external SMRT objects discovered during build.\n */\nasync function generateRegistrationFile(\n manifest: ConsumerManifest,\n projectRoot: string,\n): Promise<void> {\n const smrtDir = path.join(projectRoot, '.smrt');\n const registerPath = path.join(smrtDir, 'register.js');\n\n // Bind every imported symbol to a generated local name. Aggregated manifests\n // may contain same-named exports from different packages (and may list a\n // collection both beside its object and as its own manifest entry), so using\n // provider export names as local bindings can produce invalid duplicate\n // imports in a production consumer bundle.\n const importBindings = new Map<string, string>();\n const importsByPath = new Map<string, Map<string, string>>();\n let nextImportBinding = 0;\n const getImportBinding = (importPath: string, exportName: string): string => {\n const key = `${importPath}\\0${exportName}`;\n const existing = importBindings.get(key);\n if (existing) return existing;\n const binding = `__smrt_consumer_${nextImportBinding++}`;\n importBindings.set(key, binding);\n const specifiers =\n importsByPath.get(importPath) ?? new Map<string, string>();\n specifiers.set(exportName, binding);\n importsByPath.set(importPath, specifiers);\n return binding;\n };\n\n const registrations: string[] = [];\n const registrationManifests: Record<string, ConsumerManifest> = {};\n let importedEntryCount = 0;\n let registeredObjectCount = 0;\n\n const manifestObjects = manifest.objects;\n const manifestObjectLookup = new Map<string, ConsumerObjectDefinition>();\n for (const [key, def] of Object.entries(manifestObjects)) {\n const candidate = def;\n const lookupKeys = [\n key,\n key.includes(':') ? key.split(':').pop() : undefined,\n candidate.qualifiedName,\n candidate.className,\n candidate.exportName,\n ];\n\n for (const lookupKey of lookupKeys) {\n if (lookupKey && !manifestObjectLookup.has(lookupKey)) {\n manifestObjectLookup.set(lookupKey, candidate);\n }\n }\n }\n\n const collectionClassMemo = new WeakMap<object, boolean>();\n\n const isCollectionClass = (\n def: ConsumerObjectDefinition | undefined,\n seen = new Set<string>(),\n ): boolean => {\n if (!def || typeof def !== 'object') {\n return false;\n }\n\n const cached = collectionClassMemo.get(def);\n if (cached !== undefined) {\n return cached;\n }\n\n if (\n def?.extends === 'SmrtCollection' ||\n def?.extendsTypeArg !== undefined\n ) {\n collectionClassMemo.set(def, true);\n return true;\n }\n\n const parentName = def?.extendsQualified || def?.extends;\n if (!parentName || seen.has(parentName)) {\n collectionClassMemo.set(def, false);\n return false;\n }\n seen.add(parentName);\n\n const parentDef = manifestObjectLookup.get(parentName);\n const isCollection = parentDef ? isCollectionClass(parentDef, seen) : false;\n collectionClassMemo.set(def, isCollection);\n\n return isCollection;\n };\n\n for (const [objectName, objectDef] of Object.entries(manifestObjects)) {\n const def = objectDef;\n\n // Skip local objects (they're imported from local entry point)\n if (!def.packageName || def.packageName === manifest.packageName) {\n continue;\n }\n\n const importPath = def.importPath || def.packageName;\n const exportName = def.exportName || def.className || objectName;\n const collectionExportName = def.collectionExportName;\n const hasCollection = def.hasCollection; // Check if collection class actually exists\n const tableName = def.collection || objectName.toLowerCase();\n\n const exportBinding = getImportBinding(importPath, exportName);\n const collectionBinding =\n hasCollection && collectionExportName\n ? getImportBinding(importPath, collectionExportName)\n : undefined;\n importedEntryCount++;\n\n if (isCollectionClass(def)) {\n continue;\n }\n\n const logicalName = def.className || exportName;\n registrationManifests[objectName] = {\n ...manifest,\n packageName: def.packageName,\n packageVersion: def.packageVersion || manifest.packageVersion,\n objects: { [objectName]: def },\n };\n\n // Import evaluation triggers the provider decorator first. The explicit\n // constructor/package/key tuple then promotes that exact constructor with\n // its isolated manifest, which is stable across Rollup name deconfliction.\n registrations.push(\n `if (${exportBinding}) ObjectRegistry.register(${exportBinding}, { name: ${JSON.stringify(logicalName)}, packageName: ${JSON.stringify(def.packageName)}, _manifest: smrtRegistrationManifests[${JSON.stringify(objectName)}], _manifestKey: ${JSON.stringify(objectName)} });`,\n );\n\n // Only register collection if it exists\n if (collectionBinding) {\n registrations.push(\n `if (${collectionBinding}) ObjectRegistry.registerCollection('${tableName}', ${collectionBinding});`,\n );\n }\n\n registeredObjectCount++;\n }\n\n // Skip generation if no external entries\n if (importedEntryCount === 0) {\n console.log('[smrt:consumer] No external entries - skipping register.js');\n return;\n }\n\n const registeredObjectLabel =\n registeredObjectCount === 1 ? 'object' : 'objects';\n const sortedImports = Array.from(importsByPath.entries()).sort(\n ([left], [right]) => left.localeCompare(right),\n );\n const imports = sortedImports.map(\n ([importPath], index) =>\n `import * as __smrt_provider_${index} from '${importPath}';`,\n );\n const importDeclarations = sortedImports.flatMap(([, specifiers], index) =>\n Array.from(specifiers.entries())\n .sort(([left], [right]) => left.localeCompare(right))\n .map(\n ([exportName, binding]) =>\n `const ${binding} = getSmrtExport(__smrt_provider_${index}, ${JSON.stringify(exportName)});`,\n ),\n );\n const registrationManifestLiteral = JSON.stringify(\n JSON.stringify(registrationManifests),\n );\n\n // Generate file content\n const content = `/**\n * Auto-generated by @happyvertical/smrt-core/consumer-plugin\n * DO NOT EDIT - This file is regenerated on every build\n *\n * Registers SMRT objects from external packages for CLI discovery.\n * Generated at: ${new Date().toISOString()}\n */\n\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\n${imports.join('\\n')}\n\n/**\n * @param {Record<string, unknown>} provider\n * @param {string} exportName\n * @returns {any}\n */\nconst getSmrtExport = (provider, exportName) =>\n typeof provider[exportName] === 'function' ? provider[exportName] : undefined;\n${importDeclarations.join('\\n')}\n\nconst smrtRegistrationManifests = JSON.parse(${registrationManifestLiteral});\n\n// Register all objects (executed during module evaluation)\n${registrations.join('\\n')}\n\nexport function registerAll() {\n // Objects are already registered during module evaluation\n console.log('[smrt:register] Registered ${registeredObjectCount} external ${registeredObjectLabel}');\n}\n`;\n\n // Create .smrt directory if needed\n if (!fs.existsSync(smrtDir)) {\n fs.mkdirSync(smrtDir, { recursive: true });\n }\n\n // Write registration file\n fs.writeFileSync(registerPath, content, 'utf-8');\n\n console.log(\n `[smrt:consumer] Generated .smrt/register.js with ${importedEntryCount} external entries (${registeredObjectCount} registered ${registeredObjectLabel})`,\n );\n}\n\n/**\n * Generate project-specific types\n */\nasync function generateProjectTypes(\n typeManifest: ConsumerManifest,\n typesDir: string,\n projectRoot: string,\n): Promise<void> {\n if (!typeManifest || Object.keys(typeManifest.objects).length === 0) {\n console.log(\n '[smrt:consumer] No SMRT objects found, skipping type generation',\n );\n return;\n }\n\n await generateDeclarations({\n // The aggregated manifest is a runtime SMRT manifest assembled from external\n // package manifests; it is intentionally typed loosely at the JSON boundary,\n // so narrow it to the declaration generator's strict manifest shape here.\n manifest: typeManifest as unknown as SmartObjectManifest,\n outDir: typesDir,\n projectRoot,\n includeVirtualModules: true,\n includeObjectTypes: true,\n });\n\n console.log(\n `[smrt:consumer] Generated types for ${Object.keys(typeManifest.objects).length} objects`,\n );\n}\n\n/**\n * Get type file name for virtual module\n */\nfunction getTypeFileName(virtualModule: string): string {\n const moduleMap: Record<string, string> = {\n '@smrt/routes': 'smrt-routes.d.ts',\n '@smrt/client': 'smrt-client.d.ts',\n '@smrt/mcp': 'smrt-mcp.d.ts',\n '@smrt/types': 'smrt-types.d.ts',\n '@smrt/manifest': 'smrt-manifest.d.ts',\n '@smrt/web': 'smrt-web.d.ts',\n };\n return moduleMap[virtualModule] || 'smrt-unknown.d.ts';\n}\n\n/**\n * Fallback modules for when types aren't available\n */\nfunction generateFallbackRoutesModule(): string {\n return `\n// Fallback routes module\nexport function setupRoutes(app) {\n console.warn('[smrt:consumer] No routes available - SMRT packages may not be properly configured');\n}\nexport default setupRoutes;\n`;\n}\n\nfunction generateFallbackClientModule(\n manifest: ConsumerManifest,\n options: { kebabRoutes?: boolean } = {},\n): string {\n const objects = Object.entries(manifest?.objects || {});\n if (objects.length === 0) {\n return `\n// Fallback client module\nexport function createClient(basePath = '/api/v1') {\n console.warn('[smrt:consumer] No API client available - SMRT packages may not be properly configured');\n return {};\n}\nexport default createClient;\n`;\n }\n\n return generateClientModule(manifest as unknown as SmartObjectManifest, {\n kebabRoutes: options.kebabRoutes,\n });\n}\n\nfunction generateFallbackMcpModule(): string {\n return `\n// Fallback MCP module\nexport const tools = [];\nexport function createMCPServer() {\n console.warn('[smrt:consumer] No MCP tools available - SMRT packages may not be properly configured');\n return { name: 'smrt-consumer', version: '1.0.0', tools: [] };\n}\nexport default createMCPServer;\n`;\n}\n\nfunction generateFallbackTypesModule(manifest: ConsumerManifest): string {\n const objects = Object.entries(manifest?.objects || {});\n if (objects.length === 0) {\n return `// No types available`;\n }\n\n // Generate basic interfaces\n const interfaces = objects.map(([_name, obj]) => {\n return `export interface ${obj.className}Data {\n id?: string;\n created_at?: string;\n updated_at?: string;\n [key: string]: any;\n}`;\n });\n\n return interfaces.join('\\n\\n');\n}\n\nfunction generateFallbackManifestModule(manifest: ConsumerManifest): string {\n return `\n// Auto-generated manifest from SMRT consumer\nexport const manifest = ${JSON.stringify(manifest, null, 2)};\nexport default manifest;\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2KA,IAAM,kBAAkB;CACtB,gBAAgB;CAChB,gBAAgB;CAChB,aAAa;CACb,eAAe;CACf,kBAAkB;CAClB,aAAa;AACf;AAEA,IAAM,6CAA6C;AACnD,IAAM,qCAAqC;AAO3C,SAAS,oCAAoC,aAA6B;CACxE,OAAO,KAAK,KAAK,aAAa,SAAS,kCAAkC;AAC3E;;AAGA,SAAS,2BACP,aACA,WACQ;CACR,MAAM,OAAO,KAAK,QAAQ,WAAW;CACrC,MAAM,WAAW,KAAK,SAAS,MAAM,KAAK,QAAQ,MAAM,SAAS,CAAC;CAClE,IACE,CAAC,YACD,aAAa,QACb,SAAS,WAAW,KAAK,KAAK,KAAK,KACnC,KAAK,WAAW,QAAQ,GAExB,MAAM,IAAI,MACR,yFAAyF,KAAK,UAAU,SAAS,EAAE,EACrH;CAEF,OAAO,SAAS,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK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cesContent":["/**\n * Vite plugin for consuming SMRT packages\n * Solves virtual module resolution in downstream projects\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { DomainKnowledgeAgentSurface } from '@happyvertical/smrt-types';\nimport type { ConfigEnv, Plugin } from 'vite';\nimport {\n loadVerifiedSmrtGenerationSnapshot,\n type SmrtGenerationSnapshotOptions,\n} from '../generation-snapshot.js';\nimport { buildDomainKnowledgeManifest } from '../knowledge.js';\nimport { resolveFileKnowledgeConfig } from '../knowledge-config.js';\nimport { manifestExportCandidates } from '../manifest/package-manifest-exports.js';\nimport { generateDeclarations } from '../prebuild/index.js';\nimport type {\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types.js';\nimport { MANIFEST_TIMESTAMP } from '../scanner/types.js';\nimport { generateClientModule } from '../vite-plugin/generated-client.js';\nimport type { SmrtPluginApi } from '../vite-plugin/index.js';\nimport {\n clearGeneratedSvelteKitRouteFiles,\n reconcileSvelteKitRouteGitignore,\n type SvelteKitOptions,\n} from '../vite-plugin/sveltekit-generator.js';\nimport { canonicalSvelteKitPath } from '../vite-plugin/sveltekit-path.js';\nimport {\n activeProducerKnowledgeRoutePaths,\n activeSvelteKitRouteParticipants,\n assertNoSvelteKitRouteRootSymlinkConflict,\n assertSvelteKitRouteCoordinationComplete,\n contributeSvelteKitRoutes,\n expectedSvelteKitRouteOwners,\n markSvelteKitRouteParticipant,\n producerKnowledgeRoutePaths,\n revokeSvelteKitRoutes,\n} from '../vite-plugin/sveltekit-route-coordinator.js';\nimport {\n generateWebModule,\n isCollectionManifestClass,\n resolveCollectionItemObject,\n} from '../vite-plugin/web-collections.js';\nimport { publishArtifactFiles } from './artifact-publication.js';\n\nexport {\n loadVerifiedSmrtGenerationSnapshot,\n type SerializeSmrtGenerationSnapshotOptions,\n type SmrtGenerationSnapshotArtifact,\n type SmrtGenerationSnapshotOptions,\n type SmrtGenerationSnapshotView,\n serializeSmrtGenerationSnapshot,\n sha256SmrtGenerationSnapshot,\n} from '../generation-snapshot.js';\n\n/**\n * Loosely-typed view of an object definition as carried by an external\n * package's static manifest. The static manifests are read from JSON at the\n * package boundary, so only the fields this plugin consumes are typed; the\n * index signature preserves any additional fields (e.g. for spreads). This is\n * a structural superset of a manifest `SmartObjectDefinition` plus the\n * consumer-only `hasCollection` marker.\n */\ninterface ConsumerObjectDefinition {\n className?: string;\n packageName?: string;\n packageVersion?: string;\n qualifiedName?: string;\n importPath?: string;\n exportName?: string;\n collectionExportName?: string;\n hasCollection?: boolean;\n collection?: string;\n extends?: string;\n extendsQualified?: string;\n extendsTypeArg?: string;\n [key: string]: unknown;\n}\n\n/**\n * Aggregated manifest assembled by the consumer plugin from one or more\n * external package manifests. Loosely typed because the inputs originate from\n * JSON read at the package boundary.\n */\ninterface ConsumerManifest {\n version: string;\n timestamp: number;\n packageName?: string;\n packageVersion?: string;\n smrtDependencies?: string[];\n objects: Record<string, ConsumerObjectDefinition>;\n}\n\n/**\n * Minimal structural shape of a parsed `package.json` consumed here (name,\n * version, and the export map used to derive import paths). The index\n * signature keeps the remaining fields accessible.\n */\ninterface ConsumerPackageJson {\n name?: string;\n version?: string;\n main?: string;\n exports?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\n/**\n * SvelteKit route-hosting options for dependency models. Unlike `packages`,\n * `objects` is an HTTP exposure boundary: every entry must be an exact,\n * provider-qualified manifest key (for example, `@acme/widgets:Widget`).\n */\nexport interface SmrtConsumerSvelteKitOptions\n extends Partial<\n Pick<\n SvelteKitOptions,\n | 'routesDir'\n | 'configPath'\n | 'configFileName'\n | 'kebabRoutes'\n | 'changesRoute'\n | 'eventsRoute'\n | 'resourcesRoute'\n >\n > {\n objects: readonly string[];\n}\n\nexport interface SmrtConsumerOptions {\n /** SMRT packages to scan (e.g., ['@my-org/products', '@my-org/content']) */\n packages?: string[];\n /** Generate TypeScript declarations */\n generateTypes?: boolean;\n /** Output directory for generated types */\n typesDir?: string;\n /** Project root path (defaults to the current working directory) */\n projectRoot?: string;\n /**\n * Reuse an immutable, verified aggregated manifest instead of discovering\n * packages or writing `.smrt/manifest.json`. Registration and generated\n * types still consume the verified manifest.\n */\n generationSnapshot?: SmrtGenerationSnapshotOptions;\n /**\n * Consumer SvelteKit integration. `true` retains the historical compatibility\n * mode and does not generate dependency routes. Route hosting requires an\n * explicit, provider-qualified object allowlist.\n */\n svelteKit?: boolean | SmrtConsumerSvelteKitOptions;\n /**\n * Apply kebab-case to generated custom-method URL segments. This must match\n * the producer plugin's `svelteKit.kebabRoutes` setting. When explicit\n * consumer SvelteKit hosting is configured, its `kebabRoutes` value takes\n * precedence, including an explicit `false`.\n */\n kebabRoutes?: boolean;\n /** Use static types only (for federation builds) */\n staticTypes?: boolean;\n /** Disable file scanning */\n disableScanning?: boolean;\n}\n\n// Distinct resolved ids per plugin (#1795). smrtPlugin resolves\n// `@happyvertical/smrt-virt-*` to `\\0smrt:*`; if this consumer plugin also\n// resolved its `@smrt/*` specifiers to `\\0smrt:*` the two virtual modules would\n// share a rollup id, and in standalone/federation builds the consumer's\n// fallback `load` would non-deterministically win and shadow smrtPlugin's real\n// module. Namespacing the consumer ids (`\\0smrt-consumer:*`) keeps them\n// separate so each plugin only ever loads its own module.\nconst VIRTUAL_MODULES = {\n '@smrt/routes': 'smrt-consumer:routes',\n '@smrt/client': 'smrt-consumer:client',\n '@smrt/mcp': 'smrt-consumer:mcp',\n '@smrt/types': 'smrt-consumer:types',\n '@smrt/manifest': 'smrt-consumer:manifest',\n '@smrt/web': 'smrt-consumer:web',\n};\n\nconst CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION = 1;\nconst CONSUMER_SVELTEKIT_ROUTES_ARTIFACT = 'consumer-sveltekit-routes.json';\n\ninterface ConsumerSvelteKitRoutesArtifact {\n version: number;\n routesDir: string[];\n}\n\nfunction consumerSvelteKitRoutesArtifactPath(projectRoot: string): string {\n return path.join(projectRoot, '.smrt', CONSUMER_SVELTEKIT_ROUTES_ARTIFACT);\n}\n\n/** Persist only project-relative consumer route roots, never an output file list. */\nfunction canonicalConsumerRouteRoot(\n projectRoot: string,\n routesDir: string,\n): string {\n const root = path.resolve(projectRoot);\n const relative = path.relative(root, path.resolve(root, routesDir));\n if (\n !relative ||\n relative === '..' ||\n relative.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relative)\n ) {\n throw new Error(\n `[smrt:consumer] svelteKit.routesDir must be a project-relative subdirectory (received ${JSON.stringify(routesDir)})`,\n );\n }\n return relative.split(path.sep).join('/');\n}\n\nfunction loadConsumerSvelteKitRouteRoots(projectRoot: string): string[] {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n if (!fs.existsSync(artifactPath)) return [];\n let parsed: ConsumerSvelteKitRoutesArtifact;\n try {\n parsed = JSON.parse(fs.readFileSync(artifactPath, 'utf-8'));\n } catch {\n throw new Error(\n `[smrt:consumer] Cannot read ${CONSUMER_SVELTEKIT_ROUTES_ARTIFACT}; refusing to leave hosted routes unreconciled`,\n );\n }\n if (\n parsed?.version !== CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION ||\n !Array.isArray(parsed.routesDir) ||\n parsed.routesDir.some((routesDir) => typeof routesDir !== 'string')\n ) {\n throw new Error(\n `[smrt:consumer] Invalid ${CONSUMER_SVELTEKIT_ROUTES_ARTIFACT}; refusing to leave hosted routes unreconciled`,\n );\n }\n return [...new Set(parsed.routesDir)].map((routesDir) =>\n canonicalConsumerRouteRoot(projectRoot, routesDir),\n );\n}\n\nfunction publishConsumerSvelteKitRouteRoots(\n projectRoot: string,\n routesDir: string[],\n): void {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n fs.mkdirSync(path.dirname(artifactPath), { recursive: true });\n publishArtifactFiles([\n {\n path: artifactPath,\n content: JSON.stringify(\n {\n version: CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION,\n routesDir: [...new Set(routesDir)].sort(),\n } satisfies ConsumerSvelteKitRoutesArtifact,\n null,\n 2,\n ),\n },\n ]);\n}\n\nfunction removeConsumerSvelteKitRouteRoots(projectRoot: string): void {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n if (fs.existsSync(artifactPath)) fs.unlinkSync(artifactPath);\n}\n\n/**\n * A hosting-to-hosting move can replace one configured root with another in a\n * fresh lifecycle. Validate every durable former root before the new target\n * journals or clears anything, otherwise a rejected move could alter the\n * prior generated surface before reconciliation notices the conflict.\n */\nasync function assertConsumerSvelteKitFormerRouteRootsAreSafe(\n userConfig: unknown,\n projectRoot: string,\n routesDir: readonly string[],\n env?: ConfigEnv,\n): Promise<void> {\n if (routesDir.length === 0) return;\n const activeParticipants = await activeSvelteKitRouteParticipants(\n userConfig,\n projectRoot,\n env,\n );\n const activeRoots = activeParticipants.map(\n (participant) => participant.routesDir,\n );\n for (const priorRoutesDir of routesDir) {\n assertNoSvelteKitRouteRootSymlinkConflict(\n canonicalSvelteKitPath(path.resolve(projectRoot, priorRoutesDir)),\n activeRoots,\n );\n }\n}\n\nasync function reconcileConsumerSvelteKitRouteRoots(\n lifecycle: object,\n userConfig: unknown,\n projectRoot: string,\n routesDir: string[],\n afterReconciled: () => void,\n env?: ConfigEnv,\n): Promise<void> {\n const remaining = new Set(routesDir);\n const reconcileOne = (routesDir: string) => {\n remaining.delete(routesDir);\n if (remaining.size === 0) afterReconciled();\n };\n\n if (remaining.size === 0) {\n afterReconciled();\n return;\n }\n\n for (const routesDir of [...remaining]) {\n const routeRoot = canonicalSvelteKitPath(\n path.resolve(projectRoot, routesDir),\n );\n const activeParticipants = await activeSvelteKitRouteParticipants(\n userConfig,\n projectRoot,\n env,\n );\n // The durable consumer inventory names roots, not individual handlers.\n // Check before every reconciliation branch, including an active parent\n // consumer that would otherwise compact a nested former root without a\n // sweep. A child symlink into a foreign active root makes that ownership\n // ambiguous, so retaining the inventory makes retry safe.\n assertNoSvelteKitRouteRootSymlinkConflict(\n routeRoot,\n activeParticipants.map((participant) => participant.routesDir),\n );\n const containingConsumer = activeParticipants.find(\n (participant) =>\n participant.owner === 'consumer' &&\n (routeRoot === participant.routesDir ||\n routeRoot.startsWith(`${participant.routesDir}${path.sep}`)),\n );\n // A current parent consumer root has already swept and regenerated this\n // former child root. Sweeping it again would remove the newly selected\n // handler before SvelteKit inventories it.\n if (containingConsumer) {\n reconcileOne(routesDir);\n continue;\n }\n const containingProducer = activeParticipants.find(\n (participant) =>\n participant.owner === 'producer' &&\n (routeRoot === participant.routesDir ||\n routeRoot.startsWith(`${participant.routesDir}${path.sep}`)),\n );\n if (containingProducer) {\n await revokeSvelteKitRoutes(\n lifecycle,\n await expectedSvelteKitRouteOwners(\n userConfig,\n containingProducer.projectRoot,\n containingProducer.routesDir,\n env,\n ),\n containingProducer.projectRoot,\n containingProducer.routesDir,\n () => reconcileOne(routesDir),\n );\n continue;\n }\n const owners = await expectedSvelteKitRouteOwners(\n userConfig,\n projectRoot,\n routesDir,\n env,\n );\n if (owners.includes('producer')) {\n await revokeSvelteKitRoutes(\n lifecycle,\n owners,\n projectRoot,\n routesDir,\n () => reconcileOne(routesDir),\n );\n continue;\n }\n clearGeneratedSvelteKitRouteFiles(\n routeRoot,\n producerKnowledgeRoutePaths(lifecycle),\n new Set(\n activeParticipants\n .map((participant) => participant.routesDir)\n .filter((activeRoot) => activeRoot !== routeRoot),\n ),\n );\n reconcileSvelteKitRouteGitignore(projectRoot, routesDir);\n reconcileOne(routesDir);\n }\n}\n\nfunction consumerRouteOptions(\n value: SmrtConsumerOptions['svelteKit'],\n): SmrtConsumerSvelteKitOptions | undefined {\n if (!value || value === true) return undefined;\n if (!Array.isArray(value.objects) || value.objects.length === 0) {\n throw new Error(\n '[smrt:consumer] svelteKit.objects must list at least one provider-qualified object reference',\n );\n }\n for (const objectRef of value.objects) {\n if (typeof objectRef !== 'string' || !objectRef.includes(':')) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects entries must be provider-qualified (received ${JSON.stringify(objectRef)})`,\n );\n }\n }\n return value;\n}\n\nfunction consumerUtilityOption<T extends { enabled?: boolean }>(\n value: T | undefined,\n): T | { enabled: false } {\n return value?.enabled === true ? value : { enabled: false };\n}\n\nfunction consumerObjectRef(\n manifestKey: string,\n objectDef: ConsumerObjectDefinition,\n): string | undefined {\n if (manifestKey.includes(':')) return manifestKey;\n if (objectDef.qualifiedName?.includes(':')) return objectDef.qualifiedName;\n if (objectDef.packageName && objectDef.className) {\n return `${objectDef.packageName}:${objectDef.className}`;\n }\n return undefined;\n}\n\n/**\n * Select exactly the dependency objects that a consumer explicitly hosts.\n * Validation completes before the generator clears its managed files, so an\n * invalid deployment cannot erase a previously generated route surface.\n */\nfunction selectConsumerRouteManifest(\n manifest: ConsumerManifest,\n options: SmrtConsumerSvelteKitOptions,\n): SmartObjectManifest {\n const entriesByRef = new Map<string, [string, ConsumerObjectDefinition]>();\n for (const [manifestKey, objectDef] of Object.entries(manifest.objects)) {\n const objectRef = consumerObjectRef(manifestKey, objectDef);\n if (objectRef) entriesByRef.set(objectRef, [manifestKey, objectDef]);\n }\n\n const selected = new Set<string>();\n const objects: Record<string, ConsumerObjectDefinition> = {};\n for (const objectRef of options.objects) {\n const entry = entriesByRef.get(objectRef);\n if (!entry) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects references unknown dependency object ${JSON.stringify(objectRef)}`,\n );\n }\n if (selected.has(objectRef)) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects contains duplicate object ${JSON.stringify(objectRef)}`,\n );\n }\n selected.add(objectRef);\n const [, objectDef] = entry;\n objects[objectRef] = { ...objectDef, qualifiedName: objectRef };\n }\n\n const sourceManifest = manifest as unknown as SmartObjectManifest;\n // Use the generator's canonical ancestry resolver so a collection subclass\n // inherits the selected item's identity through any number of ancestors.\n for (const [manifestKey, objectDef] of Object.entries(manifest.objects)) {\n const candidate = objectDef as unknown as SmartObjectDefinition;\n if (!isCollectionManifestClass(sourceManifest, candidate)) continue;\n const item = resolveCollectionItemObject(sourceManifest, candidate);\n const itemEntry = item\n ? Object.entries(manifest.objects).find(\n ([, value]) => (value as unknown) === item,\n )\n : undefined;\n const itemRef = itemEntry\n ? consumerObjectRef(itemEntry[0], itemEntry[1])\n : undefined;\n if (!itemRef || !selected.has(itemRef)) continue;\n const collectionRef = consumerObjectRef(manifestKey, objectDef);\n if (collectionRef) {\n objects[collectionRef] = { ...objectDef, qualifiedName: collectionRef };\n }\n }\n\n return {\n ...manifest,\n // The generated route config imports this full registration entry point so\n // SSR retains every consumer provider, while only `objects` reach routing.\n // `smrtDependencies` is optional in verified snapshots, so derive this\n // generator signal from the immutable full manifest rather than treating\n // absent metadata as an empty provider inventory.\n smrtDependencies: [\n ...new Set([\n ...(manifest.smrtDependencies ?? []),\n ...Object.values(manifest.objects)\n .map((objectDef) => objectDef.packageName)\n .filter(\n (packageName): packageName is string =>\n typeof packageName === 'string' &&\n packageName !== manifest.packageName,\n ),\n ]),\n ].sort(),\n objects,\n } as unknown as SmartObjectManifest;\n}\n\n/**\n * Consumer plugin for projects that use SMRT packages\n */\nexport function smrtConsumer(options: SmrtConsumerOptions = {}): Plugin {\n const {\n packages = [],\n generateTypes = true,\n typesDir = 'src/types/smrt-generated',\n projectRoot = process.cwd(),\n generationSnapshot,\n disableScanning = false,\n kebabRoutes = false,\n } = options;\n const consumerSvelteKit = consumerRouteOptions(options.svelteKit);\n // Hosted routes, the generated client, and web tool definitions must expose\n // the same custom-action URLs. Nested consumer SvelteKit hosting owns this\n // policy when present, including an explicit false override.\n const effectiveKebabRoutes = consumerSvelteKit?.kebabRoutes ?? kebabRoutes;\n\n let smrtPackages: string[] = [];\n let typeManifest: ConsumerManifest | null = null;\n let typesGenerated = false;\n let producerApi: SmrtPluginApi | undefined;\n let routeLifecycleConfig: object | undefined;\n\n function loadGenerationSnapshot(): ConsumerManifest {\n if (!generationSnapshot) {\n throw new Error('[smrt:consumer] Generation snapshot is not configured');\n }\n return loadVerifiedSmrtGenerationSnapshot<ConsumerManifest>(\n generationSnapshot,\n projectRoot,\n 'dependencies',\n );\n }\n\n /**\n * Resolve the packages to aggregate, and whether that list was asserted by\n * the consumer's config. An explicit list fails closed when a package\n * yields no manifest; a heuristically discovered one only warns.\n */\n async function resolveConsumerPackages(): Promise<{\n names: string[];\n explicit: boolean;\n }> {\n if (packages.length === 0 && !disableScanning) {\n return {\n names: await discoverSmrtPackages(projectRoot),\n explicit: false,\n };\n }\n return { names: packages, explicit: packages.length > 0 };\n }\n\n async function generateConfigTypes(\n manifest?: ConsumerManifest,\n ): Promise<void> {\n if (!generateTypes || typesGenerated) return;\n\n if (manifest) {\n typeManifest = manifest;\n } else if (generationSnapshot) {\n typeManifest = loadGenerationSnapshot();\n } else {\n const resolved = await resolveConsumerPackages();\n typeManifest = await aggregateTypeManifests(resolved.names, projectRoot, {\n explicit: resolved.explicit,\n });\n }\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n\n const plugin: Plugin = {\n name: 'smrt-consumer',\n\n // SvelteKit inventories routes in its config hook. Run before it so a\n // clean consumer build sees the explicit dependency routes on its first\n // invocation, even when sveltekit() appears first in vite.config.\n enforce: 'pre',\n\n config: {\n order: 'pre',\n async handler(userConfig, env) {\n const routeLifecycle = env ?? userConfig;\n routeLifecycleConfig = routeLifecycle;\n const previousConsumerRouteRoots =\n loadConsumerSvelteKitRouteRoots(projectRoot);\n if (consumerSvelteKit) {\n await assertConsumerSvelteKitFormerRouteRootsAreSafe(\n userConfig,\n projectRoot,\n previousConsumerRouteRoots,\n env,\n );\n const routePackages = await resolveConsumerPackages();\n const routeManifest = generationSnapshot\n ? loadGenerationSnapshot()\n : await aggregateTypeManifests(routePackages.names, projectRoot, {\n explicit: routePackages.explicit,\n });\n const hostedManifest = selectConsumerRouteManifest(\n routeManifest,\n consumerSvelteKit,\n );\n const routesDir = canonicalConsumerRouteRoot(\n projectRoot,\n consumerSvelteKit.routesDir ?? 'src/routes/api',\n );\n const reservedRoutePaths = await activeProducerKnowledgeRoutePaths(\n userConfig,\n projectRoot,\n env,\n );\n const routeOptions = {\n enabled: true,\n routesDir,\n objectsDir: 'src/lib/objects',\n configPath: consumerSvelteKit.configPath ?? 'src/lib/server',\n configFileName: consumerSvelteKit.configFileName ?? 'smrt.ts',\n kebabRoutes: effectiveKebabRoutes,\n // These span a model set rather than one selected object, so new\n // consumer hosting starts fail-closed. Callers can opt in with the\n // generator's established option shapes.\n changesRoute: consumerUtilityOption(consumerSvelteKit.changesRoute),\n eventsRoute: consumerUtilityOption(consumerSvelteKit.eventsRoute),\n resourcesRoute: consumerUtilityOption(\n consumerSvelteKit.resourcesRoute,\n ),\n rejectRouteCollisions: true,\n };\n let ownershipJournaled = false;\n let reconciliationScheduled = false;\n await contributeSvelteKitRoutes(\n routeLifecycle,\n await expectedSvelteKitRouteOwners(\n userConfig,\n projectRoot,\n routeOptions.routesDir,\n env,\n ),\n projectRoot,\n {\n owner: 'consumer',\n routeManifest: hostedManifest,\n semanticManifest: routeManifest as unknown as SmartObjectManifest,\n options: routeOptions,\n reservedRoutePaths,\n beforeCleanup: async () => {\n // Route selection and collision checks have succeeded, but no\n // generated output has changed. SvelteKit type checking still\n // runs after this config hook and needs these declarations.\n await generateConfigTypes(routeManifest);\n // The generated TS registration imports this runtime module.\n // SvelteKit sync must resolve it before Vite buildStart runs.\n await generateRegistrationFile(routeManifest, projectRoot);\n if (ownershipJournaled) return;\n ownershipJournaled = true;\n // Preflight has succeeded but no generated output has changed.\n // Keep both roots until old-root reconciliation commits.\n publishConsumerSvelteKitRouteRoots(projectRoot, [\n ...previousConsumerRouteRoots,\n routesDir,\n ]);\n },\n afterGenerate: async () => {\n if (reconciliationScheduled) return;\n reconciliationScheduled = true;\n const priorRoots = previousConsumerRouteRoots.filter(\n (previousRoot) => previousRoot !== routesDir,\n );\n await reconcileConsumerSvelteKitRouteRoots(\n routeLifecycle,\n userConfig,\n projectRoot,\n priorRoots,\n () =>\n publishConsumerSvelteKitRouteRoots(projectRoot, [\n routesDir,\n ]),\n env,\n );\n },\n },\n );\n } else {\n // Legacy/non-hosting SvelteKit consumers have no route preflight,\n // but still need physical virtual-module declarations before their\n // SvelteKit typecheck reaches Vite's later buildStart lifecycle.\n await generateConfigTypes();\n if (options.svelteKit && typeManifest) {\n await generateRegistrationFile(typeManifest, projectRoot);\n }\n if (previousConsumerRouteRoots.length > 0) {\n await reconcileConsumerSvelteKitRouteRoots(\n routeLifecycle,\n userConfig,\n projectRoot,\n previousConsumerRouteRoots,\n () => removeConsumerSvelteKitRouteRoots(projectRoot),\n env,\n );\n }\n }\n return {\n build: {\n rollupOptions: {\n // Runtime registration evaluates provider entry points so their\n // exact constructors can be registered. Leave optional native\n // provider binaries to Node instead of parsing them as JavaScript.\n external: [/\\.node$/],\n },\n },\n };\n },\n },\n\n configResolved(resolvedConfig) {\n if (consumerSvelteKit && routeLifecycleConfig) {\n assertSvelteKitRouteCoordinationComplete(routeLifecycleConfig);\n }\n producerApi = (resolvedConfig.plugins ?? []).find(\n (plugin) => plugin?.name === 'smrt-auto-service',\n )?.api as SmrtPluginApi | undefined;\n },\n\n async buildStart() {\n console.log('[smrt:consumer] Initializing SMRT consumer plugin');\n\n if (generationSnapshot) {\n typeManifest = loadGenerationSnapshot();\n console.log(\n `[smrt:consumer] Reusing verified generation snapshot (${generationSnapshot.provenance})`,\n );\n await generateRegistrationFile(typeManifest, projectRoot);\n if (generateTypes && !typesGenerated) {\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n return;\n }\n\n // Discover SMRT packages if not explicitly specified\n const resolvedPackages = await resolveConsumerPackages();\n smrtPackages = resolvedPackages.names;\n\n if (smrtPackages.length > 0) {\n console.log(\n `[smrt:consumer] Found SMRT packages: ${smrtPackages.join(', ')}`,\n );\n\n // Aggregate type manifests from discovered packages\n typeManifest = await aggregateTypeManifests(smrtPackages, projectRoot, {\n explicit: resolvedPackages.explicit,\n });\n // Wait before reading .smrt/manifest.json: a producer's parallel\n // buildStart writes its current local manifest after scanning. Reading\n // first could merge an older local manifest with a newer surface.\n const agentSurface = producerApi\n ? await producerApi.resolveKnowledgeAgentSurface()\n : undefined;\n\n // Save aggregated manifest for CLI discovery\n await saveAggregatedManifest(\n typeManifest,\n projectRoot,\n producerApi?.resolveKnowledgeConfig,\n agentSurface,\n );\n\n // Generate registration file for CLI class loading\n await generateRegistrationFile(typeManifest, projectRoot);\n\n // Generate types if requested\n if (generateTypes && !typesGenerated) {\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n } else {\n console.log('[smrt:consumer] No SMRT packages found');\n typeManifest = {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n };\n }\n },\n\n resolveId(id, _importer) {\n // Resolve virtual modules to generated type declarations\n if (id in VIRTUAL_MODULES) {\n // Generated declarations are ambient TypeScript declarations, not\n // executable JavaScript. Vite must always load the consumer runtime\n // module after default type generation writes them.\n if (id !== '@smrt/types') {\n return `\\0${VIRTUAL_MODULES[id as keyof typeof VIRTUAL_MODULES]}`;\n }\n\n const typeFileName = getTypeFileName(id);\n const typePath = path.join(projectRoot, typesDir, typeFileName);\n\n // If types file exists, resolve to it\n if (fs.existsSync(typePath)) {\n return typePath;\n }\n\n // Otherwise use virtual module ID for runtime resolution\n return `\\0${VIRTUAL_MODULES[id as keyof typeof VIRTUAL_MODULES]}`;\n }\n return null;\n },\n\n async load(id) {\n // Handle virtual modules if types aren't available\n const cleanId = id.startsWith('\\0') ? id.slice(1) : id;\n\n if (!typeManifest) {\n typeManifest = generationSnapshot\n ? loadGenerationSnapshot()\n : {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n };\n }\n\n switch (cleanId) {\n case 'smrt-consumer:routes':\n return generateFallbackRoutesModule();\n\n case 'smrt-consumer:client':\n return generateFallbackClientModule(typeManifest, {\n kebabRoutes: effectiveKebabRoutes,\n });\n\n case 'smrt-consumer:mcp':\n return generateFallbackMcpModule();\n\n case 'smrt-consumer:types':\n return generateFallbackTypesModule(typeManifest);\n\n case 'smrt-consumer:manifest':\n return generateFallbackManifestModule(typeManifest);\n\n case 'smrt-consumer:web':\n return generateWebModule(\n typeManifest as unknown as SmartObjectManifest,\n {\n kebabRoutes: effectiveKebabRoutes,\n },\n );\n\n default:\n return null;\n }\n },\n };\n markSvelteKitRouteParticipant(\n plugin,\n 'consumer',\n Boolean(consumerSvelteKit),\n consumerSvelteKit?.routesDir ?? 'src/routes/api',\n undefined,\n () => projectRoot,\n );\n return plugin;\n}\n\n/**\n * Discover SMRT packages from a consumer app's dependencies.\n *\n * Intentional split (#1579): this **consumer-plugin** path is async and\n * resolves SMRT packages from the downstream app's `package.json` dependency\n * names (`@have/`/`smrt` heuristic + `hasSmrtManifest` probe) inside the Vite\n * consumer plugin. It is deliberately separate from the build-time\n * `discoverSmrtPackages()` in `src/manifest/discover-smrt-packages.ts` — a\n * synchronous, lockfile-cached `node_modules` manifest scan used for manifest\n * generation. Different inputs, contexts, and lifecycles, not duplicated logic.\n */\nasync function discoverSmrtPackages(projectRoot: string): Promise<string[]> {\n const packages: string[] = [];\n const nodeModulesPath = path.join(projectRoot, 'node_modules');\n\n if (!fs.existsSync(nodeModulesPath)) {\n return packages;\n }\n\n try {\n // Check package.json for workspace dependencies\n const packageJsonPath = path.join(projectRoot, 'package.json');\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n const allDeps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n ...packageJson.peerDependencies,\n };\n\n // Look for packages that likely contain SMRT objects\n for (const [name, version] of Object.entries(allDeps)) {\n if (\n typeof version === 'string' &&\n (name.includes('smrt') ||\n name.includes('@have/') ||\n (await hasSmrtManifest(nodeModulesPath, name)))\n ) {\n packages.push(name);\n }\n }\n }\n } catch (error) {\n console.warn('[smrt:consumer] Error discovering packages:', error);\n }\n\n return packages;\n}\n\n/**\n * Manifest locations probed for a consumed package, in preference order.\n *\n * The package's own `package.json#exports` map comes first: it is the\n * published contract for where the manifest lives, and a package whose build\n * emits outside this framework's conventional layout (for example\n * `\"./manifest.json\": \"./dist/lib/manifest.json\"`) is otherwise skipped\n * entirely (issue #2923). The conventional paths remain as a fallback for\n * packages that ship a manifest without exporting a subpath for it.\n */\nfunction legacyStaticManifestPath(packageDir: string): string {\n return path.join(packageDir, 'dist', 'manifest', 'static-manifest.js');\n}\n\nfunction packageManifestCandidates(\n packageDir: string,\n packageJson?: ConsumerPackageJson,\n): string[] {\n return [\n ...manifestExportCandidates(packageDir, packageJson),\n legacyStaticManifestPath(packageDir),\n path.join(packageDir, 'dist', 'manifest.json'),\n path.join(packageDir, 'manifest.json'),\n ];\n}\n\n/**\n * Whether a dependency looks like a SMRT package, for the name-heuristic\n * discovery path only.\n *\n * This decides whether a package this framework knows nothing about is pulled\n * into aggregation at all, so mere existence of a manifest-shaped file is not\n * enough: `manifest.json` at a package root or `dist/manifest.json` is a\n * common artifact of unrelated tooling (Vite build manifests, PWA and\n * extension manifests). A false positive would announce a stranger under\n * \"Found SMRT packages\", tell the user to publish a manifest for a package\n * that has nothing to do with SMRT, and — for a JS candidate — evaluate that\n * dependency's module inside the build.\n *\n * A JSON candidate is therefore confirmed by parsing it and requiring\n * `moduleType: 'smrt'`, matching what build-time discovery requires. A JS\n * candidate cannot be identified without importing it, which is the thing\n * being avoided, so only the historical `dist/manifest/static-manifest.js`\n * location counts — exactly the probe this function used before #2923.\n */\nasync function hasSmrtManifest(\n nodeModulesPath: string,\n packageName: string,\n): Promise<boolean> {\n const packagePath = path.join(nodeModulesPath, packageName);\n const legacyStaticManifest = legacyStaticManifestPath(packagePath);\n\n for (const manifestPath of packageManifestCandidates(packagePath)) {\n if (!fs.existsSync(manifestPath)) continue;\n\n if (!manifestPath.endsWith('.json')) {\n if (manifestPath === legacyStaticManifest) return true;\n continue;\n }\n\n try {\n const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')) as {\n moduleType?: string;\n };\n if (manifest?.moduleType === 'smrt') return true;\n } catch {\n // Not a readable SMRT manifest; keep probing the remaining candidates.\n }\n }\n\n return false;\n}\n\n/**\n * Aggregate type manifests from multiple packages.\n *\n * A package that yields no usable manifest is never dropped silently\n * (issue #2923): an explicitly listed package fails the build, and a\n * heuristically discovered one warns by name. Silence here surfaces much\n * later as missing tables, routes, and generated types with nothing in the\n * build log to connect them to the package that was skipped.\n *\n * @param packages - Package names to aggregate.\n * @param projectRoot - Consumer project root containing `node_modules`.\n * @param options - `explicit` marks a caller-supplied `packages` list, whose\n * entries are assertions rather than guesses and therefore fail closed.\n */\nasync function aggregateTypeManifests(\n packages: string[],\n projectRoot: string,\n options: { explicit?: boolean } = {},\n): Promise<ConsumerManifest> {\n const aggregatedManifest: ConsumerManifest = {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n smrtDependencies: [...packages],\n objects: {},\n };\n\n const unresolvedPackages: string[] = [];\n\n for (const packageName of packages) {\n let loadedManifest = false;\n try {\n const packageDir = path.join(projectRoot, 'node_modules', packageName);\n\n // Load package.json for version and export information\n const packageJsonPath = path.join(packageDir, 'package.json');\n let packageJson: ConsumerPackageJson;\n try {\n const packageJsonContent = fs.readFileSync(packageJsonPath, 'utf-8');\n packageJson = JSON.parse(packageJsonContent) as ConsumerPackageJson;\n } catch {\n console.warn(\n `[smrt:consumer] Could not read package.json for ${packageName}`,\n );\n unresolvedPackages.push(packageName);\n continue;\n }\n\n // Try the package's declared manifest export first, then convention.\n const manifestCandidates = packageManifestCandidates(\n packageDir,\n packageJson,\n );\n\n for (const manifestPath of manifestCandidates) {\n if (fs.existsSync(manifestPath)) {\n // Import or read the manifest. A candidate that exists but cannot be\n // read, parsed, or imported must not end the search: the export map\n // is probed before the conventional paths, so letting one stale or\n // malformed exported target throw out of this loop would take away\n // the `dist/manifest.json` fallback a package used to load through.\n let manifest: Partial<ConsumerManifest> | undefined;\n try {\n if (manifestPath.endsWith('.js')) {\n const manifestModule = await import(manifestPath);\n manifest =\n manifestModule.staticManifest || manifestModule.default;\n } else {\n const manifestContent = fs.readFileSync(manifestPath, 'utf-8');\n manifest = JSON.parse(\n manifestContent,\n ) as Partial<ConsumerManifest>;\n }\n } catch (error) {\n console.warn(\n `[smrt:consumer] Could not load manifest candidate ${manifestPath} for ${packageName}; trying the next location:`,\n error,\n );\n continue;\n }\n\n if (manifest?.objects) {\n console.log(\n `[smrt:consumer] Loaded manifest from ${packageName} (${Object.keys(manifest.objects).length} objects)`,\n );\n\n // ENHANCED: Preserve package metadata for each object\n for (const [objectName, objectDef] of Object.entries(\n manifest.objects,\n )) {\n const def = objectDef;\n\n aggregatedManifest.objects[objectName] = {\n ...def,\n // Ensure package metadata is preserved/set\n packageName:\n def.packageName || manifest.packageName || packageName,\n packageVersion:\n def.packageVersion ||\n manifest.packageVersion ||\n packageJson.version,\n // Add fallback import paths if missing\n importPath: def.importPath || determineImportPath(packageJson),\n exportName: def.exportName || def.className || objectName,\n collectionExportName:\n def.collectionExportName ||\n `${def.className || objectName}Collection`,\n };\n }\n\n loadedManifest = true;\n break; // Use first found manifest for this package\n }\n }\n }\n } catch (error) {\n console.warn(\n `[smrt:consumer] Error loading manifest from ${packageName}:`,\n error,\n );\n }\n\n if (!loadedManifest) {\n unresolvedPackages.push(packageName);\n }\n }\n\n if (unresolvedPackages.length > 0) {\n const named = unresolvedPackages.join(', ');\n if (options.explicit) {\n throw new Error(\n `[smrt:consumer] No SMRT manifest could be resolved for ${named}. ` +\n 'Listed packages must publish a manifest through ' +\n 'package.json#exports (\"./manifest.json\") or at dist/manifest.json, ' +\n 'dist/manifest/static-manifest.js, or manifest.json. Build the ' +\n 'package, or remove it from smrtConsumer({ packages }).',\n );\n }\n // Discovery matches on dependency name, so a hit here is a guess: some\n // matched packages (UI/runtime helpers) legitimately have no objects.\n // Name them anyway — a missing manifest is otherwise invisible until the\n // objects turn up absent from routes and schema.\n console.warn(\n `[smrt:consumer] No SMRT manifest could be resolved for ${named}; ` +\n 'contributing 0 objects. If the package provides SMRT objects, ' +\n 'publish its manifest through package.json#exports (\"./manifest.json\").',\n );\n }\n\n return aggregatedManifest;\n}\n\n/**\n * Determine import path from package.json\n */\nfunction determineImportPath(packageJson: ConsumerPackageJson): string {\n const packageName = packageJson.name;\n\n if (!packageName) {\n throw new Error('Package name not found in package.json');\n }\n\n // Strategy 1: Check for specific exports\n if (packageJson.exports) {\n // Check for objects export\n if (packageJson.exports['./objects']) {\n return `${packageName}/objects`;\n }\n\n // Check for main export\n const mainExport = packageJson.exports['.'];\n if (mainExport) {\n // Handle conditional exports\n if (typeof mainExport === 'object' && mainExport !== null) {\n const conditional = mainExport as Record<string, unknown>;\n if (conditional.import) {\n return packageName;\n }\n if (conditional.default) {\n return packageName;\n }\n }\n return packageName;\n }\n }\n\n // Strategy 2: Check main field\n if (packageJson.main) {\n return packageName;\n }\n\n // Strategy 3: Fallback to package name\n return packageName;\n}\n\n/**\n * Save aggregated manifest to .smrt/manifest.json for CLI discovery.\n *\n * Merge-preserving: `smrtPlugin()` writes the project's own scanned objects\n * to the same file (`writeLocalManifest`, issue #963), and both writes happen\n * in parallel `buildStart` hooks — so a plain overwrite here would clobber\n * the local objects whenever this plugin's write lands last (issue #1760\n * review). Local field metadata would then silently vanish from CLI schema\n * commands and from server runtimes that seed `.smrt/manifest.json`, dropping\n * domain columns on write. This function therefore only ADDS/refreshes the\n * external-package entries it owns and preserves everything else already in\n * the file (including the top-level `packageName` the local write sets).\n */\nasync function saveAggregatedManifest(\n manifest: ConsumerManifest,\n projectRoot: string,\n resolveKnowledgeConfig?: SmrtPluginApi['resolveKnowledgeConfig'],\n agentSurface?: DomainKnowledgeAgentSurface,\n): Promise<void> {\n const smrtDir = path.join(projectRoot, '.smrt');\n const manifestPath = path.join(smrtDir, 'manifest.json');\n\n try {\n // Create .smrt directory if it doesn't exist\n if (!fs.existsSync(smrtDir)) {\n fs.mkdirSync(smrtDir, { recursive: true });\n }\n\n // Merge with whatever is on disk: existing entries (typically the local\n // project's objects written by smrtPlugin) are preserved; aggregated\n // external entries win for the qualified names this plugin owns.\n let merged: ConsumerManifest = manifest;\n if (fs.existsSync(manifestPath)) {\n try {\n const existing = JSON.parse(\n fs.readFileSync(manifestPath, 'utf-8'),\n ) as Partial<ConsumerManifest>;\n if (existing && typeof existing.objects === 'object') {\n merged = {\n ...existing,\n ...manifest,\n // The aggregated manifest carries no packageName; keep the local\n // project's (used as the manifest cache key at runtime).\n ...(existing.packageName\n ? { packageName: existing.packageName }\n : {}),\n objects: { ...existing.objects, ...manifest.objects },\n };\n }\n } catch {\n // Unreadable/corrupt existing file — fall back to a plain write.\n }\n }\n\n // smrtPlugin writes the local knowledge artifact before this consumer\n // plugin merges external package entries into the same manifest. Refresh\n // the artifact from the merged manifest so its source hash always names\n // the manifest that CLI discovery and server runtimes actually consume.\n // The consumer deliberately does not load the scanner. Only carry a\n // surface from the current producer scan: a prior artifact can describe\n // declarations that have since changed while retaining the same path.\n // Re-hashing that current path under a stale declaration would make an\n // incorrect agent contract look fresh.\n const knowledgePath = path.join(smrtDir, 'smrt-knowledge.json');\n const packageJsonPath = path.join(projectRoot, 'package.json');\n const packageJson = fs.existsSync(packageJsonPath)\n ? JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n : undefined;\n const knowledgeConfig = resolveKnowledgeConfig\n ? await resolveKnowledgeConfig(merged as unknown as SmartObjectManifest)\n : await resolveFileKnowledgeConfig(\n projectRoot,\n merged.packageName ?? packageJson?.name,\n );\n if (knowledgeConfig.enabled === false) {\n publishArtifactFiles([\n { path: manifestPath, content: JSON.stringify(merged, null, 2) },\n ]);\n return;\n }\n const knowledge = buildDomainKnowledgeManifest({\n manifest: merged as unknown as SmartObjectManifest,\n rootDir: projectRoot,\n packageJson,\n manifestPath,\n config: knowledgeConfig,\n agentSurface,\n });\n // Stage both artifacts before replacing either. Renames are individually\n // atomic; if a synchronous later rename fails, restore every earlier\n // replacement. A process crash between renames cannot be made pair-atomic\n // with ordinary filesystem operations, so the next generation remains the\n // freshness repair path for that distinct failure mode.\n publishArtifactFiles([\n { path: knowledgePath, content: JSON.stringify(knowledge, null, 2) },\n { path: manifestPath, content: JSON.stringify(merged, null, 2) },\n ]);\n\n console.log(\n `[smrt:consumer] Saved aggregated manifest to .smrt/manifest.json (${Object.keys(merged.objects).length} objects)`,\n );\n } catch (error) {\n throw new Error('[smrt:consumer] Failed to save aggregated manifest', {\n cause: error,\n });\n }\n}\n\n/**\n * Generate registration file for CLI class loading\n *\n * Creates .smrt/register.js with static imports and registrations\n * for all external SMRT objects discovered during build.\n */\nasync function generateRegistrationFile(\n manifest: ConsumerManifest,\n projectRoot: string,\n): Promise<void> {\n const smrtDir = path.join(projectRoot, '.smrt');\n const registerPath = path.join(smrtDir, 'register.js');\n\n // Bind every imported symbol to a generated local name. Aggregated manifests\n // may contain same-named exports from different packages (and may list a\n // collection both beside its object and as its own manifest entry), so using\n // provider export names as local bindings can produce invalid duplicate\n // imports in a production consumer bundle.\n const importBindings = new Map<string, string>();\n const importsByPath = new Map<string, Map<string, string>>();\n let nextImportBinding = 0;\n const getImportBinding = (importPath: string, exportName: string): string => {\n const key = `${importPath}\\0${exportName}`;\n const existing = importBindings.get(key);\n if (existing) return existing;\n const binding = `__smrt_consumer_${nextImportBinding++}`;\n importBindings.set(key, binding);\n const specifiers =\n importsByPath.get(importPath) ?? new Map<string, string>();\n specifiers.set(exportName, binding);\n importsByPath.set(importPath, specifiers);\n return binding;\n };\n\n const registrations: string[] = [];\n const registrationManifests: Record<string, ConsumerManifest> = {};\n let importedEntryCount = 0;\n let registeredObjectCount = 0;\n\n const manifestObjects = manifest.objects;\n const manifestObjectLookup = new Map<string, ConsumerObjectDefinition>();\n for (const [key, def] of Object.entries(manifestObjects)) {\n const candidate = def;\n const lookupKeys = [\n key,\n key.includes(':') ? key.split(':').pop() : undefined,\n candidate.qualifiedName,\n candidate.className,\n candidate.exportName,\n ];\n\n for (const lookupKey of lookupKeys) {\n if (lookupKey && !manifestObjectLookup.has(lookupKey)) {\n manifestObjectLookup.set(lookupKey, candidate);\n }\n }\n }\n\n const collectionClassMemo = new WeakMap<object, boolean>();\n\n const isCollectionClass = (\n def: ConsumerObjectDefinition | undefined,\n seen = new Set<string>(),\n ): boolean => {\n if (!def || typeof def !== 'object') {\n return false;\n }\n\n const cached = collectionClassMemo.get(def);\n if (cached !== undefined) {\n return cached;\n }\n\n if (\n def?.extends === 'SmrtCollection' ||\n def?.extendsTypeArg !== undefined\n ) {\n collectionClassMemo.set(def, true);\n return true;\n }\n\n const parentName = def?.extendsQualified || def?.extends;\n if (!parentName || seen.has(parentName)) {\n collectionClassMemo.set(def, false);\n return false;\n }\n seen.add(parentName);\n\n const parentDef = manifestObjectLookup.get(parentName);\n const isCollection = parentDef ? isCollectionClass(parentDef, seen) : false;\n collectionClassMemo.set(def, isCollection);\n\n return isCollection;\n };\n\n for (const [objectName, objectDef] of Object.entries(manifestObjects)) {\n const def = objectDef;\n\n // Skip local objects (they're imported from local entry point)\n if (!def.packageName || def.packageName === manifest.packageName) {\n continue;\n }\n\n const importPath = def.importPath || def.packageName;\n const exportName = def.exportName || def.className || objectName;\n const collectionExportName = def.collectionExportName;\n const hasCollection = def.hasCollection; // Check if collection class actually exists\n const tableName = def.collection || objectName.toLowerCase();\n\n const exportBinding = getImportBinding(importPath, exportName);\n const collectionBinding =\n hasCollection && collectionExportName\n ? getImportBinding(importPath, collectionExportName)\n : undefined;\n importedEntryCount++;\n\n if (isCollectionClass(def)) {\n continue;\n }\n\n const logicalName = def.className || exportName;\n registrationManifests[objectName] = {\n ...manifest,\n packageName: def.packageName,\n packageVersion: def.packageVersion || manifest.packageVersion,\n objects: { [objectName]: def },\n };\n\n // Import evaluation triggers the provider decorator first. The explicit\n // constructor/package/key tuple then promotes that exact constructor with\n // its isolated manifest, which is stable across Rollup name deconfliction.\n registrations.push(\n `if (${exportBinding}) ObjectRegistry.register(${exportBinding}, { name: ${JSON.stringify(logicalName)}, packageName: ${JSON.stringify(def.packageName)}, _manifest: smrtRegistrationManifests[${JSON.stringify(objectName)}], _manifestKey: ${JSON.stringify(objectName)} });`,\n );\n\n // Only register collection if it exists\n if (collectionBinding) {\n registrations.push(\n `if (${collectionBinding}) ObjectRegistry.registerCollection('${tableName}', ${collectionBinding});`,\n );\n }\n\n registeredObjectCount++;\n }\n\n // Skip generation if no external entries\n if (importedEntryCount === 0) {\n console.log('[smrt:consumer] No external entries - skipping register.js');\n return;\n }\n\n const registeredObjectLabel =\n registeredObjectCount === 1 ? 'object' : 'objects';\n const sortedImports = Array.from(importsByPath.entries()).sort(\n ([left], [right]) => left.localeCompare(right),\n );\n const imports = sortedImports.map(\n ([importPath], index) =>\n `import * as __smrt_provider_${index} from '${importPath}';`,\n );\n const importDeclarations = sortedImports.flatMap(([, specifiers], index) =>\n Array.from(specifiers.entries())\n .sort(([left], [right]) => left.localeCompare(right))\n .map(\n ([exportName, binding]) =>\n `const ${binding} = getSmrtExport(__smrt_provider_${index}, ${JSON.stringify(exportName)});`,\n ),\n );\n const registrationManifestLiteral = JSON.stringify(\n JSON.stringify(registrationManifests),\n );\n\n // Generate file content\n const content = `/**\n * Auto-generated by @happyvertical/smrt-core/consumer-plugin\n * DO NOT EDIT - This file is regenerated on every build\n *\n * Registers SMRT objects from external packages for CLI discovery.\n * Generated at: ${new Date().toISOString()}\n */\n\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\n${imports.join('\\n')}\n\n/**\n * @param {Record<string, unknown>} provider\n * @param {string} exportName\n * @returns {any}\n */\nconst getSmrtExport = (provider, exportName) =>\n typeof provider[exportName] === 'function' ? provider[exportName] : undefined;\n${importDeclarations.join('\\n')}\n\nconst smrtRegistrationManifests = JSON.parse(${registrationManifestLiteral});\n\n// Register all objects (executed during module evaluation)\n${registrations.join('\\n')}\n\nexport function registerAll() {\n // Objects are already registered during module evaluation\n console.log('[smrt:register] Registered ${registeredObjectCount} external ${registeredObjectLabel}');\n}\n`;\n\n // Create .smrt directory if needed\n if (!fs.existsSync(smrtDir)) {\n fs.mkdirSync(smrtDir, { recursive: true });\n }\n\n // Write registration file\n fs.writeFileSync(registerPath, content, 'utf-8');\n\n console.log(\n `[smrt:consumer] Generated .smrt/register.js with ${importedEntryCount} external entries (${registeredObjectCount} registered ${registeredObjectLabel})`,\n );\n}\n\n/**\n * Generate project-specific types\n */\nasync function generateProjectTypes(\n typeManifest: ConsumerManifest,\n typesDir: string,\n projectRoot: string,\n): Promise<void> {\n if (!typeManifest || Object.keys(typeManifest.objects).length === 0) {\n console.log(\n '[smrt:consumer] No SMRT objects found, skipping type generation',\n );\n return;\n }\n\n await generateDeclarations({\n // The aggregated manifest is a runtime SMRT manifest assembled from external\n // package manifests; it is intentionally typed loosely at the JSON boundary,\n // so narrow it to the declaration generator's strict manifest shape here.\n manifest: typeManifest as unknown as SmartObjectManifest,\n outDir: typesDir,\n projectRoot,\n includeVirtualModules: true,\n includeObjectTypes: true,\n });\n\n console.log(\n `[smrt:consumer] Generated types for ${Object.keys(typeManifest.objects).length} objects`,\n );\n}\n\n/**\n * Get type file name for virtual module\n */\nfunction getTypeFileName(virtualModule: string): string {\n const moduleMap: Record<string, string> = {\n '@smrt/routes': 'smrt-routes.d.ts',\n '@smrt/client': 'smrt-client.d.ts',\n '@smrt/mcp': 'smrt-mcp.d.ts',\n '@smrt/types': 'smrt-types.d.ts',\n '@smrt/manifest': 'smrt-manifest.d.ts',\n '@smrt/web': 'smrt-web.d.ts',\n };\n return moduleMap[virtualModule] || 'smrt-unknown.d.ts';\n}\n\n/**\n * Fallback modules for when types aren't available\n */\nfunction generateFallbackRoutesModule(): string {\n return `\n// Fallback routes module\nexport function setupRoutes(app) {\n console.warn('[smrt:consumer] No routes available - SMRT packages may not be properly configured');\n}\nexport default setupRoutes;\n`;\n}\n\nfunction generateFallbackClientModule(\n manifest: ConsumerManifest,\n options: { kebabRoutes?: boolean } = {},\n): string {\n const objects = Object.entries(manifest?.objects || {});\n if (objects.length === 0) {\n return `\n// Fallback client module\nexport function createClient(basePath = '/api/v1') {\n console.warn('[smrt:consumer] No API client available - SMRT packages may not be properly configured');\n return {};\n}\nexport default createClient;\n`;\n }\n\n return generateClientModule(manifest as unknown as SmartObjectManifest, {\n kebabRoutes: options.kebabRoutes,\n });\n}\n\nfunction generateFallbackMcpModule(): string {\n return `\n// Fallback MCP module\nexport const tools = [];\nexport function createMCPServer() {\n console.warn('[smrt:consumer] No MCP tools available - SMRT packages may not be properly configured');\n return { name: 'smrt-consumer', version: '1.0.0', tools: [] };\n}\nexport default createMCPServer;\n`;\n}\n\nfunction generateFallbackTypesModule(manifest: ConsumerManifest): string {\n const objects = Object.entries(manifest?.objects || {});\n if (objects.length === 0) {\n return `// No types available`;\n }\n\n // Generate basic interfaces\n const interfaces = objects.map(([_name, obj]) => {\n return `export interface ${obj.className}Data {\n id?: string;\n created_at?: string;\n updated_at?: string;\n [key: string]: any;\n}`;\n });\n\n return interfaces.join('\\n\\n');\n}\n\nfunction generateFallbackManifestModule(manifest: ConsumerManifest): string {\n return `\n// Auto-generated manifest from SMRT consumer\nexport const manifest = ${JSON.stringify(manifest, null, 2)};\nexport default manifest;\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2KA,IAAM,kBAAkB;CACtB,gBAAgB;CAChB,gBAAgB;CAChB,aAAa;CACb,eAAe;CACf,kBAAkB;CAClB,aAAa;AACf;AAEA,IAAM,6CAA6C;AACnD,IAAM,qCAAqC;AAO3C,SAAS,oCAAoC,aAA6B;CACxE,OAAO,KAAK,KAAK,aAAa,SAAS,kCAAkC;AAC3E;;AAGA,SAAS,2BACP,aACA,WACQ;CACR,MAAM,OAAO,KAAK,QAAQ,WAAW;CACrC,MAAM,WAAW,KAAK,SAAS,MAAM,KAAK,QAAQ,MAAM,SAAS,CAAC;CAClE,IACE,CAAC,YACD,aAAa,QACb,SAAS,WAAW,KAAK,KAAK,KAAK,KACnC,KAAK,WAAW,QAAQ,GAExB,MAAM,IAAI,MACR,yFAAyF,KAAK,UAAU,SAAS,EAAE,EACrH;CAEF,OAAO,SAAS,MAAM,KAAK,GAAG,CAAC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5D"}
@@ -11,6 +11,7 @@
11
11
  */
12
12
  import type { CustomActionScope } from './custom-action.js';
13
13
  import type { MCPConfig, MCPContext } from './mcp.js';
14
+ import type { McpToolTarget } from './mcp-tool-name.js';
14
15
  export interface RuntimeOptions {
15
16
  /** Server name (defaults to package name) */
16
17
  name?: string;
@@ -30,7 +31,23 @@ export interface RuntimeOptions {
30
31
  description: string;
31
32
  inputSchema: Record<string, unknown>;
32
33
  outputSchema?: Record<string, unknown>;
34
+ annotations?: {
35
+ readOnlyHint: boolean;
36
+ destructiveHint: boolean;
37
+ idempotentHint: boolean;
38
+ openWorldHint: boolean;
39
+ };
40
+ title?: string;
41
+ icons?: Array<{
42
+ src: string;
43
+ mimeType?: string;
44
+ sizes?: string[];
45
+ theme?: 'light' | 'dark';
46
+ }>;
47
+ _meta?: Record<string, unknown>;
33
48
  }>;
49
+ /** Explicit original execution targets for generated protocol aliases. */
50
+ toolTargets?: Record<string, McpToolTarget>;
34
51
  /** Cache hint emitted for deploy-static tools/list results. */
35
52
  toolListCacheHint?: {
36
53
  ttlMs: number;
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-runtime-template.d.ts","sourceRoot":"","sources":["../../src/generators/mcp-runtime-template.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAOH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAStD,MAAM,WAAW,cAAc;IAC7B,6CAA6C;IAC7C,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd,mDAAmD;IACnD,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB,yBAAyB;IACzB,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB,kCAAkC;IAClC,MAAM,CAAC,EAAE,SAAS,CAAC;IAEnB,8CAA8C;IAC9C,OAAO,CAAC,EAAE,UAAU,CAAC;IAErB,2BAA2B;IAC3B,KAAK,CA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BAAiB,CAC/B,UAAU,GAAE,MAA6B,GACxC,MAAM,CAER;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,GACjB,MAAM,CASR;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CACtC,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,GACjB,MAAM,CA0GR"}
1
+ {"version":3,"file":"mcp-runtime-template.d.ts","sourceRoot":"","sources":["../../src/generators/mcp-runtime-template.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAOH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACtD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AASxD,MAAM,WAAW,cAAc;IAC7B,6CAA6C;IAC7C,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd,mDAAmD;IACnD,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB,yBAAyB;IACzB,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB,kCAAkC;IAClC,MAAM,CAAC,EAAE,SAAS,CAAC;IAEnB,8CAA8C;IAC9C,OAAO,CAAC,EAAE,UAAU,CAAC;IAErB,2BAA2B;IAC3B,KAAK,CAAC,EAAE,OAAO,CAAC;IAEhB,wDAAwD;IACxD,KAAK,CAAC,EAAE,KAAK,CAAC;QACZ,IAAI,EAAE,MAAM,CAAC;QACb,WAAW,EAAE,MAAM,CAAC;QACpB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACrC,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACvC,WAAW,CAAC,EAAE;YACZ,YAAY,EAAE,OAAO,CAAC;YACtB,eAAe,EAAE,OAAO,CAAC;YACzB,cAAc,EAAE,O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