@nimiplatform/app-tools 0.6.3 → 0.11.4

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 (115) hide show
  1. package/README.md +153 -12
  2. package/bin/nimi-app.mjs +16 -14
  3. package/lib/app-access-declaration.mjs +1 -0
  4. package/lib/app-dependency-combinations.mjs +49 -0
  5. package/lib/app-doctor-update.mjs +84 -23
  6. package/lib/app-info.mjs +33 -3
  7. package/lib/app-lifecycle-guidance.mjs +4 -2
  8. package/lib/app-pack.mjs +5 -2
  9. package/lib/app-project-lifecycle.mjs +284 -53
  10. package/lib/app-safety-profile.mjs +204 -0
  11. package/lib/app-scaffold-capabilities.mjs +11 -3
  12. package/lib/app-scaffold-profiles.mjs +136 -27
  13. package/lib/app-scaffold.mjs +55 -7
  14. package/lib/canonical-capability-ids.generated.mjs +25 -0
  15. package/lib/index.mjs +0 -4
  16. package/package.json +27 -31
  17. package/scripts/dev-shell.mjs +80 -18
  18. package/skills/nimi-app-lifecycle/SKILL.md +7 -3
  19. package/skills/nimi-app-lifecycle/references/acceptance.md +7 -1
  20. package/skills/nimi-app-lifecycle/references/adapt.md +46 -1
  21. package/skills/nimi-app-lifecycle/references/audit.md +55 -0
  22. package/skills/nimi-app-lifecycle/references/platform-gaps.md +15 -0
  23. package/skills/nimi-app-lifecycle/references/release.md +2 -2
  24. package/skills/nimi-app-lifecycle/references/safety-declaration.md +37 -0
  25. package/skills/nimi-app-lifecycle/references/upgrade-platform.md +16 -2
  26. package/templates/app-source/src/ai-studio-core/ai-config.ts +17 -3
  27. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +40 -3
  28. package/templates/app-source/src/ai-studio-core/audio-separation-request.ts +24 -0
  29. package/templates/app-source/src/ai-studio-core/contexts.tsx +4 -0
  30. package/templates/app-source/src/ai-studio-core/history-policy.ts +395 -41
  31. package/templates/app-source/src/ai-studio-core/history.ts +262 -10
  32. package/templates/app-source/src/ai-studio-core/host-context.tsx +15 -2
  33. package/templates/app-source/src/ai-studio-core/index.ts +15 -4
  34. package/templates/app-source/src/ai-studio-core/job-recovery-panel.tsx +105 -0
  35. package/templates/app-source/src/ai-studio-core/job-recovery.ts +224 -0
  36. package/templates/app-source/src/ai-studio-core/managed-result-references.ts +79 -0
  37. package/templates/app-source/src/ai-studio-core/messages/en.json +185 -10
  38. package/templates/app-source/src/ai-studio-core/messages/zh.json +185 -10
  39. package/templates/app-source/src/ai-studio-core/module-registration.ts +9 -1
  40. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +81 -2
  41. package/templates/app-source/src/ai-studio-core/parameters.ts +34 -1
  42. package/templates/app-source/src/ai-studio-core/runtime-types.ts +124 -8
  43. package/templates/app-source/src/ai-studio-core/runtime.ts +218 -20
  44. package/templates/app-source/src/ai-studio-core/section-ai-testing-annotation-result.tsx +123 -0
  45. package/templates/app-source/src/ai-studio-core/section-ai-testing-artifact-preview.ts +3 -0
  46. package/templates/app-source/src/ai-studio-core/section-ai-testing-audio-separation-result.tsx +26 -0
  47. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +14 -7
  48. package/templates/app-source/src/ai-studio-core/section-ai-testing-decision-result.tsx +76 -0
  49. package/templates/app-source/src/ai-studio-core/section-ai-testing-exchange-result.tsx +71 -0
  50. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +20 -4
  51. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +29 -0
  52. package/templates/app-source/src/ai-studio-core/section-ai-testing-music-result.tsx +45 -0
  53. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +132 -10
  54. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +122 -38
  55. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +4 -3
  56. package/templates/app-source/src/ai-studio-core/section-ai-testing-session-result.tsx +66 -0
  57. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +100 -22
  58. package/templates/app-source/src/ai-studio-core/section-ai-testing-surface.tsx +6 -0
  59. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcript-result.tsx +45 -0
  60. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcription-result.tsx +106 -0
  61. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-result.tsx +23 -4
  62. package/templates/app-source/src/ai-studio-core/section-ai-testing-voice-asset-actions.tsx +40 -0
  63. package/templates/app-source/src/ai-studio-core/section-ai-testing-voice-conversion-result.tsx +20 -0
  64. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +219 -35
  65. package/templates/app-source/src/ai-studio-core/text-annotation-document.ts +50 -0
  66. package/templates/app-source/src/ai-studio-core/text-media-replay.ts +51 -0
  67. package/templates/app-source/src/ai-studio-core/voice-assets.ts +17 -0
  68. package/templates/app-source/src/ai-studio-core/workspace.tsx +48 -6
  69. package/templates/app-source/src/studio-modules/studio-create/descriptors.ts +1 -1
  70. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +13 -1
  71. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +13 -1
  72. package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +11 -2
  73. package/templates/app-source/src/studio-modules/studio-create/parameters.ts +2 -2
  74. package/templates/app-source/src/studio-modules/studio-create/registration.ts +2 -2
  75. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +121 -3
  76. package/templates/app-source/src/studio-modules/studio-media/audio-separate-parameters.tsx +72 -0
  77. package/templates/app-source/src/studio-modules/studio-media/audio-separate-runtime.ts +90 -0
  78. package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +16 -1
  79. package/templates/app-source/src/studio-modules/studio-media/index.ts +2 -0
  80. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +225 -7
  81. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +225 -7
  82. package/templates/app-source/src/studio-modules/studio-media/music-parameters.tsx +85 -0
  83. package/templates/app-source/src/studio-modules/studio-media/music-transcription-parameters.tsx +85 -0
  84. package/templates/app-source/src/studio-modules/studio-media/music-transcription-runtime.ts +64 -0
  85. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +9 -26
  86. package/templates/app-source/src/studio-modules/studio-media/parameters.ts +170 -6
  87. package/templates/app-source/src/studio-modules/studio-media/registration.ts +29 -1
  88. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +90 -6
  89. package/templates/app-source/src/studio-modules/studio-media/vision-parameters.tsx +1 -0
  90. package/templates/app-source/src/studio-modules/studio-media/vision-runtime.ts +23 -5
  91. package/templates/app-source/src/studio-modules/studio-media/voice-convert-parameters.tsx +132 -0
  92. package/templates/app-source/src/studio-modules/studio-media/voice-convert-runtime.ts +120 -0
  93. package/templates/app-source/src/studio-modules/studio-voice/audio-url.ts +25 -0
  94. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +4 -4
  95. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +4 -4
  96. package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +36 -10
  97. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +66 -30
  98. package/templates/app-source/src/workbench-core/index.ts +2 -0
  99. package/templates/app-source/src/workbench-core/runtime-gate.tsx +102 -6
  100. package/templates/app-source/src/workbench-core/workbench-core.css +42 -0
  101. package/templates/app-source/src/workbench-core/workbench-core.tsx +69 -18
  102. package/templates/app-source.manifest.json +100 -0
  103. package/templates/default-starter/AGENTS.md +4 -2
  104. package/templates/default-starter/README.md +2 -1
  105. package/templates/default-starter/src/shell/workbench-target-adapter.ts +102 -12
  106. package/templates/default-starter.manifest.json +0 -4
  107. package/lib/simulator-conformance-ast.mjs +0 -498
  108. package/lib/simulator-conformance-css.mjs +0 -116
  109. package/lib/simulator-conformance-graph.mjs +0 -757
  110. package/lib/simulator-conformance.d.mts +0 -14
  111. package/lib/simulator-conformance.mjs +0 -203
  112. package/lib/simulator-css-profile.d.mts +0 -27
  113. package/lib/simulator-css-profile.mjs +0 -531
  114. package/lib/simulator-kit-export-resolution.mjs +0 -70
  115. package/lib/simulator-manifest.mjs +0 -334
