@nimiplatform/app-tools 0.7.5 → 0.12.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 (97) hide show
  1. package/README.md +59 -5
  2. package/bin/nimi-app.mjs +11 -3
  3. package/lib/app-access-declaration.mjs +1 -0
  4. package/lib/app-dependency-combinations.mjs +16 -28
  5. package/lib/app-doctor-update.mjs +66 -7
  6. package/lib/app-info.mjs +8 -1
  7. package/lib/app-project-lifecycle.mjs +82 -9
  8. package/lib/app-scaffold-capabilities.mjs +3 -3
  9. package/lib/app-scaffold-profiles.mjs +96 -26
  10. package/lib/app-scaffold.mjs +54 -7
  11. package/lib/canonical-capability-ids.generated.mjs +4 -0
  12. package/package.json +26 -25
  13. package/scripts/dev-shell.mjs +61 -17
  14. package/skills/nimi-app-lifecycle/references/acceptance.md +1 -1
  15. package/skills/nimi-app-lifecycle/references/adapt.md +2 -2
  16. package/skills/nimi-app-lifecycle/references/release.md +1 -1
  17. package/skills/nimi-app-lifecycle/references/upgrade-platform.md +14 -0
  18. package/templates/app-source/src/ai-studio-core/ai-config.ts +17 -3
  19. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +40 -3
  20. package/templates/app-source/src/ai-studio-core/audio-separation-request.ts +24 -0
  21. package/templates/app-source/src/ai-studio-core/contexts.tsx +4 -0
  22. package/templates/app-source/src/ai-studio-core/history-policy.ts +395 -41
  23. package/templates/app-source/src/ai-studio-core/history.ts +262 -10
  24. package/templates/app-source/src/ai-studio-core/host-context.tsx +15 -2
  25. package/templates/app-source/src/ai-studio-core/index.ts +15 -4
  26. package/templates/app-source/src/ai-studio-core/job-recovery-panel.tsx +105 -0
  27. package/templates/app-source/src/ai-studio-core/job-recovery.ts +224 -0
  28. package/templates/app-source/src/ai-studio-core/managed-result-references.ts +79 -0
  29. package/templates/app-source/src/ai-studio-core/messages/en.json +185 -10
  30. package/templates/app-source/src/ai-studio-core/messages/zh.json +185 -10
  31. package/templates/app-source/src/ai-studio-core/module-registration.ts +9 -1
  32. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +81 -2
  33. package/templates/app-source/src/ai-studio-core/parameters.ts +34 -1
  34. package/templates/app-source/src/ai-studio-core/runtime-types.ts +124 -8
  35. package/templates/app-source/src/ai-studio-core/runtime.ts +218 -20
  36. package/templates/app-source/src/ai-studio-core/section-ai-testing-annotation-result.tsx +123 -0
  37. package/templates/app-source/src/ai-studio-core/section-ai-testing-artifact-preview.ts +3 -0
  38. package/templates/app-source/src/ai-studio-core/section-ai-testing-audio-separation-result.tsx +26 -0
  39. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +14 -7
  40. package/templates/app-source/src/ai-studio-core/section-ai-testing-decision-result.tsx +76 -0
  41. package/templates/app-source/src/ai-studio-core/section-ai-testing-exchange-result.tsx +71 -0
  42. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +20 -4
  43. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +29 -0
  44. package/templates/app-source/src/ai-studio-core/section-ai-testing-music-result.tsx +45 -0
  45. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +132 -10
  46. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +122 -38
  47. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +4 -3
  48. package/templates/app-source/src/ai-studio-core/section-ai-testing-session-result.tsx +66 -0
  49. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +100 -22
  50. package/templates/app-source/src/ai-studio-core/section-ai-testing-surface.tsx +6 -0
  51. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcript-result.tsx +45 -0
  52. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcription-result.tsx +106 -0
  53. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-result.tsx +23 -4
  54. package/templates/app-source/src/ai-studio-core/section-ai-testing-voice-asset-actions.tsx +40 -0
  55. package/templates/app-source/src/ai-studio-core/section-ai-testing-voice-conversion-result.tsx +20 -0
  56. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +219 -35
  57. package/templates/app-source/src/ai-studio-core/text-annotation-document.ts +50 -0
  58. package/templates/app-source/src/ai-studio-core/text-media-replay.ts +51 -0
  59. package/templates/app-source/src/ai-studio-core/voice-assets.ts +17 -0
  60. package/templates/app-source/src/ai-studio-core/workspace.tsx +48 -6
  61. package/templates/app-source/src/studio-modules/studio-create/descriptors.ts +1 -1
  62. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +13 -1
  63. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +13 -1
  64. package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +11 -2
  65. package/templates/app-source/src/studio-modules/studio-create/parameters.ts +2 -2
  66. package/templates/app-source/src/studio-modules/studio-create/registration.ts +2 -2
  67. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +121 -3
  68. package/templates/app-source/src/studio-modules/studio-media/audio-separate-parameters.tsx +72 -0
  69. package/templates/app-source/src/studio-modules/studio-media/audio-separate-runtime.ts +90 -0
  70. package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +16 -1
  71. package/templates/app-source/src/studio-modules/studio-media/index.ts +2 -0
  72. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +225 -7
  73. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +225 -7
  74. package/templates/app-source/src/studio-modules/studio-media/music-parameters.tsx +85 -0
  75. package/templates/app-source/src/studio-modules/studio-media/music-transcription-parameters.tsx +85 -0
  76. package/templates/app-source/src/studio-modules/studio-media/music-transcription-runtime.ts +64 -0
  77. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +9 -26
  78. package/templates/app-source/src/studio-modules/studio-media/parameters.ts +170 -6
  79. package/templates/app-source/src/studio-modules/studio-media/registration.ts +29 -1
  80. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +90 -6
  81. package/templates/app-source/src/studio-modules/studio-media/vision-parameters.tsx +1 -0
  82. package/templates/app-source/src/studio-modules/studio-media/vision-runtime.ts +23 -5
  83. package/templates/app-source/src/studio-modules/studio-media/voice-convert-parameters.tsx +132 -0
  84. package/templates/app-source/src/studio-modules/studio-media/voice-convert-runtime.ts +120 -0
  85. package/templates/app-source/src/studio-modules/studio-voice/audio-url.ts +25 -0
  86. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +4 -4
  87. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +4 -4
  88. package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +28 -0
  89. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +66 -30
  90. package/templates/app-source/src/workbench-core/index.ts +2 -0
  91. package/templates/app-source/src/workbench-core/runtime-gate.tsx +102 -6
  92. package/templates/app-source/src/workbench-core/workbench-core.css +42 -0
  93. package/templates/app-source/src/workbench-core/workbench-core.tsx +69 -18
  94. package/templates/app-source.manifest.json +100 -0
  95. package/templates/default-starter/README.md +2 -1
  96. package/templates/default-starter/src/shell/workbench-target-adapter.ts +102 -12
  97. package/templates/default-starter.manifest.json +0 -4
