@nimiplatform/app-tools 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/LICENSE +198 -6
  2. package/README.md +83 -27
  3. package/bin/nimi-app.mjs +328 -45
  4. package/lib/app-access-declaration.mjs +49 -0
  5. package/lib/app-doctor-update.mjs +411 -149
  6. package/lib/app-pack.mjs +401 -0
  7. package/lib/app-project-lifecycle.mjs +1141 -0
  8. package/lib/app-scaffold-capabilities.mjs +769 -0
  9. package/lib/app-scaffold-default-source.mjs +21 -0
  10. package/lib/app-scaffold-profiles.mjs +1093 -0
  11. package/lib/app-scaffold.mjs +1266 -813
  12. package/lib/index.mjs +194 -42
  13. package/lib/simulator-conformance-ast.mjs +498 -0
  14. package/lib/simulator-conformance-css.mjs +116 -0
  15. package/lib/simulator-conformance-graph.mjs +757 -0
  16. package/lib/simulator-conformance.d.mts +14 -0
  17. package/lib/simulator-conformance.mjs +203 -0
  18. package/lib/simulator-css-profile.d.mts +27 -0
  19. package/lib/simulator-css-profile.mjs +531 -0
  20. package/lib/simulator-kit-export-resolution.mjs +70 -0
  21. package/lib/simulator-manifest.mjs +334 -0
  22. package/package.json +66 -3
  23. package/scripts/dev-shell.mjs +465 -0
  24. package/scripts/sync-app-source.mjs +300 -0
  25. package/scripts/sync-scaffold-versions.mjs +91 -0
  26. package/templates/app-source/LICENSE +21 -0
  27. package/templates/app-source/src/ai-studio-core/ai-config.ts +100 -0
  28. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +338 -0
  29. package/templates/app-source/src/ai-studio-core/contexts.tsx +61 -0
  30. package/templates/app-source/src/ai-studio-core/history-policy.ts +447 -0
  31. package/templates/app-source/src/ai-studio-core/history.ts +824 -0
  32. package/templates/app-source/src/ai-studio-core/host-context.tsx +79 -0
  33. package/templates/app-source/src/ai-studio-core/index.ts +214 -0
  34. package/templates/app-source/src/ai-studio-core/messages/en.json +310 -0
  35. package/templates/app-source/src/ai-studio-core/messages/index.ts +47 -0
  36. package/templates/app-source/src/ai-studio-core/messages/zh.json +310 -0
  37. package/templates/app-source/src/ai-studio-core/module-registration.ts +109 -0
  38. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +65 -0
  39. package/templates/app-source/src/ai-studio-core/parameter-fields.tsx +247 -0
  40. package/templates/app-source/src/ai-studio-core/parameters.ts +110 -0
  41. package/templates/app-source/src/ai-studio-core/prompt-drafts.ts +69 -0
  42. package/templates/app-source/src/ai-studio-core/run-target.ts +123 -0
  43. package/templates/app-source/src/ai-studio-core/runtime-dispatcher.ts +35 -0
  44. package/templates/app-source/src/ai-studio-core/runtime-types.ts +86 -0
  45. package/templates/app-source/src/ai-studio-core/runtime.ts +306 -0
  46. package/templates/app-source/src/ai-studio-core/section-ai-testing-admission.ts +38 -0
  47. package/templates/app-source/src/ai-studio-core/section-ai-testing-ai-config.tsx +30 -0
  48. package/templates/app-source/src/ai-studio-core/section-ai-testing-artifact-preview.ts +40 -0
  49. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +257 -0
  50. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +676 -0
  51. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +19 -0
  52. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +291 -0
  53. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +413 -0
  54. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +174 -0
  55. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +449 -0
  56. package/templates/app-source/src/ai-studio-core/section-ai-testing-surface.tsx +45 -0
  57. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +494 -0
  58. package/templates/app-source/src/ai-studio-core/studio-directives.ts +33 -0
  59. package/templates/app-source/src/ai-studio-core/workspace.tsx +381 -0
  60. package/templates/app-source/src/product-modules/agent-center/index.tsx +27 -0
  61. package/templates/app-source/src/product-modules/agent-conversation/index.tsx +19 -0
  62. package/templates/app-source/src/product-modules/agent-realtime/index.tsx +29 -0
  63. package/templates/app-source/src/product-modules/kit-recipes/gallery.tsx +142 -0
  64. package/templates/app-source/src/product-modules/kit-recipes/index.tsx +19 -0
  65. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-data-recipes.tsx +336 -0
  66. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-demos.tsx +165 -0
  67. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-recipes.tsx +682 -0
  68. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-surface.tsx +341 -0
  69. package/templates/app-source/src/studio-modules/studio-create/descriptors.ts +26 -0
  70. package/templates/app-source/src/studio-modules/studio-create/index.ts +14 -0
  71. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +67 -0
  72. package/templates/app-source/src/studio-modules/studio-create/messages/index.ts +5 -0
  73. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +67 -0
  74. package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +153 -0
  75. package/templates/app-source/src/studio-modules/studio-create/parameters.ts +70 -0
  76. package/templates/app-source/src/studio-modules/studio-create/registration.ts +46 -0
  77. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +339 -0
  78. package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +22 -0
  79. package/templates/app-source/src/studio-modules/studio-media/index.ts +12 -0
  80. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +82 -0
  81. package/templates/app-source/src/studio-modules/studio-media/messages/index.ts +5 -0
  82. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +82 -0
  83. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +283 -0
  84. package/templates/app-source/src/studio-modules/studio-media/parameters.ts +94 -0
  85. package/templates/app-source/src/studio-modules/studio-media/registration.ts +44 -0
  86. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +113 -0
  87. package/templates/app-source/src/studio-modules/studio-voice/descriptors.ts +28 -0
  88. package/templates/app-source/src/studio-modules/studio-voice/index.ts +16 -0
  89. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +99 -0
  90. package/templates/app-source/src/studio-modules/studio-voice/messages/index.ts +5 -0
  91. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +99 -0
  92. package/templates/app-source/src/studio-modules/studio-voice/parameter-panel.tsx +284 -0
  93. package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +116 -0
  94. package/templates/app-source/src/studio-modules/studio-voice/registration.ts +59 -0
  95. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +347 -0
  96. package/templates/app-source/src/workbench-core/empty-state.tsx +31 -0
  97. package/templates/app-source/src/workbench-core/index.ts +17 -0
  98. package/templates/app-source/src/workbench-core/runtime-gate.tsx +131 -0
  99. package/templates/app-source/src/workbench-core/workbench-core.css +255 -0
  100. package/templates/app-source/src/workbench-core/workbench-core.tsx +140 -0
  101. package/templates/app-source.manifest.json +333 -0
  102. package/templates/default-starter/AGENTS.md +33 -0
  103. package/templates/default-starter/LICENSE +21 -0
  104. package/templates/default-starter/README.md +41 -0
  105. package/templates/default-starter/SECURITY.md +5 -0
  106. package/templates/default-starter/index.html +12 -0
  107. package/templates/default-starter/scripts/validate.mjs +26 -0
  108. package/templates/default-starter/src/shell/App.tsx +27 -0
  109. package/templates/default-starter/src/shell/auth/app-identity.ts +3 -0
  110. package/templates/default-starter/src/shell/auth/local-app-client.ts +18 -0
  111. package/templates/default-starter/src/shell/auth/runtime-platform.ts +110 -0
  112. package/templates/default-starter/src/shell/authenticated-shell.tsx +20 -0
  113. package/templates/default-starter/src/shell/workbench-target-adapter.ts +40 -0
  114. package/templates/default-starter/src/styles.css +26 -0
  115. package/templates/default-starter/src-tauri/Cargo.toml +17 -0
  116. package/templates/default-starter/src-tauri/build.rs +5 -0
  117. package/templates/default-starter/src-tauri/capabilities/default.json +7 -0
  118. package/templates/default-starter/src-tauri/tauri.conf.json +26 -0
  119. package/templates/default-starter/tsconfig.json +18 -0
  120. package/templates/default-starter.manifest.json +99 -0
