@nimiplatform/app-tools 0.1.3 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +198 -6
- package/README.md +83 -27
- package/bin/nimi-app.mjs +328 -45
- package/lib/app-access-declaration.mjs +49 -0
- package/lib/app-doctor-update.mjs +411 -149
- package/lib/app-pack.mjs +401 -0
- package/lib/app-project-lifecycle.mjs +1141 -0
- package/lib/app-scaffold-capabilities.mjs +769 -0
- package/lib/app-scaffold-default-source.mjs +21 -0
- package/lib/app-scaffold-profiles.mjs +1093 -0
- package/lib/app-scaffold.mjs +1266 -813
- package/lib/index.mjs +194 -42
- package/lib/simulator-conformance-ast.mjs +498 -0
- package/lib/simulator-conformance-css.mjs +116 -0
- package/lib/simulator-conformance-graph.mjs +757 -0
- package/lib/simulator-conformance.d.mts +14 -0
- package/lib/simulator-conformance.mjs +203 -0
- package/lib/simulator-css-profile.d.mts +27 -0
- package/lib/simulator-css-profile.mjs +531 -0
- package/lib/simulator-kit-export-resolution.mjs +70 -0
- package/lib/simulator-manifest.mjs +334 -0
- package/package.json +66 -3
- package/scripts/dev-shell.mjs +465 -0
- package/scripts/sync-app-source.mjs +300 -0
- package/scripts/sync-scaffold-versions.mjs +91 -0
- package/templates/app-source/LICENSE +21 -0
- package/templates/app-source/src/ai-studio-core/ai-config.ts +100 -0
- package/templates/app-source/src/ai-studio-core/ai-studio-core.css +338 -0
- package/templates/app-source/src/ai-studio-core/contexts.tsx +61 -0
- package/templates/app-source/src/ai-studio-core/history-policy.ts +447 -0
- package/templates/app-source/src/ai-studio-core/history.ts +824 -0
- package/templates/app-source/src/ai-studio-core/host-context.tsx +79 -0
- package/templates/app-source/src/ai-studio-core/index.ts +214 -0
- package/templates/app-source/src/ai-studio-core/messages/en.json +310 -0
- package/templates/app-source/src/ai-studio-core/messages/index.ts +47 -0
- package/templates/app-source/src/ai-studio-core/messages/zh.json +310 -0
- package/templates/app-source/src/ai-studio-core/module-registration.ts +109 -0
- package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +65 -0
- package/templates/app-source/src/ai-studio-core/parameter-fields.tsx +247 -0
- package/templates/app-source/src/ai-studio-core/parameters.ts +110 -0
- package/templates/app-source/src/ai-studio-core/prompt-drafts.ts +69 -0
- package/templates/app-source/src/ai-studio-core/run-target.ts +123 -0
- package/templates/app-source/src/ai-studio-core/runtime-dispatcher.ts +35 -0
- package/templates/app-source/src/ai-studio-core/runtime-types.ts +86 -0
- package/templates/app-source/src/ai-studio-core/runtime.ts +306 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-admission.ts +38 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-ai-config.tsx +30 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-artifact-preview.ts +40 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +257 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +676 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +19 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +291 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +413 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +174 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +449 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-surface.tsx +45 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +494 -0
- package/templates/app-source/src/ai-studio-core/studio-directives.ts +33 -0
- package/templates/app-source/src/ai-studio-core/workspace.tsx +381 -0
- package/templates/app-source/src/product-modules/agent-center/index.tsx +27 -0
- package/templates/app-source/src/product-modules/agent-conversation/index.tsx +19 -0
- package/templates/app-source/src/product-modules/agent-realtime/index.tsx +29 -0
- package/templates/app-source/src/product-modules/kit-recipes/gallery.tsx +142 -0
- package/templates/app-source/src/product-modules/kit-recipes/index.tsx +19 -0
- package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-data-recipes.tsx +336 -0
- package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-demos.tsx +165 -0
- package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-recipes.tsx +682 -0
- package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-surface.tsx +341 -0
- package/templates/app-source/src/studio-modules/studio-create/descriptors.ts +26 -0
- package/templates/app-source/src/studio-modules/studio-create/index.ts +14 -0
- package/templates/app-source/src/studio-modules/studio-create/messages/en.json +67 -0
- package/templates/app-source/src/studio-modules/studio-create/messages/index.ts +5 -0
- package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +67 -0
- package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +153 -0
- package/templates/app-source/src/studio-modules/studio-create/parameters.ts +70 -0
- package/templates/app-source/src/studio-modules/studio-create/registration.ts +46 -0
- package/templates/app-source/src/studio-modules/studio-create/runtime.ts +339 -0
- package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +22 -0
- package/templates/app-source/src/studio-modules/studio-media/index.ts +12 -0
- package/templates/app-source/src/studio-modules/studio-media/messages/en.json +82 -0
- package/templates/app-source/src/studio-modules/studio-media/messages/index.ts +5 -0
- package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +82 -0
- package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +283 -0
- package/templates/app-source/src/studio-modules/studio-media/parameters.ts +94 -0
- package/templates/app-source/src/studio-modules/studio-media/registration.ts +44 -0
- package/templates/app-source/src/studio-modules/studio-media/runtime.ts +113 -0
- package/templates/app-source/src/studio-modules/studio-voice/descriptors.ts +28 -0
- package/templates/app-source/src/studio-modules/studio-voice/index.ts +16 -0
- package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +99 -0
- package/templates/app-source/src/studio-modules/studio-voice/messages/index.ts +5 -0
- package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +99 -0
- package/templates/app-source/src/studio-modules/studio-voice/parameter-panel.tsx +284 -0
- package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +116 -0
- package/templates/app-source/src/studio-modules/studio-voice/registration.ts +59 -0
- package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +347 -0
- package/templates/app-source/src/workbench-core/empty-state.tsx +31 -0
- package/templates/app-source/src/workbench-core/index.ts +17 -0
- package/templates/app-source/src/workbench-core/runtime-gate.tsx +131 -0
- package/templates/app-source/src/workbench-core/workbench-core.css +255 -0
- package/templates/app-source/src/workbench-core/workbench-core.tsx +140 -0
- package/templates/app-source.manifest.json +333 -0
- package/templates/default-starter/AGENTS.md +33 -0
- package/templates/default-starter/LICENSE +21 -0
- package/templates/default-starter/README.md +41 -0
- package/templates/default-starter/SECURITY.md +5 -0
- package/templates/default-starter/index.html +12 -0
- package/templates/default-starter/scripts/validate.mjs +26 -0
- package/templates/default-starter/src/shell/App.tsx +27 -0
- package/templates/default-starter/src/shell/auth/app-identity.ts +3 -0
- package/templates/default-starter/src/shell/auth/local-app-client.ts +18 -0
- package/templates/default-starter/src/shell/auth/runtime-platform.ts +110 -0
- package/templates/default-starter/src/shell/authenticated-shell.tsx +20 -0
- package/templates/default-starter/src/shell/workbench-target-adapter.ts +40 -0
- package/templates/default-starter/src/styles.css +26 -0
- package/templates/default-starter/src-tauri/Cargo.toml +17 -0
- package/templates/default-starter/src-tauri/build.rs +5 -0
- package/templates/default-starter/src-tauri/capabilities/default.json +7 -0
- package/templates/default-starter/src-tauri/tauri.conf.json +26 -0
- package/templates/default-starter/tsconfig.json +18 -0
- package/templates/default-starter.manifest.json +99 -0
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
import { isJsonObject } from '@nimiplatform/sdk/types';
|
|
2
|
+
|
|
3
|
+
import type { AIStudioHistoryPanelPreferences } from './workspace.js';
|
|
4
|
+
import type { StudioRunHistory, StudioRunHistoryRecord } from './history.js';
|
|
5
|
+
|
|
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
|
+
|
|
10
|
+
export const DEFAULT_AI_STUDIO_HISTORY_PANEL_PREFERENCES: AIStudioHistoryPanelPreferences = Object.freeze({
|
|
11
|
+
collapsed: true,
|
|
12
|
+
scope: 'capability',
|
|
13
|
+
hideFailures: false,
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
function historyError(path: string, detail: string): never {
|
|
17
|
+
throw new Error(`AI Studio history payload ${detail} at ${path}.`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function requiredString(value: unknown, path: string): string {
|
|
21
|
+
if (typeof value !== 'string') return historyError(path, 'requires a string');
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function optionalString(value: unknown, path: string): void {
|
|
26
|
+
if (value !== undefined && typeof value !== 'string') historyError(path, 'requires a string when present');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function nonNegativeNumber(value: unknown, path: string): void {
|
|
30
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
|
|
31
|
+
historyError(path, 'requires a non-negative finite number');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function optionalNonNegativeNumber(value: unknown, path: string): void {
|
|
36
|
+
if (value !== undefined) nonNegativeNumber(value, path);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function validateManagedArtifact(value: unknown, path: string): void {
|
|
40
|
+
if (!isJsonObject(value)) historyError(path, 'requires an object');
|
|
41
|
+
requiredString(value.relativePath, `${path}.relativePath`);
|
|
42
|
+
optionalString(value.mediaType, `${path}.mediaType`);
|
|
43
|
+
nonNegativeNumber(value.sizeBytes, `${path}.sizeBytes`);
|
|
44
|
+
const sha256 = requiredString(value.sha256, `${path}.sha256`);
|
|
45
|
+
if (!/^sha256:[0-9a-f]{64}$/u.test(sha256)) historyError(`${path}.sha256`, 'requires a canonical SHA-256 digest');
|
|
46
|
+
optionalString(value.displayName, `${path}.displayName`);
|
|
47
|
+
if (value.previewSource !== 'managed-asset') historyError(`${path}.previewSource`, 'requires managed-asset');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function validateHistoryResult(value: unknown, path: string): void {
|
|
51
|
+
if (!isJsonObject(value) || typeof value.ok !== 'boolean') historyError(path, 'requires a discriminated result object');
|
|
52
|
+
const kind = requiredString(value.kind, `${path}.kind`);
|
|
53
|
+
requiredString(value.summary, `${path}.summary`);
|
|
54
|
+
if (value.ok === false) {
|
|
55
|
+
if (kind !== 'non-success') historyError(`${path}.kind`, 'requires non-success for a failed result');
|
|
56
|
+
if (!['runtime-unavailable', 'input-invalid', 'sdk-method-unavailable', 'principal-unauthorized', 'operation-aborted', 'runtime-canceled', 'runtime-timeout', 'stream-interrupted', 'runtime-call-failed'].includes(String(value.reason))) {
|
|
57
|
+
historyError(`${path}.reason`, 'has an unsupported value');
|
|
58
|
+
}
|
|
59
|
+
requiredString(value.message, `${path}.message`);
|
|
60
|
+
requiredString(value.actionHint, `${path}.actionHint`);
|
|
61
|
+
optionalString(value.missingSurface, `${path}.missingSurface`);
|
|
62
|
+
if (value.diagnostics !== undefined) {
|
|
63
|
+
if (!isJsonObject(value.diagnostics)) historyError(`${path}.diagnostics`, 'requires an object');
|
|
64
|
+
const reasonCode = requiredString(value.diagnostics.reasonCode, `${path}.diagnostics.reasonCode`);
|
|
65
|
+
if (!/^[A-Z][A-Z0-9_]{0,127}$/u.test(reasonCode)) historyError(`${path}.diagnostics.reasonCode`, 'is invalid');
|
|
66
|
+
const actionHint = value.diagnostics.actionHint;
|
|
67
|
+
optionalString(actionHint, `${path}.diagnostics.actionHint`);
|
|
68
|
+
if (typeof actionHint === 'string' && actionHint && !/^[A-Za-z0-9_.-]{1,256}$/u.test(actionHint)) {
|
|
69
|
+
historyError(`${path}.diagnostics.actionHint`, 'is invalid');
|
|
70
|
+
}
|
|
71
|
+
const traceId = value.diagnostics.traceId;
|
|
72
|
+
optionalString(traceId, `${path}.diagnostics.traceId`);
|
|
73
|
+
if (typeof traceId === 'string' && traceId && !/^[A-Za-z0-9_.:-]{1,512}$/u.test(traceId)) {
|
|
74
|
+
historyError(`${path}.diagnostics.traceId`, 'is invalid');
|
|
75
|
+
}
|
|
76
|
+
const source = value.diagnostics.source;
|
|
77
|
+
optionalString(source, `${path}.diagnostics.source`);
|
|
78
|
+
if (typeof source === 'string' && source && !['runtime', 'sdk', 'realm'].includes(source)) {
|
|
79
|
+
historyError(`${path}.diagnostics.source`, 'is invalid');
|
|
80
|
+
}
|
|
81
|
+
if (value.diagnostics.retryable !== undefined && typeof value.diagnostics.retryable !== 'boolean') {
|
|
82
|
+
historyError(`${path}.diagnostics.retryable`, 'requires a boolean');
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
optionalString(value.traceId, `${path}.traceId`);
|
|
88
|
+
if (kind === 'text') {
|
|
89
|
+
requiredString(value.body, `${path}.body`);
|
|
90
|
+
nonNegativeNumber(value.charCount, `${path}.charCount`);
|
|
91
|
+
requiredString(value.finishReason, `${path}.finishReason`);
|
|
92
|
+
if (typeof value.streamed !== 'boolean') historyError(`${path}.streamed`, 'requires a boolean');
|
|
93
|
+
optionalNonNegativeNumber(value.inputTokens, `${path}.inputTokens`);
|
|
94
|
+
optionalNonNegativeNumber(value.outputTokens, `${path}.outputTokens`);
|
|
95
|
+
optionalNonNegativeNumber(value.totalTokens, `${path}.totalTokens`);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (kind === 'embedding') {
|
|
99
|
+
nonNegativeNumber(value.vectorCount, `${path}.vectorCount`);
|
|
100
|
+
nonNegativeNumber(value.dimensions, `${path}.dimensions`);
|
|
101
|
+
if (!Array.isArray(value.sample) || value.sample.some((entry) => typeof entry !== 'number' || !Number.isFinite(entry))) {
|
|
102
|
+
historyError(`${path}.sample`, 'requires finite numbers');
|
|
103
|
+
}
|
|
104
|
+
optionalNonNegativeNumber(value.totalTokens, `${path}.totalTokens`);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (kind === 'artifacts') {
|
|
108
|
+
requiredString(value.jobId, `${path}.jobId`);
|
|
109
|
+
requiredString(value.jobState, `${path}.jobState`);
|
|
110
|
+
nonNegativeNumber(value.artifactCount, `${path}.artifactCount`);
|
|
111
|
+
if (value.artifacts !== undefined) {
|
|
112
|
+
if (!Array.isArray(value.artifacts)) historyError(`${path}.artifacts`, 'requires an array');
|
|
113
|
+
value.artifacts.forEach((artifact, index) => validateManagedArtifact(artifact, `${path}.artifacts[${index}]`));
|
|
114
|
+
if (value.artifacts.length !== value.artifactCount) historyError(`${path}.artifacts`, 'must match artifactCount');
|
|
115
|
+
}
|
|
116
|
+
if (value.firstArtifact !== undefined) validateManagedArtifact(value.firstArtifact, `${path}.firstArtifact`);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (kind === 'transcript') {
|
|
120
|
+
requiredString(value.body, `${path}.body`);
|
|
121
|
+
nonNegativeNumber(value.charCount, `${path}.charCount`);
|
|
122
|
+
requiredString(value.jobId, `${path}.jobId`);
|
|
123
|
+
requiredString(value.jobState, `${path}.jobState`);
|
|
124
|
+
nonNegativeNumber(value.artifactCount, `${path}.artifactCount`);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
if (kind === 'voice-asset') {
|
|
128
|
+
requiredString(value.jobId, `${path}.jobId`);
|
|
129
|
+
requiredString(value.jobState, `${path}.jobState`);
|
|
130
|
+
requiredString(value.voiceAssetId, `${path}.voiceAssetId`);
|
|
131
|
+
if (value.creationSource !== 'reference-audio' && value.creationSource !== 'text-description') historyError(`${path}.creationSource`, 'is invalid');
|
|
132
|
+
requiredString(value.assetStatus, `${path}.assetStatus`);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (kind === 'voice-catalog') {
|
|
136
|
+
nonNegativeNumber(value.voiceCount, `${path}.voiceCount`);
|
|
137
|
+
if (!Array.isArray(value.sample)) historyError(`${path}.sample`, 'requires an array');
|
|
138
|
+
value.sample.forEach((entry, index) => {
|
|
139
|
+
if (!isJsonObject(entry)) historyError(`${path}.sample[${index}]`, 'requires an object');
|
|
140
|
+
requiredString(entry.voiceId, `${path}.sample[${index}].voiceId`);
|
|
141
|
+
requiredString(entry.creationSource, `${path}.sample[${index}].creationSource`);
|
|
142
|
+
requiredString(entry.status, `${path}.sample[${index}].status`);
|
|
143
|
+
});
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
historyError(`${path}.kind`, `has unsupported value ${kind}`);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function validateRunConfig(value: unknown, path: string): void {
|
|
150
|
+
if (!isJsonObject(value) || !isJsonObject(value.target) || !isJsonObject(value.promptControls)) {
|
|
151
|
+
historyError(path, 'requires target and promptControls objects');
|
|
152
|
+
}
|
|
153
|
+
const target = value.target;
|
|
154
|
+
requiredString(target.capabilityId, `${path}.target.capabilityId`);
|
|
155
|
+
if (target.capabilityContract !== null) requiredString(target.capabilityContract, `${path}.target.capabilityContract`);
|
|
156
|
+
for (const field of ['section', 'status', 'source', 'intentLabel', 'detail'] as const) requiredString(target[field], `${path}.target.${field}`);
|
|
157
|
+
if (!isJsonObject(target.params)) historyError(`${path}.target.params`, 'requires an object');
|
|
158
|
+
if (!Array.isArray(target.paramsSummary) || target.paramsSummary.some((entry) => typeof entry !== 'string')) historyError(`${path}.target.paramsSummary`, 'requires strings');
|
|
159
|
+
if (target.profileOrigin !== null) historyError(`${path}.target.profileOrigin`, 'requires null');
|
|
160
|
+
const controls = value.promptControls;
|
|
161
|
+
optionalString(controls.tone, `${path}.promptControls.tone`);
|
|
162
|
+
optionalString(controls.length, `${path}.promptControls.length`);
|
|
163
|
+
if (controls.toneSelected !== undefined && typeof controls.toneSelected !== 'boolean') historyError(`${path}.promptControls.toneSelected`, 'requires a boolean');
|
|
164
|
+
if (controls.lengthSelected !== undefined && typeof controls.lengthSelected !== 'boolean') historyError(`${path}.promptControls.lengthSelected`, 'requires a boolean');
|
|
165
|
+
if (typeof controls.contextAttached !== 'boolean') historyError(`${path}.promptControls.contextAttached`, 'requires a boolean');
|
|
166
|
+
optionalString(controls.context, `${path}.promptControls.context`);
|
|
167
|
+
nonNegativeNumber(controls.attachmentCount, `${path}.promptControls.attachmentCount`);
|
|
168
|
+
optionalString(value.traceId, `${path}.traceId`);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function parseHistoryRecord(value: unknown, path: string, capabilityId: string): StudioRunHistoryRecord {
|
|
172
|
+
if (!isJsonObject(value)) historyError(path, 'requires an object');
|
|
173
|
+
requiredString(value.id, `${path}.id`);
|
|
174
|
+
if (requiredString(value.capabilityId, `${path}.capabilityId`) !== capabilityId) historyError(`${path}.capabilityId`, `must match ${capabilityId}`);
|
|
175
|
+
requiredString(value.prompt, `${path}.prompt`);
|
|
176
|
+
if (!['unavailable', 'ready', 'failed', 'canceled', 'timed-out', 'local-fixture'].includes(String(value.status))) historyError(`${path}.status`, 'has an unsupported value');
|
|
177
|
+
requiredString(value.message, `${path}.message`);
|
|
178
|
+
const createdAt = requiredString(value.createdAt, `${path}.createdAt`);
|
|
179
|
+
if (Number.isNaN(new Date(createdAt).valueOf())) historyError(`${path}.createdAt`, 'requires a valid timestamp');
|
|
180
|
+
if (value.result !== undefined) validateHistoryResult(value.result, `${path}.result`);
|
|
181
|
+
if (value.runConfig !== undefined) validateRunConfig(value.runConfig, `${path}.runConfig`);
|
|
182
|
+
return value as unknown as StudioRunHistoryRecord;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function parseStudioRunHistory(value: unknown): StudioRunHistory {
|
|
186
|
+
if (value === undefined) return {};
|
|
187
|
+
if (!isJsonObject(value)) throw new Error('AI Studio history payload must be an object.');
|
|
188
|
+
const history: StudioRunHistory = {};
|
|
189
|
+
for (const [capabilityId, entries] of Object.entries(value)) {
|
|
190
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(capabilityId)) historyError('$', `contains invalid capability id ${capabilityId}`);
|
|
191
|
+
if (!Array.isArray(entries)) historyError(`$.${capabilityId}`, 'requires an array');
|
|
192
|
+
history[capabilityId] = entries.map((entry, index) => parseHistoryRecord(entry, `$.${capabilityId}[${index}]`, capabilityId));
|
|
193
|
+
}
|
|
194
|
+
return history;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function flattenStudioHistoryRecords(history: StudioRunHistory): StudioRunHistoryRecord[] {
|
|
198
|
+
return Object.values(history).flatMap((records) => records);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function studioHistoryFromRecords(records: readonly StudioRunHistoryRecord[]): StudioRunHistory {
|
|
202
|
+
const history: StudioRunHistory = {};
|
|
203
|
+
for (const record of records) {
|
|
204
|
+
const existing = Object.hasOwn(history, record.capabilityId) ? history[record.capabilityId] ?? [] : [];
|
|
205
|
+
Object.defineProperty(history, record.capabilityId, {
|
|
206
|
+
value: [...existing, record],
|
|
207
|
+
enumerable: true,
|
|
208
|
+
configurable: true,
|
|
209
|
+
writable: true,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
return history;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export function boundStudioRunHistoryWithRecord(history: StudioRunHistory, record: StudioRunHistoryRecord): StudioRunHistory {
|
|
216
|
+
const counts = new Map<string, number>();
|
|
217
|
+
const retained = [record, ...flattenStudioHistoryRecords(history).filter((existing) => existing.id !== record.id)]
|
|
218
|
+
.sort((left, right) => right.createdAt.localeCompare(left.createdAt))
|
|
219
|
+
.filter((candidate) => {
|
|
220
|
+
const count = counts.get(candidate.capabilityId) ?? 0;
|
|
221
|
+
if (count >= STUDIO_HISTORY_LIMIT_PER_CAPABILITY) return false;
|
|
222
|
+
counts.set(candidate.capabilityId, count + 1);
|
|
223
|
+
return true;
|
|
224
|
+
})
|
|
225
|
+
.slice(0, STUDIO_HISTORY_LIMIT_TOTAL_RECORDS);
|
|
226
|
+
let next = studioHistoryFromRecords(retained);
|
|
227
|
+
while (new TextEncoder().encode(JSON.stringify(next)).byteLength > STUDIO_HISTORY_LIMIT_BYTES) {
|
|
228
|
+
if (retained.length <= 1) throw new Error('AI Studio history record exceeds the storage document limit.');
|
|
229
|
+
retained.pop();
|
|
230
|
+
next = studioHistoryFromRecords(retained);
|
|
231
|
+
}
|
|
232
|
+
if (!retained.some((candidate) => candidate.id === record.id)) throw new Error('AI Studio history could not retain the newly completed run.');
|
|
233
|
+
return next;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function removeStudioRunHistoryRecord(history: StudioRunHistory, recordId: string): StudioRunHistory {
|
|
237
|
+
return studioHistoryFromRecords(flattenStudioHistoryRecords(history).filter((record) => record.id !== recordId));
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function clearStudioRunHistory(history: StudioRunHistory, capabilityId: string | null): StudioRunHistory {
|
|
241
|
+
if (capabilityId === null) return {};
|
|
242
|
+
return studioHistoryFromRecords(flattenStudioHistoryRecords(history).filter((record) => record.capabilityId !== capabilityId));
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export type StudioHistoryPolicyMutationIssue = {
|
|
246
|
+
readonly runId: string;
|
|
247
|
+
readonly step: 'asset' | 'history';
|
|
248
|
+
readonly message: string;
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
export type StudioHistoryPolicyMutationOutcome<TProjection> = {
|
|
252
|
+
readonly completed: number;
|
|
253
|
+
readonly skipped: number;
|
|
254
|
+
readonly failed: number;
|
|
255
|
+
readonly projection: TProjection;
|
|
256
|
+
readonly issues: readonly StudioHistoryPolicyMutationIssue[];
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
export function studioHistoryClearOutcomeTone(outcome: {
|
|
260
|
+
readonly skipped: number;
|
|
261
|
+
readonly failed: number;
|
|
262
|
+
}): 'success' | 'warning' | 'danger' {
|
|
263
|
+
if (outcome.failed > 0) return 'danger';
|
|
264
|
+
if (outcome.skipped > 0) return 'warning';
|
|
265
|
+
return 'success';
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export type StudioHistoryMutationSubject = {
|
|
269
|
+
readonly id: string;
|
|
270
|
+
readonly capabilityId: string;
|
|
271
|
+
readonly artifactPaths: readonly string[];
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
export function studioHistoryArtifactPaths(record: StudioRunHistoryRecord): string[] {
|
|
275
|
+
const result = record.result;
|
|
276
|
+
if (!result || result.ok === false || result.kind !== 'artifacts') return [];
|
|
277
|
+
const artifacts = result.artifacts?.length ? result.artifacts : result.firstArtifact ? [result.firstArtifact] : [];
|
|
278
|
+
return artifacts.map((artifact) => artifact.relativePath).filter(Boolean);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export async function cleanupStudioHistoryArtifacts(input: {
|
|
282
|
+
readonly relativePaths: readonly string[];
|
|
283
|
+
readonly removeArtifact: (relativePath: string) => Promise<unknown>;
|
|
284
|
+
readonly isNotFound?: (error: unknown) => boolean;
|
|
285
|
+
}): Promise<{ readonly failures: readonly string[]; readonly remainingCleanupPaths: readonly string[] }> {
|
|
286
|
+
const failures: string[] = [];
|
|
287
|
+
const remainingCleanupPaths: string[] = [];
|
|
288
|
+
for (const relativePath of [...new Set(input.relativePaths)]) {
|
|
289
|
+
try {
|
|
290
|
+
await input.removeArtifact(relativePath);
|
|
291
|
+
} catch (error) {
|
|
292
|
+
if (input.isNotFound?.(error)) continue;
|
|
293
|
+
failures.push(`${relativePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
294
|
+
remainingCleanupPaths.push(relativePath);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return { failures, remainingCleanupPaths };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
type StudioHistoryMutationPolicyPort<TProjection> = {
|
|
301
|
+
readonly deleteAssets: boolean;
|
|
302
|
+
readonly additionalSubjects?: readonly StudioHistoryMutationSubject[];
|
|
303
|
+
readonly removeArtifact: (relativePath: string) => Promise<unknown>;
|
|
304
|
+
readonly isNotFound?: (error: unknown) => boolean;
|
|
305
|
+
readonly resolveArtifactPaths?: (record: StudioRunHistoryRecord) => readonly string[];
|
|
306
|
+
readonly commit: (
|
|
307
|
+
next: StudioRunHistory,
|
|
308
|
+
removed: readonly StudioHistoryMutationSubject[],
|
|
309
|
+
) => Promise<void>;
|
|
310
|
+
readonly project: (history: StudioRunHistory) => Promise<TProjection>;
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
function mutationIssue(
|
|
314
|
+
subject: StudioHistoryMutationSubject,
|
|
315
|
+
step: 'asset' | 'history',
|
|
316
|
+
message: string,
|
|
317
|
+
): StudioHistoryPolicyMutationIssue {
|
|
318
|
+
return { runId: subject.id, step, message: message || 'History mutation failed.' };
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function mutationSubjects<TProjection>(
|
|
322
|
+
input: StudioHistoryMutationPolicyPort<TProjection>,
|
|
323
|
+
history: StudioRunHistory,
|
|
324
|
+
): StudioHistoryMutationSubject[] {
|
|
325
|
+
const subjects = flattenStudioHistoryRecords(history).map((record) => ({
|
|
326
|
+
id: record.id,
|
|
327
|
+
capabilityId: record.capabilityId,
|
|
328
|
+
artifactPaths: input.resolveArtifactPaths?.(record) ?? studioHistoryArtifactPaths(record),
|
|
329
|
+
}));
|
|
330
|
+
const runOwnedIDs = new Set(subjects.map((subject) => subject.id));
|
|
331
|
+
for (const subject of input.additionalSubjects ?? []) {
|
|
332
|
+
if (!subject.id || !subject.capabilityId || !Array.isArray(subject.artifactPaths)) {
|
|
333
|
+
throw new Error('AI Studio history mutation subject is invalid.');
|
|
334
|
+
}
|
|
335
|
+
if (subject.artifactPaths.some((relativePath) => typeof relativePath !== 'string' || !relativePath)) {
|
|
336
|
+
throw new Error(`AI Studio history mutation subject has an invalid artifact path: ${subject.id}`);
|
|
337
|
+
}
|
|
338
|
+
if (!runOwnedIDs.has(subject.id)) {
|
|
339
|
+
subjects.push(subject);
|
|
340
|
+
runOwnedIDs.add(subject.id);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return subjects;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export async function removeStudioHistoryWithPolicy<TProjection>(input: {
|
|
347
|
+
readonly history: StudioRunHistory;
|
|
348
|
+
readonly recordId: string;
|
|
349
|
+
} & StudioHistoryMutationPolicyPort<TProjection>): Promise<StudioHistoryPolicyMutationOutcome<TProjection>> {
|
|
350
|
+
const removed = mutationSubjects(input, input.history).filter((subject) => subject.id === input.recordId);
|
|
351
|
+
const currentProjection = await input.project(input.history);
|
|
352
|
+
if (removed.length === 0) return { completed: 0, skipped: 1, failed: 0, projection: currentProjection, issues: [] };
|
|
353
|
+
if (input.deleteAssets) {
|
|
354
|
+
const cleanup = await cleanupStudioHistoryArtifacts({
|
|
355
|
+
relativePaths: removed.flatMap((subject) => subject.artifactPaths),
|
|
356
|
+
removeArtifact: input.removeArtifact,
|
|
357
|
+
isNotFound: input.isNotFound,
|
|
358
|
+
});
|
|
359
|
+
if (cleanup.failures.length > 0) {
|
|
360
|
+
const message = cleanup.failures.join('; ');
|
|
361
|
+
return {
|
|
362
|
+
completed: 0,
|
|
363
|
+
skipped: removed.length,
|
|
364
|
+
failed: 0,
|
|
365
|
+
projection: currentProjection,
|
|
366
|
+
issues: removed.map((subject) => mutationIssue(subject, 'asset', message)),
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
const next = removeStudioRunHistoryRecord(input.history, input.recordId);
|
|
371
|
+
try {
|
|
372
|
+
await input.commit(next, removed);
|
|
373
|
+
return { completed: removed.length, skipped: 0, failed: 0, projection: await input.project(next), issues: [] };
|
|
374
|
+
} catch (error) {
|
|
375
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
376
|
+
return {
|
|
377
|
+
completed: 0,
|
|
378
|
+
skipped: 0,
|
|
379
|
+
failed: removed.length,
|
|
380
|
+
projection: await input.project(input.history),
|
|
381
|
+
issues: removed.map((subject) => mutationIssue(subject, 'history', message)),
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export async function clearStudioHistoryWithPolicy<TProjection>(input: {
|
|
387
|
+
readonly history: StudioRunHistory;
|
|
388
|
+
readonly capabilityId: string | null;
|
|
389
|
+
} & StudioHistoryMutationPolicyPort<TProjection>): Promise<StudioHistoryPolicyMutationOutcome<TProjection>> {
|
|
390
|
+
const removed = mutationSubjects(input, input.history).filter((subject) => (
|
|
391
|
+
input.capabilityId === null || subject.capabilityId === input.capabilityId
|
|
392
|
+
));
|
|
393
|
+
if (!input.deleteAssets) {
|
|
394
|
+
const next = clearStudioRunHistory(input.history, input.capabilityId);
|
|
395
|
+
try {
|
|
396
|
+
await input.commit(next, removed);
|
|
397
|
+
return { completed: removed.length, skipped: 0, failed: 0, projection: await input.project(next), issues: [] };
|
|
398
|
+
} catch (error) {
|
|
399
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
400
|
+
return {
|
|
401
|
+
completed: 0,
|
|
402
|
+
skipped: 0,
|
|
403
|
+
failed: removed.length || 1,
|
|
404
|
+
projection: await input.project(input.history),
|
|
405
|
+
issues: removed.map((subject) => mutationIssue(subject, 'history', message)),
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
let history = input.history;
|
|
411
|
+
let completed = 0;
|
|
412
|
+
let skipped = 0;
|
|
413
|
+
let failed = 0;
|
|
414
|
+
const issues: StudioHistoryPolicyMutationIssue[] = [];
|
|
415
|
+
for (const subject of removed) {
|
|
416
|
+
const cleanup = await cleanupStudioHistoryArtifacts({
|
|
417
|
+
relativePaths: subject.artifactPaths,
|
|
418
|
+
removeArtifact: input.removeArtifact,
|
|
419
|
+
isNotFound: input.isNotFound,
|
|
420
|
+
});
|
|
421
|
+
if (cleanup.failures.length > 0) {
|
|
422
|
+
skipped += 1;
|
|
423
|
+
issues.push(mutationIssue(subject, 'asset', cleanup.failures.join('; ')));
|
|
424
|
+
continue;
|
|
425
|
+
}
|
|
426
|
+
const next = removeStudioRunHistoryRecord(history, subject.id);
|
|
427
|
+
try {
|
|
428
|
+
await input.commit(next, [subject]);
|
|
429
|
+
history = next;
|
|
430
|
+
completed += 1;
|
|
431
|
+
} catch (error) {
|
|
432
|
+
failed += 1;
|
|
433
|
+
issues.push(mutationIssue(subject, 'history', error instanceof Error ? error.message : String(error)));
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
return { completed, skipped, failed, projection: await input.project(history), issues };
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
export function parseAIStudioHistoryPanelPreferences(value: unknown): AIStudioHistoryPanelPreferences {
|
|
440
|
+
if (!isJsonObject(value)
|
|
441
|
+
|| typeof value.collapsed !== 'boolean'
|
|
442
|
+
|| typeof value.hideFailures !== 'boolean'
|
|
443
|
+
|| !['capability', 'all', 'media'].includes(String(value.scope))) {
|
|
444
|
+
throw new Error('AI Studio history panel preferences are invalid.');
|
|
445
|
+
}
|
|
446
|
+
return { collapsed: value.collapsed, scope: value.scope as AIStudioHistoryPanelPreferences['scope'], hideFailures: value.hideFailures };
|
|
447
|
+
}
|