@nimiplatform/app-tools 0.1.3 → 0.2.1

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 (121) hide show
  1. package/LICENSE +198 -6
  2. package/README.md +83 -27
  3. package/bin/nimi-app.mjs +328 -45
  4. package/lib/app-access-declaration.mjs +49 -0
  5. package/lib/app-doctor-update.mjs +411 -149
  6. package/lib/app-pack.mjs +402 -0
  7. package/lib/app-project-lifecycle.mjs +1141 -0
  8. package/lib/app-scaffold-capabilities.mjs +769 -0
  9. package/lib/app-scaffold-default-source.mjs +21 -0
  10. package/lib/app-scaffold-profiles.mjs +1093 -0
  11. package/lib/app-scaffold.mjs +1266 -813
  12. package/lib/index.mjs +195 -42
  13. package/lib/simulator-conformance-ast.mjs +498 -0
  14. package/lib/simulator-conformance-css.mjs +116 -0
  15. package/lib/simulator-conformance-graph.mjs +757 -0
  16. package/lib/simulator-conformance.d.mts +14 -0
  17. package/lib/simulator-conformance.mjs +203 -0
  18. package/lib/simulator-css-profile.d.mts +27 -0
  19. package/lib/simulator-css-profile.mjs +531 -0
  20. package/lib/simulator-kit-export-resolution.mjs +70 -0
  21. package/lib/simulator-manifest.mjs +334 -0
  22. package/lib/windows-powershell.mjs +7 -0
  23. package/package.json +66 -3
  24. package/scripts/dev-shell.mjs +465 -0
  25. package/scripts/sync-app-source.mjs +300 -0
  26. package/scripts/sync-scaffold-versions.mjs +91 -0
  27. package/templates/app-source/LICENSE +21 -0
  28. package/templates/app-source/src/ai-studio-core/ai-config.ts +100 -0
  29. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +338 -0
  30. package/templates/app-source/src/ai-studio-core/contexts.tsx +61 -0
  31. package/templates/app-source/src/ai-studio-core/history-policy.ts +447 -0
  32. package/templates/app-source/src/ai-studio-core/history.ts +824 -0
  33. package/templates/app-source/src/ai-studio-core/host-context.tsx +79 -0
  34. package/templates/app-source/src/ai-studio-core/index.ts +214 -0
  35. package/templates/app-source/src/ai-studio-core/messages/en.json +310 -0
  36. package/templates/app-source/src/ai-studio-core/messages/index.ts +47 -0
  37. package/templates/app-source/src/ai-studio-core/messages/zh.json +310 -0
  38. package/templates/app-source/src/ai-studio-core/module-registration.ts +109 -0
  39. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +65 -0
  40. package/templates/app-source/src/ai-studio-core/parameter-fields.tsx +247 -0
  41. package/templates/app-source/src/ai-studio-core/parameters.ts +110 -0
  42. package/templates/app-source/src/ai-studio-core/prompt-drafts.ts +69 -0
  43. package/templates/app-source/src/ai-studio-core/run-target.ts +123 -0
  44. package/templates/app-source/src/ai-studio-core/runtime-dispatcher.ts +35 -0
  45. package/templates/app-source/src/ai-studio-core/runtime-types.ts +86 -0
  46. package/templates/app-source/src/ai-studio-core/runtime.ts +306 -0
  47. package/templates/app-source/src/ai-studio-core/section-ai-testing-admission.ts +38 -0
  48. package/templates/app-source/src/ai-studio-core/section-ai-testing-ai-config.tsx +30 -0
  49. package/templates/app-source/src/ai-studio-core/section-ai-testing-artifact-preview.ts +40 -0
  50. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +257 -0
  51. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +676 -0
  52. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +19 -0
  53. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +291 -0
  54. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +413 -0
  55. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +174 -0
  56. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +449 -0
  57. package/templates/app-source/src/ai-studio-core/section-ai-testing-surface.tsx +45 -0
  58. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +494 -0
  59. package/templates/app-source/src/ai-studio-core/studio-directives.ts +33 -0
  60. package/templates/app-source/src/ai-studio-core/workspace.tsx +381 -0
  61. package/templates/app-source/src/product-modules/agent-center/index.tsx +27 -0
  62. package/templates/app-source/src/product-modules/agent-conversation/index.tsx +19 -0
  63. package/templates/app-source/src/product-modules/agent-realtime/index.tsx +29 -0
  64. package/templates/app-source/src/product-modules/kit-recipes/gallery.tsx +142 -0
  65. package/templates/app-source/src/product-modules/kit-recipes/index.tsx +19 -0
  66. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-data-recipes.tsx +336 -0
  67. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-demos.tsx +165 -0
  68. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-recipes.tsx +682 -0
  69. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-surface.tsx +341 -0
  70. package/templates/app-source/src/studio-modules/studio-create/descriptors.ts +26 -0
  71. package/templates/app-source/src/studio-modules/studio-create/index.ts +14 -0
  72. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +67 -0
  73. package/templates/app-source/src/studio-modules/studio-create/messages/index.ts +5 -0
  74. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +67 -0
  75. package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +153 -0
  76. package/templates/app-source/src/studio-modules/studio-create/parameters.ts +70 -0
  77. package/templates/app-source/src/studio-modules/studio-create/registration.ts +46 -0
  78. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +339 -0
  79. package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +22 -0
  80. package/templates/app-source/src/studio-modules/studio-media/index.ts +12 -0
  81. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +82 -0
  82. package/templates/app-source/src/studio-modules/studio-media/messages/index.ts +5 -0
  83. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +82 -0
  84. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +283 -0
  85. package/templates/app-source/src/studio-modules/studio-media/parameters.ts +94 -0
  86. package/templates/app-source/src/studio-modules/studio-media/registration.ts +44 -0
  87. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +113 -0
  88. package/templates/app-source/src/studio-modules/studio-voice/descriptors.ts +28 -0
  89. package/templates/app-source/src/studio-modules/studio-voice/index.ts +16 -0
  90. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +99 -0
  91. package/templates/app-source/src/studio-modules/studio-voice/messages/index.ts +5 -0
  92. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +99 -0
  93. package/templates/app-source/src/studio-modules/studio-voice/parameter-panel.tsx +284 -0
  94. package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +116 -0
  95. package/templates/app-source/src/studio-modules/studio-voice/registration.ts +59 -0
  96. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +347 -0
  97. package/templates/app-source/src/workbench-core/empty-state.tsx +31 -0
  98. package/templates/app-source/src/workbench-core/index.ts +17 -0
  99. package/templates/app-source/src/workbench-core/runtime-gate.tsx +131 -0
  100. package/templates/app-source/src/workbench-core/workbench-core.css +255 -0
  101. package/templates/app-source/src/workbench-core/workbench-core.tsx +140 -0
  102. package/templates/app-source.manifest.json +333 -0
  103. package/templates/default-starter/AGENTS.md +33 -0
  104. package/templates/default-starter/LICENSE +21 -0
  105. package/templates/default-starter/README.md +41 -0
  106. package/templates/default-starter/SECURITY.md +5 -0
  107. package/templates/default-starter/index.html +12 -0
  108. package/templates/default-starter/scripts/validate.mjs +26 -0
  109. package/templates/default-starter/src/shell/App.tsx +27 -0
  110. package/templates/default-starter/src/shell/auth/app-identity.ts +3 -0
  111. package/templates/default-starter/src/shell/auth/local-app-client.ts +18 -0
  112. package/templates/default-starter/src/shell/auth/runtime-platform.ts +110 -0
  113. package/templates/default-starter/src/shell/authenticated-shell.tsx +20 -0
  114. package/templates/default-starter/src/shell/workbench-target-adapter.ts +40 -0
  115. package/templates/default-starter/src/styles.css +26 -0
  116. package/templates/default-starter/src-tauri/Cargo.toml +17 -0
  117. package/templates/default-starter/src-tauri/build.rs +5 -0
  118. package/templates/default-starter/src-tauri/capabilities/default.json +7 -0
  119. package/templates/default-starter/src-tauri/tauri.conf.json +26 -0
  120. package/templates/default-starter/tsconfig.json +18 -0
  121. package/templates/default-starter.manifest.json +99 -0