@@ -0,0 +1,300 @@
1
+ #!/usr/bin/env node
2
+
3
+ // apps/lab is the hand-authored full-capability development Nimi App. This module bakes
4
+ // its source snapshot into templates/app-source/** so the published
5
+ // @nimiplatform/app-tools tarball can materialize admitted capability slices
6
+ // profile and reuse reviewed shell/auth glue for default starter profiles.
7
+ //
8
+ // The snapshot is a derived build artifact (gitignored, like dist/):
9
+ // --apply materialize templates/app-source/** + manifest (prepack)
10
+ // resolveAppSource the generator's source resolver — prefers a baked
11
+ // snapshot, else reads the live apps/lab tree, so in the
12
+ // monorepo there is exactly one copy and no build step.
13
+
14
+ import {
15
+ cpSync,
16
+ existsSync,
17
+ mkdirSync,
18
+ readFileSync,
19
+ readdirSync,
20
+ rmSync,
21
+ writeFileSync,
22
+ } from 'node:fs';
23
+ import path from 'node:path';
24
+ import { fileURLToPath } from 'node:url';
25
+ import {
26
+ APP_SCAFFOLD_ADMITTED_MODULE_IDS,
27
+ APP_SCAFFOLD_MODULE_REGISTRY,
28
+ validateAppScaffoldModuleRegistry,
29
+ } from '../lib/app-scaffold-capabilities.mjs';
30
+
31
+ const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
32
+ const APP_TOOLS_ROOT = path.resolve(SCRIPT_DIR, '..');
33
+ const SOURCE_APP_DIR = path.resolve(APP_TOOLS_ROOT, '../apps/lab');
34
+ const SNAPSHOT_DIR = path.resolve(APP_TOOLS_ROOT, 'templates/app-source');
35
+ const MANIFEST_PATH = path.resolve(APP_TOOLS_ROOT, 'templates/app-source.manifest.json');
36
+ const WORKBENCH_CORE_SOURCE_ROOT = 'src/workbench-core';
37
+
38
+ function sourceRootsForModuleIds(resolvedModuleIds) {
39
+ validateAppScaffoldModuleRegistry();
40
+ if (!Array.isArray(resolvedModuleIds)) {
41
+ throw new Error('App scaffold source modules must be a canonical module id array');
42
+ }
43
+ const canonicalModuleIds = Object.values(APP_SCAFFOLD_MODULE_REGISTRY)
44
+ .sort((left, right) => left.order - right.order || left.id.localeCompare(right.id))
45
+ .map((module) => module.id)
46
+ .filter((id) => resolvedModuleIds.includes(id));
47
+ if (JSON.stringify(resolvedModuleIds) !== JSON.stringify(canonicalModuleIds)) {
48
+ throw new Error('App scaffold source modules must use canonical registry order without duplicates');
49
+ }
50
+ const selectedModuleIds = new Set(resolvedModuleIds);
51
+ for (const id of resolvedModuleIds) {
52
+ for (const dependency of APP_SCAFFOLD_MODULE_REGISTRY[id].requires) {
53
+ if (!selectedModuleIds.has(dependency)) {
54
+ throw new Error(`App scaffold source module closure is missing dependency: ${id} -> ${dependency}`);
55
+ }
56
+ }
57
+ }
58
+ const seen = new Set([WORKBENCH_CORE_SOURCE_ROOT]);
59
+ const roots = [WORKBENCH_CORE_SOURCE_ROOT];
60
+ for (const id of resolvedModuleIds) {
61
+ const module = APP_SCAFFOLD_MODULE_REGISTRY[id];
62
+ if (!module) throw new Error(`Unknown app scaffold source module: ${id}`);
63
+ for (const mapping of module.sourceMappings) {
64
+ if (seen.has(mapping.sourceRoot)) continue;
65
+ seen.add(mapping.sourceRoot);
66
+ roots.push(mapping.sourceRoot);
67
+ }
68
+ }
69
+ return Object.freeze(roots);
70
+ }
71
+
72
+ // Directories never copied into the snapshot: build output, generated Tauri
73
+ // schema/icon assets, dependency state, and host-projection truth that init
74
+ // regenerates through nimicoding rather than the scaffold copy.
75
+ const EXCLUDED_DIRS = new Set([
76
+ '.git',
77
+ 'node_modules',
78
+ 'dist',
79
+ 'dist-electron',
80
+ 'target',
81
+ '.tmp',
82
+ '.local',
83
+ '.nimi',
84
+ '.turbo',
85
+ '.vite',
86
+ ]);
87
+ const EXCLUDED_DIR_PATHS = new Set([
88
+ 'src-tauri/gen',
89
+ 'src-tauri/icons',
90
+ ]);
91
+ // Files the generator emits structurally (identity/profile/version derived or a
92
+ // fixed scaffold asset), so they must not also live as a verbatim snapshot copy.
93
+ const STRUCTURED_FILE_PATHS = new Set([
94
+ '.gitignore',
95
+ '.github/workflows/ci.yml',
96
+ 'package.json',
97
+ 'src-tauri/Cargo.lock',
98
+ ]);
99
+
100
+ // Nimi Lab's concrete identity literals. The generator string-replaces
101
+ // these with the target app identity at create time. Ordered longest-first so a
102
+ // shorter literal can never partially rewrite a longer one.
103
+ const SOURCE_IDENTITY = {
104
+ tauriIdentifier: 'ai.nimi.apps.nimi.lab',
105
+ packageName: '@nimiplatform/lab',
106
+ cargoPackageName: 'nimiapp-lab-shell',
107
+ appId: 'nimi.lab',
108
+ appTitle: 'Nimi Lab',
109
+ appSlug: 'nimi-lab',
110
+ rendererEntryId: 'lab-app',
111
+ accentPack: 'nimi-accent',
112
+ devPort: '1468',
113
+ };
114
+
115
+ // Identity field => ordered replacement key. Order is by descending literal
116
+ // length, computed once so apply/check and the generator stay identical.
117
+ const IDENTITY_REPLACEMENT_ORDER = Object.entries(SOURCE_IDENTITY)
118
+ .filter(([field]) => field !== 'rendererEntryId')
119
+ .sort(([, left], [, right]) => right.length - left.length)
120
+ .map(([field]) => field);
121
+
122
+ function isAppOwnedProductCode(relativePath) {
123
+ if (relativePath.startsWith(`${WORKBENCH_CORE_SOURCE_ROOT}/`)) {
124
+ return true;
125
+ }
126
+ for (const module of Object.values(APP_SCAFFOLD_MODULE_REGISTRY)) {
127
+ if (module.sourceMappings.some((mapping) => relativePath.startsWith(`${mapping.sourceRoot}/`))) {
128
+ return true;
129
+ }
130
+ }
131
+ if (relativePath === 'src/shell/routes/product-area.tsx') {
132
+ return true;
133
+ }
134
+ if (relativePath.startsWith('src/shell/ai/')) {
135
+ return true;
136
+ }
137
+ if (relativePath === 'src/shell/routes/settings.tsx' || relativePath.startsWith('src/shell/routes/settings/')) {
138
+ return true;
139
+ }
140
+ if (relativePath === 'src/dev-preview.tsx' || relativePath === 'dev-preview.html') {
141
+ return true;
142
+ }
143
+ if (relativePath.startsWith('src/lab/')) {
144
+ return true;
145
+ }
146
+ if (relativePath === 'src-tauri/src/world_tour.rs') {
147
+ return true;
148
+ }
149
+ if (relativePath.startsWith('test/')) {
150
+ return true;
151
+ }
152
+ return false;
153
+ }
154
+
155
+ function classifyFile(relativePath) {
156
+ return isAppOwnedProductCode(relativePath) ? 'app-owned product code' : 'scaffold-managed glue';
157
+ }
158
+
159
+ function collectSnapshotFiles(sourceDir, resolvedModuleIds = APP_SCAFFOLD_ADMITTED_MODULE_IDS) {
160
+ const files = [];
161
+ const walk = (currentDir, relativeDir) => {
162
+ const entries = readdirSync(currentDir, { withFileTypes: true });
163
+ for (const entry of entries) {
164
+ const relativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name;
165
+ if (entry.isDirectory()) {
166
+ if (EXCLUDED_DIRS.has(entry.name) || EXCLUDED_DIR_PATHS.has(relativePath)) {
167
+ continue;
168
+ }
169
+ walk(path.join(currentDir, entry.name), relativePath);
170
+ continue;
171
+ }
172
+ if (!entry.isFile()) {
173
+ continue;
174
+ }
175
+ if (STRUCTURED_FILE_PATHS.has(relativePath)) {
176
+ continue;
177
+ }
178
+ files.push(relativePath);
179
+ }
180
+ };
181
+ for (const sourceRoot of sourceRootsForModuleIds(resolvedModuleIds)) {
182
+ const absoluteRoot = path.join(sourceDir, sourceRoot);
183
+ if (!existsSync(absoluteRoot)) {
184
+ throw new Error(`Scaffold product source missing: ${sourceRoot}`);
185
+ }
186
+ walk(absoluteRoot, sourceRoot);
187
+ }
188
+ return files.sort((left, right) => left.localeCompare(right));
189
+ }
190
+
191
+ function buildManifest(files, resolvedModuleIds = APP_SCAFFOLD_ADMITTED_MODULE_IDS) {
192
+ sourceRootsForModuleIds(resolvedModuleIds);
193
+ return {
194
+ manifestVersion: 2,
195
+ sourceApp: 'apps/lab',
196
+ resolvedModules: [...resolvedModuleIds],
197
+ sourceIdentity: SOURCE_IDENTITY,
198
+ identityReplacementOrder: IDENTITY_REPLACEMENT_ORDER,
199
+ files: files.map((relativePath) => ({
200
+ path: relativePath,
201
+ class: classifyFile(relativePath),
202
+ })),
203
+ };
204
+ }
205
+
206
+ function jsonFile(value) {
207
+ return `${JSON.stringify(value, null, 2)}\n`;
208
+ }
209
+
210
+ function applySnapshot() {
211
+ if (!existsSync(SOURCE_APP_DIR)) {
212
+ throw new Error(`Nimi Lab source missing: ${SOURCE_APP_DIR}`);
213
+ }
214
+ const resolvedModuleIds = APP_SCAFFOLD_ADMITTED_MODULE_IDS;
215
+ const files = collectSnapshotFiles(SOURCE_APP_DIR, resolvedModuleIds);
216
+ rmSync(SNAPSHOT_DIR, { recursive: true, force: true });
217
+ mkdirSync(SNAPSHOT_DIR, { recursive: true });
218
+ for (const relativePath of files) {
219
+ const targetPath = path.join(SNAPSHOT_DIR, relativePath);
220
+ mkdirSync(path.dirname(targetPath), { recursive: true });
221
+ cpSync(path.join(SOURCE_APP_DIR, relativePath), targetPath);
222
+ }
223
+ // The baked snapshot is MIT distribution material; LICENSE is packaging
224
+ // metadata and never enters the scaffold source manifest.
225
+ cpSync(path.join(SOURCE_APP_DIR, 'LICENSE'), path.join(SNAPSHOT_DIR, 'LICENSE'));
226
+ writeFileSync(MANIFEST_PATH, jsonFile(buildManifest(files, resolvedModuleIds)));
227
+ return files;
228
+ }
229
+
230
+ // Source resolver used by the generator. In the monorepo it reads apps/lab
231
+ // live so scaffold checks exercise the second consumer directly.
232
+ // Published tarballs fall back to the baked snapshot because apps/lab is not
233
+ // present.
234
+ function resolveAppSource({ resolvedModuleIds = APP_SCAFFOLD_ADMITTED_MODULE_IDS } = {}) {
235
+ const requestedModuleIds = [...resolvedModuleIds];
236
+ if (existsSync(SOURCE_APP_DIR)) {
237
+ const files = collectSnapshotFiles(SOURCE_APP_DIR, requestedModuleIds);
238
+ return {
239
+ baseDir: SOURCE_APP_DIR,
240
+ manifest: buildManifest(files, requestedModuleIds),
241
+ };
242
+ }
243
+ if (existsSync(SNAPSHOT_DIR) && existsSync(MANIFEST_PATH)) {
244
+ const manifest = JSON.parse(readFileSync(MANIFEST_PATH, 'utf8'));
245
+ if (manifest?.manifestVersion !== 2 || !Array.isArray(manifest?.resolvedModules)) {
246
+ throw new Error('Unsupported baked app-source manifest');
247
+ }
248
+ for (const id of requestedModuleIds) {
249
+ if (!manifest.resolvedModules.includes(id)) {
250
+ throw new Error(`Baked app-source snapshot does not contain requested module: ${id}`);
251
+ }
252
+ }
253
+ return {
254
+ baseDir: SNAPSHOT_DIR,
255
+ manifest,
256
+ };
257
+ }
258
+ throw new Error(`No baked app-source snapshot and Nimi Lab source missing: ${SOURCE_APP_DIR}`);
259
+ }
260
+
261
+ function readAppSourceFile(baseDir, relativePath) {
262
+ return readFileSync(path.join(baseDir, relativePath), 'utf8');
263
+ }
264
+
265
+ export {
266
+ APP_TOOLS_ROOT,
267
+ IDENTITY_REPLACEMENT_ORDER,
268
+ MANIFEST_PATH,
269
+ SNAPSHOT_DIR,
270
+ SOURCE_APP_DIR,
271
+ SOURCE_IDENTITY,
272
+ STRUCTURED_FILE_PATHS,
273
+ WORKBENCH_CORE_SOURCE_ROOT,
274
+ applySnapshot,
275
+ buildManifest,
276
+ classifyFile,
277
+ collectSnapshotFiles,
278
+ readAppSourceFile,
279
+ resolveAppSource,
280
+ sourceRootsForModuleIds,
281
+ };
282
+
283
+ function main(argv) {
284
+ if (!argv.includes('--apply')) {
285
+ process.stderr.write('Usage: sync-app-source.mjs --apply\n');
286
+ process.exit(1);
287
+ }
288
+ const files = applySnapshot();
289
+ process.stdout.write(`[sync-app-source] baked ${files.length} files from apps/lab into templates/app-source\n`);
290
+ }
291
+
292
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
293
+ try {
294
+ main(process.argv.slice(2));
295
+ } catch (error) {
296
+ const message = error instanceof Error ? error.message : String(error || 'unknown error');
297
+ process.stderr.write(`[sync-app-source] failed: ${message}\n`);
298
+ process.exit(1);
299
+ }
300
+ }
@@ -0,0 +1,91 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readFileSync, writeFileSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ import { validateAppScaffoldCargoDependencyValue } from '../lib/app-scaffold-capabilities.mjs';
8
+
9
+ const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
10
+ const APP_TOOLS_ROOT = path.resolve(SCRIPT_DIR, '..');
11
+ const REPO_ROOT = path.resolve(APP_TOOLS_ROOT, '..');
12
+ const APP_TOOLS_MANIFEST_PATH = path.join(APP_TOOLS_ROOT, 'package.json');
13
+
14
+ function readJson(relativePath) {
15
+ return JSON.parse(readFileSync(path.join(REPO_ROOT, relativePath), 'utf8'));
16
+ }
17
+
18
+ function requiredString(value, label) {
19
+ if (typeof value !== 'string' || !value.trim() || value !== value.trim()) {
20
+ throw new Error(`Scaffold version source is invalid: ${label}`);
21
+ }
22
+ return value;
23
+ }
24
+
25
+ function publicPackageRange(manifest, label) {
26
+ return `^${requiredString(manifest.version, `${label}.version`)}`;
27
+ }
28
+
29
+ function nimiShellTauriVersion() {
30
+ const cargo = readFileSync(path.join(REPO_ROOT, 'kit/shell/tauri/Cargo.toml'), 'utf8');
31
+ if (!/^name\s*=\s*"nimi-shell-tauri"\s*$/mu.test(cargo)) {
32
+ throw new Error('Scaffold version source is invalid: kit/shell/tauri package name');
33
+ }
34
+ const match = cargo.match(/^version\s*=\s*"([^"]+)"\s*$/mu);
35
+ const version = requiredString(match?.[1], 'kit/shell/tauri.version');
36
+ validateAppScaffoldCargoDependencyValue(version, 'kit/shell/tauri.version');
37
+ return version;
38
+ }
39
+
40
+ export function buildScaffoldVersionProjection() {
41
+ const rootManifest = readJson('package.json');
42
+ const appToolsManifest = readJson('app-tools/package.json');
43
+ const sdkManifest = readJson('sdks/typescript/package.json');
44
+ const kitManifest = readJson('kit/package.json');
45
+ const current = appToolsManifest.nimiScaffoldVersions;
46
+ if (!current || typeof current !== 'object' || Array.isArray(current)) {
47
+ throw new Error('app-tools package manifest is missing nimiScaffoldVersions');
48
+ }
49
+ return Object.freeze({
50
+ ...current,
51
+ sdkVersion: publicPackageRange(sdkManifest, '@nimiplatform/sdk'),
52
+ appToolsVersion: publicPackageRange(appToolsManifest, '@nimiplatform/app-tools'),
53
+ nimicodingVersion: requiredString(
54
+ rootManifest.devDependencies?.['@nimiplatform/nimi-coding'],
55
+ 'root.devDependencies.@nimiplatform/nimi-coding',
56
+ ),
57
+ kitVersion: publicPackageRange(kitManifest, '@nimiplatform/kit'),
58
+ nimiShellTauriVersion: nimiShellTauriVersion(),
59
+ packageManager: requiredString(rootManifest.packageManager, 'root.packageManager'),
60
+ });
61
+ }
62
+
63
+ export function syncScaffoldVersionProjection({ apply }) {
64
+ const appToolsManifest = readJson('app-tools/package.json');
65
+ const expected = buildScaffoldVersionProjection();
66
+ if (JSON.stringify(appToolsManifest.nimiScaffoldVersions) === JSON.stringify(expected)) {
67
+ return { changed: false, projection: expected };
68
+ }
69
+ if (!apply) throw new Error('app-tools nimiScaffoldVersions is stale; run pnpm --filter @nimiplatform/app-tools build');
70
+ appToolsManifest.nimiScaffoldVersions = expected;
71
+ writeFileSync(APP_TOOLS_MANIFEST_PATH, `${JSON.stringify(appToolsManifest, null, 2)}\n`);
72
+ return { changed: true, projection: expected };
73
+ }
74
+
75
+ function main(argv) {
76
+ const apply = argv.includes('--apply');
77
+ const check = argv.includes('--check');
78
+ if (apply === check) throw new Error('Usage: sync-scaffold-versions.mjs --apply | --check');
79
+ const result = syncScaffoldVersionProjection({ apply });
80
+ process.stdout.write(`[sync-scaffold-versions] ${result.changed ? 'updated' : 'verified'} app-tools package projection\n`);
81
+ }
82
+
83
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
84
+ try {
85
+ main(process.argv.slice(2));
86
+ } catch (error) {
87
+ const message = error instanceof Error ? error.message : String(error || 'unknown error');
88
+ process.stderr.write(`[sync-scaffold-versions] failed: ${message}\n`);
89
+ process.exit(1);
90
+ }
91
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nimi Network Limited
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,100 @@
1
+ import type {
2
+ NimiPortableAppAIConfig,
3
+ NimiPortableAppAIConfigIntent,
4
+ } from '@nimiplatform/sdk/ai';
5
+ import { runtimeAIConfigStructToJson } from '@nimiplatform/sdk/ai';
6
+
7
+ export type StudioAIConfigClient = {
8
+ get(): Promise<NimiPortableAppAIConfig | null>;
9
+ };
10
+
11
+ export type StudioAIConfigRefreshEventTarget = {
12
+ addEventListener(type: string, listener: EventListener): void;
13
+ removeEventListener(type: string, listener: EventListener): void;
14
+ };
15
+
16
+ export type StudioAIConfigVisibilityTarget = StudioAIConfigRefreshEventTarget & {
17
+ readonly visibilityState: string;
18
+ };
19
+
20
+ export async function loadStudioAIConfig(
21
+ client: Pick<StudioAIConfigClient, 'get'>,
22
+ expectedAppId: string,
23
+ ): Promise<NimiPortableAppAIConfig | null> {
24
+ try {
25
+ const config = await client.get();
26
+ return config ? requireStudioAIConfigOwner(config, expectedAppId) : null;
27
+ } catch (error) {
28
+ if (isStudioAIConfigNotFound(error)) return null;
29
+ throw error;
30
+ }
31
+ }
32
+
33
+ export function subscribeStudioAIConfigRefresh(
34
+ refresh: () => void,
35
+ focusTarget: StudioAIConfigRefreshEventTarget,
36
+ visibilityTarget: StudioAIConfigVisibilityTarget,
37
+ ): () => void {
38
+ const onFocus: EventListener = () => refresh();
39
+ const onVisibilityChange: EventListener = () => {
40
+ if (visibilityTarget.visibilityState === 'visible') refresh();
41
+ };
42
+ focusTarget.addEventListener('focus', onFocus);
43
+ visibilityTarget.addEventListener('visibilitychange', onVisibilityChange);
44
+ return () => {
45
+ focusTarget.removeEventListener('focus', onFocus);
46
+ visibilityTarget.removeEventListener('visibilitychange', onVisibilityChange);
47
+ };
48
+ }
49
+
50
+ export function requireStudioAIConfigOwner(
51
+ config: NimiPortableAppAIConfig,
52
+ expectedAppId: string,
53
+ ): NimiPortableAppAIConfig {
54
+ const normalizedAppId = expectedAppId.trim();
55
+ if (!normalizedAppId || normalizedAppId !== expectedAppId) {
56
+ throw new Error('AI Studio requires an exact canonical App ID.');
57
+ }
58
+ const owner = config.owner?.owner;
59
+ if (!owner || owner.oneofKind !== 'app' || !('app' in owner) || owner.app.appId !== normalizedAppId) {
60
+ throw new Error(`AIConfig owner must be the exact ${normalizedAppId} App.`);
61
+ }
62
+ return config;
63
+ }
64
+
65
+ export function findStudioCapabilityIntent(
66
+ config: NimiPortableAppAIConfig | null,
67
+ capabilityContract: string,
68
+ ): NimiPortableAppAIConfigIntent | null {
69
+ return config?.capabilities.find(
70
+ (intent) => intent.capabilityContract === capabilityContract,
71
+ ) ?? null;
72
+ }
73
+
74
+ export function studioCloudIntentHasExactTarget(
75
+ intent: NimiPortableAppAIConfigIntent,
76
+ ): boolean {
77
+ if (intent.route.oneofKind !== 'cloud') return false;
78
+ const route = intent.route;
79
+ if (!('cloud' in route)) return false;
80
+ const target = runtimeAIConfigStructToJson(route.cloud.providerModelTarget);
81
+ const exactText = (value: unknown): boolean => (
82
+ typeof value === 'string' && value.length > 0 && value.trim() === value
83
+ );
84
+ return exactText(route.cloud.connectorRef)
85
+ && !Object.hasOwn(target, 'model')
86
+ && exactText(target.provider)
87
+ && exactText(target.providerModelId)
88
+ && exactText(target.remoteModelCatalogId);
89
+ }
90
+
91
+ function isStudioAIConfigNotFound(error: unknown): boolean {
92
+ if (!error || typeof error !== 'object') return false;
93
+ const record = error as Record<string, unknown>;
94
+ const reason = typeof record.reasonCode === 'string'
95
+ ? record.reasonCode
96
+ : typeof record.code === 'string'
97
+ ? record.code
98
+ : '';
99
+ return reason.trim().toUpperCase().replaceAll('-', '_') === 'AI_CONFIG_NOT_FOUND';
100
+ }