@@ -1,11 +1,13 @@
1
1
  import { isJsonObject } from '@nimiplatform/sdk/types';
2
+ import { validateNimiLocalAppSpeechTranscript } from '@nimiplatform/sdk/app';
3
+ import { isAudioSeparationRequest } from './audio-separation-request.js';
4
+ import { studioResultAssetPaths, studioWorldInputSource } from './managed-result-references.js';
2
5
 
3
6
  import type { AIStudioHistoryPanelPreferences } from './workspace.js';
4
7
  import type { StudioRunHistory, StudioRunHistoryRecord } from './history.js';
5
8
 
6
- export const STUDIO_HISTORY_LIMIT_PER_CAPABILITY = 40;
7
- export const STUDIO_HISTORY_LIMIT_TOTAL_RECORDS = 160;
8
- export const STUDIO_HISTORY_LIMIT_BYTES = 240 * 1024;
9
+ // Existing records may truthfully carry a previously truncated input preview.
10
+ const STORED_INPUT_PREVIEW_MAX_BYTES = 16 * 1024;
9
11
 
10
12
  export const DEFAULT_AI_STUDIO_HISTORY_PANEL_PREFERENCES: AIStudioHistoryPanelPreferences = Object.freeze({
11
13
  collapsed: true,
@@ -36,7 +38,7 @@ function optionalNonNegativeNumber(value: unknown, path: string): void {
36
38
  if (value !== undefined) nonNegativeNumber(value, path);
37
39
  }
38
40
 
39
- function validateManagedArtifact(value: unknown, path: string): void {
41
+ export function validateManagedArtifact(value: unknown, path: string): void {
40
42
  if (!isJsonObject(value)) historyError(path, 'requires an object');
41
43
  requiredString(value.relativePath, `${path}.relativePath`);
42
44
  optionalString(value.mediaType, `${path}.mediaType`);
@@ -45,9 +47,142 @@ function validateManagedArtifact(value: unknown, path: string): void {
45
47
  if (!/^sha256:[0-9a-f]{64}$/u.test(sha256)) historyError(`${path}.sha256`, 'requires a canonical SHA-256 digest');
46
48
  optionalString(value.displayName, `${path}.displayName`);
47
49
  if (value.previewSource !== 'managed-asset') historyError(`${path}.previewSource`, 'requires managed-asset');
50
+ if (value.speechAlignment !== undefined) {
51
+ const alignment = value.speechAlignment;
52
+ if (typeof value.mediaType !== 'string' || !value.mediaType.startsWith('audio/') || !isJsonObject(alignment) || typeof alignment.unit !== 'number' || ![1, 2].includes(alignment.unit) || !Array.isArray(alignment.tokens) || !alignment.tokens.length) historyError(path, 'requires typed audio alignment');
53
+ let start = 0, end = 0;
54
+ for (const token of alignment.tokens) {
55
+ if (!isJsonObject(token) || typeof token.token !== 'string' || token.token.length === 0 ||
56
+ typeof token.startMs !== 'string' || typeof token.endMs !== 'string' ||
57
+ !/^(0|[1-9]\d*)$/u.test(token.startMs) || !/^(0|[1-9]\d*)$/u.test(token.endMs)) historyError(path, 'has an invalid alignment token');
58
+ const nextStart = nonNegativeSafeInteger(Number(token.startMs), path), nextEnd = nonNegativeSafeInteger(Number(token.endMs), path);
59
+ if (nextStart < start || nextEnd < end || nextEnd < nextStart) historyError(path, 'has out-of-order alignment');
60
+ start = nextStart; end = nextEnd;
61
+ }
62
+ }
63
+ }
64
+
65
+ function boundedNonEmptyString(value: unknown, path: string, maxLength: number): string {
66
+ if (typeof value !== 'string' || !value || value.length > maxLength) historyError(path, 'requires a bounded non-empty string');
67
+ return value as string;
68
+ }
69
+
70
+ function optionalNonEmptyString(value: unknown, path: string, maxLength: number): void {
71
+ if (value !== undefined) boundedNonEmptyString(value, path, maxLength);
72
+ }
73
+
74
+ function nonNegativeSafeInteger(value: unknown, path: string): number {
75
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) historyError(path, 'requires a non-negative safe integer');
76
+ return value as number;
77
+ }
78
+
79
+ function validTimestamp(value: unknown, path: string): void {
80
+ if (Number.isNaN(new Date(requiredString(value, path)).valueOf())) historyError(path, 'requires a valid timestamp');
81
+ }
82
+
83
+ function validateHistoryJson(value: unknown, path: string, depth = 0): void {
84
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return;
85
+ if (typeof value === 'number' && Number.isFinite(value)) return;
86
+ if (depth > 32) historyError(path, 'exceeds the JSON depth bound');
87
+ if (Array.isArray(value)) {
88
+ value.forEach((entry, index) => validateHistoryJson(entry, `${path}[${index}]`, depth + 1));
89
+ return;
90
+ }
91
+ if (!isJsonObject(value)) historyError(path, 'requires JSON data');
92
+ for (const [key, entry] of Object.entries(value)) validateHistoryJson(entry, `${path}.${key}`, depth + 1);
93
+ }
94
+
95
+ export function validateFaceSwapHistory(value: unknown, path: string): void {
96
+ if (!isJsonObject(value) || !Array.isArray(value.inputs) || value.inputs.length !== 2) historyError(path, 'requires one reference and one target input');
97
+ const roles = new Set<string>();
98
+ for (const [index, input] of value.inputs.entries()) {
99
+ const inputPath = `${path}.inputs[${index}]`;
100
+ if (!isJsonObject(input) || !['reference-image', 'target-image', 'target-video'].includes(String(input.role)) || roles.has(String(input.role))) {
101
+ historyError(inputPath, 'has an invalid or duplicate role');
102
+ }
103
+ roles.add(String(input.role));
104
+ boundedNonEmptyString(input.name, `${inputPath}.name`, 255);
105
+ boundedNonEmptyString(input.mediaType, `${inputPath}.mediaType`, 255);
106
+ nonNegativeSafeInteger(input.sizeBytes, `${inputPath}.sizeBytes`);
107
+ if (!/^sha256:[0-9a-f]{64}$/u.test(requiredString(input.sha256, `${inputPath}.sha256`))) historyError(`${inputPath}.sha256`, 'requires a canonical SHA-256 digest');
108
+ }
109
+ const video = roles.has('target-video');
110
+ if (!roles.has('reference-image') || video === roles.has('target-image')) historyError(path, 'requires exactly one reference image and one target');
111
+ if (video !== (value.noFacePolicy !== undefined)) historyError(`${path}.noFacePolicy`, 'must be present exactly for a video target');
112
+ if (value.noFacePolicy !== undefined && value.noFacePolicy !== 'fail' && value.noFacePolicy !== 'preserve-frame') historyError(`${path}.noFacePolicy`, 'is invalid');
113
+ if (value.video !== undefined) {
114
+ const summary = value.video;
115
+ if (!video || !isJsonObject(summary)) historyError(`${path}.video`, 'requires a video target summary');
116
+ const total = nonNegativeSafeInteger(summary.totalFrames, `${path}.video.totalFrames`);
117
+ const transformed = nonNegativeSafeInteger(summary.transformedFrames, `${path}.video.transformedFrames`);
118
+ const preserved = nonNegativeSafeInteger(summary.preservedFrames, `${path}.video.preservedFrames`);
119
+ nonNegativeSafeInteger(summary.durationUs, `${path}.video.durationUs`);
120
+ if (total !== transformed + preserved || ![24, 25, 30].includes(Number(summary.frameRate)) || typeof summary.audioPreserved !== 'boolean') {
121
+ historyError(`${path}.video`, 'has inconsistent video facts');
122
+ }
123
+ }
124
+ }
125
+
126
+ function validateTextExchangeItem(value: unknown, path: string): void {
127
+ if (!isJsonObject(value)) historyError(path, 'requires an object');
128
+ if (value.type === 'text' || value.type === 'reasoning-summary') {
129
+ requiredString(value.text, `${path}.text`);
130
+ return;
131
+ }
132
+ if (value.type === 'reasoning-continuity') {
133
+ requiredString(value.carrierKind, `${path}.carrierKind`);
134
+ nonNegativeSafeInteger(value.version, `${path}.version`);
135
+ nonNegativeSafeInteger(value.payloadBytes, `${path}.payloadBytes`);
136
+ return;
137
+ }
138
+ if (value.type === 'tool-call' || value.type === 'tool-result') {
139
+ boundedNonEmptyString(value.toolCallId, `${path}.toolCallId`, 128);
140
+ boundedNonEmptyString(value.toolName, `${path}.toolName`, 128);
141
+ validateHistoryJson(value.type === 'tool-call' ? value.arguments : value.result, `${path}.${value.type === 'tool-call' ? 'arguments' : 'result'}`);
142
+ if (value.type === 'tool-result' && typeof value.isError !== 'boolean') historyError(`${path}.isError`, 'requires a boolean');
143
+ return;
144
+ }
145
+ historyError(`${path}.type`, 'has an unsupported value');
48
146
  }
49
147
 
50
- function validateHistoryResult(value: unknown, path: string): void {
148
+ function decisionProbability(value: unknown, path: string): void {
149
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) historyError(path, 'requires a probability from 0 to 1');
150
+ }
151
+
152
+ // Answers keep submitted order; a choice keeps every submitted candidate once
153
+ // and selects one of them.
154
+ function validateTextDecisionAnswers(value: unknown, questionCount: number, path: string): void {
155
+ if (!Array.isArray(value) || value.length !== questionCount) historyError(path, 'requires one answer per question');
156
+ const questionIds = new Set<string>();
157
+ value.forEach((answer, index) => {
158
+ const answerPath = `${path}[${index}]`;
159
+ if (!isJsonObject(answer)) historyError(answerPath, 'requires an object');
160
+ const questionId = boundedNonEmptyString(answer.questionId, `${answerPath}.questionId`, 64);
161
+ if (questionIds.has(questionId)) historyError(`${answerPath}.questionId`, 'is repeated');
162
+ questionIds.add(questionId);
163
+ if (answer.kind === 'boolean') {
164
+ decisionProbability(answer.trueProbability, `${answerPath}.trueProbability`);
165
+ return;
166
+ }
167
+ if (answer.kind !== 'choice') historyError(`${answerPath}.kind`, 'has an unsupported value');
168
+ if (!Array.isArray(answer.probabilities) || answer.probabilities.length < 2 || answer.probabilities.length > 255) {
169
+ historyError(`${answerPath}.probabilities`, 'requires 2 to 255 candidates');
170
+ }
171
+ const candidateIds = new Set<string>();
172
+ answer.probabilities.forEach((entry, position) => {
173
+ const entryPath = `${answerPath}.probabilities[${position}]`;
174
+ if (!isJsonObject(entry)) historyError(entryPath, 'requires an object');
175
+ const candidateId = boundedNonEmptyString(entry.candidateId, `${entryPath}.candidateId`, 64);
176
+ if (candidateIds.has(candidateId)) historyError(`${entryPath}.candidateId`, 'is repeated');
177
+ candidateIds.add(candidateId);
178
+ decisionProbability(entry.probability, `${entryPath}.probability`);
179
+ });
180
+ const selected = boundedNonEmptyString(answer.selectedCandidateId, `${answerPath}.selectedCandidateId`, 64);
181
+ if (!candidateIds.has(selected)) historyError(`${answerPath}.selectedCandidateId`, 'is not one of its candidates');
182
+ });
183
+ }
184
+
185
+ export function validateStudioHistoryResult(value: unknown, path: string): void {
51
186
  if (!isJsonObject(value) || typeof value.ok !== 'boolean') historyError(path, 'requires a discriminated result object');
52
187
  const kind = requiredString(value.kind, `${path}.kind`);
53
188
  requiredString(value.summary, `${path}.summary`);
@@ -59,6 +194,7 @@ function validateHistoryResult(value: unknown, path: string): void {
59
194
  requiredString(value.message, `${path}.message`);
60
195
  requiredString(value.actionHint, `${path}.actionHint`);
61
196
  optionalString(value.missingSurface, `${path}.missingSurface`);
197
+ optionalNonEmptyString(value.jobId, `${path}.jobId`, 128);
62
198
  if (value.diagnostics !== undefined) {
63
199
  if (!isJsonObject(value.diagnostics)) historyError(`${path}.diagnostics`, 'requires an object');
64
200
  const reasonCode = requiredString(value.diagnostics.reasonCode, `${path}.diagnostics.reasonCode`);
@@ -87,6 +223,10 @@ function validateHistoryResult(value: unknown, path: string): void {
87
223
  optionalString(value.traceId, `${path}.traceId`);
88
224
  if (kind === 'vision-locate') {
89
225
  requiredString(value.jobId, `${path}.jobId`);
226
+ if (value.sourceImage !== undefined) {
227
+ validateManagedArtifact(value.sourceImage, `${path}.sourceImage`);
228
+ if (!isJsonObject(value.sourceImage) || !['image/png','image/jpeg','image/webp','image/gif'].includes(String(value.sourceImage.mediaType))) historyError(`${path}.sourceImage`, 'requires the saved input image');
229
+ }
90
230
  const result = value.result;
91
231
  if (result === undefined) return;
92
232
  if (!isJsonObject(result) || typeof result.imageArtifactId !== 'string' || !result.imageArtifactId || !Number.isInteger(result.width) || (result.width as number) <= 0 || !Number.isInteger(result.height) || (result.height as number) <= 0 || !Array.isArray(result.locations)) historyError(path, 'requires a typed Locate result');
@@ -102,6 +242,12 @@ function validateHistoryResult(value: unknown, path: string): void {
102
242
  if (kind === 'text') {
103
243
  requiredString(value.body, `${path}.body`);
104
244
  nonNegativeNumber(value.charCount, `${path}.charCount`);
245
+ if (value.sourceImage !== undefined) {
246
+ validateManagedArtifact(value.sourceImage, `${path}.sourceImage`);
247
+ if (!isJsonObject(value.sourceImage) || !['image/png', 'image/jpeg', 'image/webp', 'image/gif', 'audio/wav', 'audio/mpeg', 'video/mp4'].includes(String(value.sourceImage.mediaType))) {
248
+ historyError(`${path}.sourceImage`, 'requires a saved input media artifact');
249
+ }
250
+ }
105
251
  requiredString(value.finishReason, `${path}.finishReason`);
106
252
  if (typeof value.streamed !== 'boolean') historyError(`${path}.streamed`, 'requires a boolean');
107
253
  optionalNonNegativeNumber(value.inputTokens, `${path}.inputTokens`);
@@ -109,16 +255,71 @@ function validateHistoryResult(value: unknown, path: string): void {
109
255
  optionalNonNegativeNumber(value.totalTokens, `${path}.totalTokens`);
110
256
  return;
111
257
  }
258
+ if (kind === 'speaker-embedding') {
259
+ requiredString(value.jobId, path + '.jobId');
260
+ requiredString(value.spaceId, path + '.spaceId');
261
+ if (!Array.isArray(value.vector) || !value.vector.length || value.vector.length > 4096 || value.vector.some(item => typeof item !== 'number' || !Number.isFinite(item))) historyError(path, 'requires the complete finite speaker vector');
262
+ return;
263
+ }
112
264
  if (kind === 'embedding') {
113
265
  nonNegativeNumber(value.vectorCount, `${path}.vectorCount`);
114
266
  nonNegativeNumber(value.dimensions, `${path}.dimensions`);
267
+ // Records saved before the embedding space was retained have no spaceId.
268
+ optionalNonEmptyString(value.spaceId, `${path}.spaceId`, 128);
115
269
  if (!Array.isArray(value.sample) || value.sample.some((entry) => typeof entry !== 'number' || !Number.isFinite(entry))) {
116
270
  historyError(`${path}.sample`, 'requires finite numbers');
117
271
  }
118
272
  optionalNonNegativeNumber(value.totalTokens, `${path}.totalTokens`);
119
273
  return;
120
274
  }
275
+ if (kind === 'text-annotation') {
276
+ requiredString(value.jobId, `${path}.jobId`);
277
+ requiredString(value.jobState, `${path}.jobState`);
278
+ if (!/^[a-z-]{2,16}$/u.test(requiredString(value.language, `${path}.language`))) historyError(`${path}.language`, 'is invalid');
279
+ nonNegativeSafeInteger(value.documentCount, `${path}.documentCount`);
280
+ nonNegativeSafeInteger(value.tokenCount, `${path}.tokenCount`);
281
+ nonNegativeSafeInteger(value.sentenceCount, `${path}.sentenceCount`);
282
+ validateManagedArtifact(value.document, `${path}.document`);
283
+ if (!isJsonObject(value.document) || value.document.mediaType !== 'application/json') historyError(`${path}.document`, 'requires a saved JSON document');
284
+ return;
285
+ }
286
+ if (kind === 'text-exchange') {
287
+ if (value.scenario !== 'tool-call' && value.scenario !== 'structured-output') historyError(`${path}.scenario`, 'is invalid');
288
+ if (!Array.isArray(value.steps) || value.steps.length === 0 || value.steps.length > 16) historyError(`${path}.steps`, 'requires 1 to 16 steps');
289
+ value.steps.forEach((step, index) => {
290
+ const stepPath = `${path}.steps[${index}]`;
291
+ if (!isJsonObject(step) || (step.origin !== 'model' && step.origin !== 'app') || !Array.isArray(step.items) || step.items.length === 0 || step.items.length > 64) {
292
+ historyError(stepPath, 'requires an origin and 1 to 64 items');
293
+ }
294
+ optionalString(step.finishReason, `${stepPath}.finishReason`);
295
+ optionalString(step.traceId, `${stepPath}.traceId`);
296
+ step.items.forEach((item, itemIndex) => validateTextExchangeItem(item, `${stepPath}.items[${itemIndex}]`));
297
+ });
298
+ requiredString(value.text, `${path}.text`);
299
+ if (value.structured !== undefined) validateHistoryJson(value.structured, `${path}.structured`);
300
+ return;
301
+ }
302
+ if (kind === 'text-decision') {
303
+ const questionCount = nonNegativeSafeInteger(value.questionCount, `${path}.questionCount`);
304
+ if (questionCount < 1 || questionCount > 64) historyError(`${path}.questionCount`, 'requires 1 to 64 questions');
305
+ if (value.answers !== undefined) validateTextDecisionAnswers(value.answers, questionCount, `${path}.answers`);
306
+ return;
307
+ }
308
+ if (kind === 'session') {
309
+ requiredString(value.capabilityContract, `${path}.capabilityContract`);
310
+ validTimestamp(value.startedAt, `${path}.startedAt`);
311
+ validTimestamp(value.endedAt, `${path}.endedAt`);
312
+ if (value.ending !== 'closed' && value.ending !== 'terminated') historyError(`${path}.ending`, 'is invalid');
313
+ requiredString(value.terminalReason, `${path}.terminalReason`);
314
+ if (!isJsonObject(value.observed) || Object.keys(value.observed).length > 32) historyError(`${path}.observed`, 'requires at most 32 counters');
315
+ for (const [key, count] of Object.entries(value.observed)) {
316
+ if (!/^[a-z][a-z0-9-]{0,63}$/u.test(key)) historyError(`${path}.observed`, `has an invalid counter ${key}`);
317
+ nonNegativeSafeInteger(count, `${path}.observed.${key}`);
318
+ }
319
+ return;
320
+ }
121
321
  if (kind === 'artifacts') {
322
+ if (value.sourceImage !== undefined) validateManagedArtifact(value.sourceImage, `${path}.sourceImage`);
122
323
  requiredString(value.jobId, `${path}.jobId`);
123
324
  requiredString(value.jobState, `${path}.jobState`);
124
325
  nonNegativeNumber(value.artifactCount, `${path}.artifactCount`);
@@ -128,6 +329,144 @@ function validateHistoryResult(value: unknown, path: string): void {
128
329
  if (value.artifacts.length !== value.artifactCount) historyError(`${path}.artifacts`, 'must match artifactCount');
129
330
  }
130
331
  if (value.firstArtifact !== undefined) validateManagedArtifact(value.firstArtifact, `${path}.firstArtifact`);
332
+ if (value.faceSwap !== undefined) {
333
+ if (value.musicGeneration !== undefined || value.musicTranscription !== undefined || value.voiceConversion !== undefined || value.audioSeparation !== undefined) {
334
+ historyError(path, 'mixes face replacement with another result');
335
+ }
336
+ validateFaceSwapHistory(value.faceSwap, `${path}.faceSwap`);
337
+ }
338
+ if (value.musicTranscription !== undefined) {
339
+ const music = value.musicTranscription;
340
+ if (value.musicGeneration !== undefined || !isJsonObject(music) || !isJsonObject(music.sourceInfo)
341
+ || !isJsonObject(music.inputRange) || !Array.isArray(music.scores) || !Array.isArray(value.artifacts)
342
+ || music.origin !== 'transcribed-estimate' || !['unknown', 'complete', 'truncated'].includes(String(music.completeness))) historyError(path, 'requires complete transcription metadata');
343
+ validateManagedArtifact(music.sourceAudio, `${path}.sourceAudio`);
344
+ if (!isJsonObject(music.sourceAudio) || music.sourceAudio.mediaType !== 'audio/wav') historyError(path, 'requires saved canonical source audio');
345
+ const audio = music.sourceInfo;
346
+ for (const key of ['sampleRateHz', 'channels', 'frameCount', 'durationMs']) {
347
+ if (typeof audio[key] !== 'number' || !Number.isSafeInteger(audio[key])) historyError(path, 'has invalid transcription source facts');
348
+ }
349
+ if (Number(audio.sampleRateHz) < 8000 || Number(audio.sampleRateHz) > 96000 || ![1, 2].includes(Number(audio.channels))
350
+ || Number(audio.frameCount) < 1 || Number(audio.frameCount) > Number(audio.sampleRateHz) * 600
351
+ || audio.durationMs !== Math.floor(Number(audio.frameCount) * 1000 / Number(audio.sampleRateHz))) historyError(path, 'has inconsistent transcription source facts');
352
+ const range = music.inputRange;
353
+ if (!Number.isSafeInteger(range.startFrame) || !Number.isSafeInteger(range.endFrame) || Number(range.startFrame) < 0
354
+ || Number(range.endFrame) > Number(audio.frameCount) || Number(range.startFrame) >= Number(range.endFrame)) historyError(path, 'has an invalid transcription range');
355
+ const expected = new Map<string, string>(); const pairs = new Set<string>();
356
+ for (const score of music.scores) {
357
+ if (!isJsonObject(score) || typeof score.relativePath !== 'string' || !['abc', 'midi'].includes(String(score.format))
358
+ || !['vocal-melody', 'lead-sheet', 'full-arrangement', 'note-events'].includes(String(score.part))) historyError(path, 'has an invalid transcribed score');
359
+ const pair = `${score.format}:${score.part}`;
360
+ if (pairs.has(pair) || expected.has(score.relativePath)) historyError(path, 'duplicates a transcribed score');
361
+ pairs.add(pair); expected.set(score.relativePath, score.format === 'abc' ? 'text/vnd.abc' : 'audio/midi');
362
+ }
363
+ if (music.timelineRelativePath !== undefined) {
364
+ const timeline = requiredString(music.timelineRelativePath, `${path}.timelineRelativePath`);
365
+ if (expected.has(timeline)) historyError(path, 'duplicates its timeline');
366
+ expected.set(timeline, 'application/vnd.nimi.music-timeline+json');
367
+ }
368
+ if (!expected.size || value.artifacts.length !== expected.size) historyError(path, 'does not retain its complete transcription');
369
+ for (const artifact of value.artifacts) {
370
+ if (!isJsonObject(artifact) || typeof artifact.relativePath !== 'string' || expected.get(artifact.relativePath) !== artifact.mediaType) historyError(path, 'has mismatched transcription artifacts');
371
+ expected.delete(artifact.relativePath);
372
+ }
373
+ }
374
+ if (value.voiceConversion !== undefined) {
375
+ const voice = value.voiceConversion;
376
+ if (value.musicGeneration !== undefined || value.musicTranscription !== undefined || !isJsonObject(voice) || !isJsonObject(voice.sourceInfo)
377
+ || !isJsonObject(voice.inputRange) || !isJsonObject(voice.vocalInfo) || !isJsonObject(voice.vocal) || !Array.isArray(value.artifacts)
378
+ || !['EXACT', 'MODEL_FRAME_ROUNDING'].includes(String(voice.lengthRelation))) historyError(path, 'requires complete voice conversion metadata');
379
+ validateManagedArtifact(voice.sourceVocal, `${path}.sourceVocal`);
380
+ if (!isJsonObject(voice.sourceVocal) || voice.sourceVocal.mediaType !== 'audio/wav') historyError(path, 'requires saved canonical source vocal');
381
+ if (voice.targetVoice !== undefined) {
382
+ validateManagedArtifact(voice.targetVoice, `${path}.targetVoice`);
383
+ if (!isJsonObject(voice.targetVoice) || voice.targetVoice.mediaType !== 'audio/wav') historyError(path, 'requires saved canonical target voice');
384
+ }
385
+ const source = voice.sourceInfo;
386
+ const vocal = voice.vocalInfo;
387
+ for (const key of ['sampleRateHz', 'channels', 'frameCount', 'durationMs']) {
388
+ if (typeof source[key] !== 'number' || !Number.isSafeInteger(source[key])) historyError(path, 'has invalid voice conversion source facts');
389
+ if (typeof vocal[key] !== 'number' || !Number.isSafeInteger(vocal[key])) historyError(path, 'has invalid voice conversion vocal facts');
390
+ }
391
+ for (const audio of [source, vocal]) {
392
+ if (Number(audio.sampleRateHz) < 8000 || Number(audio.sampleRateHz) > 96000 || ![1, 2].includes(Number(audio.channels))
393
+ || Number(audio.frameCount) < 1 || Number(audio.frameCount) > Number(audio.sampleRateHz) * 600
394
+ || audio.durationMs !== Math.floor(Number(audio.frameCount) * 1000 / Number(audio.sampleRateHz))) historyError(path, 'has inconsistent voice conversion facts');
395
+ }
396
+ const range = voice.inputRange;
397
+ if (!Number.isSafeInteger(range.startFrame) || !Number.isSafeInteger(range.endFrame) || Number(range.startFrame) < 0
398
+ || Number(range.endFrame) > Number(source.frameCount) || Number(range.startFrame) >= Number(range.endFrame)) historyError(path, 'has an invalid voice conversion range');
399
+ const sourceRangeDurationMs = Math.floor((Number(range.endFrame) - Number(range.startFrame)) * 1000 / Number(source.sampleRateHz));
400
+ if (typeof voice.durationDeltaMs !== 'number' || !Number.isSafeInteger(voice.durationDeltaMs)
401
+ || voice.durationDeltaMs !== Number(vocal.durationMs) - sourceRangeDurationMs) historyError(path, 'has an inconsistent voice conversion duration delta');
402
+ if (voice.lengthRelation === 'EXACT' && voice.durationDeltaMs !== 0) historyError(path, 'has an inconsistent voice conversion length relation');
403
+ if (voice.lengthRelation === 'MODEL_FRAME_ROUNDING' && Math.abs(Number(voice.durationDeltaMs)) >= 1000) historyError(path, 'has an inconsistent voice conversion length relation');
404
+ validateManagedArtifact(voice.vocal, `${path}.vocal`);
405
+ if (!isJsonObject(voice.vocal) || voice.vocal.mediaType !== 'audio/wav') historyError(path, 'does not retain its converted vocal');
406
+ const vocalPath = requiredString(voice.vocal.relativePath, `${path}.vocal.relativePath`);
407
+ if (value.artifacts.length !== 1
408
+ || !value.artifacts.some((artifact) => isJsonObject(artifact) && artifact.relativePath === vocalPath && artifact.mediaType === 'audio/wav')) {
409
+ historyError(path, 'does not retain its converted vocal');
410
+ }
411
+ }
412
+ if (value.audioSeparation !== undefined) {
413
+ const separation = value.audioSeparation;
414
+ if (value.musicGeneration !== undefined || value.musicTranscription !== undefined || value.voiceConversion !== undefined
415
+ || !isJsonObject(separation) || !isJsonObject(separation.vocals) || !isJsonObject(separation.background) || !Array.isArray(value.artifacts)) {
416
+ historyError(path, 'requires complete audio separation metadata');
417
+ }
418
+ if (separation.request !== undefined && !isAudioSeparationRequest(separation.request)) historyError(path, 'has an invalid separation request');
419
+ validateManagedArtifact(separation.sourceAudio, `${path}.sourceAudio`);
420
+ if (!isJsonObject(separation.sourceAudio) || separation.sourceAudio.mediaType !== 'audio/wav') historyError(path, 'requires saved canonical source audio');
421
+ validateManagedArtifact(separation.vocals, `${path}.vocals`);
422
+ validateManagedArtifact(separation.background, `${path}.background`);
423
+ if (!isJsonObject(separation.vocals) || separation.vocals.mediaType !== 'audio/wav'
424
+ || !isJsonObject(separation.background) || separation.background.mediaType !== 'audio/wav') historyError(path, 'does not retain its separation stems');
425
+ const vocalsPath = requiredString(separation.vocals.relativePath, `${path}.vocals.relativePath`);
426
+ const backgroundPath = requiredString(separation.background.relativePath, `${path}.background.relativePath`);
427
+ if (vocalsPath === backgroundPath) historyError(path, 'has identical vocal and background stems');
428
+ const parts = separation.instrumentParts === undefined ? [] : separation.instrumentParts;
429
+ if (!Array.isArray(parts) || parts.length > 3) historyError(path, 'has invalid instrument parts');
430
+ const expected = new Map<string, string>([[vocalsPath, 'audio/wav'], [backgroundPath, 'audio/wav']]);
431
+ const kinds = new Set<string>();
432
+ for (const part of parts) {
433
+ if (!isJsonObject(part) || !['DRUMS', 'BASS', 'OTHER'].includes(String(part.kind)) || kinds.has(String(part.kind))) {
434
+ historyError(path, 'has an invalid instrument part');
435
+ }
436
+ kinds.add(String(part.kind));
437
+ validateManagedArtifact(part.artifact, `${path}.instrumentParts.artifact`);
438
+ if (!isJsonObject(part.artifact) || part.artifact.mediaType !== 'audio/wav') historyError(path, 'does not retain its instrument stem');
439
+ const partPath = requiredString(part.artifact.relativePath, `${path}.instrumentParts.artifact.relativePath`);
440
+ if (expected.has(partPath)) historyError(path, 'duplicates a separation stem');
441
+ expected.set(partPath, 'audio/wav');
442
+ }
443
+ if (value.artifacts.length !== expected.size) historyError(path, 'does not retain its complete separation');
444
+ for (const artifact of value.artifacts) {
445
+ if (!isJsonObject(artifact) || typeof artifact.relativePath !== 'string' || expected.get(artifact.relativePath) !== artifact.mediaType) {
446
+ historyError(path, 'has mismatched separation artifacts');
447
+ }
448
+ expected.delete(artifact.relativePath);
449
+ }
450
+ }
451
+ if (value.musicGeneration !== undefined) {
452
+ const music = value.musicGeneration;
453
+ if (!isJsonObject(music) || !isJsonObject(music.audioInfo) || !Array.isArray(value.artifacts)) historyError(path, 'requires complete music metadata');
454
+ const audio = music.audioInfo;
455
+ if (!['unknown', 'model-end', 'budget-limit'].includes(String(music.termination))) historyError(path, 'has an invalid music termination');
456
+ for (const key of ['sampleRateHz', 'channels', 'frameCount', 'durationMs']) {
457
+ if (typeof audio[key] !== 'number' || !Number.isSafeInteger(audio[key]) || Number(audio[key]) < 0) historyError(path, 'has invalid canonical audio facts');
458
+ }
459
+ if (Number(audio.sampleRateHz) < 8000 || Number(audio.sampleRateHz) > 96000 || ![1, 2].includes(Number(audio.channels))
460
+ || Number(audio.frameCount) < 1 || Number(audio.frameCount) > Number(audio.sampleRateHz) * 600
461
+ || audio.durationMs !== Math.floor(Number(audio.frameCount) * 1000 / Number(audio.sampleRateHz))) historyError(path, 'has inconsistent canonical audio facts');
462
+ if (music.actualSeed !== undefined && (typeof music.actualSeed !== 'number' || !Number.isSafeInteger(music.actualSeed) || music.actualSeed < 0 || music.actualSeed > 4294967295)) historyError(path, 'has an invalid music seed');
463
+ if (!value.artifacts.some((artifact) => isJsonObject(artifact) && artifact.relativePath === music.mixRelativePath && artifact.mediaType === 'audio/wav')) historyError(path, 'does not retain its mix');
464
+ if (music.generatedScore !== undefined) {
465
+ const score = music.generatedScore;
466
+ if (!isJsonObject(score) || score.format !== 'abc' || score.origin !== 'generated-plan' || typeof score.truncated !== 'boolean'
467
+ || !value.artifacts.some((artifact) => isJsonObject(artifact) && artifact.relativePath === score.relativePath && artifact.mediaType === 'text/vnd.abc')) historyError(path, 'does not retain its generated score');
468
+ }
469
+ }
131
470
  return;
132
471
  }
133
472
  if (kind === 'transcript') {
@@ -136,9 +475,21 @@ function validateHistoryResult(value: unknown, path: string): void {
136
475
  requiredString(value.jobId, `${path}.jobId`);
137
476
  requiredString(value.jobState, `${path}.jobState`);
138
477
  nonNegativeNumber(value.artifactCount, `${path}.artifactCount`);
478
+ if (value.transcription !== undefined) {
479
+ try {
480
+ const transcript = validateNimiLocalAppSpeechTranscript(value.transcription);
481
+ if (transcript.text !== value.body) historyError(`${path}.transcription`, 'does not match the displayed text');
482
+ } catch {
483
+ historyError(`${path}.transcription`, 'does not retain a valid typed transcript');
484
+ }
485
+ }
139
486
  return;
140
487
  }
141
488
  if (kind === 'voice-asset') {
489
+ if (value.preview !== undefined) validateManagedArtifact(value.preview, `${path}.preview`);
490
+ optionalString(value.expiresAt, `${path}.expiresAt`);
491
+ optionalNonNegativeNumber(value.inputTokens, `${path}.inputTokens`);
492
+ optionalNonNegativeNumber(value.outputTokens, `${path}.outputTokens`);
142
493
  requiredString(value.jobId, `${path}.jobId`);
143
494
  requiredString(value.jobState, `${path}.jobState`);
144
495
  requiredString(value.voiceAssetId, `${path}.voiceAssetId`);
@@ -160,7 +511,7 @@ function validateHistoryResult(value: unknown, path: string): void {
160
511
  historyError(`${path}.kind`, `has unsupported value ${kind}`);
161
512
  }
162
513
 
163
- function validateRunConfig(value: unknown, path: string): void {
514
+ export function validateRunConfig(value: unknown, path: string): void {
164
515
  if (!isJsonObject(value) || !isJsonObject(value.target) || !isJsonObject(value.promptControls)) {
165
516
  historyError(path, 'requires target and promptControls objects');
166
517
  }
@@ -191,11 +542,22 @@ function parseHistoryRecord(value: unknown, path: string, capabilityId: string):
191
542
  requiredString(value.message, `${path}.message`);
192
543
  const createdAt = requiredString(value.createdAt, `${path}.createdAt`);
193
544
  if (Number.isNaN(new Date(createdAt).valueOf())) historyError(`${path}.createdAt`, 'requires a valid timestamp');
194
- if (value.result !== undefined) validateHistoryResult(value.result, `${path}.result`);
545
+ if (value.result !== undefined) validateStudioHistoryResult(value.result, `${path}.result`);
195
546
  if (value.runConfig !== undefined) validateRunConfig(value.runConfig, `${path}.runConfig`);
547
+ if (value.inputTruncated !== undefined) {
548
+ if (value.inputTruncated !== true) historyError(`${path}.inputTruncated`, 'requires true when present');
549
+ const context = isJsonObject(value.runConfig) && isJsonObject(value.runConfig.promptControls) ? value.runConfig.promptControls.context : undefined;
550
+ for (const [field, text] of [['prompt', value.prompt], ['runConfig.promptControls.context', context]] as const) {
551
+ if (typeof text === 'string' && utf8ByteLength(text) > STORED_INPUT_PREVIEW_MAX_BYTES) historyError(`${path}.${field}`, 'exceeds the truncated input limit');
552
+ }
553
+ }
196
554
  return value as unknown as StudioRunHistoryRecord;
197
555
  }
198
556
 
557
+ function utf8ByteLength(text: string): number {
558
+ return new TextEncoder().encode(text).byteLength;
559
+ }
560
+
199
561
  export function parseStudioRunHistory(value: unknown): StudioRunHistory {
200
562
  if (value === undefined) return {};
201
563
  if (!isJsonObject(value)) throw new Error('AI Studio history payload must be an object.');
@@ -226,33 +588,11 @@ export function studioHistoryFromRecords(records: readonly StudioRunHistoryRecor
226
588
  return history;
227
589
  }
228
590
 
229
- export function boundStudioRunHistoryWithRecord(history: StudioRunHistory, record: StudioRunHistoryRecord): StudioRunHistory {
230
- // History has a smaller JSON budget than a complete Runtime Locate result.
231
- // Preserve the summary/Job reference without mutating the current full result.
232
- let storedRecord = record;
233
- if (record.result?.ok && record.result.kind === 'vision-locate' && record.result.result
234
- && new TextEncoder().encode(JSON.stringify(studioHistoryFromRecords([record]))).byteLength > STUDIO_HISTORY_LIMIT_BYTES) {
235
- const { result: _locations, ...reference } = record.result;
236
- storedRecord = { ...record, result: reference };
237
- }
238
- const counts = new Map<string, number>();
239
- const retained = [storedRecord, ...flattenStudioHistoryRecords(history).filter((existing) => existing.id !== record.id)]
240
- .sort((left, right) => right.createdAt.localeCompare(left.createdAt))
241
- .filter((candidate) => {
242
- const count = counts.get(candidate.capabilityId) ?? 0;
243
- if (count >= STUDIO_HISTORY_LIMIT_PER_CAPABILITY) return false;
244
- counts.set(candidate.capabilityId, count + 1);
245
- return true;
246
- })
247
- .slice(0, STUDIO_HISTORY_LIMIT_TOTAL_RECORDS);
248
- let next = studioHistoryFromRecords(retained);
249
- while (new TextEncoder().encode(JSON.stringify(next)).byteLength > STUDIO_HISTORY_LIMIT_BYTES) {
250
- if (retained.length <= 1) throw new Error('AI Studio history record exceeds the storage document limit.');
251
- retained.pop();
252
- next = studioHistoryFromRecords(retained);
253
- }
254
- if (!retained.some((candidate) => candidate.id === record.id)) throw new Error('AI Studio history could not retain the newly completed run.');
255
- return next;
591
+ // Saving a run never removes or shrinks another run. Storage splits complete
592
+ // records across documents; only an explicit user action removes history.
593
+ export function appendStudioRunHistoryRecord(history: StudioRunHistory, record: StudioRunHistoryRecord): StudioRunHistory {
594
+ return studioHistoryFromRecords([record, ...flattenStudioHistoryRecords(history).filter((existing) => existing.id !== record.id)]
595
+ .sort((left, right) => right.createdAt.localeCompare(left.createdAt)));
256
596
  }
257
597
 
258
598
  export function removeStudioRunHistoryRecord(history: StudioRunHistory, recordId: string): StudioRunHistory {
@@ -294,10 +634,18 @@ export type StudioHistoryMutationSubject = {
294
634
  };
295
635
 
296
636
  export function studioHistoryArtifactPaths(record: StudioRunHistoryRecord): string[] {
637
+ const params = record.runConfig?.target.params;
638
+ const source = record.capabilityId === 'world.generate' && params ? studioWorldInputSource(params) : undefined;
639
+ return [...new Set([...studioResultAssetPaths(record.result), ...(source ? [source.relativePath] : [])])];
640
+ }
641
+
642
+ export function studioHistoryDocumentPaths(record: StudioRunHistoryRecord): string[] {
297
643
  const result = record.result;
298
- if (!result || result.ok === false || result.kind !== 'artifacts') return [];
299
- const artifacts = result.artifacts?.length ? result.artifacts : result.firstArtifact ? [result.firstArtifact] : [];
300
- return artifacts.map((artifact) => artifact.relativePath).filter(Boolean);
644
+ if (!result || result.ok === false) return [];
645
+ if (result.kind === 'voice-asset') return result.preview ? [result.preview.relativePath] : [];
646
+ if (result.kind === 'vision-locate') return result.sourceImage ? [result.sourceImage.relativePath] : [];
647
+ if (result.kind !== 'text-annotation') return [];
648
+ return result.document.relativePath ? [result.document.relativePath] : [];
301
649
  }
302
650
 
303
651
  export async function cleanupStudioHistoryArtifacts(input: {
@@ -369,12 +717,14 @@ export async function removeStudioHistoryWithPolicy<TProjection>(input: {
369
717
  readonly history: StudioRunHistory;
370
718
  readonly recordId: string;
371
719
  } & StudioHistoryMutationPolicyPort<TProjection>): Promise<StudioHistoryPolicyMutationOutcome<TProjection>> {
372
- const removed = mutationSubjects(input, input.history).filter((subject) => subject.id === input.recordId);
720
+ const subjects = mutationSubjects(input, input.history);
721
+ const removed = subjects.filter((subject) => subject.id === input.recordId);
722
+ const retainedPaths = new Set(subjects.filter(subject => subject.id !== input.recordId).flatMap(subject => subject.artifactPaths));
373
723
  const currentProjection = await input.project(input.history);
374
724
  if (removed.length === 0) return { completed: 0, skipped: 1, failed: 0, projection: currentProjection, issues: [] };
375
725
  if (input.deleteAssets) {
376
726
  const cleanup = await cleanupStudioHistoryArtifacts({
377
- relativePaths: removed.flatMap((subject) => subject.artifactPaths),
727
+ relativePaths: removed.flatMap((subject) => subject.artifactPaths).filter(path => !retainedPaths.has(path)),
378
728
  removeArtifact: input.removeArtifact,
379
729
  isNotFound: input.isNotFound,
380
730
  });
@@ -409,7 +759,8 @@ export async function clearStudioHistoryWithPolicy<TProjection>(input: {
409
759
  readonly history: StudioRunHistory;
410
760
  readonly capabilityId: string | null;
411
761
  } & StudioHistoryMutationPolicyPort<TProjection>): Promise<StudioHistoryPolicyMutationOutcome<TProjection>> {
412
- const removed = mutationSubjects(input, input.history).filter((subject) => (
762
+ const subjects = mutationSubjects(input, input.history);
763
+ const removed = subjects.filter((subject) => (
413
764
  input.capabilityId === null || subject.capabilityId === input.capabilityId
414
765
  ));
415
766
  if (!input.deleteAssets) {
@@ -434,9 +785,11 @@ export async function clearStudioHistoryWithPolicy<TProjection>(input: {
434
785
  let skipped = 0;
435
786
  let failed = 0;
436
787
  const issues: StudioHistoryPolicyMutationIssue[] = [];
788
+ const committedIds = new Set<string>();
437
789
  for (const subject of removed) {
790
+ const retainedPaths = new Set(subjects.filter(other => other.id !== subject.id && !committedIds.has(other.id)).flatMap(other => other.artifactPaths));
438
791
  const cleanup = await cleanupStudioHistoryArtifacts({
439
- relativePaths: subject.artifactPaths,
792
+ relativePaths: subject.artifactPaths.filter(path => !retainedPaths.has(path)),
440
793
  removeArtifact: input.removeArtifact,
441
794
  isNotFound: input.isNotFound,
442
795
  });
@@ -449,6 +802,7 @@ export async function clearStudioHistoryWithPolicy<TProjection>(input: {
449
802
  try {
450
803
  await input.commit(next, [subject]);
451
804
  history = next;
805
+ committedIds.add(subject.id);
452
806
  completed += 1;
453
807
  } catch (error) {
454
808
  failed += 1;