@nimiplatform/app-tools 0.13.1 → 0.16.0-rc.9

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 (100) hide show
  1. package/README.md +65 -8
  2. package/bin/nimi-app.mjs +26 -10
  3. package/lib/app-access-declaration.mjs +3 -0
  4. package/lib/app-dependency-combinations.mjs +70 -20
  5. package/lib/app-doctor-update.mjs +95 -36
  6. package/lib/app-host-support.mjs +6 -0
  7. package/lib/app-icons.mjs +181 -0
  8. package/lib/app-identifiers.mjs +27 -0
  9. package/lib/app-info.mjs +21 -33
  10. package/lib/app-lifecycle-guidance.mjs +2 -1
  11. package/lib/app-pack.mjs +14 -36
  12. package/lib/app-project-lifecycle.mjs +141 -243
  13. package/lib/app-scaffold-capabilities.mjs +13 -109
  14. package/lib/app-scaffold-profiles.mjs +108 -117
  15. package/lib/app-scaffold.mjs +70 -165
  16. package/lib/app-toolchain-updates.mjs +45 -0
  17. package/lib/canonical-capability-ids.generated.mjs +2 -0
  18. package/lib/development-environment.d.mts +10 -0
  19. package/lib/development-environment.mjs +39 -0
  20. package/lib/hosted-web-release.mjs +98 -0
  21. package/lib/index.mjs +40 -1
  22. package/lib/mobile-development.mjs +19 -0
  23. package/lib/realm-environments.generated.mjs +5 -0
  24. package/lib/web-coordination.mjs +59 -0
  25. package/lib/web-development.d.mts +23 -0
  26. package/lib/web-development.mjs +118 -0
  27. package/lib/web-scaffold.mjs +125 -0
  28. package/package.json +39 -27
  29. package/scripts/dev-shell.mjs +4 -1
  30. package/scripts/sync-scaffold-versions.mjs +0 -2
  31. package/skills/nimi-app-lifecycle/SKILL.md +13 -5
  32. package/skills/nimi-app-lifecycle/references/acceptance.md +6 -2
  33. package/skills/nimi-app-lifecycle/references/adapt.md +7 -3
  34. package/skills/nimi-app-lifecycle/references/audit.md +3 -2
  35. package/skills/nimi-app-lifecycle/references/create.md +8 -2
  36. package/skills/nimi-app-lifecycle/references/release.md +2 -0
  37. package/skills/nimi-app-lifecycle/references/upgrade-platform.md +15 -1
  38. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +87 -52
  39. package/templates/app-source/src/ai-studio-core/history-policy.ts +45 -11
  40. package/templates/app-source/src/ai-studio-core/history.ts +22 -11
  41. package/templates/app-source/src/ai-studio-core/host-context.tsx +9 -4
  42. package/templates/app-source/src/ai-studio-core/index.ts +2 -0
  43. package/templates/app-source/src/ai-studio-core/job-recovery-panel.tsx +15 -5
  44. package/templates/app-source/src/ai-studio-core/job-recovery.ts +2 -2
  45. package/templates/app-source/src/ai-studio-core/messages/en.json +79 -19
  46. package/templates/app-source/src/ai-studio-core/messages/zh.json +79 -19
  47. package/templates/app-source/src/ai-studio-core/module-registration.ts +1 -0
  48. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +40 -5
  49. package/templates/app-source/src/ai-studio-core/parameter-fields.tsx +12 -6
  50. package/templates/app-source/src/ai-studio-core/parameters.ts +4 -0
  51. package/templates/app-source/src/ai-studio-core/prompt-drafts.ts +42 -0
  52. package/templates/app-source/src/ai-studio-core/runtime-types.ts +9 -2
  53. package/templates/app-source/src/ai-studio-core/runtime.ts +8 -4
  54. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +98 -90
  55. package/templates/app-source/src/ai-studio-core/section-ai-testing-exchange-result.tsx +1 -1
  56. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +205 -48
  57. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +1 -0
  58. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +36 -14
  59. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +102 -77
  60. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +62 -16
  61. package/templates/app-source/src/ai-studio-core/section-ai-testing-session-result.tsx +2 -0
  62. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +12 -21
  63. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcription-result.tsx +26 -9
  64. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-result.tsx +3 -3
  65. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +182 -81
  66. package/templates/app-source/src/ai-studio-core/workspace.tsx +49 -22
  67. package/templates/app-source/src/product-modules/agent-center/index.tsx +2 -3
  68. package/templates/app-source/src/product-modules/agent-conversation/index.tsx +2 -3
  69. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +17 -3
  70. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +17 -3
  71. package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +33 -1
  72. package/templates/app-source/src/studio-modules/studio-create/parameters.ts +3 -1
  73. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +47 -4
  74. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +59 -8
  75. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +59 -8
  76. package/templates/app-source/src/studio-modules/studio-media/music-parameters.tsx +2 -1
  77. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +271 -83
  78. package/templates/app-source/src/studio-modules/studio-media/parameters.ts +120 -2
  79. package/templates/app-source/src/studio-modules/studio-media/registration.ts +1 -0
  80. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +24 -14
  81. package/templates/app-source/src/studio-modules/studio-voice/descriptors.ts +1 -1
  82. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +3 -2
  83. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +3 -2
  84. package/templates/app-source/src/studio-modules/studio-voice/parameter-panel.tsx +46 -23
  85. package/templates/app-source/src/studio-modules/studio-voice/registration.ts +2 -1
  86. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +2 -2
  87. package/templates/app-source/src/workbench-core/workbench-core.tsx +27 -3
  88. package/templates/default-starter/AGENTS.md +8 -5
  89. package/templates/default-starter/NIMI_APP.md +7 -0
  90. package/templates/default-starter/README.md +3 -1
  91. package/templates/default-starter/src/shell/App.tsx +12 -20
  92. package/templates/default-starter/src/shell/auth/local-app-client.ts +6 -15
  93. package/templates/default-starter/src/shell/auth/runtime-platform.ts +7 -107
  94. package/templates/default-starter/src/shell/workbench-target-adapter.ts +9 -126
  95. package/templates/default-starter.manifest.json +4 -16
  96. package/templates/hosted-web-release.yml +88 -0
  97. package/templates/default-starter/src-tauri/Cargo.toml +0 -17
  98. package/templates/default-starter/src-tauri/build.rs +0 -32
  99. package/templates/default-starter/src-tauri/capabilities/default.json +0 -7
  100. package/templates/default-starter/src-tauri/tauri.conf.json +0 -26