@@ -1,7 +1,17 @@
1
+ import { verifyStudioManagedAsset } from './managed-result-references.js';
2
+ import { beginStudioJobRecovery, captureStudioJobRecoveryJobId, isStudioJobRecoveryCapability, readStudioJobRecovery, recoverStudioJobId, restoreSavedStudioJobResult, saveStudioJobRecoveryResult, studioJobRecoverySignal, type StudioJobRecoveryDetails } from './job-recovery.js';
3
+ import { ScenarioType } from '@nimiplatform/sdk/runtime/generated';
1
4
  import {
2
5
  runRuntimeAIConsumeCapability,
3
6
  runRuntimeImageGenerate,
4
7
  runRuntimeMusicGenerate,
8
+ runRuntimeMusicTranscribe,
9
+ observeRuntimeMusicTranscription,
10
+ runRuntimeAudioSeparation,
11
+ observeRuntimeAudioSeparation,
12
+ runRuntimeVoiceConvert,
13
+ observeRuntimeVoiceConversion,
14
+ observeRuntimeMusicGeneration,
5
15
  runRuntimeSpeechSynthesize,
6
16
  runRuntimeSpeechTranscribe,
7
17
  runRuntimeVideoGenerate,
@@ -13,14 +23,19 @@ import {
13
23
  type NimiLocalAppClient,
14
24
  } from '@nimiplatform/sdk/app';
15
25
  import type {
26
+ StudioAudioSeparation,
27
+ StudioAudioSeparationRequest,
16
28
  StudioCapabilityRunInput,
17
29
  StudioCapabilityRunResult,
18
30
  StudioManagedArtifact,
31
+ StudioMusicGeneration,
32
+ StudioMusicTranscription,
19
33
  StudioNonSuccess,
20
34
  StudioNonSuccessDiagnostics,
21
35
  StudioNonSuccessReason,
22
36
  StudioRuntimeCapabilityDescriptor,
23
37
  StudioRuntimeInspection,
38
+ StudioVoiceConversion,
24
39
  } from './runtime-types.js';
25
40
  import {
26
41
  dispatchStudioCapabilityRuntime,
@@ -33,6 +48,13 @@ export type StudioRuntimeRunnerSet = {
33
48
  readonly aiConsume: typeof runRuntimeAIConsumeCapability;
34
49
  readonly imageGenerate: typeof runRuntimeImageGenerate;
35
50
  readonly musicGenerate: typeof runRuntimeMusicGenerate;
51
+ readonly musicTranscribe: typeof runRuntimeMusicTranscribe;
52
+ readonly musicTranscriptionObserve: typeof observeRuntimeMusicTranscription;
53
+ readonly voiceConvert: typeof runRuntimeVoiceConvert;
54
+ readonly voiceConversionObserve: typeof observeRuntimeVoiceConversion;
55
+ readonly audioSeparate: typeof runRuntimeAudioSeparation;
56
+ readonly audioSeparationObserve: typeof observeRuntimeAudioSeparation;
57
+ readonly musicObserve: typeof observeRuntimeMusicGeneration;
36
58
  readonly videoGenerate: typeof runRuntimeVideoGenerate;
37
59
  readonly speechSynthesize: typeof runRuntimeSpeechSynthesize;
38
60
  readonly speechTranscribe: typeof runRuntimeSpeechTranscribe;
@@ -58,6 +80,12 @@ export type StudioRuntimeHost = {
58
80
  };
59
81
 
60
82
  export type StudioCapabilityRuntimeContext = {
83
+ jobActionId?: string;
84
+ readonly musicSourceAudio?: StudioManagedArtifact;
85
+ readonly voiceSourceVocal?: StudioManagedArtifact;
86
+ readonly voiceTargetAudio?: StudioManagedArtifact;
87
+ readonly separationSourceAudio?: StudioManagedArtifact;
88
+ readonly separationRequest?: StudioAudioSeparationRequest;
61
89
  readonly capability: StudioRuntimeCapabilityDescriptor;
62
90
  readonly input: StudioCapabilityRunInput;
63
91
  readonly prompt: string;
@@ -87,6 +115,13 @@ export const DEFAULT_STUDIO_RUNTIME_RUNNERS: StudioRuntimeRunnerSet = Object.fre
87
115
  aiConsume: runRuntimeAIConsumeCapability,
88
116
  imageGenerate: runRuntimeImageGenerate,
89
117
  musicGenerate: runRuntimeMusicGenerate,
118
+ musicTranscribe: runRuntimeMusicTranscribe,
119
+ musicTranscriptionObserve: observeRuntimeMusicTranscription,
120
+ voiceConvert: runRuntimeVoiceConvert,
121
+ voiceConversionObserve: observeRuntimeVoiceConversion,
122
+ audioSeparate: runRuntimeAudioSeparation,
123
+ audioSeparationObserve: observeRuntimeAudioSeparation,
124
+ musicObserve: observeRuntimeMusicGeneration,
90
125
  videoGenerate: runRuntimeVideoGenerate,
91
126
  speechSynthesize: runRuntimeSpeechSynthesize,
92
127
  speechTranscribe: runRuntimeSpeechTranscribe,
@@ -129,7 +164,14 @@ export async function runStudioCapability(
129
164
 
130
165
  try {
131
166
  const dispatched = dispatchStudioCapabilityRuntime(orchestrator.handlers, context);
132
- if (dispatched) return await dispatched;
167
+ if (dispatched) {
168
+ const result = await dispatched;
169
+ if (result.ok) studioJobRecoverySignal(input).throwIfAborted();
170
+ if (context.jobActionId && isStudioJobRecoveryCapability(capability.id)) {
171
+ await saveStudioJobRecoveryResult(context.host.client.storage, context.jobActionId, result, capability.id);
172
+ }
173
+ return result;
174
+ }
133
175
  if (!context.prompt) {
134
176
  return orchestrator.nonSuccess(
135
177
  capability,
@@ -151,13 +193,67 @@ export async function runStudioCapability(
151
193
  }
152
194
  }
153
195
 
154
- export function createStudioScenarioJobClient(context: StudioCapabilityRuntimeContext) {
155
- return context.host.createScenarioJobClient(context.host.client.ai);
196
+ export function createStudioScenarioJobClient(context: StudioCapabilityRuntimeContext, savedDetails?: Pick<StudioJobRecoveryDetails, 'sourceImage'>) {
197
+ const client = context.host.createScenarioJobClient(context.host.client.ai);
198
+ return { ...client, async submitScenarioJob(request: Parameters<typeof client.submitScenarioJob>[0], options?: Parameters<typeof client.submitScenarioJob>[1]) {
199
+ const spec = request.spec?.spec;
200
+ const details: StudioJobRecoveryDetails = { ...savedDetails, scenarioType: request.scenarioType,
201
+ ...(spec?.oneofKind === 'visionLocate' ? { expectedVision: { imageArtifactId: spec.visionLocate.imageArtifactId, geometry: spec.visionLocate.geometry } } : {}),
202
+ ...(spec?.oneofKind === 'voiceCreate' ? { creationSource: spec.voiceCreate.source.oneofKind === 'referenceAudio' ? 'reference-audio' as const : 'text-description' as const } : {}),
203
+ ...(spec?.oneofKind === 'speechTranscribe' ? { timestamps: spec.speechTranscribe.timestamps } : {}),
204
+ };
205
+ const id = await beginStudioJobAction(context, details);
206
+ context.input.signal?.throwIfAborted();
207
+ context.input.observationSignal?.throwIfAborted();
208
+ const response = await client.submitScenarioJob({ ...request, idempotencyKey: id }, options);
209
+ await captureStudioJobAction(context, id, response.job?.jobId ?? '');
210
+ return response;
211
+ } };
212
+ }
213
+
214
+ export async function beginStudioJobAction(context: StudioCapabilityRuntimeContext, details: StudioJobRecoveryDetails): Promise<string> {
215
+ context.input.signal?.throwIfAborted();
216
+ context.input.observationSignal?.throwIfAborted();
217
+ if (!isStudioJobRecoveryCapability(context.capability.id)) throw new Error('This capability has no saved Job action');
218
+ const id = await beginStudioJobRecovery(context.host.client.storage, context.capability.id, undefined, undefined, undefined,
219
+ context.input.recordedRunConfig, context.input.recordedPrompt ?? context.input.prompt, details);
220
+ context.jobActionId = id;
221
+ return id;
222
+ }
223
+
224
+ export async function captureStudioJobAction(context: StudioCapabilityRuntimeContext, id: string, jobId: string): Promise<void> {
225
+ if (!isStudioJobRecoveryCapability(context.capability.id)) throw new Error('Unknown Job capability');
226
+ await captureStudioJobRecoveryJobId(context.host.client.storage, id, jobId, context.capability.id);
227
+ }
228
+
229
+ /** Reopening a business action only resolves its original identity. */
230
+ export async function recoverStudioJobAction(context: StudioCapabilityRuntimeContext, scenarioType: ScenarioType) {
231
+ const id = context.input.parameters?.recoverySubmissionId;
232
+ if (id === undefined) return null;
233
+ if (typeof id !== 'string' || !isStudioJobRecoveryCapability(context.capability.id)) throw new Error('Invalid saved action');
234
+ const entry = (await readStudioJobRecovery(context.host.client.storage, context.capability.id)).find(item => item.clientSubmissionId === id);
235
+ if (!entry || entry.details?.scenarioType !== scenarioType) throw new Error(context.host.translate('Music.recoveryMissing'));
236
+ context.jobActionId = id;
237
+ const saved = await restoreSavedStudioJobResult(entry, context.capability.label, context.capability.id, context.host.client.storage.assets, studioJobRecoverySignal(context.input));
238
+ return { entry, saved, jobId: saved ? undefined : await recoverStudioJobId(context.host.client, entry, context.capability.id) };
239
+ }
240
+
241
+ export async function submitStudioLocalJob(context: StudioCapabilityRuntimeContext,
242
+ spec: Parameters<NimiLocalAppClient['ai']['scenarioJobs']['submit']>[0], details: StudioJobRecoveryDetails) {
243
+ const id = await beginStudioJobAction(context, details);
244
+ context.input.signal?.throwIfAborted();
245
+ context.input.observationSignal?.throwIfAborted();
246
+ const response = await context.host.client.ai.scenarioJobs.submit(spec, { clientSubmissionId: id });
247
+ await captureStudioJobAction(context, id, response.job.jobId);
248
+ return response;
156
249
  }
157
250
 
158
251
  type ArtifactRunnerResult = Awaited<ReturnType<
159
252
  | typeof runRuntimeImageGenerate
160
253
  | typeof runRuntimeMusicGenerate
254
+ | typeof runRuntimeMusicTranscribe
255
+ | typeof runRuntimeAudioSeparation
256
+ | typeof runRuntimeVoiceConvert
161
257
  | typeof runRuntimeVideoGenerate
162
258
  | typeof runRuntimeSpeechSynthesize
163
259
  >>;
@@ -167,6 +263,9 @@ export async function projectStudioArtifactRunnerResult(
167
263
  result: ArtifactRunnerResult,
168
264
  ): Promise<StudioCapabilityRunResult> {
169
265
  if (result.ok === false) return projectStudioRunnerNonSuccess(context, result);
266
+ if (result.output.kind === 'music-transcription-artifacts' && !context.musicSourceAudio) throw new Error('Music transcription omitted the saved canonical input.');
267
+ if (result.output.kind === 'voice-conversion-artifacts' && !context.voiceSourceVocal) throw new Error('Voice conversion omitted the saved canonical source.');
268
+ if (result.output.kind === 'audio-separation' && !context.separationSourceAudio) throw new Error('Audio separation omitted the saved canonical source.');
170
269
  const artifacts: StudioManagedArtifact[] = [];
171
270
  const adoptedPaths: string[] = [];
172
271
  try {
@@ -179,12 +278,9 @@ export async function projectStudioArtifactRunnerResult(
179
278
  result.output.jobId,
180
279
  index,
181
280
  );
182
- const adopted = await context.host.client.storage.assets.adoptArtifact({
183
- artifactId: sourceArtifact.artifactId,
184
- relativePath,
185
- overwrite: false,
186
- });
187
- adoptedPaths.push(adopted.relativePath);
281
+ const retained = await adoptStudioJobArtifact(context, sourceArtifact, relativePath);
282
+ const adopted = retained.asset;
283
+ if (retained.created) adoptedPaths.push(adopted.relativePath);
188
284
  artifacts.push({
189
285
  relativePath: adopted.relativePath,
190
286
  ...(adopted.mediaType ? { mediaType: adopted.mediaType } : {}),
@@ -194,6 +290,7 @@ export async function projectStudioArtifactRunnerResult(
194
290
  ? context.capability.label
195
291
  : `${context.capability.label} ${index + 1}`,
196
292
  previewSource: 'managed-asset',
293
+ ...(result.output.kind === 'audio-artifacts' && result.output.artifacts[index]?.speechAlignment ? { speechAlignment: result.output.artifacts[index]!.speechAlignment } : {}),
197
294
  });
198
295
  }
199
296
  } catch (error) {
@@ -210,6 +307,63 @@ export async function projectStudioArtifactRunnerResult(
210
307
  }
211
308
  throw error;
212
309
  }
310
+ let musicGeneration: StudioMusicGeneration | undefined;
311
+ let musicTranscription: StudioMusicTranscription | undefined;
312
+ let voiceConversion: StudioVoiceConversion | undefined;
313
+ let audioSeparation: StudioAudioSeparation | undefined;
314
+ if (result.output.kind === 'music-transcription-artifacts') {
315
+ if (!context.musicSourceAudio) throw new Error('Music transcription omitted the saved canonical input.');
316
+ const pathFor = (id: string) => {
317
+ const index = result.output.artifacts.findIndex(artifact => artifact.artifactId === id);
318
+ if (index < 0 || !artifacts[index]) throw new Error('Transcription result references an unadopted output.');
319
+ return artifacts[index]!.relativePath;
320
+ };
321
+ const value = result.output.transcription;
322
+ musicTranscription = { sourceAudio: context.musicSourceAudio, sourceInfo: value.sourceInfo, inputRange: value.inputRange,
323
+ completeness: value.completeness, origin: value.origin, scores: value.scores.map(score => ({ relativePath: pathFor(score.artifactId), format: score.format, part: score.part })),
324
+ ...(value.timelineArtifactId ? { timelineRelativePath: pathFor(value.timelineArtifactId) } : {}) };
325
+ }
326
+ if (result.output.kind === 'voice-conversion-artifacts') {
327
+ if (!context.voiceSourceVocal) throw new Error('Voice conversion omitted the saved canonical source.');
328
+ const value = result.output.conversion;
329
+ const index = result.output.artifacts.findIndex(artifact => artifact.artifactId === value.vocalArtifactId);
330
+ const vocal = index < 0 ? undefined : artifacts[index];
331
+ if (!vocal || vocal.mediaType !== 'audio/wav') throw new Error('Voice conversion result references an unadopted vocal.');
332
+ voiceConversion = { sourceVocal: context.voiceSourceVocal,
333
+ ...(context.voiceTargetAudio ? { targetVoice: context.voiceTargetAudio } : {}),
334
+ vocal, sourceInfo: value.sourceInfo, inputRange: value.inputRange, vocalInfo: value.vocalInfo,
335
+ lengthRelation: value.lengthRelation, durationDeltaMs: value.durationDeltaMs };
336
+ }
337
+ if (result.output.kind === 'audio-separation') {
338
+ if (!context.separationSourceAudio) throw new Error('Audio separation omitted the saved canonical source.');
339
+ const value = result.output.separation;
340
+ const stemFor = (id: string) => {
341
+ const index = result.output.artifacts.findIndex(artifact => artifact.artifactId === id);
342
+ const stem = index < 0 ? undefined : artifacts[index];
343
+ if (!stem || stem.mediaType !== 'audio/wav') throw new Error('Audio separation result references an unadopted stem.');
344
+ return stem;
345
+ };
346
+ const vocals = stemFor(value.vocalsArtifactId);
347
+ const background = stemFor(value.backgroundArtifactId);
348
+ audioSeparation = { sourceAudio: context.separationSourceAudio, vocals, background,
349
+ ...(context.separationRequest ? { request: context.separationRequest } : {}),
350
+ ...(value.instrumentParts?.length ? { instrumentParts: value.instrumentParts.map(part => ({ kind: part.kind, artifact: stemFor(part.artifactId) })) } : {}) };
351
+ }
352
+ if (result.output.kind === 'music-artifacts') {
353
+ const generation = result.output.generation;
354
+ const pathFor = (artifactId: string) => {
355
+ const index = result.output.artifacts.findIndex((artifact) => artifact.artifactId === artifactId);
356
+ const path = artifacts[index]?.relativePath;
357
+ if (!path) throw new Error('Music result is missing its adopted artifact.');
358
+ return path;
359
+ };
360
+ musicGeneration = {
361
+ mixRelativePath: pathFor(generation.mixArtifactId), termination: generation.termination, audioInfo: generation.audioInfo,
362
+ ...(generation.actualSeed !== undefined ? { actualSeed: generation.actualSeed } : {}),
363
+ ...(generation.generatedScore ? { generatedScore: { relativePath: pathFor(generation.generatedScore.artifactId),
364
+ format: generation.generatedScore.format, origin: generation.generatedScore.origin, truncated: generation.generatedScore.truncated } } : {}),
365
+ };
366
+ }
213
367
  return {
214
368
  ok: true,
215
369
  capabilityId: context.capability.id,
@@ -217,6 +371,10 @@ export async function projectStudioArtifactRunnerResult(
217
371
  message: result.message,
218
372
  output: {
219
373
  kind: 'artifacts',
374
+ ...(musicGeneration ? { musicGeneration } : {}),
375
+ ...(musicTranscription ? { musicTranscription } : {}),
376
+ ...(voiceConversion ? { voiceConversion } : {}),
377
+ ...(audioSeparation ? { audioSeparation } : {}),
220
378
  jobId: result.output.jobId,
221
379
  jobState: result.output.jobStatus,
222
380
  artifactCount: result.output.artifactCount,
@@ -231,12 +389,13 @@ export function projectStudioRunnerNonSuccess(
231
389
  context: StudioCapabilityRuntimeContext,
232
390
  result: { readonly ok: false; readonly reason: string; readonly message: string; readonly error?: unknown },
233
391
  ): StudioNonSuccess {
234
- return context.host.nonSuccess(
392
+ const diagnostics = studioNonSuccessDiagnostics(result.error);
393
+ return withStudioKnownJob(context.host.nonSuccess(
235
394
  context.capability,
236
- studioNonSuccessReason(result.reason),
395
+ studioNonSuccessReasonFromRuntime(result.reason, diagnostics),
237
396
  result.message,
238
- studioNonSuccessDiagnostics(result.error),
239
- );
397
+ diagnostics,
398
+ ), result.error);
240
399
  }
241
400
 
242
401
  export function projectStudioRuntimeError(
@@ -244,16 +403,34 @@ export function projectStudioRuntimeError(
244
403
  error: unknown,
245
404
  ): StudioNonSuccess {
246
405
  const diagnostics = studioNonSuccessDiagnostics(error);
406
+ // An input the configured implementation cannot encode completely is an
407
+ // input outcome too; it is never retried or presented as a call failure.
247
408
  // @nimi-authority: rule.nimi.runtime.ai-provider.r126
248
- const reason = diagnostics?.reasonCode.replaceAll('-', '_').toUpperCase() === 'AI_INPUT_INVALID'
249
- ? 'input-invalid'
250
- : studioNonSuccessReason(runtimeScenarioJobNonSuccessReasonFromError(error));
251
- return context.host.nonSuccess(
409
+ const reason = studioNonSuccessReasonFromRuntime(runtimeScenarioJobNonSuccessReasonFromError(error), diagnostics);
410
+ return withStudioKnownJob(context.host.nonSuccess(
252
411
  context.capability,
253
412
  reason,
254
413
  studioRuntimeErrorMessage(error),
255
414
  diagnostics,
256
- );
415
+ ), error);
416
+ }
417
+
418
+ /** Preserve an issued Job selector; unknown submission must not gain an ID. */
419
+ function withStudioKnownJob(result: StudioNonSuccess, error: unknown): StudioNonSuccess {
420
+ const record = error && typeof error === 'object' ? error as { details?: unknown } : null;
421
+ const details = record?.details && typeof record.details === 'object' && !Array.isArray(record.details)
422
+ ? record.details as { jobId?: unknown } : null;
423
+ const id = details?.jobId;
424
+ return typeof id === 'string' && /^[A-Za-z0-9_.:-]{1,128}$/u.test(id)
425
+ ? { ...result, jobId: id }
426
+ : result;
427
+ }
428
+
429
+ function studioNonSuccessReasonFromRuntime(reason: string, diagnostics?: StudioNonSuccessDiagnostics): StudioNonSuccessReason {
430
+ if (diagnostics && ['SDK_LOCAL_APP_INPUT_INVALID', 'AI_INPUT_INVALID', 'AI_INPUT_LIMIT_EXCEEDED', 'AI_VOICE_INPUT_INVALID', 'AI_VOICE_TARGET_MODEL_MISMATCH', 'AI_VOICE_ASSET_NOT_FOUND', 'AI_VOICE_ASSET_EXPIRED'].includes(diagnostics.reasonCode)) {
431
+ return 'input-invalid';
432
+ }
433
+ return studioNonSuccessReason(reason);
257
434
  }
258
435
 
259
436
  export function studioNonSuccessReason(reason: string): StudioNonSuccessReason {
@@ -302,7 +479,7 @@ export function studioAbortError(): Error {
302
479
  return error;
303
480
  }
304
481
 
305
- async function managedStudioAssetPath(
482
+ export async function managedStudioAssetPath(
306
483
  capabilityId: string,
307
484
  jobId: string,
308
485
  artifactIndex: number,
@@ -311,5 +488,26 @@ async function managedStudioAssetPath(
311
488
  const bytes = new TextEncoder().encode(identity);
312
489
  const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
313
490
  const token = Array.from(digest, (byte) => byte.toString(16).padStart(2, '0')).join('');
314
- return `media/${capabilityId.replaceAll('.', '-')}/${token}.asset`;
491
+ return `media/${capabilityId.replaceAll('.', '-')}/${token}/result.asset`;
492
+ }
493
+
494
+ /** Reuse the original target after a lost adopt/history response. Never overwrite. */
495
+ export async function adoptStudioJobArtifact(context: StudioCapabilityRuntimeContext,
496
+ artifact: { readonly artifactId?: string; readonly mimeType: string; readonly sizeBytes?: number | string; readonly sha256?: string }, relativePath: string) {
497
+ if (!artifact.artifactId) throw new Error('Runtime artifact identity is missing');
498
+ const signal = studioJobRecoverySignal(context.input);
499
+ signal.throwIfAborted();
500
+ const assets = context.host.client.storage.assets;
501
+ const prefix = relativePath.slice(0, relativePath.lastIndexOf('/') + 1);
502
+ const retained = await assets.list({ prefix, pageSize: 2 });
503
+ if (retained.nextCursor || retained.assets.length > 1) throw new Error('Saved result target contains conflicting files');
504
+ let asset = retained.assets[0];
505
+ const created = !asset;
506
+ const hash = artifact.sha256 ? `sha256:${artifact.sha256.replace(/^sha256:/u, '')}` : undefined;
507
+ if (asset && (!hash || !asset.relativePath.startsWith(relativePath.replace(/\.[^/.]+$/u, '') + '.'))) throw new Error('Saved result cannot be matched to the original output');
508
+ signal.throwIfAborted();
509
+ if (!asset) asset = await assets.adoptArtifact({ artifactId: artifact.artifactId, relativePath, overwrite: false });
510
+ if ((hash && asset.sha256 !== hash) || (artifact.sizeBytes !== undefined && asset.sizeBytes !== Number(artifact.sizeBytes)) || asset.mediaType !== artifact.mimeType) throw new Error('Saved result does not match the original output');
511
+ await verifyStudioManagedAsset(assets, asset, signal);
512
+ return { asset, created };
315
513
  }
@@ -0,0 +1,123 @@
1
+ import { useEffect, useState } from 'react';
2
+ import type { NimiLocalAppTextAnnotationDocument, NimiLocalAppTextAnnotationResult } from '@nimiplatform/sdk/app';
3
+ import { useAIStudioHost } from './host-context.js';
4
+ import type { StudioTypedOutput } from './runtime-types.js';
5
+ import { readStudioTextAnnotationDocument } from './text-annotation-document.js';
6
+
7
+ type TextAnnotationOutput = Extract<StudioTypedOutput, { kind: 'text-annotation' }>;
8
+ type LoadState =
9
+ | { readonly status: 'loading' }
10
+ | { readonly status: 'ready'; readonly annotation: NimiLocalAppTextAnnotationResult }
11
+ | { readonly status: 'unavailable'; readonly message: string };
12
+
13
+ // Large documents stay complete in the saved JSON; the view lists a bounded
14
+ // prefix of tokens per document.
15
+ const MAX_VISIBLE_TOKENS = 400;
16
+
17
+ export function TextAnnotationResultView({ output }: { readonly output: TextAnnotationOutput }) {
18
+ const host = useAIStudioHost();
19
+ const { translate: t } = host;
20
+ const [state, setState] = useState<LoadState>(() => (
21
+ output.annotation ? { status: 'ready', annotation: output.annotation } : { status: 'loading' }
22
+ ));
23
+ const { relativePath, mediaType, sizeBytes, sha256 } = output.document;
24
+ useEffect(() => {
25
+ if (output.annotation) {
26
+ setState({ status: 'ready', annotation: output.annotation });
27
+ return undefined;
28
+ }
29
+ // A restored history result is rebuilt on every render; only the saved
30
+ // document identity selects a new read.
31
+ let active = true;
32
+ setState({ status: 'loading' });
33
+ void readStudioTextAnnotationDocument(host.sdk.assets, {
34
+ relativePath, sizeBytes, sha256, previewSource: 'managed-asset', ...(mediaType ? { mediaType } : {}),
35
+ })
36
+ .then((annotation) => { if (active) setState({ status: 'ready', annotation }); })
37
+ .catch((cause: unknown) => {
38
+ if (active) setState({ status: 'unavailable', message: cause instanceof Error ? cause.message : String(cause) });
39
+ });
40
+ return () => { active = false; };
41
+ }, [host, output.annotation, relativePath, mediaType, sizeBytes, sha256]);
42
+
43
+ return (
44
+ <section className="studio-result__rich" aria-label={t('StudioResults.annotation.title')}>
45
+ <p className="studio-result__plain">
46
+ {t('StudioResults.annotation.summary', {
47
+ language: output.language,
48
+ documents: output.documentCount,
49
+ tokens: output.tokenCount,
50
+ sentences: output.sentenceCount,
51
+ })}
52
+ </p>
53
+ <p className="studio-result__hint">{t('StudioResults.annotation.offsetHint')}</p>
54
+ {state.status === 'loading' ? <p role="status">{t('StudioResults.annotation.loading')}</p> : null}
55
+ {state.status === 'unavailable' ? (
56
+ <div className="studio-result__blocked" role="alert">
57
+ <p>{t('StudioResults.annotation.unavailable')}</p>
58
+ <p className="studio-result__hint">{state.message}</p>
59
+ </div>
60
+ ) : null}
61
+ {state.status === 'ready' ? state.annotation.documents.map((document, index) => (
62
+ <TextAnnotationDocumentView key={index} index={index} document={document} />
63
+ )) : null}
64
+ </section>
65
+ );
66
+ }
67
+
68
+ function TextAnnotationDocumentView({ index, document }: { readonly index: number; readonly document: NimiLocalAppTextAnnotationDocument }) {
69
+ const { translate: t } = useAIStudioHost();
70
+ const visibleTokens = Math.min(document.tokens.length, MAX_VISIBLE_TOKENS);
71
+ return (
72
+ <details className="studio-annotation" open={index === 0}>
73
+ <summary>
74
+ {t('StudioResults.annotation.document', {
75
+ index: index + 1,
76
+ tokens: document.tokens.length,
77
+ sentences: document.sentences.length,
78
+ scalars: Array.from(document.text).length,
79
+ })}
80
+ </summary>
81
+ <p className="studio-annotation__text">{document.text}</p>
82
+ {document.sentences.map((sentence, sentenceIndex) => {
83
+ if (sentence.startToken >= visibleTokens) return null;
84
+ const tokens = document.tokens.slice(sentence.startToken, Math.min(sentence.endToken, visibleTokens));
85
+ return (
86
+ <div key={sentenceIndex} className="studio-annotation__sentence">
87
+ <strong>{t('StudioResults.annotation.sentence', { index: sentenceIndex + 1 })}</strong>
88
+ <table className="studio-annotation__tokens">
89
+ <thead>
90
+ <tr>
91
+ <th>#</th>
92
+ <th>{t('StudioResults.annotation.token')}</th>
93
+ <th>{t('StudioResults.annotation.span')}</th>
94
+ <th>{t('StudioResults.annotation.partOfSpeech')}</th>
95
+ <th>{t('StudioResults.annotation.dependency')}</th>
96
+ <th>{t('StudioResults.annotation.head')}</th>
97
+ </tr>
98
+ </thead>
99
+ <tbody>
100
+ {tokens.map((token, offset) => {
101
+ const tokenIndex = sentence.startToken + offset;
102
+ return (
103
+ <tr key={tokenIndex}>
104
+ <td>{tokenIndex}</td>
105
+ <td><code>{token.text}</code>{token.isPunctuation ? ` · ${t('StudioResults.annotation.punctuation')}` : ''}</td>
106
+ <td><code>{`[${token.start}, ${token.end})`}</code></td>
107
+ <td>{token.partOfSpeech}</td>
108
+ <td>{token.dependency}</td>
109
+ <td>{token.headIndex}</td>
110
+ </tr>
111
+ );
112
+ })}
113
+ </tbody>
114
+ </table>
115
+ </div>
116
+ );
117
+ })}
118
+ {document.tokens.length > visibleTokens ? (
119
+ <p className="studio-result__hint">{t('StudioResults.annotation.truncatedView', { shown: visibleTokens, total: document.tokens.length })}</p>
120
+ ) : null}
121
+ </details>
122
+ );
123
+ }
@@ -1,3 +1,5 @@
1
+ import type { StudioManagedArtifact } from './runtime-types.js';
2
+
1
3
  export type StudioArtifactPreviewSource = {
2
4
  relativePath?: string;
3
5
  mediaType?: string;
@@ -5,6 +7,7 @@ export type StudioArtifactPreviewSource = {
5
7
  displayName?: string;
6
8
  previewSource?: 'managed-asset';
7
9
  sizeBytes?: number;
10
+ speechAlignment?: StudioManagedArtifact['speechAlignment'];
8
11
  };
9
12
 
10
13
  export type StudioArtifactRenderBranch =
@@ -0,0 +1,26 @@
1
+ import { useAIStudioHost } from './host-context.js';
2
+ import { ArtifactMediaResult } from './section-ai-testing-output.js';
3
+ import type { StudioAudioSeparation } from './runtime-types.js';
4
+ import { audioSeparationRequestFromParameters } from './audio-separation-request.js';
5
+
6
+ export function AudioSeparationNotice({ value, submittedParameters }: {
7
+ readonly value?: StudioAudioSeparation;
8
+ readonly submittedParameters?: Readonly<Record<string, unknown>>;
9
+ }) {
10
+ const host = useAIStudioHost(); const { translate: t } = host;
11
+ if (!value) return null;
12
+ const request = value.request ?? audioSeparationRequestFromParameters(submittedParameters);
13
+ const rangeKey = request?.kind === 'range'
14
+ ? request.endSeconds === undefined ? 'AudioSeparate.processedRangeToEnd' : 'AudioSeparate.processedRange'
15
+ : request?.kind === 'full-source' ? 'AudioSeparate.processedFullSource' : 'AudioSeparate.processedRangeUnknown';
16
+ return <section className="space-y-3" aria-label={t('AudioSeparate.result')}>
17
+ <p className="studio-result__plain" data-audio-separation-range>{t(rangeKey, request?.kind === 'range'
18
+ ? { start: request.startSeconds, end: request.endSeconds } : undefined)}</p>
19
+ <p className="text-sm opacity-70">{t('AudioSeparate.derivation')}</p>
20
+ <ArtifactMediaResult artifact={value.sourceAudio} fallbackLabel={t('AudioSeparate.source')} mediaLabel={t('AudioSeparate.source')} />
21
+ <ArtifactMediaResult artifact={value.vocals} fallbackLabel={t('AudioSeparate.vocals')} mediaLabel={t('AudioSeparate.vocals')} />
22
+ <ArtifactMediaResult artifact={value.background} fallbackLabel={t('AudioSeparate.background')} mediaLabel={t('AudioSeparate.background')} />
23
+ {value.instrumentParts?.map(part => <ArtifactMediaResult key={part.artifact.relativePath} artifact={part.artifact}
24
+ fallbackLabel={t(`AudioSeparate.parts.${part.kind}`)} mediaLabel={t(`AudioSeparate.parts.${part.kind}`)} />)}
25
+ </section>;
26
+ }
@@ -1,10 +1,10 @@
1
1
  import { useId, useState, type ChangeEvent, type ReactNode } from 'react';
2
- import { Button, IconButton, NimiText, TextareaField, Tooltip } from '@nimiplatform/kit/ui';
2
+ import { Button, IconButton, InlineAlert, NimiText, TextareaField, Tooltip } from '@nimiplatform/kit/ui';
3
3
  import { ArrowUp, Paperclip, Play, Plus, RefreshCw, ScanSearch, SlidersHorizontal, X } from 'lucide-react';
4
4
  import type { BrowserDataUrlAttachment } from '@nimiplatform/kit/features/chat/headless';
5
5
  import { useAIStudioHost } from './host-context.js';
6
6
  import type { StudioCapabilityRegistration } from './module-registration.js';
7
- import { hasStudioCapabilityRunInput } from './section-ai-testing-input.js';
7
+ import { hasStudioCapabilityRunInput, usesVerbatimStudioPrompt } from './section-ai-testing-input.js';
8
8
  import { VisionLocateImageInput } from './section-ai-testing-vision-input.js';
9
9
 
10
10
  function IntentSummaryChip({
@@ -50,6 +50,8 @@ export function TextStudioComposer({
50
50
  intentLabel,
51
51
  running,
52
52
  attachments,
53
+ attachmentPickerEnabled = true,
54
+ attachmentWarning,
53
55
  onOpenAttachmentPicker,
54
56
  onRemoveAttachment,
55
57
  canDispatch,
@@ -70,6 +72,8 @@ export function TextStudioComposer({
70
72
  intentLabel: string;
71
73
  running: boolean;
72
74
  attachments: readonly BrowserDataUrlAttachment[];
75
+ attachmentPickerEnabled?: boolean;
76
+ attachmentWarning?: string;
73
77
  onOpenAttachmentPicker: () => void;
74
78
  onRemoveAttachment: (index: number) => void;
75
79
  canDispatch: boolean;
@@ -92,15 +96,17 @@ export function TextStudioComposer({
92
96
  const isReadOnlyComposer = profile.inputKind === 'none';
93
97
  const requiresPrompt = !isReadOnlyComposer;
94
98
  const contextAttached = Boolean(context.trim());
95
- const supportsContext = requiresPrompt && capability.id !== 'audio.transcribe' && !isVisionLocate;
99
+ const supportsContext = requiresPrompt && !usesVerbatimStudioPrompt(capability.id) && !profile.rawPrompt;
96
100
  const [contextOpen, setContextOpen] = useState(false);
97
101
  const [parametersOpen, setParametersOpen] = useState(false);
98
102
  const promptReady = hasStudioCapabilityRunInput({ requiresPrompt, prompt, hasAlternativeInput })
103
+ && ((capability.id !== 'music.transcribe' && capability.id !== 'audio.voice.convert' && capability.id !== 'audio.separate') || hasAlternativeInput)
104
+ && (!profile.requiresParameterInput || hasAlternativeInput)
99
105
  && (!isVisionLocate || (attachments.length === 1 && attachments[0]?.kind === 'image'));
100
106
  const intentConfigAction = Boolean(onOpenIntentConfig) && !canDispatch && canConfigureIntent;
101
107
  const generateDisabled = isVisionLocate
102
108
  ? running || (!intentConfigAction && (!promptReady || !canDispatch))
103
- : running || !promptReady || (!canDispatch && !intentConfigAction);
109
+ : running || !promptReady || Boolean(attachmentWarning) || (!canDispatch && !intentConfigAction);
104
110
  const generateLabel = running
105
111
  ? t(profile.primaryRunningLabelKey)
106
112
  : intentConfigAction
@@ -142,9 +148,9 @@ export function TextStudioComposer({
142
148
  onOpen={onOpenIntentConfig}
143
149
  configurable={intentConfigurable && Boolean(onOpenIntentConfig)}
144
150
  />
145
- {profile.supportsAttachments && !isVisionLocate ? (
151
+ {profile.supportsAttachments && !isVisionLocate && (attachmentPickerEnabled || attachments.length > 0) ? (
146
152
  <div className="studio-attachment-strip studio-attachment-strip--icon">
147
- <Tooltip content={t('Studio.composer.attachContext')} placement="top">
153
+ {attachmentPickerEnabled ? <Tooltip content={t('Studio.composer.attachContext')} placement="top">
148
154
  <Button
149
155
  type="button"
150
156
  className="h-8 w-8 rounded-full px-0"
@@ -156,7 +162,7 @@ export function TextStudioComposer({
156
162
  >
157
163
  <Paperclip size={15} aria-hidden="true" />
158
164
  </Button>
159
- </Tooltip>
165
+ </Tooltip> : null}
160
166
  {attachments.map((item, index) => (
161
167
  <span key={item.id} className="studio-attachment-chip">
162
168
  {item.kind === 'image' ? (
@@ -208,6 +214,7 @@ export function TextStudioComposer({
208
214
  );
209
215
  return (
210
216
  <div className={`studio-composer${compact ? ' studio-composer--compact' : ''}${isVisionLocate ? ' studio-composer--vision' : ''}`}>
217
+ {attachmentWarning ? <InlineAlert tone="warning">{attachmentWarning}</InlineAlert> : null}
211
218
  {isVisionLocate ? <VisionLocateImageInput
212
219
  image={attachments[0]?.kind === 'image' ? attachments[0] : undefined}
213
220
  disabled={running}