@@ -0,0 +1,824 @@
1
+ import { isJsonObject } from '@nimiplatform/sdk/types';
2
+ import type {
3
+ StudioCapabilityRunResult,
4
+ StudioManagedArtifact,
5
+ StudioNonSuccessDiagnostics,
6
+ StudioNonSuccessReason,
7
+ } from './runtime-types.js';
8
+ import type { StudioRunTargetSource } from './parameters.js';
9
+ import type { StudioMediaHistoryRecord } from './contexts.js';
10
+
11
+ export type StudioRunTargetSnapshot = {
12
+ readonly capabilityId: string;
13
+ readonly capabilityContract: string | null;
14
+ readonly section: string;
15
+ readonly status: StudioRunTargetStatus;
16
+ readonly source: StudioRunTargetSource;
17
+ readonly intentLabel: string;
18
+ readonly detail: string;
19
+ readonly params: Readonly<Record<string, unknown>>;
20
+ readonly paramsSummary: readonly string[];
21
+ readonly profileOrigin: null;
22
+ };
23
+
24
+ export type StudioRunTargetSummary = StudioRunTargetSnapshot & {
25
+ readonly canDispatch: boolean;
26
+ };
27
+
28
+ export type StudioRunTargetStatus =
29
+ | 'checking'
30
+ | 'configured'
31
+ | 'blocked'
32
+ | 'tauri-only'
33
+ | 'sdk-gap'
34
+ | 'not-admitted';
35
+
36
+ export type StudioCapabilityLabelResolver = (capabilityId: string) => string | null | undefined;
37
+
38
+ export type StudioRunConfigSnapshot = {
39
+ target: StudioRunTargetSnapshot;
40
+ promptControls: {
41
+ tone?: string;
42
+ toneSelected?: boolean;
43
+ length?: string;
44
+ lengthSelected?: boolean;
45
+ contextAttached: boolean;
46
+ context?: string;
47
+ attachmentCount: number;
48
+ };
49
+ traceId?: string;
50
+ };
51
+
52
+ export type StudioRunHistoryResultSnapshot =
53
+ | {
54
+ ok: true;
55
+ kind: 'text';
56
+ summary: string;
57
+ body: string;
58
+ charCount: number;
59
+ finishReason: string;
60
+ streamed: boolean;
61
+ inputTokens?: number;
62
+ outputTokens?: number;
63
+ totalTokens?: number;
64
+ traceId?: string;
65
+ }
66
+ | {
67
+ ok: true;
68
+ kind: 'embedding';
69
+ summary: string;
70
+ vectorCount: number;
71
+ dimensions: number;
72
+ sample: number[];
73
+ totalTokens?: number;
74
+ traceId?: string;
75
+ }
76
+ | {
77
+ ok: true;
78
+ kind: 'artifacts';
79
+ summary: string;
80
+ jobId: string;
81
+ jobState: string;
82
+ artifactCount: number;
83
+ artifacts?: StudioManagedArtifact[];
84
+ firstArtifact?: StudioManagedArtifact;
85
+ traceId?: string;
86
+ }
87
+ | {
88
+ ok: true;
89
+ kind: 'transcript';
90
+ summary: string;
91
+ body: string;
92
+ charCount: number;
93
+ jobId: string;
94
+ jobState: string;
95
+ artifactCount: number;
96
+ traceId?: string;
97
+ }
98
+ | {
99
+ ok: true;
100
+ kind: 'voice-asset';
101
+ summary: string;
102
+ jobId: string;
103
+ jobState: string;
104
+ voiceAssetId: string;
105
+ creationSource: 'reference-audio' | 'text-description';
106
+ assetStatus: string;
107
+ traceId?: string;
108
+ }
109
+ | {
110
+ ok: true;
111
+ kind: 'voice-catalog';
112
+ summary: string;
113
+ voiceCount: number;
114
+ sample: Array<{ voiceId: string; creationSource: string; status: string }>;
115
+ traceId?: string;
116
+ }
117
+ | {
118
+ ok: false;
119
+ kind: 'non-success';
120
+ summary: string;
121
+ reason: StudioNonSuccessReason;
122
+ message: string;
123
+ actionHint: string;
124
+ missingSurface?: string;
125
+ diagnostics?: StudioNonSuccessDiagnostics;
126
+ };
127
+
128
+ export type StudioRunHistoryRecord = {
129
+ id: string;
130
+ capabilityId: string;
131
+ prompt: string;
132
+ status: string;
133
+ message: string;
134
+ createdAt: string;
135
+ result?: StudioRunHistoryResultSnapshot;
136
+ runConfig?: StudioRunConfigSnapshot;
137
+ };
138
+
139
+ export type StudioRunHistory = Record<string, StudioRunHistoryRecord[]>;
140
+
141
+ async function verifyStudioManagedArtifact(
142
+ statArtifact: (
143
+ artifact: StudioManagedArtifact,
144
+ record: StudioRunHistoryRecord,
145
+ ) => Promise<{ readonly sha256: string; readonly sizeBytes: number }>,
146
+ artifact: StudioManagedArtifact,
147
+ record: StudioRunHistoryRecord,
148
+ ): Promise<{ readonly status: 'ready' | 'unavailable'; readonly message: string }> {
149
+ try {
150
+ const stored = await statArtifact(artifact, record);
151
+ if (stored.sha256 !== artifact.sha256 || stored.sizeBytes !== artifact.sizeBytes) {
152
+ return {
153
+ status: 'unavailable',
154
+ message: `Managed artifact verification failed: ${artifact.relativePath}`,
155
+ };
156
+ }
157
+ return { status: 'ready', message: record.message };
158
+ } catch {
159
+ return {
160
+ status: 'unavailable',
161
+ message: `Managed artifact is unavailable: ${artifact.relativePath}`,
162
+ };
163
+ }
164
+ }
165
+
166
+ export async function projectStudioManagedHistory(input: {
167
+ readonly runHistory: StudioRunHistory;
168
+ readonly existingMediaHistory?: readonly StudioMediaHistoryRecord[];
169
+ readonly retainUnprojectedMedia?: boolean;
170
+ readonly resolveCapabilityLabel?: StudioCapabilityLabelResolver;
171
+ readonly statArtifact: (
172
+ artifact: StudioManagedArtifact,
173
+ record: StudioRunHistoryRecord,
174
+ ) => Promise<{ readonly sha256: string; readonly sizeBytes: number }>;
175
+ }): Promise<{
176
+ readonly runHistory: StudioRunHistory;
177
+ readonly mediaHistory: readonly StudioMediaHistoryRecord[];
178
+ }> {
179
+ const existingMediaHistory = input.existingMediaHistory ?? [];
180
+ const storedByID = new Map(existingMediaHistory.map((record) => [record.id, record]));
181
+ const projectedIDs = new Set<string>();
182
+ const mediaHistory: StudioMediaHistoryRecord[] = [];
183
+ const projectedRunHistory: StudioRunHistory = {};
184
+
185
+ for (const [capabilityId, records] of Object.entries(input.runHistory)) {
186
+ const projectedRecords: StudioRunHistoryRecord[] = [];
187
+ for (const record of records) {
188
+ const result = record.result;
189
+ let projectedRecord = record;
190
+ let unavailableReason = '';
191
+ if (result?.ok === true && result.kind === 'artifacts') {
192
+ const artifacts = result.artifacts?.length
193
+ ? result.artifacts
194
+ : result.firstArtifact ? [result.firstArtifact] : [];
195
+ for (const [index, artifact] of artifacts.entries()) {
196
+ const id = index === 0 ? record.id : `${record.id}:${index}`;
197
+ const verification = await verifyStudioManagedArtifact(input.statArtifact, artifact, record);
198
+ const { status, message } = verification;
199
+ if (status === 'unavailable' && !unavailableReason) unavailableReason = message;
200
+ const capabilityLabel = input.resolveCapabilityLabel?.(record.capabilityId) || undefined;
201
+ mediaHistory.push({
202
+ ...storedByID.get(id),
203
+ id,
204
+ runId: record.id,
205
+ kind: 'runtime-media',
206
+ capabilityId: record.capabilityId,
207
+ ...(capabilityLabel ? { capabilityLabel } : {}),
208
+ title: artifact.displayName || artifact.relativePath || result.jobId || record.capabilityId,
209
+ status,
210
+ createdAt: record.createdAt,
211
+ artifactCount: result.artifactCount,
212
+ artifactLabel: artifact.displayName || artifact.relativePath,
213
+ relativePath: artifact.relativePath,
214
+ ...(artifact.mediaType ? { mediaType: artifact.mediaType } : {}),
215
+ sizeBytes: artifact.sizeBytes,
216
+ sha256: artifact.sha256,
217
+ jobId: result.jobId,
218
+ jobState: result.jobState,
219
+ message,
220
+ traceState: result.traceId ? 'captured' : 'not-captured',
221
+ ...(result.traceId ? { traceId: result.traceId } : {}),
222
+ });
223
+ projectedIDs.add(id);
224
+ }
225
+ }
226
+ if (unavailableReason && record.status === 'ready') {
227
+ projectedRecord = { ...record, status: 'unavailable', message: unavailableReason };
228
+ }
229
+ projectedRecords.push(projectedRecord);
230
+ }
231
+ projectedRunHistory[capabilityId] = projectedRecords;
232
+ }
233
+
234
+ if (input.retainUnprojectedMedia) {
235
+ for (const stored of existingMediaHistory) {
236
+ if (projectedIDs.has(stored.id)) continue;
237
+ if (stored.kind !== 'runtime-media') {
238
+ mediaHistory.push(stored);
239
+ continue;
240
+ }
241
+ if (!stored.relativePath || stored.sizeBytes === undefined || !stored.sha256) {
242
+ mediaHistory.push({
243
+ ...stored,
244
+ status: 'unavailable',
245
+ message: `Managed artifact metadata is unavailable: ${stored.relativePath || stored.id}`,
246
+ });
247
+ continue;
248
+ }
249
+ const artifact: StudioManagedArtifact = {
250
+ relativePath: stored.relativePath,
251
+ ...(stored.mediaType ? { mediaType: stored.mediaType } : {}),
252
+ sizeBytes: stored.sizeBytes,
253
+ sha256: stored.sha256,
254
+ ...(stored.artifactLabel ? { displayName: stored.artifactLabel } : {}),
255
+ previewSource: 'managed-asset',
256
+ };
257
+ const verification = await verifyStudioManagedArtifact(input.statArtifact, artifact, {
258
+ id: stored.runId || stored.id,
259
+ capabilityId: stored.capabilityId,
260
+ prompt: '',
261
+ status: stored.status,
262
+ message: stored.message || '',
263
+ createdAt: stored.createdAt,
264
+ });
265
+ mediaHistory.push({ ...stored, status: verification.status, message: verification.message });
266
+ }
267
+ }
268
+ return { runHistory: projectedRunHistory, mediaHistory };
269
+ }
270
+
271
+ export type StudioFlatRunRecord = StudioRunHistoryRecord & {
272
+ capabilityLabel: string;
273
+ };
274
+
275
+ export type StudioRunStatusTone = 'success' | 'warning' | 'danger' | 'info';
276
+ export type StudioRunIntentSource = 'local' | 'cloud' | 'unknown';
277
+ type StudioNonSuccessRunResult = Extract<StudioCapabilityRunResult, { ok: false }>;
278
+ type StudioNonSuccessHistorySnapshot = Extract<StudioRunHistoryResultSnapshot, { ok: false }>;
279
+ export type StudioRunPromptControlFact = {
280
+ label: string;
281
+ value: string;
282
+ code?: boolean;
283
+ };
284
+ export type StudioRunConfigParamRow = {
285
+ group: string;
286
+ key: string;
287
+ label: string;
288
+ value: string;
289
+ code: boolean;
290
+ };
291
+
292
+ export function studioCapabilityResultTraceId(
293
+ result: StudioCapabilityRunResult,
294
+ ): string | undefined {
295
+ return isStudioNonSuccessRunResult(result) ? result.diagnostics?.traceId : result.trace?.traceId;
296
+ }
297
+
298
+ export function studioCapabilityResultHasTrace(
299
+ result: StudioCapabilityRunResult,
300
+ ): boolean {
301
+ return Boolean(studioCapabilityResultTraceId(result));
302
+ }
303
+
304
+ export function studioRunHistoryStatus(result: StudioCapabilityRunResult): string {
305
+ if (!isStudioNonSuccessRunResult(result)) return 'ready';
306
+ if (result.reason === 'runtime-canceled' || result.reason === 'operation-aborted') return 'canceled';
307
+ if (result.reason === 'runtime-timeout') return 'timed-out';
308
+ return result.reason === 'runtime-call-failed' ? 'failed' : 'unavailable';
309
+ }
310
+
311
+ export function createStudioRunHistoryRecord(input: {
312
+ readonly result: StudioCapabilityRunResult;
313
+ readonly prompt: string;
314
+ readonly runId: string;
315
+ readonly createdAt: string;
316
+ readonly runConfig?: StudioRunConfigSnapshot;
317
+ readonly status?: string;
318
+ }): StudioRunHistoryRecord {
319
+ const traceId = studioCapabilityResultTraceId(input.result);
320
+ return {
321
+ id: input.runId,
322
+ capabilityId: input.result.capabilityId,
323
+ prompt: input.prompt,
324
+ status: input.status ?? studioRunHistoryStatus(input.result),
325
+ message: input.result.message,
326
+ createdAt: input.createdAt,
327
+ result: createStudioRunHistoryResultSnapshot(input.result),
328
+ runConfig: input.runConfig ? { ...input.runConfig, traceId } : undefined,
329
+ };
330
+ }
331
+
332
+ export function flattenStudioRunHistory(
333
+ history: StudioRunHistory | null,
334
+ resolveCapabilityLabel: StudioCapabilityLabelResolver,
335
+ ): StudioFlatRunRecord[] {
336
+ if (!history) return [];
337
+ const records: StudioFlatRunRecord[] = [];
338
+ for (const [capabilityId, list] of Object.entries(history)) {
339
+ let capabilityLabel = capabilityId;
340
+ try {
341
+ capabilityLabel = resolveCapabilityLabel(capabilityId) || capabilityId;
342
+ } catch {
343
+ capabilityLabel = capabilityId;
344
+ }
345
+ for (const record of list) {
346
+ records.push({ ...record, capabilityLabel });
347
+ }
348
+ }
349
+ records.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
350
+ return records;
351
+ }
352
+
353
+ export function getStudioRunStatusLabel(status: StudioRunHistoryRecord['status']): string {
354
+ if (status === 'ready') return 'runtime ready';
355
+ if (status === 'unavailable') return 'sdk unavailable';
356
+ if (status === 'failed') return 'failed';
357
+ if (status === 'canceled') return 'canceled';
358
+ if (status === 'timed-out') return 'timed out';
359
+ return status.replaceAll('-', ' ');
360
+ }
361
+
362
+ export function getStudioRunStatusTone(status: StudioRunHistoryRecord['status']): StudioRunStatusTone {
363
+ if (status === 'ready') return 'success';
364
+ if (status === 'failed') return 'danger';
365
+ if (status === 'canceled') return 'warning';
366
+ if (status === 'timed-out') return 'warning';
367
+ return 'info';
368
+ }
369
+
370
+ const studioRunTimeFormatter = new Intl.DateTimeFormat('en-US', {
371
+ hour: '2-digit',
372
+ minute: '2-digit',
373
+ hourCycle: 'h23',
374
+ });
375
+
376
+ const studioRunDateTimeFormatter = new Intl.DateTimeFormat('en-US', {
377
+ month: 'short',
378
+ day: 'numeric',
379
+ hour: '2-digit',
380
+ minute: '2-digit',
381
+ hourCycle: 'h23',
382
+ });
383
+
384
+ const studioRunDateTimeWithYearFormatter = new Intl.DateTimeFormat('en-US', {
385
+ year: 'numeric',
386
+ month: 'short',
387
+ day: 'numeric',
388
+ hour: '2-digit',
389
+ minute: '2-digit',
390
+ hourCycle: 'h23',
391
+ });
392
+
393
+ function isSameLocalCalendarDate(left: Date, right: Date): boolean {
394
+ return left.getFullYear() === right.getFullYear() && left.getMonth() === right.getMonth() && left.getDate() === right.getDate();
395
+ }
396
+
397
+ export function formatStudioRunTimestamp(value: string, now: Date): string {
398
+ try {
399
+ const date = new Date(value);
400
+ if (Number.isNaN(date.valueOf())) return value;
401
+ if (isSameLocalCalendarDate(date, now)) return studioRunTimeFormatter.format(date);
402
+ if (date.getFullYear() === now.getFullYear()) return studioRunDateTimeFormatter.format(date);
403
+ return studioRunDateTimeWithYearFormatter.format(date);
404
+ } catch {
405
+ return value;
406
+ }
407
+ }
408
+
409
+ export function formatStudioRunHistoryTimestamp(value: string, now: Date): string {
410
+ try {
411
+ if (!value.trim()) return 'Unknown date';
412
+ const date = new Date(value);
413
+ if (Number.isNaN(date.valueOf())) return 'Unknown date';
414
+ if (isSameLocalCalendarDate(date, now)) return studioRunTimeFormatter.format(date);
415
+ if (date.getFullYear() === now.getFullYear()) return studioRunDateTimeFormatter.format(date);
416
+ return studioRunDateTimeWithYearFormatter.format(date);
417
+ } catch {
418
+ return 'Unknown date';
419
+ }
420
+ }
421
+
422
+ function compactBodySummary(value: string): string {
423
+ const normalized = value.replace(/\s+/g, ' ').trim();
424
+ if (!normalized) return '(empty result)';
425
+ return normalized.length > 180 ? `${normalized.slice(0, 177)}...` : normalized;
426
+ }
427
+
428
+ function traceFields(result: StudioCapabilityRunResult): Pick<Extract<StudioRunHistoryResultSnapshot, { ok: true }>, 'traceId'> {
429
+ if (isStudioNonSuccessRunResult(result)) return {};
430
+ return {
431
+ traceId: result.trace?.traceId,
432
+ };
433
+ }
434
+
435
+ function isStudioNonSuccessRunResult(result: StudioCapabilityRunResult): result is StudioNonSuccessRunResult {
436
+ return result.ok === false;
437
+ }
438
+
439
+ function isStudioNonSuccessHistorySnapshot(result: StudioRunHistoryResultSnapshot): result is StudioNonSuccessHistorySnapshot {
440
+ return result.ok === false;
441
+ }
442
+
443
+ export function createStudioRunHistoryResultSnapshot(result: StudioCapabilityRunResult): StudioRunHistoryResultSnapshot {
444
+ if (isStudioNonSuccessRunResult(result)) {
445
+ return {
446
+ ok: false,
447
+ kind: 'non-success',
448
+ summary: result.message,
449
+ reason: result.reason,
450
+ message: result.message,
451
+ actionHint: result.actionHint,
452
+ missingSurface: result.missingSurface,
453
+ ...(result.diagnostics ? { diagnostics: { ...result.diagnostics } } : {}),
454
+ };
455
+ }
456
+
457
+ const trace = traceFields(result);
458
+ const output = result.output;
459
+ if (output.kind === 'text') {
460
+ return {
461
+ ok: true,
462
+ kind: 'text',
463
+ summary: compactBodySummary(output.text),
464
+ body: output.text,
465
+ charCount: output.text.length,
466
+ finishReason: output.finishReason,
467
+ streamed: output.streamed,
468
+ inputTokens: output.inputTokens,
469
+ outputTokens: output.outputTokens,
470
+ totalTokens: output.totalTokens,
471
+ ...trace,
472
+ };
473
+ }
474
+ if (output.kind === 'embedding') {
475
+ return {
476
+ ok: true,
477
+ kind: 'embedding',
478
+ summary: `${output.vectorCount} vector${output.vectorCount === 1 ? '' : 's'} / ${output.dimensions} dimensions`,
479
+ vectorCount: output.vectorCount,
480
+ dimensions: output.dimensions,
481
+ sample: output.sample,
482
+ totalTokens: output.totalTokens,
483
+ ...trace,
484
+ };
485
+ }
486
+ if (output.kind === 'artifacts') {
487
+ const artifacts = output.artifacts.map((artifact) => ({ ...artifact }));
488
+ const firstArtifact = artifacts[0];
489
+ return {
490
+ ok: true,
491
+ kind: 'artifacts',
492
+ summary: `${output.jobState || 'unknown'} / ${output.artifactCount} artifact${output.artifactCount === 1 ? '' : 's'}${firstArtifact?.mediaType ? ` / ${firstArtifact.mediaType}` : ''}`,
493
+ jobId: output.jobId,
494
+ jobState: output.jobState,
495
+ artifactCount: output.artifactCount,
496
+ artifacts,
497
+ firstArtifact,
498
+ ...trace,
499
+ };
500
+ }
501
+ if (output.kind === 'transcript') {
502
+ return {
503
+ ok: true,
504
+ kind: 'transcript',
505
+ summary: compactBodySummary(output.text),
506
+ body: output.text,
507
+ charCount: output.text.length,
508
+ jobId: output.jobId,
509
+ jobState: output.jobState,
510
+ artifactCount: output.artifactCount,
511
+ ...trace,
512
+ };
513
+ }
514
+ if (output.kind === 'voice-asset') {
515
+ return {
516
+ ok: true,
517
+ kind: 'voice-asset',
518
+ summary: `${output.creationSource} / ${output.assetStatus} / ${output.voiceAssetId}`,
519
+ jobId: output.jobId,
520
+ jobState: output.jobState,
521
+ voiceAssetId: output.voiceAssetId,
522
+ creationSource: output.creationSource,
523
+ assetStatus: output.assetStatus,
524
+ ...trace,
525
+ };
526
+ }
527
+ return {
528
+ ok: true,
529
+ kind: 'voice-catalog',
530
+ summary: `${output.voiceCount} voice${output.voiceCount === 1 ? '' : 's'}${output.sample.length ? ` / ${output.sample.map((voice) => voice.voiceId).filter(Boolean).join(', ')}` : ''}`,
531
+ voiceCount: output.voiceCount,
532
+ sample: output.sample,
533
+ traceId: result.trace?.traceId,
534
+ };
535
+ }
536
+
537
+ export function restoreStudioCapabilityRunResult(
538
+ record: StudioRunHistoryRecord,
539
+ resolveCapabilityLabel: StudioCapabilityLabelResolver,
540
+ ): StudioCapabilityRunResult | null {
541
+ const snapshot = record.result;
542
+ if (!snapshot) return null;
543
+ if (isStudioNonSuccessHistorySnapshot(snapshot)) {
544
+ return {
545
+ ok: false,
546
+ capabilityId: record.capabilityId,
547
+ reason: snapshot.reason,
548
+ message: snapshot.message,
549
+ actionHint: snapshot.actionHint,
550
+ ...(snapshot.missingSurface ? { missingSurface: snapshot.missingSurface } : {}),
551
+ ...(snapshot.diagnostics ? { diagnostics: { ...snapshot.diagnostics } } : {}),
552
+ };
553
+ }
554
+
555
+ let capabilityLabel: string;
556
+ try {
557
+ capabilityLabel = resolveCapabilityLabel(record.capabilityId) || '';
558
+ if (!capabilityLabel) return null;
559
+ } catch {
560
+ return null;
561
+ }
562
+ const trace = snapshot.traceId
563
+ ? { traceId: snapshot.traceId }
564
+ : undefined;
565
+ const common = {
566
+ ok: true as const,
567
+ capabilityId: record.capabilityId,
568
+ capabilityLabel,
569
+ message: record.message,
570
+ ...(trace ? { trace } : {}),
571
+ };
572
+ if (snapshot.kind === 'text') {
573
+ return {
574
+ ...common,
575
+ output: {
576
+ kind: 'text',
577
+ text: snapshot.body,
578
+ finishReason: snapshot.finishReason,
579
+ streamed: snapshot.streamed,
580
+ inputTokens: snapshot.inputTokens,
581
+ outputTokens: snapshot.outputTokens,
582
+ totalTokens: snapshot.totalTokens,
583
+ },
584
+ };
585
+ }
586
+ if (snapshot.kind === 'embedding') {
587
+ return {
588
+ ...common,
589
+ output: {
590
+ kind: 'embedding',
591
+ vectorCount: snapshot.vectorCount,
592
+ dimensions: snapshot.dimensions,
593
+ sample: snapshot.sample,
594
+ totalTokens: snapshot.totalTokens,
595
+ },
596
+ };
597
+ }
598
+ if (snapshot.kind === 'artifacts') {
599
+ const artifacts = snapshot.artifacts?.map((artifact) => ({ ...artifact }))
600
+ ?? (snapshot.firstArtifact ? [{ ...snapshot.firstArtifact }] : []);
601
+ return {
602
+ ...common,
603
+ output: {
604
+ kind: 'artifacts',
605
+ jobId: snapshot.jobId,
606
+ jobState: snapshot.jobState,
607
+ artifactCount: snapshot.artifactCount,
608
+ artifacts,
609
+ ...(artifacts[0] ? { firstArtifact: artifacts[0] } : {}),
610
+ },
611
+ };
612
+ }
613
+ if (snapshot.kind === 'transcript') {
614
+ return {
615
+ ...common,
616
+ output: {
617
+ kind: 'transcript',
618
+ text: snapshot.body,
619
+ jobId: snapshot.jobId,
620
+ jobState: snapshot.jobState,
621
+ artifactCount: snapshot.artifactCount,
622
+ },
623
+ };
624
+ }
625
+ if (snapshot.kind === 'voice-asset') {
626
+ return {
627
+ ...common,
628
+ output: {
629
+ kind: 'voice-asset',
630
+ jobId: snapshot.jobId,
631
+ jobState: snapshot.jobState,
632
+ voiceAssetId: snapshot.voiceAssetId,
633
+ creationSource: snapshot.creationSource,
634
+ assetStatus: snapshot.assetStatus,
635
+ voiceReference: { kind: 'voice_asset_id', voiceAssetId: snapshot.voiceAssetId },
636
+ },
637
+ };
638
+ }
639
+ return {
640
+ ...common,
641
+ output: {
642
+ kind: 'voice-catalog',
643
+ voiceCount: snapshot.voiceCount,
644
+ sample: snapshot.sample,
645
+ },
646
+ };
647
+ }
648
+
649
+ export function getStudioRunResultSummary(record: StudioRunHistoryRecord): string {
650
+ return record.result?.summary || record.message;
651
+ }
652
+
653
+ export function getStudioRunPromptSummary(record: StudioRunHistoryRecord): string {
654
+ const normalized = record.prompt.replace(/\s+/g, ' ').trim();
655
+ return normalized.length > 130 ? `${normalized.slice(0, 127)}...` : normalized;
656
+ }
657
+
658
+ function formatStudioTokenUsage(inputTokens?: number, outputTokens?: number, totalTokens?: number): string {
659
+ const resolvedTotal = totalTokens ?? (inputTokens !== undefined && outputTokens !== undefined ? inputTokens + outputTokens : undefined);
660
+ if (resolvedTotal !== undefined) return `${resolvedTotal} tokens`;
661
+ return '';
662
+ }
663
+
664
+ function compactSettingValue(value: string, maxLength = 220): string {
665
+ const normalized = value.replace(/\s+/g, ' ').trim();
666
+ if (!normalized) return '';
667
+ return normalized.length > maxLength ? `${normalized.slice(0, maxLength - 3)}...` : normalized;
668
+ }
669
+
670
+ function formatStudioRunConfigValue(value: unknown): { value: string; code: boolean } {
671
+ if (value === null) return { value: 'null', code: true };
672
+ if (typeof value === 'string') return { value: value.length > 0 ? value : '""', code: false };
673
+ if (typeof value === 'number' || typeof value === 'boolean') return { value: String(value), code: true };
674
+ if (Array.isArray(value) && value.every((entry) => typeof entry === 'string')) {
675
+ return { value: value.join(', '), code: false };
676
+ }
677
+ if (Array.isArray(value) || isJsonObject(value)) {
678
+ try {
679
+ return { value: JSON.stringify(value), code: true };
680
+ } catch {
681
+ return { value: String(value), code: true };
682
+ }
683
+ }
684
+ return { value: String(value), code: false };
685
+ }
686
+
687
+ function pushFact(out: StudioRunPromptControlFact[], label: string, value: string | null | undefined, code = false): void {
688
+ const normalized = typeof value === 'string' ? compactSettingValue(value) : '';
689
+ if (normalized) out.push({ label, value: normalized, code });
690
+ }
691
+
692
+ export function getStudioRunPromptControlFacts(runConfig: StudioRunConfigSnapshot): StudioRunPromptControlFact[] {
693
+ const facts: StudioRunPromptControlFact[] = [];
694
+ if (runConfig.promptControls.toneSelected) {
695
+ pushFact(facts, 'Tone', runConfig.promptControls.tone);
696
+ }
697
+ if (runConfig.promptControls.lengthSelected) {
698
+ pushFact(facts, 'Length', runConfig.promptControls.length);
699
+ }
700
+ if (runConfig.promptControls.attachmentCount > 0) {
701
+ facts.push({
702
+ label: 'Attachments',
703
+ value: String(runConfig.promptControls.attachmentCount),
704
+ code: true,
705
+ });
706
+ }
707
+ return facts;
708
+ }
709
+
710
+ const PARAM_GROUP_LABELS = {
711
+ prompt: 'Prompt controls',
712
+ generation: 'Generation defaults',
713
+ response: 'Response controls',
714
+ advanced: 'Advanced settings',
715
+ } as const;
716
+
717
+ const TEXT_REQUEST_PARAM_ORDER: ReadonlyArray<{ key: string; label: string; group: string }> = [
718
+ { key: 'tone', label: 'Tone', group: PARAM_GROUP_LABELS.prompt },
719
+ { key: 'length', label: 'Length', group: PARAM_GROUP_LABELS.prompt },
720
+ { key: 'temperature', label: 'Temperature', group: PARAM_GROUP_LABELS.generation },
721
+ { key: 'maxTokens', label: 'Max Tokens', group: PARAM_GROUP_LABELS.generation },
722
+ { key: 'topP', label: 'Top P', group: PARAM_GROUP_LABELS.generation },
723
+ { key: 'topK', label: 'Top K', group: PARAM_GROUP_LABELS.generation },
724
+ { key: 'stop', label: 'Stop Sequences', group: PARAM_GROUP_LABELS.response },
725
+ { key: 'seed', label: 'Seed', group: PARAM_GROUP_LABELS.response },
726
+ { key: 'presencePenalty', label: 'Presence Penalty', group: PARAM_GROUP_LABELS.advanced },
727
+ { key: 'frequencyPenalty', label: 'Frequency Penalty', group: PARAM_GROUP_LABELS.advanced },
728
+ ];
729
+
730
+ const HIDDEN_REQUEST_PARAM_KEYS = Object.freeze([
731
+ 'companionSlots',
732
+ 'profileEntries',
733
+ 'profile_entries',
734
+ 'entryOverrides',
735
+ 'entry_overrides',
736
+ ] as const);
737
+
738
+ function hasRunConfigParam(value: unknown): boolean {
739
+ if (typeof value === 'string') return value.trim().length > 0;
740
+ if (typeof value === 'number') return Number.isFinite(value);
741
+ if (typeof value === 'boolean') return true;
742
+ if (Array.isArray(value)) return value.length > 0;
743
+ return Boolean(value);
744
+ }
745
+
746
+ function runConfigParamDefinitions(runConfig: StudioRunConfigSnapshot): ReadonlyArray<{ key: string; label: string; group: string }> {
747
+ if (runConfig.target.capabilityId === 'text.generate' || runConfig.target.capabilityId === 'chat.stream') {
748
+ return TEXT_REQUEST_PARAM_ORDER;
749
+ }
750
+ return Object.keys(runConfig.target.params)
751
+ .filter((key) => !HIDDEN_REQUEST_PARAM_KEYS.includes(key as (typeof HIDDEN_REQUEST_PARAM_KEYS)[number]))
752
+ .map((key) => ({ key, label: key, group: 'Request parameters' }));
753
+ }
754
+
755
+ export function getStudioRunConfigParamRows(runConfig: StudioRunConfigSnapshot): StudioRunConfigParamRow[] {
756
+ const params = runConfig.target.params;
757
+ if (!isJsonObject(params)) return [];
758
+ return runConfigParamDefinitions(runConfig).flatMap((definition) => {
759
+ const value = params[definition.key];
760
+ if (!hasRunConfigParam(value)) return [];
761
+ const formatted = formatStudioRunConfigValue(value);
762
+ return [{
763
+ group: definition.group,
764
+ key: definition.key,
765
+ label: definition.label,
766
+ value: formatted.value,
767
+ code: formatted.code,
768
+ }];
769
+ });
770
+ }
771
+
772
+ export function getStudioRunIntentLabel(record: StudioRunHistoryRecord): string {
773
+ const label = record.runConfig?.target.intentLabel?.trim();
774
+ if (label) return label;
775
+ return getStudioRunStatusLabel(record.status);
776
+ }
777
+
778
+ export function getStudioRunIntentSource(record: StudioRunHistoryRecord): StudioRunIntentSource {
779
+ const targetSource = record.runConfig?.target.source;
780
+ if (targetSource === 'local') return 'local';
781
+ if (targetSource === 'cloud') return 'cloud';
782
+ return 'unknown';
783
+ }
784
+
785
+ export function getStudioRunMetricSummary(record: StudioRunHistoryRecord): string {
786
+ const result = record.result;
787
+ if (!result) return getStudioRunResultSummary(record);
788
+ if (isStudioNonSuccessHistorySnapshot(result)) return result.reason;
789
+ if (result.kind === 'text') {
790
+ return [
791
+ formatStudioTokenUsage(result.inputTokens, result.outputTokens, result.totalTokens),
792
+ `${result.charCount} chars`,
793
+ ].filter(Boolean).join(' / ');
794
+ }
795
+ if (result.kind === 'embedding') {
796
+ return [
797
+ formatStudioTokenUsage(undefined, undefined, result.totalTokens),
798
+ `${result.vectorCount} vector${result.vectorCount === 1 ? '' : 's'}`,
799
+ `${result.dimensions} dims`,
800
+ ].filter(Boolean).join(' / ');
801
+ }
802
+ if (result.kind === 'artifacts') return `${result.jobState || 'unknown'} / ${result.artifactCount} artifact${result.artifactCount === 1 ? '' : 's'}`;
803
+ if (result.kind === 'transcript') return `${result.jobState || 'unknown'} / ${result.charCount} chars / ${result.artifactCount} artifact${result.artifactCount === 1 ? '' : 's'}`;
804
+ if (result.kind === 'voice-asset') return `${result.jobState || 'unknown'} / ${result.creationSource} / ${result.assetStatus}`;
805
+ return `${result.voiceCount} voice${result.voiceCount === 1 ? '' : 's'}`;
806
+ }
807
+
808
+ export function getStudioRunResultTags(record: StudioRunHistoryRecord): string[] {
809
+ const result = record.result;
810
+ if (!result) return [record.status === 'ready' ? 'Runtime' : getStudioRunStatusLabel(record.status)];
811
+ if (isStudioNonSuccessHistorySnapshot(result)) return [result.reason];
812
+ if (result.kind === 'text') {
813
+ return [
814
+ result.streamed ? 'Stream' : 'Runtime',
815
+ `${result.charCount} chars`,
816
+ result.totalTokens === undefined ? '' : `${result.totalTokens} tokens`,
817
+ ].filter(Boolean);
818
+ }
819
+ if (result.kind === 'embedding') return ['Embedding ready'];
820
+ if (result.kind === 'artifacts') return ['Ready'];
821
+ if (result.kind === 'transcript') return ['Ready'];
822
+ if (result.kind === 'voice-asset') return ['VoiceAsset ready', result.creationSource];
823
+ return [`${result.voiceCount} voices`];
824
+ }