@@ -1,6 +1,11 @@
1
+ import { isAppId } from './app-identifiers.mjs';
2
+ import { readWebDevelopment } from './web-development.mjs';
3
+ import { readMobileDevelopment } from './mobile-development.mjs';
1
4
  import { APP_AUTHOR_DECLARATION_FIELDS, hashScaffoldManagedContent } from './app-scaffold.mjs';
5
+ import { readAppIntroduction } from './app-info.mjs';
2
6
  import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
3
7
  import path from 'node:path';
8
+ import { minVersion } from 'semver';
4
9
  import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
5
10
  import {
6
11
  buildAppScaffoldSnapshotFromIntent,
@@ -15,8 +20,8 @@ import {
15
20
  } from './app-scaffold.mjs';
16
21
  import { assertManifestAppAccessDeclaration } from './app-access-declaration.mjs';
17
22
  import { assertLifecycleGuidanceCurrent, LIFECYCLE_SKILL_PATH, lifecycleOwnerSteps, planLifecycleGuidance } from './app-lifecycle-guidance.mjs';
18
- import { applyProjectFiles, describeChanges, plannedFile } from './app-project-files.mjs';
19
- import { resolveDependencyCombination } from './app-dependency-combinations.mjs';
23
+ import { applyProjectFiles, assertProjectOutputPath, describeChanges, plannedFile } from './app-project-files.mjs';
24
+ import { appToolsDeclaration, matchesRecordedHostDependencies, resolveDependencyCombination } from './app-dependency-combinations.mjs';
20
25
 
21
26
  const SCAN_EXCLUDED_DIRS = new Set([
22
27
  '.git',
@@ -206,9 +211,39 @@ function expectedSnapshotFromLock(lock, versions, intent, targetDir, options = {
206
211
  if (stableStringify(intent.directFeatures) !== stableStringify(lock.directFeatures)) {
207
212
  throw new Error('Scaffold feature selection is immutable; create a fresh scaffold for a different feature closure');
208
213
  }
214
+ if (versions.source === 'existing') retainMatchingHostFiles(targetDir, lock, snapshot, versions);
209
215
  return snapshot;
210
216
  }
211
217
 
218
+ // A maintained SDK/Kit pair can predate APIs imported by today's generated
219
+ // renderer and Host. Its checked-in wiring also binds the App-owned feature
220
+ // modules. Carry it forward only with the original paths, class and digest.
221
+ function retainMatchingHostFiles(targetDir, lock, snapshot, versions) {
222
+ const matrix = lock.dependencyMatrix;
223
+ const migration = 'Migrate the App-owned feature modules and matching Host with the selected SDK/Kit before sync.';
224
+ if (!matchesRecordedHostDependencies(matrix.npm, versions)) {
225
+ throw new Error(migration);
226
+ }
227
+ assertSameJson(lock.hostAdapterContracts, snapshot.lock.hostAdapterContracts, 'Scaffold host adapter contracts');
228
+ snapshot.retainedHostFiles = [];
229
+ snapshot.filesWithoutLock = snapshot.filesWithoutLock.map(file => {
230
+ const expected = snapshot.lock.managedFileHashes[file.path];
231
+ if (!expected || !/^(?:src\/|src-electron\/|vite\.config\.ts$)/u.test(file.path)) return file;
232
+ const recorded = lock.managedFileHashes?.[file.path];
233
+ if (!recorded || recorded.class !== expected.class) throw new Error(`${file.path}: ${migration}`);
234
+ const absolute = path.join(targetDir, file.path);
235
+ assertProjectOutputPath(targetDir, absolute);
236
+ const content = existsSync(absolute) ? readFileSync(absolute) : null;
237
+ if (!content || hashScaffoldManagedContent(file.path, content) !== recorded.sha256) {
238
+ throw new Error(`Managed scaffold drift detected: ${file.path}. Restore its locked source before sync.`);
239
+ }
240
+ if (recorded.sha256 === expected.sha256) return file;
241
+ snapshot.lock.managedFileHashes[file.path] = { ...expected, sha256: recorded.sha256 };
242
+ snapshot.retainedHostFiles.push(file.path);
243
+ return { ...file, content };
244
+ });
245
+ }
246
+
212
247
  function readContentForHash(filePath) {
213
248
  return readFileSync(filePath);
214
249
  }
@@ -442,26 +477,6 @@ function assertRequiredSupportFiles(targetDir, snapshot) {
442
477
  if (missing.length > 0) {
443
478
  throw new Error(`Missing required scaffold support files: ${missing.join(', ')}`);
444
479
  }
445
-
446
- const tauriConfig = JSON.parse(readFileSync(path.join(targetDir, 'src-tauri/tauri.conf.json'), 'utf8'));
447
- const icons = tauriConfig?.bundle?.icon;
448
- if (!Array.isArray(icons) || icons.join(',') !== 'icons/icon.png,icons/icon.ico') {
449
- throw new Error('Tauri icon support drift: bundle.icon must be ["icons/icon.png","icons/icon.ico"]');
450
- }
451
- const icon = readFileSync(path.join(targetDir, 'src-tauri/icons/icon.png'));
452
- const pngSignature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
453
- if (icon.length !== 68 || pngSignature.some((value, index) => icon[index] !== value)) {
454
- throw new Error('Tauri icon support drift: src-tauri/icons/icon.png is not the scaffold PNG');
455
- }
456
- const ico = readFileSync(path.join(targetDir, 'src-tauri/icons/icon.ico'));
457
- const icoHeader = [0x00, 0x00, 0x01, 0x00, 0x01, 0x00];
458
- if (
459
- ico.length !== 90
460
- || icoHeader.some((value, index) => ico[index] !== value)
461
- || pngSignature.some((value, index) => ico[index + 22] !== value)
462
- ) {
463
- throw new Error('Tauri icon support drift: src-tauri/icons/icon.ico is not the scaffold ICO');
464
- }
465
480
  }
466
481
 
467
482
  function usesAppOwnedRenderer(targetDir, plannedSources) {
@@ -484,9 +499,8 @@ function assertProjectConfiguration(targetDir, parsedManifest = null, managed =
484
499
  throw new Error(`Submitted manifest YAML cannot be parsed: ${error instanceof Error ? error.message : String(error)}`);
485
500
  }
486
501
  }
487
- const rendererOrigin = assertElectronLocalDevelopmentManifest(document);
488
- assertDeclaredHostSourceDirectory(targetDir, document);
489
- assertOfficialDevelopmentEntrypoints(targetDir, rendererOrigin, undefined, managed || !usesAppOwnedRenderer(targetDir));
502
+ readAppIntroduction(targetDir, document);
503
+ assertCarrierDevelopmentInputs(targetDir, document, readJsonFile(path.join(targetDir, 'package.json')), managed);
490
504
  }
491
505
 
492
506
  function assertElectronLocalDevelopmentManifest(document) {
@@ -589,11 +603,27 @@ function assertNimicodingProjectionCurrent(targetDir, runners) {
589
603
  }
590
604
  }
591
605
 
606
+ function assertCarrierDevelopmentInputs(targetDir, manifest, packageJson, managed, plannedSources) {
607
+ if (manifest.local_development && Object.hasOwn(manifest.local_development, 'mobile')) readMobileDevelopment(manifest, packageJson);
608
+ if (manifest.platform === 'web' || (manifest.local_development && Object.hasOwn(manifest.local_development, 'web'))) {
609
+ const declaration = manifest.local_development.web;
610
+ const script = /^pnpm run ([A-Za-z0-9][A-Za-z0-9:_.-]*)$/u.exec(declaration?.command || '')?.[1];
611
+ if (!script || !packageJson.scripts?.[script] || /\bnimi-app\s+dev\b/u.test(packageJson.scripts[script])) throw new Error('Web dev requires a non-recursive App-owned renderer script.');
612
+ if (manifest.platform === 'web' || declaration.origin || declaration.redirect_uri || declaration.client_id) readWebDevelopment(manifest);
613
+ if (declaration.local) readWebDevelopment(manifest, { realm: 'local' });
614
+ }
615
+ if (manifest.platform !== 'web') {
616
+ if (manifest.platform !== undefined && manifest.platform !== 'desktop') throw new Error('Unsupported App platform.');
617
+ const rendererOrigin = assertElectronLocalDevelopmentManifest(manifest);
618
+ assertDeclaredHostSourceDirectory(targetDir, manifest);
619
+ assertOfficialDevelopmentEntrypoints(targetDir, rendererOrigin, packageJson, managed || !usesAppOwnedRenderer(targetDir, plannedSources));
620
+ }
621
+ }
622
+
592
623
  export function validateAppProjectInputs(targetDir, manifest, packageJson, managed = false, plannedSources) {
593
624
  assertManifestAppAccessDeclaration(stringifyYaml(manifest), 'nimi.app.yaml');
594
- const rendererOrigin = assertElectronLocalDevelopmentManifest(manifest);
595
- assertDeclaredHostSourceDirectory(targetDir, manifest);
596
- assertOfficialDevelopmentEntrypoints(targetDir, rendererOrigin, packageJson, managed || !usesAppOwnedRenderer(targetDir, plannedSources));
625
+ readAppIntroduction(targetDir, manifest);
626
+ assertCarrierDevelopmentInputs(targetDir, manifest, packageJson, managed, plannedSources);
597
627
  const findings = scanForbiddenPatterns(targetDir, manifest.profile, managed ? null : LOCAL_DEVELOPMENT_BYPASS_LABELS, plannedSources);
598
628
  if (findings.length) throw new Error(`Forbidden App source patterns: ${findings.join('; ')}`);
599
629
  }
@@ -666,7 +696,7 @@ function validateExistingSubmittedApp(targetDir) {
666
696
  }
667
697
  const appId = typeof parsed?.app_id === 'string' ? parsed.app_id.trim() : '';
668
698
  const profile = typeof parsed?.profile === 'string' ? parsed.profile.trim() : '';
669
- if (!appId || appId !== parsed?.app_id || !SUPPORTED_APP_SCAFFOLD_PROFILES.includes(profile)) {
699
+ if (!isAppId(appId) || appId !== parsed?.app_id || !SUPPORTED_APP_SCAFFOLD_PROFILES.includes(profile)) {
670
700
  throw new Error('Existing submitted app requires canonical app_id and supported profile');
671
701
  }
672
702
  if (parsed?.manifest_role !== 'submitted-input') {
@@ -694,19 +724,40 @@ export function initApp(cwd, options = {}, versions, runners = {}) {
694
724
  // Create still uses the tool default. An explicit listed selection before
695
725
  // first init refreshes derived glue through this owner, just as sync does.
696
726
  // Check the original generated files before projecting the selected pair.
697
- const original = buildAppScaffoldSnapshotFromIntent({ intent, versions, targetDir });
698
- const combination = resolveDependencyCombination(readJsonFile(path.join(targetDir, 'package.json')), versions);
699
- const effective = { ...versions, ...combination };
727
+ const pkg = readJsonFile(path.join(targetDir, 'package.json'));
728
+ const creatorSpec = intent?.dependencyMatrix?.npm?.['@nimiplatform/app-tools'];
729
+ const compatiblePatch = typeof creatorSpec === 'string' && creatorSpec !== versions.appToolsVersion
730
+ && appToolsDeclaration(creatorSpec, versions.appToolsVersion) === creatorSpec;
731
+ const creatorVersions = compatiblePatch
732
+ ? { ...versions, ...resolveDependencyCombination({ dependencies: intent.dependencyMatrix.npm }, versions) }
733
+ : versions;
734
+ const original = buildAppScaffoldSnapshotFromIntent({ intent, versions: creatorVersions, targetDir, refreshInitialDependencies: compatiblePatch });
735
+ const combination = resolveDependencyCombination(pkg, versions);
736
+ const appToolsVersion = appToolsDeclaration(pkg.devDependencies?.['@nimiplatform/app-tools'], versions.appToolsVersion);
737
+ const effective = { ...versions, ...combination, appToolsVersion };
700
738
  const snapshot = buildAppScaffoldSnapshotFromIntent({ intent, versions: effective, targetDir, refreshDerived: true });
739
+ if (combination.source === 'existing'
740
+ && !matchesRecordedHostDependencies(intent.dependencyMatrix.npm, combination)) {
741
+ throw new Error('The selected SDK/Kit requires a different Host. Initialize with the creator combination or migrate the Host and App-owned feature modules together.');
742
+ }
701
743
  validateAppProjectInputs(targetDir, currentManifest, readJsonFile(path.join(targetDir, 'package.json')), true);
702
744
  const initializedPaths = new Set(snapshot.initFiles.map((file) => file.path));
703
- assertManagedFilesCurrent(targetDir, { managedFileHashes: Object.fromEntries(Object.entries(original.lock.managedFileHashes).filter(([relativePath]) => !initializedPaths.has(relativePath))) });
745
+ const initialFiles = Object.entries(original.lock.managedFileHashes).filter(([relativePath]) =>
746
+ !initializedPaths.has(relativePath) && !(compatiblePatch && relativePath === SCAFFOLD_INTENT_PATH));
747
+ try {
748
+ assertManagedFilesCurrent(targetDir, { managedFileHashes: Object.fromEntries(initialFiles) });
749
+ } catch (cause) {
750
+ if (!compatiblePatch) throw cause;
751
+ throw new Error(`${cause.message}. Review the listed files. For an untouched scaffold from a different generator, run nimi-app init with its exact creator ${minVersion(creatorSpec).version} (published package or original tarball), then sync with the selected tool.`, { cause });
752
+ }
704
753
  const managedFiles = snapshot.filesWithoutLock.filter((file) => snapshot.lock.managedFileHashes[file.path]);
705
754
  const planned = [...managedFiles.map((file) => {
706
755
  let content = file.content;
707
756
  if (file.path === 'nimi.app.yaml' && currentManifest) {
708
757
  const next = parseYaml(content);
709
758
  for (const field of APP_AUTHOR_DECLARATION_FIELDS) if (Object.hasOwn(currentManifest, field)) next[field] = currentManifest[field];
759
+ if (currentManifest.local_development?.web) next.local_development = { ...next.local_development, web: currentManifest.local_development.web };
760
+ if (currentManifest.local_development?.mobile) next.local_development = { ...next.local_development, mobile: currentManifest.local_development.mobile };
710
761
  content = stringifyYaml(next, { lineWidth: 0 });
711
762
  }
712
763
  return plannedFile(targetDir, file.path, content);
@@ -791,7 +842,13 @@ function collectExpectedClasses(snapshot) {
791
842
  // A lock written by an earlier scaffold version can still list a file that the
792
843
  // current generator creates once for the App to own. Only the declared paths
793
844
  // may change owner, and only from managed glue to App-owned product code.
845
+ const RETIRED_TAURI_GLUE = new Set([
846
+ 'src-tauri/Cargo.toml', 'src-tauri/build.rs', 'src-tauri/capabilities/default.json',
847
+ 'src-tauri/tauri.conf.json', 'src-tauri/src/main.rs', 'src-tauri/icons/icon.png', 'src-tauri/icons/icon.ico',
848
+ ]);
849
+
794
850
  function isAppOwnedHandover(relativePath, lockedEntry, current) {
851
+ if (!current && RETIRED_TAURI_GLUE.has(relativePath)) return lockedEntry?.class === 'scaffold-managed glue';
795
852
  return SCAFFOLD_APP_OWNED_HANDOVER_PATHS.includes(relativePath)
796
853
  && lockedEntry?.class === 'scaffold-managed glue'
797
854
  && current?.owner === 'app-owned'
@@ -832,14 +889,14 @@ function assertNoClassificationConflict(lock, snapshot, targetDir) {
832
889
  handovers.push(describeAppOwnedHandover(targetDir, relativePath, entry));
833
890
  continue;
834
891
  }
835
- throw new Error(`Scaffold classification conflict: ${relativePath}`);
892
+ throw new Error(`Scaffold classification conflict: ${relativePath}. Review its ownership and restore the matching scaffold lock before sync.`);
836
893
  }
837
894
  for (const [relativePath, entry] of Object.entries(lock.appOwnedInitialHashes || {})) {
838
895
  const current = currentClasses.get(relativePath);
839
896
  if (current?.owner === 'app-owned' && current.class === entry.class) {
840
897
  continue;
841
898
  }
842
- throw new Error(`Scaffold classification conflict: ${relativePath}`);
899
+ throw new Error(`Scaffold classification conflict: ${relativePath}. Review its ownership and restore the matching scaffold lock before sync.`);
843
900
  }
844
901
  return handovers;
845
902
  }
@@ -879,10 +936,12 @@ export function planManagedAppSync(cwd, options = {}, versions) {
879
936
  if (file.path === 'nimi.app.yaml' && currentManifest) {
880
937
  const next = parseYaml(content);
881
938
  for (const field of APP_AUTHOR_DECLARATION_FIELDS) if (Object.hasOwn(currentManifest, field)) next[field] = currentManifest[field];
939
+ if (currentManifest.local_development?.web) next.local_development = { ...next.local_development, web: currentManifest.local_development.web };
940
+ if (currentManifest.local_development?.mobile) next.local_development = { ...next.local_development, mobile: currentManifest.local_development.mobile };
882
941
  content = stringifyYaml(next, { lineWidth: 0 });
883
942
  }
884
943
  return plannedFile(targetDir, file.path, content);
885
944
  });
886
945
  planned.push(...planLifecycleGuidance(targetDir), plannedFile(targetDir, SCAFFOLD_LOCK_PATH, `${JSON.stringify(snapshot.lock, null, 2)}\n`));
887
- return { targetDir, snapshot, planned, handovers };
946
+ return { targetDir, snapshot, planned, handovers, previousDependencies: lock.dependencyMatrix.npm };
888
947
  }
@@ -0,0 +1,6 @@
1
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-002a
2
+ export function assertDesktopHostSupport(profileRef) {
3
+ if (profileRef === 'tauri-pnpm-vite') {
4
+ throw new Error('tauri-pnpm-vite is unsupported in this release. Use the original Tauri toolchain or explicitly migrate the App to Electron.');
5
+ }
6
+ }
@@ -0,0 +1,181 @@
1
+ import { lstatSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { PNG } from 'pngjs';
4
+ import { parse as parseYaml } from 'yaml';
5
+
6
+ const PNG_SIGNATURE = Buffer.from('89504e470d0a1a0a', 'hex');
7
+
8
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-042a
9
+ export function validateAppIcon(bytes) {
10
+ if (!Buffer.isBuffer(bytes) || bytes.length > 512 * 1024 || !bytes.subarray(0, 8).equals(PNG_SIGNATURE)) {
11
+ throw new Error('App icon must be a PNG of at most 512 KiB');
12
+ }
13
+ let offset = 8;
14
+ let ended = false;
15
+ while (offset + 12 <= bytes.length) {
16
+ const length = bytes.readUInt32BE(offset);
17
+ const type = bytes.toString('ascii', offset + 4, offset + 8);
18
+ if (offset + length + 12 > bytes.length || type === 'acTL') throw new Error('App icon must be a complete static PNG');
19
+ if (offset === 8 && (type !== 'IHDR' || length !== 13)) throw new Error('App icon PNG header is invalid');
20
+ if (type === 'IHDR') {
21
+ const width = bytes.readUInt32BE(offset + 8);
22
+ const height = bytes.readUInt32BE(offset + 12);
23
+ if (width < 128 || width > 1024 || width !== height) throw new Error('App icon must be square, 128–1024 pixels');
24
+ }
25
+ offset += length + 12;
26
+ if (type === 'IEND') { ended = length === 0 && offset === bytes.length; break; }
27
+ }
28
+ if (!ended) throw new Error('App icon PNG is truncated or has trailing content');
29
+ const decoded = PNG.sync.read(bytes, { checkCRC: true });
30
+ for (let index = 3; index < decoded.data.length; index += 4) {
31
+ if (decoded.data[index] !== 0) return bytes;
32
+ }
33
+ throw new Error('App icon is fully transparent; supply actual App artwork');
34
+ }
35
+
36
+ export function readAppIcon(root, { required = true } = {}) {
37
+ const manifest = parseYaml(readFileSync(path.join(root, 'nimi.app.yaml'), 'utf8'));
38
+ const relative = manifest?.metadata?.icon;
39
+ if (relative === undefined && !required) return null;
40
+ if (typeof relative !== 'string' || path.isAbsolute(relative) || relative.includes('\\')
41
+ || relative.includes(':') || relative.split('/').some(part => !part || part === '.' || part === '..')) {
42
+ throw new Error('metadata.icon must name an App-relative resource');
43
+ }
44
+ const file = path.join(root, relative);
45
+ let stat;
46
+ try { stat = lstatSync(file); } catch (error) {
47
+ if (error.code !== 'ENOENT') throw error;
48
+ if (!required) return null;
49
+ throw new Error(`metadata.icon resource is missing: ${relative}`);
50
+ }
51
+ const physicalRelative = path.relative(realpathSync(root), realpathSync(file));
52
+ if (physicalRelative.startsWith(`..${path.sep}`) || physicalRelative === '..' || path.isAbsolute(physicalRelative)
53
+ || !stat.isFile() || stat.isSymbolicLink() || stat.size > 512 * 1024) {
54
+ throw new Error('metadata.icon must be a regular PNG inside the App repository, at most 512 KiB');
55
+ }
56
+ return validateAppIcon(readFileSync(file));
57
+ }
58
+
59
+ // Area sampling in premultiplied alpha avoids dark borders around transparent artwork.
60
+ function resizedPng(source, size) {
61
+ if (size === source.width) return PNG.sync.write(source);
62
+ const target = new PNG({ width: size, height: size });
63
+ const scale = source.width / size;
64
+ for (let y = 0; y < size; y++) {
65
+ for (let x = 0; x < size; x++) {
66
+ const sum = [0, 0, 0, 0];
67
+ if (scale < 1) {
68
+ const sx = Math.max(0, Math.min(source.width - 1, (x + 0.5) * scale - 0.5));
69
+ const sy = Math.max(0, Math.min(source.height - 1, (y + 0.5) * scale - 0.5));
70
+ const x0 = Math.floor(sx), y0 = Math.floor(sy);
71
+ for (const [px, wx] of [[x0, 1 - (sx - x0)], [Math.min(x0 + 1, source.width - 1), sx - x0]]) {
72
+ for (const [py, wy] of [[y0, 1 - (sy - y0)], [Math.min(y0 + 1, source.height - 1), sy - y0]]) {
73
+ const offset = (py * source.width + px) * 4;
74
+ const alpha = source.data[offset + 3] * wx * wy;
75
+ for (let channel = 0; channel < 3; channel++) sum[channel] += source.data[offset + channel] * alpha;
76
+ sum[3] += alpha;
77
+ }
78
+ }
79
+ const offset = (y * size + x) * 4;
80
+ for (let channel = 0; channel < 3; channel++) target.data[offset + channel] = sum[3] ? Math.round(sum[channel] / sum[3]) : 0;
81
+ target.data[offset + 3] = Math.round(sum[3]);
82
+ continue;
83
+ }
84
+ for (let sy = Math.floor(y * scale); sy < Math.ceil((y + 1) * scale); sy++) {
85
+ const wy = Math.min(sy + 1, (y + 1) * scale) - Math.max(sy, y * scale);
86
+ for (let sx = Math.floor(x * scale); sx < Math.ceil((x + 1) * scale); sx++) {
87
+ const weight = wy * (Math.min(sx + 1, (x + 1) * scale) - Math.max(sx, x * scale));
88
+ const offset = (sy * source.width + sx) * 4;
89
+ const alpha = source.data[offset + 3] * weight;
90
+ for (let channel = 0; channel < 3; channel++) sum[channel] += source.data[offset + channel] * alpha;
91
+ sum[3] += alpha;
92
+ }
93
+ }
94
+ const offset = (y * size + x) * 4;
95
+ for (let channel = 0; channel < 3; channel++) target.data[offset + channel] = sum[3] ? Math.round(sum[channel] / sum[3]) : 0;
96
+ target.data[offset + 3] = Math.round(sum[3] / (scale * scale));
97
+ }
98
+ }
99
+ return PNG.sync.write(target);
100
+ }
101
+
102
+ // metadata.icon is portable in-product artwork. Only the macOS native export
103
+ // receives a platform tile and outer margin; never feed this back into app-info.
104
+ export function createMacIconPng(bytes) {
105
+ const source = PNG.sync.read(validateAppIcon(bytes));
106
+ const artwork = PNG.sync.read(resizedPng(source, 824));
107
+ const target = new PNG({ width: 1024, height: 1024 });
108
+ for (let y = 0; y < 824; y++) for (let x = 0; x < 824; x++) {
109
+ // A continuous rounded-square silhouette with antialiased edge coverage.
110
+ let coverage = 0;
111
+ for (const dy of [0.125, 0.375, 0.625, 0.875]) for (const dx of [0.125, 0.375, 0.625, 0.875]) {
112
+ if (Math.pow(Math.abs((x + dx - 412) / 412), 5)
113
+ + Math.pow(Math.abs((y + dy - 412) / 412), 5) <= 1) coverage += 1 / 16;
114
+ }
115
+ if (!coverage) continue;
116
+ const from = (y * 824 + x) * 4;
117
+ const to = ((y + 100) * 1024 + x + 100) * 4;
118
+ const alpha = artwork.data[from + 3] / 255;
119
+ const fraction = y / 823;
120
+ const background = [248 - 13 * fraction, 250 - 12 * fraction, 252 - 9 * fraction];
121
+ for (let channel = 0; channel < 3; channel++) {
122
+ target.data[to + channel] = Math.round(artwork.data[from + channel] * alpha + background[channel] * (1 - alpha));
123
+ }
124
+ target.data[to + 3] = Math.round(255 * coverage);
125
+ }
126
+ return PNG.sync.write(target);
127
+ }
128
+
129
+ export function encodeWindowsIcon(bytes) {
130
+ const source = PNG.sync.read(validateAppIcon(bytes));
131
+ const sizes = [16, 20, 24, 30, 32, 36, 40, 48, 60, 64, 72, 80, 96, 128, 256];
132
+ const images = sizes.map(size => resizedPng(source, size));
133
+ const directory = Buffer.alloc(6 + sizes.length * 16);
134
+ directory.writeUInt16LE(1, 2);
135
+ directory.writeUInt16LE(sizes.length, 4);
136
+ let position = directory.length;
137
+ sizes.forEach((size, index) => {
138
+ const offset = 6 + index * 16;
139
+ directory[offset] = directory[offset + 1] = size === 256 ? 0 : size;
140
+ directory.writeUInt16LE(1, offset + 4);
141
+ directory.writeUInt16LE(32, offset + 6);
142
+ directory.writeUInt32LE(images[index].length, offset + 8);
143
+ directory.writeUInt32LE(position, offset + 12);
144
+ position += images[index].length;
145
+ });
146
+ return Buffer.concat([directory, ...images]);
147
+ }
148
+
149
+ export function encodeMacIcon(bytes) {
150
+ const source = PNG.sync.read(createMacIconPng(bytes));
151
+ const chunks = [[16, 'icp4'], [32, 'ic11'], [32, 'icp5'], [64, 'ic12'],
152
+ [128, 'ic07'], [256, 'ic13'], [256, 'ic08'], [512, 'ic14'], [512, 'ic09'], [1024, 'ic10']]
153
+ .map(([size, type]) => {
154
+ const png = resizedPng(source, size);
155
+ const header = Buffer.alloc(8);
156
+ header.write(type);
157
+ header.writeUInt32BE(png.length + 8, 4);
158
+ return Buffer.concat([header, png]);
159
+ });
160
+ const header = Buffer.alloc(8);
161
+ header.write('icns');
162
+ header.writeUInt32BE(8 + chunks.reduce((length, chunk) => length + chunk.length, 0), 4);
163
+ return Buffer.concat([header, ...chunks]);
164
+ }
165
+
166
+ export function prepareElectronIcons(root, { required = false } = {}) {
167
+ const output = path.join(root, 'dist-electron');
168
+ // Remove only our derived files, including when artwork was removed or became invalid.
169
+ const files = ['app-icon.png', 'app-icon.ico', 'app-icon.icns', 'app-icon-macos.png'];
170
+ for (const file of files) rmSync(path.join(output, file), { force: true });
171
+ const bytes = readAppIcon(root, { required });
172
+ if (!bytes) {
173
+ process.stderr.write('[nimi-app] No App artwork yet: supply metadata.icon for native window and Dock icons. Production packaging requires it.\n');
174
+ return null;
175
+ }
176
+ const ico = encodeWindowsIcon(bytes);
177
+ const icns = encodeMacIcon(bytes);
178
+ mkdirSync(output, { recursive: true });
179
+ for (const [index, content] of [bytes, ico, icns, createMacIconPng(bytes)].entries()) writeFileSync(path.join(output, files[index]), content);
180
+ return { png: path.join(output, files[0]), ico: path.join(output, files[1]), icns: path.join(output, files[2]), macPng: path.join(output, files[3]) };
181
+ }
@@ -0,0 +1,27 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ const segment = '[a-z0-9](?:[a-z0-9-]*[a-z0-9])?';
4
+ const productId = new RegExp('^' + segment + '(?:\\.' + segment + ')+$');
5
+ const clientId = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u;
6
+ const publicSlug = new RegExp('^' + segment + '$');
7
+
8
+ export function isAppId(value) {
9
+ return typeof value === 'string' && value.length >= 3 && value.length <= 120 && productId.test(value);
10
+ }
11
+
12
+ export function isClientId(value) {
13
+ return typeof value === 'string' && value.length >= 3 && value.length <= 120 && clientId.test(value);
14
+ }
15
+
16
+ export function hostedWebIdentity(appId, slug, registeredClient) {
17
+ if (!isAppId(appId)) throw new Error('Invalid hosted Web product ID.');
18
+ if (typeof slug !== 'string' || slug.length > 63 || !publicSlug.test(slug))
19
+ throw new Error('Invalid hosted Web slug.');
20
+ const preferred = appId + '.web';
21
+ const id =
22
+ registeredClient ??
23
+ (isClientId(preferred) ? preferred : 'web.' + createHash('sha256').update(appId).digest('hex'));
24
+ if (!isClientId(id)) throw new Error('Invalid hosted Web client ID.');
25
+ const origin = 'https://' + slug + '.nimi.xyz';
26
+ return { appId, slug, clientId: id, origin, redirectUri: origin + '/' };
27
+ }
package/lib/app-info.mjs CHANGED
@@ -1,14 +1,17 @@
1
1
  // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-042a
2
2
  // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-043a
3
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-042d
3
4
  import { existsSync, lstatSync, readFileSync } from 'node:fs';
4
5
  import path from 'node:path';
5
- import { PNG } from 'pngjs';
6
+ import { readAppIcon, validateAppIcon } from './app-icons.mjs';
7
+ export { validateAppIcon } from './app-icons.mjs';
6
8
  import { parse as parseYaml } from 'yaml';
7
9
  import { normalizeAppAccessItems } from './app-access-declaration.mjs';
8
10
  import { CANONICAL_CAPABILITY_IDS } from './canonical-capability-ids.generated.mjs';
9
11
  import { SAFETY_PROFILE_FIELD, normalizeSafetyProfile } from './app-safety-profile.mjs';
10
12
 
11
13
  export const APP_INFO_MAX_BYTES = 1024 * 1024;
14
+ export const APP_INTRODUCTION_FILE = 'NIMI_APP.md';
12
15
  export const APP_INFO_FIELDS = Object.freeze([
13
16
  'format', 'app_id', 'version', 'target_id', 'display_name', 'summary', 'icon', 'readme_markdown', 'release_notes_markdown',
14
17
  'license', 'app_access', 'capability_contract_refs', 'required_standardized_feature_refs', 'storage_policy', 'author',
@@ -17,7 +20,6 @@ export const APP_INFO_FIELDS = Object.freeze([
17
20
  // Declaration fields that App Tools projects from nimi.app.yaml into the
18
21
  // archive declaration and that Registry compares against the candidate.
19
22
  export const APP_INFO_DECLARATION_FIELDS = Object.freeze(['app_id', 'display_name', 'version', 'app_access', 'capability_contract_refs', 'required_standardized_feature_refs', 'storage_policy', SAFETY_PROFILE_FIELD]);
20
- const PNG_SIGNATURE = Buffer.from('89504e470d0a1a0a', 'hex');
21
23
 
22
24
  function text(value, label, max, multiline = false) {
23
25
  if (typeof value !== 'string' || !value.trim() || value.includes('\0')
@@ -41,33 +43,6 @@ function refs(value, label) {
41
43
  return entries;
42
44
  }
43
45
 
44
- export function validateAppIcon(bytes) {
45
- if (!Buffer.isBuffer(bytes) || bytes.length > 512 * 1024 || !bytes.subarray(0, 8).equals(PNG_SIGNATURE)) {
46
- throw new Error('App icon must be a PNG of at most 512 KiB');
47
- }
48
- let offset = 8;
49
- let ended = false;
50
- while (offset + 12 <= bytes.length) {
51
- const length = bytes.readUInt32BE(offset);
52
- const type = bytes.toString('ascii', offset + 4, offset + 8);
53
- if (offset + length + 12 > bytes.length || type === 'acTL') throw new Error('App icon must be a complete static PNG');
54
- if (offset === 8 && (type !== 'IHDR' || length !== 13)) throw new Error('App icon PNG header is invalid');
55
- if (type === 'IHDR') {
56
- const width = bytes.readUInt32BE(offset + 8);
57
- const height = bytes.readUInt32BE(offset + 12);
58
- if (width < 128 || width > 1024 || width !== height) throw new Error('App icon must be square, 128–1024 pixels');
59
- }
60
- offset += length + 12;
61
- if (type === 'IEND') { ended = length === 0 && offset === bytes.length; break; }
62
- }
63
- if (!ended) throw new Error('App icon PNG is truncated or has trailing content');
64
- const decoded = PNG.sync.read(bytes, { checkCRC: true });
65
- for (let index = 3; index < decoded.data.length; index += 4) {
66
- if (decoded.data[index] !== 0) return bytes;
67
- }
68
- throw new Error('App icon is fully transparent; supply actual App artwork');
69
- }
70
-
71
46
  function storage(value) {
72
47
  if (!value || !['nimi-mediated-default', 'app-owned-os-storage'].includes(value.kind)) {
73
48
  throw new Error('App info storage_policy must declare its storage kind');
@@ -114,7 +89,7 @@ export function validateAppInfo(info) {
114
89
  const icon = Buffer.from(info.icon.data_base64, 'base64');
115
90
  if (icon.toString('base64') !== info.icon.data_base64) throw new Error('App icon base64 is not canonical');
116
91
  validateAppIcon(icon);
117
- if (info.readme_markdown !== undefined && info.readme_markdown !== '') text(info.readme_markdown, 'readme', 96 * 1024, true);
92
+ text(info.readme_markdown, 'App introduction', 96 * 1024, true);
118
93
  if (info.release_notes_markdown !== undefined && info.release_notes_markdown !== '') text(info.release_notes_markdown, 'release notes', 32 * 1024, true);
119
94
  text(info.license?.identifier, 'license identifier', 200);
120
95
  text(info.license?.text, 'license text', 128 * 1024, true);
@@ -135,7 +110,7 @@ function resource(root, relative, label, maxBytes) {
135
110
  if (typeof relative !== 'string' || path.isAbsolute(relative) || relative.includes('\\')
136
111
  || relative.split('/').some((part) => !part || part === '.' || part === '..')) throw new Error(`metadata.${label} must name an App-relative resource`);
137
112
  const file = path.join(root, relative);
138
- const field = label === 'license' ? 'App license' : `metadata.${label}`;
113
+ const field = label === 'license' ? 'App license' : label === 'introduction' ? APP_INTRODUCTION_FILE : `metadata.${label}`;
139
114
  try {
140
115
  const stat = lstatSync(file);
141
116
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size === 0 || stat.size > maxBytes) throw new Error(`must be a nonempty regular file of at most ${maxBytes} bytes`);
@@ -146,6 +121,19 @@ function resource(root, relative, label, maxBytes) {
146
121
  }
147
122
  }
148
123
 
124
+ export function readAppIntroduction(root, manifest) {
125
+ if (manifest?.metadata && Object.hasOwn(manifest.metadata, 'readme')) {
126
+ throw new Error('metadata.readme is not supported; put the user introduction in root NIMI_APP.md and remove metadata.readme');
127
+ }
128
+ let content;
129
+ try {
130
+ content = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(resource(root, APP_INTRODUCTION_FILE, 'introduction', 96 * 1024));
131
+ } catch (error) {
132
+ throw new Error(`Invalid ${APP_INTRODUCTION_FILE}: ${error.message}`, { cause: error });
133
+ }
134
+ return text(content, APP_INTRODUCTION_FILE, 96 * 1024, true);
135
+ }
136
+
149
137
  export function readAppInfo(root, targetId) {
150
138
  const manifest = parseYaml(readFileSync(path.join(root, 'nimi.app.yaml'), 'utf8'));
151
139
  const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
@@ -156,8 +144,8 @@ export function readAppInfo(root, targetId) {
156
144
  const info = validateAppInfo({
157
145
  format: 'nimi.app-info/v1', app_id: manifest.app_id, version: manifest.version, target_id: targetId,
158
146
  display_name: manifest.display_name, summary: metadata.summary,
159
- icon: { media_type: 'image/png', data_base64: validateAppIcon(resource(root, metadata.icon, 'icon', 512 * 1024)).toString('base64') },
160
- readme_markdown: metadata.readme === undefined ? '' : readText(metadata.readme, 'readme', 96 * 1024),
147
+ icon: { media_type: 'image/png', data_base64: readAppIcon(root).toString('base64') },
148
+ readme_markdown: readAppIntroduction(root, manifest),
161
149
  release_notes_markdown: metadata.release_notes === undefined ? '' : readText(metadata.release_notes, 'release_notes', 32 * 1024),
162
150
  license: { identifier: pkg.license, text: readText('LICENSE', 'license', 128 * 1024) },
163
151
  app_access: refs(manifest.app_access, 'app_access'),
@@ -12,10 +12,11 @@ const AGENTS_BLOCK = `${START}
12
12
  ## Nimi App development
13
13
 
14
14
  - For auditing adaptation feasibility or cost, creating, adapting, upgrading or releasing this App, read [the lifecycle skill](.agents/skills/nimi-app-lifecycle/SKILL.md) and only the relevant scenario. Audit-only requests do not begin implementation; prior reports remain evidence-dependent.
15
- - For first integration or foundation wiring changes, use the selected app-tools package's generated reference and reuse its Host, preload, renderer, session, App Access, AIConfig and AI call wiring. Follow the adaptation guide's baseline checks and reuse passing results for ordinary business edits.
15
+ - For first integration or foundation wiring changes, use the selected app-tools package's generated reference for the same carrier and reuse its renderer, session, App Access, AIConfig and AI call wiring; Host/preload apply only to native Desktop, while Web uses official scoped login and its admitted HTTPS source. Follow the adaptation guide's baseline checks and reuse passing results for ordinary business edits.
16
16
  - Keep App-owned product behavior, Host code, business accounts and non-AI services with this repository. Use the SDK/Kit Local App carrier for Nimi AI, configuration, storage and session access.
17
17
  - Development may consume complete local npm tarballs through the supported explicit overrides and version matrix; public-release preflight uses registry resolutions. Do not substitute source-workspace or directory links.
18
18
  - App Tools owns its lifecycle skill, this block, managed workflow and declared engineering fields; preserve other instructions, product source and licenses. Existing adoption does not create fresh scaffold intent or lock.
19
+ - Maintain root NIMI_APP.md for the App’s actual users: purpose, first steps, configuration, data handling, limitations and help. Keep engineering instructions and acceptance logs in README/developer documentation. metadata.readme and README fallback are not supported; sync never overwrites or recreates this App-owned introduction.
19
20
  - Product-operation guides apply to their specific business tasks; they do not replace the Nimi development boundary.
20
21
  - Reuse the user's confirmed scope and authorization. Report command checks separately from actual App journeys; unrun relevant paths remain NOT-VERIFIED.
21
22
  ${END}`;